lua: make later key bindings always have higher priority

Later calls to mp.add_key_binding() should take priority over previous
calls with the same key. Until now, the order was random (due to using
table pairs() iteration order).

Do this by simply sorting by a counter that is never reset. Since
input.c also gives later bindings priority, this works out.

Calling mp.remove_key_binding() on a newer binding makes an older still
existing binding with the same key active again. New bindings override
older ones, but do not overwrite them. I think these are good semantics
for most use cases.

(Note that the Lua code cannot determine whether two bindings use the
same key. Keys are strings, and two different strings could refer to the
same key. The code does not have access to input.c's key name
normalization, so it cannot compare them.)
This commit is contained in:
wm4 2019-12-07 14:53:33 +01:00
parent 855a4779ae
commit b36e8569a1
1 changed files with 13 additions and 2 deletions

View File

@ -131,6 +131,7 @@ end
-- "Newer" and more convenient API
local key_bindings = {}
local key_binding_counter = 0
local function update_key_bindings()
for i = 1, 2 do
@ -143,12 +144,19 @@ local function update_key_bindings()
section = "input_forced_" .. mp.script_name
flags = "force"
end
local cfg = ""
local bindings = {}
for k, v in pairs(key_bindings) do
if v.bind and v.forced ~= def then
cfg = cfg .. v.bind .. "\n"
bindings[#bindings + 1] = v
end
end
table.sort(bindings, function(a, b)
return a.priority < b.priority
end)
local cfg = ""
for _, v in ipairs(bindings) do
cfg = cfg .. v.bind .. "\n"
end
mp.input_define_section(section, cfg, flags)
-- TODO: remove the section if the script is stopped
mp.input_enable_section(section, "allow-hide-cursor+allow-vo-dragging")
@ -217,6 +225,9 @@ local function add_binding(attrs, key, name, fn, rp)
attrs.bind = key .. " script-binding " .. mp.script_name .. "/" .. name
end
attrs.name = name
-- new bindings override old ones (but do not overwrite them)
key_binding_counter = key_binding_counter + 1
attrs.priority = key_binding_counter
key_bindings[name] = attrs
update_key_bindings()
dispatch_key_bindings[name] = key_cb