Skip to content

Commit c8a62fe

Browse files
committed
snowcap: lua: Add a method to get unprocessed key event
The on_key_pressed handler can be limiting since: - it doesn't allow to react to key being released - it doesn't transmit the processed `text` associated with keys when using a layout with dead keys. - it doesn't transmit captured events (I've added this one to conserve the previous behavior.) This commit address this by adding a on_key_event that transmit the key state, whether it was captured on the server side, and the associated text if available.
1 parent 038dd5c commit c8a62fe

File tree

2 files changed

+43
-1
lines changed

2 files changed

+43
-1
lines changed

snowcap/api/lua/snowcap/input.lua

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,4 +12,12 @@ local input = {
1212
---@field alt boolean
1313
---@field super boolean
1414

15+
---A Key event.
16+
---@class snowcap.input.KeyEvent
17+
---@field key snowcap.Key Key Symbol.
18+
---@field mods snowcap.input.Modifiers Currently active modifiers.
19+
---@field pressed boolean True if the key is currently pressed, false on release.
20+
---@field captured boolean True if the event was flagged as Captured by a widget.
21+
---@field text? string Text produced by the event, if any.
22+
1523
return input

snowcap/api/lua/snowcap/layer.lua

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -169,14 +169,48 @@ function layer.new_widget(args)
169169
end)
170170
end
171171

172+
---Do something when a key event is received.
173+
---@param on_event fun(handle: snowcap.layer.LayerHandle, event: snowcap.input.KeyEvent)
174+
function LayerHandle:on_key_event(on_event)
175+
local err = client:snowcap_input_v1_InputService_KeyboardKey(
176+
{ id = self.id },
177+
function(response)
178+
---@cast response snowcap.input.v1.KeyboardKeyResponse
179+
180+
local mods = response.modifiers or {}
181+
mods.shift = mods.shift or false
182+
mods.ctrl = mods.ctrl or false
183+
mods.alt = mods.alt or false
184+
mods.super = mods.super or false
185+
186+
---@cast mods snowcap.input.Modifiers
187+
188+
---@type snowcap.input.KeyEvent
189+
local event = {
190+
key = response.key or 0,
191+
mods = mods,
192+
pressed = response.pressed,
193+
captured = response.captured,
194+
text = response.text,
195+
}
196+
197+
on_event(self, event)
198+
end
199+
)
200+
201+
if err then
202+
log.error(err)
203+
end
204+
end
205+
172206
---@param on_press fun(mods: snowcap.input.Modifiers, key: snowcap.Key)
173207
function LayerHandle:on_key_press(on_press)
174208
local err = client:snowcap_input_v1_InputService_KeyboardKey(
175209
{ id = self.id },
176210
function(response)
177211
---@cast response snowcap.input.v1.KeyboardKeyResponse
178212

179-
if not response.pressed then
213+
if not response.pressed or response.captured then
180214
return
181215
end
182216

0 commit comments

Comments
 (0)