teksilo_core/widget_tree/test_api.rs
1// SPDX-License-Identifier: MPL-2.0
2// SPDX-FileCopyrightText: 2026 FernTech
3
4use super::*;
5
6/// Linear interpolation between two points, `t` in `0.0..=1.0`.
7///
8/// Every multi-sample helper in this module walks its path with this, so the
9/// intermediate positions of a drag, a fling and a pinch are produced by one
10/// rule and a test that counts samples can reason about where each one landed.
11fn lerp_point(from: Point, to: Point, t: f32) -> Point {
12 Point::new(from.x + (to.x - from.x) * t, from.y + (to.y - from.y) * t)
13}
14
15impl WidgetTree {
16 /// The content id of the tooltip anchored at `widget` or anywhere inside
17 /// it.
18 ///
19 /// The attach helpers keep the content id to themselves, so a test that
20 /// needs to drive a tooltip's own surface (promote it, focus into it) has
21 /// no other way to name it. Matching the whole subtree, not just the id,
22 /// is what makes this work for composing controls: `Button` keeps focus on
23 /// its outer node but attaches its tooltip to an inner body root.
24 pub fn tooltip_content_within(&self, widget: WidgetId) -> Option<WidgetId> {
25 self.tooltips
26 .iter()
27 .find(|e| self.is_descendant_of(e.anchor_id, widget))
28 .map(|e| e.content_id)
29 }
30
31 /// Whether that tooltip has been promoted.
32 ///
33 /// Promotion is the line between an informational tip and a panel the user
34 /// asked for: it decides the AT role, the dismiss behaviour, and whether
35 /// the surface takes a Tab stop.
36 pub fn tooltip_is_sticky_within(&self, widget: WidgetId) -> bool {
37 self.tooltips
38 .iter()
39 .any(|e| self.is_descendant_of(e.anchor_id, widget) && e.is_sticky)
40 }
41
42 /// Simulate a click at the center of a widget.
43 pub fn click(&mut self, id: WidgetId) {
44 self.synthesise_tap(id);
45 }
46
47 /// Synthesise a primary-button tap at the center of `id`'s
48 /// resolved bounds. The OS hands the click off to the widget tree
49 /// even though the click never went through the normal hit-test
50 /// path. Used by the Windows custom-title-bar backend when
51 /// `WM_NCHITTEST` reported `HTMINBUTTON`/`HTMAXBUTTON`/`HTCLOSE`
52 /// for an area covering a `ControlButton` — the OS treated the
53 /// area as non-client and `WM_LBUTTONDOWN`/`UP` never fired in
54 /// widget land, so we re-issue a synthetic primary-button down
55 /// + up on the right widget.
56 ///
57 /// Equivalent semantics to [`Self::click`]; named differently so
58 /// production call sites read clearly.
59 ///
60 /// The tap runs on a standalone dispatch, so a handler it reaches
61 /// cannot use the multi-window API. Call
62 /// [`synthesise_tap_with_ops`](Self::synthesise_tap_with_ops) from
63 /// anywhere that already holds a real
64 /// [`WindowOps`](crate::window::WindowOps) sink.
65 pub fn synthesise_tap(&mut self, id: WidgetId) {
66 let mut noop = crate::window::NoopWindowOps;
67 self.synthesise_tap_with_ops(id, &mut noop);
68 }
69
70 /// [`synthesise_tap`](Self::synthesise_tap), dispatched over the
71 /// caller's app-level [`WindowOps`](crate::window::WindowOps) sink.
72 ///
73 /// A synthetic tap is a *nested* dispatch, and everything the tapped
74 /// widget does happens inside it — including the intent it sends and
75 /// the action that intent resolves to. Dispatching it standalone
76 /// therefore hands that action a context with no window sink:
77 /// `ctx.open_window` panics, and `find_window` / `focus_window` /
78 /// `close_window_by_id` silently do nothing. That is how keyboard
79 /// activation in a menu (Enter, Space, a mnemonic, type-ahead — all
80 /// four route through `EventContext::synthetic_click`) lost the
81 /// multi-window API that the same row reached fine by mouse.
82 pub fn synthesise_tap_with_ops(
83 &mut self,
84 id: WidgetId,
85 ops: &mut dyn crate::window::WindowOps,
86 ) {
87 let center = self.arena.bounds(id).center();
88 self.dispatch_event_with_ops(
89 WidgetEvent::pointer_down(center, PointerButton::Primary, Modifiers::NONE),
90 &mut *ops,
91 );
92 self.dispatch_event_with_ops(
93 WidgetEvent::pointer_up(center, PointerButton::Primary, Modifiers::NONE),
94 &mut *ops,
95 );
96 }
97
98 /// Simulate pointer movement to a position.
99 pub fn pointer_move(&mut self, position: Point) {
100 self.dispatch_event(WidgetEvent::pointer_move(position));
101 }
102
103 /// Simulate a key press (down + up), carrying the text the platform
104 /// attaches to the key ([`Key::to_text`]).
105 ///
106 /// That text is not decoration: Escape arrives as U+001B, and a widget
107 /// that inspects `text` behaves differently with it than without. This
108 /// helper used to send `text: None` for every key, so a whole class of
109 /// bug was invisible to every test in the workspace — a field that
110 /// swallowed Escape passed the suite while failing in the user's hands.
111 pub fn press_key(&mut self, key: Key, modifiers: Modifiers) {
112 self.dispatch_event(WidgetEvent::KeyDown {
113 key,
114 modifiers,
115 text: key.to_text().map(str::to_string),
116 });
117 self.dispatch_event(WidgetEvent::KeyUp { key, modifiers });
118 }
119
120 /// Simulate typing text into the focused widget.
121 pub fn type_text(&mut self, _widget: WidgetId, text: &str) {
122 for ch in text.chars() {
123 self.dispatch_event(WidgetEvent::KeyDown {
124 key: Key::Character(ch),
125 modifiers: Modifiers::NONE,
126 text: Some(ch.to_string()),
127 });
128 }
129 }
130
131 /// Simulate a pointer down at a specific position with a specific button.
132 pub fn pointer_down_button(&mut self, position: Point, button: PointerButton) {
133 self.dispatch_event(WidgetEvent::pointer_down(position, button, Modifiers::NONE));
134 }
135
136 /// Simulate a pointer up at a specific position with a specific button.
137 pub fn pointer_up_button(&mut self, position: Point, button: PointerButton) {
138 self.dispatch_event(WidgetEvent::pointer_up(position, button, Modifiers::NONE));
139 }
140
141 /// Simulate a drag from one position to another.
142 pub fn drag(&mut self, from: Point, to: Point) {
143 self.dispatch_event(WidgetEvent::pointer_down(
144 from,
145 PointerButton::Primary,
146 Modifiers::NONE,
147 ));
148 self.dispatch_event(WidgetEvent::pointer_move(to));
149 self.dispatch_event(WidgetEvent::pointer_up(
150 to,
151 PointerButton::Primary,
152 Modifiers::NONE,
153 ));
154 }
155
156 /// Get bounds of a child by index.
157 pub fn child_bounds(&self, parent: WidgetId, index: usize) -> Rect {
158 let children = self.children(parent);
159 self.bounds(children[index])
160 }
161
162 /// Get a child widget ID by index.
163 pub fn child_widget(&self, parent: WidgetId, index: usize) -> WidgetId {
164 self.children(parent)[index]
165 }
166
167 /// Advance this tree's clock by `duration`, and run everything that clock
168 /// drives.
169 ///
170 /// **The one door.** One call moves, to one virtual now: the simulated
171 /// clock, the input timeline, the gesture arenas (today: the long-press
172 /// hold), the press-feedback delays, every live fling, the animation
173 /// scheduler, the frame tick, the overlay manager's clock, tooltip dwell,
174 /// delayed overlays, the pointer-leave grace and overlay auto-dismissal —
175 /// then drains the signal, rebuild and visibility changes any of that
176 /// produced. A caller never has to advance a second thing to keep one of
177 /// those in step with another.
178 ///
179 /// It is not, however, the door to *everything* that is timed; the list
180 /// below is the current boundary, and it is the list that has to grow when
181 /// a subsystem is brought onto this clock.
182 ///
183 /// While this runs, time is **taken over**: the input timeline and the
184 /// animation clock both read the simulated clock and nothing else. A long
185 /// press fires because the caller advanced the hold and never because the
186 /// caller itself took that long; two samples dispatched without an
187 /// intervening advance are stamped the same instant rather than however far
188 /// apart the machine happened to run them; and an animation ages by exactly
189 /// what was advanced. A headless test wants that to persist, and it does. A
190 /// host sharing the tree with a real event loop — the debug automation
191 /// bridge — must give time back when the operation ends, or the window it
192 /// is attached to never measures another gesture and never advances another
193 /// animation frame: see [`resume_real_time`](Self::resume_real_time).
194 ///
195 /// What it does **not** move:
196 ///
197 /// - The shader-driven
198 /// [`AnimatedQuadRegistry`](crate::animated_quad::AnimatedQuadRegistry).
199 /// It is ticked from `render()` and has no simulated door at all.
200 /// - A deferred member's `eligible_at` on a
201 /// [`PointerSequence`](crate::gesture::PointerSequence). Not an
202 /// oversight: eligibility is never stored, it is re-derived against the
203 /// timestamp of whatever sample is being arbitrated, so there is no
204 /// transition to perform at that instant and a press that sat still past
205 /// its `long_press` is already eligible on its very next move. See
206 /// [`PointerSequence::next_hold_deadline`](crate::gesture::PointerSequence::next_hold_deadline).
207 /// A hold's `max_hold`, by contrast, *is* a stored transition and is
208 /// moved — by the gesture pass in (3).
209 /// - Any clock a widget owns itself. A widget that reads the wall clock
210 /// directly rather than taking its deadline from the tree is outside this
211 /// door by construction, and there are several in `teksilo-widgets`.
212 ///
213 /// Dispatched over a no-op window sink; call
214 /// [`advance_time_with_ops`](Self::advance_time_with_ops) from anywhere
215 /// that holds a real one.
216 pub fn advance_time(&mut self, duration: std::time::Duration) {
217 let mut noop = crate::window::NoopWindowOps;
218 self.advance_time_with_ops(duration, &mut noop);
219 }
220
221 /// [`advance_time`](Self::advance_time), over the caller's
222 /// [`WindowOps`](crate::window::WindowOps) sink.
223 ///
224 /// A tick is a dispatch: a long press recognized here runs its handler,
225 /// and that handler may open a window. Standalone,
226 /// [`NoopWindowOps`](crate::window::NoopWindowOps) panics on
227 /// `open_window` — the same trap `synthesise_tap_with_ops` exists for.
228 pub fn advance_time_with_ops(
229 &mut self,
230 duration: std::time::Duration,
231 ops: &mut dyn crate::window::WindowOps,
232 ) {
233 // (0) Take the tree off the wall clock *before* anything reads a
234 // deadline, so this whole call is measured on one axis.
235 self.enter_simulated_mode();
236
237 // (1) Promote before the clock moves. An `animate_to` armed while the
238 // clock read T must start at T; stamping it after the clock reached
239 // T + d starts it d late and the caller's very next assertion is off
240 // by exactly the duration they just advanced.
241 self.process_pending_animations_at(self.sim_clock);
242
243 // (2) The clock itself. A clock that has to be told (a `ManualClock`)
244 // is moved here; an anchored one is read off `sim_clock` by
245 // `input_now`. The overlay manager's mirror must be updated before any
246 // pass below can dismiss, because `OverlayManager::dismiss` stamps the
247 // fade's simulated start from it.
248 self.sim_clock += duration;
249 self.input_clock().advance(duration);
250 self.overlay_manager.set_sim_clock(self.sim_clock);
251
252 // (3) The input layer, in the order the real event loop uses: flings,
253 // then press-feedback delays, then the gesture arenas. `tick_gestures`
254 // owns all three — giving the fling pump its own call site here would
255 // pump every live coast twice per advance.
256 self.tick_gestures_with_ops(self.sim_clock, &mut *ops);
257
258 // (4) The frame tick, and only if one was asked for: an unrequested
259 // advance must not fire the per-frame observers. The delta is the
260 // duration advanced, not a reading of `last_frame_time` — nothing was
261 // rendered, and `last_frame_time` is the *render* pacing reference.
262 if self.frame_tick_requested.get() {
263 self.frame_tick_requested.set(false);
264 let delta = duration.as_secs_f32().clamp(0.0, 0.1);
265 self.frame_tick.set(delta);
266 }
267
268 // (5) Animations, at the new now and after the promotion in (1), so an
269 // animation armed before this call has aged by exactly `duration`.
270 self.animation_scheduler
271 .tick(self.sim_clock, &self.arena, self.paint_epoch);
272
273 // (6) The overlay and tooltip passes, in the order they depend on:
274 // a dwell that ripens can show a tooltip, a delayed overlay that
275 // matures can show a surface, and the dismissal passes below must see
276 // both within this same virtual frame.
277 self.process_tooltips();
278 self.process_delayed_overlays();
279 self.process_pointer_leave_overlays();
280 self.process_auto_dismiss_overlays();
281 self.process_overlay_fade_dismissals_sim();
282
283 // (7) Last, so a signal written by a long-press handler, a coasting
284 // fling's chained scroll or an overlay dismissal is flushed inside the
285 // virtual frame that produced it rather than a frame later.
286 self.process_state_changes(&mut *ops);
287 }
288
289 /// [`advance_time`](Self::advance_time), under the name the input side
290 /// reads better by.
291 ///
292 /// An alias, not a second timeline: there is one clock, and moving the
293 /// input axis is moving it.
294 pub fn advance_input_time(&mut self, duration: std::time::Duration) {
295 self.advance_time(duration);
296 }
297
298 /// Get the current simulated clock value.
299 pub fn simulated_now(&self) -> std::time::Instant {
300 self.sim_clock
301 }
302
303 /// Total number of live tooltip attachments, dead ones included.
304 ///
305 /// Distinct from `pending_tooltip_count`, which only counts entries with a
306 /// running dwell. This is the raw table size — the number that must stay
307 /// flat across rebuilds, since `attach_tooltip*` is called from `build()`
308 /// and the table is scanned on every pointer move, every layout pass and
309 /// once per widget in the accessibility walk.
310 pub fn tooltip_entry_count(&self) -> usize {
311 self.tooltips.len()
312 }
313
314 /// Every widget the arena still holds — active, dormant and orphaned alike.
315 ///
316 /// The number a leak test must assert on. `active_widget_count` walks the
317 /// tree from its roots and so cannot see the failure mode that matters
318 /// here: a node kept alive in the arena with nothing pointing at it. A
319 /// parentless orphan (tooltip content is `ctx.add`ed, hence parentless by
320 /// construction) is invisible to every other count in this file, and to the
321 /// accessibility tree, while still paying for itself in the arena's slotmap
322 /// forever.
323 /// Every node inside `root` (inclusive) that Tab traversal would stop on:
324 /// focusable, and not suppressed by a `tab_stop` flag on itself or any
325 /// ancestor.
326 ///
327 /// Pressing Tab and watching focus cannot answer this for a view that
328 /// claims the key for its own navigation — `TableView` moves a cell cursor
329 /// on Tab, so focus never moves and the traversal graph underneath stays
330 /// invisible. A data view should expose exactly one stop however many rows
331 /// are realized; more than one means a control inside a row has leaked
332 /// into the Tab order, where its presence would track the scroll position.
333 ///
334 /// Membership matches the real collector
335 /// ([`collect_scope_entries`](crate::widget_tree::WidgetTree)) exactly: a
336 /// dormant node and a disabled subtree are both skipped, because Tab
337 /// traversal returns at each. The two differ only in *shape* — the real
338 /// collector groups a `traversal_scope` subtree so it can order it
339 /// independently, and this returns one flat list in tree order — which is
340 /// what a membership assertion wants.
341 ///
342 /// The guards are load-bearing rather than cosmetic. Without them this
343 /// reports stops the traversal never visits, and a test asserting that a
344 /// culled or collapsed subtree left the Tab ring passes or fails for a
345 /// reason unrelated to the mechanism it is pinning.
346 pub fn tab_stops_within(&self, root: WidgetId) -> Vec<WidgetId> {
347 let mut out = Vec::new();
348 self.collect_tab_stops_within(root, &mut out);
349 out
350 }
351
352 fn collect_tab_stops_within(&self, id: WidgetId, out: &mut Vec<WidgetId>) {
353 // Dormant: `collect_scope_entries` returns here, so the whole subtree
354 // is off the traversal graph — a `Switcher`'s hidden branch, a closed
355 // popover, a `visible_when` gate that went false.
356 if !self.arena.is_active(id) {
357 return;
358 }
359 let Some(node) = self.arena.get(id) else {
360 return;
361 };
362 // Disabled: likewise a whole-subtree stop in the real collector.
363 if node
364 .enabled_state
365 .as_ref()
366 .map(|s| !s.get())
367 .unwrap_or(false)
368 {
369 return;
370 }
371 if self.is_node_focusable(node) && self.tab_stop_effective(id) {
372 out.push(id);
373 }
374 for &child in self.arena.children(id) {
375 self.collect_tab_stops_within(child, out);
376 }
377 }
378
379 pub fn widget_count(&self) -> usize {
380 self.arena.len()
381 }
382
383 /// Tear down a widget and everything it owns — its subtree, its tooltip,
384 /// and the parentless content it built with
385 /// [`add_detached`](crate::build_context::BuildContext::add_detached).
386 ///
387 /// The application-facing door is `BuildContext::destroy_subtree`; this is
388 /// the same call for tests that hold the tree directly.
389 pub fn destroy_subtree_for_testing(&mut self, id: WidgetId) {
390 self.destroy_subtree(id);
391 }
392
393 /// Panic unless every trace of a pointer interaction is gone.
394 ///
395 /// The one assertion a touch test ends with. A leak here is not a cosmetic
396 /// untidiness: a surviving capture redelivers every later move to a widget
397 /// nobody is pointing at, a surviving sequence lets a stale competitor win
398 /// the *next* press, and a live recognizer entry starts the next contact
399 /// mid-gesture. All three are silent until something much later
400 /// misbehaves, which is why this is checked rather than reasoned about.
401 ///
402 /// A **hovering** pointer resting in the table is not a leak: a mouse that
403 /// has been seen once keeps its entry for the life of the tree, and that
404 /// entry is what every singular accessor reads. What must not survive is a
405 /// pointer still *contacting* the surface, a capture, a sequence, or a
406 /// gesture arena still following a contact.
407 ///
408 /// One thing the design lists is still absent: the touch-motion layer's own
409 /// state — live pans, coasts, the window's pinch and the palm watches. The
410 /// framework press *is* checked, at the bottom of this function.
411 pub fn assert_no_leaked_pointer_state(&self) {
412 let mut leaks: Vec<String> = Vec::new();
413 for entry in self.pointers.iter() {
414 let id = entry.info.id;
415 if entry.is_contacting() {
416 leaks.push(format!(
417 "{id:?} ({:?}) is still contacting the surface",
418 entry.info.kind
419 ));
420 }
421 if let Some(captor) = entry.captured_by {
422 leaks.push(format!("{id:?} still captures {captor:?}"));
423 }
424 if let Some(sequence) = entry.sequence.as_ref() {
425 leaks.push(format!(
426 "{id:?} still has a sequence ({} member(s), winner {:?})",
427 sequence.members().len(),
428 sequence.winner()
429 ));
430 }
431 }
432 for &owner in &self.gesture_owners {
433 if self
434 .arena
435 .get(owner)
436 .and_then(|node| node.handlers.gesture_arena.as_ref())
437 .is_some_and(|set| set.is_live())
438 {
439 leaks.push(format!(
440 "{owner:?} has a gesture arena still following a contact"
441 ));
442 }
443 }
444 // The framework press. Every exit — a release, a cancel, a peer claim —
445 // goes through `end_press`, so a surviving record means one of them was
446 // missed and some node is painted as held by a pointer that is gone.
447 for id in self.arena.active_ids_iter() {
448 if let Some(pointer) = self.pressed_by(id) {
449 leaks.push(format!("{id:?} is still pressed by {pointer:?}"));
450 }
451 }
452 assert!(
453 leaks.is_empty(),
454 "pointer state leaked after the interaction:\n - {}",
455 leaks.join("\n - ")
456 );
457 }
458
459 // ---------------------------------------------------------------
460 // A21 — driving touch and pen from a test
461 // ---------------------------------------------------------------
462 //
463 // Every helper below builds a `PointerSample` in exactly the shape
464 // `teksilo-platform`'s translator builds one (`event_translation.rs`:
465 // a contact holds `ButtonMask::PRIMARY` while it is down and reports
466 // `Some(PointerButton::Primary)` on the two phases that change a
467 // button; a stylus adds its axes) and pushes it through
468 // `dispatch_pointer`, the one ingress door. Nothing here fabricates a
469 // `WidgetEvent`: a helper that stepped around the router would test
470 // the helper rather than the framework, and the hit-test-by-kind, the
471 // sequence, the pan session, the palm watch and the pinch feed all
472 // hang off that door.
473 //
474 // Every one of them puts the tree on the **simulated clock** first, and
475 // then stamps its sample from [`input_now`](Self::input_now). Both halves
476 // are load-bearing: a tree still on the wall clock stamps two consecutive
477 // samples microseconds apart, so a `touch_drag` that means "travel 200 dp,
478 // no time passes" would instead describe a flick at some thousands of dp
479 // per second and hand off to a coast — differently on every machine. Once
480 // simulated, the interval between two samples is exactly what
481 // [`advance_input_time`](Self::advance_input_time) put there and nothing
482 // else, which is what the rest of P14 is for.
483
484 /// Mint a fresh contact identity, the way the platform layer does.
485 ///
486 /// A backend reuses its own contact ids the moment a finger lifts, so
487 /// the allocator mints a `PointerId` per press; this is that call with
488 /// a per-process os id, and it `end`s the mapping immediately so the
489 /// allocator's live table does not grow across a test run.
490 pub fn new_contact(&self) -> crate::pointer::PointerId {
491 use std::sync::atomic::{AtomicU64, Ordering};
492 static NEXT_OS_ID: AtomicU64 = AtomicU64::new(1);
493 let device = crate::pointer::BackendDeviceKey::new(0x7E57);
494 let os_id = NEXT_OS_ID.fetch_add(1, Ordering::Relaxed);
495 let alloc = crate::pointer::PointerIdAllocator::global();
496 let id = alloc.begin(device, os_id);
497 alloc.end(device, os_id);
498 id
499 }
500
501 /// One direct-pointer sample, stamped on this tree's input timeline.
502 ///
503 /// `pub(super)` so a sibling module's tests can dispatch a contact of a kind
504 /// the A21 helpers do not name — `touch_down` and `pen_down` cover the two
505 /// kinds an application sees, and a gate that must refuse
506 /// [`PointerKind::Unknown`](teksilo_tokens::PointerKind::Unknown) can only be
507 /// tested by asking for one.
508 pub(super) fn direct_sample(
509 &self,
510 id: crate::pointer::PointerId,
511 kind: teksilo_tokens::PointerKind,
512 phase: crate::pointer::PointerPhase,
513 at: Point,
514 down: bool,
515 ) -> crate::pointer::PointerSample {
516 use crate::pointer::PointerPhase;
517
518 let mut pointer = crate::pointer::PointerInfo::touch(id, self.input_now());
519 pointer.kind = kind;
520 pointer.buttons = if down {
521 crate::event::ButtonMask::PRIMARY
522 } else {
523 crate::event::ButtonMask::NONE
524 };
525 crate::pointer::PointerSample {
526 pointer,
527 phase,
528 position: at,
529 // The translator reports a button only where one changed.
530 button: match phase {
531 PointerPhase::Down | PointerPhase::Up => Some(PointerButton::Primary),
532 PointerPhase::Move | PointerPhase::Cancel => None,
533 },
534 modifiers: Modifiers::NONE,
535 coalesced: Vec::new(),
536 }
537 }
538
539 /// A finger lands at `at`.
540 pub fn touch_down(&mut self, pointer: crate::pointer::PointerId, at: Point) {
541 self.enter_simulated_mode();
542 let sample = self.direct_sample(
543 pointer,
544 teksilo_tokens::PointerKind::Touch,
545 crate::pointer::PointerPhase::Down,
546 at,
547 true,
548 );
549 self.dispatch_pointer(sample);
550 }
551
552 /// That finger moves to `at`, still down.
553 pub fn touch_move(&mut self, pointer: crate::pointer::PointerId, at: Point) {
554 self.enter_simulated_mode();
555 let sample = self.direct_sample(
556 pointer,
557 teksilo_tokens::PointerKind::Touch,
558 crate::pointer::PointerPhase::Move,
559 at,
560 true,
561 );
562 self.dispatch_pointer(sample);
563 }
564
565 /// That finger lifts at `at`.
566 pub fn touch_up(&mut self, pointer: crate::pointer::PointerId, at: Point) {
567 self.enter_simulated_mode();
568 let sample = self.direct_sample(
569 pointer,
570 teksilo_tokens::PointerKind::Touch,
571 crate::pointer::PointerPhase::Up,
572 at,
573 false,
574 );
575 self.dispatch_pointer(sample);
576 }
577
578 /// The system revokes that finger (a `wl_touch.cancel`, a compositor
579 /// grab). Not an [`touch_up`](Self::touch_up): the end position carries
580 /// no meaning and no tap is completed.
581 pub fn touch_cancel(&mut self, pointer: crate::pointer::PointerId, at: Point) {
582 self.enter_simulated_mode();
583 let sample = self.direct_sample(
584 pointer,
585 teksilo_tokens::PointerKind::Touch,
586 crate::pointer::PointerPhase::Cancel,
587 at,
588 false,
589 );
590 self.dispatch_pointer(sample);
591 }
592
593 /// The live stylus's identity, minting one if the pen has not been seen.
594 ///
595 /// A stylus is singular and it *hovers*, so its table entry outlives a
596 /// lift the way a mouse's does — which is exactly what lets the pen
597 /// helpers take no id and still address one continuous session.
598 fn pen_id(&mut self) -> crate::pointer::PointerId {
599 self.pointers
600 .iter()
601 .find(|e| matches!(e.info.kind, teksilo_tokens::PointerKind::Pen(_)))
602 .map(|e| e.info.id)
603 .unwrap_or_else(|| self.new_contact())
604 }
605
606 /// One stylus sample: the direct-pointer shape plus the axes a digitizer
607 /// reports.
608 fn pen_sample(
609 &mut self,
610 phase: crate::pointer::PointerPhase,
611 at: Point,
612 pressure: Option<f32>,
613 tilt: Option<(f32, f32)>,
614 down: bool,
615 ) -> crate::pointer::PointerSample {
616 self.enter_simulated_mode();
617 let id = self.pen_id();
618 let mut sample = self.direct_sample(
619 id,
620 teksilo_tokens::PointerKind::Pen(teksilo_tokens::PenKind::default()),
621 phase,
622 at,
623 down,
624 );
625 sample.pointer.axes.pressure = pressure;
626 sample.pointer.axes.tilt = tilt;
627 sample
628 }
629
630 /// The stylus tip touches down at `at`.
631 ///
632 /// `pressure` is normalised `0.0..=1.0`; `tilt` is `(tilt_x, tilt_y)` in
633 /// degrees. Both are the axes a real digitizer reports, so a surface that
634 /// reads [`PointerInfo::effective_pressure`](crate::pointer::PointerInfo::effective_pressure)
635 /// sees what it would see from hardware.
636 pub fn pen_down(&mut self, at: Point, pressure: f32, tilt: (f32, f32)) {
637 let sample = self.pen_sample(
638 crate::pointer::PointerPhase::Down,
639 at,
640 Some(pressure),
641 Some(tilt),
642 true,
643 );
644 self.dispatch_pointer(sample);
645 }
646
647 /// The stylus draws to `at`, still on the surface.
648 pub fn pen_move(&mut self, at: Point, pressure: f32, tilt: (f32, f32)) {
649 let sample = self.pen_sample(
650 crate::pointer::PointerPhase::Move,
651 at,
652 Some(pressure),
653 Some(tilt),
654 true,
655 );
656 self.dispatch_pointer(sample);
657 }
658
659 /// The stylus lifts off at `at`. It stays in proximity — a pen hovers,
660 /// so its entry survives the lift and the next `pen_move` continues the
661 /// same session.
662 pub fn pen_up(&mut self, at: Point, pressure: f32, tilt: (f32, f32)) {
663 let sample = self.pen_sample(
664 crate::pointer::PointerPhase::Up,
665 at,
666 Some(pressure),
667 Some(tilt),
668 false,
669 );
670 self.dispatch_pointer(sample);
671 }
672
673 /// The stylus moves in proximity without touching: no tip pressure, no
674 /// button. The one direct-pointer hover in the framework.
675 pub fn pen_hover(&mut self, at: Point) {
676 let sample = self.pen_sample(
677 crate::pointer::PointerPhase::Move,
678 at,
679 Some(0.0),
680 None,
681 false,
682 );
683 self.dispatch_pointer(sample);
684 }
685
686 /// A complete press-and-release at `at` by the named device, and the
687 /// identity it used.
688 ///
689 /// The mouse arm is [`PointerId::MOUSE`](crate::pointer::PointerId::MOUSE)
690 /// and the legacy `PointerDown`/`PointerUp` pair, so
691 /// `tap_with(PointerKind::Mouse, ..)` is the pre-touch-programme click
692 /// with a position rather than a widget id.
693 pub fn tap_with(
694 &mut self,
695 kind: teksilo_tokens::PointerKind,
696 at: Point,
697 ) -> crate::pointer::PointerId {
698 match kind {
699 teksilo_tokens::PointerKind::Touch => {
700 let id = self.new_contact();
701 self.touch_down(id, at);
702 self.touch_up(id, at);
703 id
704 }
705 teksilo_tokens::PointerKind::Pen(_) => {
706 self.pen_down(at, 0.5, (0.0, 0.0));
707 let id = self.pen_id();
708 self.pen_up(at, 0.0, (0.0, 0.0));
709 id
710 }
711 _ => {
712 self.enter_simulated_mode();
713 self.pointer_down_button(at, PointerButton::Primary);
714 self.pointer_up_button(at, PointerButton::Primary);
715 crate::pointer::PointerId::MOUSE
716 }
717 }
718 }
719
720 /// Press at `at`, hold for exactly the kind's `long_press`, release.
721 ///
722 /// The hold comes from the active profile rather than a constant written
723 /// here, and it is advanced *exactly* — the recognizer fires at
724 /// `>= hold`, so a helper that added a safety margin would stop the
725 /// threshold itself from ever being asserted.
726 pub fn long_press_at(
727 &mut self,
728 kind: teksilo_tokens::PointerKind,
729 at: Point,
730 ) -> crate::pointer::PointerId {
731 let hold = self.effective_theme.input.profile(kind).long_press;
732 let id = match kind {
733 teksilo_tokens::PointerKind::Touch => {
734 let id = self.new_contact();
735 self.touch_down(id, at);
736 id
737 }
738 teksilo_tokens::PointerKind::Pen(_) => {
739 self.pen_down(at, 0.5, (0.0, 0.0));
740 self.pen_id()
741 }
742 _ => {
743 self.enter_simulated_mode();
744 self.pointer_down_button(at, PointerButton::Primary);
745 crate::pointer::PointerId::MOUSE
746 }
747 };
748 self.advance_input_time(hold);
749 match kind {
750 teksilo_tokens::PointerKind::Touch => self.touch_up(id, at),
751 teksilo_tokens::PointerKind::Pen(_) => self.pen_up(at, 0.0, (0.0, 0.0)),
752 _ => self.pointer_up_button(at, PointerButton::Primary),
753 }
754 id
755 }
756
757 /// One finger from `from` to `to` in `steps` evenly spaced moves, then a
758 /// lift. Returns the contact's identity, so the caller can ask
759 /// [`sequence_winner`](Self::sequence_winner) about it.
760 ///
761 /// The clock does **not** move: this is a drag, and a drag is decided by
762 /// distance. Use [`fling`](Self::fling) when the speed is the point.
763 pub fn touch_drag(
764 &mut self,
765 from: Point,
766 to: Point,
767 steps: usize,
768 ) -> crate::pointer::PointerId {
769 let id = self.new_contact();
770 self.touch_down(id, from);
771 let steps = steps.max(1);
772 for step in 1..=steps {
773 let t = step as f32 / steps as f32;
774 self.touch_move(id, lerp_point(from, to, t));
775 }
776 self.touch_up(id, to);
777 id
778 }
779
780 /// One finger from `from` to `to` over `over` of simulated time, released
781 /// while still moving — the shape a coast is handed off from.
782 ///
783 /// Sampled at [`FLING_SAMPLE_INTERVAL`](Self::FLING_SAMPLE_INTERVAL) so
784 /// the velocity tracker sees gaps under its `STOP_GAP` and at least its
785 /// `MIN_SAMPLE_SIZE` of them; a flick described by two far-apart samples
786 /// yields no velocity at all and would silently never fling.
787 pub fn fling(
788 &mut self,
789 from: Point,
790 to: Point,
791 over: std::time::Duration,
792 ) -> crate::pointer::PointerId {
793 let interval = Self::FLING_SAMPLE_INTERVAL;
794 let steps = (over.as_secs_f64() / interval.as_secs_f64()).ceil() as usize;
795 let steps = steps.max(crate::kinetic::MIN_SAMPLE_SIZE);
796 let per_step = over / steps as u32;
797
798 let id = self.new_contact();
799 self.touch_down(id, from);
800 for step in 1..=steps {
801 self.advance_input_time(per_step);
802 let t = step as f32 / steps as f32;
803 self.touch_move(id, lerp_point(from, to, t));
804 }
805 self.touch_up(id, to);
806 id
807 }
808
809 /// The cadence [`fling`](Self::fling) samples at: one 60 Hz frame, which
810 /// is under the velocity tracker's `STOP_GAP` and therefore never splits
811 /// a flick into two unrelated runs.
812 pub const FLING_SAMPLE_INTERVAL: std::time::Duration = std::time::Duration::from_micros(16_667);
813
814 /// Two fingers, from `a0`/`b0` to `a1`/`b1` in `steps` moves, then both
815 /// lift. Returns their identities in the order they landed.
816 ///
817 /// Both contacts are down before either moves, which is what a pinch
818 /// needs: the recognizer's reference span is the distance between the two
819 /// landings.
820 pub fn pinch(
821 &mut self,
822 a0: Point,
823 b0: Point,
824 a1: Point,
825 b1: Point,
826 steps: usize,
827 ) -> (crate::pointer::PointerId, crate::pointer::PointerId) {
828 let a = self.new_contact();
829 let b = self.new_contact();
830 self.touch_down(a, a0);
831 self.touch_down(b, b0);
832 let steps = steps.max(1);
833 for step in 1..=steps {
834 let t = step as f32 / steps as f32;
835 self.touch_move(a, lerp_point(a0, a1, t));
836 self.touch_move(b, lerp_point(b0, b1, t));
837 }
838 self.touch_up(a, a1);
839 self.touch_up(b, b1);
840 (a, b)
841 }
842
843 /// Switch the active [`TargetDensity`](teksilo_tokens::TargetDensity).
844 ///
845 /// The name A21 gives [`set_input_density`](Self::set_input_density); an
846 /// alias, because density is one setting and there is one door to it.
847 pub fn set_density(&mut self, density: teksilo_tokens::TargetDensity) {
848 self.set_input_density(density);
849 }
850
851 /// The [`TouchAction`](crate::pointer::touch_action::TouchAction) in force
852 /// at `id`: the intersection of every declaration from the root down to
853 /// it.
854 ///
855 /// This is what a press landing on `id` would *freeze*. Distinct from
856 /// [`sequence_touch_action`](Self::sequence_touch_action), which reports
857 /// what a press already in flight froze — the two differ the moment a
858 /// widget changes its declaration mid-press, which is the whole reason
859 /// the value is frozen.
860 pub fn touch_action_for(&self, id: WidgetId) -> crate::pointer::touch_action::TouchAction {
861 self.effective_touch_action(id)
862 }
863
864 /// Mark a widget as needing repaint.
865 pub fn mark_needs_paint(&mut self, id: WidgetId) {
866 self.arena.mark_needs_paint(id);
867 }
868
869 /// Set a widget subtree as dormant.
870 ///
871 /// Goes through the tree's cancel-aware parking door, so a pointer working
872 /// inside the subtree is cancelled rather than stranded on a widget the
873 /// dispatcher will no longer reach.
874 pub fn set_dormant(&mut self, id: WidgetId) {
875 self.park_subtree(id);
876 self.arena.mark_ancestors_need_layout(id);
877 self.cached_frame = None;
878 self.a11y_dirty = true;
879 }
880
881 /// Activate a dormant widget subtree.
882 pub fn activate(&mut self, id: WidgetId) {
883 self.arena.activate(id);
884 self.arena.mark_ancestors_need_layout(id);
885 self.cached_frame = None;
886 self.a11y_dirty = true;
887 }
888
889 /// Invalidate all per-widget paint caches (paint AND post-paint) and
890 /// the assembled frame cache. Forces every widget to repaint on the
891 /// next `render()` call. Used by the glyph-atlas eviction recovery:
892 /// after an eviction, any retained frame may hold quads whose atlas
893 /// UVs now point at recycled slots.
894 pub fn invalidate_all_paints(&mut self) {
895 for id in self.arena.active_ids() {
896 if let Some(node) = self.arena.get_mut(id) {
897 node.dirty.needs_paint = true;
898 node.cached_paint = None;
899 node.cached_post_paint = None;
900 }
901 }
902 self.cached_frame = None;
903 }
904}
905
906#[cfg(test)]
907mod tests {
908 use super::*;
909 use crate::signal::Signal;
910 use crate::test_widgets::{FillWidget, InsetWidget, StackWidget};
911 use crate::widget_builder::WidgetBuilder;
912
913 #[test]
914 fn child_bounds_helper() {
915 let mut tree = WidgetTree::new();
916 let child = tree.add(FillWidget::new());
917 let parent = tree.add(InsetWidget::new(5.0).set_child(child));
918 tree.layout(SizeProposal::exact(100.0, 50.0));
919 let child_bounds = tree.child_bounds(parent, 0);
920 assert_eq!(child_bounds.x, 5.0);
921 }
922
923 #[test]
924 fn signal_get_set_and_derived() {
925 let text = Signal::new(String::new());
926 let is_empty = text.map(|value| value.is_empty());
927 assert!(is_empty.get());
928 text.set("hello".to_string());
929 assert!(!is_empty.get());
930 }
931
932 #[test]
933 fn advance_time_updates_simulated_clock() {
934 let mut tree = WidgetTree::new();
935 let start = tree.simulated_now();
936
937 tree.advance_time(std::time::Duration::from_millis(500));
938 let end = tree.simulated_now();
939
940 assert_eq!(
941 end.duration_since(start),
942 std::time::Duration::from_millis(500)
943 );
944 }
945
946 #[test]
947 fn animate_to_interpolates_over_time() {
948 let mut tree = WidgetTree::new();
949 let owner = tree.add(FillWidget::new());
950 let signal = Signal::<f32>::new_animated(0.0);
951 tree.register_animated_signal(&signal, owner);
952
953 signal.animate_to(
954 100.0,
955 std::time::Duration::from_millis(200),
956 teksilo_tokens::Easing::Linear,
957 );
958
959 tree.tick_animations(std::time::Duration::from_millis(100));
960 assert!(
961 (signal.get() - 50.0).abs() < 2.0,
962 "at 50%: {}",
963 signal.get()
964 );
965
966 tree.tick_animations(std::time::Duration::from_millis(100));
967 assert!(
968 (signal.get() - 100.0).abs() < 0.1,
969 "at 100%: {}",
970 signal.get()
971 );
972
973 assert!(!tree.has_active_animations());
974 }
975
976 #[test]
977 fn animate_to_with_easing() {
978 let mut tree = WidgetTree::new();
979 let owner = tree.add(FillWidget::new());
980 let signal = Signal::<f32>::new_animated(0.0);
981 tree.register_animated_signal(&signal, owner);
982
983 signal.animate_to(
984 100.0,
985 std::time::Duration::from_millis(200),
986 teksilo_tokens::Easing::EaseIn,
987 );
988
989 tree.tick_animations(std::time::Duration::from_millis(100));
990 assert!(
991 (signal.get() - 25.0).abs() < 2.0,
992 "ease-in at 50%: {}",
993 signal.get()
994 );
995 }
996
997 #[test]
998 fn animate_to_replaces_in_flight() {
999 let mut tree = WidgetTree::new();
1000 let owner = tree.add(FillWidget::new());
1001 let signal = Signal::<f32>::new_animated(0.0);
1002 tree.register_animated_signal(&signal, owner);
1003
1004 signal.animate_to(
1005 100.0,
1006 std::time::Duration::from_millis(200),
1007 teksilo_tokens::Easing::Linear,
1008 );
1009 tree.tick_animations(std::time::Duration::from_millis(100));
1010 assert!((signal.get() - 50.0).abs() < 2.0);
1011
1012 signal.animate_to(
1013 0.0,
1014 std::time::Duration::from_millis(100),
1015 teksilo_tokens::Easing::Linear,
1016 );
1017 tree.tick_animations(std::time::Duration::from_millis(50));
1018 assert!(
1019 (signal.get() - 25.0).abs() < 3.0,
1020 "mid-replace: {}",
1021 signal.get()
1022 );
1023
1024 tree.tick_animations(std::time::Duration::from_millis(50));
1025 assert!(
1026 (signal.get() - 0.0).abs() < 0.5,
1027 "end-replace: {}",
1028 signal.get()
1029 );
1030 }
1031
1032 #[test]
1033 fn animation_marks_widgets_dirty() {
1034 let mut tree = WidgetTree::new();
1035 let widget = tree.add(FillWidget::new());
1036 let signal = Signal::<f32>::new_animated(100.0);
1037 tree.register_animated_signal(&signal, widget);
1038
1039 signal.bind_to(
1040 widget,
1041 tree.binding_registry(),
1042 crate::binding::BindingLevel::Relayout,
1043 );
1044
1045 tree.layout(SizeProposal::exact(200.0, 100.0));
1046
1047 signal.animate_to(
1048 0.0,
1049 std::time::Duration::from_millis(100),
1050 teksilo_tokens::Easing::Linear,
1051 );
1052
1053 tree.tick_animations(std::time::Duration::from_millis(50));
1054 assert!(tree.needs_redraw());
1055 }
1056
1057 // -----------------------------------------------------------------
1058 // A21 — the touch / pen helpers
1059 // -----------------------------------------------------------------
1060
1061 /// A finger holds `ButtonMask::PRIMARY` for as long as it is down.
1062 ///
1063 /// Normative, not cosmetic: every `accept_buttons` recognizer in the
1064 /// framework gates on `PRIMARY`, so a helper that reported an empty mask
1065 /// would make tap, drag, long-press and multi-tap invisible to a contact —
1066 /// and every touch test in the workspace would then be testing a device the
1067 /// platform layer does not produce (`event_translation.rs` sets the same
1068 /// mask).
1069 #[test]
1070 fn a_touch_helper_reports_the_primary_button_while_it_is_down() {
1071 use std::cell::RefCell;
1072 use std::rc::Rc;
1073
1074 let seen: Rc<RefCell<Vec<(crate::event::ButtonMask, bool)>>> =
1075 Rc::new(RefCell::new(Vec::new()));
1076 let log = seen.clone();
1077 let mut tree = WidgetTree::new();
1078 tree.add(FillWidget::new().on_pointer_event(move |_event, ctx| {
1079 let p = ctx.pointer();
1080 log.borrow_mut().push((p.buttons, p.kind.is_coarse()));
1081 crate::event::EventResponse::Ignored
1082 }));
1083 tree.layout(SizeProposal::exact(100.0, 100.0));
1084
1085 let finger = tree.new_contact();
1086 let at = Point::new(50.0, 50.0);
1087 tree.touch_down(finger, at);
1088 tree.touch_move(finger, Point::new(60.0, 50.0));
1089 tree.touch_up(finger, Point::new(60.0, 50.0));
1090
1091 let seen = seen.borrow();
1092 assert!(
1093 seen.iter().all(|(_, coarse)| *coarse),
1094 "all three are a finger"
1095 );
1096 assert_eq!(
1097 seen.iter().map(|(b, _)| *b).collect::<Vec<_>>(),
1098 vec![
1099 crate::event::ButtonMask::PRIMARY,
1100 crate::event::ButtonMask::PRIMARY,
1101 crate::event::ButtonMask::NONE,
1102 ],
1103 "down and move hold PRIMARY; the lift reports none"
1104 );
1105 tree.assert_no_leaked_pointer_state();
1106 }
1107
1108 /// The stylus helpers carry the axes a digitizer reports, and a hover
1109 /// carries neither a button nor tip pressure.
1110 #[test]
1111 fn the_pen_helpers_carry_pressure_and_tilt_and_hover_carries_neither() {
1112 use std::cell::RefCell;
1113 use std::rc::Rc;
1114
1115 type Sample = (
1116 Option<f32>,
1117 Option<(f32, f32)>,
1118 crate::event::ButtonMask,
1119 f32,
1120 );
1121 let seen: Rc<RefCell<Vec<Sample>>> = Rc::new(RefCell::new(Vec::new()));
1122 let log = seen.clone();
1123 let mut tree = WidgetTree::new();
1124 tree.add(FillWidget::new().on_pointer_event(move |_event, ctx| {
1125 let p = ctx.pointer();
1126 log.borrow_mut().push((
1127 p.axes.pressure,
1128 p.axes.tilt,
1129 p.buttons,
1130 p.effective_pressure(),
1131 ));
1132 crate::event::EventResponse::Ignored
1133 }));
1134 tree.layout(SizeProposal::exact(100.0, 100.0));
1135
1136 tree.pen_hover(Point::new(40.0, 40.0));
1137 tree.pen_down(Point::new(50.0, 50.0), 0.75, (12.0, -30.0));
1138 tree.pen_up(Point::new(50.0, 50.0), 0.0, (12.0, -30.0));
1139
1140 let seen = seen.borrow();
1141 assert_eq!(
1142 seen[0],
1143 (Some(0.0), None, crate::event::ButtonMask::NONE, 0.0),
1144 "a hover reports no tilt, no button and no tip pressure"
1145 );
1146 assert_eq!(
1147 seen[1],
1148 (
1149 Some(0.75),
1150 Some((12.0, -30.0)),
1151 crate::event::ButtonMask::PRIMARY,
1152 0.75
1153 ),
1154 "the tip's pressure and tilt reach the handler"
1155 );
1156 assert_eq!(
1157 seen[2].2,
1158 crate::event::ButtonMask::NONE,
1159 "the lift holds nothing"
1160 );
1161 tree.assert_no_leaked_pointer_state();
1162 }
1163
1164 /// A pen keeps one identity across a lift: it hovers, so its entry outlives
1165 /// the tip leaving the surface and the helpers address one session.
1166 #[test]
1167 fn the_pen_helpers_address_one_session_across_a_lift() {
1168 let mut tree = WidgetTree::new();
1169 tree.add(FillWidget::new().on_tap(|_e, _c| {}));
1170 tree.layout(SizeProposal::exact(100.0, 100.0));
1171
1172 tree.pen_down(Point::new(50.0, 50.0), 0.5, (0.0, 0.0));
1173 let first = tree
1174 .live_pointers()
1175 .find(|p| matches!(p.kind, teksilo_tokens::PointerKind::Pen(_)))
1176 .map(|p| p.id)
1177 .expect("the pen was admitted");
1178 tree.pen_up(Point::new(50.0, 50.0), 0.0, (0.0, 0.0));
1179 tree.pen_hover(Point::new(60.0, 50.0));
1180 let second = tree
1181 .live_pointers()
1182 .find(|p| matches!(p.kind, teksilo_tokens::PointerKind::Pen(_)))
1183 .map(|p| p.id)
1184 .expect("the pen is still in proximity");
1185 assert_eq!(first, second, "one stylus, one identity");
1186 }
1187
1188 /// A test scrollable: the vertical `scroll_container` claim — kinetic, as
1189 /// `ScrollArea`'s is, since a claim that is not kinetic never hands off to
1190 /// a coast — plus the `on_scroll` contract `teksilo-widgets` implements:
1191 /// absorb and answer `Handled`.
1192 fn flingable(offset: crate::signal::Signal<f32>) -> impl Widget + 'static {
1193 FillWidget::new()
1194 .scroll_container(crate::pointer::touch_action::PanAxes::Y)
1195 .on_scroll(move |event, _ctx| {
1196 let crate::event::WidgetEvent::Scroll { delta, .. } = event else {
1197 return crate::event::EventResponse::Ignored;
1198 };
1199 let dy = match *delta {
1200 crate::event::ScrollDelta::Pixels { y, .. } => y,
1201 crate::event::ScrollDelta::Lines { y, .. } => y * 20.0,
1202 };
1203 offset.set((offset.get() + dy).clamp(0.0, 10_000.0));
1204 crate::event::EventResponse::Handled
1205 })
1206 }
1207
1208 /// `fling` hands off to a coast and `touch_drag` over the same path does
1209 /// not.
1210 ///
1211 /// The pair is the assertion: both travel the same distance, and only the
1212 /// one that spends simulated time between its samples produces a velocity.
1213 /// A `fling` helper that forgot to advance the clock would still pan the
1214 /// scroller, so asserting the scroll alone would not notice.
1215 #[test]
1216 fn fling_coasts_where_the_same_drag_does_not() {
1217 let offset = crate::signal::Signal::new(0.0_f32);
1218 let mut tree = WidgetTree::new();
1219 let scroller = tree.add(flingable(offset.clone()));
1220 tree.layout(SizeProposal::exact(200.0, 400.0));
1221
1222 tree.touch_drag(Point::new(100.0, 300.0), Point::new(100.0, 100.0), 8);
1223 assert!(offset.get() > 0.0, "the drag scrolled: {}", offset.get());
1224 assert!(
1225 !tree.is_flinging(scroller),
1226 "…but a drag with no time between its samples has no velocity"
1227 );
1228 tree.assert_no_leaked_pointer_state();
1229
1230 let offset = crate::signal::Signal::new(0.0_f32);
1231 let mut tree = WidgetTree::new();
1232 let scroller = tree.add(flingable(offset.clone()));
1233 tree.layout(SizeProposal::exact(200.0, 400.0));
1234
1235 tree.fling(
1236 Point::new(100.0, 300.0),
1237 Point::new(100.0, 100.0),
1238 std::time::Duration::from_millis(50),
1239 );
1240 assert!(
1241 tree.is_flinging(scroller),
1242 "200 dp in 50 ms is a flick and hands off to a coast"
1243 );
1244 let at_release = offset.get();
1245 tree.advance_time(std::time::Duration::from_millis(100));
1246 assert!(
1247 offset.get() > at_release,
1248 "and the one clock moves it: {at_release} -> {}",
1249 offset.get()
1250 );
1251 }
1252
1253 /// `pinch` produces a real two-contact pinch stream through the single
1254 /// ingress.
1255 #[test]
1256 fn pinch_drives_a_two_contact_pinch() {
1257 use std::cell::RefCell;
1258 use std::rc::Rc;
1259
1260 let phases: Rc<RefCell<Vec<&'static str>>> = Rc::new(RefCell::new(Vec::new()));
1261 let log = phases.clone();
1262 let mut tree = WidgetTree::new();
1263 tree.add(FillWidget::new().on_pinch(move |phase, _ctx| {
1264 log.borrow_mut().push(match phase {
1265 crate::gesture::PinchPhase::Started { .. } => "started",
1266 crate::gesture::PinchPhase::Changed { .. } => "changed",
1267 crate::gesture::PinchPhase::Ended { .. } => "ended",
1268 crate::gesture::PinchPhase::Cancelled { .. } => "cancelled",
1269 });
1270 }));
1271 tree.layout(SizeProposal::exact(400.0, 400.0));
1272
1273 tree.pinch(
1274 Point::new(180.0, 200.0),
1275 Point::new(220.0, 200.0),
1276 Point::new(100.0, 200.0),
1277 Point::new(300.0, 200.0),
1278 6,
1279 );
1280
1281 let phases = phases.borrow();
1282 assert!(
1283 phases.contains(&"started"),
1284 "the spread started a pinch: {phases:?}"
1285 );
1286 assert!(
1287 phases.contains(&"changed"),
1288 "…and reported its changes: {phases:?}"
1289 );
1290 tree.assert_no_leaked_pointer_state();
1291 }
1292
1293 /// `long_press_at` holds for exactly the profile's `long_press` — not a
1294 /// millisecond more.
1295 ///
1296 /// The recognizer fires at `>= hold`, so holding for exactly it is what
1297 /// makes the threshold itself observable: a helper that padded the wait
1298 /// would pass with the hold set to anything shorter.
1299 #[test]
1300 fn long_press_at_holds_for_exactly_the_profiles_hold() {
1301 use std::cell::Cell;
1302 use std::rc::Rc;
1303
1304 for kind in [
1305 teksilo_tokens::PointerKind::Mouse,
1306 teksilo_tokens::PointerKind::Touch,
1307 teksilo_tokens::PointerKind::Pen(teksilo_tokens::PenKind::Pen),
1308 ] {
1309 let fired = Rc::new(Cell::new(0));
1310 let f = fired.clone();
1311 let mut tree = WidgetTree::new();
1312 tree.add(FillWidget::new().on_long_press(move |_e, _c| f.set(f.get() + 1)));
1313 tree.layout(SizeProposal::exact(100.0, 100.0));
1314
1315 let before = tree.simulated_now();
1316 tree.long_press_at(kind, Point::new(50.0, 50.0));
1317 assert_eq!(fired.get(), 1, "{kind:?} held long enough, once");
1318 assert_eq!(
1319 tree.simulated_now().duration_since(before),
1320 tree.effective_theme.input.profile(kind).long_press,
1321 "{kind:?}: the helper advanced exactly the profile's hold"
1322 );
1323 tree.assert_no_leaked_pointer_state();
1324 }
1325 }
1326
1327 /// `tap_with` completes a tap for every device.
1328 #[test]
1329 fn tap_with_taps_for_every_device() {
1330 use std::cell::Cell;
1331 use std::rc::Rc;
1332
1333 for kind in [
1334 teksilo_tokens::PointerKind::Mouse,
1335 teksilo_tokens::PointerKind::Touch,
1336 teksilo_tokens::PointerKind::Pen(teksilo_tokens::PenKind::Pen),
1337 ] {
1338 let taps = Rc::new(Cell::new(0));
1339 let t = taps.clone();
1340 let mut tree = WidgetTree::new();
1341 tree.add(FillWidget::new().on_tap(move |_e, _c| t.set(t.get() + 1)));
1342 tree.layout(SizeProposal::exact(100.0, 100.0));
1343 tree.tap_with(kind, Point::new(50.0, 50.0));
1344 assert_eq!(taps.get(), 1, "{kind:?} tapped once");
1345 tree.assert_no_leaked_pointer_state();
1346 }
1347 }
1348
1349 /// `touch_action_for` reports the **declaration** in force at a node — the
1350 /// root-to-target intersection — which is a different question from
1351 /// `sequence_touch_action`'s "what did this press freeze".
1352 ///
1353 /// The two differ the moment a widget changes its declaration mid-press,
1354 /// which is the whole reason the value is frozen at all.
1355 #[test]
1356 fn touch_action_for_reads_the_declaration_and_the_sequence_reads_the_freeze() {
1357 use crate::pointer::touch_action::TouchAction;
1358
1359 let mut tree = WidgetTree::new();
1360 let leaf = tree.add(FillWidget::new().on_tap(|_e, _c| {}));
1361 let outer = tree.add(
1362 StackWidget::new()
1363 .child(leaf)
1364 .touch_action(TouchAction::PAN_Y),
1365 );
1366 tree.layout(SizeProposal::exact(100.0, 100.0));
1367
1368 assert_eq!(tree.touch_action_for(outer), TouchAction::PAN_Y);
1369 assert_eq!(
1370 tree.touch_action_for(leaf),
1371 TouchAction::PAN_Y,
1372 "the fold runs root to target"
1373 );
1374
1375 let finger = tree.new_contact();
1376 tree.touch_down(finger, Point::new(50.0, 50.0));
1377 assert_eq!(tree.sequence_touch_action(finger), TouchAction::PAN_Y);
1378
1379 // The declaration changes under the live press.
1380 tree.arena
1381 .get_mut(outer)
1382 .expect("the node is live")
1383 .touch_action = TouchAction::NONE;
1384 assert_eq!(
1385 tree.touch_action_for(leaf),
1386 TouchAction::NONE,
1387 "the declaration moved"
1388 );
1389 assert_eq!(
1390 tree.sequence_touch_action(finger),
1391 TouchAction::PAN_Y,
1392 "…and the press keeps what it froze"
1393 );
1394 tree.touch_up(finger, Point::new(50.0, 50.0));
1395 tree.assert_no_leaked_pointer_state();
1396 }
1397
1398 /// `set_density` is the one density door under A21's name for it.
1399 #[test]
1400 fn set_density_is_set_input_density() {
1401 let mut a = WidgetTree::new();
1402 let mut b = WidgetTree::new();
1403 a.set_density(teksilo_tokens::TargetDensity::Touch);
1404 b.set_input_density(teksilo_tokens::TargetDensity::Touch);
1405 assert_eq!(a.theme().input, b.theme().input);
1406 assert_eq!(
1407 a.theme().input.density,
1408 teksilo_tokens::TargetDensity::Touch
1409 );
1410 }
1411}