speculatively recommend new LÖVE v11.5 in all forks
[view.love.git] / keychord.lua
blobf1b6a59c9d767032438337f69ae40871d70c2b9a
1 -- Keyboard driver
3 Modifiers = {'lctrl', 'rctrl', 'lalt', 'ralt', 'lshift', 'rshift', 'lgui', 'rgui'}
5 function App.keypressed(key, scancode, isrepeat)
6 if array.find(Modifiers, key) then
7 -- do nothing when the modifier is pressed
8 return
9 end
10 -- include the modifier(s) when the non-modifer is pressed
11 App.keychord_press(App.combine_modifiers(key), key)
12 end
14 function App.combine_modifiers(key)
15 if love.keyboard.isModifierActive then -- waiting for LÖVE v12
16 if key:match('^kp') then
17 key = App.translate_numlock(key)
18 end
19 end
20 local result = ''
21 if App.ctrl_down() then
22 result = result..'C-'
23 end
24 if App.alt_down() then
25 result = result..'M-'
26 end
27 if App.shift_down() then
28 result = result..'S-' -- don't try to use this with letters/digits
29 end
30 if App.cmd_down() then
31 result = result..'s-'
32 end
33 result = result..key
34 return result
35 end
37 function App.any_modifier_down()
38 return App.ctrl_down() or App.alt_down() or App.shift_down() or App.cmd_down()
39 end
41 function App.ctrl_down()
42 return App.key_down('lctrl') or App.key_down('rctrl')
43 end
45 function App.alt_down()
46 return App.key_down('lalt') or App.key_down('ralt')
47 end
49 function App.shift_down()
50 return App.key_down('lshift') or App.key_down('rshift')
51 end
53 function App.cmd_down()
54 return App.key_down('lgui') or App.key_down('rgui')
55 end
57 function App.is_cursor_movement(key)
58 return array.find({'left', 'right', 'up', 'down', 'home', 'end', 'pageup', 'pagedown'}, key)
59 end
61 -- mappings only to non-printable keys; leave out mappings that textinput will handle
62 Numlock_off = {
63 kp0='insert',
64 kp1='end',
65 kp2='down',
66 kp3='pagedown',
67 kp4='left',
68 -- numpad 5 translates to nothing
69 kp6='right',
70 kp7='home',
71 kp8='up',
72 kp9='pageup',
73 ['kp.']='delete',
74 -- LÖVE handles keypad operators in textinput
75 -- what's with the `kp=` and `kp,` keys? None of my keyboards have one.
76 -- Hopefully LÖVE handles them as well in textinput.
77 kpenter='enter',
78 kpdel='delete',
80 Numlock_on = {
81 kpenter='enter',
82 kpdel='delete',
84 function App.translate_numlock(key)
85 if love.keyboard.isModifierActive('numlock') then
86 return Numlock_on[key] or key
87 else
88 return Numlock_off[key] or key
89 end
90 return key
91 end
93 array = {}
95 function array.find(arr, elem)
96 if type(elem) == 'function' then
97 for i,x in ipairs(arr) do
98 if elem(x) then
99 return i
102 else
103 for i,x in ipairs(arr) do
104 if x == elem then
105 return i
109 return nil
112 function array.any(arr, f)
113 for i,x in ipairs(arr) do
114 local result = f(x)
115 if result then
116 return result
119 return false