Skip to main content

teksilo_core/widget_tree/
accessibility_impl.rs

1// SPDX-License-Identifier: MPL-2.0
2// SPDX-FileCopyrightText: 2026 FernTech
3
4use super::*;
5
6use crate::accessibility::{AccessNodeBuilder, AccessibilityInfo};
7
8/// A Teksilo rect as AccessKit expresses one: two corners rather than an
9/// origin and a size.
10pub(super) fn to_accesskit_rect(rect: teksilo_canvas::Rect) -> accesskit::Rect {
11    accesskit::Rect {
12        x0: rect.x as f64,
13        y0: rect.y as f64,
14        x1: (rect.x + rect.width) as f64,
15        y1: (rect.y + rect.height) as f64,
16    }
17}
18
19impl WidgetTree {
20    /// The AccessKit `TreeUpdate` for the current state of all active widgets:
21    /// always the **full tree**, a complete snapshot of every node under the
22    /// tree's own ids, never a delta against an earlier call.
23    ///
24    /// Call this once per frame, between layout and paint. It is the read for
25    /// everything in process (a test, the automation bridge, the announcement
26    /// ring). It is **not** what a platform adapter is fed: an adapter is
27    /// handed [`deliver_accessibility`](Self::deliver_accessibility), which
28    /// maps the ids and is skipped when
29    /// [`accessibility_delivery_owed`](Self::accessibility_delivery_owed) says
30    /// the adapter already holds the tree.
31    ///
32    /// To find out whether something changed between two calls, a test
33    /// compares [`at_version`](Self::at_version) (it bumps only when the tree's
34    /// content differs), or
35    /// [`a11y_walk_generation`](Self::a11y_walk_generation) (it counts walks,
36    /// so it also moves for a walk that reproduced the same tree), or the node
37    /// itself in the two snapshots. The two snapshots are each complete, so
38    /// comparing their lengths or "what the update contains" says nothing.
39    ///
40    /// Caches the result and rebuilds only when something that actually
41    /// changes the AT tree has happened: a focus move, an overlay change, a
42    /// widget rebuild, an active↔dormant transition, an `AccessibilityOnly`
43    /// binding flip, a shortcut rebind, a locale switch, a queued
44    /// announcement, or an explicit
45    /// [`request_accessibility_update`](Self::request_accessibility_update).
46    /// A plain relayout does not invalidate the cache.
47    pub fn sync_accessibility(&mut self) -> accesskit::TreeUpdate {
48        self.refresh_accessibility();
49        self.cached_a11y
50            .as_ref()
51            .expect("refresh_accessibility leaves an update behind")
52            .clone()
53    }
54
55    /// [`sync_accessibility`](Self::sync_accessibility) without handing out
56    /// the update: everything it does every frame (the announcers, the
57    /// announcement ring, `at_version`, the cache) at none of the cost of a
58    /// copy of the whole tree. For the event loop, which hands the adapter
59    /// [`deliver_accessibility`](Self::deliver_accessibility) or
60    /// [`accessibility_unchanged`](Self::accessibility_unchanged) and reads
61    /// nothing else.
62    #[doc(hidden)]
63    pub fn refresh_accessibility(&mut self) {
64        // Explicit re-walk request (e.g. `SceneView` materialised / destroyed a
65        // scene widget, or an a11y-only scene mutation). A relayout no longer
66        // sets `a11y_dirty` on its own, so this is the lever; drain it before
67        // the cache check below.
68        if self.a11y_update_requested.replace(false) {
69            self.a11y_dirty = true;
70        }
71        // Shortcut registry rebinds bump
72        // `ShortcutRegistry::version()`. The `access_shortcut_id`
73        // resolution in the walker reads the live registry, so any
74        // rebind must invalidate the AT-tree cache too — otherwise
75        // a rebind would not surface in the announced shortcut
76        // until something else dirties the tree (a layout, a focus
77        // change, …). Cheap: one u64 compare per `sync_accessibility`.
78        let current_shortcut_version = self.shortcut_registry.version().get();
79        if current_shortcut_version != self.last_synced_shortcut_version {
80            self.a11y_dirty = true;
81            self.last_synced_shortcut_version = current_shortcut_version;
82        }
83
84        // Locale switches make `access_label(tr!(...))` (stored as a
85        // locale-bound `Prop<String>`) resolve to a new value. The
86        // override props are read in `apply()` during the walk, so the
87        // tree must re-walk for the new announcement to surface —
88        // otherwise the screen reader keeps the old-locale string until
89        // something else dirties the tree. Mirror the shortcut-version
90        // guard above. (Same-direction switches don't rebuild the
91        // composite, so this is the only thing that refreshes AT labels.)
92        let current_locale = self.locale_signal.get();
93        if current_locale != self.last_synced_locale {
94            self.a11y_dirty = true;
95            self.last_synced_locale = current_locale;
96        }
97
98        // The window's title names the root, so a new title is a new name for
99        // the window a screen reader announces: re-walk, as for a locale.
100        let current_title = self.window_title_for_accessibility();
101        if current_title != self.last_synced_window_title {
102            self.a11y_dirty = true;
103            self.last_synced_window_title = current_title;
104        }
105
106        // The framework's own live regions. Advancing them here, before the
107        // cache check, is what makes a queued announcement able to wake a tree
108        // that is otherwise clean: `announce` sets `a11y_update_requested`,
109        // which the drain above turned into `a11y_dirty`, and the step below
110        // readies the message this update may say. The walk decides whether it
111        // does: not in an update that moves focus (see `crate::announcer`).
112        // One message enters the tree an update, so an announcer with more
113        // queued, or one still waiting, asks for another sync and another
114        // frame; one whose messages are only lingering asks the event loop to
115        // wake when the next is due to leave.
116        self.step_announcers();
117
118        if !self.a11y_dirty
119            && let Some(cached) = &self.cached_a11y
120        {
121            // Nothing about a widget's *content* depends on where it sits,
122            // so a pure translation is re-placed in the cached tree rather
123            // than rebuilt: the alternative — walking on every scroll frame
124            // — was too expensive to do, so it was not done, and every
125            // node's bounds went stale the moment anything scrolled.
126            //
127            // The full-tree contract is unchanged. Around twenty callers
128            // read this return value as a complete description of the tree
129            // (`wait_for_condition`, `snapshot_json`, `find_node`, the
130            // headless harness), and the consumer panics on an update
131            // naming a node it has never seen, so a partial update is not
132            // an option here.
133            let _ = cached;
134            let moved = self.patch_accessibility_bounds();
135            // A move alone can still announce: a live node its clipping
136            // parent brings back into view enters the filtered tree. The
137            // ring records it now; a platform adapter learns of it with the
138            // next delivery, which `teksilo-app` holds back up to 100 ms
139            // while only moves are owed, so a live node a fling carries into
140            // view and out again inside that window is recorded here and
141            // never announced by the adapter. Replaying costs
142            // a pass of the consumer over every node, on every frame of a
143            // scroll, so it is done only when something besides the
144            // announcers is live: nothing else can be announced by a move,
145            // and a live node that appears later arrives through a walk,
146            // which is always replayed. A tree that records nothing skips
147            // even the scan.
148            if moved
149                && self.announcement_ring.is_recording()
150                && let Some(patched) = &self.cached_a11y
151                && patched.nodes.iter().any(|(id, node)| {
152                    !crate::announcer::is_announcer_node(*id)
153                        && node.live().is_some_and(|live| live != accesskit::Live::Off)
154                })
155            {
156                self.announcement_ring.observe(patched);
157            }
158            return;
159        }
160
161        let (update, parents, local_bounds, descriptions, admitted) =
162            self.build_accessibility_tree(true);
163        let announcers_busy = self.settle_announcers(admitted);
164        // What the adapters will announce from this update. Here, in the
165        // `&mut self` half and not in the `&self` walk, because the ring
166        // replays exactly the updates this method hands out, in order. A tree
167        // that does not record only notes that it missed one.
168        self.announcement_ring.observe(&update);
169        // Bump the AT version only when the tree's *content* actually changed.
170        // A rebuild can be triggered by a shortcut-rebind / locale switch that
171        // produces a byte-for-byte identical `TreeUpdate`; bumping then would
172        // make `WaitCondition::AtVersionAtLeast` wake on no real change.
173        // `TreeUpdate: PartialEq`, so this is a precise (if O(n)) comparison —
174        // acceptable since it only runs on a real rebuild, not a cache hit.
175        let content_changed = self.cached_a11y.as_ref() != Some(&update);
176        self.cached_a11y = Some(update);
177        if content_changed {
178            self.adapter_ids.source_changed();
179        }
180        self.synthetic_parent_map = parents;
181        self.synthetic_local_bounds = local_bounds;
182        // What the next update's descriptions are measured against: only a
183        // delivered update is something a screen reader has heard. A node
184        // focus has just left held a text back from this update, so as not to
185        // say it on the way out; nothing else may rebuild the tree before
186        // focus comes back, and the text is owed to anyone who reads the node
187        // without focusing it, so the next update is asked for here.
188        let descriptions_catching_up = descriptions.catching_up;
189        self.description_memory = descriptions;
190        self.a11y_dirty = false;
191        // A walk has just described every node's current position, so the
192        // moves recorded up to now are already reflected.
193        self.arena.take_a11y_moved();
194        self.arena.take_a11y_resized();
195        self.a11y_walk_generation = self.a11y_walk_generation.saturating_add(1);
196        if content_changed {
197            // Mirror of the shortcut-registry version signal; saturating so the
198            // documented "monotonic" contract holds even past `u64::MAX`.
199            self.at_version.set(self.at_version.get().saturating_add(1));
200        }
201        if announcers_busy || descriptions_catching_up {
202            self.request_accessibility_update();
203            self.request_frame();
204        }
205    }
206
207    /// The update the last [`sync_accessibility`](Self::sync_accessibility)
208    /// built, as a platform adapter must be handed it.
209    ///
210    /// A node that leaves the tree a reader sees and comes back (a tab page
211    /// shown again, a reopened menu or combo list, a row scrolled back into
212    /// view, a container focus returns to) would come back under the id it
213    /// left with, and the AT-SPI adapter announced that id defunct as it left:
214    /// libatspi keeps it so, and Orca drops every event from it. This hands
215    /// such a node an id the adapter has never had, and keeps every other id
216    /// as the tree has it.
217    ///
218    /// Call it for every update handed to the adapter, and for nothing else:
219    /// it keeps its own replay of the adapter's tree, which is how it knows
220    /// what the adapter removed. `window_focused` is whether the adapter was
221    /// last told its window has focus (winit's `Focused`). Route every
222    /// `ActionRequest` the adapter sends back through
223    /// [`resolve_adapter_action`](Self::resolve_adapter_action).
224    ///
225    /// Everything else that reads the tree in process (the automation bridge,
226    /// the announcement ring, a test) reads the tree's own ids, from
227    /// `sync_accessibility`.
228    pub fn deliver_accessibility(&mut self, window_focused: bool) -> accesskit::TreeUpdate {
229        if self.cached_a11y.is_none() {
230            let _ = self.sync_accessibility();
231        }
232        let arena = &self.arena;
233        let source = self
234            .cached_a11y
235            .as_ref()
236            .expect("sync_accessibility leaves an update behind");
237        self.adapter_ids.deliver(source, window_focused, |id| {
238            crate::accessibility::node_id_to_widget_id_maybe(id)
239                .is_none_or(|widget| arena.get(widget).is_some())
240        })
241    }
242
243    /// Whether [`deliver_accessibility`](Self::deliver_accessibility) would
244    /// hand the adapter anything it does not already hold: the tree changed
245    /// since the last delivery (a walk with new content, a node moved), the
246    /// window's focus changed, or nothing was delivered yet. When it would
247    /// not, a delivery hands the adapter a copy of what it has, which it
248    /// compares node by node to find nothing. `window_focused` as for
249    /// `deliver_accessibility`; read after this frame's
250    /// [`sync_accessibility`](Self::sync_accessibility).
251    #[doc(hidden)]
252    pub fn accessibility_delivery_owed(&self, window_focused: bool) -> bool {
253        self.cached_a11y.is_none() || self.adapter_ids.owes(window_focused)
254    }
255
256    /// What to hand a platform adapter on a frame that delivers nothing new.
257    ///
258    /// While nothing is [owed](Self::accessibility_delivery_owed), an update
259    /// with no node and the focus the adapter was last handed, which it
260    /// applies without comparing anything.
261    /// [`deliver_accessibility`](Self::deliver_accessibility) would hand it
262    /// a copy of every node it holds, to compare one by one: on a frame
263    /// that only blinks a caret, that was most of the frame's work. While
264    /// something is owed, what `deliver_accessibility` hands out.
265    #[doc(hidden)]
266    pub fn accessibility_unchanged(&mut self, window_focused: bool) -> accesskit::TreeUpdate {
267        if !self.accessibility_delivery_owed(window_focused)
268            && let Some(update) = self.adapter_ids.unchanged()
269        {
270            return update;
271        }
272        self.deliver_accessibility(window_focused)
273    }
274
275    /// What to hand a platform adapter on a frame that holds back what is
276    /// [owed](Self::accessibility_delivery_owed): an update with no node and
277    /// the focus the adapter was last handed, so it compares nothing and
278    /// hears nothing new. `None` when what is owed cannot wait: nothing was
279    /// delivered yet, or the window's focus changed since the last delivery.
280    /// The caller delivers what was held later, through
281    /// [`deliver_accessibility`](Self::deliver_accessibility), which hands
282    /// out the tree as it then is.
283    #[doc(hidden)]
284    pub fn accessibility_held(&self, window_focused: bool) -> Option<accesskit::TreeUpdate> {
285        self.cached_a11y.as_ref()?;
286        self.adapter_ids.held(window_focused)
287    }
288
289    /// An action a platform adapter asked for, with its node ids back in the
290    /// tree's own. `None` when it names an id that
291    /// [`deliver_accessibility`](Self::deliver_accessibility) handed out once
292    /// and has since replaced, which is no node any more.
293    pub fn resolve_adapter_action(
294        &self,
295        request: accesskit::ActionRequest,
296    ) -> Option<accesskit::ActionRequest> {
297        self.adapter_ids.own_request(request)
298    }
299
300    /// How many accessibility walks have happened.
301    ///
302    /// A delivery that has not seen the latest walk is holding a tree whose
303    /// *shape* may be stale, not merely its geometry — so it must push the
304    /// full tree rather than rely on the geometry patch.
305    pub fn a11y_walk_generation(&self) -> u64 {
306        self.a11y_walk_generation
307    }
308
309    /// Re-place the nodes that moved, in the cached tree, without walking.
310    ///
311    /// Only geometry changes here: `at_version` is not bumped (its
312    /// contract is *semantic* change), no announcement is collected, and
313    /// the next full walk's `PartialEq` comparison stays correct because
314    /// the cache already holds the new bounds.
315    ///
316    /// A moved id absent from the cache is skipped rather than inserted:
317    /// it is a node the walk deliberately left out — a pruned layout
318    /// stack, an excluded or merged descendant — and inventing an entry
319    /// for it would put a node in the update that has no parent.
320    ///
321    /// Returns whether anything was re-placed.
322    fn patch_accessibility_bounds(&mut self) -> bool {
323        let moved = self.arena.take_a11y_moved();
324        if moved.is_empty() {
325            return false;
326        }
327        let Some(cached) = self.cached_a11y.as_mut() else {
328            return false;
329        };
330        let index: std::collections::HashMap<accesskit::NodeId, usize> = cached
331            .nodes
332            .iter()
333            .enumerate()
334            .map(|(i, (id, _))| (*id, i))
335            .collect();
336
337        for &id in moved.keys() {
338            let bounds = self.arena.bounds(id);
339            if let Some(&slot) = index.get(&crate::accessibility::widget_id_to_node_id(id)) {
340                cached.nodes[slot].1.set_bounds(to_accesskit_rect(bounds));
341            }
342        }
343
344        // Synthetic children ride their owner. Those that declared local
345        // bounds are re-derived from the owner's new origin — exact, and
346        // immune to a delta that accumulated across several passes. The
347        // rest hold absolute rects and are shifted by the owner's own delta.
348        for (&syn_id, &owner) in &self.synthetic_parent_map {
349            let Some(delta) = moved.get(&owner) else {
350                continue;
351            };
352            let Some(&slot) = index.get(&syn_id) else {
353                continue;
354            };
355            let node = &mut cached.nodes[slot].1;
356            // Unless the child names its own coordinate space. A scene item
357            // states its rectangle in scene coordinates and declares the
358            // camera beside it; the owner's window-space delta is not a
359            // quantity in that space, and adding it would slide the item by
360            // however far its *view* moved. Such a node is re-placed by a walk
361            // — the view transform folds in its own origin, so a view that
362            // moved has already dirtied the tree — and never by this patch.
363            if node.transform().is_some() {
364                continue;
365            }
366            if let Some(local) = self.synthetic_local_bounds.get(&syn_id) {
367                let origin = self.arena.bounds(owner).origin();
368                node.set_bounds(to_accesskit_rect(teksilo_canvas::Rect::new(
369                    origin.x + local.x,
370                    origin.y + local.y,
371                    local.width,
372                    local.height,
373                )));
374                // The same snap the walk applies, from the unsnapped rect:
375                // a moved line's top falls inside a different pixel.
376                if reports_in_window_space(&self.arena, owner) {
377                    let owner_box = to_accesskit_rect(self.arena.bounds(owner));
378                    snap_text_run_top(node, self.device_scale_factor, Some(owner_box));
379                }
380            } else if let Some(rect) = node.bounds() {
381                node.set_bounds(accesskit::Rect {
382                    x0: rect.x0 + delta.x as f64,
383                    y0: rect.y0 + delta.y as f64,
384                    x1: rect.x1 + delta.x as f64,
385                    y1: rect.y1 + delta.y as f64,
386                });
387            }
388        }
389        // A move can take a node out of its clipping parent's view, or bring
390        // one back, which the adapter hears as a removal or an arrival.
391        self.adapter_ids.source_changed();
392        true
393    }
394
395    /// Build a `TreeUpdate` describing the tree right now, without touching any
396    /// state.
397    ///
398    /// For a caller that wants to *look* at the accessibility tree rather than
399    /// deliver it: an automation query, a screenshot's blind-spot check, a test
400    /// assertion. Unlike [`sync_accessibility`](Self::sync_accessibility) this
401    /// neither caches, nor bumps the AT version, nor records announcements, nor
402    /// advances the framework's live regions — which matters, because a caller
403    /// that consumed an announcer step and then dropped the update would have
404    /// silently eaten a message the user was meant to hear.
405    ///
406    /// It is a full walk every time; `sync_accessibility` is the one with the
407    /// cache.
408    pub fn accessibility_tree_snapshot(&self) -> accesskit::TreeUpdate {
409        self.build_accessibility_tree(false).0
410    }
411
412    /// Advance both announcers one step: retire what is due, and ready the
413    /// next message to enter. See [`crate::announcer`].
414    fn step_announcers(&mut self) {
415        // Both are stepped, not just the busy one: an announcer with nothing
416        // queued and nothing in the tree changes nothing, so this costs
417        // nothing when nobody is announcing.
418        let now = self.animation_clock();
419        let polite = self.announcer_polite.step(now, &mut self.announcer_ids);
420        let assertive = self.announcer_assertive.step(now, &mut self.announcer_ids);
421        if polite || assertive {
422            self.a11y_dirty = true;
423        }
424        self.wake_for_retirement();
425    }
426
427    /// Put the messages that were ready in the tree when the update just
428    /// built `admitted` them, and report whether a message is still waiting,
429    /// which owes another update. See [`crate::announcer`].
430    fn settle_announcers(&mut self, admitted: bool) -> bool {
431        if admitted {
432            let now = self.animation_clock();
433            self.announcer_polite.admit(now);
434            self.announcer_assertive.admit(now);
435            self.wake_for_retirement();
436        }
437        self.announcer_polite.busy() || self.announcer_assertive.busy()
438    }
439
440    /// A message's node leaves the tree at a time, not on a frame: wake the
441    /// loop then, rather than drawing frames until it is due. Not on the
442    /// simulated clock, whose instants the event loop does not wait on; a
443    /// test advances it and syncs.
444    fn wake_for_retirement(&self) {
445        if !self.sim_time_frozen
446            && let Some(at) = [
447                self.announcer_polite.next_retirement(),
448                self.announcer_assertive.next_retirement(),
449            ]
450            .into_iter()
451            .flatten()
452            .min()
453        {
454            self.request_wake_at(at);
455        }
456    }
457
458    /// Dispatch a synthetic AccessKit action to the node identified by
459    /// `node_id` (which may be a *synthetic*, widget-emitted child node —
460    /// e.g. a rich-text `TextRun`). Resolves the owning widget exactly the
461    /// way the platform AT adapter does
462    /// ([`node_id_to_widget_id_maybe`](crate::accessibility::node_id_to_widget_id_maybe)
463    /// then [`widget_for_synthetic`](Self::widget_for_synthetic)), builds a
464    /// [`crate::event::WidgetEvent::AccessAction`],
465    /// and dispatches it through `ops` so actions that open windows /
466    /// dialogs work.
467    ///
468    /// Returns `true` when the action was **consumed** — a handler claimed it,
469    /// focus moved, or the context-menu fallback opened a menu — and `false`
470    /// when nothing acted on it, including when the target node resolves to no
471    /// live widget. Callers are expected to surface that: an action a node
472    /// never handles is a caller error, and reporting it as success (which is
473    /// what "a widget existed at the target" amounted to) leaves an automation
474    /// client chasing timing and coordinates for a UI that was never going to
475    /// move.
476    ///
477    /// This is the in-process equivalent of an OS screen reader invoking an
478    /// action — the channel an [automation](crate::WidgetTree) harness uses
479    /// to *drive* the UI without the OS AT layer.
480    pub fn dispatch_access_action(
481        &mut self,
482        node_id: accesskit::NodeId,
483        action: accesskit::Action,
484        data: Option<accesskit::ActionData>,
485        ops: &mut dyn crate::window::WindowOps,
486    ) -> bool {
487        let target = crate::accessibility::node_id_to_widget_id_maybe(node_id)
488            .or_else(|| self.widget_for_synthetic(node_id));
489        let event = crate::event::WidgetEvent::AccessAction {
490            action,
491            target,
492            target_node: node_id,
493            data,
494        };
495        self.access_action_handled = false;
496        self.dispatch_event_with_ops(event, ops);
497        self.access_action_handled
498    }
499
500    // (helper `is_presentational_container` is a module-level free fn in
501    // `accessibility_emit_impl.rs`)
502
503    /// Look up the owning widget for a synthetic AccessKit `NodeId`
504    /// emitted by `push_text_run_child` / `push_paragraph_child`.
505    /// Used by `handle_accessibility_actions` to route an
506    /// `ActionRequest` targeting a TextRun child back to the
507    /// editor that owns it.
508    pub fn widget_for_synthetic(&self, node_id: accesskit::NodeId) -> Option<WidgetId> {
509        self.synthetic_parent_map.get(&node_id).copied()
510    }
511
512    /// Resolve a tooltip's content node past a deferred host.
513    ///
514    /// A deferred tooltip body answers for itself while un-built (see
515    /// `DeferredSubtree::accessibility`), but once the user has hovered it the
516    /// host has handed its widget value to a real child and has nothing left to
517    /// say. Follow it, or a tooltip's description would be readable exactly
518    /// until the first time it was shown.
519    pub(crate) fn tooltip_content_node(&self, content_id: WidgetId) -> WidgetId {
520        self.arena
521            .get(content_id)
522            .and_then(|node| node.widget.as_any())
523            .and_then(|any| any.downcast_ref::<crate::deferred_subtree::DeferredSubtree>())
524            .and_then(|d| d.materialized_child())
525            .unwrap_or(content_id)
526    }
527
528    /// The text a tooltip would announce, harvested from its (dormant)
529    /// content widget so an anchor can carry it as a static AT description
530    /// while the tooltip is not shown.
531    ///
532    /// All three tiers publish their body through `accessibility()` as the
533    /// node *name* (`TooltipWidget::accessibility` → `set_name(text)`), so
534    /// probing the widget is enough — no parallel copy of the text has to be
535    /// threaded through `attach_tooltip*` and kept in sync. Reads at walk
536    /// time, so a locale change or a `Signal<String>` swap is picked up by the
537    /// same AT re-walk that already tracks them.
538    pub(crate) fn tooltip_access_description(&self, content_id: WidgetId) -> Option<String> {
539        let content_id = self.tooltip_content_node(content_id);
540        let node = self.arena.get(content_id)?;
541        let mut probe = AccessNodeBuilder::for_name_probe(content_id);
542        node.widget.accessibility(&mut probe);
543        if let Some(ov) = node.access_overrides.as_deref() {
544            ov.apply(&mut probe);
545        }
546        probe
547            .name()
548            .map(str::trim)
549            .filter(|name| !name.is_empty())
550            .map(str::to_owned)
551    }
552
553    /// What the accessibility layer would say about the node `id`: its role,
554    /// name, value, states and actions, after the app's `access_*` overrides.
555    ///
556    /// The answer comes from the widget's own accessibility emission whether
557    /// or not the node is in the published AT tree. A **dormant** node (a
558    /// hidden `Switcher` page, a `visible_when(false)` branch) answers with
559    /// its full role and name and is not marked hidden; ask
560    /// [`AccessibilityInfo::published`] whether assistive technology can see
561    /// it, so a walk that reads names does not count invisible widgets.
562    ///
563    /// # Panics
564    /// Panics if `id` is not in the arena (a destroyed widget). Use
565    /// [`try_accessibility_node`](Self::try_accessibility_node) when the id
566    /// may be stale.
567    pub fn accessibility_node(&self, id: WidgetId) -> AccessibilityInfo {
568        let builder = self.build_overridden_builder(id);
569        let role = builder.role();
570        let name = builder.name().map(|s| s.to_string());
571        let actions = builder.actions().to_vec();
572        let mut info = AccessibilityInfo::new(role, name, actions);
573        if let Some(toggled) = builder.toggled() {
574            info = info.with_toggled(toggled);
575        }
576        if let Some(expanded) = builder.expanded() {
577            info = info.with_expanded(expanded);
578        }
579        if let Some(selected) = builder.selected() {
580            info = info.with_selected(selected);
581        }
582        // Mirror the framework gate at `build_accessibility_recursive`:
583        // arena-driven disabled wins unless the override explicitly
584        // asks for `access_disabled(false)`. The override in force is the
585        // one the walker applies, which for a proxy may be a composite's.
586        let disabled = self.access_disabled_override(
587            id,
588            self.live_accessibility_proxy(id).is_some(),
589            &self.composites_standing_behind(id),
590        );
591        let force_clear_disabled = disabled == Some(false);
592        let disabled_arena = !self.arena.is_enabled(id) && !force_clear_disabled;
593        // Override `Some(true)` already called `set_disabled()` inside
594        // the override apply; we only need to surface it here as a
595        // separate signal because `AccessNodeBuilder` doesn't expose a
596        // `is_disabled()` getter on the builder side.
597        let disabled_override = disabled == Some(true);
598        if disabled_arena || disabled_override {
599            info = info.with_disabled(true);
600        }
601        if builder.is_hidden() {
602            info = info.with_hidden(true);
603        }
604        info = info.with_published(self.is_in_published_at_tree(id));
605        if let Some(value) = builder.value() {
606            info = info.with_value(value);
607        }
608        if let Some(v) = builder.numeric_value() {
609            info = info.with_numeric_value(v);
610        }
611        info = info.with_numeric_range(builder.min_numeric_value(), builder.max_numeric_value());
612        info.with_custom_actions(
613            builder
614                .custom_actions()
615                .iter()
616                .map(|a| a.description.clone())
617                .collect(),
618        )
619    }
620
621    /// [`accessibility_node`](Self::accessibility_node) for an id that may no
622    /// longer be in the arena: `None` for a destroyed widget, instead of a
623    /// panic.
624    pub fn try_accessibility_node(&self, id: WidgetId) -> Option<AccessibilityInfo> {
625        self.arena.get(id)?;
626        Some(self.accessibility_node(id))
627    }
628
629    /// Whether the walker reaches `id`: it is active, and no ancestor prunes
630    /// its subtree out of the AT tree (`access_exclude_subtree` drops it;
631    /// `access_merge_subtree` folds it into the ancestor's own node).
632    fn is_in_published_at_tree(&self, id: WidgetId) -> bool {
633        use crate::widget_builder::AccessSubtreeMode;
634        if !self.arena.is_active(id) {
635            return false;
636        }
637        let mut cursor = self.arena.parent(id);
638        while let Some(ancestor) = cursor {
639            match self.arena.get(ancestor) {
640                Some(node) if node.access_subtree != AccessSubtreeMode::Inherit => return false,
641                Some(_) => {}
642                None => break,
643            }
644            cursor = self.arena.parent(ancestor);
645        }
646        true
647    }
648
649    pub fn find_by_role(&self, role: accesskit::Role) -> Option<WidgetId> {
650        self.arena
651            .active_ids_iter()
652            .find(|&id| self.build_overridden_builder(id).role() == role)
653    }
654
655    pub fn find_by_label(&self, label: &str) -> Option<WidgetId> {
656        self.arena
657            .active_ids_iter()
658            .find(|&id| self.build_overridden_builder(id).name() == Some(label))
659    }
660
661    pub fn find_by_action(&self, action: accesskit::Action) -> Option<WidgetId> {
662        self.arena.active_ids_iter().find(|&id| {
663            self.build_overridden_builder(id)
664                .actions()
665                .contains(&action)
666        })
667    }
668
669    /// Get the text content of a widget from its accessibility name.
670    /// Equivalent to the label set via `AccessNodeBuilder::set_name`,
671    /// after override application.
672    pub fn text_content(&self, id: WidgetId) -> Option<String> {
673        self.arena.get(id)?;
674        self.build_overridden_builder(id)
675            .name()
676            .map(|s| s.to_string())
677    }
678
679    /// Get the text value of a widget from its accessibility value.
680    /// Equivalent to the value set via `AccessNodeBuilder::set_value`,
681    /// after override application.
682    pub fn text_value(&self, id: WidgetId) -> Option<String> {
683        self.arena.get(id)?;
684        self.build_overridden_builder(id)
685            .value()
686            .map(|s| s.to_string())
687    }
688}
689
690/// Put the window's HiDPI scale on the root node, so every rectangle in the
691/// tree can stay logical.
692///
693/// AccessKit reads a node's `bounds` in the coordinate space of the nearest
694/// ancestor carrying a `transform`, and expects the *transformed* result to be
695/// in physical pixels relative to the window origin. Teksilo lays out, paints,
696/// hit-tests and drives automation in logical pixels throughout, so every
697/// emitter — this crate's walker, `teksilo-charts`' marks, `teksilo-scene`'s
698/// items and magnets — writes a logical rectangle and none of them knows the
699/// display scale.
700///
701/// One transform on the root reconciles the two. `accesskit_consumer`
702/// accumulates a node's transform with every ancestor's up to the root, so a
703/// single scale here reaches every descendant, **including synthetic children**
704/// (text runs, chart marks, scene items) that hang off a widget with no
705/// transform of its own. It also scales the per-character positions and widths
706/// a text run carries, which live in the same node space and which a
707/// per-rectangle fix-up would silently miss.
708///
709/// The corollary is a rule for every emitter: **never multiply an emitted
710/// rectangle by a scale factor**. Doing so double-scales it here. The walker's
711/// own conformance to that rule is pinned by
712/// `emitted_bounds_stay_logical_at_scale_two`.
713///
714/// The translation term in `accesskit_winit`'s own example is an iOS-only
715/// outer-versus-inner window offset and is zero on every desktop platform;
716/// Teksilo's [`WidgetTree::safe_area`] is a *content* inset and is emphatically
717/// not the same quantity, so it does not belong here.
718pub(crate) fn emit_root_transform(root: &mut accesskit::Node, device_scale_factor: f32) {
719    root.set_transform(accesskit::Affine::scale(device_scale_factor as f64));
720}
721
722/// Whether the rectangles `owner` writes for its synthetic children are in
723/// window space, so the root's scale alone takes them to the screen.
724///
725/// Not when an ancestor is a content transform (a `SceneView`): the children
726/// of such a node, and everything below them, are described in its content
727/// space, which the transform on the boundary child projects.
728///
729/// The walk starts at the owner's parent, not at the owner, on purpose. A
730/// content transform moves a node's *arena* children only: the walker puts
731/// the transform on each of those children and none on the node itself, whose
732/// box stays a viewport in its parent's space. The node's own synthetic
733/// children hang off that untransformed node, so a rect it states relative to
734/// its own origin is in the same space as its box. (A `SceneView`, the one
735/// content transform, gives each item node a transform of its own, which
736/// `snap_text_run_top` declines to touch in any case.)
737pub(super) fn reports_in_window_space(arena: &WidgetArena, owner: WidgetId) -> bool {
738    let mut current = arena.parent(owner);
739    while let Some(id) = current {
740        if arena.get(id).is_some_and(|n| n.content_transform) {
741            return false;
742        }
743        current = arena.parent(id);
744    }
745    true
746}
747
748/// The least distance, in device pixels, between a line's real top and the
749/// pixel row its run reports as its top. Large enough that no rounding in the
750/// two paths a point travels (out through the adapter, back in through the
751/// pointer event) can put it above the line.
752const RUN_TOP_MARGIN: f64 = 0.125;
753
754/// How far into its pixel row the reported top sits, in device pixels, so
755/// that the adapter's `top * scale` rounding a hair low cannot truncate it
756/// to the row above.
757const RUN_TOP_LIFT: f64 = 1.0 / 64.0;
758
759/// Move a text run's reported top down onto the first whole device pixel row
760/// that lies inside its line and inside `owner`, the box of the node the run
761/// belongs to.
762///
763/// A screen reader that clicks on a character clicks at the top-left of the
764/// box the platform reports for it, and makes that point whole pixels first:
765/// NVDA truncates each UIA double with `int()`. A line's top seldom falls on
766/// a device pixel (a 16.94 px line height, an editor 7.6 px down the window,
767/// a 1.25 scale), so the truncated top was the last pixel row of the line
768/// above, and the click landed there. That is what NVDA's braille routing
769/// does when the routed cell is the cursor's own ("activate"), so routing
770/// onto the cursor moved the caret one line up, and from the end of a
771/// wrapped line to the start of the line it was on.
772///
773/// The run's box shrinks at the top by a little over a device pixel at most
774/// (up to `1 + RUN_TOP_MARGIN + RUN_TOP_LIFT`), and stays inside the line:
775/// nothing drawn moves, and the editor's hit test is left alone. The bottom
776/// is untouched, so two lines' boxes no longer meet: each run loses a
777/// different amount, and a gap of up to that much opens between a line's
778/// box and the one below it. Nothing a reader clicks lies in the gap, since
779/// a click goes to a character's top-left corner, which is the row this
780/// picks.
781///
782/// Truncation goes toward zero, so on a monitor above or left of the primary,
783/// where the client origin is negative, the click lands on the row *after*
784/// the chosen one. Any line with two whole rows below the margin holds both,
785/// which is every line a reader routes on. A line its node cuts down to a
786/// sliver with room for one row only (scrolled almost out of an editor) is
787/// still snapped, because no reported top truncates into one row from both
788/// signs. Where the origin is not negative the click stays on the line. Where
789/// it is, the click lands on the next row: the next line when the node cuts
790/// the sliver at its top, and just past the node when it cuts it at its
791/// bottom. Leaving the top where it was would be worse at the top edge,
792/// where it is above the node for either sign and the click reaches some
793/// other widget.
794///
795/// Only for a run whose box the root's scale alone takes to the screen (the
796/// window's client origin is whole pixels, so the window's pixel grid is the
797/// screen's): one under a content transform has a grid this cannot see.
798/// Only for horizontal text, whose character positions run along x: a
799/// vertical run's positions are measured from its top.
800///
801/// The row has to lie inside the owner as well: a click outside the node
802/// never reaches its widget, so a row there is no better than the old top,
803/// and moving the top onto it could take the run off its node altogether. A
804/// label laid out at no size, its text overflowing from its corner, keeps a
805/// run that only touches its node's box; a snapped top a pixel down left the
806/// run outside the node, so nothing a reader reviewed was where the node is.
807/// Where the owner cuts a line off at the top (a line scrolled half out of
808/// an editor), the row is the first one the node shows.
809pub(crate) fn snap_text_run_top(
810    node: &mut accesskit::Node,
811    device_scale_factor: f32,
812    owner: Option<accesskit::Rect>,
813) {
814    if node.role() != accesskit::Role::TextRun || node.transform().is_some() {
815        return;
816    }
817    if matches!(
818        node.text_direction(),
819        Some(accesskit::TextDirection::TopToBottom | accesskit::TextDirection::BottomToTop)
820    ) {
821        return;
822    }
823    let Some(mut rect) = node.bounds() else {
824        return;
825    };
826    // A box with an edge that is not a number is garbage from upstream:
827    // snapping its top would only make a finite part of it look meaningful.
828    if !(rect.y0.is_finite() && rect.y1.is_finite()) {
829        return;
830    }
831    let scale = f64::from(device_scale_factor);
832    if !(scale.is_finite() && scale > 0.0) {
833        return;
834    }
835    let (top, bottom) = match owner {
836        Some(owner) => (rect.y0.max(owner.y0), rect.y1.min(owner.y1)),
837        None => (rect.y0, rect.y1),
838    };
839    let row = (top * scale + RUN_TOP_MARGIN).ceil();
840    if row + 1.0 > bottom * scale {
841        // No whole pixel row inside both: a caret-shaped or unmeasured run,
842        // or one its node does not show, which nobody clicks on.
843        return;
844    }
845    rect.y0 = (row + RUN_TOP_LIFT) / scale;
846    node.set_bounds(rect);
847}
848
849#[cfg(test)]
850pub(crate) mod test_helpers {
851    /// Feed a `TreeUpdate` into `accesskit_consumer::Tree`, which runs the
852    /// same validation that every platform AT (VoiceOver, NVDA, …) runs on
853    /// activation. Panics on duplicate children, dangling relationship
854    /// targets, orphaned nodes, and invalid focus — turning those runtime
855    /// crashes into CI failures.
856    pub(crate) fn assert_a11y_tree_valid(update: &accesskit::TreeUpdate) {
857        accesskit_consumer::Tree::new(update.clone(), false);
858    }
859
860    /// Assert that every NodeId referenced by a relation of any node is
861    /// present in the tree. This is the invariant our post-processing pass
862    /// enforces; having a test here means a future refactor can't silently
863    /// drop the pass and regress it.
864    ///
865    /// `next_on_line` / `previous_on_line` are checked alongside the
866    /// relation lists: a text run linked to a run that never reached the
867    /// tree hangs `accesskit_consumer`'s line walk instead of ending it.
868    pub(crate) fn assert_no_dangling_relationships(update: &accesskit::TreeUpdate) {
869        let emitted: std::collections::HashSet<accesskit::NodeId> =
870            update.nodes.iter().map(|(id, _)| *id).collect();
871        for (parent_id, node) in &update.nodes {
872            for &target in node.controls() {
873                assert!(
874                    emitted.contains(&target),
875                    "node {parent_id:?} has controls() → {target:?} which is absent from the tree"
876                );
877            }
878            for &target in node.described_by() {
879                assert!(
880                    emitted.contains(&target),
881                    "node {parent_id:?} has described_by() → {target:?} which is absent from the tree"
882                );
883            }
884            for &target in node.labelled_by() {
885                assert!(
886                    emitted.contains(&target),
887                    "node {parent_id:?} has labelled_by() → {target:?} which is absent from the tree"
888                );
889            }
890            if let Some(target) = node.next_on_line() {
891                assert!(
892                    emitted.contains(&target),
893                    "node {parent_id:?} has next_on_line() → {target:?} which is absent from the tree"
894                );
895            }
896            if let Some(target) = node.previous_on_line() {
897                assert!(
898                    emitted.contains(&target),
899                    "node {parent_id:?} has previous_on_line() → {target:?} which is absent from the tree"
900                );
901            }
902        }
903    }
904
905    /// Return all NodeIds whose role matches `role`.
906    #[allow(dead_code)]
907    pub(crate) fn nodes_with_role(
908        update: &accesskit::TreeUpdate,
909        role: accesskit::Role,
910    ) -> Vec<accesskit::NodeId> {
911        update
912            .nodes
913            .iter()
914            .filter(|(_, node)| node.role() == role)
915            .map(|(id, _)| *id)
916            .collect()
917    }
918}
919
920#[cfg(test)]
921mod tests {
922    use super::test_helpers::*;
923    use super::*;
924    use crate::test_widgets::{FillWidget, StackWidget};
925
926    /// The framework-owned live-region nodes a `TreeUpdate` carries when
927    /// nothing has been announced: none, since a message's node exists only
928    /// while it is being spoken. Named rather than inlined so a node-count
929    /// assertion says what it is counting. See [`crate::announcer`].
930    const ANNOUNCER_NODES: usize = 0;
931
932    /// What an adapter announces from each update: the live nodes that enter
933    /// the filtered tree with a name, as `accesskit_atspi_common` decides it
934    /// (`adapter.rs:280-349`). A message's node stays in the tree after it is
935    /// spoken, so a node merely present in an update is not a message heard
936    /// in it; only one that arrives is.
937    struct Arrivals {
938        replay: accesskit_consumer::Tree,
939    }
940
941    impl Arrivals {
942        fn attach(update: accesskit::TreeUpdate) -> Self {
943            Self {
944                replay: accesskit_consumer::Tree::new(update, false),
945            }
946        }
947
948        fn feed(&mut self, update: accesskit::TreeUpdate) -> Vec<(String, accesskit::Live)> {
949            struct Handler(Vec<(String, accesskit::Live)>);
950            fn included(node: &accesskit_consumer::NodeRef) -> bool {
951                accesskit_consumer::common_filter(node) == accesskit_consumer::FilterResult::Include
952            }
953            impl Handler {
954                fn entered(&mut self, node: &accesskit_consumer::NodeRef) {
955                    if node.live() != accesskit::Live::Off
956                        && let Some(label) = node.label()
957                    {
958                        self.0.push((label, node.live()));
959                    }
960                }
961            }
962            impl accesskit_consumer::TreeChangeHandler for Handler {
963                fn node_added(&mut self, node: &accesskit_consumer::NodeRef) {
964                    if included(node) {
965                        self.entered(node);
966                    }
967                }
968                fn node_updated(
969                    &mut self,
970                    old: &accesskit_consumer::NodeRef,
971                    new: &accesskit_consumer::NodeRef,
972                ) {
973                    if !included(old) && included(new) {
974                        self.entered(new);
975                    }
976                }
977                fn focus_moved(
978                    &mut self,
979                    _old: Option<&accesskit_consumer::NodeRef>,
980                    _new: Option<&accesskit_consumer::NodeRef>,
981                ) {
982                }
983                fn node_removed(&mut self, _node: &accesskit_consumer::NodeRef) {}
984            }
985            let mut handler = Handler(Vec::new());
986            self.replay.update_and_process_changes(update, &mut handler);
987            handler.0
988        }
989    }
990
991    // The framework's announcer.
992    //
993    // These assert through `accesskit_consumer` directly, on the node the
994    // announcer emits, as well as through the tree's announcement ring. The
995    // ring used to read `value().or(label())` without the filter, so a live
996    // region could pass the in-process check and be silent on all three
997    // platforms, which is how two of this framework's own live regions
998    // shipped mute. The ring now replays the adapters' rules (see
999    // `crate::accessibility::announcements`), and these keep checking the
1000    // one thing the adapters key on: whether the node is in the filtered tree.
1001
1002    /// Is the announcer node one an adapter would see, and what does it say?
1003    ///
1004    /// `accesskit_consumer::Tree` runs the same filter each platform adapter
1005    /// runs. A hidden node is `FilterResult::ExcludeSubtree`, so it is absent
1006    /// from the filtered walk and no adapter will announce it.
1007    fn announced_by_consumer(update: &accesskit::TreeUpdate) -> Vec<(String, accesskit::Live)> {
1008        let consumer = accesskit_consumer::Tree::new(update.clone(), false);
1009        let state = consumer.state();
1010        let mut found = Vec::new();
1011        let mut stack = vec![state.root()];
1012        while let Some(node) = stack.pop() {
1013            if node.live() != accesskit::Live::Off
1014                && let Some(label) = node.label()
1015            {
1016                found.push((label, node.live()));
1017            }
1018            for child in node.filtered_children(&accesskit_consumer::common_filter) {
1019                stack.push(child);
1020            }
1021        }
1022        found
1023    }
1024
1025    /// Every live node an adapter can reach in the filtered walk, by id.
1026    ///
1027    /// Distinct from [`announced_by_consumer`] on purpose: a node that stays in
1028    /// the tree with its label cleared looks "silent" to a label-based check
1029    /// while remaining present. Present-but-unlabelled is exactly what does NOT
1030    /// work: no adapter speaks a name that did not change, so only a node that
1031    /// genuinely leaves and re-enters the filtered tree says the same message
1032    /// twice.
1033    fn live_nodes_in_filtered_tree(update: &accesskit::TreeUpdate) -> Vec<String> {
1034        let consumer = accesskit_consumer::Tree::new(update.clone(), false);
1035        let state = consumer.state();
1036        let mut found = Vec::new();
1037        let mut stack = vec![state.root()];
1038        while let Some(node) = stack.pop() {
1039            if node.live() != accesskit::Live::Off {
1040                found.push(format!("{:?}", node.id()));
1041            }
1042            for child in node.filtered_children(&accesskit_consumer::common_filter) {
1043                stack.push(child);
1044            }
1045        }
1046        found.sort();
1047        found
1048    }
1049
1050    fn tree_with_one_widget() -> WidgetTree {
1051        let mut tree = WidgetTree::new();
1052        tree.add(FillWidget::new().label("content"));
1053        tree.layout(SizeProposal::exact(200.0, 100.0));
1054        tree
1055    }
1056
1057    /// The headline behaviour: `announce` puts a node into the filtered tree
1058    /// once, which is the arrival every adapter announces; the node stays
1059    /// while a reader may still ask it for its role, then leaves for good.
1060    #[test]
1061    fn an_announcement_enters_the_filtered_tree_then_leaves_it() {
1062        let mut tree = tree_with_one_widget();
1063        tree.advance_time(std::time::Duration::ZERO);
1064        // Nothing announced yet: no live region, so a platform adapter sees
1065        // none.
1066        let update = tree.sync_accessibility();
1067        assert_eq!(announced_by_consumer(&update), Vec::new());
1068        assert_eq!(
1069            live_nodes_in_filtered_tree(&update),
1070            Vec::<String>::new(),
1071            "an idle announcer must put nothing in the filtered tree"
1072        );
1073        assert_a11y_tree_valid(&update);
1074        let mut arrivals = Arrivals::attach(update);
1075
1076        tree.announce("Event added");
1077
1078        let exposed = tree.sync_accessibility();
1079        assert_eq!(
1080            announced_by_consumer(&exposed),
1081            vec![("Event added".to_string(), accesskit::Live::Polite)],
1082            "the message must be a label on a live node inside the filtered tree"
1083        );
1084        assert_eq!(
1085            live_nodes_in_filtered_tree(&exposed).len(),
1086            1,
1087            "exactly one announcer node must have entered the filtered tree"
1088        );
1089        assert_a11y_tree_valid(&exposed);
1090        assert_eq!(
1091            arrivals.feed(exposed),
1092            vec![("Event added".to_string(), accesskit::Live::Polite)]
1093        );
1094
1095        // The next frame: the node is still there for a reader that has not
1096        // yet asked it for its role, and nothing arrives again.
1097        tree.advance_time(std::time::Duration::from_millis(16));
1098        let lingering = tree.sync_accessibility();
1099        assert_eq!(live_nodes_in_filtered_tree(&lingering).len(), 1);
1100        assert_eq!(
1101            arrivals.feed(lingering),
1102            Vec::new(),
1103            "a message is said once"
1104        );
1105
1106        // Once its time is over it leaves the filtered walk entirely.
1107        tree.advance_time(crate::announcer::LINGER);
1108        let gone = tree.sync_accessibility();
1109        assert_eq!(
1110            live_nodes_in_filtered_tree(&gone),
1111            Vec::<String>::new(),
1112            "the live node must leave the filtered tree entirely"
1113        );
1114        assert_a11y_tree_valid(&gone);
1115    }
1116
1117    /// The same string twice in a row. The Windows and macOS adapters only
1118    /// announce a label that *changed*, and on AT-SPI a node that has left the
1119    /// tree is defunct for good, so each must be its own new node: two
1120    /// arrivals, from two ids.
1121    #[test]
1122    fn the_same_message_announced_twice_is_exposed_twice() {
1123        let mut tree = tree_with_one_widget();
1124        tree.advance_time(std::time::Duration::ZERO);
1125        let mut arrivals = Arrivals::attach(tree.sync_accessibility());
1126        tree.announce("Saved");
1127        tree.announce("Saved");
1128
1129        let mut heard = Vec::new();
1130        let mut ids = std::collections::HashSet::new();
1131        for _ in 0..6 {
1132            let update = tree.sync_accessibility();
1133            ids.extend(
1134                update
1135                    .nodes
1136                    .iter()
1137                    .filter(|(id, _)| crate::announcer::is_announcer_node(*id))
1138                    .map(|(id, _)| *id),
1139            );
1140            heard.extend(arrivals.feed(update).into_iter().map(|(text, _)| text));
1141            tree.advance_time(std::time::Duration::from_millis(16));
1142        }
1143        assert_eq!(
1144            heard,
1145            ["Saved", "Saved"],
1146            "each announcement is its own arrival"
1147        );
1148        assert_eq!(
1149            ids.len(),
1150            2,
1151            "each announcement is spoken from its own node"
1152        );
1153    }
1154
1155    #[test]
1156    fn an_assertive_announcement_uses_the_assertive_live_setting() {
1157        let mut tree = tree_with_one_widget();
1158        tree.announce_with("Could not save", crate::announcer::Politeness::Assertive);
1159        let update = tree.sync_accessibility();
1160        assert_eq!(
1161            announced_by_consumer(&update),
1162            vec![("Could not save".to_string(), accesskit::Live::Assertive)]
1163        );
1164    }
1165
1166    /// The two levels are independent nodes, so an urgent message does not have
1167    /// to wait behind a polite one.
1168    #[test]
1169    fn the_two_politeness_levels_announce_independently() {
1170        let mut tree = tree_with_one_widget();
1171        tree.announce("Event added");
1172        tree.announce_with("Could not save", crate::announcer::Politeness::Assertive);
1173
1174        let mut spoken = announced_by_consumer(&tree.sync_accessibility());
1175        spoken.sort_by(|a, b| a.0.cmp(&b.0));
1176        assert_eq!(
1177            spoken,
1178            vec![
1179                ("Could not save".to_string(), accesskit::Live::Assertive),
1180                ("Event added".to_string(), accesskit::Live::Polite),
1181            ],
1182            "both levels must be exposed on the same update"
1183        );
1184    }
1185
1186    /// Announcing must wake a tree that has nothing else to redraw, or a
1187    /// message raised by a handler that changed nothing visible would sit
1188    /// unspoken until something unrelated happened.
1189    #[test]
1190    fn announcing_requests_the_syncs_it_needs() {
1191        let mut tree = tree_with_one_widget();
1192        let _ = tree.sync_accessibility();
1193        tree.a11y_update_requested.set(false);
1194        tree.frame_tick_requested.set(false);
1195
1196        tree.announce("Event added");
1197        assert!(
1198            tree.a11y_update_requested.get(),
1199            "an announcement must dirty the accessibility tree"
1200        );
1201        assert!(
1202            tree.frame_requested(),
1203            "an announcement must ask for the frame that carries it"
1204        );
1205
1206        // A second message queued behind the first is owed an update of its
1207        // own, so exposing the first asks again.
1208        tree.announce("3 events");
1209        tree.a11y_update_requested.set(false);
1210        tree.frame_tick_requested.set(false);
1211        let _ = tree.sync_accessibility();
1212        assert!(tree.a11y_update_requested.get());
1213        assert!(tree.frame_requested());
1214
1215        // Once both are in the tree there are no more frames to ask for: the
1216        // loop is woken when the first is due to leave, not every frame.
1217        tree.a11y_update_requested.set(false);
1218        tree.frame_tick_requested.set(false);
1219        let before = std::time::Instant::now();
1220        let _ = tree.sync_accessibility();
1221        assert!(!tree.a11y_update_requested.get());
1222        assert!(!tree.frame_requested());
1223        let wake = tree
1224            .next_timer_deadline()
1225            .expect("a message in the tree asks to be woken when it leaves");
1226        assert!(wake > before + crate::announcer::LINGER / 2);
1227    }
1228
1229    /// Asking for a frame is only half of it: the frame has to come soon. A
1230    /// visible widget ticking once a minute (a calendar row re-reading the
1231    /// clock) used to set the pace of *every* requested frame, so a queue of
1232    /// messages drained one exposure per minute, and whatever was still queued
1233    /// reached the user glued to the front of their next key press.
1234    ///
1235    /// Frames are driven in the order `teksilo-app` runs them (layout, then
1236    /// the accessibility sync, then paint), and the wait before each one is
1237    /// read from the deadline the event loop would sleep to.
1238    #[test]
1239    fn a_throttled_subscriber_does_not_hold_back_an_announcement() {
1240        /// One frame at 60 Hz, with room for rounding.
1241        const NORMAL_FRAME: std::time::Duration = std::time::Duration::from_micros(17_500);
1242        const CLOCK: std::time::Duration = std::time::Duration::from_secs(60);
1243
1244        fn frame(tree: &mut WidgetTree) -> accesskit::TreeUpdate {
1245            tree.layout(SizeProposal::exact(200.0, 100.0));
1246            let update = tree.sync_accessibility();
1247            let _ = tree.render();
1248            update
1249        }
1250        fn wait_for_next_frame(tree: &WidgetTree) -> std::time::Duration {
1251            let deadline = tree
1252                .frame_tick_deadline()
1253                .expect("a visible subscriber keeps a frame scheduled");
1254            let last = tree.last_frame_time.expect("a frame has run");
1255            deadline.saturating_duration_since(last)
1256        }
1257
1258        let mut tree = WidgetTree::new();
1259        let row = tree.add(FillWidget::new().label("content"));
1260        let _clock = tree.subscribe_frame_tick_throttled(row, CLOCK);
1261        let _ = frame(&mut tree);
1262        let _ = frame(&mut tree);
1263        assert!(
1264            wait_for_next_frame(&tree) >= CLOCK - NORMAL_FRAME,
1265            "precondition: with nothing else going on, the clock alone paces the loop"
1266        );
1267
1268        let messages = ["Annulé : l'ajout d'un évènement", "3 évènements"];
1269        for message in messages {
1270            tree.announce(message);
1271        }
1272        // Checked before any frame runs, because not every announcement comes
1273        // from a key press that redraws at once: one raised by a timer or an
1274        // async completion waits for exactly this deadline.
1275        assert!(
1276            wait_for_next_frame(&tree) <= NORMAL_FRAME,
1277            "an announcement must be carried by the next normal frame, not the clock's \
1278             (waited {:?})",
1279            wait_for_next_frame(&tree)
1280        );
1281
1282        let mut exposed = Vec::new();
1283        let mut frames = 0;
1284        let mut arrivals = Arrivals::attach(tree.accessibility_tree_snapshot());
1285        let settled = loop {
1286            let update = frame(&mut tree);
1287            frames += 1;
1288            exposed.extend(arrivals.feed(update).into_iter().map(|(text, _)| text));
1289            let wait = wait_for_next_frame(&tree);
1290            if wait > NORMAL_FRAME {
1291                break wait;
1292            }
1293            assert!(frames < 16, "the announcer never went idle");
1294        };
1295        assert_eq!(
1296            exposed, messages,
1297            "every queued message must be exposed before the loop goes back to sleeping on the \
1298             clock; one left behind is heard only at the next key press"
1299        );
1300        assert!(
1301            settled >= CLOCK - NORMAL_FRAME,
1302            "once the queue is spoken the clock must pace alone again, not free-run at 60 Hz \
1303             (waited {settled:?})"
1304        );
1305    }
1306
1307    /// The in-process ring is what the automation bridge reports, so it has to
1308    /// hear the announcer as the adapters do: once, as the node arrives.
1309    #[test]
1310    fn an_announcement_reaches_the_automation_ring() {
1311        let mut tree = tree_with_one_widget();
1312        let before = tree.announcements_since(0).len() as u64;
1313        tree.announce("Event added");
1314        let _ = tree.sync_accessibility();
1315        let got = tree.announcements_since(before);
1316        assert_eq!(got.len(), 1);
1317        assert_eq!(got[0].text, "Event added");
1318        assert!(!got[0].assertive);
1319    }
1320
1321    /// A screenshot inspects the tree and throws the update away. If it went
1322    /// through `sync_accessibility` it would consume the exposure step and the
1323    /// user would never hear the message.
1324    #[test]
1325    fn a_tree_snapshot_does_not_consume_a_pending_announcement() {
1326        let mut tree = tree_with_one_widget();
1327        tree.announce("Event added");
1328
1329        let snapshot = tree.accessibility_tree_snapshot();
1330        assert_eq!(
1331            announced_by_consumer(&snapshot),
1332            Vec::new(),
1333            "a snapshot must not advance the announcer"
1334        );
1335
1336        let delivered = tree.sync_accessibility();
1337        assert_eq!(
1338            announced_by_consumer(&delivered),
1339            vec![("Event added".to_string(), accesskit::Live::Polite)],
1340            "the message must still be there to deliver"
1341        );
1342    }
1343
1344    /// An empty message is dropped rather than costing an exposure that says
1345    /// nothing.
1346    #[test]
1347    fn an_empty_announcement_is_not_exposed() {
1348        let mut tree = tree_with_one_widget();
1349        let _ = tree.sync_accessibility();
1350        tree.announce("   ");
1351        let update = tree.sync_accessibility();
1352        assert_eq!(announced_by_consumer(&update), Vec::new());
1353    }
1354
1355    #[derive(Debug)]
1356    struct ActionWidget;
1357
1358    impl Widget for ActionWidget {
1359        fn layout_response(
1360            &self,
1361            proposal: SizeProposal,
1362            _ctx: &LayoutContext,
1363        ) -> crate::widget::LayoutResponse {
1364            proposal.resolve(0.0, 0.0).into()
1365        }
1366
1367        fn accessibility(&self, builder: &mut AccessNodeBuilder) {
1368            builder.set_role(accesskit::Role::Button);
1369            builder.set_name("Save");
1370            builder.add_action(accesskit::Action::Click);
1371            builder.add_action(accesskit::Action::Focus);
1372        }
1373    }
1374
1375    #[derive(Debug)]
1376    struct ClickableWidget;
1377
1378    impl Widget for ClickableWidget {
1379        fn layout_response(
1380            &self,
1381            proposal: SizeProposal,
1382            _ctx: &LayoutContext,
1383        ) -> crate::widget::LayoutResponse {
1384            proposal.resolve(0.0, 0.0).into()
1385        }
1386
1387        fn accessibility(&self, builder: &mut crate::accessibility::AccessNodeBuilder) {
1388            builder.set_role(accesskit::Role::Button);
1389            builder.set_name("Click Me");
1390            builder.add_action(accesskit::Action::Click);
1391        }
1392    }
1393
1394    /// A focusable node advertises `Action::Focus` whether or not its widget
1395    /// remembered to. The dispatcher services the action for any focusable
1396    /// node, so deriving the advertisement from the arena flag is what keeps
1397    /// the two in step — see `announce_focusable`.
1398    #[test]
1399    fn a_focusable_node_advertises_focus_without_the_widget_saying_so() {
1400        let mut tree = WidgetTree::new();
1401        // `ClickableWidget` names Click and nothing else.
1402        let id = tree.add(ClickableWidget.focusable(true));
1403        tree.layout(SizeProposal::exact(100.0, 100.0));
1404
1405        let info = tree.accessibility_node(id);
1406        assert!(
1407            info.actions().contains(&accesskit::Action::Focus),
1408            "the arena knows the node is focusable; the AT node must say so"
1409        );
1410
1411        // Advertised means serviceable, not merely announced.
1412        let mut ops = crate::window::NoopWindowOps;
1413        assert!(tree.dispatch_access_action(
1414            crate::accessibility::widget_id_to_node_id(id),
1415            accesskit::Action::Focus,
1416            None,
1417            &mut ops,
1418        ));
1419        assert_eq!(tree.focused(), Some(id));
1420    }
1421
1422    /// A composite that is not itself focusable but publishes one AT node and
1423    /// keeps its keyboard focus on an inner leaf: the shape `ComboBox` and
1424    /// `DateEdit` have, and `SpinBox` had before it published through its
1425    /// field. What marks it as one is that it advertises `Action::Focus` from
1426    /// its own `accessibility()`, which is exactly what those two do.
1427    #[derive(Debug)]
1428    struct CompositeWidget {
1429        child_ids: Vec<WidgetId>,
1430    }
1431
1432    impl Widget for CompositeWidget {
1433        fn layout_response(
1434            &self,
1435            proposal: SizeProposal,
1436            _ctx: &LayoutContext,
1437        ) -> crate::widget::LayoutResponse {
1438            proposal.resolve(0.0, 0.0).into()
1439        }
1440
1441        fn place_children(
1442            &self,
1443            bounds: Rect,
1444            _proposal: SizeProposal,
1445            children: &mut [crate::widget::WidgetPlacement],
1446            _ctx: &LayoutContext,
1447        ) {
1448            for child in children.iter_mut() {
1449                child.origin = bounds.origin();
1450                child.size = bounds.size();
1451            }
1452        }
1453
1454        fn children(&self) -> Vec<WidgetId> {
1455            self.child_ids.clone()
1456        }
1457
1458        fn accessibility(&self, builder: &mut crate::accessibility::AccessNodeBuilder) {
1459            builder.set_role(accesskit::Role::SpinButton);
1460            builder.add_action(accesskit::Action::Focus);
1461        }
1462    }
1463
1464    /// An assistive-tech `Focus` on a composite lands on the node that takes
1465    /// the keys, not on the root that publishes the AT node.
1466    ///
1467    /// `ctx.request_focus` has always walked to the first focusable descendant,
1468    /// precisely because a composite like `TextInput` or `SpinBox` keeps its
1469    /// focus on an inner leaf. The AT path did not, so a screen reader — or the
1470    /// automation `focus_node` tool — parked `self.focused` on a root that
1471    /// accepts no keystrokes. The second assertion is the one that bites:
1472    /// `on_key_preview` fires only on *strict* ancestors of the focused node, so
1473    /// a composite focused on its own root also loses its own stepping keys.
1474    #[test]
1475    fn an_at_focus_on_a_non_focusable_composite_lands_on_its_focusable_leaf() {
1476        let mut tree = WidgetTree::new();
1477        let leaf = tree.add(ClickableWidget.focusable(true));
1478        let root = tree.add(CompositeWidget {
1479            child_ids: vec![leaf],
1480        });
1481        tree.layout(SizeProposal::exact(100.0, 100.0));
1482
1483        let mut ops = crate::window::NoopWindowOps;
1484        assert!(tree.dispatch_access_action(
1485            crate::accessibility::widget_id_to_node_id(root),
1486            accesskit::Action::Focus,
1487            None,
1488            &mut ops,
1489        ));
1490        assert_eq!(
1491            tree.focused(),
1492            Some(leaf),
1493            "focus must reach the focusable leaf, not the composite root"
1494        );
1495    }
1496
1497    /// …and only a composite gets that walk.
1498    ///
1499    /// A plain container — a `Panel`, a `GroupBox`, a landmark, a label — is
1500    /// not focusable and offers no `Focus`, so an assistive technology asking
1501    /// to focus it is asking for something the node never advertised. Walking
1502    /// in anyway moved the keyboard onto the first control inside it, which the
1503    /// technology could have named itself and did not, and then reported
1504    /// success. The honest answer is that the action was not handled.
1505    #[test]
1506    fn an_at_focus_on_a_plain_container_does_not_walk_into_it() {
1507        let mut tree = WidgetTree::new();
1508        let leaf = tree.add(ClickableWidget.focusable(true));
1509        let root = tree.add(StackWidget::new().child(leaf));
1510        tree.layout(SizeProposal::exact(100.0, 100.0));
1511
1512        let mut ops = crate::window::NoopWindowOps;
1513        assert!(
1514            !tree.dispatch_access_action(
1515                crate::accessibility::widget_id_to_node_id(root),
1516                accesskit::Action::Focus,
1517                None,
1518                &mut ops,
1519            ),
1520            "a node that never advertised `Focus` must report the action unhandled"
1521        );
1522        assert_eq!(
1523            tree.focused(),
1524            None,
1525            "focus must stay where it was, not fall into the container's first control"
1526        );
1527    }
1528
1529    /// The walk is a fallback, not a redirect: a focusable node still focuses
1530    /// itself, so every leaf control is untouched by the composite fix.
1531    #[test]
1532    fn an_at_focus_on_a_focusable_node_still_lands_on_that_node() {
1533        let mut tree = WidgetTree::new();
1534        let outer = tree.add(ClickableWidget.focusable(true));
1535        tree.layout(SizeProposal::exact(100.0, 100.0));
1536
1537        let mut ops = crate::window::NoopWindowOps;
1538        assert!(tree.dispatch_access_action(
1539            crate::accessibility::widget_id_to_node_id(outer),
1540            accesskit::Action::Focus,
1541            None,
1542            &mut ops,
1543        ));
1544        assert_eq!(tree.focused(), Some(outer));
1545    }
1546
1547    /// The derivation is a default, not a decree: `access_remove_action` still
1548    /// takes it away, because it is applied before the overrides.
1549    #[test]
1550    fn a_derived_focus_action_is_still_removable_by_an_override() {
1551        let mut tree = WidgetTree::new();
1552        let id = tree.add(
1553            ClickableWidget
1554                .focusable(true)
1555                .access_remove_action(accesskit::Action::Focus),
1556        );
1557        tree.layout(SizeProposal::exact(100.0, 100.0));
1558        assert!(
1559            !tree
1560                .accessibility_node(id)
1561                .actions()
1562                .contains(&accesskit::Action::Focus)
1563        );
1564    }
1565
1566    /// A node nobody can focus must not advertise focus — it would be an
1567    /// action that declines to land.
1568    #[test]
1569    fn a_non_focusable_node_does_not_advertise_focus() {
1570        let mut tree = WidgetTree::new();
1571        let id = tree.add(ClickableWidget);
1572        tree.layout(SizeProposal::exact(100.0, 100.0));
1573        assert!(
1574            !tree
1575                .accessibility_node(id)
1576                .actions()
1577                .contains(&accesskit::Action::Focus)
1578        );
1579    }
1580
1581    #[test]
1582    fn labeled_widget_has_accessibility() {
1583        let mut tree = WidgetTree::new();
1584        let widget = tree.add(FillWidget::new().label("Hello"));
1585        tree.layout(SizeProposal::exact(100.0, 20.0));
1586        let info = tree.accessibility_node(widget);
1587        assert_eq!(info.role(), accesskit::Role::Label);
1588        assert_eq!(info.name(), Some("Hello"));
1589    }
1590
1591    #[test]
1592    fn find_by_label_works() {
1593        let mut tree = WidgetTree::new();
1594        let widget = tree.add(FillWidget::new().label("Save"));
1595        tree.layout(SizeProposal::exact(100.0, 20.0));
1596        assert_eq!(tree.find_by_label("Save"), Some(widget));
1597    }
1598
1599    #[test]
1600    fn label_role_emits_text_as_value_not_label() {
1601        // accesskit contract: a `Role::Label` node carries its text in the
1602        // `value` property, not `label`. Widgets set the accessible name via
1603        // `set_name` (-> `label`); the builder re-serializes it to `value`
1604        // when the role is `Role::Label`, otherwise the Name is empty under
1605        // Windows UIA and stray under macOS AXStaticText. The logical
1606        // introspection name (used by `find_by_label` etc.) is unchanged.
1607        let mut tree = WidgetTree::new();
1608        let widget = tree.add(FillWidget::new().label("Section")); // Role::Label
1609        tree.layout(SizeProposal::exact(100.0, 20.0));
1610
1611        // Logical view still reports the accessible name.
1612        assert_eq!(tree.accessibility_node(widget).name(), Some("Section"));
1613
1614        // The *emitted* node carries the text in `value`, with `label` cleared.
1615        let update = tree.sync_accessibility();
1616        let node = &update
1617            .nodes
1618            .iter()
1619            .find(|(nid, _)| *nid == crate::accessibility::widget_id_to_node_id(widget))
1620            .expect("label node must be present in the tree update")
1621            .1;
1622        assert_eq!(node.role(), accesskit::Role::Label);
1623        assert_eq!(
1624            node.value(),
1625            Some("Section"),
1626            "Role::Label text must be exposed via `value`"
1627        );
1628        assert_eq!(
1629            node.label(),
1630            None,
1631            "Role::Label must not leave text in the `label` property"
1632        );
1633    }
1634
1635    #[test]
1636    fn find_by_role_works() {
1637        let mut tree = WidgetTree::new();
1638        tree.add(FillWidget::new().label("Text"));
1639        tree.layout(SizeProposal::exact(100.0, 20.0));
1640        assert!(tree.find_by_role(accesskit::Role::Label).is_some());
1641    }
1642
1643    #[test]
1644    fn access_hidden_bound_to_signal_toggles_reactively() {
1645        use crate::signal::Signal;
1646        use crate::widget_builder::WidgetBuilder;
1647        let hidden = Signal::new(false);
1648        let mut tree = WidgetTree::new();
1649        let w = tree.add(ClickableWidget.access_hidden(hidden.clone()));
1650        tree.layout(SizeProposal::exact(100.0, 30.0));
1651        assert!(
1652            !tree.accessibility_node(w).is_hidden(),
1653            "node should be visible to AT while the signal is false"
1654        );
1655        hidden.set(true);
1656        // `apply()` reads the prop fresh, so the pulled node reflects the flip.
1657        assert!(
1658            tree.accessibility_node(w).is_hidden(),
1659            "node should hide from AT when the bound signal flips to true"
1660        );
1661        hidden.set(false);
1662        assert!(!tree.accessibility_node(w).is_hidden());
1663    }
1664
1665    /// **A widget with a context menu says so.** The dispatcher already opened
1666    /// the menu for `Action::ShowContextMenu`; nothing advertised the action, and
1667    /// an assistive technology offers what a node advertises.
1668    #[test]
1669    fn a_widget_with_a_context_menu_advertises_the_action() {
1670        let mut tree = WidgetTree::new();
1671        let plain = tree.add(FillWidget::new().label("no menu"));
1672        let with_menu = tree.add(
1673            FillWidget::new()
1674                .label("has menu")
1675                .context_menu(|_pos, _ctx| Some(Box::new(FillWidget::new()) as Box<dyn Widget>)),
1676        );
1677        tree.layout(SizeProposal::exact(100.0, 20.0));
1678
1679        assert!(
1680            tree.accessibility_node(with_menu)
1681                .actions()
1682                .contains(&Action::ShowContextMenu),
1683            "a node owning a context-menu factory must announce it"
1684        );
1685        assert!(
1686            !tree
1687                .accessibility_node(plain)
1688                .actions()
1689                .contains(&Action::ShowContextMenu),
1690            "and a node without one must not"
1691        );
1692    }
1693
1694    /// The action is derived BEFORE the overrides, so an author who explicitly
1695    /// takes it away still has it taken away.
1696    #[test]
1697    fn a_removed_context_menu_action_stays_removed() {
1698        let mut tree = WidgetTree::new();
1699        let id = tree.add(
1700            FillWidget::new()
1701                .label("suppressed")
1702                .context_menu(|_pos, _ctx| Some(Box::new(FillWidget::new()) as Box<dyn Widget>))
1703                .access_remove_action(Action::ShowContextMenu),
1704        );
1705        tree.layout(SizeProposal::exact(100.0, 20.0));
1706        assert!(
1707            !tree
1708                .accessibility_node(id)
1709                .actions()
1710                .contains(&Action::ShowContextMenu)
1711        );
1712    }
1713
1714    /// A descendant of a widget with a menu does **not** advertise it, even
1715    /// though the ancestor walk would open one there. Otherwise every nested box
1716    /// under a row with a menu would offer that menu, and an AT would read a
1717    /// dozen of them.
1718    #[test]
1719    fn a_child_does_not_advertise_its_parents_context_menu() {
1720        let mut tree = WidgetTree::new();
1721        let child = tree.add(FillWidget::new().label("inner"));
1722        let parent = tree.add(
1723            StackWidget::new()
1724                .child(child)
1725                .context_menu(|_pos, _ctx| Some(Box::new(FillWidget::new()) as Box<dyn Widget>)),
1726        );
1727        tree.layout(SizeProposal::exact(100.0, 20.0));
1728
1729        assert!(
1730            tree.accessibility_node(parent)
1731                .actions()
1732                .contains(&Action::ShowContextMenu)
1733        );
1734        assert!(
1735            !tree
1736                .accessibility_node(child)
1737                .actions()
1738                .contains(&Action::ShowContextMenu),
1739            "the menu belongs to the widget that declared it"
1740        );
1741    }
1742
1743    #[test]
1744    fn accessibility_node_collects_actions() {
1745        let mut tree = WidgetTree::new();
1746        let widget = tree.add(ActionWidget);
1747        tree.layout(SizeProposal::exact(100.0, 40.0));
1748
1749        let info = tree.accessibility_node(widget);
1750        assert_eq!(info.role(), accesskit::Role::Button);
1751        assert_eq!(info.name(), Some("Save"));
1752        assert_eq!(info.actions().len(), 2);
1753        assert!(info.actions().contains(&accesskit::Action::Click));
1754        assert!(info.actions().contains(&accesskit::Action::Focus));
1755    }
1756
1757    #[test]
1758    fn sync_accessibility_produces_tree_update() {
1759        let mut tree = WidgetTree::new();
1760        tree.add(FillWidget::new().label("First"));
1761        tree.add(FillWidget::new().label("Second"));
1762        tree.layout(SizeProposal::exact(200.0, 100.0));
1763
1764        let update = tree.sync_accessibility();
1765        // Root and the two widgets; the framework's live regions put nothing
1766        // in the tree while nothing is being said. See `crate::announcer`.
1767        assert_eq!(update.nodes.len(), 3 + ANNOUNCER_NODES);
1768        assert_eq!(update.nodes[0].0, accesskit::NodeId(0));
1769        assert!(update.tree.is_some());
1770        assert_a11y_tree_valid(&update);
1771    }
1772
1773    #[test]
1774    fn root_node_carries_locale_as_language() {
1775        let mut tree = WidgetTree::new();
1776        tree.add(FillWidget::new().label("Bonjour"));
1777
1778        // No locale set yet → no language hint (VoiceOver uses its default).
1779        tree.layout(SizeProposal::exact(200.0, 100.0));
1780        let update = tree.sync_accessibility();
1781        assert_eq!(update.nodes[0].0, accesskit::NodeId(0));
1782        assert_eq!(
1783            update.nodes[0].1.language(),
1784            None,
1785            "no language before a locale is set"
1786        );
1787
1788        // Once the app sets the locale, the root Window node carries it as a
1789        // BCP-47 language tag, which AccessKit propagates to the whole subtree.
1790        tree.set_locale("fr-FR".to_string());
1791        let update = tree.sync_accessibility();
1792        assert_eq!(
1793            update.nodes[0].1.language(),
1794            Some("fr-FR"),
1795            "root node must advertise the active locale as its language"
1796        );
1797    }
1798
1799    #[test]
1800    fn sync_accessibility_excludes_dormant_widgets() {
1801        let mut tree = WidgetTree::new();
1802        tree.add(FillWidget::new().label("Active"));
1803        let dormant = tree.add(FillWidget::new().label("Dormant"));
1804        tree.layout(SizeProposal::exact(200.0, 100.0));
1805
1806        tree.set_dormant(dormant);
1807
1808        let update = tree.sync_accessibility();
1809        assert_eq!(update.nodes.len(), 2 + ANNOUNCER_NODES);
1810        assert_a11y_tree_valid(&update);
1811    }
1812
1813    #[test]
1814    fn try_accessibility_node_is_none_for_a_destroyed_id() {
1815        let mut tree = WidgetTree::new();
1816        let id = tree.add(FillWidget::new().label("Gone soon"));
1817        tree.layout(SizeProposal::exact(200.0, 100.0));
1818        assert!(tree.try_accessibility_node(id).is_some());
1819
1820        tree.destroy_subtree_for_testing(id);
1821        assert!(tree.try_accessibility_node(id).is_none());
1822    }
1823
1824    #[test]
1825    fn a_dormant_node_answers_but_is_not_published() {
1826        let mut tree = WidgetTree::new();
1827        let shown = tree.add(FillWidget::new().label("Shown"));
1828        let parked = tree.add(FillWidget::new().label("Parked"));
1829        tree.layout(SizeProposal::exact(200.0, 100.0));
1830        tree.set_dormant(parked);
1831
1832        let shown = tree.try_accessibility_node(shown).expect("in the arena");
1833        assert!(shown.published());
1834
1835        let parked = tree.try_accessibility_node(parked).expect("in the arena");
1836        assert_eq!(
1837            parked.name(),
1838            Some("Parked"),
1839            "a dormant node still answers"
1840        );
1841        assert!(!parked.is_hidden(), "dormancy is not the hidden flag");
1842        assert!(!parked.published());
1843    }
1844
1845    #[test]
1846    fn a_node_under_an_excluded_ancestor_is_not_published() {
1847        use crate::widget_builder::WidgetBuilder;
1848        let mut tree = WidgetTree::new();
1849        let inner = tree.add(FillWidget::new().label("Inner"));
1850        let outer = tree.add(StackWidget::new().child(inner).access_exclude_subtree());
1851        tree.layout(SizeProposal::exact(200.0, 100.0));
1852
1853        assert!(tree.accessibility_node(outer).published());
1854        assert!(!tree.accessibility_node(inner).published());
1855    }
1856
1857    /// Regression test: a Relayout-only signal flip (no activation
1858    /// change, no role/label/value change, no focus change, no overlay
1859    /// activation) must NOT dirty the AccessKit cache. Previously
1860    /// `layout()` set `a11y_dirty = true` unconditionally on every
1861    /// layout pass, which fired ~60 Hz on any scene with a Pulse /
1862    /// Cycle animation.
1863    #[test]
1864    fn relayout_without_activation_change_does_not_dirty_a11y() {
1865        let mut tree = WidgetTree::new();
1866        let id = tree.add(FillWidget::new().label("Static"));
1867        tree.layout(SizeProposal::exact(200.0, 100.0));
1868
1869        // First sync clears `a11y_dirty` and populates the cache.
1870        let _ = tree.sync_accessibility();
1871        assert!(
1872            !tree.a11y_dirty,
1873            "sync_accessibility must clear the dirty flag"
1874        );
1875
1876        // Simulate a Relayout-binding flip: the widget needs
1877        // re-layout, but its accessibility shape (active set, focus,
1878        // role, label, value) is unchanged.
1879        tree.arena.mark_needs_layout(id);
1880        tree.layout(SizeProposal::exact(200.0, 100.0));
1881
1882        assert!(
1883            !tree.a11y_dirty,
1884            "pure Relayout (no activation / focus / overlay / a11y-binding change) must not dirty the AT cache"
1885        );
1886    }
1887
1888    /// A container that places its single child at a settable offset,
1889    /// without changing its size — the shape of a scroll.
1890    #[derive(Debug)]
1891    struct Mover {
1892        offset: crate::signal::Signal<f32>,
1893        child: WidgetId,
1894    }
1895
1896    impl crate::widget::Widget for Mover {
1897        fn children(&self) -> Vec<WidgetId> {
1898            vec![self.child]
1899        }
1900        fn layout_response(
1901            &self,
1902            proposal: SizeProposal,
1903            _ctx: &crate::widget::LayoutContext,
1904        ) -> crate::widget::LayoutResponse {
1905            proposal.resolve(200.0, 100.0).into()
1906        }
1907        fn place_children(
1908            &self,
1909            bounds: teksilo_canvas::Rect,
1910            _proposal: SizeProposal,
1911            children: &mut [crate::widget::WidgetPlacement],
1912            _ctx: &crate::widget::LayoutContext,
1913        ) {
1914            if let Some(placement) = children.first_mut() {
1915                placement.origin =
1916                    teksilo_canvas::Point::new(bounds.x + self.offset.get(), bounds.y);
1917                placement.size = teksilo_canvas::Size::new(50.0, 20.0);
1918            }
1919        }
1920    }
1921
1922    /// A widget that only moved is re-placed in the cached tree.
1923    ///
1924    /// This is the scroll case, and the reason the AT tree's bounds used to
1925    /// go stale: re-walking on every scroll frame was too expensive to do,
1926    /// so it was not done, and every node in a scrolled view reported the
1927    /// position it had before the scroll.
1928    #[test]
1929    fn translating_a_widget_patches_the_cache_without_a_walk() {
1930        let mut tree = WidgetTree::new();
1931        let inner = tree.add(FillWidget::new().label("Row"));
1932        let offset = crate::signal::Signal::new(0.0f32);
1933        let root = tree.add(Mover {
1934            offset: offset.clone(),
1935            child: inner,
1936        });
1937        tree.layout(SizeProposal::exact(200.0, 100.0));
1938        let update = tree.sync_accessibility();
1939        let walks = tree.a11y_walk_generation();
1940        let before = find_node(&update, inner)
1941            .unwrap()
1942            .bounds()
1943            .expect("the node carries bounds");
1944
1945        // Move the row without resizing it.
1946        offset.set(20.0);
1947        tree.arena.mark_needs_layout(root);
1948        tree.layout(SizeProposal::exact(200.0, 100.0));
1949
1950        let update = tree.sync_accessibility();
1951        assert_eq!(
1952            tree.a11y_walk_generation(),
1953            walks,
1954            "a pure translation must not cost a walk"
1955        );
1956        let after = find_node(&update, inner)
1957            .unwrap()
1958            .bounds()
1959            .expect("the node still carries bounds");
1960        assert!(
1961            (after.x0 - before.x0 - 20.0).abs() < 0.01,
1962            "the cached node must follow the move: {before:?} -> {after:?}"
1963        );
1964    }
1965
1966    #[test]
1967    fn at_version_does_not_bump_for_a_move() {
1968        // `at_version`'s contract is semantic change. A widget that moved
1969        // says the same thing from somewhere else, and a harness waiting on
1970        // the version must not wake for it.
1971        let mut tree = WidgetTree::new();
1972        let inner = tree.add(FillWidget::new().label("Row"));
1973        let offset = crate::signal::Signal::new(0.0f32);
1974        let root = tree.add(Mover {
1975            offset: offset.clone(),
1976            child: inner,
1977        });
1978        tree.layout(SizeProposal::exact(200.0, 100.0));
1979        let _ = tree.sync_accessibility();
1980        let version = tree.at_version().get();
1981
1982        offset.set(20.0);
1983        tree.arena.mark_needs_layout(root);
1984        tree.layout(SizeProposal::exact(200.0, 100.0));
1985        let _ = tree.sync_accessibility();
1986
1987        assert_eq!(tree.at_version().get(), version);
1988    }
1989
1990    /// A delivery owes the adapter nothing once it holds the tree as it is,
1991    /// and something after a move, new content, or the window's focus
1992    /// changing. teksilo-app delivers, and asks for a frame to deliver a
1993    /// held-back update, only while something is owed.
1994    #[test]
1995    fn a_delivery_is_owed_only_for_what_the_adapter_does_not_hold() {
1996        let mut tree = WidgetTree::new();
1997        let inner = tree.add(FillWidget::new().label("Row"));
1998        let offset = crate::signal::Signal::new(0.0f32);
1999        let root = tree.add(Mover {
2000            offset: offset.clone(),
2001            child: inner,
2002        });
2003        tree.layout(SizeProposal::exact(200.0, 100.0));
2004        let _ = tree.sync_accessibility();
2005        assert!(
2006            tree.accessibility_delivery_owed(true),
2007            "nothing delivered yet"
2008        );
2009        let _ = tree.deliver_accessibility(true);
2010        assert!(!tree.accessibility_delivery_owed(true));
2011        assert!(
2012            tree.accessibility_delivery_owed(false),
2013            "the window's focus changes what the adapter keeps"
2014        );
2015
2016        let _ = tree.sync_accessibility();
2017        assert!(
2018            !tree.accessibility_delivery_owed(true),
2019            "an idle frame owes nothing"
2020        );
2021
2022        offset.set(20.0);
2023        tree.arena.mark_needs_layout(root);
2024        tree.layout(SizeProposal::exact(200.0, 100.0));
2025        let _ = tree.sync_accessibility();
2026        assert!(tree.accessibility_delivery_owed(true), "a move is owed");
2027        let _ = tree.deliver_accessibility(true);
2028        assert!(!tree.accessibility_delivery_owed(true));
2029
2030        // A walk that finds the same tree owes nothing either.
2031        let walks = tree.a11y_walk_generation();
2032        tree.set_theme(crate::presets::intui::dark());
2033        let _ = tree.sync_accessibility();
2034        assert!(
2035            tree.a11y_walk_generation() > walks,
2036            "precondition: it walked"
2037        );
2038        assert!(!tree.accessibility_delivery_owed(true));
2039
2040        tree.add(FillWidget::new().label("New"));
2041        tree.layout(SizeProposal::exact(200.0, 100.0));
2042        let _ = tree.sync_accessibility();
2043        assert!(
2044            tree.accessibility_delivery_owed(true),
2045            "new content is owed"
2046        );
2047        let _ = tree.deliver_accessibility(true);
2048        assert!(!tree.accessibility_delivery_owed(true));
2049    }
2050
2051    /// A frame that changes nothing the adapter holds (a caret blink) hands
2052    /// it an update with no node, which it applies without comparing a
2053    /// node. Handing it the whole tree again cost a copy and a node by node
2054    /// comparison on every frame an assistive technology was attached.
2055    #[test]
2056    fn an_idle_frame_hands_the_adapter_no_node() {
2057        struct Count(usize);
2058        impl accesskit_consumer::TreeChangeHandler for Count {
2059            fn node_added(&mut self, _: &accesskit_consumer::NodeRef) {
2060                self.0 += 1;
2061            }
2062            fn node_updated(
2063                &mut self,
2064                _: &accesskit_consumer::NodeRef,
2065                _: &accesskit_consumer::NodeRef,
2066            ) {
2067                self.0 += 1;
2068            }
2069            fn focus_moved(
2070                &mut self,
2071                _: Option<&accesskit_consumer::NodeRef>,
2072                _: Option<&accesskit_consumer::NodeRef>,
2073            ) {
2074                self.0 += 1;
2075            }
2076            fn node_removed(&mut self, _: &accesskit_consumer::NodeRef) {
2077                self.0 += 1;
2078            }
2079        }
2080
2081        let mut tree = WidgetTree::new();
2082        let inner = tree.add(FillWidget::new().label("Row").focusable());
2083        let offset = crate::signal::Signal::new(0.0f32);
2084        let root = tree.add(Mover {
2085            offset: offset.clone(),
2086            child: inner,
2087        });
2088        tree.focus(inner);
2089        tree.layout(SizeProposal::exact(200.0, 100.0));
2090        let _ = tree.sync_accessibility();
2091        let delivered = tree.deliver_accessibility(true);
2092        let mut adapter = accesskit_consumer::Tree::new(delivered.clone(), true);
2093
2094        tree.layout(SizeProposal::exact(200.0, 100.0));
2095        let _ = tree.sync_accessibility();
2096        let idle = tree.accessibility_unchanged(true);
2097        assert!(
2098            idle.nodes.is_empty(),
2099            "an idle frame handed the adapter {} nodes to compare",
2100            idle.nodes.len()
2101        );
2102        assert_eq!(idle.tree, None);
2103        assert_eq!(idle.tree_id, delivered.tree_id);
2104        assert_eq!(idle.focus, delivered.focus, "the focus it holds");
2105        let mut changes = Count(0);
2106        adapter.update_and_process_changes(idle, &mut changes);
2107        assert_eq!(changes.0, 0, "the adapter heard a change");
2108
2109        // Something owed is still handed out.
2110        offset.set(20.0);
2111        tree.arena.mark_needs_layout(root);
2112        tree.layout(SizeProposal::exact(200.0, 100.0));
2113        let _ = tree.sync_accessibility();
2114        let moved = tree.accessibility_unchanged(true);
2115        assert!(!moved.nodes.is_empty(), "a move is delivered");
2116        assert!(!tree.accessibility_delivery_owed(true));
2117    }
2118
2119    #[test]
2120    fn resizing_a_widget_dirties_the_accessibility_tree() {
2121        // A wrapped label re-wraps at a new width, so its lines — and
2122        // therefore its text runs — are a different set, not the same set
2123        // somewhere else. Only a full walk can produce them.
2124        let mut tree = WidgetTree::new();
2125        let id = tree.add(FillWidget::new().label("Static"));
2126        tree.layout(SizeProposal::exact(200.0, 100.0));
2127        let _ = tree.sync_accessibility();
2128        let walks = tree.a11y_walk_generation();
2129
2130        tree.layout(SizeProposal::exact(300.0, 100.0));
2131        let _ = tree.sync_accessibility();
2132
2133        assert!(
2134            tree.a11y_walk_generation() > walks,
2135            "a resize must be walked, not patched"
2136        );
2137        let _ = id;
2138    }
2139
2140    #[test]
2141    fn changing_the_theme_dirties_the_accessibility_tree() {
2142        // Typography is re-resolved, so every label re-shapes — inside
2143        // bounds the layout pass may leave untouched, which records no
2144        // resize and would otherwise leave the runs describing the old
2145        // metrics.
2146        let mut tree = WidgetTree::new();
2147        tree.add(FillWidget::new().label("Static"));
2148        tree.layout(SizeProposal::exact(200.0, 100.0));
2149        let _ = tree.sync_accessibility();
2150        let walks = tree.a11y_walk_generation();
2151
2152        tree.set_theme(crate::presets::intui::dark());
2153        let _ = tree.sync_accessibility();
2154
2155        assert!(tree.a11y_walk_generation() > walks);
2156    }
2157
2158    #[test]
2159    fn changing_the_text_scale_dirties_the_accessibility_tree() {
2160        let mut tree = WidgetTree::new();
2161        tree.add(FillWidget::new().label("Static"));
2162        tree.layout(SizeProposal::exact(200.0, 100.0));
2163        let _ = tree.sync_accessibility();
2164        let walks = tree.a11y_walk_generation();
2165
2166        tree.set_user_text_scale(1.5);
2167        let _ = tree.sync_accessibility();
2168
2169        assert!(tree.a11y_walk_generation() > walks);
2170    }
2171
2172    #[test]
2173    fn a_moved_node_absent_from_the_cache_is_skipped() {
2174        // A layout stack the walker prunes, an excluded or merged
2175        // descendant: the id moved, but the tree never had a node for it.
2176        // Inventing one would put a node in the update with no parent,
2177        // which panics the consumer's tree builder.
2178        use crate::widget_builder::WidgetBuilder;
2179        let mut tree = WidgetTree::new();
2180        let hidden = tree.add(FillWidget::new().label("Inner"));
2181        let offset = crate::signal::Signal::new(0.0f32);
2182        let root = tree.add(
2183            Mover {
2184                offset: offset.clone(),
2185                child: hidden,
2186            }
2187            .access_exclude_subtree(),
2188        );
2189        tree.layout(SizeProposal::exact(200.0, 100.0));
2190        let update = tree.sync_accessibility();
2191        assert!(
2192            find_node(&update, hidden).is_none(),
2193            "the excluded descendant must be absent for this test to mean anything"
2194        );
2195
2196        offset.set(20.0);
2197        tree.arena.mark_needs_layout(root);
2198        tree.layout(SizeProposal::exact(200.0, 100.0));
2199        let update = tree.sync_accessibility();
2200
2201        assert!(find_node(&update, hidden).is_none());
2202        assert_no_dangling_relationships(&update);
2203    }
2204
2205    #[test]
2206    fn focus_on_a_node_the_walk_did_not_emit_resolves_to_an_emitted_ancestor() {
2207        // Alive is not the same as emitted. A focusable widget inside an
2208        // `access_exclude_subtree` is active — dispatch reaches it, it takes
2209        // keystrokes — and the walk emits nothing for it. Naming it as the
2210        // update's focus is not a lost link but a broken tree: the consumer
2211        // resolves `focus` against the nodes it was handed, and every platform
2212        // adapter is built on that consumer.
2213        //
2214        // The same shape reaches here from `SceneView`, which publishes fewer
2215        // cards than it keeps alive, so this is the general guarantee behind
2216        // that specific one.
2217        use crate::widget_builder::WidgetBuilder;
2218        let mut tree = WidgetTree::new();
2219        let inner = tree.add(ClickableWidget);
2220        let outer = tree.add(
2221            Mover {
2222                offset: crate::signal::Signal::new(0.0f32),
2223                child: inner,
2224            }
2225            .access_exclude_subtree(),
2226        );
2227        tree.layout(SizeProposal::exact(200.0, 100.0));
2228        tree.focus(inner);
2229
2230        let update = tree.sync_accessibility();
2231        assert!(
2232            find_node(&update, inner).is_none(),
2233            "precondition: the excluded descendant emits nothing"
2234        );
2235        let emitted: std::collections::HashSet<_> =
2236            update.nodes.iter().map(|(id, _)| *id).collect();
2237        assert!(
2238            emitted.contains(&update.focus),
2239            "the published focus must be a node in the published tree"
2240        );
2241        assert_eq!(
2242            update.focus,
2243            crate::accessibility::widget_id_to_node_id(outer),
2244            "…and specifically the nearest ancestor that did emit"
2245        );
2246        // The check every platform adapter runs on activation.
2247        accesskit_consumer::Tree::new(update, false);
2248    }
2249
2250    /// Companion to the regression above: the dormant→active path
2251    /// MUST still dirty the AT cache, because the accessibility walk
2252    /// skips dormant nodes.
2253    #[test]
2254    fn activation_transition_does_dirty_a11y() {
2255        let mut tree = WidgetTree::new();
2256        let id = tree.add(FillWidget::new().label("Toggle"));
2257        tree.layout(SizeProposal::exact(200.0, 100.0));
2258        let _ = tree.sync_accessibility();
2259        assert!(!tree.a11y_dirty);
2260
2261        tree.set_dormant(id);
2262        tree.layout(SizeProposal::exact(200.0, 100.0));
2263        assert!(
2264            tree.a11y_dirty,
2265            "active→dormant transition must dirty the AT cache so the dormant node is removed"
2266        );
2267    }
2268
2269    #[test]
2270    fn sync_accessibility_includes_focus() {
2271        let mut tree = WidgetTree::new();
2272        let widget = tree.add(FillWidget::new().focusable().label("Focused"));
2273        tree.layout(SizeProposal::exact(100.0, 50.0));
2274        tree.focus(widget);
2275
2276        let update = tree.sync_accessibility();
2277        let expected_focus = crate::accessibility::widget_id_to_node_id(widget);
2278        assert_eq!(update.focus, expected_focus);
2279        assert_a11y_tree_valid(&update);
2280    }
2281
2282    #[test]
2283    fn sync_accessibility_parent_child_relationship() {
2284        let mut tree = WidgetTree::new();
2285        let child = tree.add(FillWidget::new().label("Child"));
2286        // A label keeps the parent from being collapsed as a presentational
2287        // container, so this exercises the parent→child push (not pruning).
2288        let parent = tree.add(
2289            StackWidget::new()
2290                .child(child)
2291                .access_label_literal("Parent"),
2292        );
2293        tree.layout(SizeProposal::exact(100.0, 50.0));
2294
2295        let update = tree.sync_accessibility();
2296        assert_eq!(update.nodes.len(), 3 + ANNOUNCER_NODES);
2297
2298        let parent_node_id = crate::accessibility::widget_id_to_node_id(parent);
2299        let parent_node = update
2300            .nodes
2301            .iter()
2302            .find(|(id, _)| *id == parent_node_id)
2303            .map(|(_, node)| node)
2304            .unwrap();
2305
2306        let child_node_id = crate::accessibility::widget_id_to_node_id(child);
2307        assert!(parent_node.children().contains(&child_node_id));
2308        assert_a11y_tree_valid(&update);
2309    }
2310
2311    #[test]
2312    fn presentational_containers_collapse_and_promote_children() {
2313        // A chain of bare presentational containers (StackWidget → empty
2314        // `Role::Unknown`) wrapping a labeled leaf collapses entirely: the
2315        // leaf is promoted to its nearest semantic ancestor, and no empty
2316        // grouping node remains (VoiceOver would announce one as "group").
2317        // A *labeled* container is semantic and survives.
2318        let mut tree = WidgetTree::new();
2319        let leaf = tree.add(FillWidget::new().label("Leaf")); // Role::Label
2320        let inner = tree.add(StackWidget::new().child(leaf)); // bare → pruned
2321        let outer = tree.add(StackWidget::new().child(inner)); // bare → pruned
2322        let labeled = tree.add(
2323            StackWidget::new()
2324                .child(outer)
2325                .access_label_literal("Group"),
2326        );
2327        tree.layout(SizeProposal::exact(100.0, 50.0));
2328        let update = tree.sync_accessibility();
2329
2330        assert!(find_node(&update, inner).is_none(), "bare inner pruned");
2331        assert!(find_node(&update, outer).is_none(), "bare outer pruned");
2332
2333        let labeled_node = find_node(&update, labeled).expect("labeled group survives");
2334        let leaf_nid = crate::accessibility::widget_id_to_node_id(leaf);
2335        assert!(
2336            labeled_node.children().contains(&leaf_nid),
2337            "leaf promoted past both bare containers to the labeled ancestor"
2338        );
2339        assert!(find_node(&update, leaf).is_some(), "labeled leaf kept");
2340        assert_a11y_tree_valid(&update);
2341    }
2342
2343    #[test]
2344    fn find_by_action_finds_clickable() {
2345        let mut tree = WidgetTree::new();
2346        let widget = tree.add(ClickableWidget);
2347        tree.layout(SizeProposal::exact(100.0, 40.0));
2348
2349        assert_eq!(tree.find_by_action(accesskit::Action::Click), Some(widget));
2350        assert_eq!(tree.find_by_action(accesskit::Action::Focus), None);
2351    }
2352
2353    #[test]
2354    fn text_content_returns_accessibility_name() {
2355        let mut tree = WidgetTree::new();
2356        let widget = tree.add(FillWidget::new().label("Hello World"));
2357        tree.layout(SizeProposal::exact(100.0, 50.0));
2358
2359        assert_eq!(tree.text_content(widget), Some("Hello World".to_string()));
2360    }
2361
2362    #[test]
2363    fn text_content_returns_none_without_label() {
2364        let mut tree = WidgetTree::new();
2365        let widget = tree.add(FillWidget::new());
2366        tree.layout(SizeProposal::exact(100.0, 50.0));
2367
2368        assert_eq!(tree.text_content(widget), None);
2369    }
2370
2371    #[test]
2372    fn descendant_of_disabled_ancestor_reports_disabled() {
2373        use crate::signal::Signal;
2374
2375        let mut tree = WidgetTree::new();
2376        let child = tree.add(FillWidget::new().label("Child"));
2377        let parent = tree.add(StackWidget::new().child(child));
2378        tree.enabled_when(parent, Signal::new(false));
2379        tree.layout(SizeProposal::exact(100.0, 50.0));
2380
2381        assert!(
2382            tree.accessibility_node(child).is_disabled(),
2383            "descendant should report disabled when ancestor is disabled"
2384        );
2385    }
2386
2387    #[test]
2388    fn text_value_returns_accessibility_value() {
2389        #[derive(Debug)]
2390        struct ValueWidget;
2391
2392        impl Widget for ValueWidget {
2393            fn layout_response(
2394                &self,
2395                proposal: SizeProposal,
2396                _ctx: &LayoutContext,
2397            ) -> crate::widget::LayoutResponse {
2398                proposal.resolve(0.0, 0.0).into()
2399            }
2400
2401            fn accessibility(&self, builder: &mut crate::accessibility::AccessNodeBuilder) {
2402                builder.set_role(accesskit::Role::Slider);
2403                builder.set_name("Volume");
2404                builder.set_value("75%");
2405            }
2406        }
2407
2408        let mut tree = WidgetTree::new();
2409        let widget = tree.add(ValueWidget);
2410        tree.layout(SizeProposal::exact(100.0, 40.0));
2411
2412        assert_eq!(tree.text_value(widget), Some("75%".to_string()));
2413        assert_eq!(tree.text_content(widget), Some("Volume".to_string()));
2414    }
2415
2416    #[test]
2417    fn sync_accessibility_has_no_duplicate_children() {
2418        // Regression test for the AccessKit "duplicate child" crash (VoiceOver/NVDA).
2419        // assert_a11y_tree_valid already catches this via the consumer, but the
2420        // manual check here provides a more actionable failure message.
2421        let mut tree = WidgetTree::new();
2422        let grandchild = tree.add(FillWidget::new().label("Grandchild"));
2423        let child_a = tree.add(StackWidget::new().child(grandchild));
2424        let child_b = tree.add(FillWidget::new().label("Sibling"));
2425        let _root = tree.add(StackWidget::new().child(child_a).child(child_b));
2426        tree.layout(SizeProposal::exact(200.0, 100.0));
2427
2428        let update = tree.sync_accessibility();
2429
2430        let mut all_children: std::collections::HashMap<accesskit::NodeId, accesskit::NodeId> =
2431            std::collections::HashMap::new();
2432        for (parent_id, node) in &update.nodes {
2433            for &child_id in node.children() {
2434                let prev = all_children.insert(child_id, *parent_id);
2435                assert!(
2436                    prev.is_none(),
2437                    "duplicate child NodeId {child_id:?}: claimed by both {prev:?} and {parent_id:?}"
2438                );
2439            }
2440        }
2441        assert_a11y_tree_valid(&update);
2442    }
2443
2444    /// A container whose AT children are set after the ids exist, and which
2445    /// may claim descendants through the redirect hook, attaching them under
2446    /// a synthetic group of its own.
2447    #[derive(Debug)]
2448    struct AtParent {
2449        kids: Vec<WidgetId>,
2450        at: std::rc::Rc<std::cell::RefCell<Option<Vec<WidgetId>>>>,
2451        claims: std::rc::Rc<std::cell::RefCell<Vec<WidgetId>>>,
2452    }
2453
2454    impl AtParent {
2455        fn new(kids: Vec<WidgetId>) -> Self {
2456            Self {
2457                kids,
2458                at: Default::default(),
2459                claims: Default::default(),
2460            }
2461        }
2462    }
2463
2464    impl crate::widget::Widget for AtParent {
2465        fn layout_response(
2466            &self,
2467            proposal: SizeProposal,
2468            _ctx: &crate::widget::LayoutContext,
2469        ) -> crate::widget::LayoutResponse {
2470            proposal.resolve(10.0, 10.0).into()
2471        }
2472        fn children(&self) -> Vec<WidgetId> {
2473            self.kids.clone()
2474        }
2475        fn accessibility_children(&self) -> Option<Vec<WidgetId>> {
2476            self.at.borrow().clone()
2477        }
2478        fn accessibility(&self, builder: &mut crate::accessibility::AccessNodeBuilder) {
2479            builder.set_role(accesskit::Role::Group);
2480            let claims = self.claims.borrow();
2481            if claims.is_empty() {
2482                return;
2483            }
2484            let group =
2485                builder.push_scene_child(1, crate::accessibility::SyntheticKind::SceneGroup, |b| {
2486                    b.set_role(accesskit::Role::Group)
2487                });
2488            for &c in claims.iter() {
2489                builder
2490                    .attach_scene_child_under(group, crate::accessibility::widget_id_to_node_id(c));
2491            }
2492        }
2493        fn wants_descendant_redirects(&self) -> bool {
2494            !self.claims.borrow().is_empty()
2495        }
2496        fn a11y_redirect_descendant(
2497            &self,
2498            _self_id: WidgetId,
2499            descendant: WidgetId,
2500        ) -> Option<accesskit::NodeId> {
2501            self.claims.borrow().contains(&descendant).then(|| {
2502                crate::accessibility::synthetic_node_id(
2503                    _self_id,
2504                    1,
2505                    crate::accessibility::SyntheticKind::SceneGroup,
2506                )
2507            })
2508        }
2509    }
2510
2511    fn node_count(update: &accesskit::TreeUpdate, id: WidgetId) -> usize {
2512        let nid = crate::accessibility::widget_id_to_node_id(id);
2513        update.nodes.iter().filter(|(n, _)| *n == nid).count()
2514    }
2515
2516    fn parents_of(update: &accesskit::TreeUpdate, id: WidgetId) -> Vec<accesskit::NodeId> {
2517        let nid = crate::accessibility::widget_id_to_node_id(id);
2518        update
2519            .nodes
2520            .iter()
2521            .filter(|(_, n)| n.children().contains(&nid))
2522            .map(|(p, _)| *p)
2523            .collect()
2524    }
2525
2526    /// `accessibility_children` may name a descendant that is not a child:
2527    /// it is emitted once, under the widget that named it.
2528    #[test]
2529    fn an_accessibility_child_may_be_a_deeper_descendant() {
2530        let mut tree = WidgetTree::new();
2531        let c = tree.add(FillWidget::new().label("C"));
2532        let a_widget = AtParent::new(vec![c]);
2533        // A hands C to its ancestor: it lists no AT child of its own.
2534        *a_widget.at.borrow_mut() = Some(Vec::new());
2535        let a = tree.add(a_widget);
2536        let b = tree.add(FillWidget::new().label("B"));
2537        let r_widget = AtParent::new(vec![a, b]);
2538        let r_at = r_widget.at.clone();
2539        let r = tree.add(r_widget);
2540        *r_at.borrow_mut() = Some(vec![a, b, c]);
2541        tree.layout(SizeProposal::exact(200.0, 100.0));
2542        let update = tree.sync_accessibility();
2543        assert_eq!(node_count(&update, c), 1);
2544        assert_eq!(
2545            parents_of(&update, c),
2546            vec![crate::accessibility::widget_id_to_node_id(r)]
2547        );
2548        assert_a11y_tree_valid(&update);
2549    }
2550
2551    /// A descendant claimed twice is built once, whether the second claim
2552    /// names it again or a redirect claimed it first.
2553    #[test]
2554    fn a_child_claimed_twice_is_built_once() {
2555        // The same id twice in one list.
2556        let mut tree = WidgetTree::new();
2557        let a = tree.add(FillWidget::new().label("A"));
2558        let r_widget = AtParent::new(vec![a]);
2559        *r_widget.at.borrow_mut() = Some(vec![a, a]);
2560        tree.add(r_widget);
2561        tree.layout(SizeProposal::exact(200.0, 100.0));
2562        let update = tree.sync_accessibility();
2563        assert_eq!(node_count(&update, a), 1);
2564        assert_a11y_tree_valid(&update);
2565
2566        // A redirect claims C (from R's own list) and C's arena parent A
2567        // lists it too: the walk reaches C twice.
2568        let mut tree = WidgetTree::new();
2569        let c = tree.add(FillWidget::new().label("C"));
2570        let a = tree.add(AtParent::new(vec![c]));
2571        let r_widget = AtParent::new(vec![a]);
2572        let r_at = r_widget.at.clone();
2573        r_widget.claims.borrow_mut().push(c);
2574        tree.add(r_widget);
2575        *r_at.borrow_mut() = Some(vec![c, a]);
2576        tree.layout(SizeProposal::exact(200.0, 100.0));
2577        let update = tree.sync_accessibility();
2578        assert_eq!(node_count(&update, c), 1, "C is built once");
2579        assert_eq!(parents_of(&update, c).len(), 1, "and has one parent");
2580        assert_a11y_tree_valid(&update);
2581    }
2582
2583    #[test]
2584    fn no_dangling_relationships_in_basic_tree() {
2585        let mut tree = WidgetTree::new();
2586        let child = tree.add(FillWidget::new().label("Child"));
2587        let _parent = tree.add(StackWidget::new().child(child));
2588        tree.layout(SizeProposal::exact(100.0, 50.0));
2589
2590        let update = tree.sync_accessibility();
2591        assert_no_dangling_relationships(&update);
2592        assert_a11y_tree_valid(&update);
2593    }
2594
2595    // ── Builder-level accessibility override tests ───────────────────
2596    //
2597    // Tests for `WidgetBuilder::access_*` methods.
2598
2599    use crate::widget_builder::WidgetBuilder;
2600    use accesskit::{Action, AriaCurrent, HasPopup, Live, Orientation, Role};
2601
2602    /// Find a node in a TreeUpdate by WidgetId.
2603    fn find_node(update: &accesskit::TreeUpdate, id: WidgetId) -> Option<&accesskit::Node> {
2604        let nid = crate::accessibility::widget_id_to_node_id(id);
2605        update
2606            .nodes
2607            .iter()
2608            .find(|(node_id, _)| *node_id == nid)
2609            .map(|(_, n)| n)
2610    }
2611
2612    /// A widget that calls set_hidden() unconditionally — used to test
2613    /// `access_hidden(false)` clears widget-emitted hidden state.
2614    #[derive(Debug)]
2615    struct AlwaysHiddenWidget;
2616    impl Widget for AlwaysHiddenWidget {
2617        fn layout_response(
2618            &self,
2619            proposal: SizeProposal,
2620            _ctx: &LayoutContext,
2621        ) -> crate::widget::LayoutResponse {
2622            proposal.resolve(0.0, 0.0).into()
2623        }
2624        fn accessibility(&self, builder: &mut AccessNodeBuilder) {
2625            builder.set_role(Role::GenericContainer);
2626            builder.set_hidden();
2627        }
2628    }
2629
2630    // Test 1
2631    #[test]
2632    fn access_label_replaces_widget_label() {
2633        let mut tree = WidgetTree::new();
2634        let id = tree.add(ClickableWidget.access_label_literal("Publish"));
2635        tree.layout(SizeProposal::exact(100.0, 40.0));
2636        assert_eq!(tree.accessibility_node(id).name(), Some("Publish"));
2637    }
2638
2639    // Test 2
2640    #[test]
2641    fn access_description_appears_on_bare_widget() {
2642        let mut tree = WidgetTree::new();
2643        let id = tree.add(FillWidget::new().access_description_literal("Decorative"));
2644        tree.layout(SizeProposal::exact(50.0, 50.0));
2645        let update = tree.sync_accessibility();
2646        let node = find_node(&update, id).expect("node present");
2647        assert_eq!(node.description(), Some("Decorative"));
2648    }
2649
2650    // Test 3
2651    #[test]
2652    fn access_value_replaces_widget_value() {
2653        #[derive(Debug)]
2654        struct SliderWidget;
2655        impl Widget for SliderWidget {
2656            fn layout_response(
2657                &self,
2658                proposal: SizeProposal,
2659                _ctx: &LayoutContext,
2660            ) -> crate::widget::LayoutResponse {
2661                proposal.resolve(0.0, 0.0).into()
2662            }
2663            fn accessibility(&self, builder: &mut AccessNodeBuilder) {
2664                builder.set_role(Role::Slider);
2665                builder.set_value("50");
2666            }
2667        }
2668        let mut tree = WidgetTree::new();
2669        let id = tree.add(SliderWidget.access_value_literal("Custom"));
2670        tree.layout(SizeProposal::exact(100.0, 40.0));
2671        assert_eq!(tree.text_value(id), Some("Custom".to_string()));
2672    }
2673
2674    // Test 4
2675    #[test]
2676    fn access_role_overrides_widget_role() {
2677        let mut tree = WidgetTree::new();
2678        let id = tree.add(FillWidget::new().label("H").access_role(Role::Heading));
2679        tree.layout(SizeProposal::exact(100.0, 40.0));
2680        assert_eq!(tree.accessibility_node(id).role(), Role::Heading);
2681    }
2682
2683    #[test]
2684    fn an_unshown_tooltip_still_describes_its_anchor_for_screen_readers() {
2685        // The pass used to wire `described_by` only while the tooltip's
2686        // overlay was live. A plain tooltip is never auto-shown on focus, and
2687        // a dormant content node is excluded from the emitted tree (so it
2688        // cannot be a relation target anyway) — which left the whole plain
2689        // tier with no screen-reader path at all. With no hover, the anchor
2690        // must still carry the text as a static description.
2691        let mut tree = WidgetTree::new();
2692        let anchor = tree.add(FillWidget::new().label("Save"));
2693        let tip = tree.add(FillWidget::new().label("Save the file"));
2694        tree.layout(SizeProposal::exact(200.0, 100.0));
2695        tree.attach_tooltip(anchor, tip, std::time::Duration::from_millis(500));
2696
2697        assert!(tree.active_overlays().is_empty(), "not hovered, not shown");
2698        let update = tree.sync_accessibility();
2699        let node = find_node(&update, anchor).expect("anchor node present");
2700        assert_eq!(
2701            node.description(),
2702            Some("Save the file"),
2703            "the anchor must describe itself with its tooltip text while unshown"
2704        );
2705    }
2706
2707    #[test]
2708    fn a_shown_tooltip_switches_the_anchor_to_the_described_by_relation() {
2709        // Once the content is genuinely in the tree, the richer relation is
2710        // used instead of the copied string. The relation reaches no screen
2711        // reader through AccessKit, so the tree writes the content's text back
2712        // into the description (`accessibility_description_impl`): showing the
2713        // tooltip used to take the only description a reader had away.
2714        let mut tree = WidgetTree::new();
2715        let anchor = tree.add(FillWidget::new().label("Save"));
2716        let tip = tree.add(FillWidget::new().label("Save the file"));
2717        tree.layout(SizeProposal::exact(200.0, 100.0));
2718        tree.attach_tooltip(anchor, tip, std::time::Duration::from_millis(100));
2719
2720        tree.pointer_move(tree.bounds(anchor).center());
2721        tree.advance_time(std::time::Duration::from_millis(150));
2722        assert_eq!(tree.active_overlays().len(), 1, "tooltip shown");
2723
2724        let update = tree.sync_accessibility();
2725        let node = find_node(&update, anchor).expect("anchor node present");
2726        assert!(
2727            !node.described_by().is_empty(),
2728            "a shown tooltip is wired as a described_by relation"
2729        );
2730        assert_eq!(
2731            node.description(),
2732            Some("Save the file"),
2733            "and the anchor still describes itself with the tooltip's text"
2734        );
2735    }
2736
2737    // Test 5
2738    #[test]
2739    fn access_hint_alias_writes_description_field() {
2740        let mut tree = WidgetTree::new();
2741        let id = tree.add(FillWidget::new().access_hint_literal("Tip"));
2742        tree.layout(SizeProposal::exact(50.0, 50.0));
2743        let update = tree.sync_accessibility();
2744        let node = find_node(&update, id).unwrap();
2745        assert_eq!(node.description(), Some("Tip"));
2746    }
2747
2748    // Test 6
2749    #[test]
2750    fn access_identifier_writes_author_id() {
2751        let mut tree = WidgetTree::new();
2752        let id = tree.add(FillWidget::new().access_identifier("save-button"));
2753        tree.layout(SizeProposal::exact(50.0, 50.0));
2754        let update = tree.sync_accessibility();
2755        let node = find_node(&update, id).unwrap();
2756        assert_eq!(node.author_id(), Some("save-button"));
2757    }
2758
2759    // Test 7a — literal shortcut variant
2760    #[test]
2761    fn access_shortcut_literal_set() {
2762        let mut tree = WidgetTree::new();
2763        let id = tree.add(ClickableWidget.access_shortcut_literal("Ctrl+S"));
2764        tree.layout(SizeProposal::exact(50.0, 50.0));
2765        let update = tree.sync_accessibility();
2766        let node = find_node(&update, id).unwrap();
2767        assert_eq!(node.keyboard_shortcut(), Some("Ctrl+S"));
2768    }
2769
2770    // Test 7b — id-based shortcut resolves through ShortcutRegistry,
2771    // including auto-refresh on rebind.
2772    #[test]
2773    fn access_shortcut_id_resolves_and_tracks_rebinds() {
2774        use crate::event::Key;
2775        use crate::shortcut::{KeyStroke, Shortcut};
2776
2777        let mut tree = WidgetTree::new();
2778        tree.shortcut_registry_mut().register(
2779            Shortcut::new("app.save")
2780                .name("Save")
2781                .primary(KeyStroke::command(Key::S))
2782                .build(),
2783        );
2784        let id = tree.add(ClickableWidget.access_shortcut_id("app.save"));
2785        tree.layout(SizeProposal::exact(50.0, 50.0));
2786
2787        // The chord is declared on the primary accelerator, so the announced
2788        // name is the key the user is actually looking at: ⌘ on macOS, Ctrl
2789        // everywhere else (see `Modifiers`' `Display`).
2790        let accel = if cfg!(target_os = "macos") {
2791            "Cmd"
2792        } else {
2793            "Ctrl"
2794        };
2795
2796        // Initial registration: AT announces the default keystroke.
2797        let update = tree.sync_accessibility();
2798        let node = find_node(&update, id).unwrap();
2799        assert_eq!(
2800            node.keyboard_shortcut(),
2801            Some(format!("{accel}+S").as_str())
2802        );
2803
2804        // Simulate a user rebind: the AT announcement should track it.
2805        tree.shortcut_registry_mut()
2806            .rebind_primary("app.save", Some(KeyStroke::command(Key::Q)));
2807        let update = tree.sync_accessibility();
2808        let node = find_node(&update, id).unwrap();
2809        assert_eq!(
2810            node.keyboard_shortcut(),
2811            Some(format!("{accel}+Q").as_str())
2812        );
2813    }
2814
2815    // Test 7c — silently omits the announcement when the id has no
2816    // registered default. Same fallback behavior as `MenuItem::for_shortcut`.
2817    #[test]
2818    fn access_shortcut_id_unknown_id_omits_announcement() {
2819        let mut tree = WidgetTree::new();
2820        let id = tree.add(ClickableWidget.access_shortcut_id("never.registered"));
2821        tree.layout(SizeProposal::exact(50.0, 50.0));
2822        let update = tree.sync_accessibility();
2823        let node = find_node(&update, id).unwrap();
2824        assert_eq!(node.keyboard_shortcut(), None);
2825    }
2826
2827    // Test 8
2828    #[test]
2829    fn access_hidden_true_hides_widget() {
2830        let mut tree = WidgetTree::new();
2831        let id = tree.add(ClickableWidget.access_hidden(true));
2832        tree.layout(SizeProposal::exact(50.0, 50.0));
2833        assert!(tree.accessibility_node(id).is_hidden());
2834    }
2835
2836    // Test 9
2837    #[test]
2838    fn access_hidden_false_clears_widget_set_hidden() {
2839        let mut tree = WidgetTree::new();
2840        let id = tree.add(AlwaysHiddenWidget.access_hidden(false));
2841        tree.layout(SizeProposal::exact(50.0, 50.0));
2842        assert!(
2843            !tree.accessibility_node(id).is_hidden(),
2844            "access_hidden(false) should clear widget-emitted hidden"
2845        );
2846    }
2847
2848    // Test 10
2849    #[test]
2850    fn access_disabled_true_marks_disabled() {
2851        let mut tree = WidgetTree::new();
2852        let id = tree.add(FillWidget::new().access_disabled(true));
2853        tree.layout(SizeProposal::exact(50.0, 50.0));
2854        assert!(tree.accessibility_node(id).is_disabled());
2855    }
2856
2857    // Test 11
2858    #[test]
2859    fn access_disabled_false_clears_arena_driven_disabled() {
2860        use crate::signal::Signal;
2861        let mut tree = WidgetTree::new();
2862        let id = tree.add(FillWidget::new().label("X").access_disabled(false));
2863        tree.enabled_when(id, Signal::new(false));
2864        tree.layout(SizeProposal::exact(50.0, 50.0));
2865        assert!(
2866            !tree.accessibility_node(id).is_disabled(),
2867            "access_disabled(false) should clear even arena-driven disabled"
2868        );
2869    }
2870
2871    // Test 12
2872    #[test]
2873    fn access_controls_appends() {
2874        let mut tree = WidgetTree::new();
2875        let target = tree.add(FillWidget::new().label("Target"));
2876        let controller = tree.add(
2877            FillWidget::new()
2878                .label("Controller")
2879                .access_controls(target),
2880        );
2881        tree.layout(SizeProposal::exact(100.0, 50.0));
2882        let update = tree.sync_accessibility();
2883        let node = find_node(&update, controller).unwrap();
2884        let target_nid = crate::accessibility::widget_id_to_node_id(target);
2885        assert!(
2886            node.controls().contains(&target_nid),
2887            "controls list should contain the target NodeId"
2888        );
2889    }
2890
2891    // Test 13
2892    #[test]
2893    fn access_described_by_appends() {
2894        let mut tree = WidgetTree::new();
2895        let other = tree.add(FillWidget::new().label("Desc"));
2896        let id = tree.add(FillWidget::new().label("Main").access_described_by(other));
2897        tree.layout(SizeProposal::exact(100.0, 50.0));
2898        let update = tree.sync_accessibility();
2899        let node = find_node(&update, id).unwrap();
2900        let other_nid = crate::accessibility::widget_id_to_node_id(other);
2901        assert!(node.described_by().contains(&other_nid));
2902    }
2903
2904    // Test 14
2905    #[test]
2906    fn access_labelled_by_appends() {
2907        let mut tree = WidgetTree::new();
2908        let other = tree.add(FillWidget::new().label("Lbl"));
2909        let id = tree.add(FillWidget::new().label("Main").access_labelled_by(other));
2910        tree.layout(SizeProposal::exact(100.0, 50.0));
2911        let update = tree.sync_accessibility();
2912        let node = find_node(&update, id).unwrap();
2913        let other_nid = crate::accessibility::widget_id_to_node_id(other);
2914        assert!(node.labelled_by().contains(&other_nid));
2915    }
2916
2917    /// A control's built-in default name gives way to the label it is linked
2918    /// to, an application's name wins over both, and a default stays when
2919    /// the link names nothing. Each name as the consumer resolves it.
2920    #[test]
2921    fn a_labelled_by_relation_replaces_a_default_name_only() {
2922        use crate::accessibility::{AccessNodeBuilder, widget_id_to_node_id};
2923
2924        #[derive(Debug)]
2925        struct DefaultNamed;
2926        impl crate::widget::Widget for DefaultNamed {
2927            fn layout_response(
2928                &self,
2929                proposal: SizeProposal,
2930                _ctx: &crate::widget::LayoutContext,
2931            ) -> crate::widget::LayoutResponse {
2932                proposal.resolve(40.0, 20.0).into()
2933            }
2934            fn accessibility(&self, builder: &mut AccessNodeBuilder) {
2935                builder.set_role(accesskit::Role::TextInput);
2936                builder.set_default_name("Date");
2937            }
2938        }
2939        #[derive(Debug)]
2940        struct Named;
2941        impl crate::widget::Widget for Named {
2942            fn layout_response(
2943                &self,
2944                proposal: SizeProposal,
2945                _ctx: &crate::widget::LayoutContext,
2946            ) -> crate::widget::LayoutResponse {
2947                proposal.resolve(40.0, 20.0).into()
2948            }
2949            fn accessibility(&self, builder: &mut AccessNodeBuilder) {
2950                builder.set_role(accesskit::Role::TextInput);
2951                builder.set_name("Main");
2952            }
2953        }
2954
2955        let mut tree = WidgetTree::new();
2956        let row = tree.add(FillWidget::new().label("Birthday"));
2957        let nameless = tree.add(FillWidget::new());
2958        let linked = tree.add(DefaultNamed.access_labelled_by(row));
2959        let given = tree.add(
2960            DefaultNamed
2961                .access_labelled_by(row)
2962                .access_label_literal("Given"),
2963        );
2964        let unlinked = tree.add(DefaultNamed);
2965        let linked_to_nothing = tree.add(DefaultNamed.access_labelled_by(nameless));
2966        let named = tree.add(Named.access_labelled_by(row));
2967        tree.layout(SizeProposal::exact(400.0, 300.0));
2968        let update = tree.sync_accessibility();
2969
2970        let consumer = accesskit_consumer::Tree::new(update.clone(), false);
2971        let state = consumer.state();
2972        let name = |id| {
2973            state
2974                .node_by_tree_local_id(widget_id_to_node_id(id), accesskit::TreeId::ROOT)
2975                .and_then(|n| n.label())
2976        };
2977        assert_eq!(name(linked).as_deref(), Some("Birthday"));
2978        assert_eq!(name(given).as_deref(), Some("Given"));
2979        assert_eq!(name(unlinked).as_deref(), Some("Date"));
2980        assert_eq!(name(linked_to_nothing).as_deref(), Some("Date"));
2981        // A name set with `set_name` is not a default.
2982        assert_eq!(name(named).as_deref(), Some("Main"));
2983    }
2984
2985    /// The structural twin of the relation strip above, and a harder failure:
2986    /// a relation that dangles loses a link, a *child* that dangles breaks the
2987    /// walk, because everything under an unresolvable child is unreachable.
2988    ///
2989    /// The walker cannot produce one on its own — it pushes a child only after
2990    /// `arena.is_active`. `AccessNodeBuilder::attach_scene_child_under` can,
2991    /// and by design: it is called from a widget's `accessibility()`, which
2992    /// sees no arena, to graft another widget's node under a synthetic parent
2993    /// of its own. `teksilo-scene` does exactly that for a heavyweight card
2994    /// with a declared logical parent, and a card parked by a viewport cull is
2995    /// absent from the update.
2996    #[test]
2997    fn a_child_attached_to_a_node_that_never_reached_the_tree_is_stripped() {
2998        use crate::accessibility::{AccessNodeBuilder, SyntheticKind, widget_id_to_node_id};
2999
3000        /// Grafts its one child under a synthetic group of its own, the way a
3001        /// `SceneView` grafts a card under an `A11yGroup`.
3002        #[derive(Debug)]
3003        struct Grafter {
3004            child: std::cell::Cell<Option<WidgetId>>,
3005        }
3006
3007        impl Widget for Grafter {
3008            fn build(&mut self, ctx: &mut crate::build_context::BuildContext) -> Vec<WidgetId> {
3009                let child = ctx.add(FillWidget::new().label("Card"));
3010                self.child.set(Some(child));
3011                vec![child]
3012            }
3013            fn layout_response(
3014                &self,
3015                _p: SizeProposal,
3016                _c: &crate::widget::LayoutContext,
3017            ) -> crate::widget::LayoutResponse {
3018                teksilo_canvas::Size::new(100.0, 100.0).into()
3019            }
3020            fn children(&self) -> Vec<WidgetId> {
3021                self.child.get().into_iter().collect()
3022            }
3023            fn wants_descendant_redirects(&self) -> bool {
3024                true
3025            }
3026            fn a11y_redirect_descendant(
3027                &self,
3028                _self_id: WidgetId,
3029                descendant: WidgetId,
3030            ) -> Option<accesskit::NodeId> {
3031                // Claimed unconditionally — exactly as the scene's hook does,
3032                // which cannot see dormancy either.
3033                (self.child.get() == Some(descendant)).then(|| widget_id_to_node_id(descendant))
3034            }
3035            fn accessibility(&self, builder: &mut AccessNodeBuilder) {
3036                builder.set_role(accesskit::Role::Pane);
3037                let group =
3038                    builder.push_scene_child_under(None, 7, SyntheticKind::SceneGroup, |c| {
3039                        c.set_role(accesskit::Role::GenericContainer);
3040                        c.set_name("Group".to_string());
3041                    });
3042                if let Some(child) = self.child.get() {
3043                    builder.attach_scene_child_under(group, widget_id_to_node_id(child));
3044                }
3045            }
3046        }
3047
3048        let mut tree = WidgetTree::new();
3049        let grafter = tree.add(Grafter {
3050            child: std::cell::Cell::new(None),
3051        });
3052        tree.layout(SizeProposal::exact(200.0, 200.0));
3053        let child = tree.children(grafter)[0];
3054
3055        // While the child is live the graft is a real edge.
3056        let update = tree.sync_accessibility();
3057        let child_nid = widget_id_to_node_id(child);
3058        assert!(
3059            update.nodes.iter().any(|(id, _)| *id == child_nid),
3060            "precondition: the grafted child is in the tree"
3061        );
3062        assert!(
3063            update
3064                .nodes
3065                .iter()
3066                .any(|(_, n)| n.children().contains(&child_nid)),
3067            "precondition: something names it as a child"
3068        );
3069        assert_a11y_tree_valid(&update);
3070
3071        // Park it. The widget's `accessibility()` still grafts it — it has no
3072        // way to know — so the strip is the only thing between here and a
3073        // published tree naming a node that is not in it.
3074        tree.set_dormant(child);
3075        let update = tree.sync_accessibility();
3076        assert!(
3077            !update.nodes.iter().any(|(id, _)| *id == child_nid),
3078            "a dormant widget emits no node"
3079        );
3080        let emitted: std::collections::HashSet<accesskit::NodeId> =
3081            update.nodes.iter().map(|(id, _)| *id).collect();
3082        for (parent, node) in &update.nodes {
3083            for c in node.children() {
3084                assert!(
3085                    emitted.contains(c),
3086                    "node {parent:?} names child {c:?}, absent from the tree"
3087                );
3088            }
3089        }
3090        // And the consumer — the same validation every platform AT runs on
3091        // activation — accepts it.
3092        assert_a11y_tree_valid(&update);
3093    }
3094
3095    #[test]
3096    fn a_labelled_by_target_that_went_dormant_is_stripped() {
3097        // A dangling `labelled_by` is worse than a dangling `controls`: the
3098        // consumer builds the node's *name* by concatenating its targets'
3099        // values, and walks the relation to do it. `accesskit_consumer`'s
3100        // relation iterator unwraps the lookup, so a target that never
3101        // reached the tree panics the walk rather than merely losing a link.
3102        let mut tree = WidgetTree::new();
3103        let title = tree.add(FillWidget::new().label("Preferences"));
3104        let dialog = tree.add(FillWidget::new().access_labelled_by(title));
3105        tree.layout(SizeProposal::exact(200.0, 100.0));
3106
3107        let update = tree.sync_accessibility();
3108        assert!(
3109            !find_node(&update, dialog).unwrap().labelled_by().is_empty(),
3110            "the relation is live while the target is in the tree"
3111        );
3112
3113        tree.set_dormant(title);
3114        let update = tree.sync_accessibility();
3115        assert!(
3116            find_node(&update, dialog).unwrap().labelled_by().is_empty(),
3117            "a target absent from the tree must not survive in the relation"
3118        );
3119        assert_no_dangling_relationships(&update);
3120    }
3121
3122    #[test]
3123    fn re_registering_a_labelled_by_relation_does_not_duplicate_it() {
3124        // A composite that names itself from its own content registers the
3125        // relation from `build()`, which runs again on every rebuild. Appending
3126        // blindly would concatenate the title into the name once per rebuild.
3127        let mut tree = WidgetTree::new();
3128        let title = tree.add(FillWidget::new().label("Name"));
3129        let field = tree.add(FillWidget::new());
3130        tree.layout(SizeProposal::exact(200.0, 100.0));
3131
3132        for _ in 0..3 {
3133            tree.push_access_labelled_by(field, title);
3134        }
3135        let update = tree.sync_accessibility();
3136        assert_eq!(
3137            find_node(&update, field).unwrap().labelled_by().len(),
3138            1,
3139            "the same target registered repeatedly is one relation"
3140        );
3141    }
3142
3143    #[test]
3144    fn re_registering_a_described_by_relation_does_not_duplicate_it() {
3145        let mut tree = WidgetTree::new();
3146        let hint = tree.add(FillWidget::new().label("Must be unique"));
3147        let field = tree.add(FillWidget::new());
3148        tree.layout(SizeProposal::exact(200.0, 100.0));
3149
3150        for _ in 0..3 {
3151            tree.push_access_described_by(field, hint);
3152        }
3153        let update = tree.sync_accessibility();
3154        assert_eq!(
3155            find_node(&update, field).unwrap().described_by().len(),
3156            1,
3157            "the same target registered repeatedly is one relation"
3158        );
3159    }
3160
3161    // Test 15
3162    #[test]
3163    fn access_live_assertive_set() {
3164        let mut tree = WidgetTree::new();
3165        let id = tree.add(FillWidget::new().access_live(Live::Assertive));
3166        tree.layout(SizeProposal::exact(50.0, 50.0));
3167        let update = tree.sync_accessibility();
3168        let node = find_node(&update, id).unwrap();
3169        assert_eq!(node.live(), Some(Live::Assertive));
3170    }
3171
3172    // Test 16
3173    #[test]
3174    fn access_aria_current_set() {
3175        let mut tree = WidgetTree::new();
3176        let id = tree.add(FillWidget::new().access_current(AriaCurrent::Page));
3177        tree.layout(SizeProposal::exact(50.0, 50.0));
3178        let update = tree.sync_accessibility();
3179        let node = find_node(&update, id).unwrap();
3180        assert_eq!(node.aria_current(), Some(AriaCurrent::Page));
3181    }
3182
3183    // Test 17
3184    #[test]
3185    fn access_has_popup_set() {
3186        let mut tree = WidgetTree::new();
3187        let id = tree.add(ClickableWidget.access_has_popup(HasPopup::Menu));
3188        tree.layout(SizeProposal::exact(50.0, 50.0));
3189        let update = tree.sync_accessibility();
3190        let node = find_node(&update, id).unwrap();
3191        assert_eq!(node.has_popup(), Some(HasPopup::Menu));
3192    }
3193
3194    // Test 18
3195    #[test]
3196    fn access_orientation_set() {
3197        let mut tree = WidgetTree::new();
3198        let id = tree.add(FillWidget::new().access_orientation(Orientation::Vertical));
3199        tree.layout(SizeProposal::exact(50.0, 50.0));
3200        let update = tree.sync_accessibility();
3201        let node = find_node(&update, id).unwrap();
3202        assert_eq!(node.orientation(), Some(Orientation::Vertical));
3203    }
3204
3205    // Test 19
3206    #[test]
3207    fn access_numeric_value_and_range() {
3208        let mut tree = WidgetTree::new();
3209        let id = tree.add(
3210            FillWidget::new()
3211                .access_role(Role::Slider)
3212                .access_numeric_value(50.0)
3213                .access_numeric_range(0.0, 100.0)
3214                .access_numeric_step(5.0),
3215        );
3216        tree.layout(SizeProposal::exact(50.0, 50.0));
3217        let update = tree.sync_accessibility();
3218        let node = find_node(&update, id).unwrap();
3219        assert_eq!(node.numeric_value(), Some(50.0));
3220        assert_eq!(node.min_numeric_value(), Some(0.0));
3221        assert_eq!(node.max_numeric_value(), Some(100.0));
3222        assert_eq!(node.numeric_value_step(), Some(5.0));
3223    }
3224
3225    // Test 20
3226    #[test]
3227    fn access_action_advertises_and_routes() {
3228        use crate::signal::Signal;
3229        let flag = Signal::new(false);
3230        let flag_for_cb = flag.clone();
3231        let mut tree = WidgetTree::new();
3232        let id = tree.add(
3233            FillWidget::new()
3234                .access_action(Action::ShowContextMenu, move |_ctx| flag_for_cb.set(true)),
3235        );
3236        tree.layout(SizeProposal::exact(50.0, 50.0));
3237        let info = tree.accessibility_node(id);
3238        assert!(info.actions().contains(&Action::ShowContextMenu));
3239        tree.dispatch_event(crate::event::WidgetEvent::AccessAction {
3240            action: Action::ShowContextMenu,
3241            target: Some(id),
3242            target_node: crate::accessibility::widget_id_to_node_id(id),
3243            data: None,
3244        });
3245        assert!(flag.get(), "callback should have been invoked");
3246    }
3247
3248    // Test 21
3249    #[test]
3250    fn access_two_actions_both_route() {
3251        use crate::signal::Signal;
3252        let click = Signal::new(false);
3253        let increment = Signal::new(false);
3254        let click_cb = click.clone();
3255        let inc_cb = increment.clone();
3256        let mut tree = WidgetTree::new();
3257        let id = tree.add(
3258            FillWidget::new()
3259                .access_action(Action::ShowContextMenu, move |_| click_cb.set(true))
3260                .access_action(Action::Increment, move |_| inc_cb.set(true)),
3261        );
3262        tree.layout(SizeProposal::exact(50.0, 50.0));
3263        tree.dispatch_event(crate::event::WidgetEvent::AccessAction {
3264            action: Action::ShowContextMenu,
3265            target: Some(id),
3266            target_node: crate::accessibility::widget_id_to_node_id(id),
3267            data: None,
3268        });
3269        assert!(click.get() && !increment.get(), "only first action fired");
3270        tree.dispatch_event(crate::event::WidgetEvent::AccessAction {
3271            action: Action::Increment,
3272            target: Some(id),
3273            target_node: crate::accessibility::widget_id_to_node_id(id),
3274            data: None,
3275        });
3276        assert!(
3277            click.get() && increment.get(),
3278            "both actions fired exactly once each"
3279        );
3280    }
3281
3282    // Test 22
3283    #[test]
3284    fn access_remove_action_suppresses_widget_action() {
3285        let mut tree = WidgetTree::new();
3286        let id = tree.add(ActionWidget.access_remove_action(Action::Click));
3287        tree.layout(SizeProposal::exact(50.0, 50.0));
3288        let info = tree.accessibility_node(id);
3289        assert!(!info.actions().contains(&Action::Click));
3290        assert!(info.actions().contains(&Action::Focus));
3291    }
3292
3293    // Test 23
3294    #[test]
3295    fn access_custom_action_uses_localized_label() {
3296        let mut tree = WidgetTree::new();
3297        let id = tree.add(FillWidget::new().access_custom_action_literal("Reply", |_ctx| {}));
3298        tree.layout(SizeProposal::exact(50.0, 50.0));
3299        let update = tree.sync_accessibility();
3300        let node = find_node(&update, id).unwrap();
3301        let actions = node.custom_actions();
3302        assert_eq!(actions.len(), 1);
3303        assert_eq!(actions[0].id, 0);
3304        assert_eq!(actions[0].description.as_str(), "Reply");
3305    }
3306
3307    // Test 24
3308    #[test]
3309    fn access_custom_action_routes_by_index() {
3310        use crate::signal::Signal;
3311        let first = Signal::new(false);
3312        let second = Signal::new(false);
3313        let f = first.clone();
3314        let s = second.clone();
3315        let mut tree = WidgetTree::new();
3316        let id = tree.add(
3317            FillWidget::new()
3318                .access_custom_action_literal("First", move |_| f.set(true))
3319                .access_custom_action_literal("Second", move |_| s.set(true)),
3320        );
3321        tree.layout(SizeProposal::exact(50.0, 50.0));
3322        tree.dispatch_event(crate::event::WidgetEvent::AccessAction {
3323            action: Action::CustomAction,
3324            target: Some(id),
3325            target_node: crate::accessibility::widget_id_to_node_id(id),
3326            data: Some(accesskit::ActionData::CustomAction(1)),
3327        });
3328        assert!(!first.get(), "first should not fire");
3329        assert!(second.get(), "second should fire (index 1)");
3330    }
3331
3332    /// A widget that offers a custom action of its own, under an id clear of
3333    /// the low numbers the override entries take by position.
3334    #[derive(Debug)]
3335    struct OwnCustomActionWidget;
3336
3337    const OWN_CUSTOM_ACTION_ID: i32 = 1000;
3338
3339    impl Widget for OwnCustomActionWidget {
3340        fn layout_response(
3341            &self,
3342            proposal: SizeProposal,
3343            _ctx: &LayoutContext,
3344        ) -> crate::widget::LayoutResponse {
3345            proposal.resolve(0.0, 0.0).into()
3346        }
3347
3348        fn accessibility(&self, builder: &mut AccessNodeBuilder) {
3349            builder.set_role(accesskit::Role::Slider);
3350            builder.set_custom_actions(vec![accesskit::CustomAction {
3351                id: OWN_CUSTOM_ACTION_ID,
3352                description: "Reset to default".to_owned(),
3353            }]);
3354        }
3355    }
3356
3357    // Test 24b
3358    #[test]
3359    fn access_custom_action_appends_to_the_widgets_own() {
3360        use crate::signal::Signal;
3361        let own = Signal::new(0_u32);
3362        let added = Signal::new(0_u32);
3363        let own_sink = own.clone();
3364        let added_sink = added.clone();
3365        let mut tree = WidgetTree::new();
3366        let id = tree.add(
3367            OwnCustomActionWidget
3368                .access_custom_action_literal("Pin", move |_| added_sink.set(added_sink.get() + 1))
3369                .on_access_action_request(move |action, _node, data, _ctx| {
3370                    if action == Action::CustomAction
3371                        && data == Some(accesskit::ActionData::CustomAction(OWN_CUSTOM_ACTION_ID))
3372                    {
3373                        own_sink.set(own_sink.get() + 1);
3374                        return crate::event::EventResponse::Handled;
3375                    }
3376                    crate::event::EventResponse::Ignored
3377                }),
3378        );
3379        tree.layout(SizeProposal::exact(50.0, 50.0));
3380        let update = tree.sync_accessibility();
3381        let node = find_node(&update, id).unwrap();
3382        let offered: Vec<(i32, &str)> = node
3383            .custom_actions()
3384            .iter()
3385            .map(|a| (a.id, a.description.as_str()))
3386            .collect();
3387        assert_eq!(
3388            offered,
3389            vec![(OWN_CUSTOM_ACTION_ID, "Reset to default"), (0, "Pin")],
3390            "the application's action joins the widget's rather than replacing it",
3391        );
3392        assert!(node.supports_action(Action::CustomAction));
3393
3394        let invoke = |tree: &mut WidgetTree, custom: i32| {
3395            tree.dispatch_event(crate::event::WidgetEvent::AccessAction {
3396                action: Action::CustomAction,
3397                target: Some(id),
3398                target_node: crate::accessibility::widget_id_to_node_id(id),
3399                data: Some(accesskit::ActionData::CustomAction(custom)),
3400            });
3401        };
3402        invoke(&mut tree, 0);
3403        assert_eq!(
3404            (own.get(), added.get()),
3405            (0, 1),
3406            "index 0 is the override's"
3407        );
3408        invoke(&mut tree, OWN_CUSTOM_ACTION_ID);
3409        assert_eq!(
3410            (own.get(), added.get()),
3411            (1, 1),
3412            "and the widget's id is still the widget's"
3413        );
3414    }
3415
3416    // Test 25
3417    #[test]
3418    fn access_action_layered_with_on_access_action() {
3419        use crate::signal::Signal;
3420        let from_override = Signal::new(false);
3421        let from_user = Signal::new(false);
3422        let ov_cb = from_override.clone();
3423        let user_cb = from_user.clone();
3424        let mut tree = WidgetTree::new();
3425        let id = tree.add(
3426            FillWidget::new()
3427                .access_action(Action::ShowContextMenu, move |_| ov_cb.set(true))
3428                .on_access_action(move |_action, _ctx| {
3429                    user_cb.set(true);
3430                    crate::event::EventResponse::Handled
3431                }),
3432        );
3433        tree.layout(SizeProposal::exact(50.0, 50.0));
3434        tree.dispatch_event(crate::event::WidgetEvent::AccessAction {
3435            action: Action::ShowContextMenu,
3436            target: Some(id),
3437            target_node: crate::accessibility::widget_id_to_node_id(id),
3438            data: None,
3439        });
3440        assert!(from_override.get(), "override callback fired");
3441        assert!(from_user.get(), "user catch-all fired");
3442    }
3443
3444    // Test 26 — i18n integration via teksilo_i18n's
3445    // `From<LocalizedString> for Prop<String>` impl. We don't import
3446    // teksilo-i18n here (it depends on teksilo-core), but the conversion
3447    // works the same way for any `Into<Prop<String>>`. This stand-in
3448    // covers the same code path the FTL-bundle case takes.
3449    #[test]
3450    fn access_label_accepts_resolved_string_via_into() {
3451        // Simulate a `LocalizedString`-like wrapper: any type that
3452        // `impl Into<Prop<String>>`. The override surface stores the
3453        // prop and the walker reads its current value.
3454        struct ResolvedAtCall(String);
3455        impl From<ResolvedAtCall> for crate::signal::Prop<String> {
3456            fn from(v: ResolvedAtCall) -> crate::signal::Prop<String> {
3457                crate::signal::Prop::Static(v.0)
3458            }
3459        }
3460        let mut tree = WidgetTree::new();
3461        let id = tree.add(FillWidget::new().access_label(ResolvedAtCall("Save".to_string())));
3462        tree.layout(SizeProposal::exact(50.0, 50.0));
3463        assert_eq!(tree.accessibility_node(id).name(), Some("Save"));
3464    }
3465
3466    // Test 27
3467    #[test]
3468    fn access_exclude_subtree_prunes_children_from_at_tree() {
3469        let mut tree = WidgetTree::new();
3470        let inner1 = tree.add(FillWidget::new().label("A"));
3471        let inner2 = tree.add(FillWidget::new().label("B"));
3472        let outer = tree.add(
3473            StackWidget::new()
3474                .child(inner1)
3475                .child(inner2)
3476                // A label keeps `outer` from being collapsed as a
3477                // presentational container, so the test exercises Exclude
3478                // (not the new presentational-pruning pass).
3479                .access_label_literal("Section")
3480                .access_exclude_subtree(),
3481        );
3482        tree.layout(SizeProposal::exact(100.0, 50.0));
3483        let update = tree.sync_accessibility();
3484        // Outer is present; inner1 and inner2 are pruned.
3485        assert!(find_node(&update, outer).is_some());
3486        assert!(find_node(&update, inner1).is_none(), "inner1 pruned");
3487        assert!(find_node(&update, inner2).is_none(), "inner2 pruned");
3488        let outer_node = find_node(&update, outer).unwrap();
3489        assert!(
3490            outer_node.children().is_empty(),
3491            "outer should have no AT children when excluded"
3492        );
3493    }
3494
3495    // Test 28
3496    #[test]
3497    fn access_merge_subtree_concatenates_descendant_labels() {
3498        let mut tree = WidgetTree::new();
3499        let title = tree.add(FillWidget::new().label("Title"));
3500        let subtitle = tree.add(FillWidget::new().label("Subtitle"));
3501        let card = tree.add(
3502            StackWidget::new()
3503                .child(title)
3504                .child(subtitle)
3505                .access_merge_subtree(),
3506        );
3507        tree.layout(SizeProposal::exact(100.0, 50.0));
3508        // After merge: card's name is "Title Subtitle", children pruned.
3509        assert_eq!(tree.text_content(card), Some("Title Subtitle".to_string()));
3510        let update = tree.sync_accessibility();
3511        assert!(find_node(&update, title).is_none());
3512        assert!(find_node(&update, subtitle).is_none());
3513    }
3514
3515    #[test]
3516    fn access_merge_subtree_takes_nothing_from_under_a_hidden_descendant() {
3517        // A hidden node hides its subtree: the consumer every platform
3518        // adapter reads through treats a node as hidden when any ancestor
3519        // is. A merged name that still took the text under a hidden
3520        // wrapper would say aloud what the widget hid from the reader.
3521        let mut tree = WidgetTree::new();
3522        let title = tree.add(FillWidget::new().label("Title"));
3523        let secret = tree.add(FillWidget::new().label("Secret"));
3524        let hidden = tree.add(StackWidget::new().child(secret).access_hidden(true));
3525        let card = tree.add(
3526            StackWidget::new()
3527                .child(title)
3528                .child(hidden)
3529                .access_merge_subtree(),
3530        );
3531        tree.layout(SizeProposal::exact(100.0, 50.0));
3532        assert_eq!(tree.text_content(card), Some("Title".to_string()));
3533    }
3534
3535    // Test 29
3536    #[test]
3537    fn access_merge_subtree_unions_actions() {
3538        let mut tree = WidgetTree::new();
3539        let click_a = tree.add(ClickableWidget);
3540        let click_b = tree.add(ClickableWidget);
3541        let card = tree.add(
3542            StackWidget::new()
3543                .child(click_a)
3544                .child(click_b)
3545                .access_merge_subtree(),
3546        );
3547        tree.layout(SizeProposal::exact(100.0, 50.0));
3548        let actions = tree.accessibility_node(card).actions().to_vec();
3549        let click_count = actions.iter().filter(|a| **a == Action::Click).count();
3550        assert_eq!(
3551            click_count, 1,
3552            "Click should be present exactly once after merge (deduplicated)"
3553        );
3554    }
3555
3556    // Test 30 — covered by the i18n integration mechanism documented in
3557    // `From<LocalizedString> for String`. Since teksilo-core can't reference
3558    // LocalizedString, the merged-localized-label case is exercised by
3559    // tests 26 + 28 in combination: each child's resolved-at-call-time
3560    // String contributes to the merged label. The full FTL-bundle
3561    // round-trip is tested in the teksilo-i18n / teksilo-widgets integration
3562    // tests, not here.
3563
3564    // Test 31
3565    #[test]
3566    fn access_merge_subtree_first_nonempty_value_wins() {
3567        #[derive(Debug)]
3568        struct ValueWidget(&'static str);
3569        impl Widget for ValueWidget {
3570            fn layout_response(
3571                &self,
3572                proposal: SizeProposal,
3573                _ctx: &LayoutContext,
3574            ) -> crate::widget::LayoutResponse {
3575                proposal.resolve(0.0, 0.0).into()
3576            }
3577            fn accessibility(&self, builder: &mut AccessNodeBuilder) {
3578                builder.set_role(Role::Slider);
3579                builder.set_value(self.0);
3580            }
3581        }
3582        let mut tree = WidgetTree::new();
3583        let v1 = tree.add(ValueWidget("first"));
3584        let v2 = tree.add(ValueWidget("second"));
3585        let card = tree.add(
3586            StackWidget::new()
3587                .child(v1)
3588                .child(v2)
3589                .access_merge_subtree(),
3590        );
3591        tree.layout(SizeProposal::exact(100.0, 50.0));
3592        assert_eq!(tree.text_value(card), Some("first".to_string()));
3593    }
3594
3595    // Test 32
3596    #[test]
3597    fn access_exclude_inside_merge() {
3598        let mut tree = WidgetTree::new();
3599        let visible = tree.add(FillWidget::new().label("VISIBLE"));
3600        let pruned = tree.add(FillWidget::new().label("PRUNED"));
3601        let inner_excluded = tree.add(StackWidget::new().child(pruned).access_exclude_subtree());
3602        let card = tree.add(
3603            StackWidget::new()
3604                .child(visible)
3605                .child(inner_excluded)
3606                .access_merge_subtree(),
3607        );
3608        tree.layout(SizeProposal::exact(100.0, 50.0));
3609        let merged = tree.text_content(card).unwrap_or_default();
3610        // VISIBLE present, PRUNED absent (because inner_excluded
3611        // pruned its own subtree before the merge could absorb it).
3612        assert!(merged.contains("VISIBLE"));
3613        assert!(
3614            !merged.contains("PRUNED"),
3615            "excluded subtree should not contribute to merge"
3616        );
3617    }
3618
3619    // Test 33
3620    #[test]
3621    fn access_merge_inside_merge() {
3622        let mut tree = WidgetTree::new();
3623        let inner_a = tree.add(FillWidget::new().label("a"));
3624        let inner_b = tree.add(FillWidget::new().label("b"));
3625        let inner_card = tree.add(
3626            StackWidget::new()
3627                .child(inner_a)
3628                .child(inner_b)
3629                .access_merge_subtree(),
3630        );
3631        let outer_extra = tree.add(FillWidget::new().label("X"));
3632        let outer = tree.add(
3633            StackWidget::new()
3634                .child(inner_card)
3635                .child(outer_extra)
3636                .access_merge_subtree(),
3637        );
3638        tree.layout(SizeProposal::exact(200.0, 100.0));
3639        // Outer absorbs inner_card's already-merged label ("a b") AND
3640        // outer_extra ("X"), giving something like "a b X" or "X a b".
3641        // Order is descendant-walk order; we just verify all parts
3642        // appear and inner children are NOT double-counted.
3643        let merged = tree.text_content(outer).unwrap_or_default();
3644        assert!(merged.contains("a"));
3645        assert!(merged.contains("b"));
3646        assert!(merged.contains("X"));
3647        // Inner children should not appear AS THEIR OWN nodes:
3648        let update = tree.sync_accessibility();
3649        assert!(find_node(&update, inner_a).is_none());
3650        assert!(find_node(&update, inner_b).is_none());
3651        assert!(find_node(&update, inner_card).is_none());
3652        assert!(find_node(&update, outer_extra).is_none());
3653    }
3654
3655    // Test 34
3656    #[test]
3657    fn access_customize_runs_last() {
3658        let mut tree = WidgetTree::new();
3659        let id = tree.add(
3660            FillWidget::new()
3661                .access_label_literal("A")
3662                .access_customize(|b| b.set_name("B")),
3663        );
3664        tree.layout(SizeProposal::exact(50.0, 50.0));
3665        assert_eq!(tree.accessibility_node(id).name(), Some("B"));
3666    }
3667
3668    // Test 35
3669    #[test]
3670    fn access_customize_can_reach_inner_mut() {
3671        let mut tree = WidgetTree::new();
3672        let id = tree.add(FillWidget::new().access_customize(|b| {
3673            b.inner_mut().set_author_id("from-customize");
3674        }));
3675        tree.layout(SizeProposal::exact(50.0, 50.0));
3676        let update = tree.sync_accessibility();
3677        let node = find_node(&update, id).unwrap();
3678        assert_eq!(node.author_id(), Some("from-customize"));
3679    }
3680
3681    // Test 36 — sanity guard. WidgetNode size delta when no overrides.
3682    #[test]
3683    fn access_overrides_zero_cost_when_unused() {
3684        // The override fields add only `Option<Box<...>>` (8 bytes for
3685        // the pointer-sized null) + `AccessSubtreeMode` (1 byte enum,
3686        // padded). Sanity: at most 16 bytes added.
3687        // We don't assert a specific size because struct layout shifts
3688        // with rustc versions; we just confirm both fields are
3689        // pointer/byte sized.
3690        use std::mem::size_of;
3691        assert!(size_of::<Option<Box<crate::widget_builder::AccessibilityOverrides>>>() <= 16);
3692        assert!(size_of::<crate::widget_builder::AccessSubtreeMode>() <= 4);
3693    }
3694
3695    #[test]
3696    fn accessibility_children_overrides_at_reading_order() {
3697        // Audit G17: a widget can present a different child ORDER to assistive
3698        // tech than its layout/paint child order via `accessibility_children()`
3699        // — the mechanism TableView/TreeTableView use to read the header before
3700        // the body even though they build the body first (z-order).
3701        #[derive(Debug)]
3702        struct NamedLeaf(&'static str);
3703        impl Widget for NamedLeaf {
3704            fn layout_response(
3705                &self,
3706                proposal: SizeProposal,
3707                _ctx: &LayoutContext,
3708            ) -> crate::widget::LayoutResponse {
3709                proposal.resolve(10.0, 10.0).into()
3710            }
3711            fn accessibility(&self, builder: &mut AccessNodeBuilder) {
3712                // Button keeps `set_name` as the node's label (Role::Label
3713                // routes text to `value` instead), so the test can find the
3714                // leaves by name.
3715                builder.set_role(accesskit::Role::Button);
3716                builder.set_name(self.0);
3717            }
3718        }
3719
3720        #[derive(Debug, Default)]
3721        struct ReorderContainer {
3722            a: Option<WidgetId>,
3723            b: Option<WidgetId>,
3724        }
3725        impl Widget for ReorderContainer {
3726            fn build(&mut self, ctx: &mut crate::build_context::BuildContext) -> Vec<WidgetId> {
3727                let a = ctx.add(NamedLeaf("A"));
3728                let b = ctx.add(NamedLeaf("B"));
3729                self.a = Some(a);
3730                self.b = Some(b);
3731                vec![a, b]
3732            }
3733            fn layout_response(
3734                &self,
3735                proposal: SizeProposal,
3736                _ctx: &LayoutContext,
3737            ) -> crate::widget::LayoutResponse {
3738                proposal.resolve(100.0, 100.0).into()
3739            }
3740            fn accessibility(&self, builder: &mut AccessNodeBuilder) {
3741                // A real role so the container itself isn't dropped as a
3742                // presentational node — we need to inspect its child order.
3743                builder.set_role(accesskit::Role::Group);
3744                builder.set_name("Container");
3745            }
3746            fn children(&self) -> Vec<WidgetId> {
3747                [self.a, self.b].into_iter().flatten().collect()
3748            }
3749            fn accessibility_children(&self) -> Option<Vec<WidgetId>> {
3750                // Reverse of build/layout order.
3751                Some([self.b, self.a].into_iter().flatten().collect())
3752            }
3753        }
3754
3755        let mut tree = WidgetTree::new();
3756        let container = tree.add(ReorderContainer::default());
3757        tree.layout(SizeProposal::exact(100.0, 100.0));
3758        let update = tree.sync_accessibility();
3759
3760        let a_nid = update
3761            .nodes
3762            .iter()
3763            .find(|(_, n)| n.label() == Some("A"))
3764            .map(|(id, _)| *id)
3765            .expect("A node present");
3766        let b_nid = update
3767            .nodes
3768            .iter()
3769            .find(|(_, n)| n.label() == Some("B"))
3770            .map(|(id, _)| *id)
3771            .expect("B node present");
3772        let cnid = crate::accessibility::widget_id_to_node_id(container);
3773        let cnode = update
3774            .nodes
3775            .iter()
3776            .find(|(id, _)| *id == cnid)
3777            .map(|(_, n)| n)
3778            .expect("container node present");
3779        let kids = cnode.children();
3780        let pa = kids.iter().position(|k| *k == a_nid).expect("A is a child");
3781        let pb = kids.iter().position(|k| *k == b_nid).expect("B is a child");
3782        assert!(
3783            pb < pa,
3784            "accessibility_children() must set AT order B-before-A; got {kids:?}"
3785        );
3786    }
3787
3788    // ── the root transform: logical rectangles, physical coordinates ──────
3789    //
3790    // These set `device_scale_factor` to 2.0 explicitly. CI runs at 1.0, where
3791    // a missing or wrong scale is invisible — which is how a whole tree of
3792    // half-size AT rectangles survived this long.
3793
3794    /// The rectangle `accesskit_consumer` computes for the node labelled
3795    /// `label` — the same accumulate-every-ancestor-transform walk every
3796    /// platform adapter performs, so this is literally what an assistive
3797    /// technology is told.
3798    ///
3799    /// Found by label rather than by id because `FullNodeId` cannot be built
3800    /// from outside the consumer crate.
3801    fn consumer_bounding_box(update: &accesskit::TreeUpdate, label: &str) -> accesskit::Rect {
3802        let consumer = accesskit_consumer::Tree::new(update.clone(), false);
3803        let state = consumer.state();
3804        let mut stack = vec![state.root()];
3805        while let Some(node) = stack.pop() {
3806            // A `Role::Label`'s text lives in `value` — `label_comes_from_value`
3807            // is true for exactly that role — so look in both.
3808            let text = node.value().or_else(|| node.label());
3809            if text.as_deref() == Some(label) {
3810                return node.bounding_box().expect("node has bounds");
3811            }
3812            for child in node.children() {
3813                stack.push(child);
3814            }
3815        }
3816        panic!("no node labelled {label:?} in the consumer tree");
3817    }
3818
3819    fn tree_at_scale(scale: f32) -> (WidgetTree, WidgetId) {
3820        let mut tree = WidgetTree::new();
3821        let id = tree.add(FillWidget::new().label("content"));
3822        tree.set_device_scale_factor(scale);
3823        tree.layout(SizeProposal::exact(200.0, 100.0));
3824        (tree, id)
3825    }
3826
3827    #[test]
3828    fn the_root_carries_the_device_scale_as_its_transform() {
3829        let (mut tree, _) = tree_at_scale(2.0);
3830        let update = tree.sync_accessibility();
3831        let root = update
3832            .nodes
3833            .iter()
3834            .find(|(id, _)| *id == crate::accessibility::root_node_id())
3835            .map(|(_, n)| n)
3836            .expect("root node present");
3837        assert_eq!(
3838            root.transform().copied(),
3839            Some(accesskit::Affine::scale(2.0)),
3840            "AccessKit wants physical coordinates; the tree emits logical ones"
3841        );
3842        assert_a11y_tree_valid(&update);
3843    }
3844
3845    #[test]
3846    fn emitted_bounds_stay_logical_at_scale_two() {
3847        // The rule every emitter in the workspace has to obey — this crate's
3848        // walker, teksilo-charts' marks, teksilo-scene's items — is that a
3849        // rectangle handed to AccessKit is the same logical rectangle the
3850        // layout produced. Multiplying by the scale at the emitter would
3851        // double-scale it once the root transform is applied. This is the
3852        // fence for the sites this crate owns; the other two crates' emitters
3853        // are unreachable from here (the dependency runs the other way) and
3854        // are covered by the same statement in `emit_root_transform`'s doc.
3855        let (mut tree, id) = tree_at_scale(2.0);
3856        let update = tree.sync_accessibility();
3857        let layout = tree.bounds(id);
3858        let nid = crate::accessibility::widget_id_to_node_id(id);
3859        let raw = update
3860            .nodes
3861            .iter()
3862            .find(|(n, _)| *n == nid)
3863            .and_then(|(_, n)| n.bounds())
3864            .expect("widget node has bounds");
3865        assert_eq!(
3866            (raw.x0, raw.y0, raw.x1, raw.y1),
3867            (
3868                layout.x as f64,
3869                layout.y as f64,
3870                (layout.x + layout.width) as f64,
3871                (layout.y + layout.height) as f64,
3872            ),
3873            "an emitted rectangle must be the logical layout rectangle, unscaled"
3874        );
3875    }
3876
3877    /// The same fence for an **interactive** node — the one a touch-target
3878    /// change actually reaches.
3879    ///
3880    /// The AccessKit hit test stays exact and is never slop-expanded. A
3881    /// finger's grip outsets belong to the pointer hit path
3882    /// (`WidgetTree::widget_hit_outset` and the miss-only slop pass), not to
3883    /// the AT tree: an assistive technology is told where the control *is*, so
3884    /// inflating that rectangle would put VoiceOver's cursor and Narrator's
3885    /// highlight over ground the control does not own and would overlap its
3886    /// neighbours — and, since AccessKit resolves its own hit tests from these
3887    /// rectangles, would hand a touch-explore probe the wrong control near
3888    /// every edge.
3889    ///
3890    /// A sibling of `emitted_bounds_stay_logical_at_scale_two` rather than an
3891    /// extra assertion in it, because that test's fixture is a bare
3892    /// `FillWidget` advertising no action at all: the natural shape of this
3893    /// mistake — "inflate every node that advertises `Action::Click` so touch
3894    /// targets are easier to hit" — passes it untouched.
3895    #[test]
3896    fn an_interactive_node_emits_its_exact_layout_rectangle() {
3897        let mut tree = WidgetTree::new();
3898        let id = tree.add(ActionWidget);
3899        tree.layout(SizeProposal::exact(200.0, 100.0));
3900        let update = tree.sync_accessibility();
3901        let nid = crate::accessibility::widget_id_to_node_id(id);
3902        let node = update
3903            .nodes
3904            .iter()
3905            .find(|(n, _)| *n == nid)
3906            .map(|(_, n)| n)
3907            .expect("the interactive node is in the update");
3908        assert!(
3909            node.supports_action(accesskit::Action::Click),
3910            "the fixture has to be the clickable shape the rule is about, \
3911             or this test guards nothing"
3912        );
3913        let layout = tree.bounds(id);
3914        assert!(
3915            layout.width > 0.0 && layout.height > 0.0,
3916            "a real, non-degenerate rectangle to compare against: {layout:?}"
3917        );
3918        let raw = node.bounds().expect("the interactive node has bounds");
3919        assert_eq!(
3920            (raw.x0, raw.y0, raw.x1, raw.y1),
3921            (
3922                layout.x as f64,
3923                layout.y as f64,
3924                (layout.x + layout.width) as f64,
3925                (layout.y + layout.height) as f64,
3926            ),
3927            "a clickable node's emitted rectangle is its layout rectangle, \
3928             not an outset one"
3929        );
3930    }
3931
3932    #[test]
3933    fn what_an_assistive_technology_reads_is_the_physical_rectangle() {
3934        // Same widget, two scales: the rectangle the consumer computes — which
3935        // is the one VoiceOver / Narrator / Orca get — doubles, while the
3936        // emitted rectangle above did not.
3937        let (mut one, _) = tree_at_scale(1.0);
3938        let at_one = consumer_bounding_box(&one.sync_accessibility(), "content");
3939        let (mut two, _) = tree_at_scale(2.0);
3940        let at_two = consumer_bounding_box(&two.sync_accessibility(), "content");
3941        assert_eq!(at_two.x0, at_one.x0 * 2.0);
3942        assert_eq!(at_two.y0, at_one.y0 * 2.0);
3943        assert_eq!(at_two.x1, at_one.x1 * 2.0);
3944        assert_eq!(at_two.y1, at_one.y1 * 2.0);
3945        assert!(at_two.x1 > at_two.x0, "a real, non-degenerate rectangle");
3946    }
3947
3948    #[test]
3949    fn a_scale_change_invalidates_the_accessibility_cache() {
3950        // Dragging a window from a 1x to a 2x monitor. A plain relayout does
3951        // not dirty the AT cache, so without the guard in
3952        // `set_device_scale_factor` the second sync would return the cached
3953        // update and report every rectangle at the old display's scale
3954        // for the rest of the window's life.
3955        let (mut tree, _) = tree_at_scale(1.0);
3956        let _ = tree.sync_accessibility();
3957        tree.set_device_scale_factor(2.0);
3958        let update = tree.sync_accessibility();
3959        let root = update
3960            .nodes
3961            .iter()
3962            .find(|(id, _)| *id == crate::accessibility::root_node_id())
3963            .map(|(_, n)| n)
3964            .expect("root node present");
3965        assert_eq!(
3966            root.transform().copied(),
3967            Some(accesskit::Affine::scale(2.0))
3968        );
3969    }
3970
3971    #[test]
3972    fn setting_the_same_scale_does_not_dirty_the_tree() {
3973        // The dirty-mark is behind an equality check, so a set that changes
3974        // nothing costs nothing and — more to the point — cannot make the
3975        // "content changed" version signal move when the content did not.
3976        let (mut tree, _) = tree_at_scale(2.0);
3977        let first = tree.sync_accessibility();
3978        tree.set_device_scale_factor(2.0);
3979        let second = tree.sync_accessibility();
3980        assert_eq!(first, second);
3981    }
3982
3983    // ── the explore-by-touch gate ─────────────────────────────────────────
3984
3985    #[test]
3986    fn explore_by_touch_is_off_by_default() {
3987        let tree = WidgetTree::new();
3988        assert_eq!(tree.explore_by_touch(), crate::ExploreByTouch::Off);
3989        assert_eq!(
3990            tree.screen_reader_state(),
3991            crate::ScreenReaderState::Unknown
3992        );
3993        assert!(!tree.explore_by_touch_active());
3994    }
3995
3996    #[test]
3997    fn auto_follows_the_operating_systems_screen_reader_flag() {
3998        let mut tree = WidgetTree::new();
3999        tree.set_explore_by_touch(crate::ExploreByTouch::Auto);
4000        assert!(!tree.explore_by_touch_active(), "Unknown is not a yes");
4001        tree.set_screen_reader_state(crate::ScreenReaderState::Inactive);
4002        assert!(!tree.explore_by_touch_active());
4003        tree.set_screen_reader_state(crate::ScreenReaderState::Active);
4004        assert!(tree.explore_by_touch_active());
4005    }
4006
4007    #[test]
4008    fn on_ignores_the_screen_reader_flag_and_off_ignores_everything() {
4009        let mut tree = WidgetTree::new();
4010        tree.set_explore_by_touch(crate::ExploreByTouch::On);
4011        assert!(tree.explore_by_touch_active(), "On is the app's own choice");
4012        tree.set_explore_by_touch(crate::ExploreByTouch::Off);
4013        tree.set_screen_reader_state(crate::ScreenReaderState::Active);
4014        assert!(!tree.explore_by_touch_active());
4015    }
4016
4017    #[test]
4018    fn an_attached_accesskit_client_does_not_switch_exploring_on() {
4019        // The whole point of the gate. A magnifier, a voice-control front end,
4020        // a UI-automation inspector and this repository's own automation
4021        // harness all activate an AccessKit adapter. If activation implied a
4022        // screen reader, attaching any of them would turn every touch into a
4023        // probe and make the application untouchable.
4024        let mut tree = WidgetTree::new();
4025        tree.set_explore_by_touch(crate::ExploreByTouch::Auto);
4026        tree.set_at_client_attached(true);
4027        assert!(tree.at_client_attached());
4028        assert_eq!(
4029            tree.screen_reader_state(),
4030            crate::ScreenReaderState::Unknown,
4031            "attaching says nothing about screen readers"
4032        );
4033        assert!(!tree.explore_by_touch_active());
4034    }
4035
4036    #[test]
4037    fn touch_still_reaches_a_handler_with_an_accesskit_client_attached() {
4038        // The acceptance criterion, as a behaviour rather than a flag: a tap
4039        // must arrive at its handler at the `Off` default with an assistive
4040        // technology attached. Nothing gates the pointer path on
4041        // `explore_by_touch_active()` today; this is the fence for whoever
4042        // wires touch-as-probe later.
4043        use crate::Modifiers;
4044        use crate::pointer::{
4045            BackendDeviceKey, EventTime, PointerIdAllocator, PointerInfo, PointerPhase,
4046            PointerSample,
4047        };
4048        use crate::widget_builder::WidgetBuilder;
4049        use std::cell::Cell;
4050        use std::rc::Rc;
4051
4052        let taps = Rc::new(Cell::new(0u32));
4053        let seen = Rc::clone(&taps);
4054        let mut tree = WidgetTree::new();
4055        let id = tree.add(
4056            FillWidget::new()
4057                .label("target")
4058                .on_tap(move |_e, _ctx| seen.set(seen.get() + 1)),
4059        );
4060        tree.layout(SizeProposal::exact(200.0, 100.0));
4061        tree.set_at_client_attached(true);
4062        assert!(!tree.explore_by_touch_active());
4063
4064        let at = Point::new(50.0, 50.0);
4065        let pid = PointerIdAllocator::global().begin(BackendDeviceKey::new(0x0A11), 1);
4066        let contact = |phase| PointerSample {
4067            pointer: PointerInfo::touch(pid, EventTime::ZERO),
4068            phase,
4069            position: at,
4070            button: None,
4071            modifiers: Modifiers::NONE,
4072            coalesced: Vec::new(),
4073        };
4074        tree.dispatch_pointer(contact(PointerPhase::Down));
4075        tree.dispatch_pointer(contact(PointerPhase::Up));
4076        assert!(tree.bounds(id).width > 0.0);
4077        assert_eq!(taps.get(), 1, "a touch tap must still activate its handler");
4078    }
4079
4080    #[test]
4081    fn a_detaching_client_is_evidence_that_no_screen_reader_is_reading() {
4082        // The asymmetry: attaching proves nothing, detaching proves something.
4083        // An `Auto` window stops exploring the moment the last client goes,
4084        // without waiting for the next OS query.
4085        let mut tree = WidgetTree::new();
4086        tree.set_explore_by_touch(crate::ExploreByTouch::Auto);
4087        tree.set_screen_reader_state(crate::ScreenReaderState::Active);
4088        tree.set_at_client_attached(true);
4089        assert!(tree.explore_by_touch_active());
4090        tree.set_at_client_attached(false);
4091        assert_eq!(
4092            tree.screen_reader_state(),
4093            crate::ScreenReaderState::Inactive
4094        );
4095        assert!(!tree.explore_by_touch_active());
4096    }
4097
4098    #[test]
4099    fn a_repeated_detach_notice_does_not_clobber_a_fresh_os_reading() {
4100        // `teksilo-app` pushes the attachment flag every frame. Only the
4101        // true→false edge counts: if every `false` forced `Inactive`, an OS
4102        // query that found a screen reader would be undone on the next frame.
4103        let mut tree = WidgetTree::new();
4104        tree.set_at_client_attached(false);
4105        tree.set_screen_reader_state(crate::ScreenReaderState::Active);
4106        tree.set_at_client_attached(false);
4107        assert_eq!(tree.screen_reader_state(), crate::ScreenReaderState::Active);
4108    }
4109
4110    // ── the reactive screen-reader state ──────────────────────────────────
4111
4112    /// Subscribes to the tree's screen-reader signal through
4113    /// `BuildContext`, counting callbacks and keeping the handle it got.
4114    #[derive(Debug)]
4115    struct ScreenReaderProbe {
4116        calls: std::rc::Rc<std::cell::Cell<u32>>,
4117        seen: std::rc::Rc<std::cell::RefCell<Vec<crate::ScreenReaderState>>>,
4118        handle: std::rc::Rc<
4119            std::cell::RefCell<Option<crate::signal::Signal<crate::ScreenReaderState>>>,
4120        >,
4121        at_build: std::rc::Rc<std::cell::Cell<Option<crate::ScreenReaderState>>>,
4122    }
4123
4124    impl Widget for ScreenReaderProbe {
4125        fn build(&mut self, ctx: &mut crate::build_context::BuildContext) -> Vec<WidgetId> {
4126            let signal = ctx.screen_reader_signal();
4127            self.at_build.set(Some(ctx.screen_reader_state()));
4128            let calls = self.calls.clone();
4129            let seen = self.seen.clone();
4130            ctx.effect(&signal, move |state| {
4131                calls.set(calls.get() + 1);
4132                seen.borrow_mut().push(*state);
4133            });
4134            *self.handle.borrow_mut() = Some(signal);
4135            vec![]
4136        }
4137
4138        fn layout_response(
4139            &self,
4140            proposal: SizeProposal,
4141            _ctx: &LayoutContext,
4142        ) -> crate::widget::LayoutResponse {
4143            proposal.resolve(0.0, 0.0).into()
4144        }
4145    }
4146
4147    struct ProbeTree {
4148        tree: WidgetTree,
4149        calls: std::rc::Rc<std::cell::Cell<u32>>,
4150        seen: std::rc::Rc<std::cell::RefCell<Vec<crate::ScreenReaderState>>>,
4151        handle: std::rc::Rc<
4152            std::cell::RefCell<Option<crate::signal::Signal<crate::ScreenReaderState>>>,
4153        >,
4154        at_build: std::rc::Rc<std::cell::Cell<Option<crate::ScreenReaderState>>>,
4155    }
4156
4157    fn screen_reader_probe_tree() -> ProbeTree {
4158        screen_reader_probe_tree_in(crate::ScreenReaderState::Unknown)
4159    }
4160
4161    /// The probe tree with the OS reporting `state` before the probe builds.
4162    fn screen_reader_probe_tree_in(state: crate::ScreenReaderState) -> ProbeTree {
4163        let calls = std::rc::Rc::new(std::cell::Cell::new(0));
4164        let seen = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
4165        let handle = std::rc::Rc::new(std::cell::RefCell::new(None));
4166        let at_build = std::rc::Rc::new(std::cell::Cell::new(None));
4167        let mut tree = WidgetTree::new();
4168        tree.set_screen_reader_state(state);
4169        tree.add(ScreenReaderProbe {
4170            calls: calls.clone(),
4171            seen: seen.clone(),
4172            handle: handle.clone(),
4173            at_build: at_build.clone(),
4174        });
4175        tree.layout(SizeProposal::exact(100.0, 100.0));
4176        ProbeTree {
4177            tree,
4178            calls,
4179            seen,
4180            handle,
4181            at_build,
4182        }
4183    }
4184
4185    #[test]
4186    fn the_screen_reader_signal_starts_unknown_and_is_one_signal_for_tree_and_context() {
4187        let p = screen_reader_probe_tree();
4188        assert_eq!(
4189            p.tree.screen_reader_signal().get(),
4190            crate::ScreenReaderState::Unknown
4191        );
4192        assert_eq!(p.at_build.get(), Some(crate::ScreenReaderState::Unknown));
4193        let from_context = p.handle.borrow().clone().expect("built");
4194        assert!(
4195            crate::signal::Signal::same(&p.tree.screen_reader_signal(), &from_context),
4196            "the build context hands out the tree's own signal"
4197        );
4198    }
4199
4200    #[test]
4201    fn the_screen_reader_signal_notifies_on_a_real_change_only() {
4202        let mut p = screen_reader_probe_tree();
4203        p.tree
4204            .set_screen_reader_state(crate::ScreenReaderState::Active);
4205        assert_eq!(p.calls.get(), 1);
4206        p.tree
4207            .set_screen_reader_state(crate::ScreenReaderState::Active);
4208        assert_eq!(p.calls.get(), 1, "the same value again notifies nobody");
4209        assert_eq!(*p.seen.borrow(), vec![crate::ScreenReaderState::Active]);
4210    }
4211
4212    #[test]
4213    fn a_client_detaching_notifies_once_and_a_repeat_notifies_nobody() {
4214        let mut p = screen_reader_probe_tree();
4215        p.tree
4216            .set_screen_reader_state(crate::ScreenReaderState::Active);
4217        p.tree.set_at_client_attached(true);
4218        let before = p.calls.get();
4219        p.tree.set_at_client_attached(false);
4220        assert_eq!(p.calls.get(), before + 1);
4221        assert_eq!(
4222            p.tree.screen_reader_signal().get(),
4223            crate::ScreenReaderState::Inactive
4224        );
4225        p.tree.set_at_client_attached(false);
4226        assert_eq!(p.calls.get(), before + 1, "a repeated detach adds nothing");
4227        p.tree
4228            .set_screen_reader_state(crate::ScreenReaderState::Active);
4229        assert_eq!(p.calls.get(), before + 2);
4230        assert_eq!(
4231            p.tree.screen_reader_state(),
4232            crate::ScreenReaderState::Active,
4233            "a later OS reading sticks"
4234        );
4235    }
4236
4237    #[test]
4238    fn a_detach_that_finds_the_state_already_inactive_notifies_nobody() {
4239        let mut p = screen_reader_probe_tree();
4240        p.tree
4241            .set_screen_reader_state(crate::ScreenReaderState::Inactive);
4242        p.tree.set_at_client_attached(true);
4243        let before = p.calls.get();
4244        p.tree.set_at_client_attached(false);
4245        assert_eq!(p.calls.get(), before);
4246    }
4247
4248    #[test]
4249    fn a_state_the_os_reported_before_the_build_is_read_at_build() {
4250        let p = screen_reader_probe_tree_in(crate::ScreenReaderState::Active);
4251        assert_eq!(p.at_build.get(), Some(crate::ScreenReaderState::Active));
4252        assert_eq!(
4253            p.tree.screen_reader_signal().get(),
4254            crate::ScreenReaderState::Active
4255        );
4256    }
4257
4258    #[test]
4259    fn a_screen_reader_change_dirties_neither_layout_nor_the_accessibility_tree() {
4260        let mut p = screen_reader_probe_tree();
4261        // The baseline a real loop reaches: laid out, painted, walked.
4262        p.tree.render();
4263        let _ = p.tree.sync_accessibility();
4264        assert!(!p.tree.needs_render(), "the baseline is clean");
4265        assert!(!p.tree.a11y_dirty, "the baseline is clean");
4266
4267        p.tree
4268            .set_screen_reader_state(crate::ScreenReaderState::Active);
4269        assert!(
4270            !p.tree.needs_render(),
4271            "the setter schedules no relayout and no repaint"
4272        );
4273        assert!(
4274            !p.tree.a11y_dirty,
4275            "the accessibility tree is not re-walked"
4276        );
4277    }
4278
4279    #[test]
4280    fn an_event_handler_reads_the_screen_reader_state_of_its_dispatch() {
4281        let mut tree = WidgetTree::new();
4282        tree.set_screen_reader_state(crate::ScreenReaderState::Active);
4283        let mut read = None;
4284        tree.run_with_event_context(&mut crate::window::NoopWindowOps, |ctx| {
4285            read = Some(ctx.screen_reader_state());
4286        });
4287        assert_eq!(read, Some(crate::ScreenReaderState::Active));
4288    }
4289
4290    // ── announcements ─────────────────────────────────────────────────────
4291
4292    #[test]
4293    fn a_density_switch_announces_once_in_the_applications_own_words() {
4294        use teksilo_tokens::TargetDensity;
4295        let mut tree = tree_with_one_widget();
4296        tree.set_density_announcement(Some(std::rc::Rc::new(|d: TargetDensity| {
4297            format!("layout {d:?}")
4298        })));
4299        let _ = tree.sync_accessibility();
4300
4301        let mut arrivals = Arrivals::attach(tree.accessibility_tree_snapshot());
4302
4303        tree.set_input_density(TargetDensity::Comfortable);
4304        let update = tree.sync_accessibility();
4305        assert_eq!(
4306            arrivals.feed(update),
4307            vec![("layout Comfortable".to_string(), accesskit::Live::Polite)]
4308        );
4309
4310        // Once per *switch*: setting the density it already has says nothing.
4311        let _ = arrivals.feed(tree.sync_accessibility());
4312        tree.set_input_density(TargetDensity::Comfortable);
4313        let update = tree.sync_accessibility();
4314        assert_eq!(arrivals.feed(update), Vec::new());
4315    }
4316
4317    #[test]
4318    fn a_density_switch_is_silent_without_a_registered_wording() {
4319        // The framework cannot word this itself: `teksilo-i18n` depends on this
4320        // crate, so an English sentence is all core could hardcode, and an
4321        // English sentence spoken into a French screen reader is worse than
4322        // silence.
4323        use teksilo_tokens::TargetDensity;
4324        let mut tree = tree_with_one_widget();
4325        let _ = tree.sync_accessibility();
4326        tree.set_input_density(TargetDensity::Comfortable);
4327        let update = tree.sync_accessibility();
4328        assert_eq!(announced_by_consumer(&update), Vec::new());
4329    }
4330
4331    #[test]
4332    fn an_announcement_stays_quiet_when_the_widget_already_speaks() {
4333        let mut tree = WidgetTree::new();
4334        use crate::widget_builder::WidgetBuilder;
4335        let widget = tree.add(
4336            FillWidget::new()
4337                .label("Saved")
4338                .access_live(accesskit::Live::Polite),
4339        );
4340        tree.layout(SizeProposal::exact(200.0, 100.0));
4341        // Build the tree the check reads.
4342        let _ = tree.sync_accessibility();
4343
4344        assert!(
4345            !tree.announce_unless_widget_speaks(widget, "Saved"),
4346            "a widget with its own live region must not be doubled"
4347        );
4348        let update = tree.sync_accessibility();
4349        // One live node in the filtered tree — the widget's own. If the
4350        // framework had queued its copy, its announcer node would have entered
4351        // the filtered tree beside it and the user would hear "Saved" twice.
4352        let live = live_nodes_in_filtered_tree(&update);
4353        assert_eq!(live.len(), 1, "exactly one voice, not two: {live:?}");
4354    }
4355
4356    #[test]
4357    fn an_announcement_goes_ahead_when_the_widget_is_silent() {
4358        let mut tree = WidgetTree::new();
4359        let widget = tree.add(FillWidget::new().label("Row"));
4360        tree.layout(SizeProposal::exact(200.0, 100.0));
4361        let _ = tree.sync_accessibility();
4362
4363        assert!(tree.announce_unless_widget_speaks(widget, "Moved to 3 of 12"));
4364        let update = tree.sync_accessibility();
4365        assert_eq!(
4366            announced_by_consumer(&update),
4367            vec![("Moved to 3 of 12".to_string(), accesskit::Live::Polite)]
4368        );
4369    }
4370
4371    #[test]
4372    fn a_tree_that_records_no_announcements_still_hears_the_widget_speak() {
4373        // The check reads the last update through the consumer on the spot,
4374        // not through the announcement ring's replay, which a window of an
4375        // application nobody drives does not keep. The long-press menu
4376        // announcement goes through here in every application.
4377        let mut tree = WidgetTree::new();
4378        tree.set_records_announcements(false);
4379        use crate::widget_builder::WidgetBuilder;
4380        let widget = tree.add(
4381            FillWidget::new()
4382                .label("Saved")
4383                .access_live(accesskit::Live::Polite),
4384        );
4385        tree.layout(SizeProposal::exact(200.0, 100.0));
4386        let _ = tree.sync_accessibility();
4387        assert!(!tree.announce_unless_widget_speaks(widget, "Saved"));
4388    }
4389
4390    #[test]
4391    fn a_live_region_no_platform_hears_does_not_count_as_speaking() {
4392        // A `Status` takes its name from its label. One that carries its text
4393        // only as a value has no name, so every adapter stays silent about it,
4394        // and letting it stand in for the framework's message left the user
4395        // with nothing at all.
4396        let mut tree = WidgetTree::new();
4397        use crate::widget_builder::WidgetBuilder;
4398        let widget = tree.add(
4399            FillWidget::new()
4400                .access_role(accesskit::Role::Status)
4401                .access_value("Saved")
4402                .access_live(accesskit::Live::Polite),
4403        );
4404        tree.layout(SizeProposal::exact(200.0, 100.0));
4405        let _ = tree.sync_accessibility();
4406        assert!(tree.announce_unless_widget_speaks(widget, "Saved"));
4407    }
4408
4409    #[test]
4410    fn a_hidden_live_region_does_not_count_as_speaking() {
4411        // Hidden is outside the filtered tree, where no adapter announces.
4412        let mut tree = WidgetTree::new();
4413        use crate::widget_builder::WidgetBuilder;
4414        let widget = tree.add(
4415            FillWidget::new()
4416                .label("Saved")
4417                .access_live(accesskit::Live::Polite)
4418                .access_hidden(true),
4419        );
4420        tree.layout(SizeProposal::exact(200.0, 100.0));
4421        let _ = tree.sync_accessibility();
4422        assert!(tree.announce_unless_widget_speaks(widget, "Saved"));
4423    }
4424
4425    #[test]
4426    fn a_live_region_around_the_widget_does_not_count_as_the_widget_speaking() {
4427        // A button inside somebody else's live region, a toast's action or a
4428        // row of a live palette, inherits the region's politeness: the adapters
4429        // would speak it if its own name changed. That is the region talking,
4430        // not the button, and the menu the button just opened is still news
4431        // nobody else is giving.
4432        let mut tree = WidgetTree::new();
4433        use crate::widget_builder::WidgetBuilder;
4434        let region = tree.add(
4435            StackWidget::new()
4436                .access_role(accesskit::Role::Group)
4437                .access_label("Notification")
4438                .access_live(accesskit::Live::Polite),
4439        );
4440        let button = tree.add_child(
4441            region,
4442            FillWidget::new()
4443                .label("Annuler")
4444                .access_role(accesskit::Role::Button),
4445        );
4446        tree.layout(SizeProposal::exact(200.0, 100.0));
4447        let _ = tree.sync_accessibility();
4448        assert!(tree.announce_unless_widget_speaks(button, "Menu des actions ouvert"));
4449    }
4450
4451    #[test]
4452    fn a_live_region_with_no_text_does_not_count_as_speaking() {
4453        // A live region that is present but empty announces nothing on any
4454        // platform, so it must not silence the framework's message.
4455        let mut tree = WidgetTree::new();
4456        use crate::widget_builder::WidgetBuilder;
4457        let widget = tree.add(FillWidget::new().access_live(accesskit::Live::Polite));
4458        tree.layout(SizeProposal::exact(200.0, 100.0));
4459        let _ = tree.sync_accessibility();
4460        assert!(tree.announce_unless_widget_speaks(widget, "Something happened"));
4461    }
4462
4463    /// A widget that emits a live-region **synthetic** child, the way
4464    /// `teksilo-scene` marks a scene item as a live region: a named item
4465    /// pushed through `push_scene_child`, then made live.
4466    ///
4467    /// It used to be an annotation child, a `Role::Comment` holding its text
4468    /// as a value. That node has no name, so no platform speaks it, and the
4469    /// check this fixture feeds was passing on a region nobody could hear.
4470    #[derive(Debug)]
4471    struct SpeakingSynthetic;
4472
4473    impl crate::widget::Widget for SpeakingSynthetic {
4474        fn layout_response(
4475            &self,
4476            proposal: SizeProposal,
4477            _ctx: &crate::widget::LayoutContext,
4478        ) -> crate::widget::LayoutResponse {
4479            proposal.resolve(0.0, 0.0).into()
4480        }
4481
4482        fn accessibility(&self, builder: &mut AccessNodeBuilder) {
4483            builder.set_role(accesskit::Role::Group);
4484            let child = builder.push_scene_child(
4485                1,
4486                crate::accessibility::SyntheticKind::SceneItem,
4487                |item| {
4488                    item.set_role(accesskit::Role::Status);
4489                    item.set_name("2 items selected");
4490                },
4491            );
4492            builder.with_collected_node(child, |node| node.set_live(accesskit::Live::Polite));
4493        }
4494    }
4495
4496    #[test]
4497    fn a_live_synthetic_child_counts_as_the_widget_speaking() {
4498        // A scene can mark one of its lightweight items as a live region. The
4499        // item has no widget of its own, so the check has to resolve it back
4500        // to its owner through the synthetic-parent map — the same map the
4501        // AccessKit action router uses.
4502        let mut tree = WidgetTree::new();
4503        let widget = tree.add(SpeakingSynthetic);
4504        tree.layout(SizeProposal::exact(200.0, 100.0));
4505        let update = tree.sync_accessibility();
4506        assert!(
4507            update
4508                .nodes
4509                .iter()
4510                .any(|(id, _)| crate::accessibility::is_synthetic(*id)),
4511            "the fixture must actually emit a synthetic child"
4512        );
4513        assert!(!tree.announce_unless_widget_speaks(widget, "2 items selected"));
4514    }
4515
4516    #[test]
4517    fn a_descendants_live_region_silences_its_ancestor_too() {
4518        // The check is over the whole subtree: a composite whose inner status
4519        // line speaks is a composite that speaks.
4520        let mut tree = WidgetTree::new();
4521        let container = tree.add(StackWidget::new());
4522        use crate::widget_builder::WidgetBuilder;
4523        let inner = FillWidget::new()
4524            .label("3 results")
4525            .access_live(accesskit::Live::Polite);
4526        tree.add_child(container, inner);
4527        tree.layout(SizeProposal::exact(200.0, 100.0));
4528        let _ = tree.sync_accessibility();
4529        assert!(!tree.announce_unless_widget_speaks(container, "3 results"));
4530    }
4531
4532    // ── a run's top on a whole device pixel ───────────────────────────────
4533
4534    fn run_at(top: f64, bottom: f64) -> accesskit::Node {
4535        let mut node = accesskit::Node::new(Role::TextRun);
4536        node.set_text_direction(accesskit::TextDirection::LeftToRight);
4537        node.set_bounds(accesskit::Rect {
4538            x0: 10.0,
4539            y0: top,
4540            x1: 60.0,
4541            y1: bottom,
4542        });
4543        node
4544    }
4545
4546    /// The top a client truncates out of a run's reported box is a pixel row
4547    /// inside the run's line, a little below its real top, wherever the line
4548    /// starts and whatever the scale; the rest of the box is left alone.
4549    #[test]
4550    fn a_runs_reported_top_truncates_to_a_pixel_row_inside_its_line() {
4551        for scale in [1.0f32, 1.25, 1.5, 1.75, 2.0, 2.25, 3.0] {
4552            let s = f64::from(scale);
4553            for step in 0..400 {
4554                let top = 3.0 + f64::from(step) * 0.173;
4555                let bottom = top + 16.939453;
4556                let mut node = run_at(top, bottom);
4557                snap_text_run_top(&mut node, scale, None);
4558                let rect = node.bounds().unwrap();
4559                // On a monitor left of or above the primary, the client origin
4560                // is negative, and `int()` truncates toward zero.
4561                for client in [0.0, 217.0, -1080.0] {
4562                    let row = (rect.y0 * s + client).trunc() - client;
4563                    assert!(
4564                        row / s > top + 1e-3,
4565                        "scale {scale}, top {top}: row {row} is not below the top"
4566                    );
4567                    assert!(
4568                        row + 1.0 <= bottom * s,
4569                        "scale {scale}, top {top}: row {row} is past the line"
4570                    );
4571                }
4572                assert!(rect.y0 - top <= 1.15 / s, "the box loses at most a pixel");
4573                assert_eq!((rect.x0, rect.x1, rect.y1), (10.0, 60.0, bottom));
4574            }
4575        }
4576    }
4577
4578    /// A run with no whole pixel row inside it (a caret-shaped box) and a
4579    /// vertical run, whose characters are measured from its top, keep the top
4580    /// they were given.
4581    #[test]
4582    fn a_run_too_thin_to_hold_a_pixel_row_or_running_down_keeps_its_top() {
4583        let mut thin = run_at(10.3, 10.3);
4584        snap_text_run_top(&mut thin, 1.5, None);
4585        assert_eq!(thin.bounds().unwrap().y0, 10.3);
4586
4587        let mut vertical = run_at(10.3, 40.0);
4588        vertical.set_text_direction(accesskit::TextDirection::TopToBottom);
4589        snap_text_run_top(&mut vertical, 1.5, None);
4590        assert_eq!(vertical.bounds().unwrap().y0, 10.3);
4591    }
4592
4593    /// A box with an edge that is not a number keeps the top it was given:
4594    /// a snapped finite top on an endless box would pass for a measured one.
4595    #[test]
4596    fn a_run_with_an_edge_that_is_not_a_number_keeps_its_top() {
4597        for bottom in [f64::INFINITY, f64::NAN] {
4598            let mut node = run_at(10.3, bottom);
4599            snap_text_run_top(&mut node, 1.5, None);
4600            assert_eq!(node.bounds().unwrap().y0, 10.3, "bottom {bottom}");
4601        }
4602    }
4603
4604    /// Where the client truncates the reported top to, as a window pixel
4605    /// row: NVDA's `int()` goes toward zero, so on a monitor above or left
4606    /// of the primary (a negative client origin) it rounds up.
4607    fn clicked_row(reported_top: f64, scale: f64, client: f64) -> f64 {
4608        (reported_top * scale + client).trunc() - client
4609    }
4610
4611    /// A line its node cuts down to a sliver at the node's top edge, with
4612    /// room for one pixel row only. Where the client origin is not negative
4613    /// the click lands on that row; where it is, on the row after it, which
4614    /// is the next line but still inside the node. Leaving the top where the
4615    /// line really starts would put both clicks above the node, on whatever
4616    /// widget is there.
4617    #[test]
4618    fn a_sliver_of_a_line_at_the_top_of_its_node_is_clicked_inside_the_node() {
4619        let owner = accesskit::Rect {
4620            x0: 0.0,
4621            y0: 100.0,
4622            x1: 200.0,
4623            y1: 300.0,
4624        };
4625        // The line runs from 90 to 102: two device pixels of it show.
4626        let mut node = run_at(90.0, 102.0);
4627        snap_text_run_top(&mut node, 1.0, Some(owner));
4628        let top = node.bounds().unwrap().y0;
4629
4630        assert_eq!(clicked_row(top, 1.0, 0.0), 101.0, "on the sliver");
4631        assert_eq!(clicked_row(top, 1.0, 217.0), 101.0, "on the sliver");
4632        let below_primary = clicked_row(top, 1.0, -1080.0);
4633        assert_eq!(below_primary, 102.0, "on the next line, as documented");
4634        assert!(
4635            (owner.y0..owner.y1).contains(&below_primary),
4636            "still inside the node"
4637        );
4638    }
4639
4640    /// A line with two whole rows below the margin holds the click for
4641    /// either sign of the client origin, however little of it the node shows.
4642    #[test]
4643    fn a_line_with_two_rows_inside_its_node_holds_the_click_for_any_client_origin() {
4644        for scale in [1.0f32, 1.25, 1.5, 1.75, 2.0, 2.25, 3.0] {
4645            let s = f64::from(scale);
4646            for step in 0..200 {
4647                let owner_top = 100.0 + f64::from(step) * 0.0371;
4648                let owner = accesskit::Rect {
4649                    x0: 0.0,
4650                    y0: owner_top,
4651                    x1: 200.0,
4652                    y1: 400.0,
4653                };
4654                // Just enough of the line shows for two rows past the margin.
4655                let first = (owner_top * s + RUN_TOP_MARGIN).ceil();
4656                let bottom = (first + 2.0) / s;
4657                let mut node = run_at(owner_top - 9.0, bottom);
4658                snap_text_run_top(&mut node, scale, Some(owner));
4659                let top = node.bounds().unwrap().y0;
4660                for client in [0.0, 217.0, -1080.0, -1440.0] {
4661                    let row = clicked_row(top, s, client);
4662                    assert!(
4663                        row / s > owner_top && row + 1.0 <= bottom * s,
4664                        "scale {scale}, node top {owner_top}, client {client}: \
4665                         row {row} is outside the visible line"
4666                    );
4667                }
4668            }
4669        }
4670    }
4671
4672    /// A label laid out at no size, whose measured text runs out of its
4673    /// corner: what a `Grid` cell gives a label it has no room for.
4674    #[derive(Debug)]
4675    struct OverflowingLabel;
4676
4677    impl Widget for OverflowingLabel {
4678        fn layout_response(
4679            &self,
4680            _proposal: SizeProposal,
4681            _ctx: &LayoutContext,
4682        ) -> crate::widget::LayoutResponse {
4683            teksilo_canvas::Size::new(0.0, 0.0).into()
4684        }
4685
4686        fn accessibility(&self, builder: &mut AccessNodeBuilder) {
4687            push_one_letter_line(builder, 16.0, teksilo_canvas::Point::ZERO);
4688        }
4689    }
4690
4691    /// Report a label holding one letter, `A`, on one measured line
4692    /// `height` tall whose top-left is at `origin` in the widget's space.
4693    fn push_one_letter_line(
4694        builder: &mut AccessNodeBuilder,
4695        height: f32,
4696        origin: teksilo_canvas::Point,
4697    ) {
4698        use teksilo_canvas::TextLineSegment;
4699        use teksilo_canvas::{CharGeom, LineEnd, TextDirection, TextGeometry, TextLine};
4700        builder.set_role(accesskit::Role::Label);
4701        let line = TextLine {
4702            index: 0,
4703            byte_range: 0..1,
4704            char_range: 0..1,
4705            rect: [0.0, 0.0, 8.0, height],
4706            baseline: height * 0.75,
4707            caret_x: 0.0,
4708            segments: vec![TextLineSegment {
4709                byte_range: 0..1,
4710                char_range: 0..1,
4711                direction: TextDirection::LeftToRight,
4712                rect: [0.0, 0.0, 8.0, height],
4713                characters: vec![CharGeom {
4714                    position: 0.0,
4715                    width: 8.0,
4716                }],
4717            }],
4718            end: LineEnd::EndOfText,
4719            truncation: None,
4720        };
4721        let geometry = TextGeometry {
4722            lines: vec![line],
4723            dropped_lines: 0,
4724            source_len: 1,
4725            rendered_text: None,
4726            links: Vec::new(),
4727        };
4728        let source = crate::accessibility::text_runs::TextRunSource::from_geometry(
4729            "A", &geometry, origin, 0,
4730        );
4731        crate::accessibility::text_runs::push_text_runs(builder, None, &source);
4732    }
4733
4734    /// A container that gives its child no room, at its own origin.
4735    #[derive(Debug)]
4736    struct NoRoomCell;
4737
4738    impl Widget for NoRoomCell {
4739        fn layout_response(
4740            &self,
4741            proposal: SizeProposal,
4742            _ctx: &LayoutContext,
4743        ) -> crate::widget::LayoutResponse {
4744            proposal.resolve(0.0, 0.0).into()
4745        }
4746
4747        fn place_children(
4748            &self,
4749            bounds: teksilo_canvas::Rect,
4750            _proposal: SizeProposal,
4751            children: &mut [crate::widget::WidgetPlacement],
4752            _ctx: &LayoutContext,
4753        ) {
4754            for child in children.iter_mut() {
4755                child.origin = bounds.origin();
4756                child.size = teksilo_canvas::Size::new(0.0, 0.0);
4757            }
4758        }
4759    }
4760
4761    /// A label whose line is scrolled partly out of it at the top, the way
4762    /// an editor shows the line it has scrolled half past.
4763    #[derive(Debug)]
4764    struct ScrolledLabel {
4765        scrolled_by: f32,
4766    }
4767
4768    impl Widget for ScrolledLabel {
4769        fn layout_response(
4770            &self,
4771            _proposal: SizeProposal,
4772            _ctx: &LayoutContext,
4773        ) -> crate::widget::LayoutResponse {
4774            teksilo_canvas::Size::new(120.0, 40.0).into()
4775        }
4776
4777        fn accessibility(&self, builder: &mut AccessNodeBuilder) {
4778            push_one_letter_line(
4779                builder,
4780                16.94,
4781                teksilo_canvas::Point::new(0.0, -self.scrolled_by),
4782            );
4783        }
4784    }
4785
4786    /// A container that sets its child down `offset` from its own top.
4787    #[derive(Debug)]
4788    struct OffsetCell {
4789        offset: f32,
4790    }
4791
4792    impl Widget for OffsetCell {
4793        fn layout_response(
4794            &self,
4795            proposal: SizeProposal,
4796            _ctx: &LayoutContext,
4797        ) -> crate::widget::LayoutResponse {
4798            proposal.resolve(0.0, 0.0).into()
4799        }
4800
4801        fn place_children(
4802            &self,
4803            bounds: teksilo_canvas::Rect,
4804            _proposal: SizeProposal,
4805            children: &mut [crate::widget::WidgetPlacement],
4806            _ctx: &LayoutContext,
4807        ) {
4808            for child in children.iter_mut() {
4809                child.origin = teksilo_canvas::Point::new(bounds.x, bounds.y + self.offset);
4810                child.size = teksilo_canvas::Size::new(120.0, 40.0);
4811            }
4812        }
4813    }
4814
4815    /// A line its node cuts at the top is clicked on the first pixel row the
4816    /// node shows, not on the row the line really starts on, which is above
4817    /// the node and belongs to whatever widget is there.
4818    #[test]
4819    fn a_line_scrolled_half_out_of_its_node_is_clicked_inside_the_node() {
4820        for scale in [1.0f32, 1.25, 1.5, 1.75, 2.0] {
4821            let s = f64::from(scale);
4822            for (offset, scrolled_by) in [(40.4, 8.3), (17.6, 0.7), (63.0, 12.45)] {
4823                let mut tree = WidgetTree::new();
4824                tree.set_device_scale_factor(scale);
4825                let cell = tree.add(OffsetCell { offset });
4826                let label = tree.add_child(cell, ScrolledLabel { scrolled_by });
4827                tree.layout(SizeProposal::exact(200.0, 200.0));
4828                let node_box = tree.bounds(label);
4829                let node_top = f64::from(node_box.y);
4830                let line_top = node_top - f64::from(scrolled_by);
4831                let line_bottom = line_top + 16.94;
4832
4833                let update = tree.sync_accessibility();
4834                let run = update
4835                    .nodes
4836                    .iter()
4837                    .find(|(_, n)| n.role() == Role::TextRun)
4838                    .map(|(_, n)| n.bounds().unwrap())
4839                    .expect("the label reports a run");
4840                for client in [0.0, 217.0, -1080.0] {
4841                    let row = clicked_row(run.y0, s, client);
4842                    assert!(
4843                        row / s > node_top && (row + 1.0) / s <= line_bottom,
4844                        "scale {scale}, node top {node_top}, client {client}: \
4845                         row {row} is not on the part of the line the node shows"
4846                    );
4847                }
4848                assert!(run.y0 > line_top, "only the reported top moved down");
4849            }
4850        }
4851    }
4852
4853    /// A run that only touches its node's box keeps touching it: the snapped
4854    /// top is a row inside the node too, and a node with no row to give
4855    /// leaves the run's top where it was, rather than a pixel off the node.
4856    #[test]
4857    fn a_label_laid_out_at_no_size_keeps_its_run_on_its_node() {
4858        for scale in [1.0, 1.25, 1.5, 2.0] {
4859            let mut tree = WidgetTree::new();
4860            tree.set_device_scale_factor(scale);
4861            let cell = tree.add(NoRoomCell);
4862            let label = tree.add_child(cell, OverflowingLabel);
4863            tree.layout(SizeProposal::exact(200.0, 100.0));
4864            assert_eq!(tree.bounds(label).width, 0.0, "the label has no size");
4865            let update = tree.sync_accessibility();
4866            assert_eq!(
4867                crate::accessibility::audit::text_range_divergences(&update),
4868                Vec::new(),
4869                "scale {scale}"
4870            );
4871        }
4872    }
4873}