forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB9d8f4f8Ivan Molodetskikh1 month ago2997 commits

virtual_keyboard.rs253 lines, 11.4 KiBHistoryRawDownload
1//! `zwp_virtual_keyboard_v1` handling.
2//!
3//! Virtual keyboards are handled like a real keyboard (binds, grabs, etc), but differ in a few
4//! ways:
5//!
6//! - A virtual keyboard's keymap may differ from the seat's one, and if so, will be swapped before
7//! events from it are forwarded (restoring the saved layout and a subset of modifiers when
8//! swapping back to the original one).
9//! - If the virtual keyboard uses `no_keymap` or the same one as the seat, it will use the seat's
10//! xkb state directly.
11//! - If a client grabs the keyboard, then forwards events through a virtual keyboard (e.g., fcitx),
12//! they are then forwarded bypassing the grab to avoid loops (sway special-cases this too).
13//! - Modifiers set through the `modifiers` request apply to the shared xkb state (see
14//! `DeviceRemoved`).
15
16use std::sync::Arc;
17
18use smithay::backend::input::{Event, InputEvent, KeyboardKeyEvent};
19use smithay::utils::SERIAL_COUNTER;
20use smithay::wayland::input_method::InputMethodSeat;
21use smithay::wayland::virtual_keyboard::{
22 VirtualKeyboardBackend, VirtualKeyboardDevice, VirtualKeyboardHandler, VirtualKeyboardKeyEvent,
23 VirtualKeyboardSpecialEvent,
24};
25
26use crate::niri::{SavedKeyboardState, State};
27
28/// Virtual keyboard keymap (which temporarily replaces the shared seat one).
29#[derive(Debug)]
30pub struct VirtualKeyboardKeymap {
31 pub device: VirtualKeyboardDevice,
32 pub keymap: Arc<str>,
33 pub saved: SavedKeyboardState,
34}
35
36impl VirtualKeyboardHandler for State {
37 fn process_virtual_keyboard_event(&mut self, event: InputEvent<VirtualKeyboardBackend>) {
38 match event {
39 InputEvent::Keyboard { event } => {
40 let device = event.device();
41 self.activate_virtual_keyboard_keymap(&device);
42 if self.is_input_method_virtual_keyboard(&device) {
43 // Do not forward passed-through events from a grab back to
44 // the grab.
45 self.forward_input_method_key(&event);
46 } else {
47 self.process_input_event(InputEvent::<VirtualKeyboardBackend>::Keyboard {
48 event,
49 });
50 }
51 }
52 InputEvent::Special(VirtualKeyboardSpecialEvent::Modifiers {
53 device,
54 mods_depressed,
55 mods_latched,
56 mods_locked,
57 group,
58 }) => {
59 self.activate_virtual_keyboard_keymap(&device);
60
61 let keyboard = self.niri.seat.get_keyboard().unwrap();
62 keyboard.with_xkb_state(self, |mut context| {
63 context.set_modifier_mask(mods_depressed, mods_latched, mods_locked, group);
64 });
65 }
66 InputEvent::Special(VirtualKeyboardSpecialEvent::KeymapChanged { .. }) => {
67 // The new keymap will be activated by the next key or modifiers event.
68 }
69 InputEvent::DeviceRemoved { device } => {
70 // Restore the original keymap if this device is active. This is
71 // checked based on the device rather than on the keymap, since
72 // the client may have replaced its keymap after we activated it
73 // and not sent any key/modifier events afterwards before
74 // removing the device.
75 let active = self
76 .niri
77 .virtual_keyboard_keymap
78 .as_ref()
79 .is_some_and(|active| active.device == device);
80 if active {
81 self.restore_configured_keymap();
82 }
83
84 // The held keys have already been released by smithay.
85 //
86 // We don't reset the modifiers since there's no way to tell which ones were set by
87 // this keyboard specifically since the masks are absolute. This only affects
88 // virtual keyboards without a keymap, or with the same keymap as the seat. We could
89 // track which bits were set by each virtual keyboard, but it's more complex, and we
90 // still would need to rebuild the modifier state after to avoid potentially leaving
91 // modifiers without a corresponding key stuck, and it's not really possible to
92 // rebuild it cleanly for all possible layouts (e.g., `grp:alt_shift_toggle`,
93 // layouts with multi-level modifier keys) without tracking the exact sequence the
94 // modifiers were pressed in (see
95 // https://github.com/niri-wm/niri/pull/4548#discussion_r4237056727).
96 //
97 // Not resetting the modifiers means that:
98 //
99 // - a locked modifier or layout group set by `modifiers` stays until the user
100 // toggles it (most layouts have clearLocks on Shift/Ctrl/Alt/Super, so those can
101 // be reset by pressing the key, but ones without a corresponding key can't be
102 // cleared without a keymap change or another modifiers request from a virtual
103 // keyboard)
104 // - if the virtual keyboard sets the modifiers without taking into account the
105 // existing state and clears a locked modifier, the locked modifier will remain
106 // cleared
107 // - a modifier set only through `modifiers` will stay set until the corresponding
108 // key is pressed
109 //
110 // To handle this properly, we need support for per-device xkb state (and we can
111 // merge the modifier state across the xkb states to keep shortcuts working across
112 // keyboards) in smithay like sway and hyprland.
113 self.process_input_event(InputEvent::<VirtualKeyboardBackend>::DeviceRemoved {
114 device,
115 });
116 }
117 event => self.process_input_event(event),
118 }
119 }
120}
121
122impl State {
123 /// Whether the virtual keyboard belongs to the input method that has grabbed the keyboard.
124 pub fn is_input_method_virtual_keyboard(&self, device: &VirtualKeyboardDevice) -> bool {
125 let grab_client = self.niri.seat.input_method().keyboard_grab_client();
126 grab_client.is_some() && grab_client == device.client()
127 }
128
129 /// Forwards a key that the input method is passing through directly to the focused surface.
130 ///
131 /// While an input method holds the keyboard grab, keys go through the binds and then to the
132 /// input method, which sends back unhandled ones through its own virtual keyboard. If we
133 /// handled these normally, they would get sent back to the grab, looping forever.
134 ///
135 /// Note that sway also special-cases this in the same way.
136 pub fn forward_input_method_key(&mut self, event: &VirtualKeyboardKeyEvent) {
137 let serial = SERIAL_COUNTER.next_serial();
138
139 // The modifiers associated with the physical key went to the input method
140 // rather than to the surface, so always send the current ones.
141 let keyboard = self.niri.seat.get_keyboard().unwrap();
142 keyboard.input_forward_bypassing_grab(
143 self,
144 event.key_code(),
145 event.state(),
146 serial,
147 event.time(),
148 true,
149 );
150 }
151
152 /// Activates the virtual keyboard's keymap on the current seat, unless it already is.
153 pub fn activate_virtual_keyboard_keymap(&mut self, device: &VirtualKeyboardDevice) {
154 let Some(keymap) = device.keymap() else {
155 // The keycodes are relative to the configured keymap, so make sure
156 // it's the active one.
157 self.restore_configured_keymap();
158 return;
159 };
160
161 if let Some(active) = &mut self.niri.virtual_keyboard_keymap {
162 if active.keymap == keymap {
163 // Another virtual keyboard may have installed an identical
164 // keymap. Take ownership of it anyway, so that removing that
165 // one doesn't take the keymap out from under us.
166 active.device = device.clone();
167 return;
168 }
169 }
170
171 // A keymap identical to the configured one (e.g. from an input method
172 // forwarding keys with the keymap it received from us) doesn't need to
173 // be swapped in, which would needlessly reset the keyboard state.
174 if *self.configured_keymap() == *keymap {
175 self.restore_configured_keymap();
176 return;
177 }
178
179 // Save the state from before the first virtual keyboard keymap, since
180 // swapping keymaps resets it, and a virtual keyboard should neither
181 // affect nor be affected by it.
182 let saved = match &self.niri.virtual_keyboard_keymap {
183 Some(active) => active.saved,
184 None => self.current_keyboard_state(),
185 };
186
187 let keyboard = self.niri.seat.get_keyboard().unwrap();
188 if let Err(err) = keyboard.set_keymap_from_string(self, keymap.to_string()) {
189 warn!("error setting virtual keyboard keymap: {err:?}");
190 return;
191 }
192
193 self.niri.virtual_keyboard_keymap = Some(VirtualKeyboardKeymap {
194 device: device.clone(),
195 keymap,
196 saved,
197 });
198 self.ipc_keyboard_layouts_changed();
199 }
200
201 /// Switches the seat back from a virtual keyboard's keymap to the configured one, if needed.
202 ///
203 /// The configured keymap was saved as text before the virtual keyboard's replaced it, so this
204 /// doesn't re-read the xkb file or recompile the xkb config unnecessarily.
205 pub fn restore_configured_keymap(&mut self) {
206 let Some(active) = self.niri.virtual_keyboard_keymap.take() else {
207 return;
208 };
209
210 let keyboard = self.niri.seat.get_keyboard().unwrap();
211 let restored = self.niri.configured_keymap.clone().is_some_and(|keymap| {
212 keyboard
213 .set_keymap_from_string(self, keymap.to_string())
214 .inspect_err(|err| warn!("error restoring configured keymap: {err:?}"))
215 .is_ok()
216 });
217
218 if !restored {
219 // Shouldn't happen unless there's an xkbcommon bug or configured_keymap somehow ends
220 // up none while a virtual keymap is active, but fall back to loading it from the
221 // config.
222 error!("failed to restore the configured keymap, reloading it from the config");
223 self.niri.virtual_keyboard_keymap = Some(active);
224 self.niri.configured_keymap = None;
225 self.load_configured_keymap();
226 return;
227 }
228
229 self.restore_keyboard_state(active.saved);
230 self.ipc_keyboard_layouts_changed();
231 }
232
233 /// Returns the configured keymap as XKB_KEYMAP_FORMAT_TEXT_V1.
234 fn configured_keymap(&mut self) -> Arc<str> {
235 if let Some(keymap) = &self.niri.configured_keymap {
236 return keymap.clone();
237 }
238
239 // The seat has the configured keymap while no virtual keyboard keymap is active.
240 if self.niri.virtual_keyboard_keymap.is_some() {
241 error!("virtual_keyboard_keymap must be None when resetting configured_keymap");
242 }
243
244 let keyboard = self.niri.seat.get_keyboard().unwrap();
245 let keymap: Arc<str> = keyboard
246 .with_xkb_state(self, |context| {
247 context.xkb().lock().unwrap().keymap_as_string()
248 })
249 .into();
250 self.niri.configured_keymap = Some(keymap.clone());
251 keymap
252 }
253}