forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB9d8f4f8Ivan Molodetskikh1 month ago2997 commits

a11y.rs372 lines, 11.9 KiBHistoryRawDownload
1use std::sync::mpsc;
2use std::thread;
3
4use accesskit::{
5 ActionHandler, ActionRequest, ActivationHandler, DeactivationHandler, Live, Node, NodeId, Role,
6 TreeId, TreeInfo, TreeUpdate,
7};
8use accesskit_unix::Adapter;
9use calloop::LoopHandle;
10use niri_config::MruScope;
11
12use crate::layout::workspace::WorkspaceId;
13use crate::niri::{KeyboardFocus, Niri, State};
14use crate::utils::with_toplevel_role;
15use crate::window::mapped::MappedId;
16
17const ID_ROOT: NodeId = NodeId(0);
18const ID_ANNOUNCEMENT: NodeId = NodeId(1);
19const ID_SCREENSHOT_UI: NodeId = NodeId(2);
20const ID_EXIT_CONFIRM_DIALOG: NodeId = NodeId(3);
21const ID_OVERVIEW: NodeId = NodeId(4);
22const ID_MRU: NodeId = NodeId(5);
23
24pub struct A11y {
25 event_loop: LoopHandle<'static, State>,
26 focus: NodeId,
27 workspace_id: Option<WorkspaceId>,
28 mru_selection: Option<MappedId>,
29 mru_scope: Option<MruScope>,
30 last_mru_title: String,
31 last_announcement: String,
32 to_accesskit: Option<mpsc::SyncSender<TreeUpdate>>,
33}
34
35enum Msg {
36 InitialTree,
37 Deactivate,
38 Action(ActionRequest),
39}
40
41impl A11y {
42 pub fn new(event_loop: LoopHandle<'static, State>) -> Self {
43 Self {
44 event_loop,
45 focus: ID_ROOT,
46 workspace_id: None,
47 mru_selection: None,
48 mru_scope: None,
49 last_mru_title: String::new(),
50 last_announcement: String::new(),
51 to_accesskit: None,
52 }
53 }
54
55 pub fn start(&mut self) {
56 let (tx, rx) = calloop::channel::channel();
57 let (to_accesskit, from_main) = mpsc::sync_channel::<TreeUpdate>(8);
58
59 // The adapter has a tendency to deadlock, so put it on a thread for now...
60 let handler = Handler { tx };
61 let res = thread::Builder::new()
62 .name("AccessKit Adapter".to_owned())
63 .spawn(move || {
64 let mut adapter = Adapter::new(handler.clone(), handler.clone(), handler);
65 while let Ok(tree) = from_main.recv() {
66 let is_focused = tree.focus != ID_ROOT;
67 adapter.update_if_active(move || tree);
68 adapter.update_window_focus_state(is_focused);
69 }
70 });
71
72 match res {
73 Ok(_handle) => {}
74 Err(err) => {
75 warn!("error spawning the AccessKit adapter thread: {err:?}");
76 return;
77 }
78 }
79
80 self.event_loop
81 .insert_source(rx, |e, _, state| match e {
82 calloop::channel::Event::Msg(msg) => state.niri.on_a11y_msg(msg),
83 calloop::channel::Event::Closed => (),
84 })
85 .unwrap();
86
87 self.to_accesskit = Some(to_accesskit);
88 }
89
90 fn update_tree(&mut self, tree: TreeUpdate) {
91 trace!("updating tree: {tree:?}");
92 self.focus = tree.focus;
93
94 let Some(tx) = &mut self.to_accesskit else {
95 return;
96 };
97 match tx.try_send(tree) {
98 Ok(()) => {}
99 Err(mpsc::TrySendError::Full(_)) => {
100 warn!("AccessKit channel is full, it probably deadlocked; disconnecting");
101 self.to_accesskit = None;
102 }
103 Err(mpsc::TrySendError::Disconnected(_)) => {
104 warn!("AccessKit channel disconnected");
105 self.to_accesskit = None;
106 }
107 }
108 }
109}
110
111impl Niri {
112 pub fn refresh_a11y(&mut self) {
113 if self.a11y.to_accesskit.is_none() {
114 return;
115 }
116
117 let _span = tracy_client::span!("refresh_a11y");
118
119 let mut announcement = None;
120 let ws_id = self.layout.active_workspace().map(|ws| ws.id());
121 if let Some(ws_id) = ws_id {
122 if self.a11y.workspace_id != Some(ws_id) {
123 let (_, idx, ws) = self
124 .layout
125 .workspaces()
126 .find(|(_, _, ws)| ws.id() == ws_id)
127 .unwrap();
128
129 let mut buf = format!("Workspace {}", idx + 1);
130 if let Some(name) = ws.name() {
131 buf.push(' ');
132 buf.push_str(name);
133 }
134
135 announcement = Some(buf);
136 }
137 }
138 self.a11y.workspace_id = ws_id;
139
140 let focus = self.a11y_focus();
141
142 // Check if the MRU selection changed.
143 let mut update_mru_selection = false;
144 if focus == ID_MRU {
145 let current = self.window_mru_ui.current_window_id();
146 if self.a11y.mru_selection != current {
147 update_mru_selection = true;
148 self.a11y.mru_selection = current;
149 }
150
151 // If there's no window title to announce, check if there's a scope change.
152 let scope = self.window_mru_ui.scope();
153 if !update_mru_selection && self.a11y.mru_scope != Some(scope) {
154 announcement = Some(self.window_mru_ui.a11y_scope_text());
155 }
156 self.a11y.mru_scope = Some(scope);
157 } else {
158 self.a11y.mru_scope = None;
159 self.a11y.mru_selection = None;
160 }
161
162 let update_focus = self.a11y.focus != focus;
163
164 if !(announcement.is_some() || update_focus || update_mru_selection) {
165 return;
166 }
167
168 let mut nodes = Vec::new();
169
170 if let Some(mut announcement) = announcement {
171 // Work around having to change node value for it to get announced.
172 if announcement == self.a11y.last_announcement {
173 announcement.push(' ');
174 }
175 self.a11y.last_announcement = announcement.clone();
176
177 let mut node = Node::new(Role::Label);
178 node.set_value(announcement);
179 node.set_live(Live::Polite);
180 nodes.push((ID_ANNOUNCEMENT, node));
181 }
182
183 if focus == ID_MRU {
184 // Ideally MRU would be a Group with a child Button for a window, but I've no idea how
185 // to make it work reliably. When I did it that way, there were two issues:
186 //
187 // 1. Alt-Tab would always start reading from "Recent windows grouping" instead of the
188 // window title.
189 // 2. When Alt-Tab became empty (e.g. switching scope to something empty), Orca would
190 // completely stop reading any child buttons for the remainder of the session.
191 //
192 // I've no idea what to do about these and where they even come from. So, just flip the
193 // MRU node between Group and Button, which seems to work fine.
194 if update_mru_selection {
195 if let Some(id) = self.a11y.mru_selection {
196 if let Some((_, mapped)) = self.layout.windows().find(|(_, m)| m.id() == id) {
197 with_toplevel_role(mapped.toplevel(), |role| {
198 let mut title = role.title.as_deref().unwrap_or("Unknown").to_owned();
199 // Change title on match to ensure we announce same-titled windows.
200 if self.a11y.last_mru_title == title {
201 title.push(' ');
202 }
203 self.a11y.last_mru_title = title;
204
205 let mut mru = Node::new(Role::Button);
206 mru.set_label(&*self.a11y.last_mru_title);
207 nodes.push((ID_MRU, mru));
208 });
209 }
210 } else {
211 let mut mru = Node::new(Role::Group);
212 // Announce the current scope in the empty text to make it clear.
213 let scope = self.window_mru_ui.a11y_scope_text();
214 mru.set_label(format!("Recent windows empty, {scope}"));
215 nodes.push((ID_MRU, mru));
216 }
217 }
218 }
219
220 let update = TreeUpdate {
221 nodes,
222 tree: None,
223 tree_id: TreeId::ROOT,
224 focus,
225 };
226
227 self.a11y.update_tree(update);
228 }
229
230 pub fn a11y_announce(&mut self, mut announcement: String) {
231 if self.a11y.to_accesskit.is_none() {
232 return;
233 }
234
235 let _span = tracy_client::span!("a11y_announce");
236
237 // Work around having to change node value for it to get announced.
238 if announcement == self.a11y.last_announcement {
239 announcement.push(' ');
240 }
241 self.a11y.last_announcement = announcement.clone();
242
243 let mut node = Node::new(Role::Label);
244 node.set_value(announcement);
245 node.set_live(Live::Polite);
246
247 let update = TreeUpdate {
248 nodes: vec![(ID_ANNOUNCEMENT, node)],
249 tree: None,
250 tree_id: TreeId::ROOT,
251 focus: self.a11y.focus,
252 };
253
254 self.a11y.update_tree(update);
255 }
256
257 pub fn a11y_announce_config_error(&mut self) {
258 if self.a11y.to_accesskit.is_none() {
259 return;
260 }
261
262 self.a11y_announce(crate::ui::config_error_notification::error_text(false));
263 }
264
265 pub fn a11y_announce_hotkey_overlay(&mut self) {
266 if self.a11y.to_accesskit.is_none() {
267 return;
268 }
269
270 self.a11y_announce(self.hotkey_overlay.a11y_text());
271 }
272
273 fn a11y_focus(&self) -> NodeId {
274 match self.keyboard_focus {
275 KeyboardFocus::ScreenshotUi => ID_SCREENSHOT_UI,
276 KeyboardFocus::ExitConfirmDialog => ID_EXIT_CONFIRM_DIALOG,
277 KeyboardFocus::Overview => ID_OVERVIEW,
278 KeyboardFocus::Mru => ID_MRU,
279 _ => ID_ROOT,
280 }
281 }
282
283 fn on_a11y_msg(&mut self, msg: Msg) {
284 match msg {
285 Msg::InitialTree => {
286 let tree = self.a11y_build_full_tree();
287 trace!("sending initial tree: {tree:?}");
288 self.a11y.update_tree(tree);
289 }
290 Msg::Deactivate => {
291 trace!("deactivate");
292 }
293 Msg::Action(request) => {
294 trace!("request: {request:?}");
295 }
296 }
297 }
298
299 fn a11y_build_full_tree(&self) -> TreeUpdate {
300 let mut node = Node::new(Role::Label);
301 node.set_live(Live::Polite);
302
303 let mut screenshot_ui = Node::new(Role::Group);
304 screenshot_ui.set_label("Screenshot UI");
305
306 let exit_confirm_dialog = crate::ui::exit_confirm_dialog::a11y_node();
307
308 let mut overview = Node::new(Role::Group);
309 overview.set_label("Overview");
310
311 let mut mru = Node::new(Role::Group);
312 mru.set_label("Recent windows");
313
314 let mut root = Node::new(Role::Window);
315 root.set_children(vec![
316 ID_ANNOUNCEMENT,
317 ID_SCREENSHOT_UI,
318 ID_EXIT_CONFIRM_DIALOG,
319 ID_OVERVIEW,
320 ID_MRU,
321 ]);
322
323 let tree = TreeInfo {
324 root: ID_ROOT,
325 toolkit_name: Some(String::from("niri")),
326 toolkit_version: None,
327 };
328
329 let focus = self.a11y_focus();
330
331 // NOTE: we don't fill in current MRU selection here to avoid duplicating code; it should
332 // get updated right away anyway.
333
334 TreeUpdate {
335 nodes: vec![
336 (ID_ROOT, root),
337 (ID_ANNOUNCEMENT, node),
338 (ID_SCREENSHOT_UI, screenshot_ui),
339 (ID_EXIT_CONFIRM_DIALOG, exit_confirm_dialog),
340 (ID_OVERVIEW, overview),
341 (ID_MRU, mru),
342 ],
343 tree: Some(tree),
344 tree_id: TreeId::ROOT,
345 focus,
346 }
347 }
348}
349
350#[derive(Clone)]
351struct Handler {
352 tx: calloop::channel::Sender<Msg>,
353}
354
355impl ActivationHandler for Handler {
356 fn request_initial_tree(&mut self) -> Option<TreeUpdate> {
357 let _ = self.tx.send(Msg::InitialTree);
358 None
359 }
360}
361
362impl DeactivationHandler for Handler {
363 fn deactivate_accessibility(&mut self) {
364 let _ = self.tx.send(Msg::Deactivate);
365 }
366}
367
368impl ActionHandler for Handler {
369 fn do_action(&mut self, request: ActionRequest) {
370 let _ = self.tx.send(Msg::Action(request));
371 }
372}