-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
keymap.lua
73 lines (62 loc) · 1.66 KB
/
keymap.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
local keymap = {}
-- Creates a new keymap
--
-- Keymap is a collection of hotkeys and eventtaps that can be enabled
-- or disabled all at once.
keymap.new = function (...)
return setmetatable({...}, { __index = keymap })
end
function keymap:add(...)
for _, binding in ipairs({...}) do
table.insert(self, binding)
end
end
function keymap:enable()
for _, binding in ipairs(self) do
(binding.enable or binding.start)(binding)
end
end
function keymap:disable()
for _, binding in ipairs(self) do
(binding.disable or binding.stop)(binding)
end
end
local localKeymaps = {}
-- Registers a keymap that is only enabled in the application
-- specified by a bundle ID or windows that satisfy a function
keymap.register = function (matcher, keymap)
local fn
if type(matcher) == "function" then
fn = matcher
elseif type(matcher) == "string" then
fn = function (w)
return w ~= nil and w:application():bundleID() == matcher
end
end
local wf = hs.window.filter.new(fn)
:subscribe(hs.window.filter.windowFocused, function () keymap:enable() end)
:subscribe(hs.window.filter.windowUnfocused, function () keymap:disable() end)
if fn(hs.window.frontmostWindow()) then
keymap:enable()
end
local keymaps = localKeymaps[matcher]
if keymaps == nil then
keymaps = {}
localKeymaps[matcher] = keymaps
end
keymaps[keymap] = wf
return keymap
end
-- Unregisters a registered keymap
keymap.unregister = function (matcher, keymap)
local keymaps = localKeymaps[matcher]
if keymaps then
local wf = keymaps[keymap]
if wf then
wf:unsubscribeAll()
end
keymaps[keymap] = nil
end
return keymap
end
return keymap