crabshell-ui 0.8.0

Widgets, styles, layout, text and text editing, focus, hit testing and invalidation for Crabshell
Documentation
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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
//! What a screen reader is shown of the windows: each widget's role, name,
//! state and place, read from the window trees when it asks, and the
//! changes heard while one listens. The AT-SPI side is in
//! crabshell-services; nothing here walks a tree unless it is asked.

use std::cell::{Cell, RefCell};
use std::rc::{Rc, Weak};
use std::task::Waker;

use crate::geometry::Rect;
use crate::tree::{NodeId, NodeKind, Tree};

/// Every window's tree, for a screen reader. The shell provides one in
/// its root context, and each window registers its tree there as it is
/// made; a dropped window leaves on its own.
#[doc(hidden)]
#[derive(Default)]
pub struct Accessibility {
  windows: RefCell<Vec<(u32, Weak<RefCell<Tree>>)>>,
  next: Cell<u32>,
  /// A screen reader listens, so changes are kept for it.
  listening: Cell<bool>,
  events: RefCell<Vec<AccessEvent>>,
  /// Woken when an event is kept.
  waker: RefCell<Option<Waker>>,
}

/// One widget, or a window's root, as `window` and the node's number in
/// its tree. A removed node's number is never given again.
#[doc(hidden)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct AccessId {
  pub window: u32,
  pub node: u64,
}

/// What a widget is to a screen reader.
#[doc(hidden)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AccessRole {
  /// A panel, floating window or lock surface.
  Frame,
  /// A popup.
  Window,
  /// A row, column, stack, grid, scroll view or spacer.
  Filler,
  Button,
  Label,
  Entry,
  PasswordText,
  Slider,
  Image,
}

/// A widget as a screen reader reads it, at the moment it asked.
#[doc(hidden)]
#[derive(Clone, Debug, PartialEq)]
pub struct AccessNode {
  pub role: AccessRole,
  pub name: String,
  /// `None` for a window's root, whose parent is the application.
  pub parent: Option<AccessId>,
  /// The shown children, in Tab order.
  pub children: Vec<AccessId>,
  /// Its place among its parent's children, or a root's among the windows.
  pub index: usize,
  /// The laid-out rectangle in the window's logical pixels.
  pub rect: Rect,
  pub focusable: bool,
  pub focused: bool,
  pub enabled: bool,
  /// It and everything around it are shown.
  pub shown: bool,
  /// A root whose window has the keyboard.
  pub active: bool,
  pub editable: bool,
  pub multi_line: bool,
  /// It clicks, as a button does.
  pub clickable: bool,
}

/// A change a screen reader hears of.
#[doc(hidden)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AccessEvent {
  /// A widget shows the keyboard focus, or stops.
  Focused(AccessId, bool),
  NameChanged(AccessId),
  /// A window's root, as its window gets or loses the keyboard.
  Active(AccessId, bool),
  /// A widget shown or hidden.
  Shown(AccessId, bool),
  /// A button turned on or off.
  Enabled(AccessId, bool),
  /// `child` added to `parent` at `index`, or removed from there.
  Children {
    parent: AccessId,
    child: AccessId,
    index: usize,
    added: bool,
  },
  /// A window opened, closed, showed or hid, or a lock came or went, so
  /// [`Accessibility::windows`] may list others.
  WindowsChanged,
}

impl Accessibility {
  /// Adds a tree, and returns its window's number.
  pub(crate) fn register(&self, tree: Weak<RefCell<Tree>>) -> u32 {
    let id = self.next.get();
    self.next.set(id + 1);
    let mut windows = self.windows.borrow_mut();
    windows.retain(|(_, tree)| tree.strong_count() > 0);
    windows.push((id, tree));
    if self.listening() {
      self.push(AccessEvent::WindowsChanged);
    }
    id
  }

  /// Keeps changes for a screen reader while `on`; off, it drops those
  /// not taken.
  pub fn listen(&self, on: bool) {
    self.listening.set(on);
    if !on {
      self.events.borrow_mut().clear();
      // So whatever waits for events sees that nobody listens.
      if let Some(waker) = self.waker.take() {
        waker.wake();
      }
    }
  }

  pub(crate) fn listening(&self) -> bool {
    self.listening.get()
  }

  pub(crate) fn push(&self, event: AccessEvent) {
    self.events.borrow_mut().push(event);
    if let Some(waker) = self.waker.take() {
      waker.wake();
    }
  }

  /// The changes kept since the last call. `waker` is woken at the next.
  pub fn take_events(&self, waker: &Waker) -> Vec<AccessEvent> {
    self.waker.replace(Some(waker.clone()));
    std::mem::take(&mut self.events.borrow_mut())
  }

  /// Window `window`'s tree, while it is listed.
  fn tree(&self, window: u32) -> Option<Rc<RefCell<Tree>>> {
    if !self.windows().iter().any(|root| root.window == window) {
      return None;
    }
    let windows = self.windows.borrow();
    let (_, tree) = windows.iter().find(|(id, _)| *id == window)?;
    tree.upgrade()
  }

