niri
Clone
https://git.tahinli.com/Tahinli/niri.git
0 watching·0 forks·Rust·GPL-3.0·12.1 MiB·9d8f4f8·Ivan Molodetskikh·1 month ago·2997 commits
| 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::message::Header; |
| 15 | use zbus::names::{BusName, OwnedUniqueName, UniqueName}; |
| 16 | use zbus::object_server::SignalEmitter; |
| 17 | use zbus::zvariant::{NoneValue, OwnedObjectPath, SerializeDict, Type, Value}; |
| 18 | use zbus::{fdo, interface, DBusError}; |
| 19 | |
| 20 | use super::request_name; |
| 21 | use crate::niri::{PointContents, State}; |
| 22 | use crate::utils::get_credentials_for_surface; |
| 23 | |
| 24 | pub struct Manager { |
| 25 | pub keyboard_monitor: KeyboardMonitor, |
| 26 | pub pointer_locator: PointerLocator, |
| 27 | } |
| 28 | |
| 29 | pub enum A11yManagerToNiri { |
| 30 | QueryPointer, |
| 31 | } |
| 32 | |
| 33 | pub enum NiriToA11yManager { |
| 34 | PointerContents(Option<(PointerAppData, f64, f64)>), |
| 35 | } |
| 36 | |
| 37 | #[derive(Debug, Default)] |
| 38 | struct KeyboardData { |
| 39 | clients: HashMap<OwnedUniqueName, KeyboardClient>, |
| 40 | |
| 41 | grabbed_mods: HashSet<Keysym>, |
| 42 | grabbed_mod_last_press_time: HashMap<Keysym, Duration>, |
| 43 | suppressed_keys: HashSet<Keysym>, |
| 44 | } |
| 45 | |
| 46 | #[derive(Debug, Default)] |
| 47 | struct KeyboardClient { |
| 48 | watched: bool, |
| 49 | grabbed: bool, |
| 50 | modifiers: HashSet<Keysym>, |
| 51 | keystrokes: Vec<(Keysym, u32)>, |
| 52 | } |
| 53 | |
| 54 | #[derive(Clone, Default)] |
| 55 | pub struct KeyboardMonitor { |
| 56 | data: Arc<Mutex<KeyboardData>>, |
| 57 | iface: Arc<OnceLock<InterfaceRef<Self>>>, |
| 58 | } |
| 59 | |
| 60 | /// Keyboard monitor key block reason. |
| 61 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 62 | pub enum KbMonBlock { |
| 63 | /// Not blocked. |
| 64 | Pass, |
| 65 | /// Blocked, and this is the first press/release of the a11y modifier. |
| 66 | ModifierFirstPress, |
| 67 | /// Blocked, and this is not the a11y modifier. |
| 68 | Block, |
| 69 | } |
| 70 | |
| 71 | #[derive(Debug, Default)] |
| 72 | struct PointerData { |
| 73 | /// Clients to be notified of pointer position change. |
| 74 | clients: HashSet<OwnedUniqueName>, |
| 75 | } |
| 76 | |
| 77 | #[derive(Debug, Default, SerializeDict, Type, Value)] |
| 78 | #[zvariant(signature = "dict")] |
| 79 | pub struct PointerAppData { |
| 80 | // For the future: other impls send either pid or the two other properties, not both. |
| 81 | pid: Option<i32>, |
| 82 | app_dbus_name: Option<String>, |
| 83 | toplevel_object_path: Option<OwnedObjectPath>, |
| 84 | } |
| 85 | |
| 86 | #[derive(Clone)] |
| 87 | pub struct PointerLocator { |
| 88 | data: Arc<Mutex<PointerData>>, |
| 89 | iface: Arc<OnceLock<InterfaceRef<Self>>>, |
| 90 | to_niri: calloop::channel::Sender<A11yManagerToNiri>, |
| 91 | from_niri: async_channel::Receiver<NiriToA11yManager>, |
| 92 | } |
| 93 | |
| 94 | #[derive(DBusError, Debug)] |
| 95 | #[zbus(prefix = "org.freedesktop.a11y")] |
| 96 | enum A11yError { |
| 97 | #[zbus(error)] |
| 98 | ZBus(zbus::Error), |
| 99 | UnknownToplevel, |
| 100 | // Catch-all. |
| 101 | Failed(String), |
| 102 | } |
| 103 | |
| 104 | /// Interface for monitoring of keyboard input by assistive technologies. |
| 105 | /// |
| 106 | /// This interface is used by assistive technologies to monitor keyboard input of the compositor. |
| 107 | /// The compositor is expected to listen on the well-known bus name "org.freedesktop.a11y.Manager" |
| 108 | /// at the object path "/org/freedesktop/a11y/Manager". |
| 109 | #[interface(name = "org.freedesktop.a11y.KeyboardMonitor")] |
| 110 | impl KeyboardMonitor { |
| 111 | // Starts grabbing all key events. The client receives the events through the KeyEvent signal, |
| 112 | // and in addition, the events aren't handled normally by the compositor. This includes changes |
| 113 | // to the state of toggles like Caps Lock, Num Lock, and Scroll Lock. |
| 114 | // |
| 115 | // This behavior stays in effect until the same client calls UngrabKeyboard or closes its D-Bus |
| 116 | // connection. |
| 117 | async fn grab_keyboard(&self, #[zbus(header)] hdr: Header<'_>) -> fdo::Result<()> { |
| 118 | let Some(sender) = hdr.sender() else { |
| 119 | return Err(fdo::Error::Failed("no sender".to_owned())); |
| 120 | }; |
| 121 | let sender = OwnedUniqueName::from(sender.to_owned()); |
| 122 | trace!("enabling keyboard grab for {sender}"); |
| 123 | |
| 124 | let mut data = self.data.lock().unwrap(); |
| 125 | let client = data.clients.entry(sender).or_default(); |
| 126 | client.grabbed = true; |
| 127 | |
| 128 | Ok(()) |
| 129 | } |
| 130 | |
| 131 | // Reverses the effect of calling GrabKeyboard. If GrabKeyboard wasn't previously called, this |
| 132 | // method does nothing. |
| 133 | // |
| 134 | // After calling this method, the key grabs specified in the last call to SetKeyGrabs, if any, |
| 135 | // are still in effect. Also, the client will still receive key events through the KeyEvent |
| 136 | // signal, if it has called WatchKeyboard. |
| 137 | async fn ungrab_keyboard(&self, #[zbus(header)] hdr: Header<'_>) -> fdo::Result<()> { |
| 138 | let Some(sender) = hdr.sender() else { |
| 139 | return Err(fdo::Error::Failed("no sender".to_owned())); |
| 140 | }; |
| 141 | let sender = OwnedUniqueName::from(sender.to_owned()); |
| 142 | |
| 143 | let mut data = self.data.lock().unwrap(); |
| 144 | if let Some(client) = data.clients.get_mut(&sender) { |
| 145 | trace!("disabling keyboard grab for {sender}"); |
| 146 | client.grabbed = false; |
| 147 | } |
| 148 | |
| 149 | Ok(()) |
| 150 | } |
| 151 | |
| 152 | // Starts watching all key events. The client receives the events through the KeyEvent signal, |
| 153 | // but the events are still handled normally by the compositor. This includes changes to the |
| 154 | // state of toggles like Caps Lock, Num Lock, and Scroll Lock. |
| 155 | // |
| 156 | // This behavior stays in effect until the same client calls UnwatchKeyboard or closes its D-Bus |
| 157 | // connection. |
| 158 | async fn watch_keyboard(&self, #[zbus(header)] hdr: Header<'_>) -> fdo::Result<()> { |
| 159 | let Some(sender) = hdr.sender() else { |
| 160 | return Err(fdo::Error::Failed("no sender".to_owned())); |
| 161 | }; |
| 162 | let sender = OwnedUniqueName::from(sender.to_owned()); |
| 163 | trace!("enabling keyboard watch for {sender}"); |
| 164 | |
| 165 | let mut data = self.data.lock().unwrap(); |
| 166 | let client = data.clients.entry(sender).or_default(); |
| 167 | client.watched = true; |
| 168 | |
| 169 | Ok(()) |
| 170 | } |
| 171 | |
| 172 | // Reverses the effect of calling WatchKeyboard. If WatchKeyboard wasn't previously called, this |
| 173 | // method does nothing. |
| 174 | // |
| 175 | // After calling this method, the key grabs specified in the last call to SetKeyGrabs, if any, |
| 176 | // are still in effect, but other key events are no longer reported to this client. |
| 177 | async fn unwatch_keyboard(&self, #[zbus(header)] hdr: Header<'_>) -> fdo::Result<()> { |
| 178 | let Some(sender) = hdr.sender() else { |
| 179 | return Err(fdo::Error::Failed("no sender".to_owned())); |
| 180 | }; |
| 181 | let sender = OwnedUniqueName::from(sender.to_owned()); |
| 182 | |
| 183 | let mut data = self.data.lock().unwrap(); |
| 184 | if let Some(client) = data.clients.get_mut(&sender) { |
| 185 | trace!("disabling keyboard watch for {sender}"); |
| 186 | client.watched = false; |
| 187 | } |
| 188 | |
| 189 | Ok(()) |
| 190 | } |
| 191 | |
| 192 | // Sets the current key grabs for the calling client, overriding any previous call to this |
| 193 | // method. For grabbed key events, the KeyEvent signal is emitted, and normal key event handling |
| 194 | // is suppressed, including state changes for toggles like Caps Lock and Num Lock. |
| 195 | // |
| 196 | // The grabs set by this method stay in effect until the same client calls this method again, or |
| 197 | // until that client closes its D-Bus connection. |
| 198 | // |
| 199 | // Each item in `modifiers` is an XKB keysym. All keys in this list will be grabbed, and keys |
| 200 | // pressed while any of these keys are down will also be grabbed. |
| 201 | // |
| 202 | // Each item in `keystrokes` is a struct with the following fields: |
| 203 | // |
| 204 | // - the XKB keysym of the non-modifier key |
| 205 | // - the XKB modifier mask of the modifiers, if any, for this keystroke |
| 206 | // |
| 207 | // If any of the keys in `modifiers` is pressed alone, the compositor is required to ignore the |
| 208 | // key press and release event if a second key press of the same modifier is not received within |
| 209 | // a reasonable time frame, for example, the key repeat delay. If such event is received, this |
| 210 | // second event is processed normally. |
| 211 | async fn set_key_grabs( |
| 212 | &self, |
| 213 | #[zbus(header)] hdr: Header<'_>, |
| 214 | modifiers: Vec<u32>, |
| 215 | keystrokes: Vec<(u32, u32)>, |
| 216 | ) -> fdo::Result<()> { |
| 217 | let Some(sender) = hdr.sender() else { |
| 218 | return Err(fdo::Error::Failed("no sender".to_owned())); |
| 219 | }; |
| 220 | let sender = OwnedUniqueName::from(sender.to_owned()); |
| 221 | trace!("updating key grabs for {sender}"); |
| 222 | |
| 223 | let mut data = self.data.lock().unwrap(); |
| 224 | let client = data.clients.entry(sender).or_default(); |
| 225 | client.modifiers = HashSet::from_iter(modifiers.into_iter().map(Keysym::new)); |
| 226 | client.keystrokes = |
| 227 | Vec::from_iter(keystrokes.into_iter().map(|(k, v)| (Keysym::new(k), v))); |
| 228 | |
| 229 | data.rebuild_grabbed_mods(); |
| 230 | |
| 231 | Ok(()) |
| 232 | } |
| 233 | |
| 234 | // The compositor emits this signal for each key press or release. |
| 235 | // |
| 236 | // - `released`: whether this is a key-up event |
| 237 | // - `state`: XKB modifier mask for currently pressed modifiers |
| 238 | // - `keysym`: XKB keysym for this key |
| 239 | // - `unichar`: Unicode character for this key, or 0 if none |
| 240 | // - `keycode`: hardware-dependent keycode for this key |
| 241 | #[zbus(signal)] |
| 242 | pub async fn key_event( |
| 243 | ctxt: &SignalEmitter<'_>, |
| 244 | released: bool, |
| 245 | state: u32, |
| 246 | keysym: u32, |
| 247 | unichar: u32, |
| 248 | keycode: u16, |
| 249 | ) -> zbus::Result<()>; |
| 250 | } |
| 251 | |
| 252 | impl KeyboardMonitor { |
| 253 | #[allow(clippy::too_many_arguments)] |
| 254 | pub fn process_key( |
| 255 | &self, |
| 256 | repeat_delay: Duration, |
| 257 | time: Duration, |
| 258 | keycode: Keycode, |
| 259 | released: bool, |
| 260 | mods: u32, |
| 261 | keysym: Keysym, |
| 262 | unichar: u32, |
| 263 | ) -> KbMonBlock { |
| 264 | let _span = tracy_client::span!("KeyboardMonitor::process_key"); |
| 265 | |
| 266 | let mut ctxt = self.iface.get().unwrap().signal_emitter().clone(); |
| 267 | |
| 268 | let mut data = self.data.lock().unwrap(); |
| 269 | |
| 270 | // Emit key events as necessary. |
| 271 | for (name, client) in &data.clients { |
| 272 | if client.should_watch_keypress(&data.suppressed_keys, mods, keysym) { |
| 273 | let _span = tracy_client::span!("emitting key event"); |
| 274 | |
| 275 | // Emit to that client only. |
| 276 | ctxt = ctxt.set_destination(BusName::Unique(name.as_ref())); |
| 277 | let ctxt = &ctxt; |
| 278 | async_io::block_on(async move { |
| 279 | if let Err(err) = KeyboardMonitor::key_event( |
| 280 | ctxt, |
| 281 | released, |
| 282 | mods, |
| 283 | keysym.raw(), |
| 284 | unichar, |
| 285 | keycode.raw() as u16, |
| 286 | ) |
| 287 | .await |
| 288 | { |
| 289 | warn!("error emitting key_event: {err:?}"); |
| 290 | } |
| 291 | }); |
| 292 | } |
| 293 | } |
| 294 | |
| 295 | // Check for double-pressed grabbed modifier that should not be captured. |
| 296 | if data.grabbed_mods.contains(&keysym) { |
| 297 | if released { |
| 298 | // If missing from suppressed keys, then this is a release corresponding to the |
| 299 | // second press that got handled normally. |
| 300 | if !data.suppressed_keys.contains(&keysym) { |
| 301 | trace!("handling release for second press of grabbed modifier: {keysym:?}"); |
| 302 | return KbMonBlock::Pass; |
| 303 | } |
| 304 | } else { |
| 305 | let last_press_entry = data |
| 306 | .grabbed_mod_last_press_time |
| 307 | .entry(keysym) |
| 308 | .or_insert(Duration::ZERO); |
| 309 | let last_press = *last_press_entry; |
| 310 | *last_press_entry = time; |
| 311 | |
| 312 | // Modifier pressed twice; handle it as normal. |
| 313 | if time <= last_press.saturating_add(repeat_delay) { |
| 314 | trace!("handling second press of grabbed modifier: {keysym:?}"); |
| 315 | return KbMonBlock::Pass; |
| 316 | } |
| 317 | } |
| 318 | } |
| 319 | |
| 320 | let mut block = false; |
| 321 | |
| 322 | if released { |
| 323 | // This is a release for a key that was grabbed. |
| 324 | if data.suppressed_keys.remove(&keysym) { |
| 325 | trace!("blocking release for previously suppressed key: {keysym:?}"); |
| 326 | block = true; |
| 327 | } |
| 328 | } else if data.suppressed_keys.contains(&keysym) { |
| 329 | // Second press for an already-pressed key, e.g. from two keyboards. |
| 330 | trace!("blocking press for already-pressed key: {keysym:?}"); |
| 331 | block = true; |
| 332 | } else { |
| 333 | // Check if it's grabbed by any client. |
| 334 | if data |
| 335 | .clients |
| 336 | .values() |
| 337 | .any(|client| client.should_grab_keypress(&data.suppressed_keys, mods, keysym)) |
| 338 | { |
| 339 | trace!("blocking press for grabbed key: {keysym:?}"); |
| 340 | data.suppressed_keys.insert(keysym); |
| 341 | block = true; |
| 342 | } |
| 343 | } |
| 344 | |
| 345 | if !block { |
| 346 | KbMonBlock::Pass |
| 347 | } else if data.grabbed_mods.contains(&keysym) { |
| 348 | KbMonBlock::ModifierFirstPress |
| 349 | } else { |
| 350 | KbMonBlock::Block |
| 351 | } |
| 352 | } |
| 353 | } |
| 354 | |
| 355 | impl KeyboardData { |
| 356 | fn rebuild_grabbed_mods(&mut self) { |
| 357 | self.grabbed_mods.clear(); |
| 358 | for client in self.clients.values() { |
| 359 | self.grabbed_mods.extend(&client.modifiers); |
| 360 | } |
| 361 | } |
| 362 | } |
| 363 | |
| 364 | impl KeyboardClient { |
| 365 | fn should_grab_keypress( |
| 366 | &self, |
| 367 | suppressed_keys: &HashSet<Keysym>, |
| 368 | mods: u32, |
| 369 | keysym: Keysym, |
| 370 | ) -> bool { |
| 371 | // Grabbing all keys. |
| 372 | if self.grabbed { |
| 373 | return true; |
| 374 | } |
| 375 | |
| 376 | for modifier in &self.modifiers { |
| 377 | // This is a grabbed modifier, or a grabbed modifier is currently down. |
| 378 | if *modifier == keysym || suppressed_keys.contains(modifier) { |
| 379 | return true; |
| 380 | } |
| 381 | } |
| 382 | |
| 383 | for (grabbed_keysym, grabbed_mods) in &self.keystrokes { |
| 384 | // This is a grabbed keystroke. |
| 385 | if *grabbed_keysym == keysym && *grabbed_mods == mods { |
| 386 | return true; |
| 387 | } |
| 388 | } |
| 389 | |
| 390 | false |
| 391 | } |
| 392 | |
| 393 | fn should_watch_keypress( |
| 394 | &self, |
| 395 | suppressed_keys: &HashSet<Keysym>, |
| 396 | mods: u32, |
| 397 | keysym: Keysym, |
| 398 | ) -> bool { |
| 399 | if self.watched { |
| 400 | return true; |
| 401 | } |
| 402 | |
| 403 | self.should_grab_keypress(suppressed_keys, mods, keysym) |
| 404 | } |
| 405 | } |
| 406 | |
| 407 | /// Interface for locating the pointer position in the accessibility tree. |
| 408 | /// |
| 409 | /// This interface is used by assistive technologies to query the pointer position in the |
| 410 | /// accessibility tree. The compositor is expected to listen on the well-known bus name |
| 411 | /// "org.freedesktop.a11y.Manager" at the object path "/org/freedesktop/a11y/Manager". |
| 412 | #[interface(name = "org.freedesktop.a11y.PointerLocator")] |
| 413 | impl PointerLocator { |
| 414 | // Queries the a11y details about the toplevel beneath the mouse pointer, together with the |
| 415 | // relative position of the mouse pointer on the surface. The most up-to-date coordinates as |
| 416 | // known to the compositor are returned by this method call. |
| 417 | // |
| 418 | // Screen readers may use the given information to further query the accessibility tree of the |
| 419 | // specific application, in order to identify the application-side accessible elements directly |
| 420 | // underneath the mouse pointer. |
| 421 | // |
| 422 | // This request will also schedule the emission of a following "PointerPositionChanged" signal, |
| 423 | // whenever mouse pointer motion would happen. |
| 424 | // |
| 425 | // The "data" argument is a generic container, so far the only handled keys are relevant to |
| 426 | // AT-SPI: |
| 427 | // |
| 428 | // - "app-dbus-name" (type: s): Application D-Bus name in the a11y D-Bus |
| 429 | // - "toplevel-object-path" (type: o): Object path to the toplevel, in the given D-Bus name. |
| 430 | // |
| 431 | // If this data is not provided, the focused client will be considered to be the desktop |
| 432 | // environment itself, and the provided coordinates will be relative to its origin point. |
| 433 | // |
| 434 | // A org.freedesktop.a11y.UnknownToplevel error will be returned if the client under the pointer |
| 435 | // is non-introspectable. |
| 436 | async fn query_pointer( |
| 437 | &self, |
| 438 | #[zbus(header)] hdr: Header<'_>, |
| 439 | ) -> Result<(PointerAppData, f64, f64), A11yError> { |
| 440 | let Some(sender) = hdr.sender() else { |
| 441 | return Err(A11yError::Failed("no sender".to_owned())); |
| 442 | }; |
| 443 | let sender = OwnedUniqueName::from(sender.to_owned()); |
| 444 | |
| 445 | if let Err(err) = self.to_niri.send(A11yManagerToNiri::QueryPointer) { |
| 446 | warn!("error sending message to niri: {err:?}"); |
| 447 | return Err(A11yError::Failed("internal error".to_owned())); |
| 448 | } |
| 449 | |
| 450 | let rv = match self.from_niri.recv().await { |
| 451 | Ok(NiriToA11yManager::PointerContents(Some((data, x, y)))) => Ok((data, x, y)), |
| 452 | Ok(NiriToA11yManager::PointerContents(None)) => Err(A11yError::UnknownToplevel), |
| 453 | Err(err) => { |
| 454 | warn!("error receiving message from niri: {err:?}"); |
| 455 | Err(A11yError::Failed("internal error".to_owned())) |
| 456 | } |
| 457 | }; |
| 458 | |
| 459 | // Subscribe the client after all asynchronous operations. Otherwise it's possible for the |
| 460 | // pointer to move and the signal to be emitted before returning from this first |
| 461 | // QueryPointer request. |
| 462 | let mut data = self.data.lock().unwrap(); |
| 463 | if !data.clients.contains(&sender) { |
| 464 | trace!("enabling pointer position notifications for {sender}"); |
| 465 | data.clients.insert(sender); |
| 466 | } |
| 467 | |
| 468 | rv |
| 469 | } |
| 470 | |
| 471 | // This signal is emitted once when two conditions meet: |
| 472 | // 1. A "QueryPointer" method call happened before |
| 473 | // 2. Pointer motion happened after replying to that method call |
| 474 | // |
| 475 | // The purpose of the signal is being used as a throttling mechanism, so that a11y pointer |
| 476 | // handling is independent of device specifics like frequency rate at which input is handled. |
| 477 | // |
| 478 | // The expected response for a screen reader to this signal is scheduling a following |
| 479 | // "QueryPointer" method call. |
| 480 | #[zbus(signal)] |
| 481 | pub async fn pointer_position_changed(ctxt: &SignalEmitter<'_>) -> zbus::Result<()>; |
| 482 | } |
| 483 | |
| 484 | impl PointerLocator { |
| 485 | fn notify_pointer_position_changed(&self) { |
| 486 | let mut ctxt = self.iface.get().unwrap().signal_emitter().clone(); |
| 487 | |
| 488 | let mut data = self.data.lock().unwrap(); |
| 489 | for name in &data.clients { |
| 490 | let _span = tracy_client::span!("emitting pointer_position_changed"); |
| 491 | |
| 492 | ctxt = ctxt.set_destination(BusName::Unique(name.as_ref())); |
| 493 | let ctxt = &ctxt; |
| 494 | async_io::block_on(async move { |
| 495 | if let Err(err) = PointerLocator::pointer_position_changed(ctxt).await { |
| 496 | warn!("error emitting pointer_position_changed: {err:?}"); |
| 497 | } |
| 498 | }); |
| 499 | } |
| 500 | |
| 501 | // They will need to QueryPointer again to subscribe for the next signal. |
| 502 | data.clients.clear(); |
| 503 | } |
| 504 | } |
| 505 | |
| 506 | async fn monitor_disappeared_clients( |
| 507 | conn: &zbus::Connection, |
| 508 | kb_data: Arc<Mutex<KeyboardData>>, |
| 509 | pointer_data: Arc<Mutex<PointerData>>, |
| 510 | ) -> anyhow::Result<()> { |
| 511 | let proxy = fdo::DBusProxy::new(conn) |
| 512 | .await |
| 513 | .context("error creating a DBusProxy")?; |
| 514 | |
| 515 | let mut stream = proxy |
| 516 | .receive_name_owner_changed_with_args(&[(2, UniqueName::null_value())]) |
| 517 | .await |
| 518 | .context("error creating a NameOwnerChanged stream")?; |
| 519 | |
| 520 | while let Some(signal) = stream.next().await { |
| 521 | let args = signal |
| 522 | .args() |
| 523 | .context("error retrieving NameOwnerChanged args")?; |
| 524 | |
| 525 | let Some(name) = &**args.old_owner() else { |
| 526 | continue; |
| 527 | }; |
| 528 | |
| 529 | if args.new_owner().is_none() { |
| 530 | trace!("keyboard monitor client disconnected: {name}"); |
| 531 | |
| 532 | let name = OwnedUniqueName::from(name.to_owned()); |
| 533 | { |
| 534 | let mut data = kb_data.lock().unwrap(); |
| 535 | data.clients.remove(&name); |
| 536 | data.rebuild_grabbed_mods(); |
| 537 | } |
| 538 | { |
| 539 | let mut data = pointer_data.lock().unwrap(); |
| 540 | data.clients.remove(&name); |
| 541 | } |
| 542 | } else { |
| 543 | error!("non-null new_owner should've been filtered out"); |
| 544 | } |
| 545 | } |
| 546 | |
| 547 | Ok(()) |
| 548 | } |
| 549 | |
| 550 | impl Manager { |
| 551 | pub fn new( |
| 552 | to_niri: calloop::channel::Sender<A11yManagerToNiri>, |
| 553 | from_niri: async_channel::Receiver<NiriToA11yManager>, |
| 554 | ) -> Self { |
| 555 | Self { |
| 556 | keyboard_monitor: KeyboardMonitor::default(), |
| 557 | pointer_locator: PointerLocator { |
| 558 | data: Default::default(), |
| 559 | iface: Default::default(), |
| 560 | to_niri, |
| 561 | from_niri, |
| 562 | }, |
| 563 | } |
| 564 | } |
| 565 | |
| 566 | pub fn start(&self, monitor: bool) -> anyhow::Result<zbus::blocking::Connection> { |
| 567 | let conn = zbus::blocking::Connection::session()?; |
| 568 | conn.object_server().at( |
| 569 | "/org/freedesktop/a11y/Manager", |
| 570 | self.keyboard_monitor.clone(), |
| 571 | )?; |
| 572 | conn.object_server().at( |
| 573 | "/org/freedesktop/a11y/Manager", |
| 574 | self.pointer_locator.clone(), |
| 575 | )?; |
| 576 | request_name(&conn, "org.freedesktop.a11y.Manager", monitor)?; |
| 577 | |
| 578 | let iface = conn |
| 579 | .object_server() |
| 580 | .interface("/org/freedesktop/a11y/Manager")?; |
| 581 | let _ = self.keyboard_monitor.iface.set(iface); |
| 582 | |
| 583 | let iface = conn |
| 584 | .object_server() |
| 585 | .interface("/org/freedesktop/a11y/Manager")?; |
| 586 | let _ = self.pointer_locator.iface.set(iface); |
| 587 | |
| 588 | let kb_data = self.keyboard_monitor.data.clone(); |
| 589 | let pointer_data = self.pointer_locator.data.clone(); |
| 590 | |
| 591 | let async_conn = conn.inner().clone(); |
| 592 | let future = async move { |
| 593 | if let Err(err) = |
| 594 | monitor_disappeared_clients(&async_conn, kb_data.clone(), pointer_data.clone()) |
| 595 | .await |
| 596 | { |
| 597 | warn!("error monitoring keyboard monitor clients: {err:?}"); |
| 598 | |
| 599 | // Since the monitor is now broken, prevent any further communication. |
| 600 | if let Err(err) = async_conn.close().await { |
| 601 | warn!("error closing connection: {err:?}"); |
| 602 | } |
| 603 | |
| 604 | { |
| 605 | let mut data = kb_data.lock().unwrap(); |
| 606 | data.clients.clear(); |
| 607 | data.rebuild_grabbed_mods(); |
| 608 | } |
| 609 | { |
| 610 | let mut data = pointer_data.lock().unwrap(); |
| 611 | data.clients.clear(); |
| 612 | } |
| 613 | } |
| 614 | }; |
| 615 | let task = conn |
| 616 | .inner() |
| 617 | .executor() |
| 618 | .spawn(future, "monitor disappearing keyboard clients"); |
| 619 | task.detach(); |
| 620 | |
| 621 | Ok(conn) |
| 622 | } |
| 623 | } |
| 624 | |
| 625 | impl State { |
| 626 | pub fn a11y_process_key( |
| 627 | &mut self, |
| 628 | time: Duration, |
| 629 | keycode: Keycode, |
| 630 | state: KeyState, |
| 631 | ) -> KbMonBlock { |
| 632 | if self.niri.a11y_manager.is_none() { |
| 633 | return KbMonBlock::Pass; |
| 634 | } |
| 635 | |
| 636 | let keyboard = self.niri.seat.get_keyboard().unwrap(); |
| 637 | |
| 638 | let (mods, keysym, unichar) = keyboard.with_xkb_state(self, |context| { |
| 639 | let xkb = context.xkb().lock().unwrap(); |
| 640 | // SAFETY: we're not changing the ref count. |
| 641 | let state = unsafe { xkb.state() }; |
| 642 | |
| 643 | let keysym = state.key_get_one_sym(keycode); |
| 644 | let mods = state.serialize_mods(xkb::STATE_MODS_EFFECTIVE); |
| 645 | let unichar = state.key_get_utf32(keycode); |
| 646 | |
| 647 | (mods, keysym, unichar) |
| 648 | }); |
| 649 | |
| 650 | let config = self.niri.config.borrow(); |
| 651 | let repeat_delay = Duration::from_millis(u64::from(config.input.keyboard.repeat_delay)); |
| 652 | let released = state == KeyState::Released; |
| 653 | |
| 654 | let Some(manager) = &self.niri.a11y_manager else { |
| 655 | return KbMonBlock::Pass; |
| 656 | }; |
| 657 | let monitor = &manager.keyboard_monitor; |
| 658 | monitor.process_key(repeat_delay, time, keycode, released, mods, keysym, unichar) |
| 659 | } |
| 660 | |
| 661 | pub fn a11y_notify_pointer_motion(&mut self) { |
| 662 | let Some(manager) = &self.niri.a11y_manager else { |
| 663 | return; |
| 664 | }; |
| 665 | |
| 666 | manager.pointer_locator.notify_pointer_position_changed(); |
| 667 | } |
| 668 | |
| 669 | pub fn on_a11y_manager_msg( |
| 670 | &mut self, |
| 671 | to_a11y: &async_channel::Sender<NiriToA11yManager>, |
| 672 | msg: A11yManagerToNiri, |
| 673 | ) { |
| 674 | let A11yManagerToNiri::QueryPointer = msg; |
| 675 | let _span = tracy_client::span!("QueryPointer"); |
| 676 | |
| 677 | let pointer = &self.niri.seat.get_pointer().unwrap(); |
| 678 | let pointer_pos = pointer.current_location(); |
| 679 | |
| 680 | // Grabs can modify pointer focus, but here let's ignore them. I'm not entirely sure what's |
| 681 | // expected by a11y users though. |
| 682 | let contents = match &self.niri.pointer_contents { |
| 683 | PointContents { |
| 684 | surface: Some((surface, surface_pos)), |
| 685 | .. |
| 686 | } => { |
| 687 | if let Some(credentials) = get_credentials_for_surface(surface) { |
| 688 | // The current definition of the protocol expects buffer-relative pointer |
| 689 | // coordinates. I don't think this is correct, I opened a discussion here: |
| 690 | // https://gitlab.gnome.org/GNOME/mutter/-/work_items/4919 |
| 691 | let pos_within_surface = pointer_pos - *surface_pos; |
| 692 | |
| 693 | let data = PointerAppData { |
| 694 | pid: Some(credentials.pid), |
| 695 | // FIXME: fill these in from xdg_dbus_annotation when it's merged. |
| 696 | // https://gitlab.freedesktop.org/wayland/wayland-protocols/-/merge_requests/493 |
| 697 | app_dbus_name: None, |
| 698 | toplevel_object_path: None, |
| 699 | }; |
| 700 | |
| 701 | Some((data, pos_within_surface.x, pos_within_surface.y)) |
| 702 | } else { |
| 703 | // Client is not introspectable. |
| 704 | None |
| 705 | } |
| 706 | } |
| 707 | _ => { |
| 708 | // The focused client is niri itself. |
| 709 | Some((PointerAppData::default(), pointer_pos.x, pointer_pos.y)) |
| 710 | } |
| 711 | }; |
| 712 | |
| 713 | let msg = NiriToA11yManager::PointerContents(contents); |
| 714 | if let Err(err) = to_a11y.send_blocking(msg) { |
| 715 | warn!("error sending pointer contents to a11y manager: {err:?}"); |
| 716 | } |
| 717 | } |
| 718 | } |