aboutsummaryrefslogtreecommitdiff
path: root/src/a11y.rs
blob: 04b92dbfa1766bc94082fefb84a68f088cb4315f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
use std::sync::mpsc;
use std::thread;

use accesskit::{
    ActionHandler, ActionRequest, ActivationHandler, DeactivationHandler, Live, Node, NodeId, Role,
    Tree, TreeUpdate,
};
use accesskit_unix::Adapter;
use calloop::LoopHandle;

use crate::layout::workspace::WorkspaceId;
use crate::niri::{KeyboardFocus, Niri, State};

const ID_ROOT: NodeId = NodeId(0);
const ID_ANNOUNCEMENT: NodeId = NodeId(1);
const ID_SCREENSHOT_UI: NodeId = NodeId(2);
const ID_EXIT_CONFIRM_DIALOG: NodeId = NodeId(3);
const ID_OVERVIEW: NodeId = NodeId(4);

pub struct A11y {
    event_loop: LoopHandle<'static, State>,
    focus: NodeId,
    workspace_id: Option<WorkspaceId>,
    last_announcement: String,
    to_accesskit: Option<mpsc::SyncSender<TreeUpdate>>,
}

enum Msg {
    InitialTree,
    Deactivate,
    Action(ActionRequest),
}

impl A11y {
    pub fn new(event_loop: LoopHandle<'static, State>) -> Self {
        Self {
            event_loop,
            focus: ID_ROOT,
            workspace_id: None,
            last_announcement: String::new(),
            to_accesskit: None,
        }
    }

    pub fn start(&mut self) {
        let (tx, rx) = calloop::channel::channel();
        let (to_accesskit, from_main) = mpsc::sync_channel::<TreeUpdate>(8);

        // The adapter has a tendency to deadlock, so put it on a thread for now...
        let handler = Handler { tx };
        let res = thread::Builder::new()
            .name("AccessKit Adapter".to_owned())
            .spawn(move || {
                let mut adapter = Adapter::new(handler.clone(), handler.clone(), handler);
                while let Ok(tree) = from_main.recv() {
                    let is_focused = tree.focus != ID_ROOT;
                    adapter.update_if_active(move || tree);
                    adapter.update_window_focus_state(is_focused);
                }
            });

        match res {
            Ok(_handle) => {}
            Err(err) => {
                warn!("error spawning the AccessKit adapter thread: {err:?}");
                return;
            }
        }

        self.event_loop
            .insert_source(rx, |e, _, state| match e {
                calloop::channel::Event::Msg(msg) => state.niri.on_a11y_msg(msg),
                calloop::channel::Event::Closed => (),
            })
            .unwrap();

        self.to_accesskit = Some(to_accesskit);
    }

    fn update_tree(&mut self, tree: TreeUpdate) {
        trace!("updating tree: {tree:?}");
        self.focus = tree.focus;

        let Some(tx) = &mut self.to_accesskit else {
            return;
        };
        match tx.try_send(tree) {
            Ok(()) => {}
            Err(mpsc::TrySendError::Full(_)) => {
                warn!("AccessKit channel is full, it probably deadlocked; disconnecting");
                self.to_accesskit = None;
            }
            Err(mpsc::TrySendError::Disconnected(_)) => {
                warn!("AccessKit channel disconnected");
                self.to_accesskit = None;
            }
        }
    }
}

impl Niri {
    pub fn refresh_a11y(&mut self) {
        if self.a11y.to_accesskit.is_none() {
            return;
        }

        let _span = tracy_client::span!("refresh_a11y");

        let mut announcement = None;
        let ws_id = self.layout.active_workspace().map(|ws| ws.id());
        if let Some(ws_id) = ws_id {
            if self.a11y.workspace_id != Some(ws_id) {
                let (_, idx, ws) = self
                    .layout
                    .workspaces()
                    .find(|(_, _, ws)| ws.id() == ws_id)
                    .unwrap();

                let mut buf = format!("Workspace {}", idx + 1);
                if let Some(name) = ws.name() {
                    buf.push(' ');
                    buf.push_str(name);
                }

                announcement = Some(buf);
            }
        }
        self.a11y.workspace_id = ws_id;

        let focus = self.a11y_focus();
        let update_focus = self.a11y.focus != focus;

        if !(announcement.is_some() || update_focus) {
            return;
        }

        let mut nodes = Vec::new();

        if let Some(mut announcement) = announcement {
            // Work around having to change node value for it to get announced.
            if announcement == self.a11y.last_announcement {
                announcement.push(' ');
            }
            self.a11y.last_announcement = announcement.clone();

            let mut node = Node::new(Role::Label);
            node.set_value(announcement);
            node.set_live(Live::Polite);
            nodes.push((ID_ANNOUNCEMENT, node));
        }

        let update = TreeUpdate {
            nodes,
            tree: None,
            focus,
        };

        self.a11y.update_tree(update);
    }

    pub fn a11y_announce(&mut self, mut announcement: String) {
        if self.a11y.to_accesskit.is_none() {
            return;
        }

        let _span = tracy_client::span!("a11y_announce");

        // Work around having to change node value for it to get announced.
        if announcement == self.a11y.last_announcement {
            announcement.push(' ');
        }
        self.a11y.last_announcement = announcement.clone();

        let mut node = Node::new(Role::Label);
        node.set_value(announcement);
        node.set_live(Live::Polite);

        let update = TreeUpdate {
            nodes: vec![(ID_ANNOUNCEMENT, node)],
            tree: None,
            focus: self.a11y.focus,
        };

        self.a11y.update_tree(update);
    }

    pub fn a11y_announce_config_error(&mut self) {
        if self.a11y.to_accesskit.is_none() {
            return;
        }

        self.a11y_announce(crate::ui::config_error_notification::error_text(false));
    }

    pub fn a11y_announce_hotkey_overlay(&mut self) {
        if self.a11y.to_accesskit.is_none() {
            return;
        }

        self.a11y_announce(self.hotkey_overlay.a11y_text());
    }

    fn a11y_focus(&self) -> NodeId {
        match self.keyboard_focus {
            KeyboardFocus::ScreenshotUi => ID_SCREENSHOT_UI,
            KeyboardFocus::ExitConfirmDialog => ID_EXIT_CONFIRM_DIALOG,
            KeyboardFocus::Overview => ID_OVERVIEW,
            _ => ID_ROOT,
        }
    }

    fn on_a11y_msg(&mut self, msg: Msg) {
        match msg {
            Msg::InitialTree => {
                let tree = self.a11y_build_full_tree();
                trace!("sending initial tree: {tree:?}");
                self.a11y.update_tree(tree);
            }
            Msg::Deactivate => {
                trace!("deactivate");
            }
            Msg::Action(request) => {
                trace!("request: {request:?}");
            }
        }
    }

    fn a11y_build_full_tree(&self) -> TreeUpdate {
        let mut node = Node::new(Role::Label);
        node.set_live(Live::Polite);

        let mut screenshot_ui = Node::new(Role::Group);
        screenshot_ui.set_label("Screenshot UI");

        let exit_confirm_dialog = crate::ui::exit_confirm_dialog::a11y_node();

        let mut overview = Node::new(Role::Group);
        overview.set_label("Overview");

        let mut root = Node::new(Role::Window);
        root.set_children(vec![
            ID_ANNOUNCEMENT,
            ID_SCREENSHOT_UI