  /// The roots of the windows shown, oldest first. While a lock surface
  /// is up, only the lock surfaces, so nothing behind the lock is read
  /// or clicked.
  pub fn windows(&self) -> Vec<AccessId> {
    let windows = self.windows.borrow();
    let shown: Vec<(AccessId, bool)> = windows
      .iter()
      .filter_map(|(id, tree)| {
        let tree = tree.upgrade()?;
        let tree = tree.try_borrow().ok()?;
        let shown = tree
          .floating
          .as_ref()
          .is_none_or(|floating| floating.shown());
        let lock = tree
          .node(tree.root)
          .is_some_and(|root| root.name == "SessionLock");
        let root = AccessId {
          window: *id,
          node: tree.root.into(),
        };
        shown.then_some((root, lock))
      })
      .collect();
    let locked = shown.iter().any(|(_, lock)| *lock);
    let listed = shown.into_iter().filter(|(_, lock)| *lock || !locked);
    listed.map(|(root, _)| root).collect()
  }

  /// Widget `id` as it is now, or `None` once it is gone or its window
  /// isn't listed.
  pub fn node(&self, id: AccessId) -> Option<AccessNode> {
    let rc = self.tree(id.window)?;
    let tree = rc.try_borrow().ok()?;
    let node_id = NodeId::from(id.node);
    let node = tree.node(node_id)?;
    let is_root = node_id == tree.root;
    let at = |node: NodeId| AccessId {
      window: id.window,
      node: node.into(),
    };
    let (parent, index) = if is_root {
      let index = self.windows().iter().position(|root| *root == id);
      (None, index.unwrap_or_default())
    } else {
      let parent = tree
        .taffy
        .parent(node_id)
        .expect("invariant: a node other than the root has a parent");
      let index = exposed_children(&tree, parent)
        .iter()
        .position(|&n| n == node_id);
      (Some(at(parent)), index.unwrap_or_default())
    };
    let role = role(&tree, node_id);
    let focused = tree.keyboard.entered
      && tree.keyboard.focused.map(|focused| exposed(&tree, focused)) == Some(node_id);
    let (enabled, clickable) = match &node.kind {
      NodeKind::Button(button) => (button.enabled, button.enabled),
      _ => (true, false),
    };
    let (editable, multi_line) = match &node.kind {
      NodeKind::Input(input) => (true, input.edit.multiline),
      _ => (false, false),
    };
    let focusable = match role {
      AccessRole::Button => enabled,
      AccessRole::Entry | AccessRole::PasswordText | AccessRole::Slider => true,
      _ => false,
    };
    let children = match role {
      AccessRole::Slider => Vec::new(),
      _ => exposed_children(&tree, node_id),
    };
    Some(AccessNode {
      role,
      name: name(&tree, node_id),
      parent,
      children: children.into_iter().map(at).collect(),
      index,
      rect: node.rect.unwrap_or_default(),
      focusable,
      focused,
      enabled,
      shown: tree.shown(node_id),
      active: is_root && tree.keyboard.entered,
      editable,
      multi_line,
      clickable,
    })
  }

  /// Clicks button `id`, as Enter on it does, and says whether it was a
  /// shown, enabled button. The click runs with the tree released.
  pub fn click(&self, id: AccessId) -> bool {
    let Some(rc) = self.tree(id.window) else {
      return false;
    };
    let call = {
      let Ok(tree) = rc.try_borrow() else {
        return false;
      };
      let node_id = NodeId::from(id.node);
      let enabled = matches!(
        tree.node(node_id).map(|node| &node.kind),
        Some(NodeKind::Button(button)) if button.enabled
      );
      if !enabled || !tree.shown(node_id) {
        return false;
      }
      tree.click(node_id)
    };
    // Dropped first: the handler may drop the window.
    drop(rc);
    if let Some(call) = call {
      call.run();
    }
    true
  }
}

impl Tree {
  /// Keeps `event` for a screen reader, made from this window's number,
  /// if one listens.
  pub(crate) fn access_event(&self, event: impl FnOnce(u32) -> AccessEvent) {
    if let Some((access, window)) = &self.access
      && access.listening()
    {
      access.push(event(*window));
    }
  }

  /// Keeps an event about widget `id`, made from its id, if a screen
  /// reader listens and the widget was laid out, so one it can't have
  /// seen yet makes no noise.
  pub(crate) fn node_event(&self, id: NodeId, event: impl FnOnce(AccessId) -> AccessEvent) {
    if self.node(id).is_some_and(|node| node.rect.is_some()) {
      self.access_event(|window| event(self.access_id(window, id)));
    }
  }

  pub(crate) fn access_id(&self, window: u32, node: NodeId) -> AccessId {
    AccessId {
      window,
      node: exposed(self, node).into(),
    }
  }

  fn listening(&self) -> bool {
    self
      .access
      .as_ref()
      .is_some_and(|(access, _)| access.listening())
  }

  /// Text `id` changed, which renames it and the button around it.
  pub(crate) fn text_renamed(&self, id: NodeId) {
    if !self.listening() {
      return;
    }
    self.node_event(id, AccessEvent::NameChanged);
    self.button_renamed(id);
  }

