frus_widgets/ui.rs
1//! The driver: walks the tree carrying a context (translation + clip), produces the
2//! [`Scene`] and the hit-test maps (click, focus, scroll), and makes it possible to find a
3//! widget by identity so that keyboard/edit events can be routed to it.
4
5use std::hash::{Hash, Hasher};
6
7use frus_core::{
8 Affine, ClipShape, Color, FontWeight, LayerFilter, LayerTransform, Path, Point, Primitive,
9 Rect, Scene, Size, TextStyle,
10};
11use frus_layout::{Layout, NodeId, Overflowing, Side};
12
13use crate::shortcuts::{Intent, KeyStroke};
14
15use crate::barrier::ModalBarrier;
16use crate::dismiss::{DismissPhase, Dismissable};
17use crate::dragdrop::{DragSource, DropZone};
18use crate::hero::{lerp_rect, HeroSpot};
19use crate::interaction::{Status, WidgetId};
20use crate::pageview::PageSnap;
21use crate::physics::{ScrollMetrics, ScrollPhysics};
22use crate::portal::Placement;
23use crate::positioned::Positioning;
24use crate::refresh::Refreshable;
25use crate::relayout::Constraints;
26use crate::runtime::Runtime;
27use crate::theme::Theme;
28use crate::widget::Widget;
29
30/// Thickness of a scrollbar, in pixels (`scrollbar.dart:12`).
31const BAR_SIZE: f32 = 8.0;
32/// Minimum length of a thumb (`scrollbar.dart:15`). It is the tap target: a thumb has to
33/// be catchable by a pointer, whatever fraction of the content the viewport shows.
34const MIN_THUMB: f32 = 48.0;
35/// The thumb's opacity at rest, over `on_surface` (`scrollbar.dart:248`, `:242`). The two
36/// numbers are the reference's, and which one applies follows the surface's own
37/// brightness — this crate's scheme carries no brightness flag, so it is read off the
38/// surface rather than declared.
39/// The gap between the thumb and the edge of the viewport (`scrollbar.dart:14`).
40const BAR_MARGIN: f32 = 2.0;
41const THUMB_ON_DARK: f32 = 0.30;
42const THUMB_ON_LIGHT: f32 = 0.10;
43/// And under a pointer (`scrollbar.dart:245`, `:239`) — a five-fold change on a light
44/// surface, which is what makes a bar you can barely see worth reaching for.
45const THUMB_HOVER_ON_DARK: f32 = 0.65;
46const THUMB_HOVER_ON_LIGHT: f32 = 0.50;
47/// And while it is being dragged (`scrollbar.dart:244`, `:238`), which arrives at once:
48/// the hand is already on it, and a fade would only lag behind the grab.
49const THUMB_DRAG_ON_DARK: f32 = 0.75;
50const THUMB_DRAG_ON_LIGHT: f32 = 0.60;
51/// An Android thumb at rest: the reference's highlight colours, made opaque
52/// (`theme_data.dart:501`, `scrollbar.dart:240`).
53const ANDROID_THUMB_ON_DARK: Color = Color::rgba8(0xCC, 0xCC, 0xCC, 0xFF);
54const ANDROID_THUMB_ON_LIGHT: Color = Color::rgba8(0xBC, 0xBC, 0xBC, 0xFF);
55
56/// One **axis** of a scroll area, as a scrollbar needs to see it: which way it runs, where
57/// it has got to, how far it may go, whether its numbers run backwards, and what the area
58/// itself said about whether it wants a bar at all.
59#[derive(Copy, Clone)]
60struct Bar {
61 vertical: bool,
62 offset: f32,
63 max: f32,
64 reverse: bool,
65 /// The area's own answer, over the application's. See [`crate::Scrollbars`].
66 asked: Option<crate::physics::Scrollbars>,
67 /// Whether the area asked for its bar to stay put instead of fading.
68 visible: Option<bool>,
69}
70
71/// A scrollbar thumb (for hit-testing a drag).
72#[derive(Copy, Clone, Debug)]
73pub struct Scrollbar {
74 /// The scrollable area the bar belongs to.
75 pub id: WidgetId,
76 /// Whether the bar runs vertically; otherwise it is horizontal.
77 pub vertical: bool,
78 /// The thumb's rectangle, in absolute coordinates.
79 pub thumb: Rect,
80 /// Start and length of the track, along the axis.
81 pub track_start: f32,
82 /// The track's length along the axis.
83 pub track_len: f32,
84 /// The thumb's length along the axis.
85 pub thumb_len: f32,
86 /// Offset maximal correspondant.
87 pub max: f32,
88 /// The offsets of a **reversed** axis run the other way along the track: offset 0
89 /// is the far end, so the thumb rests there and a drag towards the start raises the
90 /// number. See [`Scrollable::reverse_y`].
91 pub reverse: bool,
92 /// **How present the bar is**, `0.0..=1.0`. A bar at zero is painted by nothing and
93 /// cannot be grabbed — but it is still here, because a mouse that comes near it
94 /// brings it back.
95 pub opacity: f32,
96 /// The rectangle a **mouse** has to be inside for the bar to notice it: the track,
97 /// widened to take in a tap target's worth of room around the thumb. The reference
98 /// reaches out like this on purpose (`scrollbar.dart:762`) — a bar 8 pixels wide,
99 /// resting at a tenth of an opacity, is not something a hand aims at precisely.
100 pub reach: Rect,
101 /// Whether a pointer can wake and drag it; not under an Android theme, where the bar
102 /// only shows where the page is (milestone 617).
103 pub interactive: bool,
104}
105
106/// The physics an area scrolls with: its own laid over its scroll behaviour's, as the
107/// reference applies a widget's physics to the scroll configuration's (milestone 649).
108fn region_physics<Msg>(widget: &dyn Widget<Msg>, theme: &Theme) -> ScrollPhysics {
109 let platform = crate::ScrollConfiguration::of().scroll_physics(theme);
110 widget
111 .scroll_physics()
112 .map_or(platform, |own| own.apply_to(platform))
113}
114
115/// A scrollable area of the frame: where it is, how far it may scroll, and how it
116/// is meant to behave at its edges.
117///
118/// The registry the shell and the runtime both read. What the area does when it is
119/// dragged, flung or pulled past an edge is settled when it is registered: its own
120/// physics if it asked for some, else what the [`ScrollBehavior`](crate::ScrollBehavior)
121/// in force there says, under the theme it is laid out in (milestone 616).
122#[derive(Copy, Clone, Debug)]
123pub struct Scrollable {
124 /// The scrollable area's identity.
125 pub id: WidgetId,
126 /// The viewport, in absolute coordinates.
127 pub viewport: Rect,
128 /// Largest horizontal offset the content may rest at (0 = nothing to scroll).
129 pub max_x: f32,
130 /// Largest vertical offset the content may rest at.
131 pub max_y: f32,
132 /// The axis the area scrolls along (milestone 649): what an area that is always
133 /// scrollable takes a drag along when nothing overflows.
134 pub axis: crate::scroll::Axis,
135 /// How the area moves at its edges and after a fling: its own, when it asked for
136 /// some, else its scroll behaviour's.
137 pub physics: ScrollPhysics,
138 /// What the area shows when pulled past an edge it will not move beyond, from its
139 /// scroll behaviour; `None` for nothing.
140 pub overscroll: Option<crate::physics::OverscrollIndicator>,
141 /// How a fling on this area is read from the finger's last moves, from its scroll
142 /// behaviour.
143 pub fling: frus_core::VelocityStrategy,
144 /// The [`crate::RefreshIndicator`] area this scrollable sits inside, when there is one.
145 /// Movement refused at its **top** edge feeds that area's pull instead of the
146 /// overscroll glow.
147 pub refresh: Option<WidgetId>,
148 /// Set when this area rests **only on pages** ([`crate::PageView`]): the release
149 /// springs to a page boundary instead of flinging.
150 pub page: Option<PageSnap>,
151 /// Whether the horizontal axis is **reversed** — offset 0 is the right-hand end of
152 /// the content rather than the left.
153 pub reverse_x: bool,
154 /// Whether the vertical axis is **reversed** — offset 0 is the **bottom** of the
155 /// content rather than the top.
156 ///
157 /// Offsets are measured from the end an axis starts at, which is what makes a
158 /// reversed list stay where it is when content arrives: a conversation resting at
159 /// offset 0 is resting at the newest message, and the newest message is wherever the
160 /// end now happens to be. Measuring from the top instead would leave the view
161 /// drifting away from the end every time something was appended, which is the one
162 /// thing this exists to prevent.
163 ///
164 /// Everything the *user* does is unchanged by it. A finger pushes the content the
165 /// way it moves, in either direction; only the arithmetic between that push and the
166 /// number changes sign, in one place.
167 pub reverse_y: bool,
168 /// What the content asked to be kept in view, in the frame's coordinates.
169 pub keep_visible: Option<KeepVisible>,
170 /// The scroll region this one sits **inside**, when there is one.
171 ///
172 /// Scroll areas nest — a sideways strip inside a page that scrolls down — and
173 /// bringing something into view means moving every one of them, from the nearest
174 /// outwards. Identities are hashes and carry no ancestry, so the walk records it.
175 pub host: Option<WidgetId>,
176}
177
178impl Scrollable {
179 /// The tracker a drag on this area reads its fling with.
180 pub fn velocity_tracker(&self) -> frus_core::VelocityTracker {
181 frus_core::VelocityTracker::new(self.fling)
182 }
183
184 /// Whether a finger may move this area at all, resting at `offset`.
185 ///
186 /// The rule the reference states plainly: the user can change the offset **if, and
187 /// only if, there is content outside the viewport to reveal** — or the content is
188 /// already displaced, having shrunk under an offset it no longer reaches. An area that
189 /// fails this takes no drag at all: not a short one, not a refused one, and so no
190 /// end-of-content glow either. An edge effect where there is no edge to meet is a
191 /// statement about the content that is not true.
192 ///
193 /// A [`crate::RefreshIndicator`] listening above is the exception, and the same one the
194 /// reference makes: a list of two items must still pull down to reload.
195 ///
196 /// The physics have the last word (milestone 649): an area the user may never scroll
197 /// takes nothing, and one the user may always scroll takes everything.
198 pub fn accepts_user_offset(&self, offset: (f32, f32)) -> bool {
199 match self.physics.user() {
200 crate::physics::UserScroll::Never => false,
201 crate::physics::UserScroll::Always => true,
202 crate::physics::UserScroll::WhenOverflowing => {
203 self.max_x > 0.0
204 || self.max_y > 0.0
205 || offset.0 != 0.0
206 || offset.1 != 0.0
207 || self.refresh.is_some()
208 }
209 }
210 }
211
212 /// Whether a movement of the user's along the vertical (`down`) or across is this
213 /// area's to take: there is content that way to reveal, or a pull to refresh above
214 /// for a movement down — unless the physics say never, or always along its axis.
215 pub fn takes_user_scroll(&self, down: bool) -> bool {
216 let overflowing = if down {
217 self.max_y > 0.0 || self.refresh.is_some()
218 } else {
219 self.max_x > 0.0
220 };
221 let along = match self.axis {
222 crate::scroll::Axis::Vertical => down,
223 crate::scroll::Axis::Horizontal => !down,
224 crate::scroll::Axis::Both => true,
225 };
226 match self.physics.user() {
227 crate::physics::UserScroll::Never => false,
228 crate::physics::UserScroll::Always => overflowing || along,
229 crate::physics::UserScroll::WhenOverflowing => overflowing,
230 }
231 }
232
233 /// The horizontal axis as the physics sees it, at `offset`.
234 pub fn metrics_x(&self, offset: f32) -> ScrollMetrics {
235 ScrollMetrics::new(offset, self.max_x, self.viewport.width)
236 }
237
238 /// The vertical axis as the physics sees it, at `offset`.
239 pub fn metrics_y(&self, offset: f32) -> ScrollMetrics {
240 ScrollMetrics::new(offset, self.max_y, self.viewport.height)
241 }
242
243 /// Turns a **screen** delta — how far the content was pushed, in pixels — into the
244 /// change it makes to this area's offsets.
245 ///
246 /// Two sign changes, and both have a reason. The content moves *opposite* the
247 /// number: dragging down reveals what is above, which is a smaller offset. And a
248 /// reversed axis counts from the other end, so the same drag raises it instead.
249 ///
250 /// One function rather than a minus sign at each of the five places a delta becomes
251 /// an offset — the wheel, the drag, the release fling, and both axes of each — so
252 /// that a reversed scroll is right in all of them or in none.
253 pub fn offset_delta(&self, screen: (f32, f32)) -> (f32, f32) {
254 (
255 if self.reverse_x { screen.0 } else { -screen.0 },
256 if self.reverse_y { screen.1 } else { -screen.1 },
257 )
258 }
259
260 /// The edge a refusal happened at, given the refused movement **in offset space**.
261 ///
262 /// A negative refusal means the content was pulled towards the axis's start, and
263 /// where that is on screen is exactly what reversing changes: the start of a
264 /// reversed vertical axis is the **bottom**. Without this the glow would flash at
265 /// the far end of a conversation the moment it refused to go further back.
266 pub fn refused_edge(&self, vertical: bool, refused: f32) -> crate::overscroll::GlowEdge {
267 let reversed = if vertical {
268 self.reverse_y
269 } else {
270 self.reverse_x
271 };
272 crate::overscroll::edge_for(vertical, if reversed { -refused } else { refused })
273 }
274
275 /// The edge an axis **starts** at, which is where a pull-to-refresh listens.
276 pub fn start_edge(&self, vertical: bool) -> crate::overscroll::GlowEdge {
277 self.refused_edge(vertical, -1.0)
278 }
279
280 /// The offset that brings `target` fully inside this viewport, and how far the
281 /// content moves to get there.
282 ///
283 /// The **least** movement that does it: a box already in view does not budge, one
284 /// off the near edge comes to that edge and no further. Centring it instead would
285 /// make Tab through a form scroll on every stop, which is motion nobody asked for.
286 ///
287 /// A target **too big** for the viewport gets its leading edge aligned, which falls
288 /// out of asking about that edge first: a tall field half off the top comes down to
289 /// the top rather than up to the bottom, because its start is what you read.
290 ///
291 /// Both halves are returned because they are not the same number. The offset is
292 /// clamped to what this region can actually do, and an outer region has to be told
293 /// how far the target really moved — not how far it was asked to.
294 pub fn reveal(&self, target: Rect, current: (f32, f32)) -> ((f32, f32), (f32, f32)) {
295 let shift = |lo: f32, hi: f32, near: f32, far: f32| {
296 if near < lo {
297 lo - near
298 } else if far > hi {
299 hi - far
300 } else {
301 0.0
302 }
303 };
304 let wanted = (
305 shift(
306 self.viewport.x,
307 self.viewport.x + self.viewport.width,
308 target.x,
309 target.x + target.width,
310 ),
311 shift(
312 self.viewport.y,
313 self.viewport.y + self.viewport.height,
314 target.y,
315 target.y + target.height,
316 ),
317 );
318 // `offset_delta` turns a movement of the content into a movement of the offset,
319 // and it is its own inverse — it negates or it does not — so the same function
320 // turns the offset that was allowed back into the content movement it buys.
321 let delta = self.offset_delta(wanted);
322 let next = (
323 (current.0 + delta.0).clamp(0.0, self.max_x),
324 (current.1 + delta.1).clamp(0.0, self.max_y),
325 );
326 let applied = (next.0 - current.0, next.1 - current.1);
327 (next, self.offset_delta(applied))
328 }
329
330 /// The offset that puts `target` in the **middle** of this viewport, and how far the
331 /// content moves to get there.
332 ///
333 /// The same pair as [`Scrollable::reveal`], and the same clamp — which is what makes
334 /// the first item of a row rest at the start rather than half off it. A target
335 /// bigger than the viewport centres too, which leaves it hanging over both edges,
336 /// and that is the honest answer: there is no offset that shows all of it.
337 pub fn centre(&self, target: Rect, current: (f32, f32)) -> ((f32, f32), (f32, f32)) {
338 let wanted = (
339 (self.viewport.x + self.viewport.width / 2.0) - (target.x + target.width / 2.0),
340 (self.viewport.y + self.viewport.height / 2.0) - (target.y + target.height / 2.0),
341 );
342 let delta = self.offset_delta(wanted);
343 let next = (
344 (current.0 + delta.0).clamp(0.0, self.max_x),
345 (current.1 + delta.1).clamp(0.0, self.max_y),
346 );
347 let applied = (next.0 - current.0, next.1 - current.1);
348 (next, self.offset_delta(applied))
349 }
350
351 /// The offset that brings `keep` into view under its own policy, and how far the
352 /// content moves from **rest** to get there.
353 ///
354 /// Absolute, because [`KeepVisible::rect`] is recorded at rest: the base is offset
355 /// zero, not wherever the region currently is.
356 pub fn keep_offset(&self, keep: KeepVisible) -> ((f32, f32), (f32, f32)) {
357 match keep.centre {
358 true => self.centre(keep.rect, (0.0, 0.0)),
359 false => self.reveal(keep.rect, (0.0, 0.0)),
360 }
361 }
362
363 /// Where the content's leading edge sits, relative to the viewport's, at `offset`.
364 ///
365 /// Normally minus the offset. On a reversed axis the content is anchored to the far
366 /// end, so offset 0 puts the content's *end* against the viewport's — which is also
367 /// the answer for content too short to scroll, where it sits at the bottom of the
368 /// box rather than the top.
369 pub fn content_origin(&self, offset: (f32, f32), content: Size) -> (f32, f32) {
370 let axis = |reverse: bool, offset: f32, viewport: f32, content: f32| {
371 if reverse {
372 viewport - content + offset
373 } else {
374 -offset
375 }
376 };
377 (
378 axis(self.reverse_x, offset.0, self.viewport.width, content.width),
379 axis(
380 self.reverse_y,
381 offset.1,
382 self.viewport.height,
383 content.height,
384 ),
385 )
386 }
387}
388
389/// A box a scroll region has been asked to **keep in view**, and which box it is.
390///
391/// A tab bar wider than its window is what this is for. Declared by the content through
392/// [`Widget::keep_visible`], carried on the region so it survives a repaint boundary
393/// like everything else about the region, and acted on by
394/// [`crate::Runtime::sync_visible`].
395#[derive(Copy, Clone, Debug, PartialEq)]
396pub struct KeepVisible {
397 /// Which box this is. The region acts when this **changes** and not otherwise: the
398 /// box moves as the region scrolls, so a region chasing the box itself would pin
399 /// the content in place and no finger could move it.
400 pub key: u64,
401 /// The box: in the declaring widget's own coordinates when it comes back from
402 /// [`Widget::keep_visible`], and in the frame's — **as it would sit at offset zero**
403 /// — when it reaches the region.
404 ///
405 /// At rest rather than where it is actually drawn, and that is the whole reason the
406 /// answer can be trusted. A box recorded where it is drawn is a box whose position
407 /// already contains the current offset, so the offset that would centre it can only
408 /// be worked out **relative** to wherever the region happens to be — and on the
409 /// first frame, before anything has been retained, there is no wherever to be
410 /// relative to. Recorded at rest, the answer is absolute: the same number on the
411 /// first frame and the hundredth.
412 pub rect: Rect,
413 /// Put it in the **middle** of the window rather than merely inside it. What a tab
414 /// bar wants: a selected tab flush against the edge reads as the end of the row.
415 /// Clamped either way, so the first tab still rests at the start.
416 pub centre: bool,
417}
418
419/// Direction of arrow-key focus navigation.
420#[derive(Clone, Copy, Debug, PartialEq, Eq)]
421pub enum FocusDirection {
422 /// The up arrow: focus moves to the widget above.
423 Up,
424 /// The down arrow: focus moves to the widget below.
425 Down,
426 /// The left arrow: focus moves to the widget on the left.
427 Left,
428 /// The right arrow: focus moves to the widget on the right.
429 Right,
430}
431
432/// A region the mouse enters and leaves, as a frame registered it (milestone 583).
433#[derive(Clone, Copy, Debug)]
434struct HoverEntry {
435 id: WidgetId,
436 /// The part that shows, which the pointer can be over.
437 seen: Rect,
438 /// The whole box, which positions are measured from.
439 whole: Rect,
440 /// The region it is inside, if any.
441 parent: Option<WidgetId>,
442 spec: crate::HoverRegion,
443}
444
445#[derive(Clone)]
446struct Hit<Msg> {
447 id: WidgetId,
448 rect: Rect,
449 /// The message the target emits, or `None` for a target that **swallows** input
450 /// without doing anything — an [`crate::AbsorbPointer`]. Such a target still wins
451 /// the hit test, which is exactly what stops the click reaching what is behind it.
452 msg: Option<Msg>,
453 /// **Inverse** transform (screen → the flat frame) of a transformed subtree
454 /// (`Transform::scale`/`rotate`/a composition): the test point is passed through it to
455 /// get back to the untransformed frame where `rect` lives. `None` = an axis-aligned,
456 /// untransformed rect (the common case).
457 xform: Option<Affine>,
458}
459
460impl<Msg> Hit<Msg> {
461 /// `true` when `point` (in screen coordinates) falls inside the target, taking any
462 /// transform on the subtree into account.
463 fn contains(&self, point: Point) -> bool {
464 let p = self.xform.map_or(point, |inv| inv.apply(point));
465 self.rect.contains(p)
466 }
467}
468
469/// The painted output of a repaint-boundary subtree, cached (see `paintcache.rs`) and
470/// replayed as is on a *hit*. Erased behind a `Box<dyn Any>` in the cache; brought back down
471/// to `Msg` here (one `Msg` instance per app → the `downcast` always succeeds).
472#[derive(Clone)]
473struct BoundaryData<Msg> {
474 prims: Vec<frus_core::Primitive>,
475 hits: Vec<Hit<Msg>>,
476 long_presses: Vec<Hit<Msg>>,
477 dismisses: Vec<Msg>,
478 focusables: Vec<Focusable>,
479 scrollables: Vec<Scrollable>,
480 draggables: Vec<(WidgetId, Rect)>,
481 drag_sources: Vec<DragSource>,
482 drop_zones: Vec<DropZone>,
483 inks: Vec<(WidgetId, Rect)>,
484 /// The detectors that take a drag, in painted order, with the box a press can land in
485 /// (clipped) and the whole box (milestone 582).
486 pans: Vec<(WidgetId, Rect, Rect)>,
487 /// The widgets that hear the pointer's raw events, likewise (milestone 586).
488 pointer_listeners: Vec<(WidgetId, Rect, Rect)>,
489 /// The regions the mouse enters and leaves, in painted order (milestone 583).
490 hover_regions: Vec<HoverEntry>,
491 text_stops: Vec<crate::TextStop>,
492 semantics: Vec<(WidgetId, Rect, frus_core::SemanticsProperties)>,
493 system_ui: Vec<(Rect, crate::SystemUiOverlayStyle)>,
494}
495
496/// Lengths of the builder's collections on entering a boundary: the lower bounds of the
497/// slices to capture on the way out.
498struct Snapshot {
499 scene: usize,
500 hits: usize,
501 long_presses: usize,
502 dismisses: usize,
503 focusables: usize,
504 scrollables: usize,
505 draggables: usize,
506 drag_sources: usize,
507 drop_zones: usize,
508 inks: usize,
509 pans: usize,
510 pointer_listeners: usize,
511 hover_regions: usize,
512 text_stops: usize,
513 semantics: usize,
514 system_ui: usize,
515 overlays: usize,
516 focus_scope_start: Option<usize>,
517}
518
519/// Lower bounds of the **interaction** registries at the start of a transformed composition
520/// (a scale/rotation layer): only what the subtree has just added is re-mapped. Distinct from
521/// [`Snapshot`] (the boundary cache) because it **includes `reorderables`** — those are never
522/// cached but do have to be transformed. See [`transform_interaction_registries`].
523/// Lengths of the registries a [`ModalBarrier`] withholds from, on entering its subtree: the
524/// point each is truncated back to on the way out. Distinct from [`XformBase`] because a
525/// barrier also covers the **scene** and the **scrollbars**, and distinct from [`Snapshot`]
526/// because it covers the registries that are never cached.
527/// What is withdrawn from a layer of an [`crate::IndexedStack`] that is not the shown one:
528/// its paint, its input and its place in the accessibility tree. Not `absorb` — the layer
529/// is not a scrim over what is behind it, it is simply not there for the reader.
530const HIDDEN_LAYER: crate::barrier::ModalBarrier = crate::barrier::ModalBarrier {
531 pointer: true,
532 absorb: false,
533 paint: true,
534 semantics: true,
535};
536
537struct BarrierBase {
538 scene: usize,
539 hits: usize,
540 long_presses: usize,
541 focusables: usize,
542 scrollables: usize,
543 scrollbars: usize,
544 draggables: usize,
545 drag_sources: usize,
546 drop_zones: usize,
547 inks: usize,
548 pans: usize,
549 pointer_listeners: usize,
550 hover_regions: usize,
551 text_stops: usize,
552 reorderables: usize,
553 interactives: usize,
554 semantics: usize,
555}
556
557struct XformBase {
558 hits: usize,
559 long_presses: usize,
560 focusables: usize,
561 scrollables: usize,
562 draggables: usize,
563 drag_sources: usize,
564 drop_zones: usize,
565 inks: usize,
566 pans: usize,
567 pointer_listeners: usize,
568 hover_regions: usize,
569 text_stops: usize,
570 reorderables: usize,
571 semantics: usize,
572}
573
574/// Node count of the subtree **if** it is "plain" — that is, if the boundary and **all** its
575/// descendants take the default walk branch (children in prefix order): not scrollable, not a
576/// navigator, not a virtualised list, no `layout_builder`, not a stack, no overlay, no
577/// continuous animation. The count then follows the walk's rect order **exactly**, which is
578/// what makes the fingerprint and the bit-for-bit replay correct. `None` = a subtree that
579/// cannot be cached (it is repainted in full — the safe fallback).
580fn plain_subtree_len<Msg>(widget: &dyn Widget<Msg>) -> Option<usize> {
581 if widget.continuous()
582 || widget.scroll_content().is_some()
583 || widget.interactive().is_some()
584 || widget.fitted().is_some()
585 || widget.rotated_quarter_turns().is_some()
586 || widget.navigator().is_some()
587 // Only *whether*, never *what*: these two ask if the widget windows its
588 // children at all, and a size it will not read is the honest argument.
589 || widget.virtual_list(Size::ZERO).is_some()
590 || widget.page_view().is_some()
591 || widget.overflow_box().is_some()
592 || widget.constraints_transform().is_some()
593 || widget.layout_builder().is_some()
594 || widget.stack()
595 // Painted where the scroll has got to, not where it was laid out.
596 || widget.sticky_header()
597 || widget.custom_layout().is_some()
598 || widget.overlay().is_some()
599 // A reorderable (a Kanban card, a draggable header): its bounds feed the reorderables
600 // registry, which is not cached — so its subtree is not put in the paint cache.
601 || widget.reorder_index().is_some()
602 // Read by the shell every frame, from the walk (milestone 640).
603 || widget.wants_title_bar()
604 || widget.title_bar_role().is_some()
605 {
606 return None;
607 }
608 let mut n = 1;
609 for child in widget.children() {
610 n += plain_subtree_len(child.as_ref())?;
611 }
612 Some(n)
613}
614
615/// Moves `v[from..to]` after the rest of `v[from..]`: what a sticky header added, after what
616/// its section added (milestone 602).
617fn after<T>(v: &mut [T], from: usize, to: usize) {
618 if to > from && from <= v.len() {
619 v[from..].rotate_left(to - from);
620 }
621}
622
623/// The walk's constraints for a child a [`crate::CustomMultiChildLayout`] lays out. An
624/// exact extent is **forced** when nothing else is only allowed, as a pinned stack layer's
625/// is; beside an axis that is only allowed, it is handed, and a child with a size of its own
626/// there keeps it.
627fn custom_constraints(c: crate::ChildConstraints) -> Constraints {
628 use crate::ChildAxis::{AtMost, Exactly, Free};
629 let axis = |a| match a {
630 Free => (0.0, true, false, false),
631 AtMost(v) => (f32::max(v, 0.0), false, false, true),
632 Exactly(v) => (f32::max(v, 0.0), false, true, false),
633 };
634 let (w, free_x, exact_x, loose_x) = axis(c.width);
635 let (h, free_y, exact_y, loose_y) = axis(c.height);
636 if (exact_x || exact_y) && !loose_x && !loose_y {
637 Constraints::pinned(
638 (!free_x).then_some(w),
639 (!free_y).then_some(h),
640 Size::new(w, h),
641 )
642 } else {
643 Constraints::axes(w, h, [free_x, free_y], [exact_x, exact_y])
644 }
645}
646
647/// Quantises a `[0,1]` float for the fingerprint (independent of tiny binary differences: two
648/// visually identical progresses ⇒ the same fingerprint).
649fn quant(x: f32) -> i32 {
650 (x * 4096.0).round() as i32
651}
652
653/// Adds to `h` everything the paint reads from a `Status`, **except** the time (excluded: a
654/// cacheable boundary holds no `continuous` widget).
655fn hash_status<H: Hasher>(s: &Status, h: &mut H) {
656 (s.interaction as u8).hash(h);
657 s.focused.hash(h);
658 s.cursor.hash(h);
659 s.selection.hash(h);
660 s.composing.hash(h);
661 // Both change what a field floats over itself without touching its selection: a bar
662 // that opens on a selection already made, handles put away by a press.
663 s.handles.hash(h);
664 s.toolbar.hash(h);
665 // What a selection area has selected in this text: the highlight is part of its paint,
666 // and the bar floats from it.
667 s.region.hash(h);
668 s.region_bar.hash(h);
669 s.region_grips.hash(h);
670 quant(s.hover_progress).hash(h);
671 quant(s.focus_progress).hash(h);
672 quant(s.press_progress).hash(h);
673 quant(s.opacity).hash(h);
674 quant(s.value).hash(h);
675 // Sub-region hover (milestone 208): a change of position repaints the highlight.
676 s.hover_cursor.map(|p| (quant(p.x), quant(p.y))).hash(h);
677}
678
679/// The result of building an interface for one frame.
680/// A **shortcut / action scope**: a subtree that binds keystrokes, answers intents, or
681/// both, together with the range of focus stops it contains.
682///
683/// The range is how "focus is inside this subtree" is answered without an ancestor test:
684/// the walk is depth-first, so a subtree's focus stops are contiguous, and the focused
685/// stop's index either falls inside the range or does not.
686struct Scope<Msg> {
687 strokes: Vec<(KeyStroke, Intent)>,
688 callbacks: Vec<(KeyStroke, Msg)>,
689 actions: Vec<(Intent, Msg)>,
690 listeners: Vec<(Intent, Msg)>,
691 /// The focus stops this subtree contains, as indices into `focusables`.
692 range: std::ops::Range<usize>,
693}
694
695/// A **focus stop**: somewhere the keyboard can land, and what the traversal should make
696/// of it.
697#[derive(Clone, Copy, Debug)]
698pub struct Focusable {
699 /// The widget's identity.
700 pub id: WidgetId,
701 /// Its **visible** box this frame: the box it was given, clipped by whatever
702 /// encloses it. Empty when it is scrolled out of sight, which is what a click test
703 /// wants — a tap on empty space must not land on something nobody can see.
704 pub rect: Rect,
705 /// Its box this frame, **unclipped**. What the geometry is really about: where the
706 /// widget is, whether or not any of it is on screen. Arrow navigation places
707 /// candidates by this, and [`Ui::reveal`] works out what to scroll from it.
708 pub bounds: Rect,
709 /// The [`crate::AutofillGroup`] this stop sits in — the form it is part of — when
710 /// there is one (milestone 512).
711 pub form: Option<WidgetId>,
712 /// The nearest enclosing scroll region, when there is one. What could bring this
713 /// stop into view, and the first link of the chain [`Ui::reveal`] walks.
714 pub scroll: Option<WidgetId>,
715 /// Focusable by a click, but **passed over by Tab** — the reference's
716 /// `ExcludeFocusTraversal`. The two are separate questions.
717 pub skip: bool,
718 /// An explicit traversal position, smallest first. `None` means tree order, which is
719 /// where everything sits until someone says otherwise.
720 pub order: Option<f32>,
721 /// The traversal group it belongs to, within which its order is resolved.
722 pub group: Option<WidgetId>,
723 /// Whether it takes the focus when it appears ([`Widget::autofocus`], milestone 605).
724 pub autofocus: bool,
725}
726
727/// The **interface** of one frame: what the walk over a widget tree produced.
728///
729/// Besides the [`Scene`] to paint it holds everything the shell asks of a frame afterwards —
730/// what a click, a long press or a dismissal answers, what can take the focus, which areas
731/// scroll, which widgets can be dragged or dropped on — so that events are routed against
732/// the frame the reader saw. It is made by [`build_ui`] and read until the next frame
733/// replaces it.
734pub struct Ui<Msg = crate::callback::Callback> {
735 scene: Scene,
736 hits: Vec<Hit<Msg>>,
737 /// Long-press targets (id, visible bounds, message).
738 long_presses: Vec<Hit<Msg>>,
739 /// Overlay dismissal messages, from the bottom to the **top**.
740 dismisses: Vec<Msg>,
741 /// The buttons of a selection bar that carry no message, and the editing action each
742 /// performs (milestone 568) — what the shell resolves a press on one to.
743 edit_actions: Vec<(WidgetId, crate::EditAction)>,
744 /// The boxes selection bars were placed in this frame: a press inside one is a press
745 /// **on the bar**, which must not put the selection it acts on away.
746 toolbars: Vec<Rect>,
747 /// Where a press lands **on an overlay** rather than on the pages under it: an overlay's
748 /// box, and the whole window under one that a press outside dismisses (milestone 642).
749 overlay_cover: Vec<Rect>,
750 focusables: Vec<Focusable>,
751 /// **Focus scope**: index of the topmost modal overlay's first focusable —
752 /// Tab/arrows/click-to-focus are trapped from there on (`None` = no modal, every
753 /// focusable takes part).
754 focus_scope_start: Option<usize>,
755 /// (id, viewport, offset max x, offset max y)
756 scrollables: Vec<Scrollable>,
757 scrollbars: Vec<Scrollbar>,
758 draggables: Vec<(WidgetId, Rect)>,
759 drag_sources: Vec<DragSource>,
760 drop_zones: Vec<DropZone>,
761 /// **Inked surfaces**: (id, the box the ink is clipped to). Tracked separately from
762 /// clicking because the splash needs the surface's **whole** box — where the finger
763 /// landed inside it, and how far the circle has to travel to cover it — which a
764 /// click target, recorded as its *visible* part, does not give.
765 inks: Vec<(WidgetId, Rect)>,
766 /// The detectors that take a drag, in painted order, with the box a press can land in
767 /// (clipped) and the whole box (milestone 582).
768 /// The row that wants the title bar's line, where it was laid out, and what the system
769 /// acts on there (milestones 640, 642).
770 title_bar_row: Option<Rect>,
771 title_bar_regions: Vec<(Rect, crate::TitleBarRole)>,
772 pans: Vec<(WidgetId, Rect, Rect)>,
773 /// The widgets that hear the pointer's raw events, likewise (milestone 586).
774 pointer_listeners: Vec<(WidgetId, Rect, Rect)>,
775 /// The regions the mouse enters and leaves, in painted order (milestone 583).
776 hover_regions: Vec<HoverEntry>,
777 /// The texts inside a [`SelectionArea`](crate::SelectionArea), in the order they were
778 /// painted — reading order — each with the area it is in.
779 text_stops: Vec<crate::TextStop>,
780 /// **Reorderables** (column headers, Kanban cards): (id, visible bounds). Tracked
781 /// independently of clicking — a card is not clickable but can still be picked up and
782 /// dropped onto.
783 reorderables: Vec<(WidgetId, Rect)>,
784 /// Interactive viewports (`InteractiveViewer`): (id, the screen viewport). The shell
785 /// routes panning (dragging) and zooming (wheel / pinch) to them.
786 interactives: Vec<(WidgetId, Rect)>,
787 /// Pull-to-refresh areas of the frame, with their configuration.
788 refreshes: Vec<Refreshable>,
789 /// Swipe-to-dismiss items of the frame, with their configuration.
790 dismissables: Vec<Dismissable>,
791 /// Draggable sheets of the frame, with their configuration and the scroll areas
792 /// walked inside each.
793 sheets: Vec<crate::sheet::SheetArea>,
794 wants_animation: bool,
795 /// The accessibility tree: semantic nodes (id, bounds, annotation), in paint order. The
796 /// shell maps it onto AccessKit.
797 semantics: Vec<(WidgetId, Rect, frus_core::SemanticsProperties)>,
798 /// The regions saying what the system bars over them should look like (paint order).
799 system_ui: Vec<(Rect, crate::SystemUiOverlayStyle)>,
800 /// Boxes whose children ran outside them, with the edge and the amount.
801 overflows: Vec<Overflowing>,
802 /// Shortcut and action scopes, in the order the walk closed them — innermost first
803 /// among any that overlap, which is the order the resolution wants.
804 scopes: Vec<Scope<Msg>>,
805 /// Keystroke listeners, with the focus stops they cover.
806 #[allow(clippy::type_complexity)]
807 listeners: Vec<(
808 std::ops::Range<usize>,
809 std::rc::Rc<dyn Fn(KeyStroke) -> Option<Msg>>,
810 )>,
811}
812
813impl<Msg: Clone> Ui<Msg> {
814 /// The scene to hand to the renderer.
815 /// Boxes in this frame whose children did not fit inside them.
816 ///
817 /// Empty is the normal answer. A non-empty one means content is being drawn outside
818 /// its parent — invisible where it is clipped, unhittable where it leaves the window,
819 /// and silent either way until something asks. That silence is what let a task row's
820 /// delete button sit off-screen through three milestones.
821 pub fn overflows(&self) -> &[Overflowing] {
822 &self.overflows
823 }
824
825 /// The scrollbars this frame drew, and therefore the ones a pointer may drag. Empty
826 /// where the platform draws none — see [`crate::Scrollbars`].
827 pub fn scrollbars(&self) -> &[Scrollbar] {
828 &self.scrollbars
829 }
830
831 /// The [`Scene`] this frame painted.
832 pub fn scene(&self) -> &Scene {
833 &self.scene
834 }
835
836 /// The frame's **accessibility tree**: every meaningful node with its bounds on screen and
837 /// its annotation ([`frus_core::SemanticsProperties`]). Paint order (= reading order). The shell
838 /// pushes it to AccessKit.
839 pub fn semantics(&self) -> &[(WidgetId, Rect, frus_core::SemanticsProperties)] {
840 &self.semantics
841 }
842
843 /// What the system bars should look like over this frame (#46): the regions under
844 /// `status_bar` answer for the status bar and those under `navigation_bar` for the
845 /// other, the one drawn last first and field by field. What none states is left
846 /// `None`, for [`crate::SystemUiOverlayStyle::resolve`] to take from the theme.
847 ///
848 /// The shell picks the two points: the first row of the screen's content under the
849 /// status bar, and the last one above the navigation bar.
850 pub fn system_ui_style(
851 &self,
852 status_bar: Point,
853 navigation_bar: Point,
854 ) -> crate::SystemUiOverlayStyle {
855 crate::system_ui::style_under(&self.system_ui, status_bar, navigation_bar)
856 }
857
858 /// `true` when a widget animates continuously (the framework must redraw).
859 /// Whether **this tree's widgets** want the next frame: a spinner turning, an ink
860 /// ripple spreading, a pull being held.
861 ///
862 /// It answers for the widgets and nothing else. A fetch still in flight also owes the
863 /// screen a frame — see [`frus_core::images_in_flight`] — and that is the *process's*
864 /// business, asked by whoever drives the loop. It used to be folded in here, which
865 /// made this method's answer depend on what an unrelated part of the program happened
866 /// to be doing: in the test suite, where everything shares one process, a refresh area
867 /// with nothing pulled asked for frames whenever another test was loading an image
868 /// (milestone 411).
869 pub fn wants_animation(&self) -> bool {
870 self.wants_animation
871 }
872
873 /// Whether something in this frame wants the title bar's line (milestone 640).
874 pub fn wants_title_bar(&self) -> bool {
875 self.title_bar_row.is_some()
876 }
877
878 /// Where the row that wants the title bar's line was laid out — a
879 /// [`WindowMenuBar`](crate::WindowMenuBar)'s, the window's and not a page's (milestone
880 /// 642). What the shell does to the pages, the back gesture at the window's edge, does
881 /// not start on it.
882 pub fn title_bar_row(&self) -> Option<Rect> {
883 self.title_bar_row
884 }
885
886 /// What the system acts on on the title bar's line: the window's icon and its buttons,
887 /// where they were painted (milestone 640).
888 pub fn title_bar_regions(&self) -> &[(Rect, crate::TitleBarRole)] {
889 &self.title_bar_regions
890 }
891
892 /// Every box a press can land on, in painted order: what on the title bar's line is the
893 /// application's, rather than the system's to move the window by (milestone 640).
894 pub fn hit_rects(&self) -> impl Iterator<Item = Rect> + '_ {
895 self.hits.iter().map(|hit| hit.rect)
896 }
897
898 /// Identity of the topmost clickable widget containing `point`.
899 pub fn hit(&self, point: Point) -> Option<WidgetId> {
900 self.hits
901 .iter()
902 .rev()
903 .find(|hit| hit.contains(point))
904 .map(|hit| hit.id)
905 }
906
907 /// The message tied to a given clickable widget. `None` for a target that swallows
908 /// input without emitting anything.
909 ///
910 /// It is always paired with [`hit`](Self::hit), so the two have to agree on which
911 /// target an identity means: every registered target therefore has one of its own,
912 /// the dismissal barrier below an overlay included.
913 pub fn msg_for(&self, id: WidgetId) -> Option<Msg> {
914 self.hits
915 .iter()
916 .find(|hit| hit.id == id)
917 .and_then(|hit| hit.msg.clone())
918 }
919
920 /// The editing action the button `id` of a selection bar performs, for a button that
921 /// carries no message (Cut, Copy, Paste, Select all — see [`crate::EditAction`]). The
922 /// shell holds the clipboard and the editing state, so it is the shell that performs it.
923 pub fn edit_action_for(&self, id: WidgetId) -> Option<crate::EditAction> {
924 self.edit_actions
925 .iter()
926 .find(|(button, _)| *button == id)
927 .map(|(_, action)| *action)
928 }
929
930 /// Whether the target `id` is one **on** a selection bar shown this frame — the click of
931 /// an assistive technology names its target by identity, not by where a pointer is, so
932 /// this is the identity-side counterpart of [`toolbar_contains`](Self::toolbar_contains).
933 pub fn hit_is_on_toolbar(&self, id: WidgetId) -> bool {
934 self.hits
935 .iter()
936 .rev()
937 .find(|hit| hit.id == id)
938 .is_some_and(|hit| {
939 self.toolbars.iter().any(|bar| {
940 bar.contains(Point::new(
941 hit.rect.x + hit.rect.width * 0.5,
942 hit.rect.y + hit.rect.height * 0.5,
943 ))
944 })
945 })
946 }
947
948 /// Whether `point` is inside a selection bar shown this frame — which a press must not
949 /// treat as a press elsewhere.
950 pub fn toolbar_contains(&self, point: Point) -> bool {
951 self.toolbars.iter().any(|bar| bar.contains(point))
952 }
953
954 /// Whether a press at `point` lands **on an overlay** — a menu, a dialog, a drawer, or
955 /// the window under one that a press outside dismisses — rather than on the pages under
956 /// it (milestone 642). What the shell does to the pages, the back gesture at the
957 /// window's edge, does not start there: in the reference that gesture is the page's, and
958 /// an overlay is above the page.
959 pub fn over_overlay(&self, point: Point) -> bool {
960 self.overlay_cover.iter().any(|r| r.contains(point))
961 }
962
963 /// Dismissal message of the **topmost** overlay (for Escape).
964 pub fn top_dismiss(&self) -> Option<Msg> {
965 self.dismisses.last().cloned()
966 }
967
968 /// **Long-press** message of the topmost target containing `point`.
969 pub fn long_press_at(&self, point: Point) -> Option<Msg> {
970 self.long_presses
971 .iter()
972 .rev()
973 .find(|hit| hit.contains(point))
974 .and_then(|hit| hit.msg.clone())
975 }
976
977 /// The frame's **pull-to-refresh areas**, with the configuration each was built
978 /// with. The shell steps them and reads their `refreshing` flag from here.
979 pub fn refresh_areas(&self) -> &[Refreshable] {
980 &self.refreshes
981 }
982
983 /// The frame's **dismissible items**, with the configuration each was built with.
984 pub fn dismissables(&self) -> &[Dismissable] {
985 &self.dismissables
986 }
987
988 /// The frame's **sheets**, with the configuration each was built with and the scroll
989 /// areas walked inside it.
990 pub fn sheets(&self) -> &[crate::sheet::SheetArea] {
991 &self.sheets
992 }
993
994 /// The sheet whose panel is under `point`, the last one walked winning — which is
995 /// the one painted on top.
996 pub fn sheet_at(&self, point: Point) -> Option<&crate::sheet::SheetArea> {
997 self.sheets.iter().rev().find(|sheet| sheet.contains(point))
998 }
999
1000 /// The sheet `id`, when it is in the frame.
1001 pub fn sheet(&self, id: WidgetId) -> Option<&crate::sheet::SheetArea> {
1002 self.sheets.iter().find(|sheet| sheet.id == id)
1003 }
1004
1005 /// The sheet the scroll area `area` was walked inside, when there is one — the
1006 /// innermost, should sheets nest, since an outer one counts the inner one's areas too.
1007 pub fn sheet_holding(&self, area: WidgetId) -> Option<&crate::sheet::SheetArea> {
1008 self.sheets
1009 .iter()
1010 .filter(|sheet| sheet.areas.contains(&area))
1011 .min_by_key(|sheet| sheet.areas.len())
1012 }
1013
1014 /// The topmost dismissible item containing `point` — the candidate a press has to
1015 /// weigh against the scrollable underneath it.
1016 pub fn dismissable_at(&self, point: Point) -> Option<Dismissable> {
1017 self.dismissables
1018 .iter()
1019 .rev()
1020 .find(|item| item.rect.contains(point))
1021 .copied()
1022 }
1023
1024 /// Every text that took part in a selection area this frame, in the order it was painted.
1025 pub fn text_stops(&self) -> &[crate::TextStop] {
1026 &self.text_stops
1027 }
1028
1029 /// The texts a [`SelectionArea`](crate::SelectionArea) holds, in reading order.
1030 pub fn text_stops_in(&self, area: WidgetId) -> impl Iterator<Item = &crate::TextStop> {
1031 self.text_stops.iter().filter(move |stop| stop.area == area)
1032 }
1033
1034 /// The topmost text in a selection area whose box contains `point`.
1035 pub fn text_stop_at(&self, point: Point) -> Option<crate::TextStop> {
1036 self.text_stops
1037 .iter()
1038 .rev()
1039 .find(|stop| stop.rect.contains(point))
1040 .copied()
1041 }
1042
1043 /// The text of `area` **nearest** `point`: the one under it, or the one closest to it —
1044 /// which is what a drag that has left the words still points at. Distance across lines
1045 /// counts four times what it does along one, so a point beside a line is nearest that
1046 /// line and not the one above it; ties go to the later text, so that a drag past the end
1047 /// of a paragraph ends at its last line.
1048 pub fn nearest_text_stop(&self, area: WidgetId, point: Point) -> Option<crate::TextStop> {
1049 let distance = |rect: Rect| {
1050 let dx = (rect.x - point.x)
1051 .max(point.x - (rect.x + rect.width))
1052 .max(0.0);
1053 let dy = (rect.y - point.y)
1054 .max(point.y - (rect.y + rect.height))
1055 .max(0.0);
1056 dy * 4.0 + dx
1057 };
1058 let mut best: Option<(f32, crate::TextStop)> = None;
1059 for stop in self.text_stops_in(area) {
1060 let d = distance(stop.rect);
1061 if best.is_none_or(|(so_far, _)| d <= so_far) {
1062 best = Some((d, *stop));
1063 }
1064 }
1065 best.map(|(_, stop)| stop)
1066 }
1067
1068 /// Topmost focusable widget containing `point`: (id, its bounds).
1069 pub fn focus_hit(&self, point: Point) -> Option<(WidgetId, Rect)> {
1070 self.focus_pool()
1071 .iter()
1072 .rev()
1073 .find(|f| f.rect.contains(point))
1074 .map(|f| (f.id, f.rect))
1075 }
1076
1077 /// The **participating** focusables: those of the topmost modal scope when there is one
1078 /// (a focus trap), otherwise all of them.
1079 fn focus_pool(&self) -> &[Focusable] {
1080 match self.focus_scope_start {
1081 Some(start) => &self.focusables[start.min(self.focusables.len())..],
1082 None => &self.focusables,
1083 }
1084 }
1085
1086 /// Nearest focusable in the given **direction** (arrow navigation, a geometric policy):
1087 /// among the focusables whose centre lies on the right side, it minimises the distance
1088 /// along the main axis with a penalty on the cross-axis offset. `None` when there is
1089 /// nothing in that direction.
1090 pub fn focus_directional(
1091 &self,
1092 current: WidgetId,
1093 direction: FocusDirection,
1094 ) -> Option<WidgetId> {
1095 // The starting point may be outside the scope (focus from before it opened); the
1096 // **candidates**, though, are trapped inside it.
1097 let from = self
1098 .focusables
1099 .iter()
1100 .find(|f| f.id == current)
1101 .map(|f| &f.rect)?;
1102 let center = |r: &Rect| (r.x + r.width * 0.5, r.y + r.height * 0.5);
1103 let (fx, fy) = center(from);
1104
1105 let mut best: Option<(WidgetId, f32)> = None;
1106 for candidate in self.focus_pool() {
1107 let (id, rect) = (candidate.id, &candidate.rect);
1108 if id == current {
1109 continue;
1110 }
1111 let (cx, cy) = center(rect);
1112 // (how far ahead in the direction, the cross-axis offset)
1113 let (ahead, cross) = match direction {
1114 FocusDirection::Right => (cx - fx, (cy - fy).abs()),
1115 FocusDirection::Left => (fx - cx, (cy - fy).abs()),
1116 FocusDirection::Down => (cy - fy, (cx - fx).abs()),
1117 FocusDirection::Up => (fy - cy, (cx - fx).abs()),
1118 };
1119 // Inside a **cone** around the direction (not a plain half-plane): a candidate
1120 // almost aligned on the cross axis but barely "ahead" (slightly different widths)
1121 // is not a directional target.
1122 if ahead <= 0.5 || cross > ahead * 3.0 {
1123 continue;
1124 }
1125 let score = ahead + cross * 3.0;
1126 if best.map(|(_, s)| score < s).unwrap_or(true) {
1127 best = Some((id, score));
1128 }
1129 }
1130 best.map(|(id, _)| id)
1131 }
1132
1133 /// Next/previous focus stop for Tab, wrapping. With no current focus, the first (or
1134 /// the last).
1135 ///
1136 /// **Tree order, unless something said otherwise.** Stops carrying an explicit order
1137 /// are sorted ahead of those that do not, smallest first, and the sort is applied
1138 /// **within a traversal group** rather than across the whole frame — so a reordered
1139 /// dialog does not reshuffle the page behind it. Stops marked `skip` are passed over
1140 /// here while remaining reachable by a click: the keyboard's order and the pointer's
1141 /// reach are two different questions.
1142 pub fn focus_next(&self, current: Option<WidgetId>, forward: bool) -> Option<WidgetId> {
1143 let order = self.traversal_order();
1144 if order.is_empty() {
1145 return None;
1146 }
1147 let n = order.len();
1148 // A current focus **outside the scope** (taken before the modal opened) is treated
1149 // as "none": Tab enters the trap.
1150 match current.and_then(|c| order.iter().position(|id| *id == c)) {
1151 Some(i) => {
1152 let j = if forward {
1153 (i + 1) % n
1154 } else {
1155 (i + n - 1) % n
1156 };
1157 Some(order[j])
1158 }
1159 None => Some(order[if forward { 0 } else { n - 1 }]),
1160 }
1161 }
1162
1163 /// The Tab order: the participating stops, minus those that asked to be skipped,
1164 /// with each traversal group's members sorted among themselves.
1165 ///
1166 /// A **stable** sort on the order key, so everything without one keeps tree order and
1167 /// ties do too — the property that makes an explicit order a local statement rather
1168 /// than a rearrangement of the whole frame.
1169 pub fn traversal_order(&self) -> Vec<WidgetId> {
1170 let pool: Vec<&Focusable> = self.focus_pool().iter().filter(|f| !f.skip).collect();
1171 if pool.iter().all(|f| f.order.is_none()) {
1172 return pool.iter().map(|f| f.id).collect();
1173 }
1174 let mut out: Vec<WidgetId> = Vec::with_capacity(pool.len());
1175 let mut i = 0;
1176 while i < pool.len() {
1177 // A group's members are contiguous: the walk is depth-first, so a subtree's
1178 // stops arrive together.
1179 let group = pool[i].group;
1180 let mut j = i;
1181 while j < pool.len() && pool[j].group == group {
1182 j += 1;
1183 }
1184 let mut run: Vec<&Focusable> = pool[i..j].to_vec();
1185 run.sort_by(|a, b| {
1186 let key = |f: &Focusable| f.order.unwrap_or(f32::INFINITY);
1187 key(a).total_cmp(&key(b))
1188 });
1189 out.extend(run.iter().map(|f| f.id));
1190 i = j;
1191 }
1192 out
1193 }
1194
1195 /// What a keystroke means here: the messages it sends, in the order they should be
1196 /// applied.
1197 ///
1198 /// The resolution, in one place because it is the whole feature:
1199 ///
1200 /// 1. Only scopes **containing the focused stop** are candidates; with nothing
1201 /// focused, all of them are. Innermost first — `scopes` is filled on the way *out*
1202 /// of the walk, so that order is already the one wanted.
1203 /// 2. A [`crate::KeyboardListener`] gets the first refusal, and a `None` from it lets
1204 /// the stroke carry on.
1205 /// 3. A direct binding ([`crate::CallbackShortcuts`]) sends its message.
1206 /// 4. Otherwise a [`crate::Shortcuts`] binding names an **intent**, and the innermost
1207 /// [`crate::Actions`] that answers it supplies the message. An intent nobody
1208 /// answers does nothing — deliberately: a key bound to a meaning the current screen
1209 /// has no answer for should be inert, not an error.
1210 /// 5. Every [`crate::ActionListener`] watching that intent adds its message too.
1211 ///
1212 /// Empty means *nobody wanted it*, and the caller should carry on to whatever it would
1213 /// have done with the key.
1214 pub fn keystroke(&self, stroke: KeyStroke, focused: Option<WidgetId>) -> Vec<Msg> {
1215 let at = focused.and_then(|id| self.focusables.iter().position(|f| f.id == id));
1216 let covers = |range: &std::ops::Range<usize>| match at {
1217 Some(i) => range.contains(&i),
1218 None => true,
1219 };
1220
1221 for (range, on_key) in self.listeners.iter().rev() {
1222 if covers(range) {
1223 if let Some(msg) = on_key(stroke) {
1224 return vec![msg];
1225 }
1226 }
1227 }
1228
1229 let mut out = Vec::new();
1230 for scope in self.scopes.iter().filter(|s| covers(&s.range)) {
1231 if let Some((_, msg)) = scope.callbacks.iter().find(|(s, _)| stroke.matches(s)) {
1232 out.push(msg.clone());
1233 return out;
1234 }
1235 let Some((_, intent)) = scope.strokes.iter().find(|(s, _)| stroke.matches(s)) else {
1236 continue;
1237 };
1238 let answer = self
1239 .scopes
1240 .iter()
1241 .filter(|s| covers(&s.range))
1242 .find_map(|s| {
1243 s.actions
1244 .iter()
1245 .find(|(i, _)| i == intent)
1246 .map(|(_, m)| m.clone())
1247 });
1248 if let Some(msg) = answer {
1249 out.push(msg);
1250 for watcher in self.scopes.iter().filter(|s| covers(&s.range)) {
1251 for (i, m) in &watcher.listeners {
1252 if i == intent {
1253 out.push(m.clone());
1254 }
1255 }
1256 }
1257 }
1258 return out;
1259 }
1260 out
1261 }
1262
1263 /// Topmost scrollable area containing `point`.
1264 pub fn scroll_hit(&self, point: Point) -> Option<Scrollable> {
1265 self.scrollables
1266 .iter()
1267 .rev()
1268 .find(|area| area.viewport.contains(point))
1269 .copied()
1270 }
1271
1272 /// **Every** scrollable area containing `point`, innermost first — the whole stack a
1273 /// finger has under it.
1274 ///
1275 /// [`Self::scroll_hit`] answers *which one is on top*, which is the right question for
1276 /// a wheel or a scrollbar. A finger asks a different one: a strip that only slides
1277 /// across, sitting in a page that only scrolls down, cannot take a drag downwards, and
1278 /// the page behind it can. Deciding that needs the ones behind as well.
1279 pub fn scroll_chain(&self, point: Point) -> impl Iterator<Item = Scrollable> + '_ {
1280 self.scrollables
1281 .iter()
1282 .rev()
1283 .filter(move |area| area.viewport.contains(point))
1284 .copied()
1285 }
1286
1287 /// Frame of a **focusable** widget `id`, when it is present this frame — so the shell can
1288 /// find the focused field's geometry (vertical caret movement).
1289 pub fn widget_rect(&self, id: WidgetId) -> Option<Rect> {
1290 self.focusables
1291 .iter()
1292 .find(|f| f.id == id)
1293 .map(|f| f.rect)
1294 // Falls back to the **reorderables** registry. Kanban cards (and headers that are
1295 // reorderable but **not** sortable) are not focusable: without this fallback the
1296 // shell cannot find their bounds, and the whole **vertical** drag preview (ghost,
1297 // insertion line, reflow) as well as the *insert-after* routing stay dead.
1298 .or_else(|| {
1299 self.reorderables
1300 .iter()
1301 .find(|(rid, _)| *rid == id)
1302 .map(|(_, rect)| *rect)
1303 })
1304 // And to the detectors that take a drag, which report where a drag is in their
1305 // own coordinates (milestone 582): the whole box, whatever a clip hides of it.
1306 .or_else(|| {
1307 self.pans
1308 .iter()
1309 .rev()
1310 .find(|(pid, _, _)| *pid == id)
1311 .map(|(_, _, whole)| *whole)
1312 })
1313 }
1314
1315 /// The box of the inked surface `id`, when the frame has one — what the shell needs
1316 /// to start a splash: where inside it the finger landed, and how big it is.
1317 ///
1318 /// The **topmost** match wins, as the hit-test does: two inked surfaces can overlap,
1319 /// and the one that took the tap is the one drawn last.
1320 pub fn ink_box(&self, id: WidgetId) -> Option<Rect> {
1321 self.inks
1322 .iter()
1323 .rev()
1324 .find(|(iid, _)| *iid == id)
1325 .map(|(_, rect)| *rect)
1326 }
1327
1328 /// The identities of **every** focusable widget of the frame (the scope included) — so
1329 /// the shell can detect the focus **disappearing** (an overlay closed) and restore it.
1330 pub fn focusable_ids(&self) -> impl Iterator<Item = WidgetId> + '_ {
1331 self.focusables.iter().map(|f| f.id)
1332 }
1333
1334 /// The focusable widgets of the frame that take the focus when they appear
1335 /// ([`Widget::autofocus`]), in tree order.
1336 pub fn autofocus_ids(&self) -> impl Iterator<Item = WidgetId> + '_ {
1337 self.focusables.iter().filter(|f| f.autofocus).map(|f| f.id)
1338 }
1339
1340 /// The focus stops of the **form** `id` is part of, in tree order, each with its box
1341 /// this frame (unclipped: a field scrolled out of sight is still a field of the form).
1342 /// A stop in no [`crate::AutofillGroup`] is a form of one. Empty when `id` is not a
1343 /// focus stop this frame.
1344 ///
1345 /// Stops, not fields: which of them take part in autofill is a question for the
1346 /// widgets ([`crate::Widget::autofill_hints`]), which the shell has and this does not.
1347 pub fn form_of(&self, id: WidgetId) -> Vec<(WidgetId, Rect)> {
1348 let Some(stop) = self.focusables.iter().find(|f| f.id == id) else {
1349 return Vec::new();
1350 };
1351 match stop.form {
1352 Some(form) => self.group_stops(form),
1353 None => vec![(stop.id, stop.bounds)],
1354 }
1355 }
1356
1357 /// The [`crate::AutofillGroup`] focus stop `id` sits in, if it is a stop this frame
1358 /// and sits in one.
1359 pub fn form_group(&self, id: WidgetId) -> Option<WidgetId> {
1360 self.focusables.iter().find(|f| f.id == id)?.form
1361 }
1362
1363 /// Every focus stop inside the [`crate::AutofillGroup`] `group`, in tree order, with
1364 /// its unclipped box. Empty once the group has left the screen — which is the moment
1365 /// a form is finished with, and the platform may offer to save what was typed in it.
1366 pub fn group_stops(&self, group: WidgetId) -> Vec<(WidgetId, Rect)> {
1367 self.focusables
1368 .iter()
1369 .filter(|f| f.form == Some(group))
1370 .map(|f| (f.id, f.bounds))
1371 .collect()
1372 }
1373
1374 /// Frame (viewport) of the scrollable area `id`, when there is one — so the shell can find
1375 /// a multi-line field's width/height (caret following).
1376 pub fn scrollable_viewport(&self, id: WidgetId) -> Option<Rect> {
1377 self.scrollables
1378 .iter()
1379 .find(|area| area.id == id)
1380 .map(|area| area.viewport)
1381 }
1382
1383 /// The scroll offsets that would bring `id` **into view**, nearest region first.
1384 ///
1385 /// Empty when it is already in view, when the frame does not contain it, or when
1386 /// nothing around it scrolls. Nobody has to check first: an empty answer is the
1387 /// answer that nothing needs to move.
1388 ///
1389 /// Nested regions are walked from the inside out, and each is told where the target
1390 /// **ended up** rather than where it started. A sideways strip inside a page that
1391 /// scrolls down moves the target across, and the page then decides how far down it
1392 /// still is; asking both about the original box would have them fight over the same
1393 /// pixels and land somewhere neither wanted.
1394 pub fn reveal(&self, id: WidgetId, runtime: &crate::Runtime) -> Vec<(WidgetId, (f32, f32))> {
1395 let Some(stop) = self.focusables.iter().find(|f| f.id == id) else {
1396 return Vec::new();
1397 };
1398 let mut target = stop.bounds;
1399 let mut host = stop.scroll;
1400 let mut moves = Vec::new();
1401 // Regions nest a handful deep at most. The bound is a backstop against a chain
1402 // that loops, which cannot happen and would hang the frame if it did.
1403 for _ in 0..16 {
1404 let Some(hid) = host else { break };
1405 let Some(area) = self.scrollables.iter().find(|area| area.id == hid) else {
1406 break;
1407 };
1408 let current = runtime.scroll.get(&hid).copied().unwrap_or((0.0, 0.0));
1409 let (offset, shift) = area.reveal(target, current);
1410 if shift.0 != 0.0 || shift.1 != 0.0 {
1411 target = target.translate(shift.0, shift.1);
1412 moves.push((hid, offset));
1413 }
1414 host = area.host;
1415 }
1416 moves
1417 }
1418
1419 /// Every scrollable area of the frame — geometry, bounds and physics — which is
1420 /// what the runtime needs to drive momentum and edges.
1421 pub fn scroll_regions(&self) -> &[Scrollable] {
1422 &self.scrollables
1423 }
1424
1425 /// The area `id`, when it is present this frame.
1426 pub fn scroll_region(&self, id: WidgetId) -> Option<Scrollable> {
1427 self.scrollables.iter().find(|area| area.id == id).copied()
1428 }
1429
1430 /// SingleChildScrollView bounds `(id, max_x, max_y)` of every scrollable area.
1431 pub fn scrollable_maxes(&self) -> Vec<(WidgetId, f32, f32)> {
1432 self.scrollables
1433 .iter()
1434 .map(|area| (area.id, area.max_x, area.max_y))
1435 .collect()
1436 }
1437
1438 /// Scrollbar thumb under `point` (to start a drag).
1439 pub fn scrollbar_at(&self, point: Point) -> Option<Scrollbar> {
1440 self.scrollbars
1441 .iter()
1442 .rev()
1443 .find(|bar| bar.interactive && bar.opacity > 0.0 && bar.thumb.contains(point))
1444 .copied()
1445 }
1446
1447 /// The scrollbar a **pointer is near enough to wake**: inside its track, or within a
1448 /// tap target's reach of its thumb.
1449 ///
1450 /// Wider than [`Ui::scrollbar_at`], and — unlike it — it answers for a bar that has
1451 /// faded out entirely, which is the whole point. A bar nobody can see is a bar nobody
1452 /// can grab, so the reference lets a mouse coming near one bring it back first
1453 /// (`scrollbar.dart:766`); only then is it something to take hold of.
1454 pub fn scrollbar_near(&self, point: Point) -> Option<Scrollbar> {
1455 self.scrollbars
1456 .iter()
1457 .rev()
1458 .find(|bar| bar.interactive && bar.reach.contains(point))
1459 .copied()
1460 }
1461
1462 /// Topmost draggable widget under `point`: (id, its bounds).
1463 pub fn draggable_at(&self, point: Point) -> Option<(WidgetId, Rect)> {
1464 self.draggables
1465 .iter()
1466 .rev()
1467 .find(|(_, rect)| rect.contains(point))
1468 .map(|(id, rect)| (*id, *rect))
1469 }
1470
1471 /// Topmost **drag source** under `point`, with what it carries.
1472 pub fn drag_source_at(&self, point: Point) -> Option<DragSource> {
1473 self.drag_sources
1474 .iter()
1475 .rev()
1476 .find(|source| source.rect.contains(point))
1477 .copied()
1478 }
1479
1480 /// Topmost **drop target** under `point`.
1481 pub fn drop_zone_at(&self, point: Point) -> Option<DropZone> {
1482 self.drop_zones
1483 .iter()
1484 .rev()
1485 .find(|zone| zone.rect.contains(point))
1486 .copied()
1487 }
1488
1489 /// Topmost **reorderable** widget under `point`: its id. The basis of reordering
1490 /// drag-and-drop (the source on press, the target on drop) — independent of clickability.
1491 pub fn reorderable_at(&self, point: Point) -> Option<WidgetId> {
1492 self.reorderables
1493 .iter()
1494 .rev()
1495 .find(|(_, rect)| rect.contains(point))
1496 .map(|(id, _)| *id)
1497 }
1498
1499 /// **Every** reorderable under `point`, topmost first.
1500 ///
1501 /// [`Self::reorderable_at`] answers *which one is on top*, which is the right question
1502 /// for a press: whatever is nearest the finger is what the finger grabbed. A **drop**
1503 /// asks a different one, because the thing on top may be a grip that nothing can be
1504 /// dropped on — see [`Widget::reorder_droppable`] — and the row it belongs to, which
1505 /// can, is the one behind it.
1506 pub fn reorderables_at(&self, point: Point) -> impl Iterator<Item = WidgetId> + '_ {
1507 self.reorderables
1508 .iter()
1509 .rev()
1510 .filter(move |(_, rect)| rect.contains(point))
1511 .map(|(id, _)| *id)
1512 }
1513
1514 /// Every **reorderable** of the frame, with its box, in paint order.
1515 pub fn reorderables(&self) -> &[(WidgetId, Rect)] {
1516 &self.reorderables
1517 }
1518
1519 /// Topmost **interactive** viewport (`InteractiveViewer`) under `point`: (id, its screen
1520 /// viewport). The shell routes panning and zooming to it.
1521 pub fn interactive_at(&self, point: Point) -> Option<(WidgetId, Rect)> {
1522 self.interactives
1523 .iter()
1524 .rev()
1525 .find(|(_, rect)| rect.contains(point))
1526 .map(|(id, rect)| (*id, *rect))
1527 }
1528
1529 /// The regions the mouse is in at `point`, the innermost first, each with its whole box
1530 /// (milestone 583).
1531 ///
1532 /// Every region under the pointer is in — a region inside another is in both — except
1533 /// those an **opaque** region hides: once one is found, only the regions it is inside
1534 /// are still in, and a region behind it that it is not inside is not.
1535 pub fn hover_regions_at(&self, point: Point) -> Vec<(WidgetId, Rect, crate::HoverRegion)> {
1536 let mut found: Vec<&HoverEntry> = Vec::new();
1537 // The regions an opaque one found so far is inside: its parent chain.
1538 let mut hidden_behind: Option<Vec<WidgetId>> = None;
1539 for region in self.hover_regions.iter().rev() {
1540 if !region.seen.contains(point) {
1541 continue;
1542 }
1543 if let Some(chain) = &hidden_behind {
1544 if !chain.contains(®ion.id) {
1545 continue;
1546 }
1547 }
1548 found.push(region);
1549 if region.spec.opaque && hidden_behind.is_none() {
1550 let mut chain = Vec::new();
1551 let mut parent = region.parent;
1552 while let Some(id) = parent {
1553 chain.push(id);
1554 parent = self
1555 .hover_regions
1556 .iter()
1557 .rev()
1558 .find(|r| r.id == id)
1559 .and_then(|r| r.parent);
1560 }
1561 hidden_behind = Some(chain);
1562 }
1563 }
1564 found
1565 .into_iter()
1566 .map(|region| (region.id, region.whole, region.spec))
1567 .collect()
1568 }
1569
1570 /// The whole box of the region `id` in this frame, if it is in it.
1571 pub fn hover_region_rect(&self, id: WidgetId) -> Option<Rect> {
1572 self.hover_regions
1573 .iter()
1574 .rev()
1575 .find(|region| region.id == id)
1576 .map(|region| region.whole)
1577 }
1578
1579 /// The widgets hearing the pointer's raw events under `point`, the innermost first, each
1580 /// with its whole box (milestone 586).
1581 pub fn pointer_listeners_at(&self, point: Point) -> Vec<(WidgetId, Rect)> {
1582 self.pointer_listeners
1583 .iter()
1584 .rev()
1585 .filter(|(_, seen, _)| seen.contains(point))
1586 .map(|(id, _, whole)| (*id, *whole))
1587 .collect()
1588 }
1589
1590 /// The innermost detector that takes a drag under `point`, and its box (milestone 582):
1591 /// the one drawn last, as the hit-test chooses.
1592 pub fn pan_at(&self, point: Point) -> Option<(WidgetId, Rect)> {
1593 self.pans
1594 .iter()
1595 .rev()
1596 .find(|(_, seen, _)| seen.contains(point))
1597 .map(|(id, seen, _)| (*id, *seen))
1598 }
1599
1600 /// Interactive viewports `(id, screen viewport)`, to drive the inertia (fling) and the
1601 /// clamping of the pan on the framework's side.
1602 pub fn interactive_bounds(&self) -> Vec<(WidgetId, Rect)> {
1603 self.interactives.clone()
1604 }
1605}
1606
1607/// Paints a **striped band** along the edge of every box whose children ran past it.
1608///
1609/// Milestone 335 taught the layout to notice an overflow and the shell to say so in the
1610/// console. That is the half a developer reads; this is the half a *screenshot* shows —
1611/// and a screenshot is what a bug report is made of. Three of this framework's own
1612/// milestones went looking for defects that a band would have pointed at: a delete button
1613/// laid out past the card (333, 334), a segmented control 221 px outside its parent (335).
1614///
1615/// The look is the reference's, because the point of it is to be recognised on sight:
1616/// black and yellow diagonal stripes, three quarters opaque, over a tenth of the box along
1617/// the offending edge, with the edge and the number written across it. Not the mechanism,
1618/// though — the reference paints one repeating gradient and this paints the stripes,
1619/// because a repeating diagonal gradient is a shader feature and a parallelogram is four
1620/// points.
1621///
1622/// **Debug builds only.** A band is a message to whoever is building the application, and
1623/// in a release build there is nobody to read it — the reference draws the same line.
1624fn paint_overflow_bands(scene: &mut Scene, overflows: &[Overflowing]) {
1625 if !cfg!(debug_assertions) || overflows.is_empty() {
1626 return;
1627 }
1628 // The reference's two colours and its 10 % band, exactly.
1629 const BLACK: Color = Color::rgba(0.0, 0.0, 0.0, 0.75);
1630 const YELLOW: Color = Color::rgba(1.0, 1.0, 0.0, 0.75);
1631 const FRACTION: f32 = 0.1;
1632 /// The stripes run at 45°; this is their period measured along the x axis.
1633 const PERIOD: f32 = 14.0;
1634
1635 let (outer, outer_bounds) = (scene.current_clip(), scene.current_bounds());
1636 scene.set_clip(Rect::UNBOUNDED);
1637 for over in overflows {
1638 let r = over.rect;
1639 let band = match over.side {
1640 Side::Left => Rect::new(r.x, r.y, r.width * FRACTION, r.height),
1641 Side::Right => Rect::new(
1642 r.x + r.width * (1.0 - FRACTION),
1643 r.y,
1644 r.width * FRACTION,
1645 r.height,
1646 ),
1647 Side::Top => Rect::new(r.x, r.y, r.width, r.height * FRACTION),
1648 Side::Bottom => Rect::new(
1649 r.x,
1650 r.y + r.height * (1.0 - FRACTION),
1651 r.width,
1652 r.height * FRACTION,
1653 ),
1654 };
1655 if band.width <= 0.0 || band.height <= 0.0 {
1656 continue;
1657 }
1658 scene.set_clip(band);
1659 scene.fill_rect(band, BLACK);
1660 // One parallelogram per stripe, sheared by the band's height so that every one
1661 // of them crosses it at 45° whatever shape the band is.
1662 let shear = band.height;
1663 let mut x = band.x - shear;
1664 while x < band.x + band.width {
1665 let stripe = Path::new()
1666 .move_to(Point::new(x, band.y))
1667 .line_to(Point::new(x + PERIOD / 2.0, band.y))
1668 .line_to(Point::new(x + PERIOD / 2.0 + shear, band.y + band.height))
1669 .line_to(Point::new(x + shear, band.y + band.height))
1670 .close();
1671 scene.fill_path(&stripe, YELLOW);
1672 x += PERIOD;
1673 }
1674 // The label is **not** clipped to the band: a vertical one is usually longer than
1675 // the box is tall, and half a sentence is worse than a sentence written over
1676 // whatever is beside it. The reference does not clip it either.
1677 scene.set_clip(Rect::UNBOUNDED);
1678 scene.set_bounds(Rect::UNBOUNDED);
1679 paint_overflow_label(scene, band, over);
1680 }
1681 scene.set_clip(outer);
1682 scene.set_bounds(outer_bounds);
1683}
1684
1685/// Writes the reference's sentence across a band: which edge overflowed, and by how much.
1686///
1687/// The console already says it — but the console is on the developer's machine and the
1688/// band is on the device, and a photograph of a phone is what half the bug reports in the
1689/// world are made of. A striped edge says *something* is too big; `RIGHT OVERFLOWED BY 86
1690/// PIXELS` says which edge, and by enough that you can tell a forgotten padding from a
1691/// missing wrap without running anything.
1692///
1693/// The words are the reference's, exactly, so that searching for them finds the same
1694/// answers. So are the numbers: 7.5 px, the heaviest weight there is, dark red on an
1695/// opaque white plate — a label that must stay readable over stripes cannot be subtle —
1696/// centred on the band's outer edge and turned a quarter turn on the vertical ones.
1697fn paint_overflow_label(scene: &mut Scene, band: Rect, over: &Overflowing) {
1698 /// The reference's label metrics.
1699 const SIZE: f32 = 7.5;
1700 /// The gap between the label and the outer edge of the band.
1701 const PAD: f32 = 1.0;
1702 /// `0xFF900000`.
1703 const INK: Color = Color::rgb(0.5647059, 0.0, 0.0);
1704
1705 let side = match over.side {
1706 Side::Left => "LEFT",
1707 Side::Right => "RIGHT",
1708 Side::Top => "TOP",
1709 Side::Bottom => "BOTTOM",
1710 };
1711 let text = format!("{side} OVERFLOWED BY {} PIXELS", format_pixels(over.amount));
1712 // The reference asks for an 800 weight; the heaviest this framework has is bold.
1713 let style = TextStyle::new(SIZE).weight(FontWeight::Bold);
1714 let size = frus_text::measure_styled(&text, SIZE, FontWeight::Bold, false);
1715
1716 // Where the middle of the label's leading edge goes, before any rotation, and by how
1717 // much the whole thing then turns about that point.
1718 let (anchor, angle) = match over.side {
1719 Side::Left => (
1720 Point::new(band.x + SIZE + PAD, band.y + band.height / 2.0),
1721 std::f32::consts::FRAC_PI_2,
1722 ),
1723 Side::Right => (
1724 Point::new(band.x + band.width - SIZE - PAD, band.y + band.height / 2.0),
1725 -std::f32::consts::FRAC_PI_2,
1726 ),
1727 Side::Top => (Point::new(band.x + band.width / 2.0, band.y + PAD), 0.0),
1728 Side::Bottom => (
1729 Point::new(band.x + band.width / 2.0, band.y + band.height - SIZE - PAD),
1730 0.0,
1731 ),
1732 };
1733 if angle == 0.0 {
1734 let at = Point::new(anchor.x - size.width / 2.0, anchor.y);
1735 scene.fill_rect(Rect::from_point_size(at, size), Color::WHITE);
1736 scene.text(at, text, &style.resolved(), INK);
1737 return;
1738 }
1739 // A rotation of a group, not of a glyph: the plate and the sentence turn together and
1740 // neither has to know it is turning.
1741 //
1742 // The group is painted **at the origin** rather than where it lands, because a layer
1743 // is rendered flat into a window-sized texture before it is composited: a vertical
1744 // label is written across a box near the right edge, so laid out flat it would run
1745 // off the texture and lose its last word before the rotation ever brought it back
1746 // inside. The transform is the one that carries the origin to where the label goes —
1747 // shift it half its width to the left, turn it, and land it on the anchor.
1748 let flat = Rect::from_point_size(Point::ZERO, size);
1749 let matrix = Affine::translation(-size.width / 2.0, 0.0)
1750 .then(Affine::rotation(angle))
1751 .then(Affine::translation(anchor.x, anchor.y));
1752 scene.transformed(LayerTransform::new(matrix), move |scene: &mut Scene| {
1753 scene.fill_rect(flat, Color::WHITE);
1754 scene.text(flat.origin(), text, &style.resolved(), INK);
1755 });
1756}
1757
1758/// How the reference writes an overflow: whole pixels past ten, one decimal past one, and
1759/// three significant figures below that — because the difference between 0.5 px and
1760/// 0.0001 px is the difference between a layout bug and a rounding error.
1761fn format_pixels(value: f32) -> String {
1762 if value > 10.0 {
1763 format!("{value:.0}")
1764 } else if value > 1.0 {
1765 format!("{value:.1}")
1766 } else {
1767 // Three significant figures: the first one sits at the first non-zero decimal.
1768 let leading = if value > 0.0 {
1769 (-value.abs().log10().floor()) as i32
1770 } else {
1771 0
1772 };
1773 format!("{value:.*}", (leading + 2).clamp(0, 12) as usize)
1774 }
1775}
1776
1777/// Identity of the `index`-th child: **by key** when the child declares one (stable whatever
1778/// its position), **positional** otherwise. It must be used everywhere a child identity is
1779/// derived (render, collection, lookup, animations) so they all stay consistent.
1780pub(crate) fn child_id<Msg>(parent: WidgetId, index: usize, child: &dyn Widget<Msg>) -> WidgetId {
1781 match child.key() {
1782 Some(key) => parent.keyed(key),
1783 None => parent.child(index),
1784 }
1785}
1786
1787/// A widget's **effective** style for layout: its `style()`, whose size is **replaced by the
1788/// runtime's interpolated size** when the widget is animated (`Widget::anim_size` +
1789/// `Container::animated_size`). This is the only place where an animated size enters layout —
1790/// used **identically** by [`build_layout`] and by the cache fingerprint (`hash_node`), which
1791/// is what keeps them consistent (the cache stays invalid for as long as the size moves).
1792pub(crate) fn effective_style<Msg>(
1793 widget: &dyn Widget<Msg>,
1794 id: WidgetId,
1795 runtime: &Runtime,
1796 theme: &Theme,
1797) -> frus_layout::Style {
1798 // The theme's say on size and spacing (milestone 309), before the runtime's
1799 // animated overrides below — an animation in flight wins over a resting default.
1800 let mut style = widget.style_themed(theme);
1801 if widget.anim_size().is_some() {
1802 if let Some(size) = runtime.anim_size(id) {
1803 style.width = frus_layout::Dimension::Length(size.width);
1804 style.height = frus_layout::Dimension::Length(size.height);
1805 }
1806 }
1807 if widget.anim_padding().is_some() {
1808 if let Some(padding) = runtime.anim_padding(id) {
1809 style.padding = padding;
1810 }
1811 }
1812 // A share of the parent, growing or shrinking. `Percent` and not `Length`, because
1813 // the whole point of the quantity is that it does not know what it will come to — and
1814 // an axis whose factor is unset goes back to following its content rather than to
1815 // nought, which is what "unset" has always meant here.
1816 if widget.anim_fractions().is_some() {
1817 if let Some((width, height)) = runtime.anim_fractions(id) {
1818 let dim = |factor: Option<f32>| match factor {
1819 Some(f) => frus_layout::Dimension::Percent(f),
1820 None => frus_layout::Dimension::Auto,
1821 };
1822 style.width = dim(width);
1823 style.height = dim(height);
1824 }
1825 }
1826 // A dismissed item closing its gap. It collapses along the axis it was **not**
1827 // swiped along — a row swiped sideways loses its height — which is what makes the
1828 // neighbours slide up rather than the row narrow to a sliver. Only an explicit
1829 // length can shrink: an `Auto` box has no number to scale, which is why
1830 // `Dismissible` asks for a size (see its docs).
1831 // A sheet's panel, as tall as the retained share of its box. The same `Percent` as a
1832 // fraction above, for the same reason: the share is the quantity, and the box it is a
1833 // share of is the layout's to know. Hashed through here as well, so the cache misses
1834 // on every frame the sheet moves.
1835 if let Some(spec) = widget.sheet() {
1836 style.height = frus_layout::Dimension::Percent(runtime.sheet_size(id, spec));
1837 }
1838 if let Some(spec) = widget.dismissible() {
1839 if let Some(factor) = runtime.dismiss_extent_factor(id) {
1840 let axis = if spec.axis.is_horizontal() {
1841 &mut style.height
1842 } else {
1843 &mut style.width
1844 };
1845 if let frus_layout::Dimension::Length(extent) = *axis {
1846 *axis = frus_layout::Dimension::Length(extent * factor);
1847 }
1848 }
1849 }
1850 style
1851}
1852
1853/// Builds the main layout tree (a scrollable is a **leaf**). `id`/`runtime` are what inject
1854/// the animated size through [`effective_style`], following the walk's identity scheme
1855/// (`child_id`) **exactly**.
1856pub(crate) fn build_layout<'a, Msg>(
1857 widget: &'a dyn Widget<Msg>,
1858 id: WidgetId,
1859 runtime: &'a Runtime,
1860 theme: &Theme,
1861 layout: &mut Layout<'a, BaselineData>,
1862) -> NodeId {
1863 let (node, fills) = build_layout_scoped(widget, id, runtime, theme, layout, true);
1864 // A root that wants to fill has no parent to fill: the flex machinery below needs one
1865 // on each side of the question. A percentage of the room the layout is being computed
1866 // in is the same answer without a parent, and it degrades to hugging the content when
1867 // that room is unbounded — a scrollable measuring its content, a natural size.
1868 if fills.horizontal {
1869 layout.fill_root(node, true);
1870 }
1871 if fills.vertical {
1872 layout.fill_root(node, false);
1873 }
1874 node
1875}
1876
1877/// The axes a subtree asks to **fill** rather than shrink-wrap.
1878///
1879/// It is not a property of one widget. A column whose row fills the width is itself as
1880/// wide as the room it was given, because the row inside it took that room — so the
1881/// request travels up as the layout is built, and each container answers it with the one
1882/// thing a container can do about it: grow along its own axis, or stretch across it.
1883#[derive(Clone, Copy, Default)]
1884pub(crate) struct Fills {
1885 horizontal: bool,
1886 vertical: bool,
1887 /// The axes on which **this** node's size is only a default, replaced by the room on
1888 /// offer when the fill is granted (milestone 590). Never passed up: it is about this
1889 /// node's own style, not the subtree's request.
1890 soft_horizontal: bool,
1891 soft_vertical: bool,
1892}
1893
1894impl Fills {
1895 /// What a widget asks for on its own account.
1896 ///
1897 /// A straight copy since milestone 405: the widget's answer already has a flag per
1898 /// axis, where it used to be one direction and a container that wanted both had no way
1899 /// to say so.
1900 fn own<Msg>(widget: &dyn Widget<Msg>, theme: &Theme) -> Self {
1901 let asked = widget.fill_axes(theme);
1902 let soft = widget.soft_extent();
1903 Fills {
1904 horizontal: asked.horizontal,
1905 vertical: asked.vertical,
1906 soft_horizontal: soft.horizontal && asked.horizontal,
1907 soft_vertical: soft.vertical && asked.vertical,
1908 }
1909 }
1910
1911 fn merge(self, other: Fills) -> Self {
1912 Fills {
1913 horizontal: self.horizontal || other.horizontal,
1914 vertical: self.vertical || other.vertical,
1915 // This node's own; a child's default is not this node's.
1916 ..self
1917 }
1918 }
1919
1920 /// Whether this node's size on one axis is only a default.
1921 fn soft(self, horizontal: bool) -> bool {
1922 if horizontal {
1923 self.soft_horizontal
1924 } else {
1925 self.soft_vertical
1926 }
1927 }
1928
1929 /// The half of a child's request a container passes on to **its** parent, given
1930 /// which way the container runs. Along its own axis a container divides the room up
1931 /// and the request stops there; across it, the container's size *is* the child's, so
1932 /// the request has to keep going.
1933 /// Whether one axis is asked for.
1934 fn wants(self, horizontal: bool) -> bool {
1935 if horizontal {
1936 self.horizontal
1937 } else {
1938 self.vertical
1939 }
1940 }
1941
1942 /// Drops any axis this box was **given a size on**: it has already been told how big
1943 /// to be, and a request to fill cannot reach past that answer.
1944 fn bounded_by(self, style: &frus_layout::Style) -> Self {
1945 let auto = |d| matches!(d, frus_layout::Dimension::Auto);
1946 // A box with an aspect ratio decides its children's size from its own, as the
1947 // reference's `AspectRatio` hands its child tight constraints: nothing inside it
1948 // reaches past it (milestone 633).
1949 if style.aspect_ratio.is_some() {
1950 return Fills {
1951 horizontal: false,
1952 vertical: false,
1953 ..self
1954 };
1955 }
1956 Fills {
1957 horizontal: self.horizontal && auto(style.width),
1958 vertical: self.vertical && auto(style.height),
1959 ..self
1960 }
1961 }
1962
1963 fn across(self, direction: frus_layout::FlexDirection) -> Self {
1964 if direction.is_horizontal() {
1965 Fills {
1966 horizontal: false,
1967 ..self
1968 }
1969 } else {
1970 Fills {
1971 vertical: false,
1972 ..self
1973 }
1974 }
1975 }
1976}
1977
1978/// A layout leaf's **text baseline**, when it has one: the distance from the top of its
1979/// box down to the line its letters sit on.
1980///
1981/// It rides on the layout tree rather than being asked of the widgets afterwards because
1982/// only the layout knows where a node ended up, and only the walk that built it knows
1983/// which branch it took — a scrollable, a stack and a page view are all *leaves* here,
1984/// with their contents laid out elsewhere, and a second walk guessing at that would be a
1985/// copy of this one waiting to drift out of step.
1986pub(crate) type BaselineData = Option<f32>;
1987
1988/// An owned copy of a theme, **made in a frame of its own**.
1989///
1990/// `#[inline(never)]` is the whole point: inlined, the eleven-kilobyte temporary is built
1991/// in the caller's frame, and the caller here is the recursive walk that pays for its
1992/// frame once per level of the tree. Behind the call it is built, copied into the
1993/// allocation, and gone before the walk recurses.
1994#[inline(never)]
1995fn owned_theme(theme: &Theme) -> std::rc::Rc<Theme> {
1996 std::rc::Rc::new(theme.clone())
1997}
1998
1999/// The body of [`build_layout`], carrying whether baselines are still being collected.
2000/// An [`crate::IgnoreBaseline`] turns them off for its subtree — the widgets inside still
2001/// have baselines, and the point is that nothing above may see them.
2002fn build_layout_scoped<'a, Msg>(
2003 widget: &'a dyn Widget<Msg>,
2004 id: WidgetId,
2005 runtime: &'a Runtime,
2006 theme: &Theme,
2007 layout: &mut Layout<'a, BaselineData>,
2008 baselines: bool,
2009) -> (NodeId, Fills) {
2010 // A component is built into what it stands for before anything is asked of the node,
2011 // the scope it introduces included — see `Widget::expand` — under the scope a wrapper
2012 // around it introduces (milestone 642).
2013 expand_scoped(widget, id, runtime, theme);
2014 // A themed subtree lays out under **its** theme, not the frame's: a theme reaches
2015 // sizes and spacing (milestone 309), so this has to happen here and not only at paint
2016 // time. `hash_node`, which fingerprints this same walk for the relayout cache, makes
2017 // the same swap — the two staying in step is what keeps the cache honest.
2018 let scoped = scoped_theme(widget, id, runtime, theme);
2019 let theme = scoped.as_deref().unwrap_or(theme);
2020 // And a **scoped surface**, the same idea one milestone later: a shell that hands a slot
2021 // a narrowed description narrows it for everything the slot builds, the deferred build
2022 // below included. Held for this subtree and put back on the way out.
2023 let _surface = widget
2024 .media_override(crate::MediaQuery::of())
2025 .map(crate::MediaQuery::install);
2026 // And the **shell**, the third inherited thing (milestone 422): a slot told what shell
2027 // it stands in composes differently — a bar grows a menu button — so it has to be in
2028 // force before `build_themed` below, exactly as the surface is.
2029 let _shell = widget.scaffold_override().map(crate::ScaffoldInfo::install);
2030 let _scrolling = widget
2031 .scroll_behavior_override()
2032 .map(crate::ScrollConfiguration::install);
2033 // A subtree that could not be composed until the theme was known (`ThemeBuilder`).
2034 // It has to happen **before** anything reads `children()`, and under the subtree's
2035 // own theme, which is why it sits after the swap above rather than at the call site.
2036 widget.build_in(id, runtime, theme);
2037 // Everything below an `IgnoreBaseline` keeps its baseline and loses the right to be
2038 // seen: the flag is narrowed once, here, so no branch below has to remember.
2039 let baselines = baselines && !widget.ignores_baseline();
2040 // A leaf's own baseline, or nothing when this subtree is being ignored.
2041 let own_baseline = if baselines {
2042 widget.text_baseline(theme)
2043 } else {
2044 None
2045 };
2046 // `Baseline`: the child is pushed down until **its** baseline lands `target` pixels
2047 // from the top of this box, and this box grows to contain it. If the child's own
2048 // baseline is already lower than that, there is nowhere to push it up to and the
2049 // child is top-aligned instead — the same answer the reference gives.
2050 if let Some(target) = widget.baseline_target() {
2051 let mut style = effective_style(widget, id, runtime, theme);
2052 if let Some(child) = widget.children().first() {
2053 let child = child.as_ref();
2054 let cid = child_id(id, 0, child);
2055 // A child with no baseline of its own is treated as if its baseline were its
2056 // bottom edge, which is what a box with no text amounts to.
2057 let child_baseline = natural_baseline(child, cid, runtime, theme)
2058 .unwrap_or_else(|| natural_size(child, cid, runtime, theme).height);
2059 style.padding.top += (target - child_baseline).max(0.0);
2060 let (node, fills) = build_layout_scoped(child, cid, runtime, theme, layout, baselines);
2061 return (layout.container(style, &[node]), fills);
2062 }
2063 return (layout.leaf(style, None), Fills::default());
2064 }
2065 // `RotatedBox`: a leaf whose box is the child's **natural** size, with its dimensions
2066 // **swapped** for an odd quarter turn (the rotation does affect layout). The child itself
2067 // is laid out separately (at render time).
2068 if let Some(q) = widget.rotated_quarter_turns() {
2069 let mut style = effective_style(widget, id, runtime, theme);
2070 if let Some(child) = widget.children().first() {
2071 let nat = natural_size(
2072 child.as_ref(),
2073 child_id(id, 0, child.as_ref()),
2074 runtime,
2075 theme,
2076 );
2077 let (w, h) = if q.rem_euclid(4) % 2 != 0 {
2078 (nat.height, nat.width)
2079 } else {
2080 (nat.width, nat.height)
2081 };
2082 style.width = frus_layout::Dimension::Length(w);
2083 style.height = frus_layout::Dimension::Length(h);
2084 }
2085 return (layout.leaf(style, own_baseline), Fills::default());
2086 }
2087 // `Intrinsic`: one axis is taken from what the content would **like** to be, not from
2088 // the space on offer. The content is measured once, unconstrained, and the answer is
2089 // written into this node's style as a length — the same trick `RotatedBox` uses, except
2090 // that here the child stays inside, laid out normally within the size it asked for.
2091 if let Some((axis, step)) = widget.intrinsic() {
2092 let mut style = effective_style(widget, id, runtime, theme);
2093 if let Some(child) = widget.children().first() {
2094 let child = child.as_ref();
2095 let cid = child_id(id, 0, child);
2096 let nat = natural_size(child, cid, runtime, theme);
2097 let quantise = |extent: f32| match step {
2098 Some(step) if step > 0.0 => (extent / step).ceil() * step,
2099 _ => extent,
2100 };
2101 match axis {
2102 crate::constraints::IntrinsicAxis::Width => {
2103 style.width = frus_layout::Dimension::Length(quantise(nat.width));
2104 }
2105 crate::constraints::IntrinsicAxis::Height => {
2106 style.height = frus_layout::Dimension::Length(quantise(nat.height));
2107 }
2108 }
2109 let (node, fills) = build_layout_scoped(child, cid, runtime, theme, layout, baselines);
2110 return (layout.container(style, &[node]), fills);
2111 }
2112 return (layout.leaf(style, own_baseline), Fills::default());
2113 }
2114 // `OverflowBox`: a leaf, because its child is laid out **separately**, to constraints of
2115 // its own. That separation is the whole feature — a child sharing this node's layout
2116 // could never be bigger than it.
2117 if widget.overflow_box().is_some() {
2118 return (
2119 layout.leaf(effective_style(widget, id, runtime, theme), own_baseline),
2120 Fills::default(),
2121 );
2122 }
2123 // A box that **transforms the space on offer**: its child is laid out in a box derived
2124 // from this one's, in a tree of its own, and this box is then as big as what came back
2125 // — held to what it was itself offered, which is the reference's
2126 // `constraints.constrain(child.size)`. `UnconstrainedBox` is this branch with the
2127 // constraint taken away.
2128 if let Some(transform) = widget.constraints_transform() {
2129 let style = effective_style(widget, id, runtime, theme);
2130 let child = widget.children().first().map(|c| c.as_ref());
2131 let owned = owned_theme(theme);
2132 let animated = widget.animated_size();
2133 let factor = widget.size_factor();
2134 let measure: frus_layout::MeasureFn<'a> = Box::new(move |w, h| {
2135 let Some(child) = child else {
2136 return Size::new(0.0, 0.0);
2137 };
2138 let (aw, free_x, fill_x) = transform.width.offered(w);
2139 let (ah, free_y, fill_y) = transform.height.offered(h);
2140 let mut inner: Layout<BaselineData> = Layout::new();
2141 let node = build_layout(child, child_id(id, 0, child), runtime, &owned, &mut inner);
2142 // **Handed** every axis that has a number, **asked** about every axis that does
2143 // not. Merely constraining them instead would leave a child with no size of its
2144 // own — a plain container — hugging at nothing, and a box asked how big its child
2145 // wanted to be would come back empty. A loose axis is the exception, and says so:
2146 // there the number is only the most the child may take (milestone 598).
2147 inner.compute_axes(node, aw, ah, [free_x, free_y], [fill_x, fill_y]);
2148 let mut size = inner.size_of(node);
2149 // A box following its child's size answers with the size it has got to, and is
2150 // told when the child's has changed (milestone 594). An intrinsic question is
2151 // answered and not recorded: on an axis the child is **given**, the layout
2152 // offering nothing (how big with no limit) or zero (how small could it be). Either
2153 // makes a paragraph a size it never ends up at — one line, or one word a line.
2154 // On an axis the child decides, the offer is not read, so it asks nothing.
2155 if let Some(spec) = &animated {
2156 let asks = |rule, offer: Option<f32>| {
2157 rule == crate::constraints::AxisConstraint::AsGiven
2158 && offer.is_none_or(|v| v <= 0.0)
2159 };
2160 let probe = asks(transform.width, w) || asks(transform.height, h);
2161 let shown = runtime
2162 .size_anims
2163 .borrow_mut()
2164 .observe(id, size, spec, !probe);
2165 // Whole pixels, rounded up and then held to the offer below: a size on its
2166 // way between two others is a fraction, and a box rounded down from one is
2167 // one its content no longer fits in (milestone 289).
2168 size = Size::new(frus_core::fits(shown.width), frus_core::fits(shown.height));
2169 }
2170 // A fraction of the child, on each axis, in whole pixels (milestone 596).
2171 if let Some((across, down)) = factor {
2172 size = Size::new(
2173 frus_core::fits(size.width * across.max(0.0)),
2174 frus_core::fits(size.height * down.max(0.0)),
2175 );
2176 }
2177 // Held to the offer: a child too big for the room spills, and the box stays the
2178 // size the room was.
2179 Size::new(
2180 size.width.min(w.unwrap_or(f32::INFINITY)),
2181 size.height.min(h.unwrap_or(f32::INFINITY)),
2182 )
2183 });
2184 return (
2185 layout.measured_leaf(style, own_baseline, measure),
2186 // An animated box asks for the room on the axes its child is given
2187 // (milestone 594); a plain transform box asks for nothing.
2188 Fills::own(widget, theme),
2189 );
2190 }
2191 // A `LayoutBuilder` **is measured**: it builds its content from the space offered and
2192 // is then as big as what it built, which is the reference's
2193 // `size = constraints.constrain(child.size)`. It cannot be a plain leaf, because a
2194 // leaf answers before it has been asked and there is nothing to answer with until the
2195 // box is known; and it cannot be a container, because its child does not exist yet.
2196 //
2197 // Taffy calls the closure during the computation with the space actually available —
2198 // the same moment the reference runs its layout callback — and the closure builds the
2199 // subtree, lays it out in a `Layout` of its own, and hands back the size. An axis the
2200 // style pins is still the style's: taffy does not ask about a dimension it already
2201 // knows, so `LayoutBuilder::height(200.0)` behaves exactly as it did.
2202 if let Some(build) = widget.layout_builder() {
2203 let style = effective_style(widget, id, runtime, theme);
2204 // The closure needs an **owned** theme: a themed subtree's theme is a local in
2205 // this function, so it cannot be borrowed for as long as the closure lives. The
2206 // runtime and the widget are borrowed, which is the whole reason `Layout` carries
2207 // a lifetime.
2208 //
2209 // This is a clone of eleven kilobytes, and it used to be a silent one — `Theme`
2210 // was `Copy` until milestone 448, so `*theme` read like a pointer copy and was
2211 // not. It happens once per `LayoutBuilder`, not once per node.
2212 //
2213 // **Behind an `Rc`, and made somewhere else**, because the cost that mattered was
2214 // not the copy. A `Theme` local here and a closure that captures one are two
2215 // slots of eleven kilobytes in *this* function's frame, and a frame is charged to
2216 // every level of the walk whether or not the branch is taken: 24 736 bytes a
2217 // level, which overflowed a Windows main thread's megabyte at about forty. The
2218 // `Rc` makes the capture a pointer, and `owned_theme` keeps the copy in a frame
2219 // that pops before the recursion goes any deeper.
2220 let owned = owned_theme(theme);
2221 let cid = id.child(0);
2222 let measure: frus_layout::MeasureFn<'a> = Box::new(move |w, h| {
2223 // What taffy offers. `None` is an *intrinsic* question — how big would you
2224 // be with no limit, or with none at all — and there is no honest answer to
2225 // it here: finding out means running the application's callback
2226 // speculatively. The reference refuses these outright (`computeDryLayout`
2227 // asserts); we build at the offered numbers, substituting zero for what is
2228 // not offered, and leave the unoffered axis free in the nested computation
2229 // so the content's own size comes back.
2230 let offered = Size::new(w.unwrap_or(0.0), h.unwrap_or(0.0));
2231 let child = build(offered);
2232 let mut inner: Layout<BaselineData> = Layout::new();
2233 let node = build_layout(child.as_ref(), cid, runtime, &owned, &mut inner);
2234 // The content is **handed** the offered box, not asked what it would like:
2235 // it was built from that box. An axis that was not offered is the one being
2236 // asked about, and stays free so the content's own size comes back.
2237 match (w, h) {
2238 (Some(w), Some(h)) => inner.compute_filled(node, w, h),
2239 _ => inner.compute_scroll(
2240 node,
2241 offered.width,
2242 offered.height,
2243 w.is_none(),
2244 h.is_none(),
2245 ),
2246 }
2247 inner.size_of(node)
2248 });
2249 return (
2250 layout.measured_leaf(style, own_baseline, measure),
2251 Fills::own(widget, theme),
2252 );
2253 }
2254 // **A viewport is sized from its content on the axis it does not scroll.**
2255 //
2256 // A scrollable area declares a size on the axis it scrolls — that is what a viewport
2257 // is, a window shorter than what is behind it. On the *other* axis there is nothing to
2258 // choose: the content is as tall as it is, and the viewport is that tall. Until
2259 // milestone 485 a horizontal strip took the 200 px that belongs to a vertical one, so a
2260 // scrollable tab bar 48 px tall claimed 200 and pushed its panel a hundred and fifty
2261 // pixels into empty space (#65).
2262 //
2263 // It cannot be answered by the widget alone, and that is the whole reason this lives
2264 // here. A scroll host lays its content out **against** the viewport on the axis that
2265 // does not scroll — the content of a horizontal strip is given the viewport's height —
2266 // so a viewport that said `Auto` there would hand the content nothing and come back
2267 // nothing tall, the circle closing at zero. Breaking it takes a measurement, at the one
2268 // moment the runtime and the theme are both to hand.
2269 if let Some(content) = widget.scroll_content() {
2270 let style = effective_style(widget, id, runtime, theme);
2271 let axis = widget.scroll_axis();
2272 // Only an axis that **neither scrolls nor was given a size**. A caller's number is
2273 // a caller's number, and an axis that scrolls has already answered.
2274 let hug_x = !axis.free_x() && matches!(style.width, frus_layout::Dimension::Auto);
2275 let hug_y = !axis.free_y() && matches!(style.height, frus_layout::Dimension::Auto);
2276 // And an axis that **scrolls with no size given and no growing asked**: as big as
2277 // the content, up to the room on offer — the reference's viewport,
2278 // `constraints.constrain(child.size)` (milestone 590). It used to be 200 px.
2279 let free_to_measure =
2280 |d| matches!(d, frus_layout::Dimension::Auto) && style.flex_grow == 0.0;
2281 let clamp_x = axis.free_x() && free_to_measure(style.width);
2282 let clamp_y = axis.free_y() && free_to_measure(style.height);
2283 if hug_x || hug_y || clamp_x || clamp_y {
2284 let owned = owned_theme(theme);
2285 let cid = child_id(id, 0, content);
2286 let measure: frus_layout::MeasureFn<'a> = Box::new(move |w, h| {
2287 let mut inner: Layout<BaselineData> = Layout::new();
2288 let node = build_layout(content, cid, runtime, &owned, &mut inner);
2289 // The content is unconstrained on every axis that scrolls — that is what
2290 // scrolling means — and on the one being measured. What is left is an axis
2291 // with a real number on it, and the content is held to it.
2292 inner.compute_scroll(
2293 node,
2294 w.unwrap_or(0.0),
2295 h.unwrap_or(0.0),
2296 hug_x || axis.free_x() || w.is_none(),
2297 hug_y || axis.free_y() || h.is_none(),
2298 );
2299 let content = inner.size_of(node);
2300 let pad = widget.scroll_padding();
2301 // **Only the hugged axis is answered.** On the axis that scrolls, a
2302 // viewport is precisely *not* as big as its content — answering with the
2303 // content's size there would make a flexible viewport ask for the whole
2304 // length of what is behind it as its basis, and a column holding one would
2305 // overflow by however much there was to scroll. Nought is what a leaf
2306 // answered before this branch existed, and it is still the right answer.
2307 let whole_x = content.width + pad.left + pad.right;
2308 let whole_y = content.height + pad.top + pad.bottom;
2309 Size::new(
2310 if hug_x {
2311 whole_x
2312 } else if clamp_x {
2313 whole_x.min(w.unwrap_or(f32::INFINITY))
2314 } else {
2315 0.0
2316 },
2317 if hug_y {
2318 whole_y
2319 } else if clamp_y {
2320 whole_y.min(h.unwrap_or(f32::INFINITY))
2321 } else {
2322 0.0
2323 },
2324 )
2325 });
2326 return (
2327 layout.measured_leaf(style, own_baseline, measure),
2328 Fills::own(widget, theme),
2329 );
2330 }
2331 }
2332
2333 // **A stack that is as big as its largest unpinned layer** (`stack.dart:625`): each such
2334 // layer is laid out in a tree of its own under the stack's fit, and the stack is the
2335 // largest of them, held to the room it is offered. With none, or under `Expand`, it is
2336 // the room itself — which its fill request asks for.
2337 if widget.stack() && widget.stack_measured() {
2338 let style = effective_style(widget, id, runtime, theme);
2339 let owned = owned_theme(theme);
2340 let fit = widget.stack_fit();
2341 let layers = widget.children();
2342 let measure: frus_layout::MeasureFn<'a> = Box::new(move |w, h| {
2343 let mut size = Size::new(0.0, 0.0);
2344 // Under `Expand` the stack is the room; otherwise its largest unpinned layer.
2345 // With none, it is nothing here, and its fill request asks for the room.
2346 let sized_by_layers = fit != crate::StackFit::Expand;
2347 for (i, layer) in layers.iter().enumerate() {
2348 if layer.positioned().is_some() {
2349 continue;
2350 }
2351 let mut inner: Layout<BaselineData> = Layout::new();
2352 let node = build_layout(
2353 layer.as_ref(),
2354 child_id(id, i, layer.as_ref()),
2355 runtime,
2356 &owned,
2357 &mut inner,
2358 );
2359 // Forced or handed the room, a layer fills it; allowed it, it is asked —
2360 // and one that asks for the room takes it on its own, as a root.
2361 let fill = fit != crate::StackFit::Loose;
2362 let (fill_x, fill_y) = (fill, fill);
2363 inner.compute_axes(
2364 node,
2365 w.unwrap_or(0.0),
2366 h.unwrap_or(0.0),
2367 [w.is_none(), h.is_none()],
2368 [fill_x && w.is_some(), fill_y && h.is_some()],
2369 );
2370 let own = inner.size_of(node);
2371 size = Size::new(size.width.max(own.width), size.height.max(own.height));
2372 }
2373 // The room, on each axis that was offered one, when the layers do not decide.
2374 if !sized_by_layers {
2375 size = Size::new(w.unwrap_or(size.width), h.unwrap_or(size.height));
2376 }
2377 Size::new(
2378 frus_core::fits(size.width).min(w.unwrap_or(f32::INFINITY)),
2379 frus_core::fits(size.height).min(h.unwrap_or(f32::INFINITY)),
2380 )
2381 });
2382 return (
2383 layout.measured_leaf(style, own_baseline, measure),
2384 Fills::own(widget, theme),
2385 );
2386 }
2387
2388 // Scrollables, interactive viewports, fitters (`FittedBox`), navigators, virtualised
2389 // lists and stacks: their content is laid out separately (independent layers / screens /
2390 // items, or a child laid out at its natural size).
2391 if widget.scroll_content().is_some()
2392 || widget.interactive().is_some()
2393 || widget.fitted().is_some()
2394 || widget.navigator().is_some()
2395 || widget.virtual_list(Size::ZERO).is_some()
2396 || widget.page_view().is_some()
2397 || widget.stack()
2398 || widget.custom_layout().is_some()
2399 {
2400 // Nothing bubbles out of these: what is inside is laid out somewhere else, to
2401 // constraints of its own, and cannot have an opinion about this box.
2402 return (
2403 layout.leaf(effective_style(widget, id, runtime, theme), own_baseline),
2404 Fills::own(widget, theme),
2405 );
2406 }
2407 // A portal only lays out its anchor (child 0); the overlay is deferred.
2408 if widget.overlay().is_some() {
2409 let anchor_w = widget.children()[0].as_ref();
2410 let (anchor, fills) = build_layout_scoped(
2411 anchor_w,
2412 child_id(id, 0, anchor_w),
2413 runtime,
2414 theme,
2415 layout,
2416 baselines,
2417 );
2418 // **The anchor takes the room the portal is given**, across the axis it fills. Laid
2419 // in a row, an anchor stretched to the portal's height but kept its own width, so a
2420 // menu row with a submenu open, which is a portal, shrank to its label while every
2421 // other row was as wide as the menu, and its chevron was drawn off the menu's start
2422 // edge (milestone 607). A column stretches it across instead; an anchor that fills
2423 // only the height keeps the row.
2424 let mut style = effective_style(widget, id, runtime, theme);
2425 style.flex_direction = if fills.vertical && !fills.horizontal {
2426 frus_layout::FlexDirection::Row
2427 } else {
2428 frus_layout::FlexDirection::Column
2429 };
2430 return (layout.container(style, &[anchor]), fills);
2431 }
2432 let children = widget.children();
2433 if children.is_empty() {
2434 // A leaf measured under constraints (a paragraph that wraps…): taffy calls the
2435 // closure during the computation.
2436 if let Some(measure) = widget.measure(theme) {
2437 return (
2438 layout.measured_leaf(
2439 effective_style(widget, id, runtime, theme),
2440 own_baseline,
2441 measure,
2442 ),
2443 Fills::own(widget, theme),
2444 );
2445 }
2446 (
2447 layout.leaf(effective_style(widget, id, runtime, theme), own_baseline),
2448 Fills::own(widget, theme),
2449 )
2450 } else {
2451 let style = effective_style(widget, id, runtime, theme);
2452 let built: Vec<(NodeId, Fills)> = children
2453 .iter()
2454 .enumerate()
2455 .map(|(i, child)| {
2456 build_layout_scoped(
2457 child.as_ref(),
2458 child_id(id, i, child.as_ref()),
2459 runtime,
2460 theme,
2461 layout,
2462 baselines,
2463 )
2464 })
2465 .collect();
2466 let child_ids: Vec<NodeId> = built.iter().map(|(node, _)| *node).collect();
2467 // `MainAxisSize::Max`: a run that fills the room its parent leaves it. Only the
2468 // parent knows what that means — grow along an axis it shares, stretch across
2469 // one it does not — which is why the child asks rather than saying.
2470 //
2471 // The request is the child's **and its subtree's**: a column whose row fills the
2472 // width is itself as wide as the room it was given.
2473 let alone = children.len() == 1;
2474 for (node, fills) in &built {
2475 for horizontal in [true, false] {
2476 if !fills.wants(horizontal) {
2477 continue;
2478 }
2479 let parallel = horizontal == style.flex_direction.is_horizontal();
2480 // Along an axis the parent runs too, the reference leaves the main axis
2481 // **unbounded** and `Max` quietly degrades to `Min`: there is no maximum
2482 // to take. The exception is a parent with a single child — a padding, an
2483 // alignment, a decorated box — which passes its own constraints straight
2484 // down, and there the run does fill.
2485 if parallel && !alone {
2486 continue;
2487 }
2488 // A size that was only a default gives way to the room (milestone 590).
2489 if fills.soft(horizontal) {
2490 layout.clear_size(*node, horizontal);
2491 }
2492 layout.fill_parent(*node, horizontal, parallel);
2493 }
2494 }
2495 // A **lone** child gives way; several do not.
2496 //
2497 // The reference hands an inflexible child of a row or a column an unbounded main
2498 // axis: it is never squeezed, and a line that does not fit overflows and says so.
2499 // That is the default here now, because a framework that quietly crushes a button
2500 // instead of reporting a layout that does not fit is one whose bugs are invisible
2501 // — milestone 333 spent three milestones on exactly that crushed button.
2502 //
2503 // But a box with one child is not dividing a line up: it is handing its own
2504 // constraints down, and the reference bounds a lone child by them. The same
2505 // exception the fill request and the floor below both make, for the same reason.
2506 if alone {
2507 for node in &child_ids {
2508 layout.allow_shrink(*node);
2509 }
2510 }
2511 // A grid's tiles are all the same shape. The ratio is the *container's*, since a
2512 // tile cannot know how wide its column came out, and the reference says the same:
2513 // a grid's delegate hands every child a tight box derived from the track, square
2514 // unless the application asked for another ratio.
2515 if let Some(ratio) = widget.tile_shape() {
2516 for node in &child_ids {
2517 layout.set_tile_shape(*node, ratio);
2518 }
2519 }
2520 // A child that refuses to be squeezed along the row. Only a row of **several**
2521 // children may say so. Across a column the same floor would refuse a width the
2522 // column was handing it, which is how a paragraph is told how wide to be; and a
2523 // box with a single child — a padding, an alignment, a decorated box — is handing
2524 // one down rather than dividing a line up, whichever way it nominally runs.
2525 if style.flex_direction.is_horizontal() && !alone {
2526 for (child, node) in children.iter().zip(&child_ids) {
2527 if let Some(floor) = child.main_axis_floor(theme) {
2528 layout.set_min_width(*node, floor);
2529 }
2530 }
2531 }
2532 // **Baseline** cross-alignment: the children are pushed down until their
2533 // baselines meet, which is the only alignment that makes two runs of different
2534 // sizes read as one line rather than as one row.
2535 //
2536 // It is resolved here rather than by taffy, which cannot: taffy asks a leaf for
2537 // a size and a leaf can only answer with one. The measurement a baseline needs
2538 // is the font's, so the answer has to come from up here, where the widgets are.
2539 //
2540 // The **natural** baseline is the right one to measure even though the children
2541 // will be laid out at some other width: the first line of a piece of text sits
2542 // in the same place however narrow the box gets, since narrowing it adds lines
2543 // below rather than moving the first one.
2544 if style.align == frus_layout::Align::Baseline && style.flex_direction.is_horizontal() {
2545 let own: Vec<Option<f32>> = children
2546 .iter()
2547 .enumerate()
2548 .map(|(i, child)| {
2549 natural_baseline(
2550 child.as_ref(),
2551 child_id(id, i, child.as_ref()),
2552 runtime,
2553 theme,
2554 )
2555 })
2556 .collect();
2557 if let Some(deepest) = own.iter().flatten().copied().reduce(f32::max) {
2558 for (node, b) in child_ids.iter().zip(&own) {
2559 // A child with no baseline keeps its place: it is a box, and a box
2560 // has nothing to line up.
2561 if let Some(b) = b {
2562 layout.add_margin_top(*node, deepest - b);
2563 }
2564 }
2565 }
2566 }
2567 // What this container passes on to **its** parent. Across its own axis the
2568 // container's size is its child's, so the request keeps going; along it the
2569 // container divides the room up and the request stops. A container with a single
2570 // child divides nothing, and passes the whole request on.
2571 let mut fills = Fills::own(widget, theme);
2572 // A grid divides its room on both axes and sizes its cells itself — the
2573 // reference's grid hands its tiles tight constraints — so a cell's request stops at
2574 // it (milestone 633).
2575 let divides_both = style.grid_columns.is_some();
2576 for (_, child) in &built {
2577 if divides_both {
2578 continue;
2579 }
2580 fills = fills.merge(if alone {
2581 *child
2582 } else {
2583 child.across(style.flex_direction)
2584 });
2585 }
2586 (
2587 layout.container(style, &child_ids),
2588 fills.bounded_by(&style),
2589 )
2590 }
2591}
2592
2593/// The distance from the top of `widget`'s **natural** box to the first baseline inside
2594/// it, or `None` when there is no text in there to have one.
2595///
2596/// It lays the subtree out on its own, exactly as [`natural_size`] does, and takes the
2597/// first baseline the layout collected. First in *layout* order, which is the order a
2598/// reader would find it in — and it is the leaves that carry them, so an intervening
2599/// padding or alignment is already counted in the rectangle it comes with.
2600pub(crate) fn natural_baseline<Msg>(
2601 widget: &dyn Widget<Msg>,
2602 id: WidgetId,
2603 runtime: &Runtime,
2604 theme: &Theme,
2605) -> Option<f32> {
2606 let mut layout = Layout::new();
2607 let node = build_layout(widget, id, runtime, theme, &mut layout);
2608 layout.compute_scroll(node, 0.0, 0.0, true, true);
2609 let rects = layout.absolute_rects(node);
2610 let top = rects.first()?.0.y;
2611 rects
2612 .iter()
2613 .find_map(|(rect, data)| data.copied().flatten().map(|b| rect.y + b - top))
2614}
2615
2616/// **Natural** (intrinsic) size of a subtree: laid out under free axes (`MaxContent`), with
2617/// no imposed constraint. Used by `RotatedBox` (the dimensions to swap) and — at render time
2618/// — by `FittedBox` (the fit factor).
2619pub(crate) fn natural_size<Msg>(
2620 widget: &dyn Widget<Msg>,
2621 id: WidgetId,
2622 runtime: &Runtime,
2623 theme: &Theme,
2624) -> Size {
2625 let mut layout = Layout::new();
2626 let node = build_layout(widget, id, runtime, theme, &mut layout);
2627 layout.compute_scroll(node, 0.0, 0.0, true, true);
2628 layout
2629 .absolute_rects(node)
2630 .first()
2631 .map(|(r, _)| Size::new(r.width, r.height))
2632 .unwrap_or(Size::new(0.0, 0.0))
2633}
2634
2635/// A deferred overlay: `(content, id, the anchor's bounds, placement, dismissal,
2636/// progress 0..=1, whether it takes the pointer, the scrim's colour, the theme it was
2637/// declared under)`. The progress animates the appearance — a drawer sliding in, a
2638/// scrim fading — and is `1.0` for overlays that are not animated.
2639///
2640/// The **theme travels with it** because an overlay is painted long after the walk has
2641/// left the node that declared it: a dialog opened from inside a [`crate::Themed`]
2642/// subtree would otherwise come out in the root's theme, which is the surprise the
2643/// reference had to grow a whole mechanism to avoid. The scrim's colour travels for the
2644/// same reason — by the time it is painted, the widget that asked for it is long
2645/// behind.
2646type Overlay<'a, Msg> = (
2647 &'a dyn Widget<Msg>,
2648 WidgetId,
2649 Rect,
2650 Placement,
2651 Option<Msg>,
2652 f32,
2653 bool,
2654 Option<frus_core::Color>,
2655 std::rc::Rc<Theme>,
2656);
2657
2658struct Builder<'a, Msg> {
2659 scene: Scene,
2660 hits: Vec<Hit<Msg>>,
2661 long_presses: Vec<Hit<Msg>>,
2662 dismisses: Vec<Msg>,
2663 edit_actions: Vec<(WidgetId, crate::EditAction)>,
2664 toolbars: Vec<Rect>,
2665 overlay_cover: Vec<Rect>,
2666 focusables: Vec<Focusable>,
2667 /// Start of the topmost modal overlay's focus scope.
2668 focus_scope_start: Option<usize>,
2669 /// Set while inside an `ExcludeFocus`: nothing in here registers a focus stop.
2670 focus_excluded: bool,
2671 /// Where a press or a drag can land, when that is less than what is drawn: inside a
2672 /// stack that lets its layers hang over its edges, its own box (milestone 639).
2673 touch_clip: Option<Rect>,
2674 /// The identity of the nearest enclosing backdrop group — the key a backdrop
2675 /// asking to be shared takes. Pushed and popped by the walk, like the focus flags.
2676 backdrop_group: Option<u64>,
2677 /// Set while inside an `ExcludeFocusTraversal`: stops register, Tab passes them by.
2678 focus_skipped: bool,
2679 /// The traversal order in force, from the nearest enclosing `FocusTraversalOrder`.
2680 focus_order: Option<f32>,
2681 /// The nearest enclosing `FocusTraversalGroup`, within which an order is resolved.
2682 focus_group: Option<WidgetId>,
2683 /// The nearest enclosing [`crate::AutofillGroup`]: the form a field is part of.
2684 autofill_group: Option<WidgetId>,
2685 /// Shortcut and action scopes closed so far this frame.
2686 scopes: Vec<Scope<Msg>>,
2687 /// Keystroke listeners, with the focus stops they cover.
2688 #[allow(clippy::type_complexity)]
2689 listeners: Vec<(
2690 std::ops::Range<usize>,
2691 std::rc::Rc<dyn Fn(KeyStroke) -> Option<Msg>>,
2692 )>,
2693 scrollables: Vec<Scrollable>,
2694 scrollbars: Vec<Scrollbar>,
2695 draggables: Vec<(WidgetId, Rect)>,
2696 drag_sources: Vec<DragSource>,
2697 drop_zones: Vec<DropZone>,
2698 inks: Vec<(WidgetId, Rect)>,
2699 /// The detectors that take a drag, in painted order, with the box a press can land in
2700 /// (clipped) and the whole box (milestone 582).
2701 /// The row that wants the title bar's line, where it was laid out, and what the system
2702 /// acts on there (milestones 640, 642).
2703 title_bar_row: Option<Rect>,
2704 title_bar_regions: Vec<(Rect, crate::TitleBarRole)>,
2705 pans: Vec<(WidgetId, Rect, Rect)>,
2706 /// The widgets that hear the pointer's raw events, likewise (milestone 586).
2707 pointer_listeners: Vec<(WidgetId, Rect, Rect)>,
2708 /// The regions the mouse enters and leaves, in painted order (milestone 583).
2709 hover_regions: Vec<HoverEntry>,
2710 text_stops: Vec<crate::TextStop>,
2711 /// The region the mouse enters and leaves that the walk is inside, if any: the parent of
2712 /// the next one registered (milestone 583).
2713 hover_parent: Option<WidgetId>,
2714 /// The [`SelectionArea`](crate::SelectionArea) the walk is inside, if it is inside one, and
2715 /// its widget — which may have a say over the bar.
2716 area: Option<WidgetId>,
2717 area_widget: Option<&'a dyn Widget<Msg>>,
2718 /// Whether the bar over a selection area's selection has been placed this frame: it goes
2719 /// against the first text the selection covers, and only that one.
2720 region_bar_placed: bool,
2721 reorderables: Vec<(WidgetId, Rect)>,
2722 interactives: Vec<(WidgetId, Rect)>,
2723 /// Deferred overlays: (content, id, the anchor's bounds, placement, dismissal, progress
2724 /// `0..=1`). The progress animates the appearance (a drawer sliding in, a scrim fading);
2725 /// it is `1.0` for overlays that are not animated.
2726 overlays: Vec<Overlay<'a, Msg>>,
2727 /// A widget is asking for a continuous, time-driven animation.
2728 wants_animation: bool,
2729 available: Size,
2730 runtime: &'a Runtime,
2731 /// The theme **in force at this point of the walk** — the root's, unless a
2732 /// [`crate::Themed`] ancestor replaced it. Owned rather than borrowed because a
2733 /// subtree's theme is derived from the one above it and outlives nothing.
2734 ///
2735 /// Owned **behind an `Rc`**: a `Theme` is eleven kilobytes, and this field is swapped
2736 /// on the way into a themed subtree and swapped back on the way out. By value that is
2737 /// two copies of eleven kilobytes standing in the walk's frame — one being moved in,
2738 /// one held across the recursion waiting to be put back — on every level of the tree,
2739 /// taken or not. Behind a pointer the swap is a pointer's width, and the walk's frame
2740 /// went from 28 144 bytes a level to 5 264.
2741 theme: std::rc::Rc<Theme>,
2742 /// The inspector's collection (`Some` only while it is on): one node per painted widget,
2743 /// in paint order.
2744 inspector: Option<Vec<crate::inspector::InspectorNode>>,
2745 /// **The widgets this frame builds as it goes** — a list's rows, a paged view's pages,
2746 /// what a builder makes from its box — kept for the rest of the walk, so that they go
2747 /// through the same walk as the tree they sit in (milestone 592). They used to go through
2748 /// a reduced copy of it that knew no overlay, no transform and no nested scroll, and an
2749 /// open menu in a list's row crashed the frame.
2750 built: &'a Built<Msg>,
2751 /// Current depth of the walk (for the dump's indentation and the palette of the
2752 /// inspector's outlines).
2753 depth: usize,
2754 /// The [`crate::RefreshIndicator`] area currently being walked, if any: every scrollable
2755 /// registered under it records it, so the shell knows where to send the movement
2756 /// its physics refuses. Saved and restored around the subtree, so sibling areas do
2757 /// not inherit one another's.
2758 refresh_host: Option<WidgetId>,
2759 /// The scroll region currently being walked, if any: the nearest one enclosing
2760 /// whatever the walk is looking at. Focus stops record it so the shell can reveal
2761 /// them, and nested regions record one another. Saved and restored around the
2762 /// subtree, like [`Builder::refresh_host`].
2763 scroll_host: Option<WidgetId>,
2764 /// Which screen of a route transition the walk is inside (`0` = leaving, `1` =
2765 /// entering); `None` outside one. Recorded on each hero so the two sides of a
2766 /// flight are told apart rather than guessed from paint order.
2767 hero_screen: Option<u8>,
2768 /// The shared elements seen so far, each with the widget that declared it (needed
2769 /// to lift its subtree's painting) and the transition screen it belongs to.
2770 heroes: Vec<(HeroSpot, &'a dyn Widget<Msg>)>,
2771 /// The frame's refresh areas, in paint order.
2772 refreshes: Vec<Refreshable>,
2773 /// The frame's dismissible items, in paint order.
2774 dismissables: Vec<Dismissable>,
2775 /// The frame's sheets, in the order their subtrees finished walking.
2776 sheets: Vec<crate::sheet::SheetArea>,
2777 /// Accessibility nodes collected during the walk (paint order).
2778 semantics: Vec<(WidgetId, Rect, frus_core::SemanticsProperties)>,
2779 /// The parts of the screen saying what the system bars over them should look like,
2780 /// with their boxes, in paint order.
2781 system_ui: Vec<(Rect, crate::SystemUiOverlayStyle)>,
2782 /// Boxes whose children did not fit, screen-positioned, from every sub-root walked
2783 /// this frame.
2784 overflows: std::cell::RefCell<Vec<Overflowing>>,
2785 /// The same, still in their sub-root's own coordinates, waiting for the walk to reach
2786 /// that sub-root and say where on screen it ended up.
2787 pending_overflows: std::cell::RefCell<std::collections::HashMap<WidgetId, Vec<Overflowing>>>,
2788}
2789
2790impl<'a, Msg: Clone + 'static> Builder<'a, Msg> {
2791 /// A layout root's rects, through the relayout cache retained in the runtime (it only
2792 /// recomputes through taffy when the style/structure/constraints have changed). A brief
2793 /// mutable borrow: the `Vec` returned is owned.
2794 ///
2795 /// In **RTL**, taffy computes in LTR (canonical, and cached), then each rect is
2796 /// **mirrored** about the root's width (the 1st rect): the rows reverse, the alignment
2797 /// and the margins flip — without touching the widgets. The text itself is drawn
2798 /// normally inside its moved box (the *internal* bidi is handled by cosmic-text).
2799 fn cached_rects(&self, key: WidgetId, root: &dyn Widget<Msg>, c: Constraints) -> Vec<Rect> {
2800 let (mut rects, overflows) =
2801 self.runtime
2802 .layout_cache
2803 .borrow_mut()
2804 .rects(key, root, self.runtime, &self.theme, c);
2805 self.mirror(&mut rects);
2806 self.record_overflows(key, &rects, overflows);
2807 rects
2808 }
2809
2810 /// Files this sub-root's overflowing boxes under its identity, mirrored with
2811 /// everything else in RTL — where an edge changes name as well as position, since the
2812 /// layout is the mirror image and "ran past the right" becomes "ran past the left".
2813 ///
2814 /// They wait here rather than going straight out because a sub-root's rectangles are
2815 /// in its **own** coordinates: a scrollable's content, a page, a list item and a
2816 /// stack's layer each get their own taffy pass, and where that pass lands on screen is
2817 /// only known when the walk reaches it. [`Self::claim_overflows`] is the other half.
2818 /// Records a child that came out **bigger than the box holding it**, one entry per
2819 /// edge it ran past — the same yellow and black band a row too full of children gets,
2820 /// from a box that laid its child out itself and so was never measured against it.
2821 ///
2822 /// The rectangle is already on the screen, this being the walk rather than a sub-root's
2823 /// own pass, so it goes straight out rather than through [`Self::record_overflows`].
2824 fn report_spill(&self, own: Rect, child: Rect) {
2825 // Per edge, from where the child actually landed: a centred child that is too wide
2826 // runs past **both** sides, and a band on one of them would be a half-truth.
2827 let over = [
2828 (Side::Left, own.x - child.x),
2829 (Side::Top, own.y - child.y),
2830 (Side::Right, (child.x + child.width) - (own.x + own.width)),
2831 (
2832 Side::Bottom,
2833 (child.y + child.height) - (own.y + own.height),
2834 ),
2835 ];
2836 let spills: Vec<Overflowing> = over
2837 .into_iter()
2838 .filter(|(_, amount)| *amount > 0.5)
2839 .map(|(side, amount)| Overflowing {
2840 rect: own,
2841 side,
2842 amount,
2843 })
2844 .collect();
2845 self.overflows.borrow_mut().extend(spills);
2846 }
2847
2848 fn record_overflows(&self, key: WidgetId, mirrored: &[Rect], overflows: Vec<Overflowing>) {
2849 if overflows.is_empty() {
2850 return;
2851 }
2852 let rtl = self.rtl();
2853 let root = mirrored.first().copied();
2854 let list: Vec<Overflowing> = overflows
2855 .into_iter()
2856 .map(|mut o| {
2857 if let (true, Some(root)) = (rtl, root) {
2858 o.rect.x = root.x + (root.width - (o.rect.x - root.x) - o.rect.width);
2859 o.side = match o.side {
2860 Side::Left => Side::Right,
2861 Side::Right => Side::Left,
2862 other => other,
2863 };
2864 }
2865 o
2866 })
2867 .collect();
2868 self.pending_overflows.borrow_mut().insert(key, list);
2869 }
2870
2871 /// The walk has reached sub-root `id` and knows where it sits: its overflowing boxes
2872 /// become screen rectangles.
2873 fn claim_overflows(&self, id: WidgetId, translation: (f32, f32)) {
2874 let taken = self.pending_overflows.borrow_mut().remove(&id);
2875 if let Some(list) = taken {
2876 self.overflows
2877 .borrow_mut()
2878 .extend(list.into_iter().map(|o| Overflowing {
2879 rect: o.rect.translate(translation.0, translation.1),
2880 ..o
2881 }));
2882 }
2883 }
2884
2885 /// The layout direction **in force here** — read from the ambient theme rather than
2886 /// from a field set once at the root, so a [`crate::Themed`] subtree carries its own.
2887 ///
2888 /// What that reaches is everything decided during the walk: which edge a drawer
2889 /// slides from, which way an anchored overlay opens, the sign of a rotation, the
2890 /// mirroring of any **layout root** inside the subtree (a scrollable, an overlay).
2891 /// What it does not reach is ordinary flow inside the subtree: the frame's rects are
2892 /// computed once at the root and mirrored there as a whole, so a direction set part
2893 /// way down does not reverse the rows around it. Setting the direction on the theme
2894 /// handed to `build_ui` is still the way to flip an application.
2895 fn rtl(&self) -> bool {
2896 self.theme.direction.is_rtl()
2897 }
2898
2899 /// Mirrors a root's rects horizontally (RTL). The first rect is the root itself: its
2900 /// width is the axis of symmetry.
2901 fn mirror(&self, rects: &mut [Rect]) {
2902 if !self.rtl() {
2903 return;
2904 }
2905 let Some(root) = rects.first().copied() else {
2906 return;
2907 };
2908 // The axis: the rects are relative to the root (origin at root.x).
2909 for r in rects.iter_mut() {
2910 r.x = root.x + (root.width - (r.x - root.x) - r.width);
2911 }
2912 }
2913
2914 /// 64-bit fingerprint of everything painting a boundary subtree reads **without**
2915 /// rebuilding the `view`: each descendant's `Status` (in walk order) and the subtree's
2916 /// absolute rects. An unchanged fingerprint + generation ⇒ a bit-for-bit identical paint.
2917 /// The time is excluded (a cacheable boundary holds no `continuous` widget).
2918 fn boundary_fingerprint(
2919 &self,
2920 widget: &dyn Widget<Msg>,
2921 id: WidgetId,
2922 translation: (f32, f32),
2923 sub: &[Rect],
2924 ) -> u64 {
2925 let mut h = std::collections::hash_map::DefaultHasher::new();
2926 self.rtl().hash(&mut h);
2927 translation.0.to_bits().hash(&mut h);
2928 translation.1.to_bits().hash(&mut h);
2929 for r in sub {
2930 r.x.to_bits().hash(&mut h);
2931 r.y.to_bits().hash(&mut h);
2932 r.width.to_bits().hash(&mut h);
2933 r.height.to_bits().hash(&mut h);
2934 }
2935 self.hash_statuses(widget, id, &mut h);
2936 h.finish()
2937 }
2938
2939 /// Adds `widget`'s `Status` to `h`, then its children's, recursively — following the
2940 /// walk's identity scheme (`child_id`) **exactly**, so it lines up with the order in which
2941 /// `walk_node` paints them.
2942 fn hash_statuses<H: Hasher>(&self, widget: &dyn Widget<Msg>, id: WidgetId, h: &mut H) {
2943 hash_status(&self.full_status(widget, id), h);
2944 // Live ink is part of what the boundary paints, and it moves every frame while a
2945 // splash is alive. Without it here the cached primitives would be replayed and
2946 // the ripple would stand still — and once the ink dries the hash goes back to
2947 // what it was, so the boundary starts hitting again.
2948 if let Some(ripples) = self.runtime.ink.get(&id) {
2949 ripples.hash_state(h);
2950 }
2951 for (i, child) in widget.children().iter().enumerate() {
2952 self.hash_statuses(child.as_ref(), child_id(id, i, child.as_ref()), h);
2953 }
2954 }
2955
2956 /// Current lengths of the builder's collections: the lower bound of the slices to capture
2957 /// for a boundary (see [`capture_since`](Self::capture_since)).
2958 fn snapshot(&self) -> Snapshot {
2959 Snapshot {
2960 scene: self.scene.primitives().len(),
2961 hits: self.hits.len(),
2962 long_presses: self.long_presses.len(),
2963 dismisses: self.dismisses.len(),
2964 focusables: self.focusables.len(),
2965 scrollables: self.scrollables.len(),
2966 draggables: self.draggables.len(),
2967 drag_sources: self.drag_sources.len(),
2968 drop_zones: self.drop_zones.len(),
2969 inks: self.inks.len(),
2970 pans: self.pans.len(),
2971 pointer_listeners: self.pointer_listeners.len(),
2972 hover_regions: self.hover_regions.len(),
2973 text_stops: self.text_stops.len(),
2974 semantics: self.semantics.len(),
2975 system_ui: self.system_ui.len(),
2976 overlays: self.overlays.len(),
2977 focus_scope_start: self.focus_scope_start,
2978 }
2979 }
2980
2981 /// Captures the output produced since `snap` (the collections' *tail slices*) into a
2982 /// [`BoundaryData`]. Returns `None` — hence **not cacheable** — when the subtree pushed an
2983 /// overlay or touched the modal focus scope (global state that cannot be captured here).
2984 fn capture_since(&self, snap: &Snapshot) -> Option<BoundaryData<Msg>> {
2985 if self.overlays.len() != snap.overlays || self.focus_scope_start != snap.focus_scope_start
2986 {
2987 return None;
2988 }
2989 Some(BoundaryData {
2990 prims: self.scene.primitives()[snap.scene..].to_vec(),
2991 hits: self.hits[snap.hits..].to_vec(),
2992 long_presses: self.long_presses[snap.long_presses..].to_vec(),
2993 dismisses: self.dismisses[snap.dismisses..].to_vec(),
2994 focusables: self.focusables[snap.focusables..].to_vec(),
2995 scrollables: self.scrollables[snap.scrollables..].to_vec(),
2996 draggables: self.draggables[snap.draggables..].to_vec(),
2997 drag_sources: self.drag_sources[snap.drag_sources..].to_vec(),
2998 drop_zones: self.drop_zones[snap.drop_zones..].to_vec(),
2999 inks: self.inks[snap.inks..].to_vec(),
3000 pans: self.pans[snap.pans..].to_vec(),
3001 pointer_listeners: self.pointer_listeners[snap.pointer_listeners..].to_vec(),
3002 hover_regions: self.hover_regions[snap.hover_regions..].to_vec(),
3003 text_stops: self.text_stops[snap.text_stops..].to_vec(),
3004 semantics: self.semantics[snap.semantics..].to_vec(),
3005 system_ui: self.system_ui[snap.system_ui..].to_vec(),
3006 })
3007 }
3008
3009 /// Replays a boundary from the cache: primitives already formed (clip/owner baked in) and
3010 /// interaction maps, appended as is.
3011 fn splice_boundary(&mut self, data: BoundaryData<Msg>) {
3012 for p in data.prims {
3013 self.scene.push_primitive(p);
3014 }
3015 self.hits.extend(data.hits);
3016 self.long_presses.extend(data.long_presses);
3017 self.dismisses.extend(data.dismisses);
3018 self.focusables.extend(data.focusables);
3019 self.scrollables.extend(data.scrollables);
3020 self.draggables.extend(data.draggables);
3021 self.drag_sources.extend(data.drag_sources);
3022 self.drop_zones.extend(data.drop_zones);
3023 self.inks.extend(data.inks);
3024 self.pans.extend(data.pans);
3025 self.pointer_listeners.extend(data.pointer_listeners);
3026 self.hover_regions.extend(data.hover_regions);
3027 self.text_stops.extend(data.text_stops);
3028 self.semantics.extend(data.semantics);
3029 self.system_ui.extend(data.system_ui);
3030 }
3031
3032 /// Lengths of every registry a [`ModalBarrier`] can withhold from, taken before its subtree
3033 /// is walked.
3034 fn barrier_base(&self) -> BarrierBase {
3035 BarrierBase {
3036 scene: self.scene.primitives().len(),
3037 hits: self.hits.len(),
3038 long_presses: self.long_presses.len(),
3039 focusables: self.focusables.len(),
3040 scrollables: self.scrollables.len(),
3041 scrollbars: self.scrollbars.len(),
3042 draggables: self.draggables.len(),
3043 drag_sources: self.drag_sources.len(),
3044 drop_zones: self.drop_zones.len(),
3045 inks: self.inks.len(),
3046 pans: self.pans.len(),
3047 pointer_listeners: self.pointer_listeners.len(),
3048 hover_regions: self.hover_regions.len(),
3049 text_stops: self.text_stops.len(),
3050 reorderables: self.reorderables.len(),
3051 interactives: self.interactives.len(),
3052 semantics: self.semantics.len(),
3053 }
3054 }
3055
3056 /// Drops what the subtree added since `base`, according to `barrier`, and — for an
3057 /// absorbing barrier — puts a message-less hit target in its place so that input stops
3058 /// at the barrier instead of reaching whatever is painted behind it.
3059 /// Resolves the **shared elements** of a route transition: every tag that appears
3060 /// on both screens flies from where it was to where it is going.
3061 ///
3062 /// Called once, after both screens have been drawn, because that is the first
3063 /// moment both boxes are known. `hero_base` and `scene_base` mark where those two
3064 /// screens started.
3065 ///
3066 /// What flies is the **destination**'s own painting, mapped onto the box it is
3067 /// travelling through. Both originals are taken out of the frame: a thing that is
3068 /// flying is not also sitting at either end, and leaving them in is the difference
3069 /// between a shared element and three copies of one.
3070 fn fly_heroes(&mut self, hero_base: usize, scene_base: usize, progress: f32) {
3071 let spots: Vec<(HeroSpot, &'a dyn Widget<Msg>)> = self.heroes.split_off(hero_base);
3072 if spots.len() < 2 {
3073 return;
3074 }
3075 // The pairs: one tag, one hero on each side. A tag on one side only has nothing
3076 // to fly to, and a tag used more than once per side is ambiguous — both are
3077 // left alone rather than guessed at.
3078 let mut flights: Vec<(Rect, Rect, &'a dyn Widget<Msg>, WidgetId, WidgetId)> = Vec::new();
3079 for (from, _) in spots.iter().filter(|(s, _)| s.screen == 0) {
3080 let mut matching = spots
3081 .iter()
3082 .filter(|(s, _)| s.screen == 1 && s.tag == from.tag);
3083 let Some((to, widget)) = matching.next() else {
3084 continue;
3085 };
3086 if matching.next().is_some() {
3087 continue;
3088 }
3089 flights.push((from.rect, to.rect, *widget, from.id, to.id));
3090 }
3091 if flights.is_empty() {
3092 return;
3093 }
3094
3095 // Everything the two screens painted, so the originals can be taken out and the
3096 // travelling copies laid on top.
3097 let painted = self.scene.split_off(scene_base);
3098 let mut hidden: std::collections::HashSet<u64> = std::collections::HashSet::new();
3099 for (_, _, widget, from_id, to_id) in &flights {
3100 for id in subtree_ids(*widget, *to_id) {
3101 hidden.insert(id.as_u64());
3102 }
3103 // The source's subtree is the *other* screen's widget, whose identity is
3104 // rooted at `from_id`; the same relative shape, so the ids follow.
3105 for id in subtree_ids(*widget, *from_id) {
3106 hidden.insert(id.as_u64());
3107 }
3108 }
3109 // The destinations' own painting, wherever it was drawn: a page in a transition may
3110 // be inside a layer that zooms or fades it (milestone 620), and a hero in flight is
3111 // above both pages, untouched by either — as the reference's flies in the overlay.
3112 let destinations: std::collections::HashSet<u64> = flights
3113 .iter()
3114 .flat_map(|(_, _, widget, _, to_id)| subtree_ids(*widget, *to_id))
3115 .map(|id| id.as_u64())
3116 .collect();
3117 let mut taken = Vec::new();
3118 for primitive in take_owned(painted, &hidden, &destinations, &mut taken) {
3119 self.scene.push_primitive(primitive);
3120 }
3121 let painted = taken;
3122
3123 self.scene.set_clip(Rect::UNBOUNDED);
3124 for (from, to, _, _, to_id) in &flights {
3125 let travelling = lerp_rect(*from, *to, progress);
3126 if to.width <= 0.0 || to.height <= 0.0 {
3127 continue;
3128 }
3129 let (sx, sy) = (travelling.width / to.width, travelling.height / to.height);
3130 let pivot = Point::new(to.x, to.y);
3131 let owners: std::collections::HashSet<u64> = subtree_ids(
3132 flights
3133 .iter()
3134 .find(|(_, _, _, _, id)| id == to_id)
3135 .map(|(_, _, w, _, _)| *w)
3136 .expect("the flight just matched"),
3137 *to_id,
3138 )
3139 .iter()
3140 .map(|id| id.as_u64())
3141 .collect();
3142 for primitive in painted.iter().filter(|p| owners.contains(&p.owner())) {
3143 let flown = primitive
3144 .scaled_about_xy(pivot, sx, sy)
3145 .translated(travelling.x - to.x, travelling.y - to.y)
3146 .with_clip(Rect::UNBOUNDED);
3147 self.scene.push_primitive(flown);
3148 }
3149 }
3150 }
3151
3152 /// Reconciles what a [`crate::Semantics`] wrapper's subtree announced with what the
3153 /// wrapper says about it.
3154 ///
3155 /// The wrapper's own answers win, and the subtree's show through wherever it said
3156 /// nothing — a container that knows a child is a *heading* rarely knows what the words
3157 /// are, and dropping them would replace a spoken title with silence.
3158 ///
3159 /// The merged node goes in **where the subtree's first one was**, not at the end. The
3160 /// accessibility tree is flat and its order is reading order, so a wrapper appended
3161 /// after its own contents would be read after them.
3162 fn apply_description(
3163 &mut self,
3164 described: crate::semantics::Description,
3165 base: usize,
3166 id: WidgetId,
3167 own: Rect,
3168 ) {
3169 let mut props = described.props;
3170 // Merging swallows every child's own entry, so **something** has to answer for
3171 // this node when it is activated — the wrapper itself never does (see
3172 // `Semantics::on_click`'s own reasoning: an annotation that swallowed a click
3173 // would put a hit target over the widget it describes). Found testing #18 in a
3174 // real browser and real screen reader: a `Checkbox::new(..).on_toggle(..)`
3175 // merged with its row's caption read correctly and did **nothing** on
3176 // activation, on every platform, because the merged entry carried the row's own
3177 // id, which nothing routes a click through. When exactly one child in the
3178 // swallowed subtree was clickable, its id is who a click or a keyboard
3179 // activation has to reach, so the merged entry keys on that id instead — the
3180 // wrapper's id is kept only when there is no such child, or more than one and
3181 // "the one that gets clicked" has no single answer.
3182 let mut operable = None;
3183 if described.merging {
3184 let mut clickable_count = 0;
3185 for (child_id, _, child) in self.semantics.drain(base..).collect::<Vec<_>>() {
3186 if child.clickable {
3187 clickable_count += 1;
3188 operable = Some(child_id);
3189 }
3190 props = props.over(&child);
3191 }
3192 if clickable_count != 1 {
3193 operable = None;
3194 }
3195 }
3196 let id = operable.unwrap_or(id);
3197 if props.is_meaningful() && own.width > 0.0 && own.height > 0.0 {
3198 self.semantics.insert(base, (id, own, props));
3199 }
3200 }
3201
3202 fn apply_barrier(
3203 &mut self,
3204 barrier: ModalBarrier,
3205 base: &BarrierBase,
3206 id: WidgetId,
3207 own: Rect,
3208 ) {
3209 if barrier.pointer {
3210 self.hits.truncate(base.hits);
3211 self.long_presses.truncate(base.long_presses);
3212 self.focusables.truncate(base.focusables);
3213 self.scrollables.truncate(base.scrollables);
3214 self.scrollbars.truncate(base.scrollbars);
3215 self.draggables.truncate(base.draggables);
3216 self.drag_sources.truncate(base.drag_sources);
3217 self.drop_zones.truncate(base.drop_zones);
3218 self.inks.truncate(base.inks);
3219 self.pans.truncate(base.pans);
3220 self.pointer_listeners.truncate(base.pointer_listeners);
3221 self.hover_regions.truncate(base.hover_regions);
3222 self.text_stops.truncate(base.text_stops);
3223 self.reorderables.truncate(base.reorderables);
3224 self.interactives.truncate(base.interactives);
3225 // The modal focus scope is an index **into** `focusables`. A barrier that cut
3226 // away the focusable it pointed at would leave it dangling past the end, and
3227 // every later slice of the pool would then be empty — no focusable at all,
3228 // rather than the ones the barrier meant to spare.
3229 if let Some(start) = self.focus_scope_start {
3230 self.focus_scope_start = Some(start.min(self.focusables.len()));
3231 }
3232 }
3233 if barrier.absorb && own.width > 0.0 && own.height > 0.0 {
3234 self.hits.push(Hit {
3235 id,
3236 rect: own,
3237 msg: None,
3238 xform: None,
3239 });
3240 }
3241 if barrier.paint {
3242 // The clip is baked into each primitive when it is pushed, so dropping the tail
3243 // leaves nothing for the next sibling to repair.
3244 let _hidden = self.scene.split_off(base.scene);
3245 }
3246 if barrier.semantics {
3247 self.semantics.truncate(base.semantics);
3248 }
3249 }
3250
3251 /// Lower bounds of the interaction registries **before** a transformed composited subtree.
3252 fn xform_base(&self) -> XformBase {
3253 XformBase {
3254 hits: self.hits.len(),
3255 long_presses: self.long_presses.len(),
3256 focusables: self.focusables.len(),
3257 scrollables: self.scrollables.len(),
3258 draggables: self.draggables.len(),
3259 drag_sources: self.drag_sources.len(),
3260 drop_zones: self.drop_zones.len(),
3261 inks: self.inks.len(),
3262 pans: self.pans.len(),
3263 pointer_listeners: self.pointer_listeners.len(),
3264 hover_regions: self.hover_regions.len(),
3265 text_stops: self.text_stops.len(),
3266 reorderables: self.reorderables.len(),
3267 semantics: self.semantics.len(),
3268 }
3269 }
3270
3271 /// Applies the layer transform `matrix` to the registry entries **added since** `base`:
3272 /// the test point of click / long-press targets goes through `M⁻¹` (without overwriting an
3273 /// inner transform already set); and when `matrix` preserves axis alignment
3274 /// (scale/translation, no rotation), the **rects** of focus / scrolling / dragging /
3275 /// **reordering** / accessibility are mapped exactly by `M` (otherwise they are left as
3276 /// they are — the click stays correct through `M⁻¹`). The **shared factor** of the two
3277 /// transformed-composition sites (`walk`'s boundary and `emit_transformed_child`): one
3278 /// place to keep up to date, which forgets no registry (milestone 250 had forgotten
3279 /// `reorderables` in exactly one of the two).
3280 fn transform_interaction_registries(&mut self, base: &XformBase, matrix: Affine) {
3281 let inverse = matrix.inverse();
3282 for h in &mut self.hits[base.hits..] {
3283 h.xform.get_or_insert(inverse);
3284 }
3285 for h in &mut self.long_presses[base.long_presses..] {
3286 h.xform.get_or_insert(inverse);
3287 }
3288 if matrix.is_axis_aligned() {
3289 for f in &mut self.focusables[base.focusables..] {
3290 f.rect = matrix.apply_rect(f.rect);
3291 f.bounds = matrix.apply_rect(f.bounds);
3292 }
3293 for area in &mut self.scrollables[base.scrollables..] {
3294 area.viewport = matrix.apply_rect(area.viewport);
3295 }
3296 for source in &mut self.drag_sources[base.drag_sources..] {
3297 source.rect = matrix.apply_rect(source.rect);
3298 }
3299 for zone in &mut self.drop_zones[base.drop_zones..] {
3300 zone.rect = matrix.apply_rect(zone.rect);
3301 }
3302 for (_, r) in &mut self.inks[base.inks..] {
3303 *r = matrix.apply_rect(*r);
3304 }
3305 for (_, seen, whole) in &mut self.pans[base.pans..] {
3306 *seen = matrix.apply_rect(*seen);
3307 *whole = matrix.apply_rect(*whole);
3308 }
3309 for (_, seen, whole) in &mut self.pointer_listeners[base.pointer_listeners..] {
3310 *seen = matrix.apply_rect(*seen);
3311 *whole = matrix.apply_rect(*whole);
3312 }
3313 for region in &mut self.hover_regions[base.hover_regions..] {
3314 region.seen = matrix.apply_rect(region.seen);
3315 region.whole = matrix.apply_rect(region.whole);
3316 }
3317 for stop in &mut self.text_stops[base.text_stops..] {
3318 stop.rect = matrix.apply_rect(stop.rect);
3319 }
3320 for (_, r) in &mut self.draggables[base.draggables..] {
3321 *r = matrix.apply_rect(*r);
3322 }
3323 for (_, r) in &mut self.reorderables[base.reorderables..] {
3324 *r = matrix.apply_rect(*r);
3325 }
3326 for (_, r, _) in &mut self.semantics[base.semantics..] {
3327 *r = matrix.apply_rect(*r);
3328 }
3329 }
3330 }
3331
3332 /// Entry point for walking a node. When the node is a cacheable **repaint boundary**, it
3333 /// tries to replay its subtree from the paint cache; otherwise (or on a *miss*) it
3334 /// delegates to the full walk [`walk_node`](Self::walk_node), capturing its output for the
3335 /// next frame. Every recursion goes through here → nested boundaries get cached too.
3336 /// The focus flags a subtree carries — exclusion, Tab-skipping, an order, a group —
3337 /// are **subtree-scoped**, so they are pushed here and popped on the way out rather
3338 /// than asked of each widget at the moment it registers. The body of the walk has
3339 /// early returns in a dozen branches; wrapping it is the only way to be sure the
3340 /// scope is closed on every one of them.
3341 fn walk(
3342 &mut self,
3343 widget: &'a dyn Widget<Msg>,
3344 id: WidgetId,
3345 translation: (f32, f32),
3346 clip: Rect,
3347 rects: &[Rect],
3348 index: &mut usize,
3349 ) {
3350 let outer = (
3351 self.focus_excluded,
3352 self.focus_skipped,
3353 self.focus_order,
3354 self.focus_group,
3355 );
3356 if !widget.descendants_focusable() {
3357 self.focus_excluded = true;
3358 }
3359 if widget.focus_skip_traversal() {
3360 self.focus_skipped = true;
3361 }
3362 if let Some(order) = widget.focus_order() {
3363 self.focus_order = Some(order);
3364 }
3365 if widget.focus_group() {
3366 self.focus_group = Some(id);
3367 }
3368 // The backdrop group a subtree sits in, scoped the same way and for the same
3369 // reason. Its own identity is the key: stable across frames, and unique
3370 // without anything having to hand one out.
3371 let outer_group = self.backdrop_group;
3372 if widget.backdrop_group() {
3373 self.backdrop_group = Some(id.as_u64());
3374 }
3375 // The form a field belongs to, scoped the same way (milestone 512).
3376 let outer_form = self.autofill_group;
3377 if widget.autofill_group() {
3378 self.autofill_group = Some(id);
3379 }
3380 // The focus stops this subtree contains start here; the walk is depth-first, so
3381 // they are contiguous and the range closes below.
3382 let stops_before = self.focusables.len();
3383 self.walk_scoped(widget, id, translation, clip, rects, index);
3384 (
3385 self.focus_excluded,
3386 self.focus_skipped,
3387 self.focus_order,
3388 self.focus_group,
3389 ) = outer;
3390 self.backdrop_group = outer_group;
3391 self.autofill_group = outer_form;
3392 self.close_scope(widget, stops_before);
3393 }
3394
3395 /// Files whatever tables this subtree carried, with the focus stops it turned out to
3396 /// contain. Recorded **on the way out**, because the range is not known on the way in;
3397 /// so `scopes` ends up innermost-first among any that overlap, which is the order the
3398 /// resolution wants and the reason it is not sorted afterwards.
3399 fn close_scope(&mut self, widget: &'a dyn Widget<Msg>, stops_before: usize) {
3400 let range = stops_before..self.focusables.len();
3401 if let Some(on_key) = widget.on_keystroke() {
3402 self.listeners.push((range.clone(), on_key));
3403 }
3404 let (strokes, callbacks) = (widget.shortcut_bindings(), widget.shortcut_callbacks());
3405 let (actions, listeners) = (widget.action_bindings(), widget.action_listeners());
3406 if strokes.is_empty() && callbacks.is_empty() && actions.is_empty() && listeners.is_empty()
3407 {
3408 return;
3409 }
3410 self.scopes.push(Scope {
3411 strokes: strokes.to_vec(),
3412 callbacks: callbacks.to_vec(),
3413 actions: actions.to_vec(),
3414 listeners: listeners.to_vec(),
3415 range,
3416 });
3417 }
3418
3419 fn walk_scoped(
3420 &mut self,
3421 widget: &'a dyn Widget<Msg>,
3422 id: WidgetId,
3423 translation: (f32, f32),
3424 clip: Rect,
3425 rects: &[Rect],
3426 index: &mut usize,
3427 ) {
3428 self.claim_overflows(id, translation);
3429 // A **sheet's panel**: the subtree is walked as usual, and every scroll area it
3430 // registered is recorded against the sheet, so the shell knows which lists share a
3431 // finger with it. By range, since a subtree's registrations are contiguous —
3432 // a replayed boundary splices its own in the same place.
3433 if let Some(spec) = widget.sheet() {
3434 let panel = rects[*index].translate(translation.0, translation.1);
3435 let first = self.scrollables.len();
3436 self.walk_node(widget, id, translation, clip, rects, index);
3437 let areas = self.scrollables[first..]
3438 .iter()
3439 .map(|area| area.id)
3440 .collect();
3441 // What the share is a share of. At nought there is nothing to divide by, so the
3442 // height last measured stands in: a finger that lowered the panel to nothing
3443 // may still be holding it.
3444 let size = self.runtime.sheet_size(id, spec);
3445 let available = if size > 0.0 {
3446 panel.height / size
3447 } else {
3448 self.runtime
3449 .sheets
3450 .get(&id)
3451 .map_or(0.0, |sheet| sheet.available())
3452 };
3453 self.sheets.push(crate::sheet::SheetArea {
3454 id,
3455 panel,
3456 available,
3457 spec: spec.clone(),
3458 areas,
3459 });
3460 return;
3461 }
3462
3463 // A **refresh area**: the subtree is walked with this widget named as the host, so
3464 // every scrollable inside records where to send the movement its physics refuses at
3465 // the top edge. The indicator is then painted **over** the subtree — painting it in
3466 // the widget's own `paint` would put it under the list it belongs to.
3467 if let Some(spec) = widget.refresh() {
3468 let viewport = rects[*index]
3469 .translate(translation.0, translation.1)
3470 .intersect(clip);
3471 let outer = self.refresh_host.replace(id);
3472 self.walk_node(widget, id, translation, clip, rects, index);
3473 self.refresh_host = outer;
3474
3475 let area = Refreshable { id, viewport, spec };
3476 if let Some(pull) = self.runtime.refresh.get(&id) {
3477 crate::refresh::paint_refresh(&mut self.scene, &area, pull, &self.theme, clip);
3478 // A pull that is settling, spinning or fading away drives itself, so the
3479 // frame after this one has to happen.
3480 self.wants_animation = true;
3481 }
3482 self.refreshes.push(area);
3483 return;
3484 }
3485
3486 // A **barrier** (`IgnorePointer`, `AbsorbPointer`, a hidden `Visibility`,
3487 // `ExcludeSemantics`): the subtree is walked exactly as usual, and then whatever it
3488 // added to the withheld registries is dropped again.
3489 //
3490 // Removing afterwards rather than skipping the walk is what makes it exact. A widget
3491 // deep inside registers its click target, focus stop, scrollable area or accessibility
3492 // node without knowing that something above is holding the subtree out of the frame;
3493 // truncating at the barrier catches every one of them, including those added by
3494 // widgets written after this code. It also keeps the walk's rect indexing untouched,
3495 // which a skipped subtree would break.
3496 // A **description** (`Semantics`): something above states what the subtree *is*,
3497 // which the subtree cannot state for itself. Same shape as the barrier below and for
3498 // the same reason — walk first, reconcile after, so a widget deep inside annotates
3499 // itself without knowing anything is speaking for it.
3500 if let Some(described) = widget.describes() {
3501 let base = self.semantics.len();
3502 let own = rects[*index]
3503 .translate(translation.0, translation.1)
3504 .intersect(clip);
3505 self.walk_node(widget, id, translation, clip, rects, index);
3506 self.apply_description(described, base, id, own);
3507 return;
3508 }
3509
3510 if let Some(barrier) = widget.barrier().filter(|b| !b.is_none()) {
3511 let base = self.barrier_base();
3512 // The barrier's own box, before `walk_node` advances the index past it.
3513 let own = rects[*index]
3514 .translate(translation.0, translation.1)
3515 .intersect(clip);
3516 self.walk_node(widget, id, translation, clip, rects, index);
3517 self.apply_barrier(barrier, &base, id, own);
3518 return;
3519 }
3520
3521 // An opacity group: the subtree is painted normally, then its range of primitives is
3522 // **drained** into a composited layer at the group's opacity — so overlaps do not
3523 // double-blend. The animated opacity is the value the runtime tweened; otherwise the
3524 // fixed target. Opaque (≈1): no layer at all (zero cost).
3525 if let Some(target) = widget.opacity_group() {
3526 let opacity = self.runtime.value_or(id, target).clamp(0.0, 1.0);
3527 // Transparent (≈0): walked, so that what it registers is still there, and not
3528 // painted at all — the reference's faded-out child costs nothing to draw either
3529 // (milestone 595). A layer of nothing would still be a primitive in the frame.
3530 if opacity < 0.001 {
3531 let start = self.scene.primitives().len();
3532 self.walk_node(widget, id, translation, clip, rects, index);
3533 let _unseen = self.scene.split_off(start);
3534 return;
3535 }
3536 if opacity < 0.999 {
3537 let start = self.scene.primitives().len();
3538 self.walk_node(widget, id, translation, clip, rects, index);
3539 let group = self.scene.split_off(start);
3540 self.scene.push_primitive(Primitive::Layer {
3541 primitives: group,
3542 opacity,
3543 clip,
3544 clip_shape: ClipShape::Rect,
3545 transform: None,
3546 filter: LayerFilter::NONE,
3547 owner: id.as_u64(),
3548 });
3549 return;
3550 }
3551 // Fully opaque: an ordinary render (no pointless layer).
3552 }
3553
3554 // A **pixel effect** over the subtree (`ColorFiltered`, `ImageFiltered`,
3555 // `ShaderMask`): painted normally, then drained into a composited layer that
3556 // carries the effect. The renderer applies it when it composites — the image
3557 // filter as a pre-pass over the layer texture, the colour filter and the mask
3558 // in the compositing fragment.
3559 //
3560 // The box is passed in because a mask is written in fractions of the box it
3561 // covers, and this is the first point at which that box is a place on screen.
3562 if let Some(filter) = widget.layer_filter(crate::widget::FilterContext {
3563 box_rect: rects[*index].translate(translation.0, translation.1),
3564 backdrop_group: self.backdrop_group,
3565 }) {
3566 // The layer keeps the **ambient** clip rather than its own box: an image
3567 // filter reaches past the pixels it came from, and cutting it at the box
3568 // would shave the edge off every blur.
3569 let start = self.scene.primitives().len();
3570 self.walk_node(widget, id, translation, clip, rects, index);
3571 let group = self.scene.split_off(start);
3572 let (group, filter, clip_box) = fold_filter(group, filter, clip);
3573 self.scene.push_primitive(Primitive::Layer {
3574 primitives: group,
3575 opacity: 1.0,
3576 clip: clip_box,
3577 clip_shape: ClipShape::Rect,
3578 transform: None,
3579 filter,
3580 owner: id.as_u64(),
3581 });
3582 return;
3583 }
3584
3585 // **Shape** clipping: the subtree is painted normally, bounded to the widget's box,
3586 // then its primitives are **drained** into a composited layer whose shape (rounded
3587 // corners / ellipse) modulates the alpha — the overflowing corners are erased at
3588 // compositing time. The shape's box is the layer's clip rect. Two sources: `ClipPath`
3589 // (an arbitrary path, taking priority) or `ClipRRect`/`ClipOval` (an analytic shape).
3590 // The local path is **offset to the box's screen position**.
3591 if widget.clip_path().is_some() || widget.clip_shape().is_some() {
3592 let box_rect = rects[*index].translate(translation.0, translation.1);
3593 let shape = widget
3594 .clip_path()
3595 .map(|p| ClipShape::Path(p.translated(box_rect.x, box_rect.y)))
3596 .or_else(|| widget.clip_shape())
3597 .expect("clip_path or clip_shape is Some");
3598 let clip_box = clip.intersect(box_rect);
3599 let start = self.scene.primitives().len();
3600 self.walk_node(widget, id, translation, clip_box, rects, index);
3601 let group = self.scene.split_off(start);
3602 // A clip around a filter is **one** layer, not two. It matters most for a
3603 // backdrop: the reference's own advice is to wrap one in a clip to give it
3604 // its shape, and a backdrop pushed a level down would be filtering the
3605 // clip's contents rather than the frame.
3606 let (group, filter, clip_box) = fold_filter(group, LayerFilter::NONE, clip_box);
3607 self.scene.push_primitive(Primitive::Layer {
3608 primitives: group,
3609 opacity: 1.0,
3610 clip: clip_box,
3611 clip_shape: shape,
3612 transform: None,
3613 filter,
3614 owner: id.as_u64(),
3615 });
3616 return;
3617 }
3618
3619 // Composable paint transforms (`Transform`: scale and/or rotation; translation goes
3620 // through the child offset instead). Scale and rotation are melted into **a single
3621 // affine matrix** `M`, the subtree is painted **flat**, then wrapped in a composited
3622 // layer transformed by `M`. The hit-test applies `M⁻¹` to the point. The translation,
3623 // applied upstream through `child_offset`, is the innermost one.
3624 //
3625 // A transform that was told to **animate** hands over its numbers, and only its
3626 // numbers: the pivots stay the widget's, because a pivot is a choice of origin
3627 // rather than a quantity and interpolating it would slide the subtree across the
3628 // screen with nothing describing it having changed. Where the runtime has never
3629 // heard of this widget the static value stands, which is the same rule every
3630 // other animated property follows on mount.
3631 let moving = self.runtime.anim_transform(id);
3632 let scale = widget
3633 .transform_scale()
3634 .map(|(sx, sy, pivot)| {
3635 moving.map_or((sx, sy, pivot), |m| (m.scale_x, m.scale_y, pivot))
3636 })
3637 .filter(|(sx, sy, _)| (sx - 1.0).abs() > 1e-4 || (sy - 1.0).abs() > 1e-4);
3638 let rotate = widget
3639 .transform_rotate()
3640 .map(|(angle, pivot)| moving.map_or((angle, pivot), |m| (m.rotation, pivot)))
3641 .filter(|(a, _)| a.abs() > 1e-4);
3642 if scale.is_some() || rotate.is_some() {
3643 // The pivots are taken on the **child's** box (the next node in prefix order): it
3644 // is the child that gets transformed, and its box hugs the content even when the
3645 // Transform's own box is stretched by the parent.
3646 let basis = rects.get(*index + 1).copied().unwrap_or(rects[*index]);
3647 let box_rect = basis.translate(translation.0, translation.1);
3648 let pivot_of = |align: frus_core::Alignment| {
3649 Point::new(
3650 box_rect.x + box_rect.width * align.fraction_x(),
3651 box_rect.y + box_rect.height * align.fraction_y(),
3652 )
3653 };
3654 // The composition: scale (about its own pivot) **then** rotation (about its own).
3655 // In RTL the world is mirrored → the rotation direction is inverted.
3656 let mut matrix = Affine::IDENTITY;
3657 if let Some((sx, sy, pivot_align)) = scale {
3658 matrix = matrix.then(Affine::scale(sx, sy).about(pivot_of(pivot_align)));
3659 }
3660 if let Some((angle, pivot_align)) = rotate {
3661 let angle = if self.rtl() { -angle } else { angle };
3662 matrix = matrix.then(Affine::rotation(angle).about(pivot_of(pivot_align)));
3663 }
3664
3665 let p0 = self.scene.primitives().len();
3666 let base = self.xform_base();
3667 self.walk_node(widget, id, translation, clip, rects, index);
3668 // Wraps the range of primitives — painted flat — in a layer transformed by `M`
3669 // (scale/rotation applied at compositing time).
3670 let group = self.scene.split_off(p0);
3671 self.scene.push_primitive(Primitive::Layer {
3672 primitives: group,
3673 opacity: 1.0,
3674 clip,
3675 clip_shape: ClipShape::Rect,
3676 transform: Some(LayerTransform::new(matrix)),
3677 filter: LayerFilter::NONE,
3678 owner: id.as_u64(),
3679 });
3680 // Counter-transforms the hit-test and maps the subtree's interaction rects.
3681 self.transform_interaction_registries(&base, matrix);
3682 return;
3683 }
3684
3685 // The inspector wants a full walk (it collects every node); caching only happens
3686 // outside inspection.
3687 if self.inspector.is_none() && widget.repaint_boundary() {
3688 if let Some(count) = plain_subtree_len(widget) {
3689 let start = *index;
3690 let sub = &rects[start..start + count];
3691 let fp = self.boundary_fingerprint(widget, id, translation, sub);
3692
3693 // Hit: the same generation (config) + the same fingerprint (state+geometry)
3694 // ⇒ the paint would be identical. The output is cloned and replayed.
3695 let hit = {
3696 let mut pc = self.runtime.paint_cache.borrow_mut();
3697 pc.get(id, fp).and_then(|(rc, any)| {
3698 any.downcast_ref::<BoundaryData<Msg>>()
3699 .map(|d| (rc, d.clone()))
3700 })
3701 };
3702 if let Some((rc, data)) = hit {
3703 self.runtime.paint_cache.borrow_mut().note_hit();
3704 self.splice_boundary(data);
3705 *index += rc;
3706 return;
3707 }
3708
3709 // Miss: paints normally, capturing the subtree's output (primitives +
3710 // interaction maps) for the next frame.
3711 let snap = self.snapshot();
3712 self.walk_node(widget, id, translation, clip, rects, index);
3713 self.runtime.paint_cache.borrow_mut().note_miss();
3714 if let Some(data) = self.capture_since(&snap) {
3715 self.runtime
3716 .paint_cache
3717 .borrow_mut()
3718 .put(id, fp, count, Box::new(data));
3719 }
3720 return;
3721 }
3722 }
3723 self.walk_node(widget, id, translation, clip, rects, index);
3724 }
3725
3726 /// Deforms the region's content by its overscroll **stretch**, if it has one
3727 /// (milestone 591): everything painted since `mark` goes into one layer, scaled along
3728 /// the axis from the edge pulled, and what can be touched in it moves with it.
3729 fn add_overscroll_stretch(
3730 &mut self,
3731 id: WidgetId,
3732 viewport: Rect,
3733 clip: Rect,
3734 mark: (usize, XformBase),
3735 ) {
3736 let Some(matrix) = self
3737 .runtime
3738 .scroll_stretch
3739 .get(&id)
3740 .and_then(|stretch| stretch.transform(viewport))
3741 else {
3742 return;
3743 };
3744 let (p0, base) = mark;
3745 let group = self.scene.split_off(p0);
3746 self.scene.push_primitive(Primitive::Layer {
3747 primitives: group,
3748 opacity: 1.0,
3749 clip,
3750 clip_shape: ClipShape::Rect,
3751 transform: Some(LayerTransform::new(matrix)),
3752 filter: LayerFilter::NONE,
3753 owner: id.as_u64(),
3754 });
3755 self.transform_interaction_registries(&base, matrix);
3756 }
3757
3758 /// Paints a child **flat** (laid out separately, at `translation`, with its own rects)
3759 /// then wraps it in a composited layer transformed by `matrix` and clipped to `clip`. The
3760 /// hit-test counter-transforms the point (`M⁻¹`); when `matrix` stays axis-aligned
3761 /// (scale/translation), the focus / scroll / drag / accessibility bounds are transformed
3762 /// too. The shared factor of `InteractiveViewer`, `RotatedBox` and `FittedBox`.
3763 // The child, its identity, and the four things that place it. Splitting them would
3764 // only mean passing the same values in two hops.
3765 #[allow(clippy::too_many_arguments)]
3766 fn emit_transformed_child(
3767 &mut self,
3768 child: &'a dyn Widget<Msg>,
3769 cid: WidgetId,
3770 translation: (f32, f32),
3771 clip: Rect,
3772 child_rects: &[Rect],
3773 matrix: Affine,
3774 owner: WidgetId,
3775 ) {
3776 let p0 = self.scene.primitives().len();
3777 let base = self.xform_base();
3778 let mut child_index = 0;
3779 self.walk(child, cid, translation, clip, child_rects, &mut child_index);
3780 let group = self.scene.split_off(p0);
3781 self.scene.push_primitive(Primitive::Layer {
3782 primitives: group,
3783 opacity: 1.0,
3784 clip,
3785 clip_shape: ClipShape::Rect,
3786 transform: Some(LayerTransform::new(matrix)),
3787 filter: LayerFilter::NONE,
3788 owner: owner.as_u64(),
3789 });
3790 self.transform_interaction_registries(&base, matrix);
3791 }
3792
3793 /// Paints one node, **under the theme it asks for**. A [`crate::Themed`] replaces the
3794 /// ambient theme for itself and everything below it; it is put back on the way out, so
3795 /// the sibling that follows is untouched. Everything the subtree reads — its paint,
3796 /// its ink, its focus ring, its layout through `cached_rects`, and any overlay it
3797 /// defers — goes through this field, which is what makes one swap enough.
3798 fn walk_node(
3799 &mut self,
3800 widget: &'a dyn Widget<Msg>,
3801 id: WidgetId,
3802 translation: (f32, f32),
3803 clip: Rect,
3804 rects: &[Rect],
3805 index: &mut usize,
3806 ) {
3807 // The box this node is about to be given, read **before** the walk consumes the
3808 // index: a decoration painted over the children needs it once they are done, and
3809 // by then `*index` has moved past the whole subtree.
3810 let over = rects
3811 .get(*index)
3812 .copied()
3813 .map(|r| r.translate(translation.0, translation.1));
3814 let outer = scoped_theme(widget, id, self.runtime, &self.theme)
3815 .map(|theme| std::mem::replace(&mut self.theme, std::rc::Rc::from(theme)));
3816 // The node that turns the texts under it selectable together is a selection area:
3817 // the texts it registers below belong to it, until the walk leaves it.
3818 let outer_area = outer
3819 .as_ref()
3820 .filter(|before| !before.widgets.text.selectable && self.theme.widgets.text.selectable)
3821 .map(|_| (self.area.replace(id), self.area_widget.replace(widget)));
3822 // The scoped surface, held for this subtree exactly as the layout walk holds it —
3823 // a widget that paints from `MediaQuery::of()` must see the same description it
3824 // was measured against, or the two disagree by whatever the scope removed.
3825 let _surface = widget
3826 .media_override(crate::MediaQuery::of())
3827 .map(crate::MediaQuery::install);
3828 let _shell = widget.scaffold_override().map(crate::ScaffoldInfo::install);
3829 let _scrolling = widget
3830 .scroll_behavior_override()
3831 .map(crate::ScrollConfiguration::install);
3832 // A region the mouse enters and leaves: registered before its subtree, so that the
3833 // regions inside it name it as their parent (milestone 583).
3834 let outer_hover = match (widget.hover_region(), over) {
3835 (Some(spec), Some(whole)) => {
3836 self.register_hover_region(id, spec, whole, clip);
3837 Some(self.hover_parent.replace(id))
3838 }
3839 _ => None,
3840 };
3841 self.walk_node_themed(widget, id, translation, clip, rects, index);
3842 if let Some(parent) = outer_hover {
3843 self.hover_parent = parent;
3844 }
3845 if let Some((area, area_widget)) = outer_area {
3846 self.area = area;
3847 self.area_widget = area_widget;
3848 }
3849 // Over its own children: the reference's `foregroundDecoration`, and the only
3850 // point in the walk where a widget paints after its subtree. Still under this
3851 // node's own theme, since it is this node's decoration.
3852 if let Some(bounds) = over {
3853 if let Some(decoration) = widget.foreground(&self.theme) {
3854 let status = self.full_status(widget, id);
3855 self.scene.set_clip(clip);
3856 self.scene.set_owner(id.as_u64());
3857 self.scene.set_bounds(bounds);
3858 decoration.paint_into_in(
3859 &mut self.scene,
3860 bounds,
3861 status.opacity,
3862 self.theme.direction,
3863 );
3864 self.scene.set_clip(clip);
3865 }
3866 }
3867 if let Some(outer) = outer {
3868 self.theme = outer;
3869 }
3870 }
3871
3872 /// The walk proper, with the theme already in place — split out so that no early
3873 /// return inside it can skip putting the outer theme back.
3874 fn walk_node_themed(
3875 &mut self,
3876 widget: &'a dyn Widget<Msg>,
3877 id: WidgetId,
3878 translation: (f32, f32),
3879 clip: Rect,
3880 rects: &[Rect],
3881 index: &mut usize,
3882 ) {
3883 let rect = rects[*index];
3884 *index += 1;
3885 let draw_rect = rect.translate(translation.0, translation.1);
3886 self.inspect_enter(widget, id, draw_rect);
3887
3888 let status = self.full_status(widget, id);
3889 if widget.continuous() {
3890 self.wants_animation = true;
3891 }
3892
3893 self.scene.set_clip(clip);
3894 self.scene.set_owner(id.as_u64());
3895 // The box this widget was given. Text primitives record it: a line of text
3896 // says only where it starts, and the renderer has to know what it covers to
3897 // order it against anything else (milestone 295).
3898 self.scene.set_bounds(draw_rect);
3899 widget.paint(draw_rect, status, &self.theme, &mut self.scene);
3900 // A widget may have tightened the clip (TextField, for one): it is restored here.
3901 self.scene.set_clip(clip);
3902 // A part of the screen saying what the system bars over it should look like, kept
3903 // with its box: the shell asks which ones lie under each bar (#46).
3904 if let Some(style) = widget.system_ui_style() {
3905 self.system_ui.push((draw_rect, style));
3906 }
3907 // The ink a tap left on this surface: over the surface's own paint, under its
3908 // children — where a material surface puts it. The box is recorded too, so the
3909 // shell can start the next splash at the right place, in the right size.
3910 if let Some(style) = widget.ink(&self.theme) {
3911 self.inks.push((id, draw_rect));
3912 if let Some(ripples) = self.runtime.ink.get(&id) {
3913 ripples.paint(
3914 id.as_u64(),
3915 draw_rect,
3916 style.radius,
3917 style.color,
3918 &mut self.scene,
3919 );
3920 self.scene.set_clip(clip);
3921 }
3922 }
3923 self.draw_focus_ring(draw_rect, &status, widget);
3924 if let Some(can_paste) = status.toolbar {
3925 self.push_selection_toolbar(widget, id, draw_rect, clip, &status, can_paste);
3926 }
3927 if status.region_bar && !self.region_bar_placed {
3928 if let Some(range) = status.region {
3929 self.push_region_toolbar(widget, id, draw_rect, clip, range);
3930 }
3931 }
3932
3933 // A shared element is recorded **whether or not it is on screen**: half way
3934 // through a transition the one being left behind has usually slid off the edge,
3935 // and its box is exactly what the flight starts from. Every other registry here
3936 // is about what a pointer can reach, which is why they are inside the guard.
3937 if let Some(screen) = self.hero_screen {
3938 if let Some(tag) = widget.hero_tag() {
3939 self.heroes.push((
3940 HeroSpot {
3941 tag,
3942 screen,
3943 id,
3944 rect: draw_rect,
3945 },
3946 widget,
3947 ));
3948 }
3949 }
3950
3951 let visible = draw_rect.intersect(clip);
3952 // A text in a selection area: a place a selection can begin, end or pass through,
3953 // registered as far as it is visible, in the order it is painted.
3954 if self.theme.widgets.text.selectable && visible.width > 0.0 && visible.height > 0.0 {
3955 if let (Some(area), Some(_)) = (self.area, widget.selection_text()) {
3956 self.text_stops.push(crate::TextStop {
3957 id,
3958 rect: draw_rect,
3959 area,
3960 });
3961 }
3962 }
3963 // A focus stop clipped entirely away by a **scroll** is still a focus stop.
3964 // Tab has to reach the field below the fold — the shell brings it into view
3965 // when it lands there — and registering only what the eye can see is how a long
3966 // form came to have half its fields unreachable from the keyboard. Clipped away
3967 // by anything else it is gone: nothing could reveal it, so focus would land
3968 // where the eye cannot follow.
3969 //
3970 // Only the focus registry does this. A click still needs the visible box, or a
3971 // tap on empty space would land on something scrolled out of sight.
3972 if widget.focusable()
3973 && !self.focus_excluded
3974 && (self.scroll_host.is_some() || (visible.width > 0.0 && visible.height > 0.0))
3975 {
3976 self.focusables.push(Focusable {
3977 id,
3978 rect: visible,
3979 bounds: draw_rect,
3980 form: self.autofill_group,
3981 scroll: self.scroll_host,
3982 skip: self.focus_skipped || widget.focus_skip_traversal(),
3983 order: widget.focus_order().or(self.focus_order),
3984 group: self.focus_group,
3985 autofocus: widget.autofocus(),
3986 });
3987 }
3988 if visible.width > 0.0 && visible.height > 0.0 {
3989 // What a press or a drag can reach: the visible box, cut at a hanging stack's.
3990 let touch = self.touch_clip.map_or(visible, |t| visible.intersect(t));
3991 // A press that lands on a **surface** and on nothing inside it stops there.
3992 // Registered before the children, so anything inside still wins on the way
3993 // back out — see [`Widget::opaque`].
3994 if widget.opaque() {
3995 self.hits.push(Hit {
3996 id,
3997 rect: touch,
3998 msg: None,
3999 xform: None,
4000 });
4001 }
4002 // A target for a press: something that answers a tap, or a double or a secondary
4003 // tap without one — the shell asks it for those once the press lands on it.
4004 let tap = widget.on_click();
4005 if tap.is_some()
4006 || widget.on_double_tap().is_some()
4007 || widget.on_secondary_tap().is_some()
4008 {
4009 self.hits.push(Hit {
4010 id,
4011 rect: touch,
4012 msg: tap,
4013 xform: None,
4014 });
4015 }
4016 // A detector that takes a drag (milestone 582).
4017 if widget.pan_axis().is_some() {
4018 self.pans.push((id, touch, draw_rect));
4019 }
4020 // The title bar's line (milestone 640).
4021 if widget.wants_title_bar() {
4022 self.title_bar_row = Some(draw_rect);
4023 }
4024 if let Some(role) = widget.title_bar_role() {
4025 self.title_bar_regions.push((draw_rect, role));
4026 }
4027 // A widget that hears the pointer's raw events (milestone 586).
4028 if widget.pointer_listener() {
4029 self.pointer_listeners.push((id, touch, draw_rect));
4030 }
4031 if let Some(msg) = widget.on_long_press() {
4032 self.long_presses.push(Hit {
4033 id,
4034 rect: touch,
4035 msg: Some(msg),
4036 xform: None,
4037 });
4038 }
4039 if let Some(action) = widget.edit_action() {
4040 self.edit_actions.push((id, action));
4041 }
4042 if widget.draggable() {
4043 self.draggables.push((id, touch));
4044 }
4045 if let Some(payload) = widget.drag_payload() {
4046 self.drag_sources.push(DragSource {
4047 id,
4048 rect: touch,
4049 payload,
4050 });
4051 }
4052 if widget.drop_zone() {
4053 self.drop_zones.push(DropZone { id, rect: touch });
4054 }
4055 if widget.reorder_index().is_some() {
4056 self.reorderables.push((id, touch));
4057 }
4058 // The accessibility tree: nodes that carry meaning (a role or a label).
4059 if let Some(sem) = widget.semantics().filter(|s| s.is_meaningful()) {
4060 self.semantics.push((id, visible, sem));
4061 }
4062 // A **multi-line** field whose content overflows: a scrollable region (wheel and
4063 // inertia through the generic machinery; the shell follows the caret) plus a
4064 // draggable scrollbar (mouse and touch).
4065 if let Some(vp) = widget.text_viewport(draw_rect) {
4066 if let Some((content_h, visible_h, _, _)) = widget.text_metrics(draw_rect.width, 0)
4067 {
4068 let max_y = (content_h - visible_h).max(0.0);
4069 if max_y > 0.0 {
4070 self.scrollables.push(Scrollable {
4071 id,
4072 viewport: vp,
4073 max_x: 0.0,
4074 max_y,
4075 axis: crate::scroll::Axis::Vertical,
4076 physics: region_physics(widget, &self.theme),
4077 overscroll: crate::ScrollConfiguration::of()
4078 .overscroll_indicator(&self.theme),
4079 fling: crate::ScrollConfiguration::of()
4080 .velocity_tracker(&self.theme)
4081 .strategy(),
4082 refresh: self.refresh_host,
4083 page: None,
4084 reverse_x: false,
4085 reverse_y: false,
4086 host: self.scroll_host,
4087 keep_visible: None,
4088 });
4089 let offset_y = self
4090 .runtime
4091 .scroll
4092 .get(&id)
4093 .map(|s| s.1)
4094 .unwrap_or(0.0)
4095 .clamp(0.0, max_y);
4096 self.add_scrollbar(
4097 id,
4098 vp,
4099 Bar {
4100 vertical: true,
4101 offset: offset_y,
4102 max: max_y,
4103 reverse: false,
4104 asked: widget.scrollbars(),
4105 visible: widget.thumb_visibility(),
4106 },
4107 );
4108 }
4109 }
4110 }
4111 }
4112
4113 if let Some((progress, forward)) = widget.navigator() {
4114 let bounds = draw_rect;
4115 let children = widget.children();
4116 // **The pages stop at the navigator's edge.** A screen sliding in comes from
4117 // outside the box, and one sliding out goes outside it; before milestone 398
4118 // the only thing stopping them was the window, so a navigator that was not the
4119 // whole window painted its pages over its siblings — and even a full-window
4120 // one spent the frame drawing a screen nobody could see. The reference clips
4121 // by default (`Clip.hardEdge`) for the same reason.
4122 let clip = if widget.navigator_clips() {
4123 clip.intersect(bounds)
4124 } else {
4125 clip
4126 };
4127 // The pages under the one on show are kept in the tree and stay out of the picture.
4128 let hidden = widget.navigator_retained().min(children.len());
4129 let shown = &children[hidden..];
4130 if shown.len() >= 2 {
4131 // **A transition, as the theme's platform draws it** (milestone 620): the
4132 // builder the theme maps the platform to says where each page is, how big,
4133 // how opaque, and what lies between them, `progress` of the way through.
4134 let builder = self.theme.page_transitions.builder_for(self.theme.platform);
4135 let frame = builder.frame(progress, forward, widget.navigator_gesture());
4136 // `Navigator::from` inserts the screen being left at index 0, so
4137 // `shown[1]` is always the destination: the page on top on a push, the one
4138 // underneath on a pop.
4139 let (top, below) = if forward { (1, 0) } else { (0, 1) };
4140 let mirror = if frame.mirrored && self.rtl() {
4141 -1.0
4142 } else {
4143 1.0
4144 };
4145 // Where the shared elements of this transition start, in both the
4146 // registry and the scene: everything after this point belongs to the
4147 // two screens, and the flight is resolved from it once both are drawn.
4148 let hero_base = self.heroes.len();
4149 let scene_base = self.scene.primitives().len();
4150 let surface = self.theme.scheme.surface;
4151 let fill = |builder: &mut Self, color: Color| {
4152 builder.scene.set_owner(0);
4153 builder.scene.set_clip(clip);
4154 builder.scene.fill_rect(bounds, color);
4155 };
4156 if frame.backdrop > 0.0 {
4157 fill(self, surface.fade(frame.backdrop));
4158 }
4159 let outer_screen = self.hero_screen.replace(below as u8);
4160 // A screen being left keeps its floating layers to itself.
4161 // `process_overlays` draws every overlay above the **whole window**, after
4162 // both screens, so a menu left open on the departing screen would be
4163 // painted on top of the screen that replaced it. Whatever the departing one
4164 // defers is dropped.
4165 let overlay_base = self.overlays.len();
4166 self.render_posed(
4167 shown[below].as_ref(),
4168 child_id(id, hidden + below, shown[below].as_ref()),
4169 bounds,
4170 frame.below,
4171 mirror,
4172 clip,
4173 );
4174 if below != 1 {
4175 self.overlays.truncate(overlay_base);
4176 }
4177 if frame.barrier > 0.0 {
4178 fill(self, Color::BLACK.fade(frame.barrier));
4179 }
4180 if frame.scrim > 0.0 {
4181 fill(self, surface.fade(frame.scrim));
4182 }
4183 if frame.edge_shadow > 0.0 {
4184 self.paint_edge_shadow(bounds, frame, mirror, clip);
4185 }
4186 self.hero_screen = Some(top as u8);
4187 let overlay_base = self.overlays.len();
4188 self.render_posed(
4189 shown[top].as_ref(),
4190 child_id(id, hidden + top, shown[top].as_ref()),
4191 bounds,
4192 frame.top,
4193 mirror,
4194 clip,
4195 );
4196 if top != 1 {
4197 self.overlays.truncate(overlay_base);
4198 }
4199 self.hero_screen = outer_screen;
4200 self.fly_heroes(hero_base, scene_base, progress);
4201 } else if let Some(screen) = shown.first() {
4202 self.render_screen(
4203 screen.as_ref(),
4204 child_id(id, hidden, screen.as_ref()),
4205 bounds,
4206 0.0,
4207 clip,
4208 );
4209 }
4210 } else if widget.interactive().is_some() {
4211 // An **interactive** viewport (`InteractiveViewer`): the child fills the viewport
4212 // at scale 1, then the retained transform (scale + translation, from the shell's
4213 // gestures) is applied to it through **a single layer** carrying both the matrix
4214 // `M` and the clip to the viewport.
4215 let viewport = draw_rect;
4216 let content_clip = clip.intersect(viewport);
4217 self.interactives.push((id, viewport));
4218 if let Some(content) = widget.children().first() {
4219 let content = content.as_ref();
4220 let cid = child_id(id, 0, content);
4221 let content_rects = self.cached_rects(
4222 cid,
4223 content,
4224 Constraints::definite(Size::new(viewport.width, viewport.height)),
4225 );
4226 let matrix = self
4227 .runtime
4228 .interactive
4229 .get(&id)
4230 .copied()
4231 .unwrap_or_default()
4232 .matrix();
4233 self.emit_transformed_child(
4234 content,
4235 cid,
4236 (viewport.x, viewport.y),
4237 content_clip,
4238 &content_rects,
4239 matrix,
4240 id,
4241 );
4242 }
4243 } else if let Some(q) = widget.rotated_quarter_turns() {
4244 // `RotatedBox`: the child, measured at its **natural** size, is centred in the box
4245 // (with the dimensions swapped for an odd quarter, see `build_layout`) then rotated
4246 // about the centre. The rotation, applied at compositing time, does not stay
4247 // axis-aligned for an odd quarter (the focus bounds are left as they are — the
4248 // click itself stays correct through `M⁻¹`).
4249 let box_rect = draw_rect;
4250 if let Some(child) = widget.children().first() {
4251 let child = child.as_ref();
4252 let cid = child_id(id, 0, child);
4253 let child_rects =
4254 self.cached_rects(cid, child, Constraints::scroll(0.0, 0.0, true, true));
4255 let nat = child_rects
4256 .first()
4257 .copied()
4258 .unwrap_or(Rect::new(0.0, 0.0, 0.0, 0.0));
4259 let center = Point::new(
4260 box_rect.x + box_rect.width / 2.0,
4261 box_rect.y + box_rect.height / 2.0,
4262 );
4263 let translation = (center.x - nat.width / 2.0, center.y - nat.height / 2.0);
4264 let angle = q.rem_euclid(4) as f32 * std::f32::consts::FRAC_PI_2;
4265 let angle = if self.rtl() { -angle } else { angle };
4266 let matrix = Affine::rotation(angle).about(center);
4267 self.emit_transformed_child(
4268 child,
4269 cid,
4270 translation,
4271 clip,
4272 &child_rects,
4273 matrix,
4274 id,
4275 );
4276 }
4277 } else if let Some(fit) = widget.fitted() {
4278 // `FittedBox`: the child, measured at its **natural** size, is scaled according to
4279 // the `BoxFit` (uniformly, except for `Fill`), centred and clipped to the box. The
4280 // scale stays axis-aligned → the focus bounds follow.
4281 let box_rect = draw_rect;
4282 let content_clip = clip.intersect(box_rect);
4283 if let Some(child) = widget.children().first() {
4284 let child = child.as_ref();
4285 let cid = child_id(id, 0, child);
4286 let child_rects =
4287 self.cached_rects(cid, child, Constraints::scroll(0.0, 0.0, true, true));
4288 let nat = child_rects
4289 .first()
4290 .copied()
4291 .unwrap_or(Rect::new(0.0, 0.0, 0.0, 0.0));
4292 let (sx, sy) = fit.scale(
4293 Size::new(nat.width, nat.height),
4294 Size::new(box_rect.width, box_rect.height),
4295 );
4296 let center = Point::new(
4297 box_rect.x + box_rect.width / 2.0,
4298 box_rect.y + box_rect.height / 2.0,
4299 );
4300 let translation = (center.x - nat.width / 2.0, center.y - nat.height / 2.0);
4301 let matrix = Affine::scale(sx, sy).about(center);
4302 self.emit_transformed_child(
4303 child,
4304 cid,
4305 translation,
4306 content_clip,
4307 &child_rects,
4308 matrix,
4309 id,
4310 );
4311 }
4312 } else if let Some(content) = widget.scroll_content() {
4313 let axis = widget.scroll_axis();
4314 let viewport = draw_rect;
4315 let content_clip = clip.intersect(viewport);
4316 // `reverse` applies to the axis this scrolls along; a two-dimensional scroll
4317 // takes it on the vertical, which is the one a reversed view is ever about.
4318 let reverse = if widget.scroll_reverse() {
4319 (axis.free_x() && !axis.free_y(), axis.free_y())
4320 } else {
4321 (false, false)
4322 };
4323
4324 // The padding is **inside** the viewport and scrolls with the content:
4325 // room at the end of a feed is reachable by scrolling to it, room taken out
4326 // of the window would sit there for ever. The reference's `SliverPadding`.
4327 let pad = widget.scroll_padding();
4328 let content_rects = self.cached_rects(
4329 child_id(id, 0, content),
4330 content,
4331 Constraints::scroll(
4332 (viewport.width - pad.left - pad.right).max(0.0),
4333 (viewport.height - pad.top - pad.bottom).max(0.0),
4334 axis.free_x(),
4335 axis.free_y(),
4336 ),
4337 );
4338
4339 let content_size = content_rects
4340 .first()
4341 .copied()
4342 .unwrap_or(Rect::new(0.0, 0.0, 0.0, 0.0));
4343 // What scrolls is the content **and** its room, which is what makes the far
4344 // inset reachable rather than decorative.
4345 let scrolled = Size::new(
4346 content_size.width + pad.left + pad.right,
4347 content_size.height + pad.top + pad.bottom,
4348 );
4349 let max_x = (scrolled.width - viewport.width).max(0.0);
4350 let max_y = (scrolled.height - viewport.height).max(0.0);
4351
4352 // The geometry without the identity: enough to ask where the content sits at
4353 // an offset, and what offset would put a box where it is wanted.
4354 let frame = Scrollable {
4355 id,
4356 viewport,
4357 max_x,
4358 max_y,
4359 axis,
4360 physics: crate::ScrollPhysics::CLAMPING,
4361 overscroll: None,
4362 fling: frus_core::VelocityStrategy::Regression,
4363 refresh: None,
4364 page: None,
4365 reverse_x: reverse.0,
4366 reverse_y: reverse.1,
4367 host: None,
4368 keep_visible: None,
4369 };
4370 // What the content asks to be kept in view — a tab bar's selected tab — in
4371 // the content's own coordinates, which is the only frame it can speak in.
4372 let asked = content.keep_visible(
4373 Size::new(content_size.width, content_size.height),
4374 &self.theme,
4375 );
4376 // Where that box would sit if nobody had scrolled: the frame's coordinates,
4377 // with the offset taken out. See [`KeepVisible::rect`] for why it is stored
4378 // this way rather than where it is drawn.
4379 let keep = asked.map(|keep| {
4380 let rest = frame.content_origin((0.0, 0.0), scrolled);
4381 KeepVisible {
4382 rect: keep.rect.translate(
4383 viewport.x + rest.0 + pad.left,
4384 viewport.y + rest.1 + pad.top,
4385 ),
4386 ..keep
4387 }
4388 });
4389 // Inside the extent this frame has just measured, unless something owns the
4390 // offset: content that shrank is drawn where it rests (milestone 533).
4391 let (offset_x, offset_y) = match self.runtime.scroll_offset_within(id, (max_x, max_y)) {
4392 Some(offset) => offset,
4393 // Never scrolled, and something inside wants to be seen: **open** there
4394 // rather than sliding across a frame later. A tab bar restored on its
4395 // eighth tab should show the eighth tab, not show the first and then
4396 // travel. The same answer a paged view gives its initial page, and the
4397 // runtime retains the offset on that first frame so it stays.
4398 None => match keep {
4399 Some(keep) => frame.keep_offset(keep).0,
4400 None => (0.0, 0.0),
4401 },
4402 };
4403
4404 let origin = frame.content_origin((offset_x, offset_y), scrolled);
4405 let content_translation = (
4406 viewport.x + origin.0 + pad.left,
4407 viewport.y + origin.1 + pad.top,
4408 );
4409 self.scrollables.push(Scrollable {
4410 id,
4411 viewport,
4412 max_x,
4413 max_y,
4414 axis,
4415 physics: region_physics(widget, &self.theme),
4416 overscroll: crate::ScrollConfiguration::of().overscroll_indicator(&self.theme),
4417 fling: crate::ScrollConfiguration::of()
4418 .velocity_tracker(&self.theme)
4419 .strategy(),
4420 refresh: self.refresh_host,
4421 page: None,
4422 reverse_x: reverse.0,
4423 reverse_y: reverse.1,
4424 host: self.scroll_host,
4425 keep_visible: keep,
4426 });
4427 let mut content_index = 0;
4428 // Where the content starts, so that a stretch can take all of it (milestone 591).
4429 let stretch_mark = (self.scene.primitives().len(), self.xform_base());
4430 let outer = self.scroll_host.replace(id);
4431 self.walk(
4432 content,
4433 child_id(id, 0, content),
4434 content_translation,
4435 content_clip,
4436 &content_rects,
4437 &mut content_index,
4438 );
4439 self.scroll_host = outer;
4440 self.add_overscroll_stretch(id, viewport, content_clip, stretch_mark);
4441
4442 // The overscroll glow, then the scrollbars, over the content (not
4443 // clipped by it).
4444 self.scene.set_clip(clip);
4445 self.add_overscroll_glow(id, viewport);
4446 if max_y > 0.0 {
4447 self.add_scrollbar(
4448 id,
4449 viewport,
4450 Bar {
4451 vertical: true,
4452 offset: offset_y,
4453 max: max_y,
4454 reverse: reverse.1,
4455 asked: widget.scrollbars(),
4456 visible: widget.thumb_visibility(),
4457 },
4458 );
4459 }
4460 if max_x > 0.0 {
4461 self.add_scrollbar(
4462 id,
4463 viewport,
4464 Bar {
4465 vertical: false,
4466 offset: offset_x,
4467 max: max_x,
4468 reverse: reverse.0,
4469 asked: widget.scrollbars(),
4470 visible: widget.thumb_visibility(),
4471 },
4472 );
4473 }
4474 } else if let Some(vlist) =
4475 widget.virtual_list(Size::new(draw_rect.width, draw_rect.height))
4476 {
4477 // A virtualised list: only build/lay out/paint the visible window.
4478 let viewport = draw_rect;
4479 let content_clip = clip.intersect(viewport);
4480 let reverse = widget.scroll_reverse();
4481 // Down the screen or across it. A list virtualises along **one** axis, which
4482 // is what lets it place item `n` without building the ones before it, so
4483 // `Axis::Both` has no meaning here and reads as vertical.
4484 let across = matches!(vlist.axis, crate::scroll::Axis::Horizontal);
4485 // Room around the items, inside the viewport and scrolling with them. The
4486 // **leading** inset is the one at the end the items start from, so a
4487 // reversed list clears the far end first and both keep their sides.
4488 let pad = widget.scroll_padding();
4489 let (lead, trail, cross_near, cross_far) = match (across, reverse) {
4490 (true, false) => (pad.left, pad.right, pad.top, pad.bottom),
4491 (true, true) => (pad.right, pad.left, pad.top, pad.bottom),
4492 (false, false) => (pad.top, pad.bottom, pad.left, pad.right),
4493 (false, true) => (pad.bottom, pad.top, pad.left, pad.right),
4494 };
4495 // From here down it is a main axis and a cross axis, and only the two
4496 // branches at the end have to know which is which. The alternative was a
4497 // second copy of the window arithmetic below, which is where a reversed
4498 // list gets its signs right -- and a fix applied to one copy and not the
4499 // other is exactly how the two would drift apart.
4500 let (extent, cross_extent) = match across {
4501 true => (viewport.width, viewport.height),
4502 false => (viewport.height, viewport.width),
4503 };
4504 let content = lead + trail + vlist.count as f32 * vlist.item_extent;
4505 let max = (content - extent).max(0.0);
4506 let bounds = if across { (max, 0.0) } else { (0.0, max) };
4507 let offset = self
4508 .runtime
4509 .scroll_offset_within(id, bounds)
4510 .map_or(0.0, |(x, y)| if across { x } else { y });
4511 self.scrollables.push(Scrollable {
4512 id,
4513 viewport,
4514 max_x: if across { max } else { 0.0 },
4515 max_y: if across { 0.0 } else { max },
4516 axis: if across {
4517 crate::scroll::Axis::Horizontal
4518 } else {
4519 crate::scroll::Axis::Vertical
4520 },
4521 physics: region_physics(widget, &self.theme),
4522 overscroll: crate::ScrollConfiguration::of().overscroll_indicator(&self.theme),
4523 fling: crate::ScrollConfiguration::of()
4524 .velocity_tracker(&self.theme)
4525 .strategy(),
4526 refresh: self.refresh_host,
4527 page: None,
4528 reverse_x: across && reverse,
4529 reverse_y: !across && reverse,
4530 host: self.scroll_host,
4531 keep_visible: None,
4532 });
4533
4534 // Where the content starts, so that a stretch can take all of it (milestone 591).
4535 let stretch_mark = (self.scene.primitives().len(), self.xform_base());
4536 let outer = self.scroll_host.replace(id);
4537 if vlist.item_extent > 0.0 && vlist.count > 0 {
4538 // The **window** is the same arithmetic either way, and that is not a
4539 // coincidence: a reversed list counts its indices from the end, and a
4540 // reversed offset counts its pixels from the end, so index and offset
4541 // agree about which way is forward. Only where an item lands differs.
4542 let first = ((offset - lead) / vlist.item_extent).floor().max(0.0) as usize;
4543 let last = ((((offset + extent - lead) / vlist.item_extent).ceil()).max(0.0)
4544 as usize)
4545 .min(vlist.count);
4546 let origin = if across { viewport.x } else { viewport.y };
4547 for i in first..last {
4548 let item = (vlist.build)(i);
4549 let along = if reverse {
4550 origin + extent - lead - (i + 1) as f32 * vlist.item_extent + offset
4551 } else {
4552 origin + lead + i as f32 * vlist.item_extent - offset
4553 };
4554 let (x, y) = match across {
4555 true => (along, viewport.y + cross_near),
4556 false => (viewport.x + cross_near, along),
4557 };
4558
4559 // **Filled**, not merely constrained: a list hands its children a
4560 // box rather than asking them how big they would like to be. The
4561 // reference gives a list's children a *tight* cross-axis extent, and
4562 // for a fixed-extent list a tight main-axis one too — which is
4563 // exactly the pair of numbers here.
4564 //
4565 // Constrained-but-not-filled, a row whose width nobody set hugged
4566 // its own text: a list of coloured rows painted a column of chips
4567 // down the left instead of rows across the list. Found on a device
4568 // in milestone 349.
4569 let free_cross = (cross_extent - cross_near - cross_far).max(0.0);
4570 let item_rects = self.cached_rects(
4571 id.child(i),
4572 item.as_ref(),
4573 Constraints::filled(match across {
4574 true => Size::new(vlist.item_extent, free_cross),
4575 false => Size::new(free_cross, vlist.item_extent),
4576 }),
4577 );
4578
4579 let item = self.keep(item);
4580 let mut item_index = 0;
4581 self.walk(
4582 item,
4583 id.child(i),
4584 (x, y),
4585 content_clip,
4586 &item_rects,
4587 &mut item_index,
4588 );
4589 }
4590 }
4591
4592 self.scroll_host = outer;
4593 self.add_overscroll_stretch(id, viewport, content_clip, stretch_mark);
4594 self.scene.set_clip(clip);
4595 self.add_overscroll_glow(id, viewport);
4596 if max > 0.0 {
4597 self.add_scrollbar(
4598 id,
4599 viewport,
4600 Bar {
4601 vertical: !across,
4602 offset,
4603 max,
4604 reverse,
4605 asked: widget.scrollbars(),
4606 visible: widget.thumb_visibility(),
4607 },
4608 );
4609 }
4610 } else if let Some(pages) = widget.page_view() {
4611 // A paged view: like a virtualised list turned on its side, and with the
4612 // page extent — the whole geometry — derived from the viewport rather than
4613 // given. Only the pages the viewport touches are built.
4614 let viewport = draw_rect;
4615 let content_clip = clip.intersect(viewport);
4616 let snap = pages.snap(viewport);
4617 let (viewport_along, page_across) = if snap.horizontal {
4618 (viewport.width, viewport.height)
4619 } else {
4620 (viewport.height, viewport.width)
4621 };
4622 let reverse = widget.scroll_reverse();
4623 // Room at both ends, so a page narrower than the viewport comes to rest
4624 // **centred** in it rather than jammed against the leading edge — and so
4625 // the last one can be reached at all: unpadded, the travel stops with the
4626 // last page's trailing edge on the viewport's, which is short of where that
4627 // page rests. Padded, the total works out to `extent × (count - 1)`,
4628 // the last page's own offset, exactly.
4629 let pad = pages.end_padding(viewport);
4630 let total = pages.count as f32 * snap.extent + 2.0 * pad;
4631 let max = (total - viewport_along).max(0.0);
4632 // With no retained offset this is the view's **first** frame, and it opens
4633 // on the page it was asked for. Reading the initial page here rather than
4634 // correcting it a frame later is what keeps page 0 from flashing past on
4635 // the way to page 3.
4636 let bounds = if snap.horizontal {
4637 (max, 0.0)
4638 } else {
4639 (0.0, max)
4640 };
4641 let along = match self.runtime.scroll_offset_within(id, bounds) {
4642 Some((x, y)) => {
4643 if snap.horizontal {
4644 x
4645 } else {
4646 y
4647 }
4648 }
4649 None => snap
4650 .offset_of(snap.requested.min(pages.count.saturating_sub(1)))
4651 .clamp(0.0, max),
4652 };
4653 self.scrollables.push(Scrollable {
4654 id,
4655 viewport,
4656 max_x: if snap.horizontal { max } else { 0.0 },
4657 max_y: if snap.horizontal { 0.0 } else { max },
4658 axis: if snap.horizontal {
4659 crate::scroll::Axis::Horizontal
4660 } else {
4661 crate::scroll::Axis::Vertical
4662 },
4663 physics: region_physics(widget, &self.theme),
4664 overscroll: crate::ScrollConfiguration::of().overscroll_indicator(&self.theme),
4665 fling: crate::ScrollConfiguration::of()
4666 .velocity_tracker(&self.theme)
4667 .strategy(),
4668 refresh: self.refresh_host,
4669 page: Some(snap),
4670 reverse_x: snap.horizontal && reverse,
4671 reverse_y: !snap.horizontal && reverse,
4672 host: self.scroll_host,
4673 keep_visible: None,
4674 });
4675
4676 // Where the content starts, so that a stretch can take all of it (milestone 591).
4677 let stretch_mark = (self.scene.primitives().len(), self.xform_base());
4678 let outer = self.scroll_host.replace(id);
4679 if pages.count > 0 {
4680 // The window is the same arithmetic whichever end index 0 is at: a
4681 // reversed view counts its indices from the far end and a reversed
4682 // offset counts its pixels from the same one, so the two agree about
4683 // which way forward is. Only where a page **lands** differs.
4684 let first = ((along - pad) / snap.extent).floor().max(0.0) as usize;
4685 let last = ((((along + viewport_along - pad) / snap.extent).ceil()).max(0.0)
4686 as usize)
4687 .min(pages.count)
4688 .max(first + 1);
4689 // A wheel shows **more** rows than a flat strip would: the ones a quarter
4690 // turn away are compressed into the last few pixels at either end, and
4691 // their flat positions are a whole quarter-circumference outside the
4692 // viewport. Widening the window in both directions keeps the reversed
4693 // arithmetic above untouched, and the rows that turn out to have gone
4694 // over the horizon are dropped below — before they are built.
4695 let (first, last) = match pages.wheel {
4696 Some(wheel) => {
4697 let span = wheel.radius(viewport_along) * std::f32::consts::FRAC_PI_2;
4698 let extra = (span / snap.extent).ceil().max(0.0) as usize + 1;
4699 (first.saturating_sub(extra), (last + extra).min(pages.count))
4700 }
4701 None => (first, last),
4702 };
4703 for index in first..last.min(pages.count) {
4704 let start = match reverse {
4705 true => viewport_along - pad - (index + 1) as f32 * snap.extent + along,
4706 false => pad + index as f32 * snap.extent - along,
4707 };
4708 // Where this row's centre would sit on the unrolled strip, measured
4709 // from the middle of the viewport — which is the whole of what the
4710 // cylinder needs to know about it.
4711 let on_wheel = match pages.wheel {
4712 Some(wheel) => {
4713 let flat = start + snap.extent / 2.0 - viewport_along / 2.0;
4714 match wheel.row(viewport_along, flat) {
4715 // Past the horizon: not drawn, and not built either.
4716 None => continue,
4717 Some(row) => Some((row, flat)),
4718 }
4719 }
4720 None => None,
4721 };
4722 let page = (pages.build)(index);
4723 let (size, origin) = if snap.horizontal {
4724 (
4725 Size::new(snap.extent, page_across),
4726 (viewport.x + start, viewport.y),
4727 )
4728 } else {
4729 (
4730 Size::new(page_across, snap.extent),
4731 (viewport.x, viewport.y + start),
4732 )
4733 };
4734
4735 // A page is **given** its box, not asked for one: it fills the
4736 // panel even when its content is a single centred line.
4737 let page_rects = self.cached_rects(
4738 id.child(index),
4739 page.as_ref(),
4740 Constraints::filled(size),
4741 );
4742
4743 let mut page_index = 0;
4744 // The row is drawn **flat**, then the whole of it is composited on
4745 // the cylinder — one layer per row, the way `Transform` does it, so
4746 // the text, the rules and the backgrounds all turn together instead
4747 // of each primitive having to know it is on a wheel.
4748 let before = self.scene.primitives().len();
4749 let base = self.xform_base();
4750 let page = self.keep(page);
4751 self.walk(
4752 page,
4753 id.child(index),
4754 origin,
4755 content_clip,
4756 &page_rects,
4757 &mut page_index,
4758 );
4759 if let Some((row, flat)) = on_wheel {
4760 // The row's own centre on screen: the scale is about it, so a row
4761 // shrinks in place rather than creeping towards a corner.
4762 let centre = Point::new(
4763 viewport.x + viewport.width / 2.0,
4764 viewport.y + viewport_along / 2.0 + flat,
4765 );
4766 let matrix = Affine::scale(row.scale_x, row.scale_y)
4767 .about(centre)
4768 // And then up or down to where the cylinder actually put it.
4769 .then(Affine::translation(0.0, row.offset - flat));
4770 let group = self.scene.split_off(before);
4771 self.scene.push_primitive(Primitive::Layer {
4772 primitives: group,
4773 opacity: row.opacity.clamp(0.0, 1.0),
4774 clip: content_clip,
4775 clip_shape: ClipShape::Rect,
4776 transform: Some(LayerTransform::new(matrix)),
4777 filter: LayerFilter::NONE,
4778 owner: id.child(index).as_u64(),
4779 });
4780 self.transform_interaction_registries(&base, matrix);
4781 }
4782 }
4783 }
4784
4785 self.scroll_host = outer;
4786 self.add_overscroll_stretch(id, viewport, content_clip, stretch_mark);
4787 self.scene.set_clip(clip);
4788 self.add_overscroll_glow(id, viewport);
4789 } else if let Some(overflow) = widget.overflow_box() {
4790 // The child is laid out to constraints of its own — which is why it can
4791 // come out bigger than the box holding it — then anchored inside it and
4792 // rendered **without** the box's clip. A spill that got clipped here would
4793 // be no spill at all; a `ClipRect` above is how a caller asks for one.
4794 let own = draw_rect;
4795 if let Some(child) = widget.children().first() {
4796 let child = child.as_ref();
4797 let cid = child_id(id, 0, child);
4798 let asked = overflow.child_size(Size::new(own.width, own.height));
4799 let child_rects = if overflow.unconstrained {
4800 // Unconstrained: the child is asked how big it wants to be, and
4801 // gets exactly that.
4802 self.cached_rects(cid, child, Constraints::scroll(0.0, 0.0, true, true))
4803 } else if overflow.natural_height {
4804 // The box's width, and the height the child asks for at it.
4805 self.cached_rects(
4806 cid,
4807 child,
4808 Constraints::scroll(asked.width, 0.0, false, true),
4809 )
4810 } else {
4811 self.cached_rects(cid, child, Constraints::filled(asked))
4812 };
4813 let size = child_rects
4814 .first()
4815 .map(|r| Size::new(r.width, r.height))
4816 .unwrap_or(asked);
4817 let origin = overflow.origin(own, size);
4818
4819 let mut child_index = 0;
4820 self.walk(child, cid, origin, clip, &child_rects, &mut child_index);
4821 }
4822 } else if let Some(transform) = widget.constraints_transform() {
4823 // The child is laid out at **the same box the measurement gave it**, worked out
4824 // again from what is left of that measurement — the box it produced. Each of
4825 // the three things an axis can say survives the round trip; see
4826 // `AxisConstraint::at`.
4827 let own = draw_rect;
4828 if let Some(child) = widget.children().first() {
4829 let child = child.as_ref();
4830 let cid = child_id(id, 0, child);
4831 // A box a multiple of its child below one is smaller than the child: on a
4832 // loose axis, the child is allowed what it had, the box divided back by the
4833 // factor, and at zero there is nothing to divide, so it is asked. At one or
4834 // more the box already holds it (milestone 598).
4835 let factor = widget.size_factor().unwrap_or((1.0, 1.0));
4836 let back = |rule, own: f32, factor: f32| match rule {
4837 crate::constraints::AxisConstraint::Loose if factor <= 0.0 => {
4838 crate::constraints::AxisConstraint::Unbounded.at(own)
4839 }
4840 crate::constraints::AxisConstraint::Loose if factor < 1.0 => {
4841 rule.at(own / factor)
4842 }
4843 _ => rule.at(own),
4844 };
4845 let (aw, free_x, fill_x) = back(transform.width, own.width, factor.0);
4846 let (ah, free_y, fill_y) = back(transform.height, own.height, factor.1);
4847 // A box on its way to its child's size is not that size yet, and the child is
4848 // laid out as ever (milestone 594). On the axes the child decides, it comes
4849 // back at its own size, which is where the box is going; an axis it is given
4850 // as it came is not animated at all, the box filling the room there.
4851 let animated = widget.animated_size();
4852 let constraints = Constraints::axes(aw, ah, [free_x, free_y], [fill_x, fill_y]);
4853 let child_rects = self.cached_rects(cid, child, constraints);
4854 let size = child_rects
4855 .first()
4856 .map(|r| Size::new(r.width, r.height))
4857 .unwrap_or(Size::new(0.0, 0.0));
4858 // An anchor that may be directional is resolved here, where the reading
4859 // direction is known (milestone 597).
4860 // An anchor on its way to another is where the runtime has it (milestone 600).
4861 let geometry = widget.alignment_geometry().map(|geometry| {
4862 match self.runtime.anim_offset(id) {
4863 Some((x, y)) => geometry.with_fractions(x, y),
4864 None => geometry,
4865 }
4866 });
4867 let align = match geometry {
4868 Some(geometry) => geometry.resolve(if self.rtl() {
4869 frus_core::TextDirection::Rtl
4870 } else {
4871 frus_core::TextDirection::Ltr
4872 }),
4873 None => transform.alignment,
4874 };
4875 let origin = (
4876 own.x + (own.width - size.width) * align.fraction_x(),
4877 own.y + (own.height - size.height) * align.fraction_y(),
4878 );
4879 if transform.report {
4880 self.report_spill(own, Rect::new(origin.0, origin.1, size.width, size.height));
4881 }
4882 let clip = match &animated {
4883 Some(spec) if spec.clip => clip.intersect(own),
4884 // A reveal is the child cut to it (milestone 596).
4885 _ if widget.clips_to_box() => clip.intersect(own),
4886 _ => clip,
4887 };
4888 let mut child_index = 0;
4889 self.walk(child, cid, origin, clip, &child_rects, &mut child_index);
4890 }
4891 } else if let Some(build) = widget.layout_builder() {
4892 // Builds the content from the actual box, then lays it out and renders it inside
4893 // (like a list item: with no retained state).
4894 let bounds = draw_rect;
4895 let content_clip = clip.intersect(bounds);
4896 let child = build(Size::new(bounds.width, bounds.height));
4897
4898 // **Filled**, not merely constrained: the content is handed this box, and it
4899 // was built from this box in the first place. Constraining it instead let a
4900 // root with no width of its own hug its content — a grid built here laid its
4901 // columns out at nothing, which is what `GridView::extent`'s first tests found
4902 // (milestone 356). The same distinction a list's items and a paged view's
4903 // pages already draw.
4904 let child_rects = self.cached_rects(
4905 id.child(0),
4906 child.as_ref(),
4907 Constraints::filled(Size::new(bounds.width, bounds.height)),
4908 );
4909
4910 let child = self.keep(child);
4911 let mut child_index = 0;
4912 self.walk(
4913 child,
4914 id.child(0),
4915 (bounds.x, bounds.y),
4916 content_clip,
4917 &child_rects,
4918 &mut child_index,
4919 );
4920 } else if let Some(build) = widget.scroll_overlay() {
4921 // The **body first**, exactly as an ordinary single child: it keeps its own
4922 // identity, registers itself as a scroll region in its own right, and consumes
4923 // its rects from this array the way the generic walk would. Nothing about it
4924 // changes for being watched.
4925 let children = widget.children();
4926 for (child_index, child) in children.iter().enumerate() {
4927 self.walk(
4928 child.as_ref(),
4929 child_id(id, child_index, child.as_ref()),
4930 translation,
4931 clip,
4932 rects,
4933 index,
4934 );
4935 }
4936 // Then the overlay, built from **where the body has got to this frame**. Read
4937 // from the retained offset rather than from the registry the walk is still
4938 // filling: the offset is written before the frame is drawn, so it is current,
4939 // where the extents beside it are not yet known — which is why the builder is
4940 // handed the one and not the other.
4941 let offset = children
4942 .first()
4943 .map(|body| child_id(id, 0, body.as_ref()))
4944 .and_then(|body| self.runtime.scroll.get(&body).copied())
4945 .unwrap_or((0.0, 0.0));
4946 let bounds = draw_rect;
4947 let over = build(offset, Size::new(bounds.width, bounds.height));
4948 // `child(1)`, beside the body's `child(0)` — or beside its key, which cannot
4949 // collide with a positional identity. The overlay is laid out in a tree of its
4950 // own, so it needs an identity of its own for hover, ink and the paint cache.
4951 let over_id = id.child(1);
4952 let over_rects = self.cached_rects(
4953 over_id,
4954 over.as_ref(),
4955 // **Filled**, not constrained: an overlay covers the region it is over, and
4956 // where inside that box its content sits is the caller's business — a
4957 // column pins it to the top, an `Align` puts it anywhere else. The same
4958 // rule a `layout_builder`'s content is given.
4959 Constraints::filled(Size::new(bounds.width, bounds.height)),
4960 );
4961 let over = self.keep(over);
4962 let mut over_index = 0;
4963 self.walk(
4964 over,
4965 over_id,
4966 (bounds.x, bounds.y),
4967 clip.intersect(bounds),
4968 &over_rects,
4969 &mut over_index,
4970 );
4971 } else if let Some(spec) = widget.dismissible() {
4972 // A dismissible item is a stack whose **last** layer — the item itself — is
4973 // offset by however far it has been swiped, and whose earlier layers, the
4974 // backgrounds, show only through the strip the item has uncovered. Clipping
4975 // them is what makes a background read as something the item is sliding
4976 // *off*, rather than a block that was always there.
4977 let bounds = draw_rect;
4978 let state = self.runtime.dismiss.get(&id).copied();
4979 let progress = state.map(|s| s.progress()).unwrap_or(0.0);
4980 let layers = widget.children();
4981 let last = layers.len().saturating_sub(1);
4982 // Which background: the first covers a swipe towards the end, the second —
4983 // when there is one — the other way. With only one, it serves both.
4984 let shown_background = if progress < 0.0 && last >= 2 { 1 } else { 0 };
4985 let strip = crate::dismiss::revealed_strip(bounds, progress);
4986
4987 for (i, layer) in layers.iter().enumerate() {
4988 let is_item = i == last;
4989 if !is_item && (i != shown_background || progress == 0.0) {
4990 // Not the background this direction shows: skip it, and skip the
4991 // rects it would have consumed — it is laid out separately, so
4992 // there is no index to keep in step.
4993 continue;
4994 }
4995 let offset = if is_item {
4996 if spec.axis.is_horizontal() {
4997 (bounds.width * progress, 0.0)
4998 } else {
4999 (0.0, bounds.height * progress)
5000 }
5001 } else {
5002 (0.0, 0.0)
5003 };
5004 let layer_clip = if is_item {
5005 clip.intersect(bounds)
5006 } else {
5007 clip.intersect(strip)
5008 };
5009 if layer_clip.width <= 0.0 || layer_clip.height <= 0.0 {
5010 continue;
5011 }
5012 let cid = child_id(id, i, layer.as_ref());
5013 let layer_rects = self.cached_rects(
5014 cid,
5015 layer.as_ref(),
5016 Constraints::filled(Size::new(bounds.width, bounds.height)),
5017 );
5018 let mut layer_index = 0;
5019 self.walk(
5020 layer.as_ref(),
5021 cid,
5022 (bounds.x + offset.0, bounds.y + offset.1),
5023 layer_clip,
5024 &layer_rects,
5025 &mut layer_index,
5026 );
5027 }
5028
5029 self.dismissables.push(Dismissable {
5030 id,
5031 rect: bounds,
5032 spec,
5033 });
5034 // A swipe that is settling, flying or collapsing drives itself.
5035 if state.is_some_and(|s| s.phase() != DismissPhase::Drag) {
5036 self.wants_animation = true;
5037 }
5038 } else if let Some(custom) = widget.custom_layout() {
5039 // Children placed by a function (milestone 601): it is handed this box, measures
5040 // each child in a layout of its own under the constraints it chooses, and says
5041 // where it goes. The function runs here, where the box is known, and nowhere
5042 // else, which is why the box's size cannot depend on its children.
5043 let own = draw_rect;
5044 let children = widget.children();
5045 let measure = |i: usize, c: crate::ChildConstraints| -> Vec<Rect> {
5046 let child = children[i].as_ref();
5047 self.cached_rects(child_id(id, i, child), child, custom_constraints(c))
5048 };
5049 let mut layout = crate::ChildLayout::new(custom.keys, &measure);
5050 (custom.delegate)(Size::new(own.width, own.height), &mut layout);
5051 let (laid, at) = (layout.laid, layout.at);
5052 for (i, child) in children.iter().enumerate() {
5053 let Some(child_rects) = &laid[i] else {
5054 continue;
5055 };
5056 let mut child_index = 0;
5057 self.walk(
5058 child.as_ref(),
5059 child_id(id, i, child.as_ref()),
5060 (own.x + at[i].x, own.y + at[i].y),
5061 clip,
5062 child_rects,
5063 &mut child_index,
5064 );
5065 }
5066 } else if widget.stack() {
5067 // A stack: the layers are rendered in order, bottom first.
5068 let bounds = draw_rect;
5069 // Cut at the stack's edges unless it says otherwise (`stack.dart:718`).
5070 let layer_clip = if widget.stack_clips() {
5071 clip.intersect(bounds)
5072 } else {
5073 clip
5074 };
5075 // Drawn past its edges or not, a stack is only touched inside them: the
5076 // reference asks a box whether a point is in it before its children.
5077 let outer_touch = self.touch_clip;
5078 if !widget.stack_clips() {
5079 self.touch_clip = Some(outer_touch.map_or(bounds, |t| t.intersect(bounds)));
5080 }
5081 let fit = widget.stack_fit();
5082 // The stack's own reading direction, or the theme's.
5083 let rtl = widget
5084 .stack_direction()
5085 .map_or(self.rtl(), |d| d == frus_core::TextDirection::Rtl);
5086 // An **indexed** stack shows one layer and lays out the rest. Which is a
5087 // question for here rather than for the widget: a layer that wrapped itself in
5088 // something to keep quiet would no longer be laid out the way a bare layer is,
5089 // and the layout is the whole promise.
5090 let shown = widget.stack_visible();
5091 // Where a layer smaller than the stack sits. Resolved once, against the
5092 // reading direction, so a start-anchored badge follows the script.
5093 let align = widget
5094 .alignment_geometry()
5095 .unwrap_or(frus_core::AlignmentGeometry::Physical(
5096 frus_core::Alignment::TOP_LEFT,
5097 ))
5098 .resolve(if rtl {
5099 frus_core::TextDirection::Rtl
5100 } else {
5101 frus_core::TextDirection::Ltr
5102 });
5103 for (i, layer) in widget.children().iter().enumerate() {
5104 let cid = child_id(id, i, layer.as_ref());
5105 // What this layer asks for on each axis: a pinned pair gives a number, a
5106 // lone pin plus an explicit extent gives one, and neither leaves the axis
5107 // to the layer itself — or, under `Expand`, to the stack.
5108 // A layer moving between two sets of pins is read from the runtime rather
5109 // than from the widget: the widget carries where it is **going**, and a
5110 // layer that jumped there would be the whole bug this animates away.
5111 // Both the size and the place come from the one value, so a box cannot be
5112 // measured against one frame's pins and placed against another's.
5113 let pins = match layer.positioned() {
5114 Some(spec) if layer.anim_pins().is_some() => {
5115 Some(self.runtime.anim_pins(cid).unwrap_or(spec))
5116 }
5117 other => other,
5118 };
5119 // A start or an end pin is a left or a right once the direction is known
5120 // (milestone 589). The stack's layers are placed on the screen as they are,
5121 // not mirrored, so this is the one place it is decided.
5122 let pins = pins.map(|p| p.for_direction(rtl));
5123 let (want_w, want_h) = match pins {
5124 Some(p) => (
5125 p.resolved_width(bounds.width),
5126 p.resolved_height(bounds.height),
5127 ),
5128 None => (Some(bounds.width), Some(bounds.height)),
5129 };
5130 // A pinned layer is **forced** into what its edges say: two opposite
5131 // pins are not a suggestion, and a width of its own is a contradiction
5132 // rather than a second opinion. An unpinned layer under `Expand` is
5133 // merely handed the box, which leaves a layer that chose a size alone —
5134 // that is what a badge sitting in a filled stack has always relied on.
5135 // An axis nobody pinned is left free, so the layer's own size comes back.
5136 let layer_rects = if pins.is_some() {
5137 self.cached_rects(
5138 cid,
5139 layer.as_ref(),
5140 Constraints::pinned(want_w, want_h, Size::new(bounds.width, bounds.height)),
5141 )
5142 } else {
5143 let room = Size::new(
5144 want_w.unwrap_or(bounds.width),
5145 want_h.unwrap_or(bounds.height),
5146 );
5147 // The stack's fit (`stack.dart:634`): allowed up to the room, forced
5148 // into it, or handed it.
5149 let c = match fit {
5150 // A layer that asks for the room takes it here unasked: laid out on
5151 // its own, its fill request is the root's.
5152 crate::StackFit::Loose => Constraints::axes(
5153 room.width,
5154 room.height,
5155 [false, false],
5156 [false, false],
5157 ),
5158 crate::StackFit::Expand => {
5159 Constraints::pinned(Some(room.width), Some(room.height), room)
5160 }
5161 crate::StackFit::Passthrough => Constraints::filled(room),
5162 };
5163 self.cached_rects(cid, layer.as_ref(), c)
5164 };
5165 let own = layer_rects
5166 .first()
5167 .copied()
5168 .unwrap_or(Rect::new(0.0, 0.0, 0.0, 0.0));
5169 let (dx, dy) = match pins {
5170 Some(p) => (
5171 Positioning::place(
5172 p.left,
5173 p.right,
5174 bounds.width,
5175 own.width,
5176 align.fraction_x(),
5177 ),
5178 Positioning::place(
5179 p.top,
5180 p.bottom,
5181 bounds.height,
5182 own.height,
5183 align.fraction_y(),
5184 ),
5185 ),
5186 None => (
5187 (bounds.width - own.width).max(0.0) * align.fraction_x(),
5188 (bounds.height - own.height).max(0.0) * align.fraction_y(),
5189 ),
5190 };
5191 let mut layer_index = 0;
5192 // A layer that is not the shown one is walked in full — so it is measured,
5193 // and so the runtime keeps its scroll offset, its caret and its focus — and
5194 // then everything it added is dropped again. The same withdrawal a
5195 // `Visibility` that maintains its size performs, applied from outside.
5196 let hidden = shown.is_some_and(|which| which != i);
5197 let base = hidden.then(|| self.barrier_base());
5198 self.walk(
5199 layer.as_ref(),
5200 cid,
5201 (bounds.x + dx, bounds.y + dy),
5202 layer_clip,
5203 &layer_rects,
5204 &mut layer_index,
5205 );
5206 if let Some(base) = base {
5207 self.apply_barrier(HIDDEN_LAYER, &base, cid, Rect::new(0.0, 0.0, 0.0, 0.0));
5208 }
5209 }
5210 self.touch_clip = outer_touch;
5211 } else if let Some((content, placement)) = widget.overlay() {
5212 // The anchor (child 0) is rendered inline; the overlay (child 1) is deferred.
5213 self.walk(
5214 widget.children()[0].as_ref(),
5215 child_id(id, 0, widget.children()[0].as_ref()),
5216 translation,
5217 clip,
5218 rects,
5219 index,
5220 );
5221 // The appearance progress: for an animated overlay (a drawer), the value the
5222 // runtime interpolated; otherwise `1.0` (shown at once). With no value recorded
5223 // (an isolated render), the target is adopted immediately.
5224 let target = widget.anim_target().unwrap_or(1.0);
5225 let progress = self.runtime.value_or(id, target);
5226 // A tooltip only shows while the anchor is hovered; an animated overlay disappears
5227 // once its progress has fallen back to zero.
5228 let visible = match placement {
5229 Placement::Tooltip => self.runtime.input.hovered == Some(id.child(0)),
5230 _ => true,
5231 };
5232 if visible && progress > 0.001 {
5233 self.overlays.push((
5234 content,
5235 child_id(id, 1, content),
5236 draw_rect,
5237 placement,
5238 widget.overlay_dismiss(),
5239 progress,
5240 widget.overlay_traps_focus(),
5241 widget.overlay_scrim(&self.theme),
5242 self.theme.clone(),
5243 ));
5244 }
5245 } else {
5246 let children = widget.children();
5247 // Fractional alignment (`Container::alignment`) + paint offset
5248 // (`Transform::translate`): both offset the subtree. `(0, 0)` otherwise → the
5249 // ordinary flex walk.
5250 let extra = self.child_offset(widget, id, rect, rects, *index, children);
5251 if widget.sticky_header() && children.len() == 2 {
5252 self.walk_sticky(
5253 widget,
5254 id,
5255 draw_rect,
5256 (translation.0 + extra.0, translation.1 + extra.1),
5257 clip,
5258 rects,
5259 index,
5260 );
5261 self.depth -= 1;
5262 return;
5263 }
5264 for (child_index, child) in children.iter().enumerate() {
5265 self.walk(
5266 child.as_ref(),
5267 child_id(id, child_index, child.as_ref()),
5268 (translation.0 + extra.0, translation.1 + extra.1),
5269 clip,
5270 rects,
5271 index,
5272 );
5273 }
5274 }
5275 self.depth -= 1;
5276 }
5277
5278 /// A section with a sticky header (milestone 602). The header is moved down to the top of
5279 /// what is visible — the clip — but never above the section's top nor so far that it
5280 /// leaves the section's bottom, which is how the next section's header pushes it off.
5281 ///
5282 /// It is drawn **over** the section, which goes under it, so what the header adds is
5283 /// moved after what the section adds: its primitives, and the registries a pointer is
5284 /// matched against last-first. Focus and semantics keep the reading order, header first.
5285 #[allow(clippy::too_many_arguments)]
5286 fn walk_sticky(
5287 &mut self,
5288 widget: &'a dyn Widget<Msg>,
5289 id: WidgetId,
5290 section: Rect,
5291 translation: (f32, f32),
5292 clip: Rect,
5293 rects: &[Rect],
5294 index: &mut usize,
5295 ) {
5296 let children = widget.children();
5297 let header = rects
5298 .get(*index)
5299 .copied()
5300 .unwrap_or(Rect::new(0.0, 0.0, 0.0, 0.0))
5301 .translate(translation.0, translation.1);
5302 let room = (section.y + section.height - (header.y + header.height)).max(0.0);
5303 let down = (clip.y - header.y).clamp(0.0, room);
5304 let start = self.barrier_base();
5305 self.walk(
5306 children[0].as_ref(),
5307 child_id(id, 0, children[0].as_ref()),
5308 (translation.0, translation.1 + down),
5309 clip,
5310 rects,
5311 index,
5312 );
5313 let mid = self.barrier_base();
5314 self.walk(
5315 children[1].as_ref(),
5316 child_id(id, 1, children[1].as_ref()),
5317 translation,
5318 clip,
5319 rects,
5320 index,
5321 );
5322 let mut primitives = self.scene.split_off(start.scene);
5323 after(&mut primitives, 0, mid.scene - start.scene);
5324 for primitive in primitives {
5325 self.scene.push_primitive(primitive);
5326 }
5327 after(&mut self.hits, start.hits, mid.hits);
5328 after(&mut self.long_presses, start.long_presses, mid.long_presses);
5329 after(&mut self.scrollables, start.scrollables, mid.scrollables);
5330 after(&mut self.draggables, start.draggables, mid.draggables);
5331 after(&mut self.drag_sources, start.drag_sources, mid.drag_sources);
5332 after(&mut self.drop_zones, start.drop_zones, mid.drop_zones);
5333 after(&mut self.inks, start.inks, mid.inks);
5334 after(&mut self.pans, start.pans, mid.pans);
5335 after(
5336 &mut self.pointer_listeners,
5337 start.pointer_listeners,
5338 mid.pointer_listeners,
5339 );
5340 after(
5341 &mut self.hover_regions,
5342 start.hover_regions,
5343 mid.hover_regions,
5344 );
5345 after(&mut self.interactives, start.interactives, mid.interactives);
5346 }
5347
5348 /// Offset to apply to a child's subtree: the sum of the **fractional alignment**
5349 /// (`Widget::alignment`, a single child slid through the free space) and the **paint
5350 /// offset** (`Transform::translate`, the whole subtree offset without touching layout).
5351 /// `(0, 0)` by default. Since it is added to the walk's translation, this offset follows
5352 /// both the primitives **and** the hit-test.
5353 fn child_offset(
5354 &self,
5355 widget: &dyn Widget<Msg>,
5356 id: WidgetId,
5357 container: Rect,
5358 rects: &[Rect],
5359 child_index: usize,
5360 children: &[Box<dyn Widget<Msg>>],
5361 ) -> (f32, f32) {
5362 let mut off = (0.0, 0.0);
5363
5364 // Fractional alignment: it targets a single child. taffy laid the child out at the
5365 // top left (Start/Start) at its natural size; it is then slid by `free × fraction`.
5366 // A **stack** answers this question too, and means something else by it: where a
5367 // layer smaller than the box sits, which the stack branch applies per layer. It
5368 // must not also be applied to the stack itself, or a stack with exactly one layer
5369 // would shift twice.
5370 if let (Some(geo), 1, false) = (widget.alignment_geometry(), children.len(), widget.stack())
5371 {
5372 // An **animated** anchor moves through the runtime's pair rather than the
5373 // widget's own numbers, in the anchor's own coordinates — so the reading
5374 // direction is applied to the interpolated anchor below, and not to the two
5375 // it came from.
5376 let geo = match self.runtime.anim_offset(id) {
5377 Some((x, y)) => geo.with_fractions(x, y),
5378 None => geo,
5379 };
5380 // Resolves the alignment (physical or directional) against the reading direction;
5381 // `resolve` produces a physical `Alignment` that the rest (with its RTL correction)
5382 // handles uniformly.
5383 let direction = if self.rtl() {
5384 frus_core::TextDirection::Rtl
5385 } else {
5386 frus_core::TextDirection::Ltr
5387 };
5388 let align = geo.resolve(direction);
5389 let child = rects[child_index];
5390 let pad = effective_style(widget, id, self.runtime, &self.theme).padding;
5391 let free_w = (container.width - pad.left - pad.right - child.width).max(0.0);
5392 let free_h = (container.height - pad.top - pad.bottom - child.height).max(0.0);
5393 // In RTL, taffy lays the child out on the left and `mirror` has sent it back to
5394 // the right: the baseline is therefore already right-aligned. 1 is subtracted so
5395 // the fraction stays **physical** (x = +1 ⇒ the right in both directions).
5396 let fx = align.fraction_x() - if self.rtl() { 1.0 } else { 0.0 };
5397 off.0 += free_w * fx;
5398 off.1 += free_h * align.fraction_y();
5399 }
5400
5401 // Paint offset (`Transform::translate`): in RTL the world's x axis is mirrored, so a
5402 // logical +x offset ("towards the end") points left — the sign is inverted to stay
5403 // consistent with the reading direction.
5404 if let Some((tx, ty)) = widget.transform_translate() {
5405 off.0 += if self.rtl() { -tx } else { tx };
5406 off.1 += ty;
5407 }
5408
5409 // The same offset, given as a **fraction of the child's own box**
5410 // (`FractionalTranslation`). The child's rectangle is the one thing this function
5411 // has that the widget did not: a widget cannot multiply by a width it was never
5412 // told.
5413 if let Some((fx, fy)) = widget.translate_fraction() {
5414 // The same tween, on the other offset rule: a slide that animates reads the
5415 // runtime's pair, and one that does not reads its own.
5416 let (fx, fy) = self.runtime.anim_offset(id).unwrap_or((fx, fy));
5417 let child = rects.get(child_index).copied().unwrap_or(container);
5418 let tx = child.width * fx;
5419 off.0 += if self.rtl() { -tx } else { tx };
5420 off.1 += child.height * fy;
5421 }
5422
5423 off
5424 }
5425
5426 /// Records the widget in the inspector's collection (when it is on) and opens a depth
5427 /// level — every render path closes it again at the end of the function
5428 /// (`self.depth -= 1`).
5429 fn inspect_enter(&mut self, widget: &dyn Widget<Msg>, id: WidgetId, draw_rect: Rect) {
5430 if let Some(nodes) = &mut self.inspector {
5431 nodes.push(crate::inspector::InspectorNode {
5432 id,
5433 rect: draw_rect,
5434 name: widget.debug_name(),
5435 depth: self.depth,
5436 });
5437 }
5438 self.depth += 1;
5439 }
5440
5441 /// A widget's full status: pointer interaction + focus + animation progresses + the
5442 /// cursor/selection when there is one.
5443 fn full_status(&self, widget: &dyn Widget<Msg>, id: WidgetId) -> crate::interaction::Status {
5444 let mut status = self.runtime.input.status_for(id);
5445 status.hover_progress = self.runtime.hover_progress(id);
5446 status.focus_progress = self.runtime.focus_progress(id);
5447 // A press is a progression now, and where the runtime has never heard of this
5448 // widget the flag is adopted whole — the rule `value` follows just below. Without
5449 // it a frame built outside the loop would draw a held widget as untouched.
5450 status.press_progress = self.runtime.press_progress_or(
5451 id,
5452 if status.interaction == crate::interaction::Interaction::Pressed {
5453 1.0
5454 } else {
5455 0.0
5456 },
5457 );
5458 status.opacity = self.runtime.opacity(id);
5459 // A widget's own animated value, or **its target** where the runtime has never
5460 // heard of it: the same rule the runtime applies on mount (adopt, do not animate
5461 // in from zero). Without the fallback an isolated render — a test, a frame built
5462 // before the loop has advanced anything — draws every such widget at zero: a
5463 // switch that is on drawn off, an indicator under the wrong tab.
5464 status.value = match widget.anim_target() {
5465 Some(target) => self.runtime.value_or(id, target),
5466 None => self.runtime.value(id),
5467 };
5468 status.value_placed = self.runtime.value_placed(id);
5469 status.anim_color = self.runtime.anim_color(id);
5470 status.anim_radius = self.runtime.anim_radius(id);
5471 status.time = self.runtime.time;
5472 status.drag_over = self.runtime.drag_over == Some(id);
5473 status.scroll_y = self.runtime.scroll.get(&id).map(|s| s.1).unwrap_or(0.0);
5474 // What a selection area has selected in this text, focused or not.
5475 status.region = self
5476 .runtime
5477 .region
5478 .as_ref()
5479 .and_then(|selection| selection.ranges.get(&id).copied());
5480 status.region_bar = status.region.is_some()
5481 && self
5482 .runtime
5483 .region
5484 .as_ref()
5485 .is_some_and(|selection| selection.bar);
5486 if let Some(selection) = self.runtime.region.as_ref().filter(|s| s.handles) {
5487 let here =
5488 |point: Option<crate::RegionPoint>| point.filter(|p| p.text == id).map(|p| p.index);
5489 status.region_grips = (here(selection.start), here(selection.end));
5490 }
5491 if status.focused {
5492 if let Some(edit) = self.runtime.edits.get(&id) {
5493 status.cursor = Some(edit.cursor);
5494 status.selection = edit.selection_range();
5495 status.composing = edit.composing;
5496 }
5497 status.handles = self.runtime.selection_handles == Some(id);
5498 status.toolbar = self
5499 .runtime
5500 .selection_toolbar
5501 .filter(|mark| mark.id == id)
5502 .map(|mark| mark.can_paste);
5503 status.caret_hidden = self.runtime.caret_hidden;
5504 }
5505 status
5506 }
5507
5508 /// The generic focus ring (for widgets that do not draw their own).
5509 fn draw_focus_ring(
5510 &mut self,
5511 draw_rect: Rect,
5512 status: &crate::interaction::Status,
5513 widget: &dyn Widget<Msg>,
5514 ) {
5515 // The generic ring only appears when the last interaction was a **keyboard** one
5516 // (`focus_visible`) — a click must not flash a ring.
5517 if status.focused
5518 && self.runtime.focus_visible
5519 && widget.focusable()
5520 && !widget.draws_own_focus()
5521 {
5522 let ring = Rect::new(
5523 draw_rect.x - 2.0,
5524 draw_rect.y - 2.0,
5525 draw_rect.width + 4.0,
5526 draw_rect.height + 4.0,
5527 );
5528 let alpha = 0.4 + 0.6 * status.focus_progress.clamp(0.0, 1.0);
5529 self.scene.draw_rect(
5530 ring,
5531 Color::TRANSPARENT,
5532 self.theme.radius + 2.0,
5533 2.0,
5534 self.theme.focus.fade(alpha),
5535 );
5536 }
5537 }
5538
5539 /// Keeps a widget this frame has just built for the rest of the walk, and hands back
5540 /// the reference the walk takes (milestone 592).
5541 fn keep(&self, widget: Box<dyn Widget<Msg>>) -> &'a dyn Widget<Msg> {
5542 let built: &'a Built<Msg> = self.built;
5543 let kept: &'a mut Box<dyn Widget<Msg>> = built.alloc(widget);
5544 &**kept
5545 }
5546
5547 /// Lays out a full-window screen and renders it offset by `off_x`.
5548 /// Renders a page in a transition, as `pose` puts it: moved along the reading direction
5549 /// (`mirror` turns that round), scaled about its centre and faded. A page at its
5550 /// natural size and opacity is drawn as it always was; otherwise it goes into one
5551 /// layer, and what can be touched in it moves with it.
5552 fn render_posed(
5553 &mut self,
5554 screen: &'a dyn Widget<Msg>,
5555 id: WidgetId,
5556 bounds: Rect,
5557 pose: crate::PagePose,
5558 mirror: f32,
5559 clip: Rect,
5560 ) {
5561 let off_x = pose.dx * bounds.width * mirror;
5562 let plain = (pose.scale - 1.0).abs() < 1e-4 && pose.opacity > 0.999;
5563 if plain {
5564 self.render_screen(screen, id, bounds, off_x, clip);
5565 return;
5566 }
5567 let mark = (self.scene.primitives().len(), self.xform_base());
5568 self.render_screen(screen, id, bounds, off_x, clip);
5569 let (p0, base) = mark;
5570 let group = self.scene.split_off(p0);
5571 // A page not yet faded in is still a layer, at nothing: a hero on it is about to
5572 // fly from it, and the flight takes it out of here.
5573 let centre = Point::new(
5574 bounds.x + off_x + bounds.width * 0.5,
5575 bounds.y + bounds.height * 0.5,
5576 );
5577 let matrix = Affine::scale(pose.scale, pose.scale).about(centre);
5578 self.scene.push_primitive(Primitive::Layer {
5579 primitives: group,
5580 opacity: pose.opacity.clamp(0.0, 1.0),
5581 clip,
5582 clip_shape: ClipShape::Rect,
5583 transform: Some(LayerTransform::new(matrix)),
5584 filter: LayerFilter::NONE,
5585 owner: id.as_u64(),
5586 });
5587 self.transform_interaction_registries(&base, matrix);
5588 }
5589
5590 /// The iOS page's shadow along its start edge (`route.dart:1065`): black at `0x04`
5591 /// fading to nothing over 5 % of the page's width, outside the page, at `frame`'s
5592 /// strength.
5593 fn paint_edge_shadow(
5594 &mut self,
5595 bounds: Rect,
5596 frame: crate::TransitionFrame,
5597 mirror: f32,
5598 clip: Rect,
5599 ) {
5600 let width = bounds.width * 0.05;
5601 let edge = if mirror < 0.0 {
5602 bounds.x + bounds.width + frame.top.dx * bounds.width * mirror
5603 } else {
5604 bounds.x + frame.top.dx * bounds.width
5605 };
5606 let shade = Color::rgba8(0, 0, 0, 0x04).fade(frame.edge_shadow);
5607 // Darkest at the page's edge, nothing at the far side: left to right, the colours
5608 // are ordered by which side the page is on.
5609 let (rect, from, to) = if mirror < 0.0 {
5610 (
5611 Rect::new(edge, bounds.y, width, bounds.height),
5612 shade,
5613 Color::TRANSPARENT,
5614 )
5615 } else {
5616 (
5617 Rect::new(edge - width, bounds.y, width, bounds.height),
5618 Color::TRANSPARENT,
5619 shade,
5620 )
5621 };
5622 self.scene.set_owner(0);
5623 self.scene.set_clip(clip);
5624 self.scene
5625 .gradient_rect(rect, from, to, [1.0, 0.0], 0.0, 0.0, Color::TRANSPARENT);
5626 }
5627
5628 fn render_screen(
5629 &mut self,
5630 screen: &'a dyn Widget<Msg>,
5631 id: WidgetId,
5632 bounds: Rect,
5633 off_x: f32,
5634 clip: Rect,
5635 ) {
5636 let rects = self.cached_rects(
5637 id,
5638 screen,
5639 Constraints::definite(Size::new(bounds.width, bounds.height)),
5640 );
5641 let screen_clip = clip.intersect(bounds);
5642 let mut index = 0;
5643 self.walk(
5644 screen,
5645 id,
5646 (bounds.x + off_x, bounds.y),
5647 screen_clip,
5648 &rects,
5649 &mut index,
5650 );
5651 }
5652
5653 /// Floats field `id`'s **selection bar** over everything, when the shell has marked it as
5654 /// showing (milestone 568): asks the field for the bar its situation calls for, and for
5655 /// the box to place it against, and defers it like any other overlay.
5656 ///
5657 /// The three conditions are read where they are true — the selection from the retained
5658 /// edit, the text from the widget, the clipboard from the mark the shell set when the
5659 /// bar opened — so they are the same ones the field's default list is decided by.
5660 fn push_selection_toolbar(
5661 &mut self,
5662 widget: &'a dyn Widget<Msg>,
5663 id: WidgetId,
5664 draw_rect: Rect,
5665 clip: Rect,
5666 status: &Status,
5667 can_paste: bool,
5668 ) {
5669 let Some(edit) = self.runtime.edits.get(&id).copied() else {
5670 return;
5671 };
5672 let Some(local) = widget.selection_anchor(draw_rect.width, &edit, status.scroll_y) else {
5673 return;
5674 };
5675 let anchor = local.translate(draw_rect.x, draw_rect.y);
5676 // Opened by a right-click, the bar goes where the pointer was (milestone 618), as
5677 // the reference's context menu does (`editable_text.dart:3211`); the selection
5678 // still decides whether it is shown at all.
5679 let pointer = self
5680 .runtime
5681 .selection_toolbar
5682 .filter(|mark| mark.id == id)
5683 .and_then(|mark| mark.at)
5684 .map(|at| Rect::new(at.x, at.y, 0.0, 0.0));
5685 // The bar goes with what it points at: a selection scrolled out of the region it is
5686 // drawn in takes its bar with it, rather than leaving it floating over nothing.
5687 let seen = anchor.x + anchor.width >= clip.x
5688 && anchor.x <= clip.x + clip.width
5689 && anchor.y + anchor.height > clip.y
5690 && anchor.y < clip.y + clip.height;
5691 if !seen {
5692 return;
5693 }
5694 let len = widget.text_value().map_or(0, |text| text.chars().count());
5695 let selection = edit
5696 .selection_range()
5697 .map(|(start, end)| (start.min(len), end.min(len)))
5698 .filter(|(start, end)| start < end);
5699 let context = crate::ToolbarContext {
5700 has_selection: selection.is_some(),
5701 can_paste,
5702 all_selected: len == 0 || selection == Some((0, len)),
5703 };
5704 let Some(content) = widget.selection_toolbar(context) else {
5705 return;
5706 };
5707 self.overlays.push((
5708 content,
5709 id.toolbar(context.variant()),
5710 pointer.unwrap_or(anchor),
5711 Placement::Selection,
5712 None,
5713 1.0,
5714 false,
5715 None,
5716 self.theme.clone(),
5717 ));
5718 }
5719
5720 /// Registers a region the mouse enters and leaves, as far as it shows (milestone 583).
5721 fn register_hover_region(
5722 &mut self,
5723 id: WidgetId,
5724 spec: crate::HoverRegion,
5725 whole: Rect,
5726 clip: Rect,
5727 ) {
5728 let seen = whole.intersect(clip);
5729 if seen.width > 0.0 && seen.height > 0.0 {
5730 self.hover_regions.push(HoverEntry {
5731 id,
5732 seen,
5733 whole,
5734 parent: self.hover_parent,
5735 spec,
5736 });
5737 }
5738 }
5739
5740 /// Floats the bar of a selection area's selection over `range` of this text — the first
5741 /// the selection covers, in reading order, since the walk meets them in that order.
5742 fn push_region_toolbar(
5743 &mut self,
5744 widget: &'a dyn Widget<Msg>,
5745 id: WidgetId,
5746 draw_rect: Rect,
5747 clip: Rect,
5748 range: (usize, usize),
5749 ) {
5750 let all_selected = self
5751 .runtime
5752 .region
5753 .as_ref()
5754 .is_some_and(|selection| selection.all);
5755 let context = crate::ToolbarContext {
5756 has_selection: true,
5757 can_paste: false,
5758 all_selected,
5759 };
5760 let Some((local, own)) = widget.region_toolbar(context, draw_rect.width, range) else {
5761 return;
5762 };
5763 // The area's bar, if the application said what it holds; the text's otherwise.
5764 let content = match self.area_widget.and_then(|area| area.area_toolbar(context)) {
5765 Some(Some(bar)) => bar,
5766 Some(None) => return,
5767 None => own,
5768 };
5769 let anchor = local.translate(draw_rect.x, draw_rect.y);
5770 let seen = anchor.x + anchor.width >= clip.x
5771 && anchor.x <= clip.x + clip.width
5772 && anchor.y + anchor.height > clip.y
5773 && anchor.y < clip.y + clip.height;
5774 if !seen {
5775 return;
5776 }
5777 self.region_bar_placed = true;
5778 self.overlays.push((
5779 content,
5780 id.toolbar(context.variant()),
5781 anchor,
5782 Placement::Selection,
5783 None,
5784 1.0,
5785 false,
5786 None,
5787 self.theme.clone(),
5788 ));
5789 }
5790
5791 /// Processes the deferred overlays: sub-layout, positioning and rendering **above**
5792 /// everything (their clickable areas win). May spawn further overlays (nested portals).
5793 fn process_overlays(&mut self) {
5794 let window = Rect::new(0.0, 0.0, self.available.width, self.available.height);
5795 while let Some((content, oid, anchor, placement, dismiss, progress, traps, scrim, theme)) =
5796 self.overlays.pop()
5797 {
5798 // The theme this overlay was declared under, for the whole of its layout and
5799 // painting; whatever was in force when the walk ended is put back after it,
5800 // so two overlays declared under two themes do not bleed into each other.
5801 let outer = std::mem::replace(&mut self.theme, theme);
5802 // Drawers slide along a **spring curve** (a gentle arrival), not linearly; the
5803 // other overlays keep their raw progress.
5804 let progress = if matches!(
5805 placement,
5806 Placement::Left | Placement::Right | Placement::Bottom
5807 ) {
5808 crate::runtime::spring_ease(progress)
5809 } else {
5810 progress
5811 };
5812 // The content's natural size. A drawer (`Left`) is constrained in height to the
5813 // window (so its `Percent(1.0)` panel unfolds) with a free width; the other
5814 // overlays take their natural size.
5815 let (free_x, free_y) = match placement {
5816 Placement::Left | Placement::Right => (true, false),
5817 // The sheet is full-width (constrained to the window) with its natural height:
5818 // its `Percent(1.0)` panel unfolds across the width.
5819 Placement::Bottom => (false, true),
5820 _ => (true, true),
5821 };
5822 let mut rects = self.cached_rects(
5823 oid,
5824 content,
5825 Constraints::scroll(self.available.width, self.available.height, free_x, free_y),
5826 );
5827 let mut size = rects
5828 .first()
5829 .copied()
5830 .unwrap_or(Rect::new(0.0, 0.0, 0.0, 0.0));
5831 // **Nothing wider than the window.** A free axis asks the content how big it
5832 // would like to be, and a dialog answers with the width of its widest line —
5833 // which, at a reader's font size, is wider than the screen. Centred, that
5834 // spills off *both* edges, and a button drawn at a negative x is a button
5835 // nobody can press. So the answer is taken as a wish rather than a size: past
5836 // the room there is, the content is laid out again at that room, and whatever
5837 // can fold — a paragraph, a bar of actions — folds.
5838 //
5839 // The room is the window less the content's **own margin**, which is how an
5840 // overlay says how far off the edges it wants to be held: a dialog's inset
5841 // padding is exactly that, and a clamp that ignored it would push the surface
5842 // flat against both sides of the screen.
5843 //
5844 // The height is deliberately left alone. A dialog too tall for the screen
5845 // wants its content to scroll, which is a question of its own; squashing it
5846 // here would only move the spill inside the surface.
5847 let inset = content.style_themed(&self.theme).margin;
5848 let room = (self.available.width - inset.left - inset.right).max(0.0);
5849 if free_x && size.width > room {
5850 rects = self.cached_rects(
5851 oid,
5852 content,
5853 Constraints::scroll(room, self.available.height, false, free_y),
5854 );
5855 size = rects
5856 .first()
5857 .copied()
5858 .unwrap_or(Rect::new(0.0, 0.0, 0.0, 0.0));
5859 }
5860
5861 // A drawer's slide-in from the left / right edge.
5862 let from_left = -(1.0 - progress) * size.width;
5863 let from_right = self.available.width - progress * size.width;
5864 // An anchored menu/tooltip: aligned to the anchor's **start** edge — in RTL that
5865 // edge is the right one (the menu opens leftwards).
5866 let anchor_x = if self.rtl() {
5867 anchor.x + anchor.width - size.width
5868 } else {
5869 anchor.x
5870 };
5871 let mut pos = match placement {
5872 Placement::Below => (anchor_x, anchor.y + anchor.height + 4.0),
5873 // A submenu: past the row's end edge, its first row level with the row —
5874 // the panel's own room above its rows taken back (milestone 603).
5875 Placement::Beside if self.rtl() => (anchor.x - size.width, anchor.y - 8.0),
5876 Placement::Beside => (anchor.x + anchor.width, anchor.y - 8.0),
5877 Placement::Center => (
5878 (self.available.width - size.width) * 0.5,
5879 (self.available.height - size.height) * 0.5,
5880 ),
5881 Placement::Tooltip => (anchor_x, anchor.y - size.height - 6.0),
5882 // The bar over a selection: on the desktops, a menu hanging from the pointer
5883 // or the selection's top (milestone 618); elsewhere centred on it, above or
5884 // below, inside the window.
5885 Placement::Selection if crate::selectiontoolbar::uses_menu(self.theme.platform) => {
5886 crate::selectiontoolbar::place_menu(
5887 crate::selectiontoolbar::primary_anchor(anchor),
5888 Size::new(size.width, size.height),
5889 window,
5890 )
5891 }
5892 Placement::Selection => crate::selectiontoolbar::place(
5893 anchor,
5894 Size::new(size.width, size.height),
5895 window,
5896 crate::textinput::HANDLE_SIZE,
5897 ),
5898 // `Left` = a drawer on the **start** side; in RTL, start = the right.
5899 Placement::Left if self.rtl() => (from_right, 0.0),
5900 Placement::Left => (from_left, 0.0),
5901 // `Right` = the **end** side; in RTL, end = the left.
5902 Placement::Right if self.rtl() => (from_left, 0.0),
5903 Placement::Right => (from_right, 0.0),
5904 // The sheet slides up from the bottom: its bottom edge stays flush with the
5905 // window, offset downwards by `(1-progress)·height`.
5906 Placement::Bottom => (0.0, self.available.height - progress * size.height),
5907 };
5908
5909 // An **anchored** overlay follows a widget; the others (a modal, a drawer, a
5910 // sheet) are positioned against the window and have no anchor worth the name.
5911 // Only the first kind can find its anchor gone from the window: a screen
5912 // sliding out under a `Navigator`, a row scrolled sideways past the edge.
5913 let anchored = matches!(
5914 placement,
5915 Placement::Below | Placement::Tooltip | Placement::Beside
5916 );
5917 let anchor_on_screen = !anchored
5918 || (anchor.x < self.available.width
5919 && anchor.x + anchor.width > 0.0
5920 && anchor.y < self.available.height
5921 && anchor.y + anchor.height > 0.0);
5922
5923 // Auto-flip: when an anchored overlay overflows an edge, it is flipped / nudged
5924 // back inside the window.
5925 //
5926 // This is for a menu opened near the right margin, and it assumes the anchor is
5927 // something the window is showing. When the anchor has **left** the window the
5928 // nudge does the opposite of its job: it drags a departing screen's menu back
5929 // into view, fully opaque, over the screen that replaced it. An overlay whose
5930 // anchor is off screen goes off screen with it.
5931 if anchored && anchor_on_screen {
5932 // A vertical overflow → flip to the other side of the anchor.
5933 if placement == Placement::Below
5934 && pos.1 + size.height > self.available.height
5935 && anchor.y - size.height - 4.0 >= 0.0
5936 {
5937 pos.1 = anchor.y - size.height - 4.0;
5938 } else if placement == Placement::Tooltip
5939 && pos.1 < 0.0
5940 && anchor.y + anchor.height + size.height + 6.0 <= self.available.height
5941 {
5942 pos.1 = anchor.y + anchor.height + 6.0;
5943 }
5944 // A submenu with no room on its end side opens on the other side of its row,
5945 // rather than being pushed back over the row it came from.
5946 if placement == Placement::Beside {
5947 let (end, start) = if self.rtl() {
5948 (anchor.x - size.width, anchor.x + anchor.width)
5949 } else {
5950 (anchor.x + anchor.width, anchor.x - size.width)
5951 };
5952 let fits = |x: f32| x >= 0.0 && x + size.width <= self.available.width;
5953 if !fits(end) && fits(start) {
5954 pos.0 = start;
5955 }
5956 if pos.1 + size.height > self.available.height {
5957 pos.1 = (self.available.height - size.height).max(0.0);
5958 }
5959 }
5960 // A horizontal overflow → nudge back inside the window.
5961 if pos.0 + size.width > self.available.width {
5962 pos.0 = (self.available.width - size.width).max(0.0);
5963 }
5964 if pos.0 < 0.0 {
5965 pos.0 = 0.0;
5966 }
5967 }
5968
5969 if matches!(
5970 placement,
5971 Placement::Center | Placement::Left | Placement::Right | Placement::Bottom
5972 ) {
5973 // The scrim behind the modal / the drawer, modulated by the progress (a fade
5974 // synchronised with the slide). The colour is the overlay's own when it asked
5975 // for one — alpha included, since a scrim's transparency *is* the colour —
5976 // and the `scrim` role at half opacity otherwise.
5977 let base = scrim.unwrap_or_else(|| self.theme.scheme.scrim.with_alpha(0.5));
5978 self.scene.set_owner(0);
5979 self.scene.set_clip(window);
5980 self.scene
5981 .fill_rect(window, base.with_alpha(base.a * progress));
5982 }
5983
5984 // Dismissal on a click **outside** the content (a modal, a menu…): a full-screen
5985 // hit added **before** the content, so the content beats it where they overlap.
5986 // The dismissal is also remembered for Escape (the last one rendered = the
5987 // topmost).
5988 //
5989 // Gated on the same condition as the nudge, and for the same reason: a
5990 // window-wide barrier belonging to an overlay nobody can see would swallow the
5991 // next press anywhere on the screen that replaced it.
5992 if let Some(msg) = dismiss.filter(|_| anchor_on_screen) {
5993 self.overlay_cover.push(window);
5994 self.dismisses.push(msg.clone());
5995 self.hits.push(Hit {
5996 id: oid.barrier(),
5997 rect: window,
5998 msg: Some(msg),
5999 xform: None,
6000 });
6001 }
6002
6003 // A **modal** (scrimmed) or **trapping anchored** (menu) overlay: its focusables
6004 // form a **scope** that traps Tab/arrows/click-to-focus. The last one rendered (the
6005 // topmost) wins; anchored overlays that do not trap (a tooltip, an autocomplete
6006 // list) leave the focus alone.
6007 let modal = matches!(
6008 placement,
6009 Placement::Center | Placement::Left | Placement::Right | Placement::Bottom
6010 );
6011 if modal || traps {
6012 self.focus_scope_start = Some(self.focusables.len());
6013 }
6014
6015 // Where a press is the overlay's and not the pages' — a tooltip takes none.
6016 if placement != Placement::Tooltip && anchor_on_screen {
6017 self.overlay_cover
6018 .push(Rect::new(pos.0, pos.1, size.width, size.height));
6019 }
6020
6021 // A bar over a selection: where it ended up, so that a press on it is known for
6022 // one — see [`Ui::toolbar_contains`].
6023 if placement == Placement::Selection {
6024 self.toolbars
6025 .push(Rect::new(pos.0, pos.1, size.width, size.height));
6026 }
6027
6028 let mut index = 0;
6029 self.walk(content, oid, pos, window, &rects, &mut index);
6030 self.theme = outer;
6031 }
6032 }
6033}
6034
6035impl<Msg: Clone> Builder<'_, Msg> {
6036 /// Draws a scrollbar (track + thumb) and registers it for hit-testing a drag.
6037 /// Paints the region's overscroll glows over its viewport.
6038 ///
6039 /// The colour is the scheme's **secondary**: the edge feedback is an
6040 /// acknowledgement, not a call to action, so it must read as part of the surface
6041 /// rather than compete with whatever primary-coloured control sits nearby.
6042 fn add_overscroll_glow(&mut self, id: WidgetId, viewport: Rect) {
6043 if let Some(glows) = self.runtime.scroll_glow.get(&id) {
6044 glows.paint(viewport, self.theme.scheme.secondary, &mut self.scene);
6045 }
6046 }
6047
6048 fn add_scrollbar(&mut self, id: WidgetId, viewport: Rect, axis: Bar) {
6049 let Bar {
6050 vertical,
6051 offset,
6052 max,
6053 reverse,
6054 asked,
6055 visible,
6056 } = axis;
6057 // **Along the horizontal axis, never** (`app.dart:861`) — on any platform, under
6058 // any setting. A sideways strip is scrolled by the thing that made it sideways,
6059 // and a bar under it takes room from content that is short of it already.
6060 if !vertical {
6061 return;
6062 }
6063 // And down the vertical one, only where the platform's own scroll views have a
6064 // bar (`app.dart:865` against `:870`). A finger already knows where it is on the
6065 // page; a permanent bar over the content is an affordance for a pointer that
6066 // cannot feel the edges. This drew one everywhere, on both axes, always.
6067 let behavior = crate::ScrollConfiguration::of().scrollbars(&self.theme);
6068 if asked.unwrap_or(behavior) == crate::physics::Scrollbars::Never {
6069 return;
6070 }
6071 let (track_start, track_len, content_len) = if vertical {
6072 (viewport.y, viewport.height, viewport.height + max)
6073 } else {
6074 (viewport.x, viewport.width, viewport.width + max)
6075 };
6076 // Every metric below is `theme ?? framework`. There is no per-call override for a
6077 // scrollbar — it is drawn by the walk, not by a widget a caller configured — so
6078 // the chain is two terms here rather than three.
6079 let bar = &self.theme.widgets.scrollbar;
6080 // **Under an Android theme, the platform's own bar** (`scrollbar.dart:331`): half
6081 // as thick, flush with the edge, square-ended, an opaque grey at rest, and not
6082 // something a pointer takes hold of. The theme's platform decides it, as the
6083 // reference's does, so a theme set to Android draws it on any device.
6084 let android = self.theme.platform == frus_core::TargetPlatform::Android;
6085 let bar_size = bar
6086 .thickness
6087 .unwrap_or(if android { BAR_SIZE / 2.0 } else { BAR_SIZE });
6088 let bar_margin = bar.margin.unwrap_or(if android { 0.0 } else { BAR_MARGIN });
6089 let thumb_len = (track_len * track_len / content_len)
6090 .max(bar.min_thumb_length.unwrap_or(MIN_THUMB))
6091 .min(track_len);
6092 let travel = track_len - thumb_len;
6093 // Along a reversed axis the numbers run the other way, so the thumb does too:
6094 // offset 0 is the far end, and that is where it rests.
6095 let fraction = if max > 0.0 { offset / max } else { 0.0 };
6096 let fraction = if reverse { 1.0 - fraction } else { fraction };
6097 let thumb_pos = track_start + fraction * travel;
6098
6099 // The track's rectangle is still worked out — it is the room a pointer has to be
6100 // in, and the geometry the thumb sits in — but nothing is painted for it.
6101 //
6102 // `BAR_SIZE` is the **thumb's** thickness, not a slot's: the reference keeps the
6103 // thumb clear of the edge with `crossAxisMargin` (`scrollbar.dart:357`) rather
6104 // than shrinking it to fit. This drew a 6-pixel thumb inside an 8-pixel slot,
6105 // which is the same arithmetic with the wrong number left over.
6106 let (track, thumb) = if vertical {
6107 let x = viewport.x + viewport.width - bar_margin - bar_size;
6108 (
6109 Rect::new(
6110 x - bar_margin,
6111 viewport.y,
6112 bar_size + bar_margin * 2.0,
6113 viewport.height,
6114 ),
6115 Rect::new(x, thumb_pos, bar_size, thumb_len),
6116 )
6117 } else {
6118 let y = viewport.y + viewport.height - bar_margin - bar_size;
6119 (
6120 Rect::new(
6121 viewport.x,
6122 y - bar_margin,
6123 viewport.width,
6124 bar_size + bar_margin * 2.0,
6125 ),
6126 Rect::new(thumb_pos, y, thumb_len, bar_size),
6127 )
6128 };
6129 // What a mouse has to be inside for the bar to notice it: the track, widened to
6130 // take in a tap target's worth of room around the thumb (`scrollbar.dart:762`).
6131 let reach = {
6132 let (cx, cy) = (thumb.x + thumb.width * 0.5, thumb.y + thumb.height * 0.5);
6133 let r = crate::theme::MIN_TAP_TARGET * 0.5;
6134 let x0 = track.x.min(cx - r);
6135 let y0 = track.y.min(cy - r);
6136 let x1 = (track.x + track.width).max(cx + r);
6137 let y1 = (track.y + track.height).max(cy + r);
6138 Rect::new(x0, y0, x1 - x0, y1 - y0)
6139 };
6140
6141 // **How present the bar is**, this frame. It arrives when the area moves and goes
6142 // again once the area has been still long enough; an area nobody has scrolled has
6143 // none at all. Unless it was asked to stay (`scrollbar.dart:214`).
6144 let fade = self.runtime.scrollbar_fade_of(id);
6145 let opacity = if visible.unwrap_or(false) {
6146 1.0
6147 } else {
6148 fade.opacity.clamp(0.0, 1.0)
6149 };
6150
6151 // **No track.** The reference's is transparent unless a caller asks for one
6152 // (`scrollbar.dart:281`), and even then it is 3 to 5 %.
6153 //
6154 // The thumb takes the reference's opacity for the surface's brightness: at rest
6155 // (`scrollbar.dart:242`, `:248`), warmed towards its hovered value while a
6156 // pointer is near it (`:239`, `:245`), and at its dragged value the moment the
6157 // thumb is held (`:238`, `:244`) — that one does not fade in, because the hand is
6158 // already on it and a fade would only lag behind the grab.
6159 // The scheme's own answer, which is what the reference reads here
6160 // (`scrollbar.dart:232`). This used to be `surface.compute_luminance() < 0.5`:
6161 // right on both built-in schemes and a guess on any other.
6162 let dark = self.theme.brightness().is_dark();
6163 let (rest, warm, grabbed) = if dark {
6164 (THUMB_ON_DARK, THUMB_HOVER_ON_DARK, THUMB_DRAG_ON_DARK)
6165 } else {
6166 (THUMB_ON_LIGHT, THUMB_HOVER_ON_LIGHT, THUMB_DRAG_ON_LIGHT)
6167 };
6168 // A theme's levels replace the scheme's, one at a time: naming the resting
6169 // opacity says nothing about the held one.
6170 let rest = bar.opacity.unwrap_or(rest);
6171 let warm = bar.hover_opacity.unwrap_or(warm);
6172 let grabbed = bar.drag_opacity.unwrap_or(grabbed);
6173 let base = bar.thumb_color.unwrap_or(self.theme.scheme.on_surface);
6174 // At rest under an Android theme, the reference's thumb is the theme's highlight
6175 // made opaque (`scrollbar.dart:240`, `:246`), not a fade of the content colour —
6176 // unless the theme chose a colour or a resting level of its own.
6177 let idle = if android && bar.thumb_color.is_none() && bar.opacity.is_none() {
6178 if dark {
6179 ANDROID_THUMB_ON_DARK
6180 } else {
6181 ANDROID_THUMB_ON_LIGHT
6182 }
6183 } else {
6184 base.fade(rest)
6185 };
6186 let color = if self.runtime.scrollbar_dragged == Some(id) {
6187 base.fade(grabbed)
6188 } else {
6189 idle.lerp(base.fade(warm), fade.hover.clamp(0.0, 1.0))
6190 };
6191 if opacity > 0.0 {
6192 self.scene.draw_rect(
6193 thumb,
6194 color.fade(opacity),
6195 bar.radius
6196 .unwrap_or(if android { 0.0 } else { bar_size * 0.5 }),
6197 0.0,
6198 Color::TRANSPARENT,
6199 );
6200 }
6201 // Registered even when nothing was painted for it — unlike a bar the platform
6202 // does not draw at all, which is not registered because it is not there. A mouse
6203 // coming near a faded bar is what brings it back (`scrollbar.dart:2132`), so
6204 // something has to be here for the mouse to find. What a bar at zero cannot be is
6205 // **grabbed**; see `Ui::scrollbar_at`.
6206 self.scrollbars.push(Scrollbar {
6207 id,
6208 vertical,
6209 thumb,
6210 track_start,
6211 track_len,
6212 thumb_len,
6213 reverse,
6214 max,
6215 opacity,
6216 reach,
6217 interactive: bar.interactive.unwrap_or(!android),
6218 });
6219 }
6220}
6221
6222/// `primitives` without those owned by `hidden`, looking inside layers too; the ones owned
6223/// by `keep` among them are moved into `taken`, as painted, outside any layer. A layer left
6224/// with nothing in it is dropped.
6225fn take_owned(
6226 primitives: Vec<Primitive>,
6227 hidden: &std::collections::HashSet<u64>,
6228 keep: &std::collections::HashSet<u64>,
6229 taken: &mut Vec<Primitive>,
6230) -> Vec<Primitive> {
6231 let mut out = Vec::with_capacity(primitives.len());
6232 for primitive in primitives {
6233 match primitive {
6234 Primitive::Layer {
6235 primitives: inner,
6236 opacity,
6237 clip,
6238 clip_shape,
6239 transform,
6240 filter,
6241 owner,
6242 } => {
6243 let inner = take_owned(inner, hidden, keep, taken);
6244 if !inner.is_empty() {
6245 out.push(Primitive::Layer {
6246 primitives: inner,
6247 opacity,
6248 clip,
6249 clip_shape,
6250 transform,
6251 filter,
6252 owner,
6253 });
6254 }
6255 }
6256 other if hidden.contains(&other.owner()) => {
6257 if keep.contains(&other.owner()) {
6258 taken.push(other);
6259 }
6260 }
6261 other => out.push(other),
6262 }
6263 }
6264 out
6265}
6266
6267/// Turns a widget tree into a [`Ui`] for a given size, runtime state and theme.
6268pub fn build_ui<'a, Msg: Clone + 'static>(
6269 root: &'a dyn Widget<Msg>,
6270 available: Size,
6271 runtime: &'a Runtime,
6272 theme: &'a Theme,
6273) -> Ui<Msg> {
6274 build_ui_impl(root, available, runtime, theme, false).0
6275}
6276
6277/// Like [`build_ui`], but it also collects the **inspection nodes** (one per painted widget:
6278/// name, box, depth) — the raw material of the runtime inspector and of the diagnostic dump.
6279/// Reserve it for the frames where the inspector is on.
6280pub fn build_ui_inspected<'a, Msg: Clone + 'static>(
6281 root: &'a dyn Widget<Msg>,
6282 available: Size,
6283 runtime: &'a Runtime,
6284 theme: &'a Theme,
6285) -> (Ui<Msg>, Vec<crate::inspector::InspectorNode>) {
6286 let (ui, nodes) = build_ui_impl(root, available, runtime, theme, true);
6287 (ui, nodes.unwrap_or_default())
6288}
6289
6290/// Panics, **in debug builds only**, when the reader's font size is installed and the
6291/// surface it belongs to is not.
6292///
6293/// The two travel together — [`MediaQuery::install`] sets both — so a scale away from 1
6294/// with no description means somebody installed half a surface, and the half they left out
6295/// is about to be missing for the layout that follows. That is not a theory: for four
6296/// milestones the shell scoped only the build, the scale was 1 while text was measured and
6297/// painted, and the reader's setting reached a device without moving a pixel. Nothing said
6298/// a word — not the 91 goldens, not clippy, not the strict rustdoc.
6299///
6300/// Debug only, because it is a wiring mistake rather than a state a running application can
6301/// reach: it should stop a test, not a user's frame. A scale of exactly 1 is the neutral
6302/// value and says nothing either way, so it is never a failure.
6303#[cfg(debug_assertions)]
6304fn assert_surface_is_whole() {
6305 let scale = frus_core::text_scale();
6306 if (scale - 1.0).abs() > f32::EPSILON && !crate::MediaQuery::of().is_described() {
6307 panic!(
6308 "a text scale of {scale} is installed with no surface described: something \
6309 installed half a surface. Use `MediaQuery::install` (or `scope`), which sets \
6310 the description and the reader's font size together \u{2014} see milestone 408."
6311 );
6312 }
6313}
6314
6315/// Where a frame keeps the widgets it builds as it walks (see `Builder::built`).
6316type Built<Msg> = typed_arena::Arena<Box<dyn Widget<Msg>>>;
6317
6318fn build_ui_impl<Msg: Clone + 'static>(
6319 root: &dyn Widget<Msg>,
6320 available: Size,
6321 runtime: &Runtime,
6322 theme: &Theme,
6323 inspect: bool,
6324) -> (Ui<Msg>, Option<Vec<crate::inspector::InspectorNode>>) {
6325 // Made first, so that it outlives the walk that borrows from it.
6326 let built = Built::new();
6327 build_ui_walk(root, available, runtime, theme, inspect, &built)
6328}
6329
6330fn build_ui_walk<'a, Msg: Clone + 'static>(
6331 root: &'a dyn Widget<Msg>,
6332 available: Size,
6333 runtime: &'a Runtime,
6334 theme: &'a Theme,
6335 inspect: bool,
6336 built: &'a Built<Msg>,
6337) -> (Ui<Msg>, Option<Vec<crate::inspector::InspectorNode>>) {
6338 #[cfg(debug_assertions)]
6339 assert_surface_is_whole();
6340
6341 let (mut rects, overflows) = runtime.layout_cache.borrow_mut().rects(
6342 WidgetId::ROOT,
6343 root,
6344 runtime,
6345 theme,
6346 Constraints::definite(available),
6347 );
6348
6349 let mut builder = Builder {
6350 scene: Scene::new(),
6351 hits: Vec::new(),
6352 long_presses: Vec::new(),
6353 dismisses: Vec::new(),
6354 edit_actions: Vec::new(),
6355 toolbars: Vec::new(),
6356 overlay_cover: Vec::new(),
6357 focusables: Vec::new(),
6358 focus_scope_start: None,
6359 scrollables: Vec::new(),
6360 scrollbars: Vec::new(),
6361 draggables: Vec::new(),
6362 drag_sources: Vec::new(),
6363 drop_zones: Vec::new(),
6364 inks: Vec::new(),
6365 pans: Vec::new(),
6366 title_bar_row: None,
6367 title_bar_regions: Vec::new(),
6368 pointer_listeners: Vec::new(),
6369 hover_regions: Vec::new(),
6370 hover_parent: None,
6371 text_stops: Vec::new(),
6372 area: None,
6373 area_widget: None,
6374 region_bar_placed: false,
6375 reorderables: Vec::new(),
6376 interactives: Vec::new(),
6377 overlays: Vec::new(),
6378 wants_animation: false,
6379 available,
6380 runtime,
6381 theme: std::rc::Rc::new(theme.clone()),
6382 inspector: inspect.then(Vec::new),
6383 depth: 0,
6384 refresh_host: None,
6385 scroll_host: None,
6386 hero_screen: None,
6387 heroes: Vec::new(),
6388 refreshes: Vec::new(),
6389 dismissables: Vec::new(),
6390 sheets: Vec::new(),
6391 semantics: Vec::new(),
6392 system_ui: Vec::new(),
6393 focus_excluded: false,
6394 touch_clip: None,
6395 backdrop_group: None,
6396 focus_skipped: false,
6397 focus_order: None,
6398 focus_group: None,
6399 autofill_group: None,
6400 scopes: Vec::new(),
6401 listeners: Vec::new(),
6402 overflows: std::cell::RefCell::new(Vec::new()),
6403 pending_overflows: std::cell::RefCell::new(std::collections::HashMap::new()),
6404 built,
6405 };
6406 // The root is mirrored in RTL (like every layout root).
6407 builder.mirror(&mut rects);
6408 builder.record_overflows(WidgetId::ROOT, &rects, overflows);
6409 let mut index = 0;
6410 builder.walk(
6411 root,
6412 WidgetId::ROOT,
6413 (0.0, 0.0),
6414 Rect::UNBOUNDED,
6415 &rects,
6416 &mut index,
6417 );
6418
6419 // Overlays (floating menus, modals, tooltips) above everything else. (Their walk restarts
6420 // from depth 0: roots as far as the inspector is concerned.)
6421 builder.process_overlays();
6422
6423 // End of frame: forget the layout roots and repaint boundaries of widgets that have gone,
6424 // and freeze the caches' diagnostic counters.
6425 runtime.layout_cache.borrow_mut().end_frame();
6426 runtime.paint_cache.borrow_mut().end_frame();
6427
6428 // Replays the outgoing subtrees, fading out, over the current scene.
6429 builder.scene.set_clip(Rect::UNBOUNDED);
6430 for (primitives, opacity) in runtime.leaving.values() {
6431 for primitive in primitives {
6432 builder.scene.push_faded(primitive, *opacity);
6433 }
6434 }
6435
6436 // A box whose children ran past it now **says so on the screen**, not only in the
6437 // console — see `paint_overflow_bands`. Last, so nothing paints over it.
6438 paint_overflow_bands(&mut builder.scene, &builder.overflows.borrow());
6439
6440 let ui = Ui {
6441 scene: builder.scene,
6442 hits: builder.hits,
6443 long_presses: builder.long_presses,
6444 dismisses: builder.dismisses,
6445 edit_actions: builder.edit_actions,
6446 toolbars: builder.toolbars,
6447 overlay_cover: builder.overlay_cover,
6448 focusables: builder.focusables,
6449 focus_scope_start: builder.focus_scope_start,
6450 scrollables: builder.scrollables,
6451 scrollbars: builder.scrollbars,
6452 draggables: builder.draggables,
6453 drag_sources: builder.drag_sources,
6454 drop_zones: builder.drop_zones,
6455 inks: builder.inks,
6456 pans: builder.pans,
6457 title_bar_row: builder.title_bar_row,
6458 title_bar_regions: builder.title_bar_regions,
6459 pointer_listeners: builder.pointer_listeners,
6460 hover_regions: builder.hover_regions,
6461 text_stops: builder.text_stops,
6462 reorderables: builder.reorderables,
6463 interactives: builder.interactives,
6464 refreshes: builder.refreshes,
6465 dismissables: builder.dismissables,
6466 sheets: builder.sheets,
6467 wants_animation: builder.wants_animation,
6468 semantics: builder.semantics,
6469 system_ui: builder.system_ui,
6470 overflows: builder.overflows.into_inner(),
6471 scopes: builder.scopes,
6472 listeners: builder.listeners,
6473 };
6474 (ui, builder.inspector)
6475}
6476
6477/// Collects the identities of every widget in the tree (prefix order), following the same
6478/// positional scheme as [`build_ui`]. Used to detect mounts/unmounts between two frames.
6479pub fn collect_ids<Msg>(root: &dyn Widget<Msg>) -> Vec<WidgetId> {
6480 fn walk<Msg>(widget: &dyn Widget<Msg>, id: WidgetId, out: &mut Vec<WidgetId>) {
6481 out.push(id);
6482 for (index, child) in widget.children().iter().enumerate() {
6483 walk(child.as_ref(), child_id(id, index, child.as_ref()), out);
6484 }
6485 }
6486 let mut out = Vec::new();
6487 walk(root, WidgetId::ROOT, &mut out);
6488 out
6489}
6490
6491/// Identities of the **subtree** rooted at `root_id` — `widget` being the widget with that
6492/// identity — that is `[root_id, …descendants]`, derived by the same positional scheme as
6493/// [`collect_ids`].
6494///
6495/// Used by the **drag ghost**: a **rich** card's primitives are painted by its children (owners
6496/// other than the card itself). To capture all of its visuals, the shell gathers the primitives
6497/// of the **whole** subtree, not only the card's own.
6498pub fn subtree_ids<Msg>(widget: &dyn Widget<Msg>, root_id: WidgetId) -> Vec<WidgetId> {
6499 fn walk<Msg>(widget: &dyn Widget<Msg>, id: WidgetId, out: &mut Vec<WidgetId>) {
6500 out.push(id);
6501 for (index, child) in widget.children().iter().enumerate() {
6502 walk(child.as_ref(), child_id(id, index, child.as_ref()), out);
6503 }
6504 }
6505 let mut out = Vec::new();
6506 walk(widget, root_id, &mut out);
6507 out
6508}
6509
6510/// The owners of everything a carried row, card or item may be **moved past** this frame:
6511/// every reorderable that can be dropped on, and all it paints.
6512///
6513/// What a reorder preview slides out of the way is decided by geometry — the band the
6514/// source sits in — and geometry alone moves whatever shares that band: a button floating
6515/// over a list, the navigation bar under it. This is the other half of the question, *is
6516/// it part of something that can be reordered*, asked of the tree. A grip is inside its
6517/// row, so it moves with it without being a target itself.
6518pub fn reorderable_owners<Msg>(
6519 ui: &Ui<Msg>,
6520 root: &dyn Widget<Msg>,
6521) -> std::collections::HashSet<u64> {
6522 ui.reorderables
6523 .iter()
6524 .filter_map(|(id, _)| {
6525 find_widget(root, *id)
6526 .filter(|widget| widget.reorder_droppable())
6527 .map(|widget| subtree_ids(widget, *id))
6528 })
6529 .flatten()
6530 .map(|id| id.as_u64())
6531 .collect()
6532}
6533
6534/// The slots a reorderable `id` can be dropped among **in its own list**: its siblings — the
6535/// children of its parent — that can be dropped on, with their boxes this frame, in order.
6536///
6537/// A list's rows are one widget's children, and so are a board column's cards and the drop
6538/// zone that ends it. Nothing else on the page is, which is what lets a drop that landed on
6539/// no row at all still mean *somewhere in this list* rather than anywhere reorderable.
6540/// Siblings the frame registered no box for are left out.
6541pub fn reorder_siblings<Msg>(
6542 ui: &Ui<Msg>,
6543 root: &dyn Widget<Msg>,
6544 id: WidgetId,
6545) -> Vec<(WidgetId, Rect)> {
6546 fn parent_of<Msg>(
6547 widget: &dyn Widget<Msg>,
6548 own: WidgetId,
6549 target: WidgetId,
6550 ) -> Option<(&dyn Widget<Msg>, WidgetId)> {
6551 for (index, child) in widget.children().iter().enumerate() {
6552 let id = child_id(own, index, child.as_ref());
6553 if id == target {
6554 return Some((widget, own));
6555 }
6556 if let Some(found) = parent_of(child.as_ref(), id, target) {
6557 return Some(found);
6558 }
6559 }
6560 None
6561 }
6562 let Some((parent, parent_id)) = parent_of(root, WidgetId::ROOT, id) else {
6563 return Vec::new();
6564 };
6565 parent
6566 .children()
6567 .iter()
6568 .enumerate()
6569 .filter(|(_, child)| child.reorder_index().is_some() && child.reorder_droppable())
6570 .filter_map(|(index, child)| {
6571 let id = child_id(parent_id, index, child.as_ref());
6572 ui.reorderables
6573 .iter()
6574 .find(|(registered, _)| *registered == id)
6575 .map(|(_, rect)| (id, *rect))
6576 })
6577 .collect()
6578}
6579
6580/// Identity of the **first** widget declaring the key `key` (a hash), or `None`. It is how the
6581/// shell resolves a focus-by-key request (`Command::focus`): the application wraps a field in
6582/// `keyed(k, …)`, then focuses by `k`.
6583pub fn find_by_key<Msg>(root: &dyn Widget<Msg>, key: u64) -> Option<WidgetId> {
6584 fn walk<Msg>(widget: &dyn Widget<Msg>, id: WidgetId, key: u64) -> Option<WidgetId> {
6585 if widget.key() == Some(key) {
6586 return Some(id);
6587 }
6588 for (index, child) in widget.children().iter().enumerate() {
6589 if let Some(found) = walk(child.as_ref(), child_id(id, index, child.as_ref()), key) {
6590 return Some(found);
6591 }
6592 }
6593 None
6594 }
6595 walk(root, WidgetId::ROOT, key)
6596}
6597
6598/// Identity of the **sheet** the key `key` names: the first sheet's panel at or under the
6599/// widget declaring it, which is the identity the sheet's state is kept under and the one the
6600/// frame's sheets are reported by. `None` when nothing declares the key, or nothing under it
6601/// is a sheet.
6602///
6603/// A sheet's state belongs to its panel, which the application never builds itself, so a
6604/// request by key (`Command::sheet`) needs this one step more than a focus request does.
6605pub fn find_sheet_by_key<Msg>(root: &dyn Widget<Msg>, key: u64) -> Option<WidgetId> {
6606 fn first_sheet<Msg>(widget: &dyn Widget<Msg>, id: WidgetId) -> Option<WidgetId> {
6607 if widget.sheet().is_some() {
6608 return Some(id);
6609 }
6610 widget
6611 .children()
6612 .iter()
6613 .enumerate()
6614 .find_map(|(index, child)| {
6615 first_sheet(child.as_ref(), child_id(id, index, child.as_ref()))
6616 })
6617 }
6618 fn walk<Msg>(widget: &dyn Widget<Msg>, id: WidgetId, key: u64) -> Option<WidgetId> {
6619 if widget.key() == Some(key) {
6620 return first_sheet(widget, id);
6621 }
6622 widget
6623 .children()
6624 .iter()
6625 .enumerate()
6626 .find_map(|(index, child)| {
6627 walk(child.as_ref(), child_id(id, index, child.as_ref()), key)
6628 })
6629 }
6630 walk(root, WidgetId::ROOT, key)
6631}
6632
6633/// Path from the **root down to the widget** with identity `target` (`[root, …, target]`), for
6634/// the leaf→root bubbling of keys. Empty when it cannot be found.
6635pub fn find_path<Msg>(root: &dyn Widget<Msg>, target: WidgetId) -> Vec<&dyn Widget<Msg>> {
6636 fn walk<'a, Msg>(
6637 widget: &'a dyn Widget<Msg>,
6638 id: WidgetId,
6639 target: WidgetId,
6640 path: &mut Vec<&'a dyn Widget<Msg>>,
6641 ) -> bool {
6642 path.push(widget);
6643 if id == target {
6644 return true;
6645 }
6646 for (index, child) in widget.children().iter().enumerate() {
6647 if walk(
6648 child.as_ref(),
6649 child_id(id, index, child.as_ref()),
6650 target,
6651 path,
6652 ) {
6653 return true;
6654 }
6655 }
6656 path.pop();
6657 false
6658 }
6659 let mut path = Vec::new();
6660 if !walk(root, WidgetId::ROOT, target, &mut path) {
6661 path.clear();
6662 }
6663 path
6664}
6665
6666/// The theme a subtree inherits at this node — the widget's own override, with any
6667/// **animated text style** the runtime is holding for it laid on top.
6668///
6669/// The one place the theme swap happens, and it is one place on purpose. The swap is made
6670/// four times over a frame — by the layout pass, by the relayout fingerprint that has to
6671/// agree with it or the cache lies, by the paint walk, and by [`build_deferred`] before
6672/// any of them — and every animated value in this framework is read from the runtime by
6673/// whoever consumes it. This one's consumer is the swap itself, so a copy of the rule at
6674/// each of the four sites is four chances to drift. `Responsive` cost three silent bugs
6675/// that way (milestone 495); this is the same lesson written down as a function.
6676///
6677/// Cheap where nothing is animated: no `anim_text_style`, no clone, and the widget's own
6678/// `theme_override` is returned untouched — which is every node but the rare one.
6679pub(crate) fn scoped_theme<Msg>(
6680 widget: &dyn Widget<Msg>,
6681 id: WidgetId,
6682 runtime: &Runtime,
6683 inherited: &Theme,
6684) -> Option<Box<Theme>> {
6685 let own = widget.theme_override(inherited);
6686 let Some(target) = widget.anim_text_style() else {
6687 return own;
6688 };
6689 // Mid-flight if the runtime has a value for this node, and the target otherwise —
6690 // which is the first frame, before the family has been advanced over this tree.
6691 let style = runtime.anim_text_style(id).unwrap_or(target);
6692 let mut theme = own.map_or_else(|| inherited.clone(), |boxed| *boxed);
6693 // **Merged over**, not assigned: the node's own `theme_override` has already put the
6694 // target style and the four unanimated answers (alignment, wrapping, overflow, line
6695 // count) in place, and this replaces field by field exactly what is moving.
6696 theme.widgets.text.style = theme.widgets.text.style.merge(style);
6697 Some(Box::new(theme))
6698}
6699
6700/// Builds what `widget` stands for ([`Widget::expand`]) **under the scopes the node says it
6701/// introduces before it is built** — the surface, the theme, the shell and the scrolling a
6702/// [`MediaScope`](crate::MediaScope) or a [`Themed`](crate::Themed) around a component
6703/// imposes (milestone 642).
6704///
6705/// A wrapper and the component inside it are one node, and the walks ask a node for its
6706/// scopes after building it, since what a component builds may introduce one. That left
6707/// the wrapper's own scope out of the build: `MediaScope::tweak(.., page)` built `page` for
6708/// the whole window, and a scaffold in it read a size it was not laid out in. An unbuilt
6709/// component answers for no scope, so what is asked here is exactly the wrapper's; the walk
6710/// asks again once the component is built, and gets the whole chain.
6711///
6712/// Out of line, so that the walks' recursive frames do not carry what is held here.
6713#[inline(never)]
6714fn expand_scoped<Msg>(widget: &dyn Widget<Msg>, id: WidgetId, runtime: &Runtime, theme: &Theme) {
6715 let _surface = widget
6716 .media_override(crate::MediaQuery::of())
6717 .map(crate::MediaQuery::install);
6718 let _shell = widget.scaffold_override().map(crate::ScaffoldInfo::install);
6719 let _scrolling = widget
6720 .scroll_behavior_override()
6721 .map(crate::ScrollConfiguration::install);
6722 let scoped = scoped_theme(widget, id, runtime, theme);
6723 widget.expand(id, runtime, scoped.as_deref().unwrap_or(theme));
6724}
6725
6726/// Runs the **deferred builds** over a tree, the way the layout pass does on its way down.
6727///
6728/// A [`ThemeBuilder`](crate::ThemeBuilder) — and everything built on one, an
6729/// [`AppBar`](crate::AppBar) included — has no children at all until something calls
6730/// [`Widget::build_themed`] on it. The layout pass does that first thing, so within a frame
6731/// nothing ever meets an unbuilt subtree.
6732///
6733/// **A tree built outside a frame does.** The shell rebuilds from `view` alone on a burst of
6734/// keystrokes, faster than a frame, so the next key sees the current value rather than the
6735/// retained tree's — and then reads that tree straight away. Every traversal that arrives
6736/// there ([`find_widget`], focus resolution, a caret being revealed) walks a tree whose
6737/// deferred subtrees are empty, and silently finds nothing.
6738///
6739/// This is that half of the walk and nothing else: the theme swap
6740/// ([`Widget::theme_override`]) then the build, top-down. The swap is not optional — a
6741/// builder inside a [`Themed`](crate::Themed) has to see its own subtree's theme, and a
6742/// preparation that is *nearly* the walk is worse than none, because what it builds is wrong
6743/// rather than absent.
6744///
6745/// **Which is why it takes a runtime.** A subtree under an animated text style
6746/// (`AnimatedDefaultTextStyle`) inherits a theme that is moving, and a builder inside one
6747/// composes against whatever theme reaches it *first* — this walk. Preparing it against
6748/// the target instead of the value in flight is the same failure as skipping the swap: what
6749/// it builds is wrong rather than absent, and only for as long as the movement lasts, which
6750/// is the hardest kind to see. The runtime is one frame behind here, because this runs
6751/// before the frame advances its animations, and one frame behind is the whole tree agreeing
6752/// with itself rather than a builder disagreeing with the layout around it.
6753pub fn build_deferred<Msg>(root: &dyn Widget<Msg>, theme: &Theme, runtime: &Runtime) {
6754 fn walk<Msg>(widget: &dyn Widget<Msg>, id: WidgetId, runtime: &Runtime, theme: &Theme) {
6755 expand_scoped(widget, id, runtime, theme);
6756 let scoped = scoped_theme(widget, id, runtime, theme);
6757 let theme = scoped.as_deref().unwrap_or(theme);
6758 let _surface = widget
6759 .media_override(crate::MediaQuery::of())
6760 .map(crate::MediaQuery::install);
6761 let _shell = widget.scaffold_override().map(crate::ScaffoldInfo::install);
6762 let _scrolling = widget
6763 .scroll_behavior_override()
6764 .map(crate::ScrollConfiguration::install);
6765 widget.build_in(id, runtime, theme);
6766 for (index, child) in widget.children().iter().enumerate() {
6767 walk(
6768 child.as_ref(),
6769 child_id(id, index, child.as_ref()),
6770 runtime,
6771 theme,
6772 );
6773 }
6774 }
6775 walk(root, WidgetId::ROOT, runtime, theme);
6776}
6777
6778/// The widget of the tree under `root` that has the identity `target`, or `None` if none
6779/// does. Identities are the ones the walk that built the frame gave, so an id read from a
6780/// [`Ui`] finds its widget here.
6781pub fn find_widget<Msg>(root: &dyn Widget<Msg>, target: WidgetId) -> Option<&dyn Widget<Msg>> {
6782 fn walk<Msg>(
6783 widget: &dyn Widget<Msg>,
6784 id: WidgetId,
6785 target: WidgetId,
6786 ) -> Option<&dyn Widget<Msg>> {
6787 if id == target {
6788 return Some(widget);
6789 }
6790 for (index, child) in widget.children().iter().enumerate() {
6791 if let Some(found) = walk(child.as_ref(), child_id(id, index, child.as_ref()), target) {
6792 return Some(found);
6793 }
6794 }
6795 None
6796 }
6797 walk(root, WidgetId::ROOT, target)
6798}
6799
6800/// Folds a filter into the single filtered layer its subtree turned out to be, so two
6801/// filter widgets wrapped one inside the other cost one layer rather than two.
6802///
6803/// It is not only a saving. Compositing renders a layer into a texture and composites
6804/// that texture; a layer *inside* that texture is not composited again, so a nested
6805/// filter would simply not be applied. Folding is what makes `ColorFiltered` around
6806/// `ImageFiltered` mean what it reads as.
6807///
6808/// Everything about the inner layer must be neutral — full opacity, a plain
6809/// rectangular clip, no transform — because those are applied at compositing time and
6810/// there is only one composite to apply them at. And the two filters must not want
6811/// the same slot: greyscale of an inverted picture is not the inversion of a
6812/// greyscale one, so there is no single layer that means both, and the two nest.
6813fn fold_filter(
6814 group: Vec<Primitive>,
6815 filter: LayerFilter,
6816 clip: Rect,
6817) -> (Vec<Primitive>, LayerFilter, Rect) {
6818 if group.len() != 1 {
6819 return (group, filter, clip);
6820 }
6821 let Primitive::Layer {
6822 opacity,
6823 clip: inner_clip,
6824 clip_shape,
6825 transform,
6826 filter: inner,
6827 ..
6828 } = &group[0]
6829 else {
6830 return (group, filter, clip);
6831 };
6832 if *opacity < 0.999 || !matches!(clip_shape, ClipShape::Rect) || transform.is_some() {
6833 return (group, filter, clip);
6834 }
6835 let (inner, inner_clip) = (*inner, *inner_clip);
6836 let Some(merged) = filter.merge(inner) else {
6837 return (group, filter, clip);
6838 };
6839 let Some(Primitive::Layer { primitives, .. }) = group.into_iter().next() else {
6840 unreachable!("checked just above")
6841 };
6842 (primitives, merged, clip.intersect(inner_clip))
6843}
6844
6845#[cfg(test)]
6846mod tests {
6847 use super::*;
6848 use crate::physics::Scrollbars;
6849 use crate::runtime::Edit;
6850 use crate::{
6851 Button, Container, Flex, Key, Keyed, OverlayPortal, Placement, SingleChildScrollView,
6852 TextField,
6853 };
6854 use frus_core::{Color, Point, Primitive, Rect, Size};
6855
6856 /// **A deep tree on the smallest stack any platform gives a frame.**
6857 ///
6858 /// Building a tree recurses twice over it — the layout walk and the scene walk — and
6859 /// what each level costs is a property of those two functions, not of the widgets.
6860 /// Two `Theme` copies in each frame made that cost 53 kilobytes a level, so a tree
6861 /// forty deep exhausted the megabyte a Windows main thread gets and the process died
6862 /// with no panic and no message. A real screen nests further than forty.
6863 ///
6864 /// One megabyte and 64 levels is what this holds to: the platform's smallest stack,
6865 /// against a tree deeper than a screen builds and half again the depth that used to
6866 /// die. It is deliberately not the deepest that fits — around 128 now, at about seven
6867 /// kilobytes a level — because a tripwire wants margin over the number it guards. An
6868 /// overflow aborts rather than fails, so this one kills the run outright, which is the
6869 /// right noise for what it watches.
6870 #[test]
6871 fn a_deep_tree_builds_on_a_platform_s_smallest_stack() {
6872 let built = std::thread::Builder::new()
6873 .stack_size(1024 * 1024)
6874 .spawn(|| {
6875 let mut node: Box<dyn Widget<Msg>> = Box::new(crate::Text::new("the bottom"));
6876 for _ in 0..64 {
6877 node = Box::new(Container::new().padding(1.0).child(node));
6878 }
6879 let ui = build_ui(
6880 node.as_ref(),
6881 Size::new(800.0, 600.0),
6882 &Runtime::default(),
6883 &Theme::default(),
6884 );
6885 ui.scene().primitives().len()
6886 })
6887 .expect("spawning the deep-tree thread")
6888 .join()
6889 .expect("the deep tree was built");
6890 assert!(built > 0, "and it painted something");
6891 }
6892
6893 #[derive(Clone, Debug, PartialEq)]
6894 enum Msg {
6895 A,
6896 B,
6897 C,
6898 D,
6899 Edited(String),
6900 }
6901
6902 #[test]
6903 fn semantics_tree_carries_roles_and_labels() {
6904 use crate::{Button, Checkbox, Role, Text};
6905 let rt = Runtime::default();
6906 let tree = crate::Flex::column()
6907 .child(Text::new("Titre"))
6908 .child(Button::new("Submit").on_press(Msg::A))
6909 .child(Checkbox::new(true).on_toggle(|_| Msg::B));
6910 let ui = build_ui(&tree, Size::new(300.0, 200.0), &rt, &Theme::default());
6911 let sem = ui.semantics();
6912 // One node per meaningful widget (the containing Flex is skipped).
6913 let roles: Vec<Role> = sem.iter().map(|(_, _, s)| s.role).collect();
6914 assert!(roles.contains(&Role::Label));
6915 assert!(roles.contains(&Role::Button));
6916 assert!(roles.contains(&Role::CheckBox));
6917 // The button carries its label and is actionable.
6918 let button = sem.iter().find(|(_, _, s)| s.role == Role::Button).unwrap();
6919 assert_eq!(button.2.label.as_deref(), Some("Submit"));
6920 assert!(button.2.clickable);
6921 // The checked box mirrors its state.
6922 let check = sem
6923 .iter()
6924 .find(|(_, _, s)| s.role == Role::CheckBox)
6925 .unwrap();
6926 assert_eq!(check.2.toggled, crate::Toggled::True);
6927 }
6928
6929 fn clickable_sample() -> Flex<Msg> {
6930 Flex::row()
6931 .width(400.0)
6932 .height(100.0)
6933 .padding(10.0)
6934 .gap(8.0)
6935 .child(
6936 Container::new()
6937 .width(120.0)
6938 .color(Color::rgb(1.0, 0.0, 0.0))
6939 .hover_color(Color::rgb(0.0, 1.0, 0.0))
6940 .on_click(Msg::A),
6941 )
6942 .child(
6943 Container::new()
6944 .flex(1.0)
6945 .color(Color::rgb(0.0, 0.0, 1.0))
6946 .on_click(Msg::B),
6947 )
6948 }
6949
6950 /// A box whose children ran past it is **marked on the screen**, over a tenth of it,
6951 /// on the edge they ran past — and a box whose children fit is left alone.
6952 #[test]
6953 fn an_overflow_paints_a_band_on_the_edge_it_ran_past() {
6954 use crate::{Container, Flex};
6955 // Two children, because a row with one is not dividing a line up — it hands its
6956 // constraints down, and a lone child is bounded by them rather than overflowing.
6957 let row = |child_width: f32| {
6958 let root: Flex<()> = Flex::row()
6959 .width(100.0)
6960 .height(40.0)
6961 .child(
6962 Container::new()
6963 .width(child_width)
6964 .height(20.0)
6965 .color(Color::WHITE),
6966 )
6967 .child(Container::new().width(20.0).height(20.0));
6968 let rt = crate::runtime::Runtime::default();
6969 build_ui(
6970 &root,
6971 Size::new(200.0, 100.0),
6972 &rt,
6973 &crate::theme::Theme::dark(),
6974 )
6975 };
6976 // The stripes are paths; nothing else in this tree draws one.
6977 let stripes = |ui: &Ui<()>| {
6978 ui.scene()
6979 .primitives()
6980 .iter()
6981 .filter(|p| matches!(p, Primitive::Path { .. }))
6982 .count()
6983 };
6984 let over = row(300.0);
6985 assert!(!over.overflows().is_empty(), "the fixture has to overflow");
6986 assert!(stripes(&over) > 2, "striped: {}", stripes(&over));
6987 // The band is on the right-hand tenth: 90..100 of a 100-wide row.
6988 let band = over
6989 .scene()
6990 .primitives()
6991 .iter()
6992 .rev()
6993 .find_map(|p| match p {
6994 Primitive::Rect { rect, color, .. } if color.a > 0.7 && color.r == 0.0 => {
6995 Some(*rect)
6996 }
6997 _ => None,
6998 })
6999 .expect("the band under the stripes");
7000 assert!((band.x - 90.0).abs() < 0.5, "at the right edge: {band:?}");
7001 assert!((band.width - 10.0).abs() < 0.5, "a tenth of it: {band:?}");
7002
7003 let fits = row(40.0);
7004 assert!(fits.overflows().is_empty(), "the fixture has to fit");
7005 assert!(fits.overflows().is_empty());
7006 assert_eq!(stripes(&fits), 0, "nothing to mark");
7007 }
7008
7009 /// The band says **which edge and by how much**, in the reference's words. A striped
7010 /// edge tells you something is too big; the sentence tells you what to look for, and
7011 /// it is the only half of the report that survives being photographed off a device.
7012 #[test]
7013 fn a_band_writes_which_edge_overflowed_and_by_how_much() {
7014 use crate::{Container, Flex};
7015 let root: Flex<()> = Flex::row()
7016 .width(100.0)
7017 .height(40.0)
7018 .child(
7019 Container::new()
7020 .width(300.0)
7021 .height(20.0)
7022 .color(Color::WHITE),
7023 )
7024 .child(Container::new().width(20.0).height(20.0));
7025 let ui = build_ui(
7026 &root,
7027 Size::new(200.0, 100.0),
7028 &Runtime::default(),
7029 &Theme::dark(),
7030 );
7031 // The label is inside the rotated layer, which is why the search is recursive.
7032 fn labels(primitives: &[Primitive], out: &mut Vec<String>) {
7033 for p in primitives {
7034 match p {
7035 Primitive::Text { text, .. } => out.push(text.clone()),
7036 Primitive::Layer { primitives, .. } => labels(primitives, out),
7037 _ => {}
7038 }
7039 }
7040 }
7041 let mut found = Vec::new();
7042 labels(ui.scene().primitives(), &mut found);
7043 assert!(
7044 found.iter().any(|t| t == "RIGHT OVERFLOWED BY 220 PIXELS"),
7045 "the sentence, in the reference's words: {found:?}"
7046 );
7047 }
7048
7049 /// The reference's precision rule: whole pixels when there are many, a decimal when
7050 /// there are few, three significant figures when there is almost nothing — which is
7051 /// the difference between a layout bug and a rounding error.
7052 #[test]
7053 fn an_overflow_is_written_to_the_precision_it_deserves() {
7054 assert_eq!(format_pixels(86.0), "86");
7055 // Past ten pixels the decimal is noise; at ten exactly it is not yet.
7056 assert_eq!(format_pixels(10.4), "10");
7057 assert_eq!(format_pixels(10.0), "10.0");
7058 assert_eq!(format_pixels(4.5), "4.5");
7059 assert_eq!(format_pixels(1.0), "1.00");
7060 assert_eq!(format_pixels(0.5), "0.500");
7061 assert_eq!(format_pixels(0.0123), "0.0123");
7062 }
7063
7064 #[test]
7065 fn rtl_mirrors_row_horizontally() {
7066 let size = Size::new(400.0, 100.0);
7067 // A = a fixed 120 px button (on the left in LTR), B = the flexible remainder.
7068 let ltr = build_ui(
7069 &clickable_sample(),
7070 size,
7071 &Runtime::default(),
7072 &Theme::default(),
7073 );
7074 let rtl = build_ui(
7075 &clickable_sample(),
7076 size,
7077 &Runtime::default(),
7078 &Theme::default().rtl(),
7079 );
7080 let hit = |ui: &Ui<Msg>, x: f32| ui.hit(Point::new(x, 50.0)).and_then(|id| ui.msg_for(id));
7081
7082 // LTR: button A takes the left edge.
7083 assert_eq!(hit(<r, 40.0), Some(Msg::A));
7084 assert_eq!(hit(<r, 360.0), Some(Msg::B));
7085 // RTL: everything is mirrored — A moves to the right, B takes the left.
7086 assert_eq!(hit(&rtl, 360.0), Some(Msg::A), "A on the right in RTL");
7087 assert_eq!(hit(&rtl, 40.0), Some(Msg::B), "B on the left in RTL");
7088 }
7089
7090 #[test]
7091 fn wrapped_text_wraps_in_layout_and_invalidates_the_cache() {
7092 let tree = |text: &str| {
7093 crate::Flex::column()
7094 .width(120.0)
7095 .child(crate::Text::new(text).wrap())
7096 .child(Container::new().height(10.0).on_click(Msg::A))
7097 };
7098 // Position of the clickable follower: the first y hit while sweeping.
7099 let follower_y = |ui: &Ui<Msg>| {
7100 (0..600)
7101 .map(|y| y as f32)
7102 .find(|&y| ui.hit(Point::new(60.0, y)).is_some())
7103 .expect("suiveur cliquable")
7104 };
7105
7106 let rt = Runtime::default();
7107 let long = "a rather long paragraph that will wrap onto several lines";
7108 let ui = build_ui(&tree(long), Size::new(120.0, 600.0), &rt, &Theme::default());
7109
7110 // The paragraph's render carries its wrap width (≤ the column).
7111 let max_w = ui
7112 .scene()
7113 .primitives()
7114 .iter()
7115 .find_map(|p| match p {
7116 Primitive::Text { max_width, .. } => *max_width,
7117 _ => None,
7118 })
7119 .expect("a wrapped paragraph");
7120 assert!(max_w <= 120.5, "wrapped to the column width: {max_w}");
7121
7122 // The wrapped text takes several lines: the follower is pushed down.
7123 let y_long = follower_y(&ui);
7124 assert!(
7125 y_long > 30.0,
7126 "the follower is pushed down by the wrap: {y_long}"
7127 );
7128
7129 // The SAME structure/styles, different content, the SAME runtime (a warm cache): the
7130 // measure key must invalidate the cache — otherwise the rects would be stale.
7131 let ui2 = build_ui(
7132 &tree("short"),
7133 Size::new(120.0, 600.0),
7134 &rt,
7135 &Theme::default(),
7136 );
7137 let y_short = follower_y(&ui2);
7138 assert!(
7139 y_short < y_long,
7140 "shorter content → a higher follower (the cache was invalidated): {y_short} vs {y_long}"
7141 );
7142 }
7143
7144 #[test]
7145 fn relayout_cache_reuses_the_root_layout_across_frames() {
7146 let rt = Runtime::default();
7147 let size = Size::new(400.0, 100.0);
7148 // Frame 1: nothing cached → a recomputation (at least the root).
7149 let _ = build_ui(&clickable_sample(), size, &rt, &Theme::default());
7150 let (hits1, misses1) = rt.layout_cache.borrow().last_frame_stats();
7151 assert_eq!(hits1, 0, "1st frame: nothing reused");
7152 assert!(misses1 >= 1, "1st frame: at least one computation");
7153
7154 // Frame 2: the same tree, the same constraints → the root is reused.
7155 let _ = build_ui(&clickable_sample(), size, &rt, &Theme::default());
7156 let (hits2, misses2) = rt.layout_cache.borrow().last_frame_stats();
7157 assert_eq!(hits2, 1, "2nd frame: the root is reused");
7158 assert_eq!(misses2, 0, "2nd frame: nothing recomputed");
7159
7160 // Frame 3: the window is resized → the constraints change → a recomputation.
7161 let _ = build_ui(
7162 &clickable_sample(),
7163 Size::new(500.0, 100.0),
7164 &rt,
7165 &Theme::default(),
7166 );
7167 let (hits3, misses3) = rt.layout_cache.borrow().last_frame_stats();
7168 assert_eq!((hits3, misses3), (0, 1), "redimensionnement → recalcul");
7169 }
7170
7171 #[test]
7172 fn modal_traps_tab_arrows_and_pointer_focus() {
7173 use crate::portal::{OverlayPortal, Placement};
7174 // The background: two focusable buttons; the open modal: two buttons as well.
7175 let dialog = Flex::<Msg>::row()
7176 .child(Button::new("ok").on_press(Msg::C))
7177 .child(Button::new("no").on_press(Msg::D));
7178 let tree: Flex<Msg> = Flex::column()
7179 .child(Button::new("bg1").on_press(Msg::A))
7180 .child(Button::new("bg2").on_press(Msg::B))
7181 .child(
7182 OverlayPortal::new(Container::new())
7183 .overlay(dialog, Placement::Center)
7184 .dismiss(Msg::A),
7185 );
7186 let ui = build_ui(
7187 &tree,
7188 Size::new(400.0, 300.0),
7189 &Runtime::default(),
7190 &Theme::default(),
7191 );
7192
7193 // Tab enters the trap (the modal's first focusable) and cycles inside it.
7194 let first = ui.focus_next(None, true).expect("the scope's first");
7195 assert_eq!(ui.msg_for(first), Some(Msg::C));
7196 let second = ui.focus_next(Some(first), true).expect("suivant");
7197 assert_eq!(ui.msg_for(second), Some(Msg::D));
7198 let wrapped = ui.focus_next(Some(second), true).expect("boucle");
7199 assert_eq!(
7200 ui.msg_for(wrapped),
7201 Some(Msg::C),
7202 "Tab cycles inside the modal"
7203 );
7204
7205 // The arrows stay inside the scope: there is nothing above the dialog.
7206 assert_eq!(ui.focus_directional(first, FocusDirection::Up), None);
7207 let right = ui
7208 .focus_directional(first, FocusDirection::Right)
7209 .expect("to the right");
7210 assert_eq!(ui.msg_for(right), Some(Msg::D));
7211
7212 // Click-to-focus ignores the background (the bg1 button is at the top left).
7213 assert_eq!(
7214 ui.focus_hit(Point::new(10.0, 10.0)),
7215 None,
7216 "fond hors scope"
7217 );
7218
7219 // Without a modal: no trap, Tab starts at the background.
7220 let open_less: Flex<Msg> = Flex::column()
7221 .child(Button::new("bg1").on_press(Msg::A))
7222 .child(Button::new("bg2").on_press(Msg::B));
7223 let ui2 = build_ui(
7224 &open_less,
7225 Size::new(400.0, 300.0),
7226 &Runtime::default(),
7227 &Theme::default(),
7228 );
7229 let f = ui2.focus_next(None, true).expect("premier");
7230 assert_eq!(ui2.msg_for(f), Some(Msg::A));
7231 }
7232
7233 #[test]
7234 fn open_menu_traps_focus_in_its_items() {
7235 use crate::PopupMenuButton;
7236 // A focusable background plus an **open** menu (anchor + two items).
7237 let menu = PopupMenuButton::new(Button::new("open").on_press(Msg::A), true, Msg::D)
7238 .item("one", Msg::B)
7239 .item("two", Msg::C);
7240 let tree: Flex<Msg> = Flex::column()
7241 .child(Button::new("bg").on_press(Msg::A))
7242 .child(menu);
7243 let ui = build_ui(
7244 &tree,
7245 Size::new(400.0, 300.0),
7246 &Runtime::default(),
7247 &Theme::default(),
7248 );
7249
7250 // Tab enters the menu's items and **cycles** inside (background and anchor are out of scope).
7251 let first = ui.focus_next(None, true).expect("the scope's first");
7252 assert_eq!(ui.msg_for(first), Some(Msg::B));
7253 let second = ui.focus_next(Some(first), true).expect("suivant");
7254 assert_eq!(ui.msg_for(second), Some(Msg::C));
7255 let wrapped = ui.focus_next(Some(second), true).expect("boucle");
7256 assert_eq!(
7257 ui.msg_for(wrapped),
7258 Some(Msg::B),
7259 "Tab cycles inside the open menu"
7260 );
7261 // The background (top left) is out of scope while the menu is open.
7262 assert_eq!(
7263 ui.focus_hit(Point::new(10.0, 10.0)),
7264 None,
7265 "fond hors scope"
7266 );
7267
7268 // The menu **closed**: no trap, Tab starts at the background.
7269 let closed: Flex<Msg> = Flex::column()
7270 .child(Button::new("bg").on_press(Msg::A))
7271 .child(PopupMenuButton::new(
7272 Button::new("open").on_press(Msg::B),
7273 false,
7274 Msg::D,
7275 ));
7276 let ui2 = build_ui(
7277 &closed,
7278 Size::new(400.0, 300.0),
7279 &Runtime::default(),
7280 &Theme::default(),
7281 );
7282 let f = ui2.focus_next(None, true).expect("premier");
7283 assert_eq!(ui2.msg_for(f), Some(Msg::A), "with no open menu, no trap");
7284 }
7285
7286 #[test]
7287 fn escape_infrastructure_finds_path_and_topmost_dismiss() {
7288 use crate::portal::{OverlayPortal, Placement};
7289 // An open portal (a modal with a dismissal) around a clickable anchor.
7290 let anchor = Container::<Msg>::new()
7291 .width(50.0)
7292 .height(30.0)
7293 .on_click(Msg::A);
7294 let content = Container::<Msg>::new()
7295 .width(80.0)
7296 .height(40.0)
7297 .on_click(Msg::B);
7298 let portal = OverlayPortal::new(anchor)
7299 .overlay(content, Placement::Center)
7300 .dismiss(Msg::C);
7301 let tree: Flex<Msg> = Flex::column().child(portal);
7302
7303 let ui = build_ui(
7304 &tree,
7305 Size::new(300.0, 200.0),
7306 &Runtime::default(),
7307 &Theme::default(),
7308 );
7309 // The topmost dismissal is the portal's.
7310 assert_eq!(ui.top_dismiss(), Some(Msg::C));
7311
7312 // Focus "inside the dialog": the root→content path goes through the portal, which
7313 // consumes Escape while bubbling. (The Center content, 80×40, is centred in 300×200 →
7314 // its centre is at (150, 100).)
7315 let inner = ui
7316 .hit(Point::new(150.0, 100.0))
7317 .expect("contenu de la modale");
7318 let path = find_path(&tree, inner);
7319 assert!(path.len() >= 3, "root, portal, content: {}", path.len());
7320 assert_eq!(
7321 path.last().unwrap().on_click(),
7322 Some(Msg::B),
7323 "the target closes the path"
7324 );
7325 let consumed = path
7326 .iter()
7327 .rev()
7328 .find_map(|w| match w.on_key(&crate::Key::Escape) {
7329 crate::KeyResponse::Handled(msg) => Some(msg),
7330 _ => None,
7331 });
7332 assert_eq!(
7333 consumed,
7334 Some(Some(Msg::C)),
7335 "the portal consumes Escape while bubbling"
7336 );
7337
7338 // Chemin introuvable → vide ; pas d'overlay → pas de fermeture.
7339 assert!(find_path(&tree, WidgetId::ROOT.child(99)).is_empty());
7340 let closed: Flex<Msg> = Flex::column().child(Container::new().on_click(Msg::A));
7341 let ui2 = build_ui(
7342 &closed,
7343 Size::new(300.0, 200.0),
7344 &Runtime::default(),
7345 &Theme::default(),
7346 );
7347 assert_eq!(ui2.top_dismiss(), None);
7348 }
7349
7350 #[test]
7351 fn long_press_targets_are_collected_topmost_first() {
7352 // A long-press container holding a long-press child: a point inside the child returns
7353 // the child's message (the topmost one).
7354 let tree: Container<Msg> = Container::new()
7355 .width(200.0)
7356 .height(100.0)
7357 .on_long_press(Msg::A)
7358 .child(
7359 Container::new()
7360 .width(50.0)
7361 .height(50.0)
7362 .on_long_press(Msg::B),
7363 );
7364 let ui = build_ui(
7365 &tree,
7366 Size::new(200.0, 100.0),
7367 &Runtime::default(),
7368 &Theme::default(),
7369 );
7370 assert_eq!(ui.long_press_at(Point::new(25.0, 25.0)), Some(Msg::B));
7371 assert_eq!(ui.long_press_at(Point::new(150.0, 80.0)), Some(Msg::A));
7372 assert_eq!(ui.long_press_at(Point::new(500.0, 500.0)), None);
7373 }
7374
7375 #[test]
7376 fn hit_and_msg_for_route_correctly() {
7377 let rt = Runtime::default();
7378 let ui = build_ui(
7379 &clickable_sample(),
7380 Size::new(400.0, 100.0),
7381 &rt,
7382 &Theme::default(),
7383 );
7384 let id_a = ui.hit(Point::new(50.0, 50.0)).expect("A");
7385 let id_b = ui.hit(Point::new(300.0, 50.0)).expect("B");
7386 assert_ne!(id_a, id_b);
7387 assert_eq!(ui.msg_for(id_a), Some(Msg::A));
7388 assert_eq!(ui.msg_for(id_b), Some(Msg::B));
7389 assert_eq!(ui.hit(Point::new(3.0, 3.0)), None);
7390 }
7391
7392 /// Every rectangle a frame paints down the right-hand edge of a 200-wide viewport.
7393 /// The bar is drawn last, over the content, and it is the only thing over there.
7394 fn painted(ui: &Ui<()>) -> Vec<(Rect, Color)> {
7395 ui.scene()
7396 .primitives()
7397 .iter()
7398 .filter_map(|p| match p {
7399 Primitive::Rect { rect, color, .. }
7400 if rect.x >= 200.0 - BAR_SIZE - BAR_MARGIN * 2.0 =>
7401 {
7402 Some((*rect, *color))
7403 }
7404 _ => None,
7405 })
7406 .collect()
7407 }
7408
7409 /// A runtime, and a scroll behaviour in force for as long as the guard lives, that
7410 /// draws scrollbars — one that follows a desktop — or does not.
7411 fn bars_runtime(how: Scrollbars) -> (Runtime, crate::ScrollBehaviorGuard) {
7412 let behavior = match how {
7413 Scrollbars::Always => {
7414 crate::ScrollBehavior::new().with_platform(frus_core::TargetPlatform::Linux)
7415 }
7416 Scrollbars::Never => crate::ScrollBehavior::new().with_scrollbars(false),
7417 };
7418 (
7419 Runtime::default(),
7420 crate::ScrollConfiguration::install(behavior),
7421 )
7422 }
7423
7424 /// A tall page in a short window, its bar **pinned**: whether a bar fades is the
7425 /// business of the tests below, and these are about whether there is one to fade.
7426 fn bars(area: SingleChildScrollView<()>, how: Scrollbars) -> Vec<(Rect, Color)> {
7427 let (runtime, _bars) = bars_runtime(how);
7428 let ui = build_ui(
7429 &area.thumb_visibility(true),
7430 Size::new(200.0, 100.0),
7431 &runtime,
7432 &Theme::dark(),
7433 );
7434 painted(&ui)
7435 }
7436
7437 /// **Under an Android theme, the platform's own bar** (`scrollbar.dart:331`, milestone
7438 /// 617): 4 px instead of 8, flush with the edge instead of 2 px in, square instead of
7439 /// a pill, an opaque grey at rest instead of a fade of the content colour, and nothing
7440 /// a pointer can take hold of — whatever this test runs on.
7441 #[test]
7442 fn an_android_theme_draws_the_android_bar() {
7443 let (runtime, _bars) = bars_runtime(Scrollbars::Always);
7444 let laid = |platform: frus_core::TargetPlatform| {
7445 let ui = build_ui(
7446 &tall().thumb_visibility(true),
7447 Size::new(200.0, 100.0),
7448 &runtime,
7449 &Theme::dark().with_platform(platform),
7450 );
7451 let thumb = ui
7452 .scene()
7453 .primitives()
7454 .iter()
7455 .find_map(|p| match p {
7456 Primitive::Rect {
7457 rect,
7458 color,
7459 radius,
7460 ..
7461 } if rect.x >= 200.0 - BAR_SIZE - BAR_MARGIN * 2.0 => {
7462 Some((*rect, *color, radius.top_left))
7463 }
7464 _ => None,
7465 })
7466 .expect("a thumb");
7467 let bar = ui.scrollbars()[0];
7468 let center = Point::new(
7469 bar.thumb.x + bar.thumb.width / 2.0,
7470 bar.thumb.y + bar.thumb.height / 2.0,
7471 );
7472 (
7473 thumb,
7474 bar.interactive,
7475 ui.scrollbar_at(center).is_some(),
7476 ui.scrollbar_near(center).is_some(),
7477 )
7478 };
7479 let ((rect, color, radius), interactive, grabbed, woken) =
7480 laid(frus_core::TargetPlatform::Android);
7481 assert_eq!(
7482 (rect.width, rect.x + rect.width),
7483 (4.0, 200.0),
7484 "4 px, flush"
7485 );
7486 assert_eq!(radius, 0.0, "square ends");
7487 assert_eq!(color, ANDROID_THUMB_ON_DARK, "an opaque grey at rest");
7488 assert!(
7489 !interactive && !grabbed && !woken,
7490 "nothing to take hold of"
7491 );
7492
7493 let ((rect, color, radius), interactive, grabbed, woken) =
7494 laid(frus_core::TargetPlatform::Linux);
7495 assert_eq!(
7496 (rect.width, rect.x + rect.width),
7497 (8.0, 198.0),
7498 "8 px, 2 px in"
7499 );
7500 assert_eq!(radius, 4.0, "a pill");
7501 assert!(color.a < 1.0, "a fade of the content colour");
7502 assert!(
7503 interactive && grabbed && woken,
7504 "a pointer takes hold of it"
7505 );
7506 }
7507
7508 /// **A theme's word outranks the platform's** on an Android theme too: a bar it makes
7509 /// interactive is one, and a colour it chose is the one at rest.
7510 #[test]
7511 fn an_android_bar_takes_the_theme_s_word() {
7512 let (runtime, _bars) = bars_runtime(Scrollbars::Always);
7513 let mut theme = Theme::dark().with_platform(frus_core::TargetPlatform::Android);
7514 theme.widgets.scrollbar.interactive = Some(true);
7515 theme.widgets.scrollbar.thumb_color = Some(Color::rgb(1.0, 0.0, 0.0));
7516 let ui = build_ui(
7517 &tall().thumb_visibility(true),
7518 Size::new(200.0, 100.0),
7519 &runtime,
7520 &theme,
7521 );
7522 let bar = ui.scrollbars()[0];
7523 assert!(bar.interactive);
7524 let color = painted(&ui)[0].1;
7525 assert_eq!((color.r, color.g, color.b), (1.0, 0.0, 0.0));
7526 }
7527
7528 /// A tall column in a short viewport: something to scroll.
7529 fn tall() -> SingleChildScrollView<()> {
7530 SingleChildScrollView::new()
7531 .width(200.0)
7532 .height(100.0)
7533 .child(Container::<()>::new().width(200.0).height(1000.0))
7534 }
7535
7536 /// **A touch screen gets no scrollbar** (`app.dart:870`).
7537 ///
7538 /// This drew one on every platform, on both axes, always — a permanent bar over the
7539 /// content of every scrolling page on a phone, where the reference draws nothing at
7540 /// all. A finger already knows where it is on the page.
7541 #[test]
7542 fn a_touch_screen_gets_no_scrollbar() {
7543 assert_eq!(bars(tall(), Scrollbars::Never), vec![]);
7544 assert_eq!(
7545 bars(tall(), Scrollbars::Always).len(),
7546 1,
7547 "and a desktop gets one"
7548 );
7549
7550 // Nothing to drag, either: a bar that is not drawn is not a target.
7551 let (runtime, _bars) = bars_runtime(Scrollbars::Never);
7552 let ui = build_ui(&tall(), Size::new(200.0, 100.0), &runtime, &Theme::dark());
7553 assert!(ui.scrollbars().is_empty());
7554 }
7555
7556 /// **A bar takes the scheme's word for the brightness, not the surface's luminance.**
7557 ///
7558 /// The opacities either side of this are three times apart at rest (`scrollbar.dart:242`,
7559 /// `:248`), so getting the question wrong is not a shade — it is a bar that reads as
7560 /// a smudge, or one that reads as a stripe.
7561 ///
7562 /// A **dimmed light** scheme is where the two answers part. The measurement it used
7563 /// to make says dark; the scheme says light, and the scheme is the one that knows.
7564 #[test]
7565 fn a_bar_reads_the_scheme_s_brightness_and_not_its_luminance() {
7566 use crate::media::Brightness;
7567 let dimmed = |brightness| {
7568 let mut theme = Theme::light();
7569 theme.scheme.surface = Color::rgb8(110, 110, 110);
7570 theme.scheme.brightness = brightness;
7571 theme
7572 };
7573 let thumb = |theme: &Theme| {
7574 let (runtime, _bars) = bars_runtime(Scrollbars::Always);
7575 let ui = build_ui(
7576 &tall().thumb_visibility(true),
7577 Size::new(200.0, 100.0),
7578 &runtime,
7579 theme,
7580 );
7581 painted(&ui)[0].1
7582 };
7583
7584 let light = dimmed(Brightness::Light);
7585 assert!(
7586 light.scheme.surface.compute_luminance() < 0.5,
7587 "the luminance the old line measured says dark"
7588 );
7589 assert_eq!(
7590 thumb(&light),
7591 light.scheme.on_surface.fade(THUMB_ON_LIGHT),
7592 "and the bar takes the scheme's word instead"
7593 );
7594
7595 let dark = dimmed(Brightness::Dark);
7596 assert_eq!(thumb(&dark), dark.scheme.on_surface.fade(THUMB_ON_DARK));
7597 }
7598
7599 /// **A theme reaches every number the bar is made of**, not only its colour. A
7600 /// scrollbar themed in its colour and sized from a constant is themed in the half
7601 /// that shows and unthemed in the half a pointer has to hit.
7602 ///
7603 /// There is no per-call override to outrank here — nobody configures a scrollbar at a
7604 /// call site, the walk draws it — so the chain is `theme ?? framework`, and the second
7605 /// half of this test is that the framework still answers where the theme says nothing.
7606 #[test]
7607 fn a_theme_reaches_every_number_the_scrollbar_is_made_of() {
7608 const THUMB: Color = Color::rgb(0.2, 0.7, 0.9);
7609 let mut theme = Theme::dark();
7610 theme.widgets.scrollbar.thickness = Some(14.0);
7611 theme.widgets.scrollbar.margin = Some(5.0);
7612 theme.widgets.scrollbar.min_thumb_length = Some(90.0);
7613 theme.widgets.scrollbar.radius = Some(2.0);
7614 theme.widgets.scrollbar.thumb_color = Some(THUMB);
7615 theme.widgets.scrollbar.opacity = Some(0.8);
7616
7617 let (runtime, _bars) = bars_runtime(Scrollbars::Always);
7618 let ui = build_ui(
7619 &tall().thumb_visibility(true),
7620 Size::new(200.0, 100.0),
7621 &runtime,
7622 &theme,
7623 );
7624 // `painted` filters on the strip a bar of the **default** thickness occupies, so
7625 // it cannot see a themed one — which is the point of the theme. This asks for the
7626 // strip the themed bar is in.
7627 let over_there: Vec<(Rect, Color)> = ui
7628 .scene()
7629 .primitives()
7630 .iter()
7631 .filter_map(|p| match p {
7632 Primitive::Rect { rect, color, .. } if rect.x >= 200.0 - 14.0 - 5.0 * 2.0 => {
7633 Some((*rect, *color))
7634 }
7635 _ => None,
7636 })
7637 .collect();
7638 assert_eq!(over_there.len(), 1, "still one rectangle: the thumb");
7639 let (thumb, color) = over_there[0];
7640 assert!(
7641 (thumb.width - 14.0).abs() < 0.01,
7642 "the theme's thickness: {thumb:?}"
7643 );
7644 assert!(
7645 ((thumb.x + thumb.width) - (200.0 - 5.0)).abs() < 0.01,
7646 "held clear by the theme's margin, not shrunk to fit: {thumb:?}"
7647 );
7648 assert!(
7649 thumb.height >= 90.0,
7650 "and never shorter than the theme's floor: {thumb:?}"
7651 );
7652 assert_eq!(
7653 color,
7654 THUMB.fade(0.8),
7655 "the theme's colour, faded to the theme's resting level"
7656 );
7657
7658 // The radius is not in `painted`, which reads the rectangles' colours; take it
7659 // from the primitive itself. A pill is what an unthemed bar is, and this one is
7660 // not a pill.
7661 let radius = ui.scene().primitives().iter().find_map(|p| match p {
7662 Primitive::Rect { radius, .. } if radius.top_left > 0.0 => Some(radius.top_left),
7663 _ => None,
7664 });
7665 assert_eq!(radius, Some(2.0), "the theme's corner radius");
7666
7667 // And with a theme that says nothing, the framework still answers.
7668 let plain = bars(tall(), Scrollbars::Always);
7669 let (thumb, color) = plain[0];
7670 assert!((thumb.width - BAR_SIZE).abs() < 0.01);
7671 assert_eq!(color, Theme::dark().scheme.on_surface.fade(THUMB_ON_DARK));
7672 }
7673
7674 /// **And it is a thumb and nothing else** (`scrollbar.dart:281`): the reference's
7675 /// track is transparent unless a caller asks for one, and even then it is 3 to 5 %.
7676 /// This painted an 18 % stripe down every scrolling page, under a 55 % thumb.
7677 #[test]
7678 fn a_bar_is_a_thumb_and_no_track() {
7679 let painted = bars(tall(), Scrollbars::Always);
7680 assert_eq!(painted.len(), 1, "one rectangle: the thumb");
7681 let (thumb, color) = painted[0];
7682 assert!(
7683 (thumb.width - BAR_SIZE).abs() < 0.01,
7684 "at the reference's thickness: {thumb:?}"
7685 );
7686 assert!(
7687 ((thumb.x + thumb.width) - (200.0 - BAR_MARGIN)).abs() < 0.01,
7688 "and clear of the edge by `crossAxisMargin`, not shrunk to fit: {thumb:?}"
7689 );
7690 assert!(
7691 thumb.height >= MIN_THUMB,
7692 "and never shorter than a pointer can catch: {thumb:?}"
7693 );
7694 let theme = Theme::dark();
7695 assert_eq!(color, theme.scheme.on_surface.fade(THUMB_ON_DARK));
7696 }
7697
7698 /// **Along the horizontal axis, never** (`app.dart:861`) — on any platform, under any
7699 /// setting. A sideways strip is scrolled by whatever made it sideways, and a bar
7700 /// under it takes room from content that is short of it already.
7701 #[test]
7702 fn a_sideways_strip_never_gets_one() {
7703 let strip = SingleChildScrollView::new()
7704 .axis(crate::scroll::Axis::Horizontal)
7705 .width(200.0)
7706 .height(100.0)
7707 .child(Container::<()>::new().width(1000.0).height(100.0));
7708 let (runtime, _bars) = bars_runtime(Scrollbars::Always);
7709 let ui = build_ui(&strip, Size::new(200.0, 100.0), &runtime, &Theme::dark());
7710 assert!(
7711 ui.scrollbars().is_empty(),
7712 "a desktop draws none across, either"
7713 );
7714 }
7715
7716 /// And **one area may answer for itself**, over the application's answer — the
7717 /// per-area say the physics beside it already had.
7718 #[test]
7719 fn an_area_may_ask_for_its_own_answer() {
7720 assert_eq!(
7721 bars(tall().scrollbars(Scrollbars::Always), Scrollbars::Never).len(),
7722 1,
7723 "asked for one where the platform gives none"
7724 );
7725 assert_eq!(
7726 bars(tall().scrollbars(Scrollbars::Never), Scrollbars::Always),
7727 vec![],
7728 "and refused one where it does"
7729 );
7730 }
7731
7732 /// **A bar nobody has scrolled is not there at all.** The reference's fade starts
7733 /// closed and is opened only by movement (`scrollbar.dart:1960`); a list that has
7734 /// just appeared shows its content, not its furniture.
7735 ///
7736 /// It is **registered** even so, which a bar the platform does not draw is not. The
7737 /// difference is real: that one is not there, and this one is here and invisible —
7738 /// and a mouse coming near it is the only thing that can bring it back.
7739 #[test]
7740 fn an_untouched_area_shows_no_bar_but_can_still_be_reached_for() {
7741 let (runtime, _bars) = bars_runtime(Scrollbars::Always);
7742 let ui = build_ui(&tall(), Size::new(200.0, 100.0), &runtime, &Theme::dark());
7743 assert_eq!(painted(&ui), vec![], "nothing is painted for it");
7744
7745 let bar = *ui.scrollbars().first().expect("registered all the same");
7746 assert_eq!(bar.opacity, 0.0);
7747 let on_it = Point::new(194.0, 20.0);
7748 assert!(
7749 ui.scrollbar_at(on_it).is_none(),
7750 "and a bar at zero cannot be grabbed"
7751 );
7752 assert!(
7753 ui.scrollbar_near(on_it).is_some(),
7754 "but it can be reached for, which is what brings it back"
7755 );
7756 // The reach is wider than the bar: 8 pixels at a tenth of an opacity is not
7757 // something a hand aims at precisely.
7758 assert!(
7759 ui.scrollbar_near(Point::new(178.0, 20.0)).is_some(),
7760 "the reach takes in a tap target's room around the thumb: {:?}",
7761 bar.reach
7762 );
7763 }
7764
7765 /// **A pinned bar does not fade** (`scrollbar.dart:214`) — for an area whose content
7766 /// does not look scrollable, or one a reader should be able to aim at without
7767 /// scrolling first to make the bar appear.
7768 #[test]
7769 fn a_pinned_bar_does_not_fade() {
7770 let (runtime, _bars) = bars_runtime(Scrollbars::Always);
7771 let ui = build_ui(
7772 &tall().thumb_visibility(true),
7773 Size::new(200.0, 100.0),
7774 &runtime,
7775 &Theme::dark(),
7776 );
7777 assert_eq!(painted(&ui).len(), 1, "there without being scrolled to");
7778 assert_eq!(ui.scrollbars()[0].opacity, 1.0);
7779 }
7780
7781 /// **A thumb under a pointer, and a thumb in a hand**, are two different colours
7782 /// (`scrollbar.dart:245`, `:244`) — and neither is the resting one. The dragged
7783 /// value arrives at once: the hand is already on it.
7784 #[test]
7785 fn a_thumb_answers_the_pointer() {
7786 use crate::runtime::ScrollbarFade;
7787 let build = |prime: &dyn Fn(&mut Runtime)| {
7788 let (mut runtime, _bars) = bars_runtime(Scrollbars::Always);
7789 prime(&mut runtime);
7790 let ui = build_ui(
7791 &tall().thumb_visibility(true),
7792 Size::new(200.0, 100.0),
7793 &runtime,
7794 &Theme::dark(),
7795 );
7796 let id = ui.scrollbars()[0].id;
7797 (id, painted(&ui)[0].1)
7798 };
7799
7800 let theme = Theme::dark();
7801 let (id, resting) = build(&|_| {});
7802 assert_eq!(resting, theme.scheme.on_surface.fade(THUMB_ON_DARK));
7803
7804 let (_, warmed) = build(&|rt| {
7805 rt.scrollbar_fade.insert(
7806 id,
7807 ScrollbarFade {
7808 opacity: 1.0,
7809 hover: 1.0,
7810 ..ScrollbarFade::default()
7811 },
7812 );
7813 });
7814 assert_eq!(warmed, theme.scheme.on_surface.fade(THUMB_HOVER_ON_DARK));
7815
7816 let (_, grabbed) = build(&|rt| rt.scrollbar_dragged = Some(id));
7817 assert_eq!(grabbed, theme.scheme.on_surface.fade(THUMB_DRAG_ON_DARK));
7818 }
7819
7820 #[test]
7821 fn hover_progress_interpolates_color() {
7822 let rt = Runtime::default();
7823 let base = build_ui(
7824 &clickable_sample(),
7825 Size::new(400.0, 100.0),
7826 &rt,
7827 &Theme::default(),
7828 );
7829 let id_a = base.hit(Point::new(50.0, 50.0)).unwrap();
7830
7831 // Without any progress: the base colour (red).
7832 if let Primitive::Rect { color, .. } = base.scene().primitives()[0] {
7833 assert_eq!(color, Color::rgb(1.0, 0.0, 0.0));
7834 } else {
7835 panic!("expected a rect");
7836 }
7837
7838 // Full progress: the hover colour (green).
7839 let mut rt = Runtime::default();
7840 rt.input.hovered = Some(id_a);
7841 rt.anims.insert(
7842 id_a,
7843 crate::Anim {
7844 hover: 1.0,
7845 ..Default::default()
7846 },
7847 );
7848 let ui = build_ui(
7849 &clickable_sample(),
7850 Size::new(400.0, 100.0),
7851 &rt,
7852 &Theme::default(),
7853 );
7854 if let Primitive::Rect { color, .. } = ui.scene().primitives()[0] {
7855 assert_eq!(color, Color::rgb(0.0, 1.0, 0.0));
7856 } else {
7857 panic!("expected a rect");
7858 }
7859 }
7860
7861 #[test]
7862 fn multiline_field_registers_as_scrollable_when_overflowing() {
7863 // A multi-line field whose content exceeds `rows` registers itself as a scrollable
7864 // area (with `max_y > 0`) — which is what the wheel and the scrollbar target. A short
7865 // field does not register.
7866 let tall = TextField::<Msg>::new("a\nb\nc\nd\ne\nf")
7867 .on_input(Msg::Edited)
7868 .rows(2)
7869 .width(200.0);
7870 let tree: Flex<Msg> = Flex::column().child(tall);
7871 let rt = Runtime::default();
7872 let ui = build_ui(&tree, Size::new(220.0, 240.0), &rt, &Theme::default());
7873 let maxes = ui.scrollable_maxes();
7874 assert_eq!(maxes.len(), 1, "the overflowing field registers");
7875 assert!(maxes[0].2 > 0.0, "max_y > 0 (overflowing content)");
7876
7877 let short = TextField::<Msg>::new("a\nb")
7878 .on_input(Msg::Edited)
7879 .rows(4)
7880 .width(200.0);
7881 let tree: Flex<Msg> = Flex::column().child(short);
7882 let ui = build_ui(&tree, Size::new(220.0, 240.0), &rt, &Theme::default());
7883 assert!(
7884 ui.scrollable_maxes().is_empty(),
7885 "a short field does not scroll"
7886 );
7887 }
7888
7889 #[test]
7890 fn only_text_inputs_place_a_cursor() {
7891 // The invariant of the click fix (milestone 39): a focusable button returns NO cursor
7892 // (`cursor_at` = None), so the shell does not start a text selection on it and does not
7893 // capture the click. Only text fields place one.
7894 let button = Button::<Msg>::new("x").on_press(Msg::A);
7895 assert_eq!(Widget::<Msg>::cursor_at(&button, 10.0, 5.0, 200.0, 0), None);
7896 let input = TextField::<Msg>::new("hi").on_input(Msg::Edited);
7897 assert!(Widget::<Msg>::cursor_at(&input, 10.0, 5.0, 200.0, 0).is_some());
7898 }
7899
7900 /// A form taller than its window: six buttons of 60 px in a 150 px scroll.
7901 fn long_form() -> SingleChildScrollView<Msg> {
7902 let mut column = Flex::<Msg>::column();
7903 for i in 0..6 {
7904 column = column.child(
7905 Button::new(format!("field {i}"))
7906 .on_press(Msg::A)
7907 .height(60.0),
7908 );
7909 }
7910 SingleChildScrollView::new()
7911 .width(200.0)
7912 .height(150.0)
7913 .child(column)
7914 }
7915
7916 fn form_ui(runtime: &Runtime) -> Ui<Msg> {
7917 build_ui(
7918 &long_form(),
7919 Size::new(200.0, 150.0),
7920 runtime,
7921 &Theme::default(),
7922 )
7923 }
7924
7925 /// **Every** field is a focus stop, not only the two and a half on screen.
7926 ///
7927 /// Registering what the eye can see is how a long form came to have most of its
7928 /// fields unreachable from the keyboard: Tab walked the visible ones and wrapped.
7929 #[test]
7930 fn tab_reaches_the_fields_below_the_fold() {
7931 let ui = form_ui(&Runtime::default());
7932 assert_eq!(ui.focusables.len(), 6, "all six, not the visible ones");
7933 // And the traversal is in tree order, so Tab walks down the form.
7934 let ids: Vec<_> = ui.focusables.iter().map(|f| f.id).collect();
7935 assert_eq!(ui.focus_next(Some(ids[2]), true), Some(ids[3]));
7936 }
7937
7938 /// A stop clipped away by a scroll keeps its **real** box, and an empty visible one.
7939 /// The two are different questions and the registry answers both.
7940 #[test]
7941 fn a_stop_out_of_sight_keeps_its_geometry() {
7942 let ui = form_ui(&Runtime::default());
7943 let fifth = ui.focusables[5];
7944 assert!((fifth.bounds.y - 300.0).abs() < 0.5, "{:?}", fifth.bounds);
7945 assert_eq!(fifth.rect.height, 0.0, "none of it is on screen");
7946 assert!(fifth.scroll.is_some(), "something around it scrolls");
7947 }
7948
7949 /// A click still lands only on what can be seen. The unclipped box of a field
7950 /// scrolled out of sight overlaps the window, and a tap there must not focus it.
7951 #[test]
7952 fn a_click_still_only_reaches_what_is_visible() {
7953 let ui = form_ui(&Runtime::default());
7954 // The second field, in the middle of its own visible box.
7955 let second = ui.focusables[1];
7956 let inside = Point::new(
7957 second.rect.x + second.rect.width / 2.0,
7958 second.rect.y + second.rect.height / 2.0,
7959 );
7960 assert_eq!(ui.focus_hit(inside).map(|(id, _)| id), Some(second.id));
7961 // The sixth field's **real** box overlaps nothing on screen, and a tap where it
7962 // would be if the form were not scrolled hits nothing at all.
7963 let sixth = ui.focusables[5];
7964 let past = Point::new(
7965 sixth.bounds.x + sixth.bounds.width / 2.0,
7966 sixth.bounds.y + sixth.bounds.height / 2.0,
7967 );
7968 assert!(past.y > 150.0, "past the fold: {past:?}");
7969 assert_eq!(ui.focus_hit(past), None);
7970 }
7971
7972 /// Focus lands below the fold and the view follows: the least movement that brings
7973 /// the field's foot to the window's.
7974 #[test]
7975 fn revealing_a_stop_below_the_fold_scrolls_to_it() {
7976 let runtime = Runtime::default();
7977 let ui = form_ui(&runtime);
7978 let area = ui.scroll_regions()[0];
7979 let fifth = ui.focusables[5].id;
7980 let moves = ui.reveal(fifth, &runtime);
7981 // Field 5 sits at 300..360 and the window is 150 tall: its foot reaches the
7982 // window's foot at 360 - 150 = 210.
7983 assert_eq!(moves, vec![(area.id, (0.0, 210.0))]);
7984 }
7985
7986 /// Already in view, nothing moves — the answer is the empty list rather than a
7987 /// zero, so no caller has to ask twice.
7988 #[test]
7989 fn revealing_something_already_in_view_moves_nothing() {
7990 let runtime = Runtime::default();
7991 let ui = form_ui(&runtime);
7992 assert!(ui.reveal(ui.focusables[0].id, &runtime).is_empty());
7993 assert!(ui.reveal(ui.focusables[1].id, &runtime).is_empty());
7994 // And a stop the frame does not contain at all is not an error.
7995 assert!(ui.reveal(WidgetId::from_u64(7), &runtime).is_empty());
7996 }
7997
7998 /// Coming back **up** the form scrolls the other way, and only as far as it must.
7999 #[test]
8000 fn revealing_a_stop_above_the_fold_scrolls_back() {
8001 let mut runtime = Runtime::default();
8002 let area_id = form_ui(&runtime).scroll_regions()[0].id;
8003 runtime.scroll.insert(area_id, (0.0, 210.0));
8004 let ui = form_ui(&runtime);
8005 let first = ui.focusables[0].id;
8006 // Field 0 sits at 0..60: its head reaches the window's head at offset 0.
8007 assert_eq!(ui.reveal(first, &runtime), vec![(area_id, (0.0, 0.0))]);
8008 // At offset 210 the window shows 210..360, so field 4 (240..300) is wholly in
8009 // it and does not move. Field 3 (180..240) hangs over the top edge and would.
8010 assert!(ui.reveal(ui.focusables[4].id, &runtime).is_empty());
8011 assert!(!ui.reveal(ui.focusables[3].id, &runtime).is_empty());
8012 }
8013
8014 /// The arithmetic on its own: the least movement, the leading edge for anything too
8015 /// big to fit, and the clamp at the ends of the travel.
8016 #[test]
8017 fn the_reveal_moves_as_little_as_it_can() {
8018 let area = Scrollable {
8019 id: WidgetId::ROOT,
8020 viewport: Rect::new(0.0, 0.0, 100.0, 100.0),
8021 max_x: 0.0,
8022 max_y: 400.0,
8023 axis: crate::scroll::Axis::Vertical,
8024 physics: crate::ScrollPhysics::CLAMPING,
8025 overscroll: Some(crate::OverscrollIndicator::Glow),
8026 fling: frus_core::VelocityStrategy::Regression,
8027 refresh: None,
8028 page: None,
8029 reverse_x: false,
8030 reverse_y: false,
8031 host: None,
8032 keep_visible: None,
8033 };
8034 // Inside: nothing.
8035 assert_eq!(
8036 area.reveal(Rect::new(0.0, 10.0, 50.0, 20.0), (0.0, 0.0)).1,
8037 (0.0, 0.0)
8038 );
8039 // Below: its foot comes to the window's foot, and no further.
8040 assert_eq!(
8041 area.reveal(Rect::new(0.0, 140.0, 50.0, 20.0), (0.0, 0.0)).0,
8042 (0.0, 60.0)
8043 );
8044 // Above: its head comes to the window's head.
8045 assert_eq!(
8046 area.reveal(Rect::new(0.0, -30.0, 50.0, 20.0), (0.0, 50.0))
8047 .0,
8048 (0.0, 20.0)
8049 );
8050 // Taller than the window: the **start** edge wins, because that is what is read.
8051 assert_eq!(
8052 area.reveal(Rect::new(0.0, -10.0, 50.0, 300.0), (0.0, 40.0))
8053 .0,
8054 (0.0, 30.0)
8055 );
8056 // And the travel is a wall: an offset past the end is not asked for.
8057 assert_eq!(
8058 area.reveal(Rect::new(0.0, 900.0, 50.0, 20.0), (0.0, 0.0)).0,
8059 (0.0, 400.0)
8060 );
8061 }
8062
8063 /// A reversed axis numbers its offsets from the far end, so the same movement of the
8064 /// content is the opposite movement of the offset. One function knows that, and the
8065 /// reveal asks it rather than keeping a second opinion.
8066 #[test]
8067 fn the_reveal_follows_a_reversed_axis() {
8068 let area = Scrollable {
8069 id: WidgetId::ROOT,
8070 viewport: Rect::new(0.0, 0.0, 100.0, 100.0),
8071 max_x: 0.0,
8072 max_y: 400.0,
8073 axis: crate::scroll::Axis::Vertical,
8074 physics: crate::ScrollPhysics::CLAMPING,
8075 overscroll: Some(crate::OverscrollIndicator::Glow),
8076 fling: frus_core::VelocityStrategy::Regression,
8077 refresh: None,
8078 page: None,
8079 reverse_x: false,
8080 reverse_y: true,
8081 host: None,
8082 keep_visible: None,
8083 };
8084 // A box below the window: the content must move **up** by 60 either way. On a
8085 // reversed axis a rising offset pushes the content down (`content_origin` is
8086 // `viewport - content + offset` there), so the offset comes **down** by 60 to do
8087 // what a plain axis would need it to go up by.
8088 let (offset, shift) = area.reveal(Rect::new(0.0, 140.0, 50.0, 20.0), (0.0, 100.0));
8089 assert_eq!(shift, (0.0, -60.0));
8090 assert_eq!(offset, (0.0, 40.0));
8091 }
8092
8093 /// Centring puts the box in the middle of the window, and the clamp is what keeps
8094 /// the first and last items of a row where they belong rather than half off it.
8095 #[test]
8096 fn centring_is_clamped_to_the_travel() {
8097 let area = Scrollable {
8098 id: WidgetId::ROOT,
8099 viewport: Rect::new(0.0, 0.0, 300.0, 50.0),
8100 max_x: 700.0,
8101 max_y: 0.0,
8102 axis: crate::scroll::Axis::Vertical,
8103 physics: crate::ScrollPhysics::CLAMPING,
8104 overscroll: Some(crate::OverscrollIndicator::Glow),
8105 fling: frus_core::VelocityStrategy::Regression,
8106 refresh: None,
8107 page: None,
8108 reverse_x: false,
8109 reverse_y: false,
8110 host: None,
8111 keep_visible: None,
8112 };
8113 // A box at 400..500 has its middle at 450; the window's is at 150.
8114 assert_eq!(
8115 area.centre(Rect::new(400.0, 0.0, 100.0, 50.0), (0.0, 0.0))
8116 .0,
8117 (300.0, 0.0)
8118 );
8119 // The first item cannot be centred without scrolling backwards, so it stays.
8120 assert_eq!(
8121 area.centre(Rect::new(0.0, 0.0, 100.0, 50.0), (0.0, 0.0)).0,
8122 (0.0, 0.0)
8123 );
8124 // Nor the last past the end of the travel.
8125 assert_eq!(
8126 area.centre(Rect::new(900.0, 0.0, 100.0, 50.0), (0.0, 0.0))
8127 .0,
8128 (700.0, 0.0)
8129 );
8130 }
8131
8132 /// **A lone child could widen the box it was given, and take the screen with it.**
8133 ///
8134 /// A flex item's automatic minimum is its **min-content** size, so agreeing to shrink
8135 /// buys nothing on its own: the item shrinks willingly and then refuses to go below
8136 /// the widest thing inside it. A column holding one over-wide row came out at that
8137 /// row's width; the padded box around it came out at the same; and every sibling,
8138 /// stretched across the column, came out at the same again — a whole screen laid out
8139 /// to the width of its widest line and then clipped by the window.
8140 ///
8141 /// Reported from a real application: a shop whose banner, search field, filter row
8142 /// and product grid were all cut off at the same edge, because one segmented control
8143 /// four segments wide had decided how wide the screen was.
8144 ///
8145 /// The over-wide child still overflows — that is the reference's behaviour and the
8146 /// honest one — but it no longer drags its parent and its siblings out with it.
8147 #[test]
8148 fn a_lone_child_cannot_widen_the_box_it_was_given() {
8149 let ordinary = Color::rgb(0.1, 0.2, 0.3);
8150 let overwide = Color::rgb(0.9, 0.8, 0.7);
8151 let screen: SingleChildScrollView<Msg> = SingleChildScrollView::new().width(300.0).child(
8152 Container::new().padding(24.0).child(
8153 Flex::column()
8154 .align(frus_layout::Align::Stretch)
8155 .child(Container::new().height(20.0).color(ordinary))
8156 .child(Container::new().width(600.0).height(20.0).color(overwide)),
8157 ),
8158 );
8159 let ui = build_ui(
8160 &screen,
8161 Size::new(300.0, 800.0),
8162 &Runtime::default(),
8163 &Theme::default(),
8164 );
8165 let width_of = |wanted: Color| {
8166 ui.scene()
8167 .primitives()
8168 .iter()
8169 .find_map(|p| match p {
8170 Primitive::Rect { color, rect, .. } if *color == wanted => Some(rect.width),
8171 _ => None,
8172 })
8173 .expect("the box is drawn")
8174 };
8175 // 300 less the padding either side, and not 600.
8176 assert_eq!(width_of(ordinary), 252.0);
8177 // The one that asked to be too wide still is: it overflows rather than being
8178 // squeezed, and rather than resizing everything around it.
8179 assert_eq!(width_of(overwide), 600.0);
8180 }
8181
8182 #[test]
8183 fn tab_cycles_focusables_in_order() {
8184 let tree = Flex::<Msg>::column()
8185 .child(Button::new("un").on_press(Msg::A))
8186 .child(Button::new("deux").on_press(Msg::B));
8187 let ui = build_ui(
8188 &tree,
8189 Size::new(200.0, 200.0),
8190 &Runtime::default(),
8191 &Theme::default(),
8192 );
8193 assert_eq!(ui.focusables.len(), 2, "both buttons are focusable");
8194 let first = ui.focusables[0].id;
8195 let second = ui.focusables[1].id;
8196
8197 // With no focus: Tab -> first, Shift+Tab -> last.
8198 assert_eq!(ui.focus_next(None, true), Some(first));
8199 assert_eq!(ui.focus_next(None, false), Some(second));
8200 // Wrap-around.
8201 assert_eq!(ui.focus_next(Some(first), true), Some(second));
8202 assert_eq!(ui.focus_next(Some(second), true), Some(first));
8203 assert_eq!(ui.focus_next(Some(first), false), Some(second));
8204 }
8205
8206 #[test]
8207 fn focus_ring_for_button_not_for_textinput() {
8208 let theme = Theme::default();
8209 let ring = theme.focus.fade(0.4); // focus_progress = 0 → alpha 0.4
8210 let count_ring = |tree: &dyn Widget<Msg>, keyboard: bool| -> usize {
8211 let mut rt = Runtime::default();
8212 let probe = build_ui(tree, Size::new(200.0, 200.0), &rt, &theme);
8213 rt.input.focused = probe.focusables.first().map(|f| f.id);
8214 rt.focus_visible = keyboard;
8215 let ui = build_ui(tree, Size::new(200.0, 200.0), &rt, &theme);
8216 ui.scene()
8217 .primitives()
8218 .iter()
8219 .filter(
8220 |p| matches!(p, Primitive::Rect { border_color, .. } if *border_color == ring),
8221 )
8222 .count()
8223 };
8224 let with_button = Flex::<Msg>::column().child(Button::new("x").on_press(Msg::A));
8225 assert!(
8226 count_ring(&with_button, true) >= 1,
8227 "a button focused with the keyboard has a generic ring"
8228 );
8229 // Focus taken with the pointer: no ring (FocusHighlightMode).
8230 assert_eq!(
8231 count_ring(&with_button, false),
8232 0,
8233 "a click does not flash a ring"
8234 );
8235
8236 let with_input = Flex::<Msg>::column().child(TextField::new("hi").on_input(Msg::Edited));
8237 assert_eq!(
8238 count_ring(&with_input, true),
8239 0,
8240 "the field draws its own focus"
8241 );
8242 }
8243
8244 #[test]
8245 fn arrow_focus_navigates_geometrically() {
8246 // A 2×2 grid of buttons; each target is identified by its message.
8247 let grid: Flex<Msg> = Flex::column()
8248 .child(
8249 Flex::row()
8250 .child(Button::new("a").on_press(Msg::A))
8251 .child(Button::new("b").on_press(Msg::B)),
8252 )
8253 .child(
8254 Flex::row()
8255 .child(Button::new("c").on_press(Msg::C))
8256 .child(Button::new("d").on_press(Msg::D)),
8257 );
8258 let ui = build_ui(
8259 &grid,
8260 Size::new(300.0, 200.0),
8261 &Runtime::default(),
8262 &Theme::default(),
8263 );
8264 let top_left = ui.focus_next(None, true).expect("premier focusable");
8265 assert_eq!(ui.msg_for(top_left), Some(Msg::A));
8266
8267 // Right: a → b; down: a → c; and nothing to the left of a.
8268 let right = ui
8269 .focus_directional(top_left, FocusDirection::Right)
8270 .expect("to the right");
8271 assert_eq!(ui.msg_for(right), Some(Msg::B));
8272 let down = ui
8273 .focus_directional(top_left, FocusDirection::Down)
8274 .expect("downwards");
8275 assert_eq!(ui.msg_for(down), Some(Msg::C));
8276 assert_eq!(ui.focus_directional(top_left, FocusDirection::Left), None);
8277 // The diagonal is kept in check: from b, down → d (aligned), not c.
8278 let down_right = ui
8279 .focus_directional(right, FocusDirection::Down)
8280 .expect("down from b");
8281 assert_eq!(ui.msg_for(down_right), Some(Msg::D));
8282 }
8283
8284 #[test]
8285 fn keyed_identity_survives_middle_removal() {
8286 let colored = |c: Color| Container::<Msg>::new().width(50.0).height(20.0).color(c);
8287 let red = Color::rgb(1.0, 0.0, 0.0);
8288 let green = Color::rgb(0.0, 1.0, 0.0);
8289 let blue = Color::rgb(0.0, 0.0, 1.0);
8290
8291 let owner_of = |ui: &Ui<Msg>, c: Color| -> u64 {
8292 ui.scene()
8293 .primitives()
8294 .iter()
8295 .find_map(|p| match p {
8296 Primitive::Rect { color, owner, .. } if *color == c => Some(*owner),
8297 _ => None,
8298 })
8299 .expect("the primitive is there")
8300 };
8301
8302 // The list [red(key 1), green(key 2), blue(key 3)].
8303 let full = Flex::<Msg>::column()
8304 .child(Keyed::new(1u64, colored(red)))
8305 .child(Keyed::new(2u64, colored(green)))
8306 .child(Keyed::new(3u64, colored(blue)));
8307 let ui_full = build_ui(
8308 &full,
8309 Size::new(200.0, 200.0),
8310 &Runtime::default(),
8311 &Theme::default(),
8312 );
8313
8314 // The list [red(1), blue(3)]: the green in the middle is removed → blue goes from index 2 to 1.
8315 let removed = Flex::<Msg>::column()
8316 .child(Keyed::new(1u64, colored(red)))
8317 .child(Keyed::new(3u64, colored(blue)));
8318 let ui_removed = build_ui(
8319 &removed,
8320 Size::new(200.0, 200.0),
8321 &Runtime::default(),
8322 &Theme::default(),
8323 );
8324
8325 // Blue's identity (owner, key 3) is UNCHANGED despite the shift in position.
8326 assert_eq!(owner_of(&ui_full, blue), owner_of(&ui_removed, blue));
8327
8328 // Without a key, the 2nd child's positional identity DOES change (index 2 vs 1).
8329 let unkeyed_full = Flex::<Msg>::column()
8330 .child(colored(red))
8331 .child(colored(green))
8332 .child(colored(blue));
8333 let unkeyed_removed = Flex::<Msg>::column()
8334 .child(colored(red))
8335 .child(colored(blue));
8336 let u1 = build_ui(
8337 &unkeyed_full,
8338 Size::new(200.0, 200.0),
8339 &Runtime::default(),
8340 &Theme::default(),
8341 );
8342 let u2 = build_ui(
8343 &unkeyed_removed,
8344 Size::new(200.0, 200.0),
8345 &Runtime::default(),
8346 &Theme::default(),
8347 );
8348 assert_ne!(owner_of(&u1, blue), owner_of(&u2, blue));
8349 }
8350
8351 #[test]
8352 fn center_overlay_scrim_click_dismisses() {
8353 // A Center modal with `.dismiss`: clicking the scrim (outside the content) returns the
8354 // dismissal message; clicking the content does not.
8355 let modal = Container::<Msg>::new()
8356 .width(100.0)
8357 .height(60.0)
8358 .color(Color::WHITE);
8359 let portal: OverlayPortal<Msg> =
8360 OverlayPortal::new(Container::<Msg>::new().width(20.0).height(20.0))
8361 .overlay(modal, Placement::Center)
8362 .dismiss(Msg::A);
8363 let ui = build_ui(
8364 &portal,
8365 Size::new(400.0, 300.0),
8366 &Runtime::default(),
8367 &Theme::default(),
8368 );
8369
8370 // The top-left corner: on the scrim → it dismisses.
8371 let corner = ui.hit(Point::new(5.0, 5.0)).expect("a clickable scrim");
8372 assert_eq!(ui.msg_for(corner), Some(Msg::A));
8373 }
8374
8375 /// **The shell's mark reaches the field** (milestone 511): a focused field whose
8376 /// selection the runtime marks as a touch one paints its two handles; the same
8377 /// selection unmarked paints none, and so does a marked field that lost the focus.
8378 #[test]
8379 fn a_touch_selection_reaches_the_field_as_handles() {
8380 let tree = Flex::column().width(300.0).height(80.0).child(
8381 TextField::new("hello world")
8382 .width(200.0)
8383 .on_input(Msg::Edited),
8384 );
8385 let theme = Theme::default();
8386 let size = Size::new(300.0, 80.0);
8387 let (id, _) = build_ui(&tree, size, &Runtime::default(), &theme)
8388 .focus_hit(Point::new(10.0, 10.0))
8389 .expect("the field");
8390 let handles = |focused: bool, marked: bool| {
8391 let mut rt = Runtime::default();
8392 rt.edits.insert(
8393 id,
8394 Edit {
8395 cursor: 11,
8396 anchor: Some(6),
8397 composing: None,
8398 },
8399 );
8400 rt.input.focused = focused.then_some(id);
8401 rt.selection_handles = marked.then_some(id);
8402 let ui = build_ui(&tree, size, &rt, &theme);
8403 ui.scene()
8404 .primitives()
8405 .iter()
8406 .filter(|p| {
8407 matches!(p, Primitive::Path { fill: Some(c), .. } if *c == theme.scheme.primary)
8408 })
8409 .count()
8410 };
8411 assert_eq!(handles(true, true), 2);
8412 assert_eq!(handles(true, false), 0, "a selection made with a mouse");
8413 assert_eq!(handles(false, true), 0, "a field left behind");
8414 }
8415
8416 /// A wrapper that fuses with its field shares its identity, so it is the wrapper the
8417 /// shell asks for the handles — and a wrapper that forgot to pass the question on
8418 /// would leave a finger nothing to take (the three silent bugs `Responsive` has
8419 /// already cost, milestones 477 to 495).
8420 #[test]
8421 fn the_wrappers_that_fuse_with_a_field_pass_its_handles_on() {
8422 let field = || TextField::<Msg>::new("hello world").width(200.0);
8423 let edit = Edit {
8424 cursor: 11,
8425 anchor: Some(6),
8426 composing: None,
8427 };
8428 let direct = Widget::<Msg>::selection_handles(&field(), 200.0, &edit, 0.0);
8429 assert!(direct.is_some());
8430 let keyed = crate::Keyed::new(1, field());
8431 let responsive = crate::Responsive::new(crate::SizeClass::Compact).compact(field());
8432 let boxed: Box<dyn Widget<Msg>> = Box::new(field());
8433 assert_eq!(keyed.selection_handles(200.0, &edit, 0.0), direct);
8434 assert_eq!(responsive.selection_handles(200.0, &edit, 0.0), direct);
8435 assert_eq!(boxed.selection_handles(200.0, &edit, 0.0), direct);
8436 }
8437
8438 /// The tree the selection-bar tests share: a field with `spacer` px of room above it, so
8439 /// the bar has somewhere to go above the selection (or not, at 0).
8440 fn bar_tree(spacer: f32, value: &str) -> impl Widget<Msg> {
8441 Flex::column()
8442 .width(300.0)
8443 .height(400.0)
8444 .child(Container::new().width(300.0).height(spacer))
8445 .child(
8446 TextField::new(value.to_string())
8447 .width(200.0)
8448 .on_input(Msg::Edited),
8449 )
8450 }
8451
8452 /// The identity of the field in [`bar_tree`].
8453 fn bar_field_id(tree: &impl Widget<Msg>) -> WidgetId {
8454 let ui = build_ui(
8455 tree,
8456 Size::new(300.0, 400.0),
8457 &Runtime::default(),
8458 &Theme::default(),
8459 );
8460 let id = ui.focusable_ids().next().expect("the field");
8461 id
8462 }
8463
8464 /// A frame with the field's bar open: `edit` selected, the runtime's mark saying
8465 /// `can_paste`, and the field focused and marked as the two flags say.
8466 fn bar_frame(
8467 tree: &impl Widget<Msg>,
8468 edit: Edit,
8469 can_paste: bool,
8470 focused: bool,
8471 marked: bool,
8472 ) -> Ui<Msg> {
8473 let id = bar_field_id(tree);
8474 let mut rt = Runtime::default();
8475 rt.edits.insert(id, edit);
8476 rt.input.focused = focused.then_some(id);
8477 rt.selection_toolbar = marked.then_some(crate::runtime::ToolbarMark {
8478 id,
8479 can_paste,
8480 at: None,
8481 });
8482 // The pill's tests: under a theme that follows Android, where the bar is a pill
8483 // (milestone 618), whatever this test runs on.
8484 build_ui(tree, Size::new(300.0, 400.0), &rt, &pill_theme())
8485 }
8486
8487 /// **On the desktops the bar is a menu, and a right-click puts it at the pointer**
8488 /// (milestone 618; `editable_text.dart:3211`): opened any other way it hangs from the
8489 /// top of the selection, at its middle; opened by a right-click it hangs from where the
8490 /// pointer was; either way it is pushed back inside the window.
8491 #[test]
8492 fn a_desktop_menu_hangs_from_the_pointer_or_the_selection() {
8493 let tree = bar_tree(150.0, "hello world");
8494 let id = bar_field_id(&tree);
8495 let theme = Theme::default().with_platform(frus_core::TargetPlatform::Linux);
8496 let frame = |at: Option<Point>| {
8497 let mut rt = Runtime::default();
8498 rt.edits.insert(id, selected(5, Some(0)));
8499 rt.input.focused = Some(id);
8500 rt.selection_toolbar = Some(crate::runtime::ToolbarMark {
8501 id,
8502 can_paste: false,
8503 at,
8504 });
8505 build_ui(&tree, Size::new(300.0, 400.0), &rt, &theme)
8506 };
8507 let window = Rect::new(0.0, 0.0, 300.0, 400.0);
8508
8509 let ui = frame(Some(Point::new(40.0, 60.0)));
8510 let menu = ui.toolbars[0];
8511 assert_eq!(menu.width, 222.0, "the menu, not the pill");
8512 assert_eq!((menu.x, menu.y), (40.0, 60.0), "at the pointer");
8513
8514 let ui = frame(Some(Point::new(250.0, 380.0)));
8515 let menu = ui.toolbars[0];
8516 let expected = crate::selectiontoolbar::place_menu(
8517 Point::new(250.0, 380.0),
8518 Size::new(menu.width, menu.height),
8519 window,
8520 );
8521 assert_eq!((menu.x, menu.y), expected, "pushed back inside");
8522 assert!(menu.x + menu.width <= 292.0 && menu.y + menu.height <= 392.0);
8523
8524 let ui = frame(None);
8525 let menu = ui.toolbars[0];
8526 let field = ui.widget_rect(id).expect("the field");
8527 assert!(
8528 (menu.y - field.y).abs() < field.height,
8529 "hangs from the selection's top, not above it: {menu:?} {field:?}"
8530 );
8531 }
8532
8533 /// A theme whose selection bar is the pill.
8534 fn pill_theme() -> Theme {
8535 Theme::default().with_platform(frus_core::TargetPlatform::Android)
8536 }
8537
8538 fn selected(cursor: usize, anchor: Option<usize>) -> Edit {
8539 Edit {
8540 cursor,
8541 anchor,
8542 composing: None,
8543 }
8544 }
8545
8546 /// The editing actions a finger can reach on the bar, found the way a finger finds
8547 /// them: pressing along a line through the bar and asking what is there.
8548 fn reachable_actions(ui: &Ui<Msg>) -> Vec<crate::EditAction> {
8549 let Some(bar) = ui.toolbars.first().copied() else {
8550 return Vec::new();
8551 };
8552 let mut found = Vec::new();
8553 let mut x = bar.x + 1.0;
8554 while x < bar.x + bar.width {
8555 let at = Point::new(x, bar.y + bar.height * 0.5);
8556 if let Some(action) = ui.hit(at).and_then(|id| ui.edit_action_for(id)) {
8557 if !found.contains(&action) {
8558 found.push(action);
8559 }
8560 }
8561 x += 2.0;
8562 }
8563 found
8564 }
8565
8566 fn sorted_actions(mut actions: Vec<crate::EditAction>) -> Vec<crate::EditAction> {
8567 actions.sort_by_key(|action| format!("{action:?}"));
8568 actions
8569 }
8570
8571 /// **The bar floats above a selection** (milestone 568): a focused field the shell has
8572 /// marked, with a word selected and something on the clipboard, gets Cut, Copy, Paste and
8573 /// Select all — in a box **above** the field, and each one a target a press can find.
8574 #[test]
8575 fn a_marked_field_floats_its_selection_bar_above_it() {
8576 use crate::EditAction::{Copy, Cut, Paste, SelectAll};
8577 let tree = bar_tree(200.0, "hello world");
8578 let ui = bar_frame(&tree, selected(11, Some(6)), true, true, true);
8579 assert_eq!(ui.toolbars.len(), 1, "one bar");
8580 let bar = ui.toolbars[0];
8581 // Above the **selection**, a gap clear of it: not above the field, whose top edge a
8582 // bar over a line of text a few px down may overlap.
8583 let field = ui.widget_rect(bar_field_id(&tree)).expect("the field");
8584 let selection = Widget::<Msg>::selection_anchor(
8585 &TextField::<Msg>::new("hello world").width(200.0),
8586 field.width,
8587 &selected(11, Some(6)),
8588 0.0,
8589 )
8590 .expect("a selection box");
8591 let gap = field.y + selection.y - (bar.y + bar.height);
8592 assert!(
8593 (gap - crate::selectiontoolbar::GAP).abs() < 0.01,
8594 "the bar ends {gap} px above the selection: {bar:?}, selection at {selection:?} in {field:?}"
8595 );
8596 assert!(
8597 bar.x >= 0.0 && bar.x + bar.width <= 300.0,
8598 "inside the window"
8599 );
8600 assert_eq!(
8601 sorted_actions(reachable_actions(&ui)),
8602 sorted_actions(vec![Cut, Copy, Paste, SelectAll])
8603 );
8604 }
8605
8606 /// With no room above the field, the bar goes **below** the selection — clear of the
8607 /// handles that hang there.
8608 #[test]
8609 fn with_no_room_above_the_bar_goes_below_the_field() {
8610 let tree = bar_tree(0.0, "hello world");
8611 let ui = bar_frame(&tree, selected(11, Some(6)), true, true, true);
8612 let bar = *ui.toolbars.first().expect("a bar");
8613 let field = ui.widget_rect(bar_field_id(&tree)).expect("the field");
8614 assert!(
8615 bar.y >= field.y + field.height * 0.5,
8616 "below the selection's line: bar {bar:?}, field {field:?}"
8617 );
8618 }
8619
8620 /// **Only a marked, focused field shows its bar**: the same selection unmarked (made
8621 /// with a mouse or the keyboard) shows none, and neither does a marked field that lost
8622 /// the focus.
8623 #[test]
8624 fn the_bar_shows_only_for_the_marked_focused_field() {
8625 let tree = bar_tree(200.0, "hello world");
8626 let edit = selected(11, Some(6));
8627 let shown = |focused, marked| bar_frame(&tree, edit, true, focused, marked).toolbars.len();
8628 assert_eq!(shown(true, true), 1);
8629 assert_eq!(shown(true, false), 0, "not marked");
8630 assert_eq!(shown(false, true), 0, "a field left behind");
8631 }
8632
8633 /// **The list follows the three conditions**: nothing selected offers Paste and Select
8634 /// all; everything selected offers Cut and Copy; and a field with nothing in it and
8635 /// nothing to paste has no bar at all.
8636 #[test]
8637 fn the_bar_offers_what_the_situation_allows() {
8638 use crate::EditAction::{Copy, Cut, Paste, SelectAll};
8639 let tree = bar_tree(200.0, "hello world");
8640 // A caret, no selection, something to paste.
8641 let caret = bar_frame(&tree, selected(3, None), true, true, true);
8642 assert_eq!(
8643 sorted_actions(reachable_actions(&caret)),
8644 sorted_actions(vec![Paste, SelectAll])
8645 );
8646 // A caret and an empty clipboard: only Select all.
8647 let bare = bar_frame(&tree, selected(3, None), false, true, true);
8648 assert_eq!(reachable_actions(&bare), vec![SelectAll]);
8649 // Everything selected (`usize::MAX` is "the end", as Select all leaves it).
8650 let all = bar_frame(&tree, selected(usize::MAX, Some(0)), false, true, true);
8651 assert_eq!(
8652 sorted_actions(reachable_actions(&all)),
8653 sorted_actions(vec![Cut, Copy])
8654 );
8655 // An empty field with nothing to paste has nothing to offer.
8656 let empty = bar_tree(200.0, "");
8657 let nothing = bar_frame(&empty, selected(0, None), false, true, true);
8658 assert!(nothing.toolbars.is_empty());
8659 }
8660
8661 /// A press on the bar is known for one — the shell must not treat it as a press
8662 /// elsewhere, which puts the selection away.
8663 #[test]
8664 fn a_press_on_the_bar_is_a_press_on_the_bar() {
8665 let tree = bar_tree(200.0, "hello world");
8666 let ui = bar_frame(&tree, selected(11, Some(6)), true, true, true);
8667 let bar = ui.toolbars[0];
8668 assert!(ui.toolbar_contains(Point::new(bar.x + 3.0, bar.y + 3.0)));
8669 assert!(!ui.toolbar_contains(Point::new(bar.x - 5.0, bar.y - 5.0)));
8670 let unmarked = bar_frame(&tree, selected(11, Some(6)), true, true, false);
8671 assert!(!unmarked.toolbar_contains(Point::new(bar.x + 3.0, bar.y + 3.0)));
8672 }
8673
8674 /// The same, **by identity** — how an assistive technology names what it clicks: a button
8675 /// of the bar is on the bar, the field it acts on is not.
8676 #[test]
8677 fn a_target_named_by_identity_is_on_the_bar_or_not() {
8678 let tree = bar_tree(200.0, "hello world");
8679 let ui = bar_frame(&tree, selected(11, Some(6)), true, true, true);
8680 let bar = ui.toolbars[0];
8681 let button = ui
8682 .hit(Point::new(
8683 bar.x + bar.width * 0.5,
8684 bar.y + bar.height * 0.5,
8685 ))
8686 .filter(|id| ui.edit_action_for(*id).is_some())
8687 .or_else(|| {
8688 let mut x = bar.x + 1.0;
8689 let mut found = None;
8690 while x < bar.x + bar.width && found.is_none() {
8691 found = ui
8692 .hit(Point::new(x, bar.y + bar.height * 0.5))
8693 .filter(|id| ui.edit_action_for(*id).is_some());
8694 x += 2.0;
8695 }
8696 found
8697 })
8698 .expect("a button of the bar");
8699 assert!(ui.hit_is_on_toolbar(button));
8700 assert!(!ui.hit_is_on_toolbar(bar_field_id(&tree)));
8701 }
8702
8703 /// **The hooks pass through the wrappers that fuse with a field** — the same three silent
8704 /// bugs `Responsive` has already cost (milestones 477 to 495), for the bar's hooks.
8705 #[test]
8706 fn the_wrappers_that_fuse_with_a_field_pass_its_bar_on() {
8707 use crate::ToolbarContext;
8708 let field = || TextField::<Msg>::new("hello world").width(200.0);
8709 let context = ToolbarContext {
8710 has_selection: true,
8711 can_paste: true,
8712 all_selected: false,
8713 };
8714 let edit = selected(11, Some(6));
8715 let count = |widget: &dyn Widget<Msg>| {
8716 widget
8717 .selection_toolbar(context)
8718 .map(|bar| bar.children().len())
8719 };
8720 let direct = count(&field());
8721 assert_eq!(direct, Some(4));
8722 let anchor = Widget::<Msg>::selection_anchor(&field(), 200.0, &edit, 0.0);
8723 assert!(anchor.is_some());
8724 let keyed = crate::Keyed::new(1, field());
8725 let responsive = crate::Responsive::new(crate::SizeClass::Compact).compact(field());
8726 let boxed: Box<dyn Widget<Msg>> = Box::new(field());
8727 assert_eq!(count(&keyed), direct);
8728 assert_eq!(count(&responsive), direct);
8729 assert_eq!(count(&boxed), direct);
8730 assert_eq!(keyed.selection_anchor(200.0, &edit, 0.0), anchor);
8731 assert_eq!(responsive.selection_anchor(200.0, &edit, 0.0), anchor);
8732 assert_eq!(boxed.selection_anchor(200.0, &edit, 0.0), anchor);
8733 }
8734
8735 /// Two fields, one marked: **one bar**, over the marked one — not one over each field
8736 /// that happens to hold a selection.
8737 #[test]
8738 fn of_two_fields_only_the_marked_one_shows_a_bar() {
8739 let tree = Flex::column()
8740 .width(300.0)
8741 .height(400.0)
8742 .child(Container::new().width(300.0).height(150.0))
8743 .child(
8744 TextField::new("first field")
8745 .width(200.0)
8746 .on_input(Msg::Edited),
8747 )
8748 .child(
8749 TextField::new("second field")
8750 .width(200.0)
8751 .on_input(Msg::Edited),
8752 );
8753 let theme = pill_theme();
8754 let size = Size::new(300.0, 400.0);
8755 let ids: Vec<WidgetId> = build_ui(&tree, size, &Runtime::default(), &theme)
8756 .focusable_ids()
8757 .collect();
8758 assert_eq!(ids.len(), 2);
8759 let mut rt = Runtime::default();
8760 for id in &ids {
8761 rt.edits.insert(*id, selected(5, Some(0)));
8762 }
8763 // Focus follows the marked field; the other holds a selection too, unfocused.
8764 rt.input.focused = Some(ids[1]);
8765 rt.selection_toolbar = Some(crate::runtime::ToolbarMark {
8766 id: ids[1],
8767 can_paste: true,
8768 at: None,
8769 });
8770 let ui = build_ui(&tree, size, &rt, &theme);
8771 assert_eq!(ui.toolbars.len(), 1);
8772 let second = ui.widget_rect(ids[1]).expect("the second field");
8773 let bar = ui.toolbars[0];
8774 // Above the second field's line and below the first: it belongs to the second.
8775 assert!(
8776 bar.y + bar.height <= second.y + second.height,
8777 "{bar:?} vs {second:?}"
8778 );
8779 assert!(
8780 bar.y > 100.0,
8781 "not over the first field's row, which is at 150: {bar:?}"
8782 );
8783 // The bar is the *marked* field's: focus on the other one opens nothing.
8784 rt.input.focused = Some(ids[0]);
8785 let elsewhere = build_ui(&tree, size, &rt, &theme);
8786 assert!(elsewhere.toolbars.is_empty());
8787 }
8788
8789 /// **The paint cache tells a field with its bar open from one without** (milestone 568).
8790 /// The fingerprint of a cached subtree is the statuses inside it, so two statuses that
8791 /// differ only in the bar — or in the handles, which it had never held — must hash apart,
8792 /// or the cache would replay the frame from before the bar opened.
8793 #[test]
8794 fn the_bar_and_the_handles_are_part_of_a_fields_fingerprint() {
8795 let hashed = |status: &Status| {
8796 let mut hasher = std::collections::hash_map::DefaultHasher::new();
8797 hash_status(status, &mut hasher);
8798 hasher.finish()
8799 };
8800 let plain = Status::default();
8801 let open = Status {
8802 toolbar: Some(true),
8803 ..Status::default()
8804 };
8805 let open_without_paste = Status {
8806 toolbar: Some(false),
8807 ..Status::default()
8808 };
8809 let handled = Status {
8810 handles: true,
8811 ..Status::default()
8812 };
8813 assert_ne!(hashed(&plain), hashed(&open), "the bar opening");
8814 assert_ne!(
8815 hashed(&open),
8816 hashed(&open_without_paste),
8817 "the clipboard emptying"
8818 );
8819 assert_ne!(hashed(&plain), hashed(&handled), "the handles appearing");
8820 }
8821
8822 /// **A field knows the form it is part of** (milestone 512): the stops inside one
8823 /// [`crate::AutofillGroup`] are that form, in tree order, whichever of them asks; two
8824 /// groups side by side are two forms; a field in no group is a form of one; and a
8825 /// group sits in the focus registry, so a cached subtree replays it like any stop.
8826 #[test]
8827 fn a_field_knows_the_form_it_is_part_of() {
8828 use crate::{AutofillGroup, AutofillHint};
8829 let field = |value: &str, hint: AutofillHint| {
8830 TextField::new(value)
8831 .width(200.0)
8832 .on_input(Msg::Edited)
8833 .autofill([hint])
8834 };
8835 let tree = Flex::column()
8836 .width(300.0)
8837 .height(400.0)
8838 .child(AutofillGroup::new(
8839 Flex::column()
8840 .child(field("someone", AutofillHint::Username))
8841 .child(field("secret", AutofillHint::Password)),
8842 ))
8843 .child(AutofillGroup::new(field(
8844 "123456",
8845 AutofillHint::OneTimeCode,
8846 )))
8847 .child(TextField::new("search").width(200.0).on_input(Msg::Edited));
8848 let ui = build_ui(
8849 &tree,
8850 Size::new(300.0, 400.0),
8851 &Runtime::default(),
8852 &Theme::default(),
8853 );
8854 let ids: Vec<WidgetId> = ui.focusable_ids().collect();
8855 assert_eq!(ids.len(), 4);
8856 let form = |id: WidgetId| ui.form_of(id).iter().map(|(f, _)| *f).collect::<Vec<_>>();
8857 assert_eq!(form(ids[0]), vec![ids[0], ids[1]], "the sign-in pair");
8858 assert_eq!(
8859 form(ids[1]),
8860 vec![ids[0], ids[1]],
8861 "whichever of the two asks"
8862 );
8863 assert_eq!(
8864 form(ids[2]),
8865 vec![ids[2]],
8866 "a second group is a second form"
8867 );
8868 assert_eq!(
8869 form(ids[3]),
8870 vec![ids[3]],
8871 "a field in no group is a form of one"
8872 );
8873 assert!(ui.form_of(WidgetId::from_u64(7)).is_empty());
8874 // The two groups are told apart by identity, and a lone field has none.
8875 let (first, second) = (ui.form_group(ids[0]), ui.form_group(ids[2]));
8876 assert!(first.is_some() && second.is_some() && first != second);
8877 assert_eq!(ui.form_group(ids[3]), None);
8878 assert_eq!(ui.group_stops(first.unwrap()).len(), 2);
8879 // Each stop carries its box, which is what the platform anchors its offer to.
8880 assert!(ui.form_of(ids[1]).iter().all(|(_, r)| r.height > 0.0));
8881 }
8882
8883 #[test]
8884 fn find_widget_and_edit_types() {
8885 let tree = Flex::column()
8886 .width(300.0)
8887 .height(80.0)
8888 .child(TextField::new("hi").width(200.0).on_input(Msg::Edited));
8889 let rt = Runtime::default();
8890 let ui = build_ui(&tree, Size::new(300.0, 80.0), &rt, &Theme::default());
8891 let (id, _rect) = ui.focus_hit(Point::new(10.0, 10.0)).expect("the field");
8892
8893 let widget = find_widget(&tree, id).expect("the widget was found");
8894 let mut edit = Edit {
8895 cursor: 2,
8896 anchor: None,
8897 composing: None,
8898 };
8899 assert_eq!(
8900 widget.on_edit(&mut edit, &Key::Text("!".to_string())),
8901 Some(Msg::Edited("hi!".to_string()))
8902 );
8903 }
8904
8905 #[test]
8906 fn a_traversal_can_arrive_before_the_layout_pass() {
8907 // Milestone 415. A `ThemeBuilder`'s subtree does not exist until something has
8908 // called `build_themed` on it, and `children()` says so in its own doc: "a
8909 // traversal that arrives first should call `build_themed`, not this".
8910 //
8911 // The shell has such a traversal. On a **burst of keystrokes** — a software
8912 // keyboard, `adb input text`, auto-repeat — it rebuilds the tree from `view` alone
8913 // and reads it immediately, with no layout pass in between, so every deferred
8914 // subtree in it is empty and every widget inside one is unreachable.
8915 let deferred = |value: &str| {
8916 let value = value.to_string();
8917 crate::ThemeBuilder::new(move |_: &Theme| {
8918 TextField::new(value.clone())
8919 .width(200.0)
8920 .on_input(Msg::Edited)
8921 })
8922 };
8923 let laid_out = Flex::column()
8924 .width(300.0)
8925 .height(80.0)
8926 .child(deferred("hi"));
8927 let rt = Runtime::default();
8928 let ui = build_ui(&laid_out, Size::new(300.0, 80.0), &rt, &Theme::default());
8929 let (id, _) = ui.focus_hit(Point::new(10.0, 10.0)).expect("the field");
8930 assert!(
8931 find_widget(&laid_out, id).is_some(),
8932 "after a layout pass the field is where the hit-test said it was"
8933 );
8934
8935 // The same tree, freshly built and not yet laid out. `build_deferred` is what the
8936 // layout pass does on its way down, and nothing else.
8937 let fresh = Flex::column()
8938 .width(300.0)
8939 .height(80.0)
8940 .child(deferred("hi"));
8941 build_deferred(&fresh, &Theme::default(), &Runtime::default());
8942 assert!(
8943 find_widget(&fresh, id).is_some(),
8944 "prepared the same way, the same traversal reaches the same widget"
8945 );
8946 }
8947
8948 #[test]
8949 #[should_panic(expected = "before it was built")]
8950 fn reading_an_unbuilt_deferred_subtree_trips_the_wire() {
8951 // Without the preparation the traversal used to return `None` and the caller
8952 // shrugged: no field found, no caret revealed, nothing said. The failure mode was
8953 // **silence**, so the guard is a panic in debug rather than a comment.
8954 let fresh =
8955 Flex::<Msg>::column()
8956 .width(300.0)
8957 .height(80.0)
8958 .child(crate::ThemeBuilder::new(|_: &Theme| {
8959 Container::<Msg>::new().width(10.0).height(10.0)
8960 }));
8961 let _ = find_widget(&fresh, WidgetId::ROOT.child(9));
8962 }
8963
8964 #[test]
8965 fn a_deferred_subtree_is_built_under_its_own_theme() {
8966 // The layout pass swaps the theme before it builds (`theme_override`), so a
8967 // builder inside a `Themed` sees the subtree's theme and not the frame's.
8968 // `build_deferred` has to make the same swap or it would build the wrong subtree
8969 // — and being *nearly* the walk is worse than not being it at all.
8970 let seen = std::rc::Rc::new(std::cell::Cell::new(0.0f32));
8971 let recorder = {
8972 let seen = seen.clone();
8973 crate::ThemeBuilder::new(move |theme: &Theme| {
8974 seen.set(theme.radius);
8975 Container::<Msg>::new().width(10.0).height(10.0)
8976 })
8977 };
8978 let inner = Theme {
8979 radius: 99.0,
8980 ..Theme::default()
8981 };
8982 let tree = Flex::<Msg>::column().child(crate::Themed::new(inner, recorder));
8983 build_deferred(&tree, &Theme::default(), &Runtime::default());
8984 assert_eq!(seen.get(), 99.0, "the subtree's theme, not the frame's");
8985 }
8986
8987 #[test]
8988 fn find_by_key_resolves_a_keyed_field_to_its_focus_id() {
8989 // Two named fields: `find_by_key` finds each one's focus identity (the one the
8990 // hit-test would assign), and it tells the keys apart.
8991 fn hash(k: &str) -> u64 {
8992 use std::hash::{Hash, Hasher};
8993 let mut h = std::collections::hash_map::DefaultHasher::new();
8994 k.hash(&mut h);
8995 h.finish()
8996 }
8997 let tree: Flex<Msg> = Flex::column()
8998 .child(Keyed::new(
8999 "email",
9000 TextField::new("").on_input(Msg::Edited),
9001 ))
9002 .child(Keyed::new(
9003 "password",
9004 TextField::new("").on_input(Msg::Edited),
9005 ));
9006
9007 let email = find_by_key(&tree, hash("email")).expect("email was found");
9008 let password = find_by_key(&tree, hash("password")).expect("password was found");
9009 assert_ne!(email, password, "distinct keys → distinct identities");
9010 // The identity resolved is indeed the by-key identity (stable, independent of the
9011 // position).
9012 assert_eq!(email, WidgetId::ROOT.keyed(hash("email")));
9013 assert!(
9014 find_by_key(&tree, hash("absent")).is_none(),
9015 "an unknown key → None"
9016 );
9017
9018 // And above all: it is **exactly** the identity the focus hit-test would assign to
9019 // that field — so setting this focus really does route to it.
9020 let rt = Runtime::default();
9021 let ui = build_ui(&tree, Size::new(300.0, 200.0), &rt, &Theme::default());
9022 let (hit_id, _) = ui
9023 .focus_hit(Point::new(10.0, 10.0))
9024 .expect("the email field under the cursor");
9025 assert_eq!(email, hit_id, "find_by_key == the field's focus identity");
9026 }
9027
9028 #[test]
9029 fn ink_is_painted_over_the_surface_and_under_its_child() {
9030 use crate::ink::InkWell;
9031 let tree = Container::<Msg>::new().width(120.0).height(60.0).child(
9032 InkWell::<Msg>::new().radius(8.0).on_click(Msg::A).child(
9033 Container::<Msg>::new()
9034 .width(120.0)
9035 .height(60.0)
9036 .color(frus_core::Color::WHITE),
9037 ),
9038 );
9039 let size = Size::new(120.0, 60.0);
9040
9041 // Dry: the well paints nothing of its own.
9042 let rt = Runtime::default();
9043 let dry = build_ui(&tree, size, &rt, &Theme::default());
9044 let plain = dry.scene.len();
9045 let id = dry.inks.first().expect("the well registered its box").0;
9046 assert_eq!(
9047 dry.ink_box(id).map(|r| (r.width, r.height)),
9048 Some((120.0, 60.0)),
9049 "the registry carries the **whole** box, which is what sizes the splash"
9050 );
9051
9052 // A finger lands in the top-left corner, and is still down.
9053 let mut rt = Runtime::default();
9054 rt.input.pressed = Some(id);
9055 rt.ink_press(id, Point::new(10.0, 10.0), Size::new(120.0, 60.0));
9056 rt.advance_ink(1.0 / 60.0);
9057 let ui = build_ui(&tree, size, &rt, &Theme::default());
9058 assert_eq!(ui.scene.len(), plain + 1, "the splash adds one layer");
9059
9060 // It is a shape-clipped layer, so the ink cannot escape the rounded corners…
9061 let (index, clip_shape) = ui
9062 .scene
9063 .primitives()
9064 .iter()
9065 .enumerate()
9066 .find_map(|(i, p)| match p {
9067 frus_core::Primitive::Layer { clip_shape, .. } => Some((i, clip_shape.clone())),
9068 _ => None,
9069 })
9070 .expect("the ink is a composited layer");
9071 assert_eq!(clip_shape, frus_core::ClipShape::RRect(8.0.into()));
9072
9073 // …and it is painted **before** the child that sits on top of it: the ink is
9074 // under the content, the way a material surface holds it.
9075 let child_index = ui
9076 .scene
9077 .primitives()
9078 .iter()
9079 .rposition(|p| matches!(p, frus_core::Primitive::Rect { .. }))
9080 .expect("the child painted a rectangle");
9081 assert!(
9082 index < child_index,
9083 "ink at {index} must come before the content at {child_index}"
9084 );
9085 }
9086
9087 #[test]
9088 fn a_splash_left_unconfirmed_does_not_wait_for_ever() {
9089 // The finger came down and never came back up on this widget — it slid off, or
9090 // the widget went away mid-press. Nothing will ever confirm the splash, and
9091 // without the sweep in `advance_ink` the ink would sit there for good.
9092 let mut rt = Runtime::default();
9093 let id = WidgetId::from_u64(42);
9094 rt.input.pressed = Some(id);
9095 rt.ink_press(id, Point::new(5.0, 5.0), Size::new(100.0, 40.0));
9096 // Held for a fifth of a second: the ink is up, and it stays up.
9097 for _ in 0..12 {
9098 rt.advance_ink(1.0 / 60.0);
9099 }
9100 assert!(rt.ink.contains_key(&id), "the splash waits for the finger");
9101
9102 // The finger is gone and nothing confirmed the tap.
9103 rt.input.pressed = None;
9104 let mut frames = 0;
9105 while rt.advance_ink(1.0 / 60.0) && frames < 200 {
9106 frames += 1;
9107 }
9108 assert!(rt.ink.is_empty(), "the ink is gone after {frames} frames");
9109 assert!(frames <= 6, "and quickly: a cancel is 75 ms, took {frames}");
9110 }
9111
9112 #[test]
9113 fn an_overscroll_glow_is_painted_over_its_scroll_area() {
9114 let tree = SingleChildScrollView::<Msg>::new()
9115 .width(200.0)
9116 .height(100.0)
9117 .child(Container::<Msg>::new().width(100.0).height(400.0));
9118 let size = Size::new(200.0, 100.0);
9119
9120 // Quiet: nothing extra is drawn.
9121 let rt = Runtime::default();
9122 let plain = build_ui(&tree, size, &rt, &Theme::default()).scene.len();
9123
9124 // A fling has just landed on the bottom edge.
9125 let mut rt = Runtime::default();
9126 let id = build_ui(&tree, size, &rt, &Theme::default()).scroll_regions()[0].id;
9127 rt.glow_absorb(
9128 id,
9129 Some(crate::physics::OverscrollIndicator::Glow),
9130 crate::overscroll::GlowEdge::Bottom,
9131 4000.0,
9132 );
9133 rt.advance_glow(0.02);
9134 let ui = build_ui(&tree, size, &rt, &Theme::default());
9135 assert_eq!(
9136 ui.scene.len(),
9137 plain + 1,
9138 "the glow adds exactly one shape to the frame"
9139 );
9140 // The glow sits under the scrollbars, so it is not the last primitive: it is
9141 // the only filled path in the frame.
9142 let clip = ui
9143 .scene
9144 .primitives()
9145 .iter()
9146 .find_map(|p| match p {
9147 frus_core::Primitive::Path { clip, .. } => Some(*clip),
9148 _ => None,
9149 })
9150 .expect("the glow is a filled path");
9151 // Drawn against the bottom of the viewport, and inside it.
9152 assert!(
9153 (clip.y + clip.height - 100.0).abs() < 1.0,
9154 "clip = {clip:?}"
9155 );
9156 assert!(clip.width <= 200.0 + 1e-3);
9157 }
9158
9159 /// **A list's rows go through the same walk as the rest of the tree** (milestone 592): a
9160 /// carousel in each row is a scroll area of its own. The reduced walk the rows used to take
9161 /// knew no scroll area.
9162 #[test]
9163 fn a_list_row_is_walked_like_the_rest_of_the_tree() {
9164 let tree = crate::ListView::<Msg>::new(20, 60.0, |_| {
9165 SingleChildScrollView::<Msg>::new()
9166 .axis(crate::scroll::Axis::Horizontal)
9167 .height(60.0)
9168 .child(Container::<Msg>::new().width(900.0).height(60.0))
9169 })
9170 .width(300.0)
9171 .height(200.0);
9172 let ui = build_ui(
9173 &tree,
9174 Size::new(300.0, 200.0),
9175 &Runtime::default(),
9176 &Theme::default(),
9177 );
9178 let regions = ui.scroll_regions();
9179 assert!(
9180 regions.len() >= 4,
9181 "the list and a carousel per visible row: {}",
9182 regions.len()
9183 );
9184 assert!(
9185 regions.iter().any(|r| r.max_x > 0.0),
9186 "a row scrolls across: {regions:?}"
9187 );
9188 }
9189
9190 /// The stretch layers of a frame: their owner and their transform.
9191 fn stretch_layers(ui: &Ui<Msg>) -> Vec<(u64, frus_core::Affine)> {
9192 ui.scene
9193 .primitives()
9194 .iter()
9195 .filter_map(|p| match p {
9196 frus_core::Primitive::Layer {
9197 transform: Some(transform),
9198 owner,
9199 ..
9200 } => Some((*owner, transform.affine)),
9201 _ => None,
9202 })
9203 .collect()
9204 }
9205
9206 /// **Where the indicator is the stretch, a pull deforms the content and draws no
9207 /// glow** (milestone 591): one layer holds the whole content, scaled down the axis
9208 /// from the top it is pulled past, and a button in it is touched where it is drawn.
9209 #[test]
9210 fn a_stretch_scales_the_content_from_the_edge_pulled() {
9211 let tree = SingleChildScrollView::<Msg>::new()
9212 .width(200.0)
9213 .height(100.0)
9214 .child(
9215 Flex::<Msg>::column()
9216 .child(Container::<Msg>::new().width(100.0).height(50.0))
9217 .child(crate::Button::new("Go").on_press(Msg::A))
9218 .child(Container::<Msg>::new().width(100.0).height(400.0)),
9219 );
9220 let size = Size::new(200.0, 100.0);
9221 let mut rt = Runtime::default();
9222 let quiet = build_ui(&tree, size, &rt, &Theme::default());
9223 let id = quiet.scroll_regions()[0].id;
9224 assert!(
9225 stretch_layers(&quiet).is_empty(),
9226 "at rest, nothing is deformed"
9227 );
9228 let button = quiet
9229 .focusable_ids()
9230 .find_map(|b| quiet.widget_rect(b))
9231 .expect("the button");
9232
9233 rt.glow_pull(
9234 id,
9235 Some(crate::physics::OverscrollIndicator::Stretch),
9236 crate::overscroll::GlowEdge::Top,
9237 100.0,
9238 100.0,
9239 0.0,
9240 200.0,
9241 );
9242 assert!(
9243 rt.scroll_glow.is_empty(),
9244 "no glow where the content stretches"
9245 );
9246 let ui = build_ui(&tree, size, &rt, &Theme::default());
9247 let layers = stretch_layers(&ui);
9248 assert_eq!(layers.len(), 1, "{layers:?}");
9249 let (owner, m) = layers[0];
9250 assert_eq!(owner, id.as_u64());
9251 let top = m.apply(Point::new(0.0, 0.0));
9252 let low = m.apply(Point::new(200.0, 100.0));
9253 assert!(top.y.abs() < 1e-3, "the top holds: {top:?}");
9254 assert!((low.x - 200.0).abs() < 1e-3, "not across: {low:?}");
9255 assert!(low.y > 100.5, "down the axis: {low:?}");
9256 let moved = ui
9257 .focusable_ids()
9258 .find_map(|b| ui.widget_rect(b))
9259 .expect("the button");
9260 assert!(
9261 moved.y > button.y && moved.height > button.height,
9262 "touched where drawn: {button:?} -> {moved:?}"
9263 );
9264
9265 // Letting go springs it back, and the layer goes with it.
9266 rt.glow_scroll_end(id);
9267 while rt.advance_glow(1.0 / 60.0) {}
9268 assert!(rt.scroll_stretch.is_empty());
9269 assert!(stretch_layers(&build_ui(&tree, size, &rt, &Theme::default())).is_empty());
9270 }
9271
9272 /// A list stretches the same way, from the bottom when pulled past its end.
9273 #[test]
9274 fn a_list_stretches_from_its_end() {
9275 let tree = crate::ListView::<Msg>::new(50, 20.0, |i| crate::Text::new(format!("{i}")))
9276 .width(200.0)
9277 .height(100.0);
9278 let size = Size::new(200.0, 100.0);
9279 let mut rt = Runtime::default();
9280 let id = build_ui(&tree, size, &rt, &Theme::default()).scroll_regions()[0].id;
9281 rt.glow_absorb(
9282 id,
9283 Some(crate::physics::OverscrollIndicator::Stretch),
9284 crate::overscroll::GlowEdge::Bottom,
9285 4000.0,
9286 );
9287 rt.advance_glow(0.02);
9288 let ui = build_ui(&tree, size, &rt, &Theme::default());
9289 let layers = stretch_layers(&ui);
9290 assert_eq!(layers.len(), 1);
9291 let m = layers[0].1;
9292 assert!((m.apply(Point::new(0.0, 100.0)).y - 100.0).abs() < 1e-3);
9293 assert!(m.apply(Point::new(0.0, 0.0)).y < -0.5);
9294 }
9295
9296 /// **An area's own physics lie over its behaviour's** (milestone 649): never or always
9297 /// scrollable keeps the platform's feel, and a feel given keeps the platform's rule.
9298 #[test]
9299 fn an_area_s_physics_lie_over_its_behaviour_s() {
9300 use crate::physics::{ScrollFeel, UserScroll};
9301 use frus_core::TargetPlatform as P;
9302 let scroll = |physics: ScrollPhysics, height: f32| {
9303 SingleChildScrollView::new()
9304 .width(200.0)
9305 .height(100.0)
9306 .physics(physics)
9307 .child(Container::<Msg>::new().width(100.0).height(height))
9308 };
9309 let rt = Runtime::default();
9310 let _root = crate::ScrollConfiguration::install(crate::ScrollBehavior::material());
9311 let region = |tree: &dyn Widget<Msg>, platform: P| {
9312 let theme = Theme::default().with_platform(platform);
9313 build_ui(tree, Size::new(200.0, 100.0), &rt, &theme).scroll_regions()[0]
9314 };
9315 let never = region(&scroll(ScrollPhysics::NEVER, 400.0), P::Ios);
9316 assert_eq!(never.physics.user(), UserScroll::Never);
9317 assert_eq!(
9318 never.physics.feel(),
9319 ScrollFeel::Bouncing(crate::physics::ScrollDecelerationRate::Normal),
9320 "the platform's feel"
9321 );
9322 assert!(
9323 !never.accepts_user_offset((0.0, 0.0)),
9324 "content to reveal, and no finger"
9325 );
9326 let always = region(&scroll(ScrollPhysics::ALWAYS, 50.0), P::Android);
9327 assert_eq!(always.physics.feel(), ScrollFeel::Clamping);
9328 assert!(
9329 always.accepts_user_offset((0.0, 0.0)),
9330 "nothing to reveal, and a finger"
9331 );
9332 assert_eq!(always.axis, crate::scroll::Axis::Vertical);
9333 let bouncing = region(&scroll(ScrollPhysics::BOUNCING, 400.0), P::Android);
9334 assert_eq!(
9335 bouncing.physics,
9336 ScrollPhysics::BOUNCING,
9337 "a feel given, the default rule"
9338 );
9339 }
9340
9341 /// **What an area does is its scroll behaviour's, settled when it is registered**
9342 /// (milestone 616): under the application's behaviour it follows the theme's
9343 /// platform, a `ScrollConfiguration` changes it for its subtree, and the area's own
9344 /// physics win over both.
9345 #[test]
9346 fn a_scroll_area_carries_its_physics_into_the_registry() {
9347 use frus_core::TargetPlatform as P;
9348 let tall = || Container::<Msg>::new().width(100.0).height(400.0);
9349 let plain = || {
9350 SingleChildScrollView::new()
9351 .width(200.0)
9352 .height(100.0)
9353 .child(tall())
9354 };
9355 let rt = Runtime::default();
9356 let _root = crate::ScrollConfiguration::install(crate::ScrollBehavior::material());
9357 let region = |tree: &dyn Widget<Msg>, platform: P| {
9358 let theme = Theme::default().with_platform(platform);
9359 build_ui(tree, Size::new(200.0, 100.0), &rt, &theme).scroll_regions()[0]
9360 };
9361
9362 // Untold: the theme's platform decides, through the behaviour.
9363 let ios = region(&plain(), P::Ios);
9364 assert_eq!(ios.physics, ScrollPhysics::BOUNCING);
9365 assert_eq!(ios.overscroll, None, "nothing past the edge on iOS");
9366 assert_eq!(
9367 ios.fling,
9368 frus_core::VelocityStrategy::RecentAverage(frus_core::BOUNCING_FLING_WEIGHTS)
9369 );
9370 let android = region(&plain(), P::Android);
9371 assert_eq!(android.physics, ScrollPhysics::CLAMPING);
9372 assert_eq!(
9373 android.overscroll,
9374 Some(crate::OverscrollIndicator::Stretch)
9375 );
9376 assert_eq!(android.fling, frus_core::VelocityStrategy::Regression);
9377
9378 // A subtree under another behaviour scrolls as that one says.
9379 let configured = crate::ScrollConfiguration::new(
9380 crate::ScrollBehavior::material()
9381 .with_physics(ScrollPhysics::BOUNCING)
9382 .with_overscroll(false),
9383 plain(),
9384 );
9385 let inside = region(&configured, P::Android);
9386 assert_eq!(inside.physics, ScrollPhysics::BOUNCING);
9387 assert_eq!(inside.overscroll, None);
9388 // And only that subtree: the behaviour is put back after it.
9389 assert_eq!(
9390 crate::ScrollConfiguration::of(),
9391 crate::ScrollBehavior::material()
9392 );
9393
9394 // Told: the area's own choice wins over the behaviour's.
9395 let bouncy = SingleChildScrollView::new()
9396 .width(200.0)
9397 .height(100.0)
9398 .physics(ScrollPhysics::BOUNCING)
9399 .child(tall());
9400 let area = region(&bouncy, P::Android);
9401 assert_eq!(area.physics, ScrollPhysics::BOUNCING);
9402 // And the metrics it hands the physics describe the right axis.
9403 let metrics = area.metrics_y(10.0);
9404 assert_eq!(metrics.pixels, 10.0);
9405 assert_eq!(metrics.max, 300.0); // 400 of content in a 100 viewport
9406 assert_eq!(metrics.viewport, 100.0);
9407 }
9408
9409 #[test]
9410 fn scroll_translates_and_clips_content() {
9411 let content = Flex::<Msg>::column()
9412 .gap(0.0)
9413 .child(
9414 Container::new()
9415 .height(60.0)
9416 .color(Color::rgb(1.0, 0.0, 0.0)),
9417 )
9418 .child(
9419 Container::new()
9420 .height(60.0)
9421 .color(Color::rgb(0.0, 1.0, 0.0)),
9422 )
9423 .child(
9424 Container::new()
9425 .height(60.0)
9426 .color(Color::rgb(0.0, 0.0, 1.0)),
9427 );
9428 let tree = SingleChildScrollView::new()
9429 .width(200.0)
9430 .height(100.0)
9431 .child(content);
9432
9433 let rt = Runtime::default();
9434 let ui = build_ui(&tree, Size::new(200.0, 100.0), &rt, &Theme::default());
9435 let area = ui.scrollables[0];
9436 let sid = area.id;
9437 assert_eq!(area.max_y, 80.0); // 180 - 100
9438 assert_eq!(area.max_x, 0.0);
9439 assert_eq!(ui.first_rect().0.y, 0.0);
9440 assert_eq!(ui.first_rect().1, Rect::new(0.0, 0.0, 200.0, 100.0));
9441
9442 let mut rt = Runtime::default();
9443 rt.scroll.insert(sid, (0.0, 50.0));
9444 let ui2 = build_ui(&tree, Size::new(200.0, 100.0), &rt, &Theme::default());
9445 assert_eq!(ui2.first_rect().0.y, -50.0);
9446 }
9447
9448 #[test]
9449 fn kanban_cards_are_reorderable_without_being_clickable() {
9450 use crate::Kanban;
9451 let board = Kanban::new(|_, _, _, _| Msg::A).column("To do", ["Card A"]);
9452 let rt = Runtime::default();
9453 let ui = build_ui(&board, Size::new(400.0, 300.0), &rt, &Theme::default());
9454 // The card **and** the drop zone are registered as reorderables.
9455 assert!(
9456 ui.reorderables.len() >= 2,
9457 "the card + the drop zone are in the reorderables registry"
9458 );
9459 // A point on the card can be **picked up** (it is reorderable) but is **not clickable**
9460 // — which is the whole point of the registry: without it, `ui.hit` alone would never
9461 // find the card.
9462 let (card_id, card) = ui.reorderables[0];
9463 let p = Point::new(card.x + 5.0, card.y + 5.0);
9464 assert!(
9465 ui.reorderable_at(p).is_some(),
9466 "the card can be picked up at that point"
9467 );
9468 assert!(
9469 ui.hit(p).is_none(),
9470 "…but it is not clickable (absent from the hit registry)"
9471 );
9472 // `widget_rect` must find the card **through the reorderable fallback** (it is not
9473 // focusable): otherwise the shell's vertical drag preview never starts.
9474 assert_eq!(
9475 ui.widget_rect(card_id),
9476 Some(card),
9477 "widget_rect falls back to the reorderables registry"
9478 );
9479 }
9480
9481 #[test]
9482 fn reorderables_inside_a_scroll_are_still_registered() {
9483 // The milestone 258/260 scenario: the board (with its reorderable cards) is **wrapped
9484 // in a `SingleChildScrollView`**. The reorderables must stay registered — otherwise dragging a card
9485 // stops engaging as soon as the board scrolls.
9486 use crate::{Axis, Kanban, SingleChildScrollView};
9487 let board = Kanban::new(|_, _, _, _| Msg::A).column("To do", ["Card A"]);
9488 let scrolled = SingleChildScrollView::new()
9489 .axis(Axis::Horizontal)
9490 .width(400.0)
9491 .height(300.0)
9492 .child(board);
9493 let rt = Runtime::default();
9494 let ui = build_ui(&scrolled, Size::new(400.0, 300.0), &rt, &Theme::default());
9495 assert!(
9496 ui.reorderables.len() >= 2,
9497 "the card + the drop zone stay reorderable even inside a SingleChildScrollView (got {})",
9498 ui.reorderables.len()
9499 );
9500 }
9501
9502 #[test]
9503 fn reorderables_inside_a_per_column_card_scroll_are_still_registered() {
9504 // Milestone 264: `card_area_height` puts each column's cards inside a **vertical
9505 // `SingleChildScrollView` with an explicit height**. This is exactly the case that *collapsed* at
9506 // milestone 263 (a flex scroll with no defined ancestor height → cards clipped to zero
9507 // and no longer reorderable). With a **defined** height the visible cards must stay
9508 // registered as reorderables — a guard against a regression of per-column dragging.
9509 use crate::Kanban;
9510 let board = Kanban::new(|_, _, _, _| Msg::A)
9511 .card_area_height(220.0)
9512 .column("To do", ["Card A", "Card B"]);
9513 let rt = Runtime::default();
9514 let ui = build_ui(&board, Size::new(400.0, 300.0), &rt, &Theme::default());
9515 assert!(
9516 ui.reorderables.len() >= 3,
9517 "2 cards + the drop zone stay reorderable inside a vertical scroll with a defined height \
9518 (got {})",
9519 ui.reorderables.len()
9520 );
9521 }
9522
9523 #[test]
9524 fn scrollable_columns_fill_the_board_height_then_scroll() {
9525 // Milestone 266: `Kanban::scrollable_columns()` makes the columns **fill** the board's
9526 // height (laid out in an ancestor with a defined height), and each column scrolls its
9527 // cards vertically **with no explicit height** (the flex does the arithmetic, so the
9528 // milestone 264 stopgap is gone). This checks that at least one column has a vertical
9529 // `SingleChildScrollView` whose viewport **fills** the height (far more than the default 200) and
9530 // **scrolls** (max_y > 0), which is the proof of fill-then-scroll.
9531 use crate::{Axis, Container, Flex, Kanban, SingleChildScrollView};
9532 // Enough cards to **overflow** the filled viewport (otherwise max_y = 0: nothing to scroll).
9533 let long: Vec<String> = (0..24).map(|i| format!("card {i}")).collect();
9534 let board = Kanban::new(|_, _, _, _| Msg::A)
9535 .scrollable_columns()
9536 .column("To do", long);
9537 // `board_screen`'s nesting: the board inside a **plain `Container` with padding** (the
9538 // visual margin), itself inside a horizontal `flex(1)` SingleChildScrollView, inside a screen (a Flex
9539 // column) of bounded height. That `Auto` `Container` **collapsed** at milestone 266
9540 // (hence the `Flex` `flex(1)` workaround); since `compute_scroll` **fills the
9541 // constrained axis**, it fills the viewport's height and the board follows — no filler
9542 // container needed any more.
9543 let padded = Container::<Msg>::new().padding(24.0).child(board);
9544 let scroll_h = SingleChildScrollView::new()
9545 .axis(Axis::Horizontal)
9546 .width(360.0)
9547 .flex(1.0)
9548 .child(padded);
9549 let root: Flex<Msg> = Flex::column().width(400.0).height(600.0).child(scroll_h);
9550 let ui = build_ui(
9551 &root,
9552 Size::new(400.0, 600.0),
9553 &Runtime::default(),
9554 &Theme::default(),
9555 );
9556 // A column's **vertical** scroll: a tall viewport (it fills) and it scrolls.
9557 let filled = ui
9558 .scrollables
9559 .iter()
9560 .any(|area| area.viewport.height > 300.0 && area.max_y > 0.0);
9561 assert!(
9562 filled,
9563 "a column fills the board's height then scrolls (scrollables: {:?})",
9564 ui.scrollables
9565 );
9566 }
9567
9568 #[test]
9569 fn subtree_ids_covers_a_widget_and_its_descendants() {
9570 use crate::Text;
9571 // Root (Container) > Flex(column) > [Text, Text].
9572 let tree: Container<Msg> = Container::new().child(
9573 Flex::<Msg>::column()
9574 .child(Text::new("a"))
9575 .child(Text::new("b")),
9576 );
9577 let all = collect_ids(&tree);
9578 // From the root: identical to `collect_ids` (the same positional walk).
9579 assert_eq!(subtree_ids(&tree, WidgetId::ROOT), all);
9580 // A child's subtree starts with its own identity and stays a **strict** subset of the
9581 // tree (which is how a rich card's ghost captures all of its content).
9582 let flex_id = all[1];
9583 let sub = subtree_ids(Widget::children(&tree)[0].as_ref(), flex_id);
9584 assert_eq!(
9585 sub[0], flex_id,
9586 "the subtree starts with the identity supplied"
9587 );
9588 assert!(
9589 sub.len() < all.len() && sub.iter().all(|i| all.contains(i)),
9590 "a subset of the tree including the descendants"
9591 );
9592 }
9593
9594 impl<Msg: Clone> Ui<Msg> {
9595 fn first_rect(&self) -> (Rect, Rect) {
9596 for primitive in self.scene.primitives() {
9597 if let Primitive::Rect { rect, clip, .. } = primitive {
9598 return (*rect, *clip);
9599 }
9600 }
9601 panic!("no rect at all");
9602 }
9603 }
9604
9605 /// A static subtree under `RepaintBoundary` (mixed content: text + boxes) — enough to
9606 /// produce several primitives.
9607 fn boundary_tree() -> Container<Msg> {
9608 use crate::Text;
9609 Container::new().repaint_boundary().child(
9610 Flex::<Msg>::column()
9611 .child(Text::new("Statique"))
9612 .child(Container::new().width(30.0).height(20.0).on_click(Msg::A))
9613 .child(Button::new("ok").on_press(Msg::B)),
9614 )
9615 }
9616
9617 #[test]
9618 fn repaint_boundary_reuses_a_static_subtree_bit_identical() {
9619 let tree = boundary_tree();
9620 let size = Size::new(200.0, 200.0);
9621 let theme = Theme::default();
9622 let rt = Runtime::default();
9623
9624 // Frame 1: nothing cached → 1 miss (a full paint), the subtree is captured.
9625 let ui1 = build_ui(&tree, size, &rt, &theme);
9626 // The **primitives** are what is compared (the scene's transient ambient state — the
9627 // current clip/owner — is not rendered).
9628 let dbg1 = format!("{:?}", ui1.scene().primitives());
9629 assert_eq!(rt.paint_cache.borrow().last_frame_stats(), (0, 1));
9630
9631 // Frame 2: the same generation + the same state → the boundary is reused.
9632 let ui2 = build_ui(&tree, size, &rt, &theme);
9633 let dbg2 = format!("{:?}", ui2.scene().primitives());
9634 assert_eq!(
9635 rt.paint_cache.borrow().last_frame_stats(),
9636 (1, 0),
9637 "the boundary is reused"
9638 );
9639 assert_eq!(
9640 dbg1, dbg2,
9641 "the replayed scene is bit-for-bit identical to the full repaint"
9642 );
9643 // The interaction maps are replayed too (a click stays routable).
9644 assert_eq!(ui1.hits.len(), ui2.hits.len());
9645 assert!(!ui2.hits.is_empty(), "the subtree's hit is indeed replayed");
9646 }
9647
9648 #[test]
9649 fn repaint_boundary_invalidated_by_generation_bump() {
9650 let tree = boundary_tree();
9651 let size = Size::new(200.0, 200.0);
9652 let theme = Theme::default();
9653 let rt = Runtime::default();
9654
9655 build_ui(&tree, size, &rt, &theme); // frame 1 : miss + capture
9656
9657 // The `view` is rebuilt (the config may have changed).
9658 rt.paint_cache.borrow_mut().bump_generation();
9659 build_ui(&tree, size, &rt, &theme); // frame 2
9660 assert_eq!(
9661 rt.paint_cache.borrow().last_frame_stats(),
9662 (0, 1),
9663 "a stale generation → a full repaint"
9664 );
9665 }
9666
9667 #[test]
9668 fn repaint_boundary_invalidated_by_interaction_change() {
9669 let tree = boundary_tree();
9670 let size = Size::new(200.0, 200.0);
9671 let theme = Theme::default();
9672 let mut rt = Runtime::default();
9673
9674 build_ui(&tree, size, &rt, &theme); // frame 1 : miss + capture
9675
9676 // No rebuild, but a descendant's interaction state changes (the boundary's animated
9677 // hover) → the fingerprint differs → a repaint.
9678 rt.anims.insert(
9679 WidgetId::ROOT,
9680 crate::Anim {
9681 hover: 0.5,
9682 ..Default::default()
9683 },
9684 );
9685 build_ui(&tree, size, &rt, &theme); // frame 2
9686 assert_eq!(
9687 rt.paint_cache.borrow().last_frame_stats(),
9688 (0, 1),
9689 "the interaction state changed → a full repaint"
9690 );
9691
9692 // Once the state has settled, the boundary is reused again.
9693 build_ui(&tree, size, &rt, &theme); // frame 3
9694 assert_eq!(rt.paint_cache.borrow().last_frame_stats(), (1, 0));
9695 }
9696}