forge
Explore
Log in

Don't you dare go Hollow

Implement org.fd.a11y KeyboardMonitor

Browse files at this commit

672bf3e1ff5c5a31c2685ed558bd399789469a9cIvan MolodetskikhParent: fefc0bc
Makes Orca work with niri:
- keyboard watching and announcing everywhere (not just GTK 3 windows)
- grabs for the Orca modifier (with double-press to pass through) and keystrokes
src/dbus/freedesktop_a11y.rsadded+461 -0
@@ -0,0 +1,461 @@
1+// References:
2+// - https://invent.kde.org/plasma/kwin/-/blob/397fbbe52a8f2d855ad0c9817b51a9bdf06a68e2/src/a11ykeyboardmonitor.cpp#L41
3+// - https://gitlab.gnome.org/GNOME/mutter/-/blob/cbb7295ac1f93a2dfd55a7c0544688e7e5c4d2e2/src/backends/meta-a11y-manager.c
4+
5+use std::collections::{HashMap, HashSet};
6+use std::sync::{Arc, Mutex, OnceLock};
7+use std::time::Duration;
8+
9+use anyhow::Context;
10+use futures_util::StreamExt;
11+use smithay::backend::input::{KeyState, Keycode};
12+use smithay::input::keyboard::{xkb, Keysym};
13+use zbus::blocking::object_server::InterfaceRef;
14+use zbus::fdo::{self, RequestNameFlags};
15+use zbus::interface;
16+use zbus::message::Header;
17+use zbus::names::{BusName, OwnedUniqueName, UniqueName};
18+use zbus::object_server::SignalEmitter;
19+use zbus::zvariant::NoneValue;
20+
21+use super::Start;
22+use crate::niri::State;
23+
24+#[derive(Debug, Default)]
25+struct Data {
26+ clients: HashMap<OwnedUniqueName, Client>,
27+
28+ grabbed_mods: HashSet<Keysym>,
29+ grabbed_mod_last_press_time: HashMap<Keysym, Duration>,
30+ suppressed_keys: HashSet<Keysym>,
31+}
32+
33+#[derive(Debug, Default)]
34+struct Client {
35+ watched: bool,
36+ grabbed: bool,
37+ modifiers: HashSet<Keysym>,
38+ keystrokes: Vec<(Keysym, u32)>,
39+}
40+
41+#[derive(Clone)]
42+pub struct KeyboardMonitor {
43+ data: Arc<Mutex<Data>>,
44+ iface: Arc<OnceLock<InterfaceRef<Self>>>,
45+}
46+
47+/// Interface for monitoring of keyboard input by assistive technologies.
48+///
49+/// This interface is used by assistive technologies to monitor keyboard input of the compositor.
50+/// The compositor is expected to listen on the well-known bus name "org.freedesktop.a11y.Manager"
51+/// at the object path "/org/freedesktop/a11y/Manager".
52+#[interface(name = "org.freedesktop.a11y.KeyboardMonitor")]
53+impl KeyboardMonitor {
54+ // Starts grabbing all key events. The client receives the events through the KeyEvent signal,
55+ // and in addition, the events aren't handled normally by the compositor. This includes changes
56+ // to the state of toggles like Caps Lock, Num Lock, and Scroll Lock.
57+ //
58+ // This behavior stays in effect until the same client calls UngrabKeyboard or closes its D-Bus
59+ // connection.
60+ async fn grab_keyboard(&self, #[zbus(header)] hdr: Header<'_>) -> fdo::Result<()> {
61+ let Some(sender) = hdr.sender() else {
62+ return Err(fdo::Error::Failed("no sender".to_owned()));
63+ };
64+ let sender = OwnedUniqueName::from(sender.to_owned());
65+ trace!("enabling keyboard grab for {sender}");
66+
67+ let mut data = self.data.lock().unwrap();
68+ let client = data.clients.entry(sender).or_default();
69+ client.grabbed = true;
70+
71+ Ok(())
72+ }
73+
74+ // Reverses the effect of calling GrabKeyboard. If GrabKeyboard wasn't previously called, this
75+ // method does nothing.
76+ //
77+ // After calling this method, the key grabs specified in the last call to SetKeyGrabs, if any,
78+ // are still in effect. Also, the client will still receive key events through the KeyEvent
79+ // signal, if it has called WatchKeyboard.
80+ async fn ungrab_keyboard(&self, #[zbus(header)] hdr: Header<'_>) -> fdo::Result<()> {
81+ let Some(sender) = hdr.sender() else {
82+ return Err(fdo::Error::Failed("no sender".to_owned()));
83+ };
84+ let sender = OwnedUniqueName::from(sender.to_owned());
85+
86+ let mut data = self.data.lock().unwrap();
87+ if let Some(client) = data.clients.get_mut(&sender) {
88+ trace!("disabling keyboard grab for {sender}");
89+ client.grabbed = false;
90+ }
91+
92+ Ok(())
93+ }
94+
95+ // Starts watching all key events. The client receives the events through the KeyEvent signal,
96+ // but the events are still handled normally by the compositor. This includes changes to the
97+ // state of toggles like Caps Lock, Num Lock, and Scroll Lock.
98+ //
99+ // This behavior stays in effect until the same client calls UnwatchKeyboard or closes its D-Bus
100+ // connection.
101+ async fn watch_keyboard(&self, #[zbus(header)] hdr: Header<'_>) -> fdo::Result<()> {
102+ let Some(sender) = hdr.sender() else {
103+ return Err(fdo::Error::Failed("no sender".to_owned()));
104+ };
105+ let sender = OwnedUniqueName::from(sender.to_owned());
106+ trace!("enabling keyboard watch for {sender}");
107+
108+ let mut data = self.data.lock().unwrap();
109+ let client = data.clients.entry(sender).or_default();
110+ client.watched = true;
111+
112+ Ok(())
113+ }
114+
115+ // Reverses the effect of calling WatchKeyboard. If WatchKeyboard wasn't previously called, this
116+ // method does nothing.
117+ //
118+ // After calling this method, the key grabs specified in the last call to SetKeyGrabs, if any,
119+ // are still in effect, but other key events are no longer reported to this client.
120+ async fn unwatch_keyboard(&self, #[zbus(header)] hdr: Header<'_>) -> fdo::Result<()> {
121+ let Some(sender) = hdr.sender() else {
122+ return Err(fdo::Error::Failed("no sender".to_owned()));
123+ };
124+ let sender = OwnedUniqueName::from(sender.to_owned());
125+
126+ let mut data = self.data.lock().unwrap();
127+ if let Some(client) = data.clients.get_mut(&sender) {
128+ trace!("disabling keyboard watch for {sender}");
129+ client.watched = false;
130+ }
131+
132+ Ok(())
133+ }
134+
135+ // Sets the current key grabs for the calling client, overriding any previous call to this
136+ // method. For grabbed key events, the KeyEvent signal is emitted, and normal key event handling
137+ // is suppressed, including state changes for toggles like Caps Lock and Num Lock.
138+ //
139+ // The grabs set by this method stay in effect until the same client calls this method again, or
140+ // until that client closes its D-Bus connection.
141+ //
142+ // Each item in `modifiers` is an XKB keysym. All keys in this list will be grabbed, and keys
143+ // pressed while any of these keys are down will also be grabbed.
144+ //
145+ // Each item in `keystrokes` is a struct with the following fields:
146+ //
147+ // - the XKB keysym of the non-modifier key
148+ // - the XKB modifier mask of the modifiers, if any, for this keystroke
149+ //
150+ // If any of the keys in `modifiers` is pressed alone, the compositor is required to ignore the
151+ // key press and release event if a second key press of the same modifier is not received within
152+ // a reasonable time frame, for example, the key repeat delay. If such event is received, this
153+ // second event is processed normally.
154+ async fn set_key_grabs(
155+ &self,
156+ #[zbus(header)] hdr: Header<'_>,
157+ modifiers: Vec<u32>,
158+ keystrokes: Vec<(u32, u32)>,
159+ ) -> fdo::Result<()> {
160+ let Some(sender) = hdr.sender() else {
161+ return Err(fdo::Error::Failed("no sender".to_owned()));
162+ };
163+ let sender = OwnedUniqueName::from(sender.to_owned());
164+ trace!("updating key grabs for {sender}");
165+
166+ let mut data = self.data.lock().unwrap();
167+ let client = data.clients.entry(sender).or_default();
168+ client.modifiers = HashSet::from_iter(modifiers.into_iter().map(Keysym::new));
169+ client.keystrokes =
170+ Vec::from_iter(keystrokes.into_iter().map(|(k, v)| (Keysym::new(k), v)));
171+
172+ data.rebuild_grabbed_mods();
173+
174+ Ok(())
175+ }
176+
177+ // The compositor emits this signal for each key press or release.
178+ //
179+ // - `released`: whether this is a key-up event
180+ // - `state`: XKB modifier mask for currently pressed modifiers
181+ // - `keysym`: XKB keysym for this key
182+ // - `unichar`: Unicode character for this key, or 0 if none
183+ // - `keycode`: hardware-dependent keycode for this key
184+ #[zbus(signal)]
185+ pub async fn key_event(
186+ ctxt: &SignalEmitter<'_>,
187+ released: bool,
188+ state: u32,
189+ keysym: u32,
190+ unichar: u32,
191+ keycode: u16,
192+ ) -> zbus::Result<()>;
193+}
194+
195+impl KeyboardMonitor {
196+ #[allow(clippy::new_without_default)]
197+ pub fn new() -> Self {
198+ Self {
199+ data: Arc::new(Mutex::new(Data::default())),
200+ iface: Arc::new(OnceLock::new()),
201+ }
202+ }
203+
204+ #[allow(clippy::too_many_arguments)]
205+ pub fn process_key(
206+ &self,
207+ repeat_delay: Duration,
208+ time: Duration,
209+ keycode: Keycode,
210+ released: bool,
211+ mods: u32,
212+ keysym: Keysym,
213+ unichar: u32,
214+ ) -> bool {
215+ let _span = tracy_client::span!("KeyboardMonitor::process_key");
216+
217+ let mut ctxt = self.iface.get().unwrap().signal_emitter().clone();
218+
219+ let mut data = self.data.lock().unwrap();
220+
221+ // Emit key events as necessary.
222+ for (name, client) in &data.clients {
223+ if client.should_watch_keypress(&data.suppressed_keys, mods, keysym) {
224+ let _span = tracy_client::span!("emitting key event");
225+
226+ // Emit to that client only.
227+ ctxt = ctxt.set_destination(BusName::Unique(name.as_ref()));
228+ let ctxt = &ctxt;
229+ async_io::block_on(async move {
230+ if let Err(err) = KeyboardMonitor::key_event(
231+ ctxt,
232+ released,
233+ mods,
234+ keysym.raw(),
235+ unichar,
236+ keycode.raw() as u16,
237+ )
238+ .await
239+ {
240+ warn!("error emitting key_event: {err:?}");
241+ }
242+ });
243+ }
244+ }
245+
246+ // Check for double-pressed grabbed modifier that should not be captured.
247+ if data.grabbed_mods.contains(&keysym) {
248+ if released {
249+ // If missing from suppressed keys, then this is a release corresponding to the
250+ // second press that got handled normally.
251+ if !data.suppressed_keys.contains(&keysym) {
252+ trace!("handling release for second press of grabbed modifier: {keysym:?}");
253+ return false;
254+ }
255+ } else {
256+ let last_press_entry = data
257+ .grabbed_mod_last_press_time
258+ .entry(keysym)
259+ .or_insert(Duration::ZERO);
260+ let last_press = *last_press_entry;
261+ *last_press_entry = time;
262+
263+ // Modifier pressed twice; handle it as normal.
264+ if time <= last_press.saturating_add(repeat_delay) {
265+ trace!("handling second press of grabbed modifier: {keysym:?}");
266+ return false;
267+ }
268+ }
269+ }
270+
271+ let mut block = false;
272+
273+ if released {
274+ // This is a release for a key that was grabbed.
275+ if data.suppressed_keys.remove(&keysym) {
276+ trace!("blocking release for previously suppressed key: {keysym:?}");
277+ block = true;
278+ }
279+ } else if data.suppressed_keys.contains(&keysym) {
280+ // Second press for an already-pressed key, e.g. from two keyboards.
281+ trace!("blocking press for already-pressed key: {keysym:?}");
282+ block = true;
283+ } else {
284+ // Check if it's grabbed by any client.
285+ if data
286+ .clients
287+ .values()
288+ .any(|client| client.should_grab_keypress(&data.suppressed_keys, mods, keysym))
289+ {
290+ trace!("blocking press for grabbed key: {keysym:?}");
291+ data.suppressed_keys.insert(keysym);
292+ block = true;
293+ }
294+ }
295+
296+ block
297+ }
298+}
299+
300+impl Data {
301+ fn rebuild_grabbed_mods(&mut self) {
302+ self.grabbed_mods.clear();
303+ for client in self.clients.values() {
304+ self.grabbed_mods.extend(&client.modifiers);
305+ }
306+ }
307+}
308+
309+impl Client {
310+ fn should_grab_keypress(
311+ &self,
312+ suppressed_keys: &HashSet<Keysym>,
313+ mods: u32,
314+ keysym: Keysym,
315+ ) -> bool {
316+ // Grabbing all keys.
317+ if self.grabbed {
318+ return true;
319+ }
320+
321+ for modifier in &self.modifiers {
322+ // This is a grabbed modifier, or a grabbed modifier is currently down.
323+ if *modifier == keysym || suppressed_keys.contains(modifier) {
324+ return true;
325+ }
326+ }
327+
328+ for (grabbed_keysym, grabbed_mods) in &self.keystrokes {
329+ // This is a grabbed keystroke.
330+ if *grabbed_keysym == keysym && *grabbed_mods == mods {
331+ return true;
332+ }
333+ }
334+
335+ false
336+ }
337+
338+ fn should_watch_keypress(
339+ &self,
340+ suppressed_keys: &HashSet<Keysym>,
341+ mods: u32,
342+ keysym: Keysym,
343+ ) -> bool {
344+ if self.watched {
345+ return true;
346+ }
347+
348+ self.should_grab_keypress(suppressed_keys, mods, keysym)
349+ }
350+}
351+
352+async fn monitor_disappeared_clients(
353+ conn: &zbus::Connection,
354+ data: Arc<Mutex<Data>>,
355+) -> anyhow::Result<()> {
356+ let proxy = fdo::DBusProxy::new(conn)
357+ .await
358+ .context("error creating a DBusProxy")?;
359+
360+ let mut stream = proxy
361+ .receive_name_owner_changed_with_args(&[(2, UniqueName::null_value())])
362+ .await
363+ .context("error creating a NameOwnerChanged stream")?;
364+
365+ while let Some(signal) = stream.next().await {
366+ let args = signal
367+ .args()
368+ .context("error retrieving NameOwnerChanged args")?;
369+
370+ let Some(name) = &**args.old_owner() else {
371+ continue;
372+ };
373+
374+ if args.new_owner().is_none() {
375+ trace!("keyboard monitor client disconnected: {name}");
376+
377+ let name = OwnedUniqueName::from(name.to_owned());
378+ let mut data = data.lock().unwrap();
379+ data.clients.remove(&name);
380+ data.rebuild_grabbed_mods();
381+ } else {
382+ error!("non-null new_owner should've been filtered out");
383+ }
384+ }
385+
386+ Ok(())
387+}
388+
389+impl Start for KeyboardMonitor {
390+ fn start(self) -> anyhow::Result<zbus::blocking::Connection> {
391+ let data = self.data.clone();
392+
393+ let conn = zbus::blocking::Connection::session()?;
394+ let flags = RequestNameFlags::AllowReplacement
395+ | RequestNameFlags::ReplaceExisting
396+ | RequestNameFlags::DoNotQueue;
397+
398+ conn.object_server()
399+ .at("/org/freedesktop/a11y/Manager", self.clone())?;
400+ conn.request_name_with_flags("org.freedesktop.a11y.Manager", flags)?;
401+
402+ let iface = conn
403+ .object_server()
404+ .interface("/org/freedesktop/a11y/Manager")?;
405+ let _ = self.iface.set(iface);
406+
407+ let async_conn = conn.inner().clone();
408+ let future = async move {
409+ if let Err(err) = monitor_disappeared_clients(&async_conn, data.clone()).await {
410+ warn!("error monitoring keyboard monitor clients: {err:?}");
411+
412+ // Since the monitor is now broken, prevent any further communication.
413+ if let Err(err) = async_conn.close().await {
414+ warn!("error closing connection: {err:?}");
415+ }
416+
417+ let mut data = data.lock().unwrap();
418+ data.clients.clear();
419+ data.rebuild_grabbed_mods();
420+ }
421+ };
422+ let task = conn
423+ .inner()
424+ .executor()
425+ .spawn(future, "monitor disappearing keyboard clients");
426+ task.detach();
427+
428+ Ok(conn)
429+ }
430+}
431+
432+impl State {
433+ pub fn a11y_process_key(&mut self, time: Duration, keycode: Keycode, state: KeyState) -> bool {
434+ if self.niri.a11y_keyboard_monitor.is_none() {
435+ return false;
436+ }
437+
438+ let keyboard = self.niri.seat.get_keyboard().unwrap();
439+
440+ let (mods, keysym, unichar) = keyboard.with_xkb_state(self, |context| {
441+ let xkb = context.xkb().lock().unwrap();
442+ // SAFETY: we're not changing the ref count.
443+ let state = unsafe { xkb.state() };
444+
445+ let keysym = state.key_get_one_sym(keycode);
446+ let mods = state.serialize_mods(xkb::STATE_MODS_EFFECTIVE);
447+ let unichar = state.key_get_utf32(keycode);
448+
449+ (mods, keysym, unichar)
450+ });
451+
452+ let config = self.niri.config.borrow();
453+ let repeat_delay = Duration::from_millis(u64::from(config.input.keyboard.repeat_delay));
454+ let released = state == KeyState::Released;
455+
456+ let Some(monitor) = &self.niri.a11y_keyboard_monitor else {
457+ return false;
458+ };
459+ monitor.process_key(repeat_delay, time, keycode, released, mods, keysym, unichar)
460+ }
461+}
src/dbus/mod.rsmodified+9 -0
@@ -3,6 +3,7 @@ use zbus::object_server::Interface;
3 3
4 use crate::niri::State;4 use crate::niri::State;
5 5
6+pub mod freedesktop_a11y;
6 pub mod freedesktop_locale1;7 pub mod freedesktop_locale1;
7 pub mod freedesktop_screensaver;8 pub mod freedesktop_screensaver;
8 pub mod gnome_shell_introspect;9 pub mod gnome_shell_introspect;
@@ -15,6 +16,7 @@ pub mod mutter_screen_cast;
15 #[cfg(feature = "xdp-gnome-screencast")]16 #[cfg(feature = "xdp-gnome-screencast")]
16 use mutter_screen_cast::ScreenCast;17 use mutter_screen_cast::ScreenCast;
17 18
19+use self::freedesktop_a11y::KeyboardMonitor;
18 use self::freedesktop_screensaver::ScreenSaver;20 use self::freedesktop_screensaver::ScreenSaver;
19 use self::gnome_shell_introspect::Introspect;21 use self::gnome_shell_introspect::Introspect;
20 use self::mutter_display_config::DisplayConfig;22 use self::mutter_display_config::DisplayConfig;
@@ -34,6 +36,7 @@ pub struct DBusServers {
34 #[cfg(feature = "xdp-gnome-screencast")]36 #[cfg(feature = "xdp-gnome-screencast")]
35 pub conn_screen_cast: Option<Connection>,37 pub conn_screen_cast: Option<Connection>,
36 pub conn_locale1: Option<Connection>,38 pub conn_locale1: Option<Connection>,
39+ pub conn_keyboard_monitor: Option<Connection>,
37 }40 }
38 41
39 impl DBusServers {42 impl DBusServers {
@@ -125,6 +128,12 @@ impl DBusServers {
125 let screen_cast = ScreenCast::new(backend.ipc_outputs(), to_niri);128 let screen_cast = ScreenCast::new(backend.ipc_outputs(), to_niri);
126 dbus.conn_screen_cast = try_start(screen_cast);129 dbus.conn_screen_cast = try_start(screen_cast);
127 }130 }
131+
132+ let keyboard_monitor = KeyboardMonitor::new();
133+ if let Some(x) = try_start(keyboard_monitor.clone()) {
134+ dbus.conn_keyboard_monitor = Some(x);
135+ niri.a11y_keyboard_monitor = Some(keyboard_monitor);
136+ }
128 }137 }
129 138
130 let (to_niri, from_locale1) = calloop::channel::channel();139 let (to_niri, from_locale1) = calloop::channel::channel();
src/input/mod.rsmodified+11 -0
@@ -359,6 +359,17 @@ impl State {
359 359
360 let is_inhibiting_shortcuts = self.is_inhibiting_shortcuts();360 let is_inhibiting_shortcuts = self.is_inhibiting_shortcuts();
361 361
362+ // Accessibility modifier grabs should override XKB state changes (e.g. Caps Lock), so we
363+ // need to process them before keyboard.input() below.
364+ #[cfg(feature = "dbus")]
365+ if self.a11y_process_key(
366+ Duration::from_millis(u64::from(time)),
367+ event.key_code(),
368+ event.state(),
369+ ) {
370+ return;
371+ }
372+
362 let Some(Some(bind)) = self.niri.seat.get_keyboard().unwrap().input(373 let Some(Some(bind)) = self.niri.seat.get_keyboard().unwrap().input(
363 self,374 self,
364 event.key_code(),375 event.key_code(),
src/niri.rsmodified+4 -0
@@ -385,6 +385,8 @@ pub struct Niri {
385 #[cfg(feature = "dbus")]385 #[cfg(feature = "dbus")]
386 pub dbus: Option<crate::dbus::DBusServers>,386 pub dbus: Option<crate::dbus::DBusServers>,
387 #[cfg(feature = "dbus")]387 #[cfg(feature = "dbus")]
388+ pub a11y_keyboard_monitor: Option<crate::dbus::freedesktop_a11y::KeyboardMonitor>,
389+ #[cfg(feature = "dbus")]
388 pub inhibit_power_key_fd: Option<zbus::zvariant::OwnedFd>,390 pub inhibit_power_key_fd: Option<zbus::zvariant::OwnedFd>,
389 391
390 pub ipc_server: Option<IpcServer>,392 pub ipc_server: Option<IpcServer>,
@@ -2659,6 +2661,8 @@ impl Niri {
2659 #[cfg(feature = "dbus")]2661 #[cfg(feature = "dbus")]
2660 dbus: None,2662 dbus: None,
2661 #[cfg(feature = "dbus")]2663 #[cfg(feature = "dbus")]
2664+ a11y_keyboard_monitor: None,
2665+ #[cfg(feature = "dbus")]
2662 inhibit_power_key_fd: None,2666 inhibit_power_key_fd: None,
2663 2667
2664 ipc_server,2668 ipc_server,