  /// Something inside a button changed what it shows, which renames the
  /// nearest button around `id`.
  pub(crate) fn button_renamed(&self, id: NodeId) {
    if !self.listening() {
      return;
    }
    let mut at = self.taffy.parent(id);
    while let Some(parent) = at {
      if matches!(
        self.node(parent).map(|node| &node.kind),
        Some(NodeKind::Button(_))
      ) {
        // A label inside a slider renames nothing more.
        if exposed(self, parent) == parent {
          self.node_event(parent, AccessEvent::NameChanged);
        }
        return;
      }
      at = self.taffy.parent(parent);
    }
  }
}

/// The node a screen reader sees for `id`: the slider around it, if any,
/// since a slider shows as one object.
fn exposed(tree: &Tree, id: NodeId) -> NodeId {
  let mut found = id;
  let mut at = Some(id);
  while let Some(current) = at {
    let Some(node) = tree.node(current) else {
      break;
    };
    if node.name == "Slider" {
      found = current;
    }
    at = tree.taffy.parent(current);
  }
  found
}

/// The children of `id`, in Tab order, hidden ones too: their state
/// says they don't show.
fn exposed_children(tree: &Tree, id: NodeId) -> Vec<NodeId> {
  tree.taffy.children(id).unwrap_or_default()
}

impl Tree {
  /// `parent`'s children before a change, when a screen reader listens
  /// and has seen it: it was laid out and isn't inside a slider.
  pub(crate) fn access_children(&self, parent: NodeId) -> Option<Vec<NodeId>> {
    let seen = self.node(parent).is_some_and(|node| node.rect.is_some());
    (self.listening()
      && seen
      && exposed(self, parent) == parent
      && role(self, parent) != AccessRole::Slider)
      // Its groups still hold children removed from taffy before.
      .then(|| {
        self
          .node(parent)
          .map(|node| node.groups.concat())
          .unwrap_or_default()
      })
  }

  /// Tells a screen reader which children `parent` lost and gained.
  pub(crate) fn children_changed(&self, parent: NodeId, before: &[NodeId], after: &[NodeId]) {
    let removed = before
      .iter()
      .enumerate()
      .filter(|(_, id)| !after.contains(id));
    let added = after
      .iter()
      .enumerate()
      .filter(|(_, id)| !before.contains(id));
    let changes = removed
      .map(|change| (change, false))
      .chain(added.map(|change| (change, true)));
    for ((index, &child), added) in changes {
      // Neither is inside a slider, and a removed child is gone from
      // taffy, so their ids are their own.
      let id = |window, node: NodeId| AccessId {
        window,
        node: node.into(),
      };
      self.access_event(|window| AccessEvent::Children {
        parent: id(window, parent),
        child: id(window, child),
        index,
        added,
      });
    }
  }
}

fn role(tree: &Tree, id: NodeId) -> AccessRole {
  let Some(node) = tree.node(id) else {
    return AccessRole::Filler;
  };
  if node.name == "Slider" {
    return AccessRole::Slider;
  }
  match &node.kind {
    NodeKind::Root if tree.popup.is_some() => AccessRole::Window,
    NodeKind::Root => AccessRole::Frame,
    NodeKind::Button(_) => AccessRole::Button,
    NodeKind::Text(_) => AccessRole::Label,
    NodeKind::Input(input) if input.password => AccessRole::PasswordText,
    NodeKind::Input(_) => AccessRole::Entry,
    NodeKind::Icon(_) | NodeKind::Image(_) | NodeKind::Capture(_) | NodeKind::Canvas(_) => {
      AccessRole::Image
    }
    _ => AccessRole::Filler,
  }
}

/// The name a config gave, or else a button's shown text, a text's own,
/// a field's placeholder, or a window's title or namespace.
fn name(tree: &Tree, id: NodeId) -> String {
  let Some(node) = tree.node(id) else {
    return String::new();
  };
  if let Some(name) = &node.accessible_name {
    return name.clone();
  }
  match &node.kind {
    NodeKind::Root => match &tree.floating {
      Some(floating) => floating.title().to_owned(),
      None if tree.popup.is_none() && node.name == "PanelWindow" => tree.surface.namespace.clone(),
      None => String::new(),
    },
    NodeKind::Text(text) => text.content.clone(),
    NodeKind::Input(input) => input.placeholder.clone(),
    NodeKind::Button(_) => {
      let mut texts = Vec::new();
      let mut pending = vec![id];
      while let Some(at) = pending.pop() {
        match tree.node(at) {
          Some(node) if !node.visible => continue,
          Some(node) => {
            if let NodeKind::Text(text) = &node.kind
              && !text.content.trim().is_empty()
            {
              texts.push(text.content.trim().to_owned());
            }
          }
          None => continue,
        }
        let mut children = tree.taffy.children(at).unwrap_or_default();
        children.reverse();
        pending.extend(children);
      }
      texts.join(" ")
    }
    _ => String::new(),
  }
}