Skip to main content

sui_widgets/
containers.rs

1use crate::draw::{inset_rect, mix_color};
2use std::{cell::RefCell, ops::Range, rc::Rc, sync::Arc};
3
4use sui_core::{
5    DragEvent, DragEventKind, Event, InvalidationKind, InvalidationRequest, InvalidationTarget,
6    KeyState, Path, Point, PointerButton, PointerEvent, PointerEventKind, PointerKind, Rect,
7    ScrollDelta, SemanticsAction, SemanticsActionRequest, SemanticsNode, SemanticsRole,
8    SemanticsValue, Size, Vector, WakeEvent, WidgetId, WindowEvent,
9};
10use sui_layout::{
11    Alignment, Axis, Constraints, FlexAlignContent, FlexItem, FlexJustify, FlexMeasurePhase,
12    FlexStyle, FlexWrap, IntrinsicSize, Padding as Insets, arrange_flex, flex_layout,
13    flex_layout_with_probes,
14};
15use sui_reactive::Observable;
16use sui_runtime::{
17    ArrangeCtx, Command, EventCtx, EventPhase, FrameClock, LayerOptions, MeasureCtx,
18    PaintBoundaryMode, PaintCtx, REACTIVE_CHANGED, SemanticsCtx, SingleChild, Widget,
19    WidgetChildren, WidgetPod, WidgetPodMutVisitor, WidgetPodVisitor,
20};
21use sui_scene::{Brush, LayerCompositionMode};
22
23use crate::DefaultTheme;
24use crate::frame::{physical_pixels, snap_to_pixels, stroke_border};
25
26pub struct Padding {
27    insets: Insets,
28    fill_child_width: bool,
29    fill_child_height: bool,
30    child: SingleChild,
31}
32
33impl Padding {
34    pub fn new<W>(insets: Insets, child: W) -> Self
35    where
36        W: Widget + 'static,
37    {
38        Self {
39            insets,
40            fill_child_width: false,
41            fill_child_height: false,
42            child: SingleChild::new(child),
43        }
44    }
45
46    pub fn all<W>(value: f32, child: W) -> Self
47    where
48        W: Widget + 'static,
49    {
50        Self::new(Insets::all(value), child)
51    }
52
53    pub fn horizontal<W>(value: f32, child: W) -> Self
54    where
55        W: Widget + 'static,
56    {
57        let value = value.max(0.0);
58        Self::new(
59            Insets {
60                left: value,
61                top: 0.0,
62                right: value,
63                bottom: 0.0,
64            },
65            child,
66        )
67    }
68
69    pub fn vertical<W>(value: f32, child: W) -> Self
70    where
71        W: Widget + 'static,
72    {
73        let value = value.max(0.0);
74        Self::new(
75            Insets {
76                left: 0.0,
77                top: value,
78                right: 0.0,
79                bottom: value,
80            },
81            child,
82        )
83    }
84
85    pub fn symmetric<W>(horizontal: f32, vertical: f32, child: W) -> Self
86    where
87        W: Widget + 'static,
88    {
89        Self::new(
90            Insets {
91                left: horizontal.max(0.0),
92                top: vertical.max(0.0),
93                right: horizontal.max(0.0),
94                bottom: vertical.max(0.0),
95            },
96            child,
97        )
98    }
99
100    pub fn insets(&self) -> Insets {
101        self.insets
102    }
103
104    pub fn fill_child_width(mut self, fill_child_width: bool) -> Self {
105        self.fill_child_width = fill_child_width;
106        self
107    }
108
109    pub fn fill_child_height(mut self, fill_child_height: bool) -> Self {
110        self.fill_child_height = fill_child_height;
111        self
112    }
113
114    pub fn fill_child(mut self) -> Self {
115        self.fill_child_width = true;
116        self.fill_child_height = true;
117        self
118    }
119
120    pub fn child_pod(&self) -> &WidgetPod {
121        self.child.child()
122    }
123
124    pub fn child_mut(&mut self) -> &mut WidgetPod {
125        self.child.child_mut()
126    }
127}
128
129impl Widget for Padding {
130    fn supports_output_reuse(&self) -> bool {
131        true
132    }
133    fn measure_axis(&mut self, ctx: &mut MeasureCtx, constraints: Constraints, axis: Axis) -> f32 {
134        let (min, max, padding) = match axis {
135            Axis::Horizontal => (
136                constraints.min.width,
137                constraints.max.width,
138                self.insets.left + self.insets.right,
139            ),
140            Axis::Vertical => (
141                constraints.min.height,
142                constraints.max.height,
143                self.insets.top + self.insets.bottom,
144            ),
145        };
146        if min == max {
147            return min;
148        }
149        let extent =
150            self.child
151                .measure_axis(ctx, inset_constraints(constraints, self.insets), axis);
152        (extent + padding).clamp(min, max)
153    }
154
155    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
156        let child_constraints = inset_constraints(constraints, self.insets);
157        let child_size = self.child.measure(ctx, child_constraints);
158
159        constraints.clamp(expand_size(child_size, self.insets))
160    }
161
162    fn measure_size(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
163        let child_constraints = inset_constraints(constraints, self.insets);
164        let child_size = self.child.measure_size(ctx, child_constraints);
165
166        constraints.clamp(expand_size(child_size, self.insets))
167    }
168
169    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
170        let content = inset_rect(bounds, self.insets);
171        let measured = self.child.child().measured_size();
172        let child_size = Size::new(
173            if self.fill_child_width {
174                content.width()
175            } else {
176                measured.width.min(content.width())
177            },
178            if self.fill_child_height {
179                content.height()
180            } else {
181                measured.height.min(content.height())
182            },
183        );
184        self.child
185            .arrange(ctx, Rect::from_origin_size(content.origin, child_size));
186    }
187
188    fn paint(&self, ctx: &mut PaintCtx) {
189        self.child.paint(ctx);
190    }
191
192    fn semantics(&self, ctx: &mut SemanticsCtx) {
193        self.child.semantics(ctx);
194    }
195
196    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
197        self.child.visit_children(visitor);
198    }
199
200    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
201        self.child.visit_children_mut(visitor);
202    }
203}
204
205pub struct Align {
206    horizontal: Alignment,
207    vertical: Alignment,
208    child: SingleChild,
209}
210
211impl Align {
212    pub fn new<W>(horizontal: Alignment, vertical: Alignment, child: W) -> Self
213    where
214        W: Widget + 'static,
215    {
216        Self {
217            horizontal,
218            vertical,
219            child: SingleChild::new(child),
220        }
221    }
222
223    pub fn center<W>(child: W) -> Self
224    where
225        W: Widget + 'static,
226    {
227        Self::new(Alignment::Center, Alignment::Center, child)
228    }
229
230    pub fn child_pod(&self) -> &WidgetPod {
231        self.child.child()
232    }
233
234    pub fn child_mut(&mut self) -> &mut WidgetPod {
235        self.child.child_mut()
236    }
237}
238
239impl Widget for Align {
240    fn supports_output_reuse(&self) -> bool {
241        true
242    }
243    fn measure_axis(&mut self, ctx: &mut MeasureCtx, constraints: Constraints, axis: Axis) -> f32 {
244        let (min, max, alignment) = match axis {
245            Axis::Horizontal => (
246                constraints.min.width,
247                constraints.max.width,
248                self.horizontal,
249            ),
250            Axis::Vertical => (
251                constraints.min.height,
252                constraints.max.height,
253                self.vertical,
254            ),
255        };
256        if min == max || (alignment == Alignment::Stretch && max.is_finite()) {
257            return max;
258        }
259        let child_constraints =
260            aligned_child_constraints(constraints, self.horizontal, self.vertical);
261        self.child
262            .measure_axis(ctx, child_constraints, axis)
263            .clamp(min, max)
264    }
265
266    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
267        let child_constraints =
268            aligned_child_constraints(constraints, self.horizontal, self.vertical);
269        let child_size = self.child.measure(ctx, child_constraints);
270        constraints.clamp(Size::new(
271            stretched_dimension(self.horizontal, constraints.max.width, child_size.width),
272            stretched_dimension(self.vertical, constraints.max.height, child_size.height),
273        ))
274    }
275
276    fn measure_size(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
277        let child_constraints =
278            aligned_child_constraints(constraints, self.horizontal, self.vertical);
279        let child_size = self.child.measure_size(ctx, child_constraints);
280        constraints.clamp(Size::new(
281            stretched_dimension(self.horizontal, constraints.max.width, child_size.width),
282            stretched_dimension(self.vertical, constraints.max.height, child_size.height),
283        ))
284    }
285
286    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
287        let child_size = self.child.child().measured_size();
288        self.child.arrange(
289            ctx,
290            Rect::from_origin_size(
291                Point::new(
292                    bounds.x() + aligned_offset(self.horizontal, bounds.width() - child_size.width),
293                    bounds.y() + aligned_offset(self.vertical, bounds.height() - child_size.height),
294                ),
295                child_size,
296            ),
297        );
298    }
299
300    fn paint(&self, ctx: &mut PaintCtx) {
301        self.child.paint(ctx);
302    }
303
304    fn semantics(&self, ctx: &mut SemanticsCtx) {
305        self.child.semantics(ctx);
306    }
307
308    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
309        self.child.visit_children(visitor);
310    }
311
312    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
313        self.child.visit_children_mut(visitor);
314    }
315}
316
317pub struct Background {
318    brush: Brush,
319    brush_reader: Option<Box<dyn Fn() -> Brush>>,
320    child: SingleChild,
321}
322
323impl Background {
324    pub fn new<W>(brush: impl Into<Brush>, child: W) -> Self
325    where
326        W: Widget + 'static,
327    {
328        Self {
329            brush: brush.into(),
330            brush_reader: None,
331            child: SingleChild::new(child),
332        }
333    }
334
335    pub fn brush_when<F, B>(mut self, brush: F) -> Self
336    where
337        F: Fn() -> B + 'static,
338        B: Into<Brush>,
339    {
340        self.brush_reader = Some(Box::new(move || brush().into()));
341        self
342    }
343
344    pub fn child_pod(&self) -> &WidgetPod {
345        self.child.child()
346    }
347
348    pub fn child_mut(&mut self) -> &mut WidgetPod {
349        self.child.child_mut()
350    }
351}
352
353impl Widget for Background {
354    fn supports_output_reuse(&self) -> bool {
355        self.brush_reader.is_none()
356    }
357    fn measure_axis(&mut self, ctx: &mut MeasureCtx, constraints: Constraints, axis: Axis) -> f32 {
358        self.child.measure_axis(ctx, constraints, axis)
359    }
360
361    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
362        self.child.measure(ctx, constraints)
363    }
364
365    fn measure_size(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
366        self.child.measure_size(ctx, constraints)
367    }
368
369    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
370        self.child.arrange(ctx, bounds);
371    }
372
373    fn paint(&self, ctx: &mut PaintCtx) {
374        let brush = self
375            .brush_reader
376            .as_ref()
377            .map(|reader| reader())
378            .unwrap_or_else(|| self.brush.clone());
379        ctx.fill_bounds(brush);
380        self.child.paint(ctx);
381    }
382
383    fn semantics(&self, ctx: &mut SemanticsCtx) {
384        self.child.semantics(ctx);
385    }
386
387    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
388        self.child.visit_children(visitor);
389    }
390
391    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
392        self.child.visit_children_mut(visitor);
393    }
394}
395
396pub struct SemanticRegion {
397    name: String,
398    name_reader: Option<Box<dyn Fn() -> String>>,
399    description: Option<String>,
400    description_reader: Option<Box<dyn Fn() -> String>>,
401    role: SemanticsRole,
402    child: SingleChild,
403}
404
405impl SemanticRegion {
406    pub fn new<W>(name: impl Into<String>, child: W) -> Self
407    where
408        W: Widget + 'static,
409    {
410        Self {
411            name: name.into(),
412            name_reader: None,
413            description: None,
414            description_reader: None,
415            role: SemanticsRole::GenericContainer,
416            child: SingleChild::new(child),
417        }
418    }
419
420    pub fn name_when<F>(mut self, name: F) -> Self
421    where
422        F: Fn() -> String + 'static,
423    {
424        self.name_reader = Some(Box::new(name));
425        self
426    }
427
428    pub fn description(mut self, description: impl Into<String>) -> Self {
429        self.description = Some(description.into());
430        self.description_reader = None;
431        self
432    }
433
434    pub fn description_when<F>(mut self, description: F) -> Self
435    where
436        F: Fn() -> String + 'static,
437    {
438        self.description_reader = Some(Box::new(description));
439        self
440    }
441
442    pub fn role(mut self, role: SemanticsRole) -> Self {
443        self.role = role;
444        self
445    }
446
447    pub fn child_pod(&self) -> &WidgetPod {
448        self.child.child()
449    }
450
451    pub fn child_mut(&mut self) -> &mut WidgetPod {
452        self.child.child_mut()
453    }
454
455    fn name_text(&self) -> String {
456        self.name_reader
457            .as_ref()
458            .map(|reader| reader())
459            .unwrap_or_else(|| self.name.clone())
460    }
461
462    fn description_text(&self) -> Option<String> {
463        self.description_reader
464            .as_ref()
465            .map(|reader| reader())
466            .or_else(|| self.description.clone())
467    }
468}
469
470impl Widget for SemanticRegion {
471    fn supports_output_reuse(&self) -> bool {
472        true
473    }
474    fn measure_axis(&mut self, ctx: &mut MeasureCtx, constraints: Constraints, axis: Axis) -> f32 {
475        self.child.measure_axis(ctx, constraints, axis)
476    }
477
478    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
479        self.child.measure(ctx, constraints)
480    }
481
482    fn measure_size(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
483        self.child.measure_size(ctx, constraints)
484    }
485
486    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
487        self.child.arrange(ctx, bounds);
488    }
489
490    fn paint(&self, ctx: &mut PaintCtx) {
491        self.child.paint(ctx);
492    }
493
494    fn semantics(&self, ctx: &mut SemanticsCtx) {
495        let mut node = SemanticsNode::new(ctx.widget_id(), self.role.clone(), ctx.bounds());
496        node.name = Some(self.name_text());
497        node.description = self.description_text();
498        ctx.push(node);
499        self.child.semantics(ctx);
500    }
501
502    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
503        self.child.visit_children(visitor);
504    }
505
506    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
507        self.child.visit_children_mut(visitor);
508    }
509}
510
511pub struct SizedBox {
512    width: Option<f32>,
513    height: Option<f32>,
514    child: Option<SingleChild>,
515}
516
517impl SizedBox {
518    pub fn new() -> Self {
519        Self {
520            width: None,
521            height: None,
522            child: None,
523        }
524    }
525
526    pub fn width(mut self, width: f32) -> Self {
527        self.width = Some(width.max(0.0));
528        self
529    }
530
531    pub fn height(mut self, height: f32) -> Self {
532        self.height = Some(height.max(0.0));
533        self
534    }
535
536    pub fn size(mut self, size: Size) -> Self {
537        self.width = Some(size.width.max(0.0));
538        self.height = Some(size.height.max(0.0));
539        self
540    }
541
542    pub fn child<W>(mut self, child: W) -> Self
543    where
544        W: Widget + 'static,
545    {
546        self.child = Some(SingleChild::new(child));
547        self
548    }
549
550    pub fn child_pod(&self) -> Option<&WidgetPod> {
551        self.child.as_ref().map(SingleChild::child)
552    }
553
554    pub fn child_mut(&mut self) -> Option<&mut WidgetPod> {
555        self.child.as_mut().map(SingleChild::child_mut)
556    }
557}
558
559impl Default for SizedBox {
560    fn default() -> Self {
561        Self::new()
562    }
563}
564
565impl Widget for SizedBox {
566    fn supports_output_reuse(&self) -> bool {
567        true
568    }
569    fn measure_axis(&mut self, ctx: &mut MeasureCtx, constraints: Constraints, axis: Axis) -> f32 {
570        let (min, max, explicit) = match axis {
571            Axis::Horizontal => (constraints.min.width, constraints.max.width, self.width),
572            Axis::Vertical => (constraints.min.height, constraints.max.height, self.height),
573        };
574        if let Some(value) = explicit {
575            return value.clamp(min, max);
576        }
577        if min == max {
578            return min;
579        }
580        let child_constraints = sized_box_constraints(constraints, self.width, self.height);
581        self.child
582            .as_mut()
583            .map_or(0.0, |child| {
584                child.measure_axis(ctx, child_constraints, axis)
585            })
586            .clamp(min, max)
587    }
588
589    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
590        let child_constraints = sized_box_constraints(constraints, self.width, self.height);
591        let child_size = if let Some(child) = &mut self.child {
592            child.measure(ctx, child_constraints)
593        } else {
594            Size::ZERO
595        };
596
597        constraints.clamp(Size::new(
598            self.width.unwrap_or(child_size.width),
599            self.height.unwrap_or(child_size.height),
600        ))
601    }
602
603    fn measure_size(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
604        let child_constraints = sized_box_constraints(constraints, self.width, self.height);
605        let child_size = if let Some(child) = &mut self.child {
606            child.measure_size(ctx, child_constraints)
607        } else {
608            Size::ZERO
609        };
610
611        constraints.clamp(Size::new(
612            self.width.unwrap_or(child_size.width),
613            self.height.unwrap_or(child_size.height),
614        ))
615    }
616
617    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
618        if let Some(child) = &mut self.child {
619            let measured = child.child().measured_size();
620            let child_size = Size::new(
621                measured.width.min(bounds.width()),
622                measured.height.min(bounds.height()),
623            );
624            child.arrange(ctx, Rect::from_origin_size(bounds.origin, child_size));
625        }
626    }
627
628    fn paint(&self, ctx: &mut PaintCtx) {
629        if let Some(child) = &self.child {
630            child.paint(ctx);
631        }
632    }
633
634    fn semantics(&self, ctx: &mut SemanticsCtx) {
635        if let Some(child) = &self.child {
636            child.semantics(ctx);
637        }
638    }
639
640    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
641        if let Some(child) = &self.child {
642            child.visit_children(visitor);
643        }
644    }
645
646    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
647        if let Some(child) = &mut self.child {
648            child.visit_children_mut(visitor);
649        }
650    }
651}
652
653pub struct Stack {
654    axis: Axis,
655    spacing: f32,
656    alignment: Alignment,
657    children: WidgetChildren,
658}
659
660impl Stack {
661    pub fn new(axis: Axis) -> Self {
662        Self {
663            axis,
664            spacing: 0.0,
665            alignment: Alignment::Start,
666            children: WidgetChildren::new(),
667        }
668    }
669
670    pub fn horizontal() -> Self {
671        Self::new(Axis::Horizontal)
672    }
673
674    pub fn vertical() -> Self {
675        Self::new(Axis::Vertical)
676    }
677
678    pub fn gap(mut self, gap: f32) -> Self {
679        self.spacing = gap.max(0.0);
680        self
681    }
682
683    pub fn alignment(mut self, alignment: Alignment) -> Self {
684        self.alignment = alignment;
685        self
686    }
687
688    pub fn with_child<W>(mut self, child: W) -> Self
689    where
690        W: Widget + 'static,
691    {
692        self.children.push(child);
693        self
694    }
695
696    pub fn push<W>(&mut self, child: W)
697    where
698        W: Widget + 'static,
699    {
700        self.children.push(child);
701    }
702
703    pub fn children(&self) -> &[WidgetPod] {
704        self.children.as_slice()
705    }
706
707    pub fn children_mut(&mut self) -> &mut [WidgetPod] {
708        self.children.as_mut_slice()
709    }
710}
711
712impl Stack {
713    fn measure_children(
714        &mut self,
715        ctx: &mut MeasureCtx,
716        constraints: Constraints,
717        size_only: bool,
718    ) -> Size {
719        let max_main = axis_main(self.axis, constraints.max);
720        let max_cross = axis_cross(self.axis, constraints.max);
721        let stretch_cross = self.alignment == Alignment::Stretch && max_cross.is_finite();
722        let mut main_extent = 0.0;
723        let mut cross_extent: f32 = 0.0;
724
725        for (index, child) in self.children.as_mut_slice().iter_mut().enumerate() {
726            let spacing_before = if index == 0 { 0.0 } else { self.spacing };
727            let remaining_main = (max_main - main_extent - spacing_before).max(0.0);
728            let child_constraints =
729                stack_child_constraints(self.axis, remaining_main, max_cross, stretch_cross);
730            let child_size = if size_only {
731                child.probe_measure(ctx, child_constraints)
732            } else {
733                child.measure(ctx, child_constraints)
734            };
735            main_extent += spacing_before + axis_main(self.axis, child_size);
736            cross_extent = cross_extent.max(axis_cross(self.axis, child_size));
737        }
738
739        constraints.clamp(axis_size(self.axis, main_extent, cross_extent))
740    }
741}
742
743impl Widget for Stack {
744    fn supports_output_reuse(&self) -> bool {
745        true
746    }
747    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
748        self.measure_children(ctx, constraints, false)
749    }
750
751    fn measure_size(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
752        self.measure_children(ctx, constraints, true)
753    }
754
755    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
756        let cross_available = axis_cross(self.axis, bounds.size);
757        let mut main_offset = 0.0;
758
759        for (index, child) in self.children.as_mut_slice().iter_mut().enumerate() {
760            if index > 0 {
761                main_offset += self.spacing;
762            }
763
764            let child_size = stack_arranged_child_size(
765                self.axis,
766                self.alignment,
767                child.measured_size(),
768                cross_available,
769            );
770            let cross_offset = aligned_offset(
771                self.alignment,
772                cross_available - axis_cross(self.axis, child_size),
773            );
774            child.arrange(
775                ctx,
776                Rect::from_origin_size(
777                    Point::new(bounds.x(), bounds.y())
778                        + axis_point(self.axis, main_offset, cross_offset).to_vector(),
779                    child_size,
780                ),
781            );
782            main_offset += axis_main(self.axis, child_size);
783        }
784    }
785
786    fn paint(&self, ctx: &mut PaintCtx) {
787        self.children.paint(ctx);
788    }
789
790    fn semantics(&self, ctx: &mut SemanticsCtx) {
791        self.children.semantics(ctx);
792    }
793
794    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
795        self.children.visit_children(visitor);
796    }
797
798    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
799        self.children.visit_children_mut(visitor);
800    }
801}
802
803pub struct TrailingSlotRow {
804    body: SingleChild,
805    trailing: SingleChild,
806    trailing_width: f32,
807    trailing_height: f32,
808    gap: f32,
809}
810
811impl TrailingSlotRow {
812    pub fn new<B, T>(body: B, trailing: T) -> Self
813    where
814        B: Widget + 'static,
815        T: Widget + 'static,
816    {
817        Self {
818            body: SingleChild::new(body),
819            trailing: SingleChild::new(trailing),
820            trailing_width: 0.0,
821            trailing_height: 0.0,
822            gap: 0.0,
823        }
824    }
825
826    pub fn trailing_width(mut self, width: f32) -> Self {
827        self.trailing_width = width.max(0.0);
828        self
829    }
830
831    pub fn trailing_height(mut self, height: f32) -> Self {
832        self.trailing_height = height.max(0.0);
833        self
834    }
835
836    pub fn gap(mut self, gap: f32) -> Self {
837        self.gap = gap.max(0.0);
838        self
839    }
840
841    pub fn body(&self) -> &WidgetPod {
842        self.body.child()
843    }
844
845    pub fn body_mut(&mut self) -> &mut WidgetPod {
846        self.body.child_mut()
847    }
848
849    pub fn trailing(&self) -> &WidgetPod {
850        self.trailing.child()
851    }
852
853    pub fn trailing_mut(&mut self) -> &mut WidgetPod {
854        self.trailing.child_mut()
855    }
856
857    fn layout_rects(&self, bounds: Rect) -> (Rect, Rect) {
858        let trailing_height = self
859            .trailing_height
860            .min(bounds.width())
861            .min(bounds.height())
862            .max(0.0);
863        let trailing_width = self.trailing_width.min(bounds.width()).max(0.0);
864        let gap = if trailing_width > 0.0 && bounds.width() > trailing_width {
865            self.gap.min(bounds.width() - trailing_width).max(0.0)
866        } else {
867            0.0
868        };
869        let body_width = (bounds.width() - trailing_width - gap).max(0.0);
870        let body = Rect::new(bounds.x(), bounds.y(), body_width, bounds.height());
871        let trailing = Rect::new(
872            bounds.x() + body_width + gap,
873            bounds.y() + ((bounds.height() - trailing_height) * 0.5).max(0.0),
874            trailing_width,
875            trailing_height,
876        );
877        (body, trailing)
878    }
879}
880
881impl Widget for TrailingSlotRow {
882    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
883        let width = if constraints.max.width.is_finite() {
884            constraints.max.width
885        } else {
886            constraints.min.width.max(self.trailing_width)
887        };
888        if !constraints.max.height.is_finite() {
889            let provisional_height = constraints.min.height.max(self.trailing_height);
890            let bounds = Rect::new(0.0, 0.0, width, provisional_height);
891            let (body, trailing) = self.layout_rects(bounds);
892            let body_size = self.body.measure(
893                ctx,
894                Constraints::new(
895                    Size::new(body.width(), 0.0),
896                    Size::new(body.width(), f32::INFINITY),
897                ),
898            );
899            self.trailing.measure(
900                ctx,
901                Constraints::tight(Size::new(trailing.width(), self.trailing_height)),
902            );
903            let height = body_size
904                .height
905                .max(self.trailing_height)
906                .max(constraints.min.height);
907            return constraints.clamp(Size::new(width, height));
908        }
909
910        let height = constraints.max.height.max(constraints.min.height);
911        let bounds = Rect::new(0.0, 0.0, width, height);
912        let (body, trailing) = self.layout_rects(bounds);
913        self.body.measure(
914            ctx,
915            Constraints::tight(Size::new(body.width(), body.height())),
916        );
917        self.trailing.measure(
918            ctx,
919            Constraints::tight(Size::new(trailing.width(), trailing.height())),
920        );
921        constraints.clamp(Size::new(width, height))
922    }
923
924    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
925        let (body, trailing) = self.layout_rects(bounds);
926        self.body.arrange(ctx, body);
927        self.trailing.arrange(ctx, trailing);
928    }
929
930    fn paint(&self, ctx: &mut PaintCtx) {
931        self.body.paint(ctx);
932        self.trailing.paint(ctx);
933    }
934
935    fn semantics(&self, ctx: &mut SemanticsCtx) {
936        self.body.semantics(ctx);
937        self.trailing.semantics(ctx);
938    }
939
940    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
941        self.body.visit_children(visitor);
942        self.trailing.visit_children(visitor);
943    }
944
945    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
946        self.body.visit_children_mut(visitor);
947        self.trailing.visit_children_mut(visitor);
948    }
949}
950
951/// Vertical dock layout with optional fixed-height top and bottom slots.
952///
953/// The body fills the remaining height. This is a layout primitive, not a themed panel: callers
954/// provide their own surfaces, separators, status bars, and scroll views.
955pub struct Dock {
956    top: Option<SingleChild>,
957    bottom: Option<SingleChild>,
958    body: SingleChild,
959    top_height: f32,
960    bottom_height: f32,
961    fallback_width: f32,
962    fallback_body_height: f32,
963}
964
965impl Dock {
966    pub fn new<W>(body: W) -> Self
967    where
968        W: Widget + 'static,
969    {
970        Self {
971            top: None,
972            bottom: None,
973            body: SingleChild::new(body),
974            top_height: 0.0,
975            bottom_height: 0.0,
976            fallback_width: 320.0,
977            fallback_body_height: 240.0,
978        }
979    }
980
981    pub fn top<W>(mut self, height: f32, widget: W) -> Self
982    where
983        W: Widget + 'static,
984    {
985        self.top = Some(SingleChild::new(widget));
986        self.top_height = height.max(0.0);
987        self
988    }
989
990    pub fn bottom<W>(mut self, height: f32, widget: W) -> Self
991    where
992        W: Widget + 'static,
993    {
994        self.bottom = Some(SingleChild::new(widget));
995        self.bottom_height = height.max(0.0);
996        self
997    }
998
999    pub fn fallback_width(mut self, width: f32) -> Self {
1000        self.fallback_width = width.max(0.0);
1001        self
1002    }
1003
1004    pub fn fallback_body_height(mut self, height: f32) -> Self {
1005        self.fallback_body_height = height.max(0.0);
1006        self
1007    }
1008
1009    pub fn top_child(&self) -> Option<&WidgetPod> {
1010        self.top.as_ref().map(SingleChild::child)
1011    }
1012
1013    pub fn top_child_mut(&mut self) -> Option<&mut WidgetPod> {
1014        self.top.as_mut().map(SingleChild::child_mut)
1015    }
1016
1017    pub fn body(&self) -> &WidgetPod {
1018        self.body.child()
1019    }
1020
1021    pub fn body_mut(&mut self) -> &mut WidgetPod {
1022        self.body.child_mut()
1023    }
1024
1025    pub fn bottom_child(&self) -> Option<&WidgetPod> {
1026        self.bottom.as_ref().map(SingleChild::child)
1027    }
1028
1029    pub fn bottom_child_mut(&mut self) -> Option<&mut WidgetPod> {
1030        self.bottom.as_mut().map(SingleChild::child_mut)
1031    }
1032
1033    fn width_for_measure(&self, constraints: Constraints) -> f32 {
1034        if constraints.max.width.is_finite() {
1035            constraints.max.width
1036        } else {
1037            constraints.min.width.max(self.fallback_width)
1038        }
1039    }
1040}
1041
1042impl Widget for Dock {
1043    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
1044        let width = self.width_for_measure(constraints);
1045        let top_h = self.top_height.max(0.0);
1046        let bottom_h = self.bottom_height.max(0.0);
1047
1048        let top_size = if let Some(top) = &mut self.top {
1049            top.measure(ctx, Constraints::tight(Size::new(width, top_h)))
1050        } else {
1051            Size::ZERO
1052        };
1053        let bottom_size = if let Some(bottom) = &mut self.bottom {
1054            bottom.measure(ctx, Constraints::tight(Size::new(width, bottom_h)))
1055        } else {
1056            Size::ZERO
1057        };
1058
1059        let available_body_h = if constraints.max.height.is_finite() {
1060            (constraints.max.height - top_h - bottom_h).max(0.0)
1061        } else {
1062            self.fallback_body_height
1063        };
1064        let body_size = self.body.measure(
1065            ctx,
1066            Constraints::new(
1067                Size::new(width, 0.0),
1068                Size::new(width, available_body_h.max(0.0)),
1069            ),
1070        );
1071
1072        let height = if constraints.max.height.is_finite() {
1073            constraints.max.height
1074        } else {
1075            top_h + body_size.height + bottom_h
1076        };
1077        let width = width
1078            .max(top_size.width)
1079            .max(body_size.width)
1080            .max(bottom_size.width);
1081        constraints.clamp(Size::new(width, height))
1082    }
1083
1084    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
1085        let top_h = self.top_height.min(bounds.height()).max(0.0);
1086        let bottom_h = self
1087            .bottom_height
1088            .min((bounds.height() - top_h).max(0.0))
1089            .max(0.0);
1090        let body_h = (bounds.height() - top_h - bottom_h).max(0.0);
1091
1092        if let Some(top) = &mut self.top {
1093            top.arrange(
1094                ctx,
1095                Rect::new(bounds.x(), bounds.y(), bounds.width(), top_h),
1096            );
1097        }
1098        self.body.arrange(
1099            ctx,
1100            Rect::new(bounds.x(), bounds.y() + top_h, bounds.width(), body_h),
1101        );
1102        if let Some(bottom) = &mut self.bottom {
1103            bottom.arrange(
1104                ctx,
1105                Rect::new(
1106                    bounds.x(),
1107                    bounds.max_y() - bottom_h,
1108                    bounds.width(),
1109                    bottom_h,
1110                ),
1111            );
1112        }
1113    }
1114
1115    fn paint(&self, ctx: &mut PaintCtx) {
1116        self.body.paint(ctx);
1117        if let Some(top) = &self.top {
1118            top.paint(ctx);
1119        }
1120        if let Some(bottom) = &self.bottom {
1121            bottom.paint(ctx);
1122        }
1123    }
1124
1125    fn semantics(&self, ctx: &mut SemanticsCtx) {
1126        if let Some(top) = &self.top {
1127            top.semantics(ctx);
1128        }
1129        self.body.semantics(ctx);
1130        if let Some(bottom) = &self.bottom {
1131            bottom.semantics(ctx);
1132        }
1133    }
1134
1135    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
1136        if let Some(top) = &self.top {
1137            top.visit_children(visitor);
1138        }
1139        self.body.visit_children(visitor);
1140        if let Some(bottom) = &self.bottom {
1141            bottom.visit_children(visitor);
1142        }
1143    }
1144
1145    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
1146        if let Some(top) = &mut self.top {
1147            top.visit_children_mut(visitor);
1148        }
1149        self.body.visit_children_mut(visitor);
1150        if let Some(bottom) = &mut self.bottom {
1151            bottom.visit_children_mut(visitor);
1152        }
1153    }
1154}
1155
1156/// Vertical dock layout where the bottom child is measured to its natural height.
1157///
1158/// This is useful for composer/status panels that grow with content while the body takes whatever
1159/// height remains above them.
1160pub struct MeasuredBottomDock {
1161    body: SingleChild,
1162    bottom: SingleChild,
1163    fallback_size: Size,
1164}
1165
1166impl MeasuredBottomDock {
1167    pub fn new<B, T>(body: B, bottom: T) -> Self
1168    where
1169        B: Widget + 'static,
1170        T: Widget + 'static,
1171    {
1172        Self {
1173            body: SingleChild::new(body),
1174            bottom: SingleChild::new(bottom),
1175            fallback_size: Size::new(640.0, 640.0),
1176        }
1177    }
1178
1179    pub fn fallback_size(mut self, size: Size) -> Self {
1180        self.fallback_size = Size::new(size.width.max(0.0), size.height.max(0.0));
1181        self
1182    }
1183
1184    pub fn body(&self) -> &WidgetPod {
1185        self.body.child()
1186    }
1187
1188    pub fn body_mut(&mut self) -> &mut WidgetPod {
1189        self.body.child_mut()
1190    }
1191
1192    pub fn bottom(&self) -> &WidgetPod {
1193        self.bottom.child()
1194    }
1195
1196    pub fn bottom_mut(&mut self) -> &mut WidgetPod {
1197        self.bottom.child_mut()
1198    }
1199}
1200
1201impl Widget for MeasuredBottomDock {
1202    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
1203        let width = if constraints.max.width.is_finite() {
1204            constraints.max.width
1205        } else {
1206            constraints.min.width.max(self.fallback_size.width)
1207        };
1208        let height = if constraints.max.height.is_finite() {
1209            constraints.max.height
1210        } else {
1211            constraints.min.height.max(self.fallback_size.height)
1212        };
1213        let bottom_size = self.bottom.measure(
1214            ctx,
1215            Constraints::new(Size::new(width, 0.0), Size::new(width, height)),
1216        );
1217        let bottom_h = bottom_size.height.min(height).max(0.0);
1218        let body_h = (height - bottom_h).max(0.0);
1219        self.body
1220            .measure(ctx, Constraints::tight(Size::new(width, body_h)));
1221        constraints.clamp(Size::new(width, body_h + bottom_h))
1222    }
1223
1224    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
1225        let bottom_h = self
1226            .bottom
1227            .child()
1228            .measured_size()
1229            .height
1230            .min(bounds.height())
1231            .max(0.0);
1232        let body_h = (bounds.height() - bottom_h).max(0.0);
1233        self.body.arrange(
1234            ctx,
1235            Rect::new(bounds.x(), bounds.y(), bounds.width(), body_h),
1236        );
1237        self.bottom.arrange(
1238            ctx,
1239            Rect::new(
1240                bounds.x(),
1241                bounds.max_y() - bottom_h,
1242                bounds.width(),
1243                bottom_h,
1244            ),
1245        );
1246    }
1247
1248    fn paint(&self, ctx: &mut PaintCtx) {
1249        self.body.paint(ctx);
1250        self.bottom.paint(ctx);
1251    }
1252
1253    fn semantics(&self, ctx: &mut SemanticsCtx) {
1254        self.body.semantics(ctx);
1255        self.bottom.semantics(ctx);
1256    }
1257
1258    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
1259        self.body.visit_children(visitor);
1260        self.bottom.visit_children(visitor);
1261    }
1262
1263    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
1264        self.body.visit_children_mut(visitor);
1265        self.bottom.visit_children_mut(visitor);
1266    }
1267}
1268
1269#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1270enum FixedPane {
1271    First,
1272    Second,
1273}
1274
1275pub struct FixedPaneSplit {
1276    axis: Axis,
1277    fixed_pane: FixedPane,
1278    fixed_extent: f32,
1279    divider_extent: f32,
1280    fallback_flexible_extent: f32,
1281    first: SingleChild,
1282    divider: SingleChild,
1283    second: SingleChild,
1284}
1285
1286impl FixedPaneSplit {
1287    pub fn new<F, D, S>(axis: Axis, first: F, divider: D, second: S) -> Self
1288    where
1289        F: Widget + 'static,
1290        D: Widget + 'static,
1291        S: Widget + 'static,
1292    {
1293        Self {
1294            axis,
1295            fixed_pane: FixedPane::First,
1296            fixed_extent: 0.0,
1297            divider_extent: 1.0,
1298            fallback_flexible_extent: 320.0,
1299            first: SingleChild::new(first),
1300            divider: SingleChild::new(divider),
1301            second: SingleChild::new(second),
1302        }
1303    }
1304
1305    pub fn horizontal<F, D, S>(first: F, divider: D, second: S) -> Self
1306    where
1307        F: Widget + 'static,
1308        D: Widget + 'static,
1309        S: Widget + 'static,
1310    {
1311        Self::new(Axis::Horizontal, first, divider, second)
1312    }
1313
1314    pub fn vertical<F, D, S>(first: F, divider: D, second: S) -> Self
1315    where
1316        F: Widget + 'static,
1317        D: Widget + 'static,
1318        S: Widget + 'static,
1319    {
1320        Self::new(Axis::Vertical, first, divider, second)
1321    }
1322
1323    pub fn fixed_first(mut self, extent: f32) -> Self {
1324        self.fixed_pane = FixedPane::First;
1325        self.fixed_extent = extent.max(0.0);
1326        self
1327    }
1328
1329    pub fn fixed_second(mut self, extent: f32) -> Self {
1330        self.fixed_pane = FixedPane::Second;
1331        self.fixed_extent = extent.max(0.0);
1332        self
1333    }
1334
1335    pub fn divider_extent(mut self, extent: f32) -> Self {
1336        self.divider_extent = extent.max(0.0);
1337        self
1338    }
1339
1340    pub fn fallback_flexible_extent(mut self, extent: f32) -> Self {
1341        self.fallback_flexible_extent = extent.max(0.0);
1342        self
1343    }
1344
1345    pub fn first(&self) -> &WidgetPod {
1346        self.first.child()
1347    }
1348
1349    pub fn first_mut(&mut self) -> &mut WidgetPod {
1350        self.first.child_mut()
1351    }
1352
1353    pub fn divider(&self) -> &WidgetPod {
1354        self.divider.child()
1355    }
1356
1357    pub fn divider_mut(&mut self) -> &mut WidgetPod {
1358        self.divider.child_mut()
1359    }
1360
1361    pub fn second(&self) -> &WidgetPod {
1362        self.second.child()
1363    }
1364
1365    pub fn second_mut(&mut self) -> &mut WidgetPod {
1366        self.second.child_mut()
1367    }
1368
1369    fn split_extents(&self, total_main: f32) -> (f32, f32, f32) {
1370        let divider = self.divider_extent.min(total_main).max(0.0);
1371        let available = (total_main - divider).max(0.0);
1372        match self.fixed_pane {
1373            FixedPane::First => {
1374                let first = self.fixed_extent.min(available).max(0.0);
1375                (first, divider, (available - first).max(0.0))
1376            }
1377            FixedPane::Second => {
1378                let second = self.fixed_extent.min(available).max(0.0);
1379                ((available - second).max(0.0), divider, second)
1380            }
1381        }
1382    }
1383
1384    fn child_constraints(&self, main: f32, cross: Option<f32>) -> Constraints {
1385        Constraints::new(
1386            axis_size(self.axis, main, cross.unwrap_or(0.0)),
1387            axis_size(self.axis, main, cross.unwrap_or(f32::INFINITY)),
1388        )
1389    }
1390
1391    fn child_rect(&self, bounds: Rect, main_offset: f32, main: f32) -> Rect {
1392        Rect::from_origin_size(
1393            bounds.origin + axis_point(self.axis, main_offset, 0.0).to_vector(),
1394            axis_size(self.axis, main, axis_cross(self.axis, bounds.size)),
1395        )
1396    }
1397}
1398
1399impl Widget for FixedPaneSplit {
1400    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
1401        let total_main = if axis_main(self.axis, constraints.max).is_finite() {
1402            axis_main(self.axis, constraints.max)
1403        } else {
1404            self.fixed_extent + self.divider_extent + self.fallback_flexible_extent
1405        };
1406        let cross_max = axis_cross(self.axis, constraints.max);
1407        let tight_cross = cross_max.is_finite().then_some(cross_max);
1408        let (first_main, divider_main, second_main) = self.split_extents(total_main);
1409
1410        let first_size = self
1411            .first
1412            .measure(ctx, self.child_constraints(first_main, tight_cross));
1413        let divider_size = self
1414            .divider
1415            .measure(ctx, self.child_constraints(divider_main, tight_cross));
1416        let second_size = self
1417            .second
1418            .measure(ctx, self.child_constraints(second_main, tight_cross));
1419
1420        let cross = tight_cross.unwrap_or_else(|| {
1421            axis_cross(self.axis, first_size)
1422                .max(axis_cross(self.axis, divider_size))
1423                .max(axis_cross(self.axis, second_size))
1424                .max(axis_cross(self.axis, constraints.min))
1425        });
1426        constraints.clamp(axis_size(self.axis, total_main, cross))
1427    }
1428
1429    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
1430        let (first_main, divider_main, second_main) =
1431            self.split_extents(axis_main(self.axis, bounds.size));
1432        self.first
1433            .arrange(ctx, self.child_rect(bounds, 0.0, first_main));
1434        self.divider
1435            .arrange(ctx, self.child_rect(bounds, first_main, divider_main));
1436        self.second.arrange(
1437            ctx,
1438            self.child_rect(bounds, first_main + divider_main, second_main),
1439        );
1440    }
1441
1442    fn paint(&self, ctx: &mut PaintCtx) {
1443        self.first.paint(ctx);
1444        self.divider.paint(ctx);
1445        self.second.paint(ctx);
1446    }
1447
1448    fn semantics(&self, ctx: &mut SemanticsCtx) {
1449        self.first.semantics(ctx);
1450        self.divider.semantics(ctx);
1451        self.second.semantics(ctx);
1452    }
1453
1454    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
1455        self.first.visit_children(visitor);
1456        self.divider.visit_children(visitor);
1457        self.second.visit_children(visitor);
1458    }
1459
1460    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
1461        self.first.visit_children_mut(visitor);
1462        self.divider.visit_children_mut(visitor);
1463        self.second.visit_children_mut(visitor);
1464    }
1465}
1466
1467pub struct Flex {
1468    style: FlexStyle,
1469    items: Vec<FlexItem>,
1470    children: WidgetChildren,
1471}
1472
1473impl Flex {
1474    pub fn new(axis: Axis) -> Self {
1475        Self {
1476            style: FlexStyle::new(axis),
1477            items: Vec::new(),
1478            children: WidgetChildren::new(),
1479        }
1480    }
1481
1482    pub fn horizontal() -> Self {
1483        Self::new(Axis::Horizontal)
1484    }
1485
1486    pub fn vertical() -> Self {
1487        Self::new(Axis::Vertical)
1488    }
1489
1490    pub fn with_style(mut self, style: FlexStyle) -> Self {
1491        self.style = style;
1492        self
1493    }
1494
1495    pub fn wrap(mut self, wrap: FlexWrap) -> Self {
1496        self.style = self.style.wrap(wrap);
1497        self
1498    }
1499
1500    pub fn gap(mut self, gap: f32) -> Self {
1501        self.style = self.style.gap(gap);
1502        self
1503    }
1504
1505    pub fn main_gap(mut self, gap: f32) -> Self {
1506        self.style = self.style.main_gap(gap);
1507        self
1508    }
1509
1510    pub fn cross_gap(mut self, gap: f32) -> Self {
1511        self.style = self.style.cross_gap(gap);
1512        self
1513    }
1514
1515    pub fn justify(mut self, justify: FlexJustify) -> Self {
1516        self.style = self.style.justify(justify);
1517        self
1518    }
1519
1520    pub fn align_items(mut self, alignment: Alignment) -> Self {
1521        self.style = self.style.align_items(alignment);
1522        self
1523    }
1524
1525    pub fn align_content(mut self, alignment: FlexAlignContent) -> Self {
1526        self.style = self.style.align_content(alignment);
1527        self
1528    }
1529
1530    pub fn with_child<W>(mut self, child: W) -> Self
1531    where
1532        W: Widget + 'static,
1533    {
1534        self.children.push(child);
1535        self.items.push(FlexItem::new());
1536        self
1537    }
1538
1539    pub fn with_item<W>(mut self, child: W, item: FlexItem) -> Self
1540    where
1541        W: Widget + 'static,
1542    {
1543        self.children.push(child);
1544        self.items.push(item);
1545        self
1546    }
1547
1548    pub fn spacer(mut self) -> Self {
1549        self.push_spacer();
1550        self
1551    }
1552
1553    pub fn push<W>(&mut self, child: W)
1554    where
1555        W: Widget + 'static,
1556    {
1557        self.children.push(child);
1558        self.items.push(FlexItem::new());
1559    }
1560
1561    pub fn push_item<W>(&mut self, child: W, item: FlexItem)
1562    where
1563        W: Widget + 'static,
1564    {
1565        self.children.push(child);
1566        self.items.push(item);
1567    }
1568
1569    pub fn push_spacer(&mut self) {
1570        self.children.push(SizedBox::new());
1571        self.items.push(FlexItem::fill());
1572    }
1573
1574    pub const fn style(&self) -> FlexStyle {
1575        self.style
1576    }
1577
1578    /// Each child's [`FlexItem`] layout settings, in child order.
1579    pub fn flex_items(&self) -> &[FlexItem] {
1580        &self.items
1581    }
1582
1583    pub fn flex_items_mut(&mut self) -> &mut [FlexItem] {
1584        &mut self.items
1585    }
1586
1587    /// The [`FlexItem`] layout settings of child `index`.
1588    pub fn flex_item(&self, index: usize) -> Option<FlexItem> {
1589        self.items.get(index).copied()
1590    }
1591
1592    /// Replace the [`FlexItem`] layout settings of child `index`, returning
1593    /// whether that child exists.
1594    pub fn set_flex_item(&mut self, index: usize, item: FlexItem) -> bool {
1595        let Some(slot) = self.items.get_mut(index) else {
1596            return false;
1597        };
1598        *slot = item;
1599        true
1600    }
1601
1602    pub fn children(&self) -> &[WidgetPod] {
1603        self.children.as_slice()
1604    }
1605
1606    pub fn children_mut(&mut self) -> &mut [WidgetPod] {
1607        self.children.as_mut_slice()
1608    }
1609}
1610
1611impl Flex {
1612    fn measure_flex(
1613        &mut self,
1614        ctx: &mut MeasureCtx,
1615        constraints: Constraints,
1616        commit: bool,
1617    ) -> Size {
1618        let axis = self.style.axis;
1619        flex_layout_with_probes(self.style, &self.items, constraints, |index, c, phase| {
1620            let child = &mut self.children.as_mut_slice()[index];
1621            match phase {
1622                FlexMeasurePhase::Probe => {
1623                    let main = child.probe_measure_axis(ctx, c, axis);
1624                    match axis {
1625                        Axis::Horizontal => Size::new(main, 0.0),
1626                        Axis::Vertical => Size::new(0.0, main),
1627                    }
1628                }
1629                FlexMeasurePhase::Commit if commit => child.measure(ctx, c),
1630                FlexMeasurePhase::Commit => child.probe_measure(ctx, c),
1631            }
1632        })
1633        .size
1634    }
1635}
1636
1637impl Widget for Flex {
1638    fn supports_output_reuse(&self) -> bool {
1639        true
1640    }
1641    fn measure_axis(&mut self, ctx: &mut MeasureCtx, constraints: Constraints, axis: Axis) -> f32 {
1642        let extent = |size: Size| match axis {
1643            Axis::Horizontal => size.width,
1644            Axis::Vertical => size.height,
1645        };
1646        if extent(constraints.min) == extent(constraints.max) {
1647            return extent(constraints.min);
1648        }
1649        if axis != self.style.axis {
1650            return extent(self.measure_size(ctx, constraints));
1651        }
1652        // Main-axis line allocation is independent of cross-axis extents. Keep
1653        // the shared flex algorithm, projecting only the child sizes it needs.
1654        extent(
1655            flex_layout(self.style, &self.items, constraints, |index, c| {
1656                let main = self.children.as_mut_slice()[index].probe_measure_axis(ctx, c, axis);
1657                match axis {
1658                    Axis::Horizontal => Size::new(main, 0.0),
1659                    Axis::Vertical => Size::new(0.0, main),
1660                }
1661            })
1662            .size,
1663        )
1664    }
1665
1666    fn measure_size(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
1667        self.measure_flex(ctx, constraints, false)
1668    }
1669
1670    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
1671        self.measure_flex(ctx, constraints, true)
1672    }
1673
1674    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
1675        let measured_sizes = self
1676            .children
1677            .as_slice()
1678            .iter()
1679            .map(WidgetPod::measured_size)
1680            .collect::<Vec<_>>();
1681        let layout = arrange_flex(self.style, &self.items, bounds.size, &measured_sizes);
1682
1683        for (index, item_layout) in layout.items.iter().enumerate() {
1684            self.children.arrange_child(
1685                index,
1686                ctx,
1687                item_layout.rect.translate(bounds.origin.to_vector()),
1688            );
1689        }
1690    }
1691
1692    fn paint(&self, ctx: &mut PaintCtx) {
1693        self.children.paint(ctx);
1694    }
1695
1696    fn semantics(&self, ctx: &mut SemanticsCtx) {
1697        self.children.semantics(ctx);
1698    }
1699
1700    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
1701        self.children.visit_children(visitor);
1702    }
1703
1704    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
1705        self.children.visit_children_mut(visitor);
1706    }
1707}
1708
1709pub struct SwitchView {
1710    selected: usize,
1711    selected_reader: Option<Box<dyn Fn() -> usize>>,
1712    selected_source: Option<Arc<dyn Observable<usize>>>,
1713    children: WidgetChildren,
1714}
1715
1716impl SwitchView {
1717    pub fn new() -> Self {
1718        Self {
1719            selected: 0,
1720            selected_reader: None,
1721            selected_source: None,
1722            children: WidgetChildren::new(),
1723        }
1724    }
1725
1726    pub fn selected(mut self, selected: usize) -> Self {
1727        self.selected = selected;
1728        self.selected_reader = None;
1729        self.selected_source = None;
1730        self
1731    }
1732
1733    pub fn selected_when<F>(mut self, selected: F) -> Self
1734    where
1735        F: Fn() -> usize + 'static,
1736    {
1737        self.selected_reader = Some(Box::new(selected));
1738        self.selected_source = None;
1739        self
1740    }
1741
1742    /// Bind the active child index to an observable value while retaining all
1743    /// child widget pods and their local state.
1744    pub fn selected_from<O>(mut self, selected: O) -> Self
1745    where
1746        O: Observable<usize> + 'static,
1747    {
1748        self.selected = selected.get();
1749        self.selected_reader = None;
1750        self.selected_source = Some(Arc::new(selected));
1751        self
1752    }
1753
1754    pub fn with_child<W>(mut self, child: W) -> Self
1755    where
1756        W: Widget + 'static,
1757    {
1758        self.children.push(child);
1759        self
1760    }
1761
1762    pub fn push<W>(&mut self, child: W)
1763    where
1764        W: Widget + 'static,
1765    {
1766        self.children.push(child);
1767    }
1768
1769    pub fn selected_index(&self) -> Option<usize> {
1770        self.active_index()
1771    }
1772
1773    pub fn children(&self) -> &[WidgetPod] {
1774        self.children.as_slice()
1775    }
1776
1777    pub fn children_mut(&mut self) -> &mut [WidgetPod] {
1778        self.children.as_mut_slice()
1779    }
1780
1781    fn active_index(&self) -> Option<usize> {
1782        let selected = self
1783            .selected_source
1784            .as_ref()
1785            .map(|source| source.get())
1786            .or_else(|| self.selected_reader.as_ref().map(|reader| reader()))
1787            .unwrap_or(self.selected);
1788        (selected < self.children.as_slice().len()).then_some(selected)
1789    }
1790}
1791
1792impl Default for SwitchView {
1793    fn default() -> Self {
1794        Self::new()
1795    }
1796}
1797
1798impl Widget for SwitchView {
1799    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
1800        if let Some(source) = &self.selected_source {
1801            self.selected = ctx.observe(source.as_ref());
1802        }
1803        let Some(index) = self.active_index() else {
1804            return constraints.clamp(Size::ZERO);
1805        };
1806
1807        self.children.as_mut_slice()[index].measure(ctx, constraints)
1808    }
1809
1810    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
1811        if let Some(index) = self.active_index() {
1812            self.children.as_mut_slice()[index].arrange(ctx, bounds);
1813        }
1814    }
1815
1816    fn paint(&self, ctx: &mut PaintCtx) {
1817        if let Some(index) = self.active_index() {
1818            self.children.as_slice()[index].paint(ctx);
1819        }
1820    }
1821
1822    fn semantics(&self, ctx: &mut SemanticsCtx) {
1823        if let Some(index) = self.active_index() {
1824            self.children.as_slice()[index].semantics(ctx);
1825        }
1826    }
1827
1828    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
1829        if let Some(index) = self.active_index() {
1830            visitor.visit(&self.children.as_slice()[index]);
1831        }
1832    }
1833
1834    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
1835        if let Some(index) = self.active_index() {
1836            visitor.visit(&mut self.children.as_mut_slice()[index]);
1837        }
1838    }
1839}
1840
1841/// Hosts a child subtree that is rebuilt whenever a caller-supplied key changes.
1842///
1843/// This is useful for composed widgets whose child list is fixed at construction time, such as
1844/// segmented views, breadcrumbs, and virtualized tables. The container checks the key during
1845/// measure, on pointer release, and on redraw. When the key changes it replaces the child pod and
1846/// requests a fresh layout/paint pass.
1847pub struct RebuildOnChange<K: PartialEq + Clone> {
1848    key_fn: Option<Box<dyn Fn() -> K>>,
1849    key_source: Option<Arc<dyn Observable<K>>>,
1850    build: Box<dyn Fn(&K) -> WidgetPod>,
1851    last_key: K,
1852    child: WidgetPod,
1853}
1854
1855impl<K: PartialEq + Clone> RebuildOnChange<K> {
1856    /// Rebuild from the key `key_fn` returns, read during measure, on
1857    /// pointer release, and on redraw.
1858    pub fn key_when<KF, BF>(key_fn: KF, build: BF) -> Self
1859    where
1860        KF: Fn() -> K + 'static,
1861        BF: Fn(&K) -> WidgetPod + 'static,
1862    {
1863        let last_key = key_fn();
1864        let child = build(&last_key);
1865        Self {
1866            key_fn: Some(Box::new(key_fn)),
1867            key_source: None,
1868            build: Box::new(build),
1869            last_key,
1870            child,
1871        }
1872    }
1873
1874    /// Rebuild from an observable structural key.
1875    ///
1876    /// Unlike [`Self::key_when`], this form wakes the runtime and targets
1877    /// this host automatically when the key changes.
1878    pub fn key_from<O, BF>(key_source: O, build: BF) -> Self
1879    where
1880        O: Observable<K> + 'static,
1881        BF: Fn(&K) -> WidgetPod + 'static,
1882        K: 'static,
1883    {
1884        let last_key = key_source.get();
1885        let child = build(&last_key);
1886        Self {
1887            key_fn: None,
1888            key_source: Some(Arc::new(key_source)),
1889            build: Box::new(build),
1890            last_key,
1891            child,
1892        }
1893    }
1894
1895    fn current_key(&self) -> K {
1896        self.key_source
1897            .as_ref()
1898            .map(|source| source.get())
1899            .or_else(|| self.key_fn.as_ref().map(|key_fn| key_fn()))
1900            .expect("RebuildOnChange requires a key reader or observable")
1901    }
1902
1903    pub fn refresh(&mut self) -> bool {
1904        let key = self.current_key();
1905        if key != self.last_key {
1906            self.child = (self.build)(&key);
1907            self.last_key = key;
1908            true
1909        } else {
1910            false
1911        }
1912    }
1913
1914    pub fn child_pod(&self) -> &WidgetPod {
1915        &self.child
1916    }
1917
1918    pub fn child_mut(&mut self) -> &mut WidgetPod {
1919        &mut self.child
1920    }
1921}
1922
1923impl<K: PartialEq + Clone + 'static> Widget for RebuildOnChange<K> {
1924    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
1925        if let Some(source) = &self.key_source {
1926            let _ = ctx.observe(source.as_ref(), InvalidationKind::Measure);
1927        }
1928        let pointer_up = matches!(
1929            event,
1930            Event::Pointer(pointer) if matches!(pointer.kind, PointerEventKind::Up)
1931        );
1932        let redraw = matches!(event, Event::Window(WindowEvent::RedrawRequested));
1933        if (pointer_up || redraw) && self.refresh() {
1934            ctx.record_rebuild(
1935                std::any::type_name::<Self>(),
1936                "caller-supplied structural key changed",
1937            );
1938            ctx.request_measure();
1939            ctx.request_arrange();
1940            ctx.request_paint();
1941            ctx.request_semantics();
1942        }
1943    }
1944
1945    fn command(&mut self, ctx: &mut EventCtx, command: &Command<'_>) {
1946        if command.is(REACTIVE_CHANGED) && self.refresh() {
1947            ctx.record_rebuild(
1948                std::any::type_name::<Self>(),
1949                "observable structural key changed",
1950            );
1951            ctx.request_measure();
1952            ctx.request_arrange();
1953            ctx.request_paint();
1954            ctx.request_semantics();
1955            ctx.set_handled();
1956        }
1957    }
1958
1959    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
1960        if let Some(source) = &self.key_source {
1961            let _ = ctx.observe(source.as_ref());
1962        }
1963        if self.refresh() {
1964            ctx.record_rebuild(
1965                std::any::type_name::<Self>(),
1966                "caller-supplied structural key changed during measure",
1967            );
1968        }
1969        self.child.measure(ctx, constraints)
1970    }
1971
1972    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
1973        self.child.arrange(ctx, bounds);
1974    }
1975
1976    fn paint(&self, ctx: &mut PaintCtx) {
1977        self.child.paint(ctx);
1978    }
1979
1980    fn semantics(&self, ctx: &mut SemanticsCtx) {
1981        self.child.semantics(ctx);
1982    }
1983
1984    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
1985        visitor.visit(&self.child);
1986    }
1987
1988    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
1989        visitor.visit(&mut self.child);
1990    }
1991}
1992
1993/// Hosts a child subtree that is rebuilt whenever layout constraints resolve to a new key.
1994///
1995/// This is useful for breakpoint-driven layouts where the available width or height changes which
1996/// control set should be mounted. The container owns the child replacement and invalidation; the
1997/// caller only provides the key derivation and child builder.
1998pub struct RebuildOnConstraints<K: PartialEq + Clone> {
1999    key_fn: Box<dyn Fn(Constraints) -> K>,
2000    build: Box<dyn Fn(&K) -> WidgetPod>,
2001    last_key: K,
2002    child: WidgetPod,
2003}
2004
2005impl<K: PartialEq + Clone> RebuildOnConstraints<K> {
2006    pub fn new<KF, BF>(initial_key: K, key_fn: KF, build: BF) -> Self
2007    where
2008        KF: Fn(Constraints) -> K + 'static,
2009        BF: Fn(&K) -> WidgetPod + 'static,
2010    {
2011        let child = build(&initial_key);
2012        Self {
2013            key_fn: Box::new(key_fn),
2014            build: Box::new(build),
2015            last_key: initial_key,
2016            child,
2017        }
2018    }
2019
2020    pub fn refresh_for_constraints(&mut self, constraints: Constraints) -> bool {
2021        let key = (self.key_fn)(constraints);
2022        if key != self.last_key {
2023            self.child = (self.build)(&key);
2024            self.last_key = key;
2025            true
2026        } else {
2027            false
2028        }
2029    }
2030
2031    pub fn child_pod(&self) -> &WidgetPod {
2032        &self.child
2033    }
2034
2035    pub fn child_mut(&mut self) -> &mut WidgetPod {
2036        &mut self.child
2037    }
2038}
2039
2040impl<K: PartialEq + Clone + 'static> Widget for RebuildOnConstraints<K> {
2041    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
2042        let pointer_up = matches!(
2043            event,
2044            Event::Pointer(pointer) if matches!(pointer.kind, PointerEventKind::Up)
2045        );
2046        let redraw = matches!(event, Event::Window(WindowEvent::RedrawRequested));
2047        let bounds = ctx.bounds();
2048        if (pointer_up || redraw)
2049            && self.refresh_for_constraints(Constraints::tight(Size::new(
2050                bounds.width(),
2051                bounds.height(),
2052            )))
2053        {
2054            ctx.record_rebuild(
2055                std::any::type_name::<Self>(),
2056                "constraint-derived structural key changed",
2057            );
2058            ctx.request_measure();
2059            ctx.request_arrange();
2060            ctx.request_paint();
2061            ctx.request_semantics();
2062        }
2063    }
2064
2065    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
2066        if self.refresh_for_constraints(constraints) {
2067            ctx.record_rebuild(
2068                std::any::type_name::<Self>(),
2069                "constraint-derived structural key changed during measure",
2070            );
2071        }
2072        self.child.measure(ctx, constraints)
2073    }
2074
2075    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
2076        self.child.arrange(ctx, bounds);
2077    }
2078
2079    fn paint(&self, ctx: &mut PaintCtx) {
2080        self.child.paint(ctx);
2081    }
2082
2083    fn semantics(&self, ctx: &mut SemanticsCtx) {
2084        self.child.semantics(ctx);
2085    }
2086
2087    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
2088        visitor.visit(&self.child);
2089    }
2090
2091    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
2092        visitor.visit(&mut self.child);
2093    }
2094}
2095
2096#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2097pub enum ScrollAxes {
2098    None,
2099    Vertical,
2100    Horizontal,
2101    Both,
2102}
2103
2104impl ScrollAxes {
2105    const fn allows_horizontal(self) -> bool {
2106        matches!(self, Self::Horizontal | Self::Both)
2107    }
2108
2109    const fn allows_vertical(self) -> bool {
2110        matches!(self, Self::Vertical | Self::Both)
2111    }
2112}
2113
2114/// How far a touch moves before it scrolls rather than presses.
2115pub(crate) const TOUCH_SCROLL_DRAG_THRESHOLD: f32 = 4.0;
2116
2117/// How close to a scroll view's edge a drag starts scrolling it.
2118const DRAG_AUTO_SCROLL_EDGE: f32 = 40.0;
2119/// How fast a drag at the very edge scrolls, in pixels a second.
2120const DRAG_AUTO_SCROLL_SPEED: f32 = 1_200.0;
2121
2122/// Scrolling a scroll view while a drag hovers near its edges.
2123#[derive(Debug, Clone, Copy)]
2124struct DragAutoScroll {
2125    enabled: bool,
2126    /// Pixels a second; zero when the drag is not near an edge.
2127    velocity: Vector,
2128}
2129
2130impl Default for DragAutoScroll {
2131    fn default() -> Self {
2132        Self {
2133            enabled: true,
2134            velocity: Vector::ZERO,
2135        }
2136    }
2137}
2138
2139impl DragAutoScroll {
2140    fn is_scrolling(&self) -> bool {
2141        self.velocity != Vector::ZERO
2142    }
2143
2144    fn stop(&mut self) {
2145        self.velocity = Vector::ZERO;
2146    }
2147
2148    /// Follow `drag` over a scroll view showing `viewport`, which scrolls
2149    /// along the axes marked in `axes` (horizontal, vertical).
2150    fn follow(&mut self, ctx: &mut EventCtx, drag: &DragEvent, viewport: Rect, axes: (bool, bool)) {
2151        if !self.enabled {
2152            return;
2153        }
2154        let was_scrolling = self.is_scrolling();
2155        match drag.kind {
2156            DragEventKind::Enter | DragEventKind::Over => {
2157                let speed = |scrolls: bool, position: f32, start: f32, end: f32| {
2158                    if scrolls {
2159                        drag_edge_speed(position, start, end)
2160                    } else {
2161                        0.0
2162                    }
2163                };
2164                self.velocity = Vector::new(
2165                    speed(axes.0, drag.position.x, viewport.x(), viewport.max_x()),
2166                    speed(axes.1, drag.position.y, viewport.y(), viewport.max_y()),
2167                );
2168            }
2169            DragEventKind::Leave if drag.target == Some(ctx.widget_id()) => self.stop(),
2170            DragEventKind::Drop | DragEventKind::End => self.stop(),
2171            DragEventKind::Leave => {}
2172        }
2173        if self.is_scrolling() && !was_scrolling {
2174            ctx.request_animation_frame();
2175        }
2176    }
2177
2178    /// How far to scroll for a frame `delta` seconds after the last one.
2179    fn step(&self, delta: f64) -> Vector {
2180        // A long gap, like the first frame after a pause, would jump.
2181        let seconds = delta.clamp(0.0, 1.0 / 20.0) as f32;
2182        Vector::new(self.velocity.x * seconds, self.velocity.y * seconds)
2183    }
2184}
2185
2186/// Signed scrolling speed for a drag at `position` along an axis whose
2187/// visible span is `start..end`: faster the closer it is to either edge.
2188fn drag_edge_speed(position: f32, start: f32, end: f32) -> f32 {
2189    let zone = DRAG_AUTO_SCROLL_EDGE.min((end - start) / 4.0);
2190    if zone <= 0.0 {
2191        return 0.0;
2192    }
2193    let ramp = |distance: f32| {
2194        let closeness = 1.0 - (distance / zone).clamp(0.0, 1.0);
2195        closeness * closeness * DRAG_AUTO_SCROLL_SPEED
2196    };
2197    if position < start + zone {
2198        -ramp(position - start)
2199    } else if position > end - zone {
2200        ramp(end - position)
2201    } else {
2202        0.0
2203    }
2204}
2205
2206/// How far back before release a touch drag's speed is measured, in seconds.
2207const TOUCH_VELOCITY_WINDOW: f64 = 0.1;
2208/// A finger that rested this long before lifting releases without speed.
2209const TOUCH_VELOCITY_STALE: f64 = 0.05;
2210const TOUCH_VELOCITY_SAMPLES: usize = 8;
2211/// How quickly a fling slows, per second: velocity decays by `e^-friction`
2212/// each second, close to the 0.998-per-millisecond deceleration of iOS.
2213const TOUCH_FLING_FRICTION: f32 = 2.0;
2214/// Release speeds below this, in pixels a second, stop where they lift.
2215const TOUCH_FLING_MIN_SPEED: f32 = 60.0;
2216/// A fling ends once it slows below this, in pixels a second.
2217const TOUCH_FLING_STOP_SPEED: f32 = 12.0;
2218const TOUCH_FLING_MAX_SPEED: f32 = 8_000.0;
2219
2220/// Recent positions of a touch drag, for its speed when the finger lifts.
2221#[derive(Debug, Clone, Copy)]
2222struct TouchVelocity {
2223    samples: [(f64, Point); TOUCH_VELOCITY_SAMPLES],
2224    len: usize,
2225    next: usize,
2226}
2227
2228impl TouchVelocity {
2229    fn new(time: f64, position: Point) -> Self {
2230        let mut velocity = Self {
2231            samples: [(time, position); TOUCH_VELOCITY_SAMPLES],
2232            len: 0,
2233            next: 0,
2234        };
2235        velocity.push(time, position);
2236        velocity
2237    }
2238
2239    fn push(&mut self, time: f64, position: Point) {
2240        self.samples[self.next] = (time, position);
2241        self.next = (self.next + 1) % TOUCH_VELOCITY_SAMPLES;
2242        self.len = (self.len + 1).min(TOUCH_VELOCITY_SAMPLES);
2243    }
2244
2245    fn sample(&self, back: usize) -> (f64, Point) {
2246        self.samples[(self.next + TOUCH_VELOCITY_SAMPLES - back) % TOUCH_VELOCITY_SAMPLES]
2247    }
2248
2249    /// The finger's velocity in pixels a second as it lifts at `time`.
2250    fn release(&self, time: f64) -> Vector {
2251        if self.len < 2 {
2252            return Vector::ZERO;
2253        }
2254        let newest = self.sample(1);
2255        if time - newest.0 > TOUCH_VELOCITY_STALE {
2256            return Vector::ZERO;
2257        }
2258        let mut oldest = newest;
2259        for back in 2..=self.len {
2260            let sample = self.sample(back);
2261            if newest.0 - sample.0 > TOUCH_VELOCITY_WINDOW {
2262                break;
2263            }
2264            oldest = sample;
2265        }
2266        let span = newest.0 - oldest.0;
2267        if span <= f64::EPSILON {
2268            return Vector::ZERO;
2269        }
2270        let distance = newest.1 - oldest.1;
2271        let span = span as f32;
2272        Vector::new(distance.x / span, distance.y / span)
2273    }
2274}
2275
2276/// Scrolling that coasts on after a touch drag lets go, slowing to a stop.
2277#[derive(Debug, Clone, Copy, Default)]
2278struct TouchFling {
2279    /// Scroll offset change in pixels a second; zero when not coasting.
2280    velocity: Vector,
2281}
2282
2283impl TouchFling {
2284    fn is_active(&self) -> bool {
2285        self.velocity != Vector::ZERO
2286    }
2287
2288    /// Stop coasting, reporting whether it was.
2289    fn stop(&mut self) -> bool {
2290        let was_active = self.is_active();
2291        self.velocity = Vector::ZERO;
2292        was_active
2293    }
2294
2295    /// Coast at `velocity`, in scroll offset pixels a second, when it is
2296    /// fast enough to be a fling.
2297    fn start(&mut self, ctx: &mut EventCtx, velocity: Vector) {
2298        let speed = velocity.x.hypot(velocity.y);
2299        if !speed.is_finite() || speed < TOUCH_FLING_MIN_SPEED {
2300            self.stop();
2301            return;
2302        }
2303        let scale = (TOUCH_FLING_MAX_SPEED / speed).min(1.0);
2304        self.velocity = Vector::new(velocity.x * scale, velocity.y * scale);
2305        ctx.request_animation_frame();
2306    }
2307
2308    /// How far to scroll for a frame `delta` seconds after the last one,
2309    /// slowing the fling by as much.
2310    fn step(&mut self, delta: f64) -> Vector {
2311        // A long gap, like the first frame after a pause, would jump.
2312        let seconds = delta.clamp(0.0, 1.0 / 20.0) as f32;
2313        let decay = (-TOUCH_FLING_FRICTION * seconds).exp();
2314        // The distance covered while the velocity decays over the frame.
2315        let travel = (1.0 - decay) / TOUCH_FLING_FRICTION;
2316        let step = Vector::new(self.velocity.x * travel, self.velocity.y * travel);
2317        self.velocity = Vector::new(self.velocity.x * decay, self.velocity.y * decay);
2318        if self.velocity.x.hypot(self.velocity.y) < TOUCH_FLING_STOP_SPEED {
2319            self.stop();
2320        }
2321        step
2322    }
2323
2324    /// Drop the motion along any axis where `step` moved nothing, as at a
2325    /// scroll limit.
2326    fn block(&mut self, step: Vector, moved: Vector) {
2327        if step.x != 0.0 && moved.x.abs() <= f32::EPSILON {
2328            self.velocity.x = 0.0;
2329        }
2330        if step.y != 0.0 && moved.y.abs() <= f32::EPSILON {
2331            self.velocity.y = 0.0;
2332        }
2333    }
2334}
2335
2336type OffsetChangeCallback = Rc<dyn Fn(Vector)>;
2337type OffsetChangeCallbackWithCtx = Rc<dyn Fn(&mut EventCtx, Vector)>;
2338
2339/// A scroll view's `on_offset_change` callbacks and the offset they last saw.
2340#[derive(Default)]
2341struct OffsetChange {
2342    callback: Option<OffsetChangeCallback>,
2343    callback_with_ctx: Option<OffsetChangeCallbackWithCtx>,
2344    notified: Vector,
2345}
2346
2347impl OffsetChange {
2348    fn is_watched(&self) -> bool {
2349        self.callback.is_some() || self.callback_with_ctx.is_some()
2350    }
2351
2352    /// Tell the callbacks about `offset` if it differs from what they saw.
2353    fn notify(&mut self, ctx: &mut EventCtx, offset: Vector) {
2354        if offset == self.notified {
2355            return;
2356        }
2357        self.notified = offset;
2358        if let Some(callback) = self.callback.clone() {
2359            callback(offset);
2360        }
2361        if let Some(callback) = self.callback_with_ctx.clone() {
2362            callback(ctx, offset);
2363        }
2364    }
2365
2366    /// Layout moved the view to `offset`, as for a scroll bar drag or a
2367    /// jump to an item. Layout has no event context to pass, so the
2368    /// callbacks hear about it on the next animation frame.
2369    fn defer<C>(&self, ctx: &mut C, offset: Vector)
2370    where
2371        C: ScrollInvalidationCtx,
2372    {
2373        if offset != self.notified && self.is_watched() {
2374            ctx.request_animation_frame();
2375        }
2376    }
2377}
2378
2379#[derive(Debug, Clone, Copy)]
2380struct TouchScrollGesture {
2381    pointer_id: u64,
2382    start_position: Point,
2383    dragging: bool,
2384    velocity: TouchVelocity,
2385}
2386
2387impl TouchScrollGesture {
2388    fn new(pointer: &PointerEvent, time: f64) -> Self {
2389        Self {
2390            pointer_id: pointer.pointer_id,
2391            start_position: pointer.position,
2392            dragging: false,
2393            velocity: TouchVelocity::new(time, pointer.position),
2394        }
2395    }
2396
2397    /// The scroll velocity to coast at when the finger lifts at `time`:
2398    /// opposite the finger's, along the axes the view scrolls.
2399    fn release_velocity(&self, time: f64, axes: ScrollAxes) -> Vector {
2400        let finger = self.velocity.release(time);
2401        Vector::new(
2402            if axes.allows_horizontal() {
2403                -finger.x
2404            } else {
2405                0.0
2406            },
2407            if axes.allows_vertical() {
2408                -finger.y
2409            } else {
2410                0.0
2411            },
2412        )
2413    }
2414
2415    fn matches(self, pointer: &PointerEvent) -> bool {
2416        self.pointer_id == pointer.pointer_id
2417    }
2418
2419    fn passed_threshold(self, pointer: &PointerEvent, axes: ScrollAxes) -> bool {
2420        let distance = pointer.position - self.start_position;
2421        let distance_squared = match axes {
2422            ScrollAxes::None => 0.0,
2423            ScrollAxes::Vertical => distance.y * distance.y,
2424            ScrollAxes::Horizontal => distance.x * distance.x,
2425            ScrollAxes::Both => distance.x * distance.x + distance.y * distance.y,
2426        };
2427        distance_squared >= TOUCH_SCROLL_DRAG_THRESHOLD * TOUCH_SCROLL_DRAG_THRESHOLD
2428    }
2429}
2430
2431/// Controls the child's measured extent along a scrollable axis.
2432#[derive(Debug, Clone, Copy, Default, PartialEq)]
2433pub enum ContentExtent {
2434    /// Let the child choose its preferred unbounded extent.
2435    #[default]
2436    Natural,
2437    /// Give the child a finite maximum equal to the viewport.
2438    Viewport,
2439    /// Keep the child at least as large as the viewport while allowing growth.
2440    AtLeastViewport,
2441    /// Keep the child at least as large as an explicit logical-pixel extent.
2442    AtLeast(f32),
2443    /// Measure the child at its reported minimum readable extent.
2444    MinContent,
2445}
2446
2447impl ContentExtent {
2448    fn resolve(self, viewport: f32, minimum_content: f32) -> (f32, f32) {
2449        let viewport = if viewport.is_finite() {
2450            viewport.max(0.0)
2451        } else {
2452            0.0
2453        };
2454        match self {
2455            Self::Natural => (0.0, f32::INFINITY),
2456            Self::Viewport => (0.0, viewport),
2457            Self::AtLeastViewport => (viewport, f32::INFINITY),
2458            Self::AtLeast(extent) => (
2459                if extent.is_finite() {
2460                    extent.max(0.0)
2461                } else {
2462                    0.0
2463                },
2464                f32::INFINITY,
2465            ),
2466            Self::MinContent => {
2467                let extent = if minimum_content.is_finite() {
2468                    minimum_content.max(0.0)
2469                } else {
2470                    0.0
2471                };
2472                (extent, extent)
2473            }
2474        }
2475    }
2476}
2477
2478#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2479pub enum Overflow {
2480    Visible,
2481    Clip,
2482    Scroll,
2483    Auto,
2484}
2485
2486impl Overflow {
2487    const fn is_scrollable(self) -> bool {
2488        matches!(self, Self::Scroll | Self::Auto)
2489    }
2490
2491    const fn clips_paint(self) -> bool {
2492        !matches!(self, Self::Visible)
2493    }
2494}
2495
2496#[derive(Debug, Clone)]
2497pub struct ScrollState {
2498    inner: Rc<RefCell<ScrollStateInner>>,
2499}
2500
2501#[derive(Debug, Clone)]
2502struct ScrollStateInner {
2503    axes: ScrollAxes,
2504    viewport: Size,
2505    content_size: Size,
2506    offset: Vector,
2507    pending_virtual_item: Option<usize>,
2508    /// Content-space top of each virtual-scroll item from the latest layout.
2509    virtual_item_offsets: Vec<f32>,
2510    scroll_view_id: Option<WidgetId>,
2511    scroll_content_id: Option<WidgetId>,
2512    scroll_bar_ids: Vec<WidgetId>,
2513}
2514
2515impl ScrollState {
2516    pub fn new() -> Self {
2517        Self::default()
2518    }
2519
2520    pub fn viewport_size(&self) -> Size {
2521        self.inner.borrow().viewport
2522    }
2523
2524    pub fn content_size(&self) -> Size {
2525        self.inner.borrow().content_size
2526    }
2527
2528    pub fn current_offset(&self) -> Vector {
2529        let inner = self.inner.borrow();
2530        clamp_shared_offset(inner.axes, inner.viewport, inner.content_size, inner.offset)
2531    }
2532
2533    pub fn max_offset(&self) -> Vector {
2534        let inner = self.inner.borrow();
2535        shared_max_offset(inner.viewport, inner.content_size)
2536    }
2537
2538    pub(crate) fn bind_scroll_view(&self, scroll_view_id: WidgetId, scroll_content_id: WidgetId) {
2539        let mut inner = self.inner.borrow_mut();
2540        inner.scroll_view_id = Some(scroll_view_id);
2541        inner.scroll_content_id = Some(scroll_content_id);
2542    }
2543
2544    fn bind_scroll_bar(&self, scroll_bar_id: WidgetId) {
2545        let mut inner = self.inner.borrow_mut();
2546        if !inner.scroll_bar_ids.contains(&scroll_bar_id) {
2547            inner.scroll_bar_ids.push(scroll_bar_id);
2548        }
2549    }
2550
2551    pub(crate) fn sync_metrics(
2552        &self,
2553        axes: ScrollAxes,
2554        viewport: Size,
2555        content_size: Size,
2556    ) -> bool {
2557        let mut inner = self.inner.borrow_mut();
2558        let next_offset = clamp_shared_offset(axes, viewport, content_size, inner.offset);
2559        let changed = inner.axes != axes
2560            || inner.viewport != viewport
2561            || inner.content_size != content_size
2562            || inner.offset != next_offset;
2563        inner.axes = axes;
2564        inner.viewport = viewport;
2565        inner.content_size = content_size;
2566        inner.offset = next_offset;
2567        changed
2568    }
2569
2570    pub(crate) fn sync_unmeasured_axes(&self, axes: ScrollAxes) {
2571        let mut inner = self.inner.borrow_mut();
2572        if inner.viewport == Size::ZERO && inner.content_size == Size::ZERO {
2573            inner.axes = axes;
2574            inner.offset = axis_limited_offset(axes, inner.offset);
2575        }
2576    }
2577
2578    /// Updates the shared scroll offset, clamped to the current viewport and
2579    /// content metrics. Returns whether the effective offset changed.
2580    ///
2581    /// Widgets bound to this state observe the new offset on their next layout
2582    /// pass; event handlers should request the corresponding invalidation.
2583    pub fn set_offset(&self, offset: Vector) -> bool {
2584        let mut inner = self.inner.borrow_mut();
2585        let next_offset = if inner.viewport == Size::ZERO && inner.content_size == Size::ZERO {
2586            axis_limited_offset(inner.axes, offset)
2587        } else {
2588            clamp_shared_offset(inner.axes, inner.viewport, inner.content_size, offset)
2589        };
2590        if inner.offset == next_offset {
2591            return false;
2592        }
2593        inner.offset = next_offset;
2594        true
2595    }
2596
2597    /// Queues a virtual-scroll item to align with the viewport start on the
2598    /// next layout pass. Returns whether the pending request changed.
2599    ///
2600    /// Resolving the request during layout keeps the target aligned with the
2601    /// item's latest measured position, including requests made before the
2602    /// first render.
2603    pub fn scroll_to_item(&self, index: usize) -> bool {
2604        let mut inner = self.inner.borrow_mut();
2605        if inner.pending_virtual_item == Some(index) {
2606            return false;
2607        }
2608        inner.pending_virtual_item = Some(index);
2609        true
2610    }
2611
2612    /// Queues a virtual-scroll item and invalidates the bound viewport so the
2613    /// jump is laid out and repainted in the frame requested by an event.
2614    pub fn scroll_to_item_with_ctx(&self, index: usize, ctx: &mut EventCtx) -> bool {
2615        if !self.scroll_to_item(index) {
2616            return false;
2617        }
2618
2619        let subscribers = self.subscribers();
2620        if let Some(scroll_view_id) = subscribers.scroll_view_id {
2621            for kind in [
2622                InvalidationKind::Measure,
2623                InvalidationKind::Paint,
2624                InvalidationKind::HitTest,
2625                InvalidationKind::Semantics,
2626            ] {
2627                ctx.request(InvalidationRequest::new(
2628                    InvalidationTarget::Widget(scroll_view_id),
2629                    kind,
2630                ));
2631            }
2632        }
2633        for scroll_bar_id in subscribers.scroll_bar_ids {
2634            request_scroll_bar_refresh(ctx, scroll_bar_id);
2635        }
2636        true
2637    }
2638
2639    /// Index of the virtual-scroll item whose extent contains the content
2640    /// offset `y`, measured from the top of the scrolled content. Offsets past
2641    /// the last item resolve to the last item; returns `None` before the bound
2642    /// [`VirtualScrollView`] has been laid out or when it has no items.
2643    ///
2644    /// Scroll-spy navigation compares this against the current offset, for
2645    /// example `virtual_item_at(current_offset().y + threshold)`.
2646    pub fn virtual_item_at(&self, y: f32) -> Option<usize> {
2647        let inner = self.inner.borrow();
2648        let offsets = &inner.virtual_item_offsets;
2649        if offsets.is_empty() {
2650            return None;
2651        }
2652        Some(
2653            offsets
2654                .partition_point(|top| *top <= y)
2655                .saturating_sub(1)
2656                .min(offsets.len() - 1),
2657        )
2658    }
2659
2660    /// Index of the virtual-scroll item at the top edge of the viewport.
2661    pub fn first_visible_item(&self) -> Option<usize> {
2662        self.virtual_item_at(self.current_offset().y)
2663    }
2664
2665    /// Content-space top of a virtual-scroll item from the latest layout.
2666    pub fn virtual_item_offset(&self, index: usize) -> Option<f32> {
2667        self.inner.borrow().virtual_item_offsets.get(index).copied()
2668    }
2669
2670    pub(crate) fn sync_virtual_item_offsets(&self, offsets: &[f32]) {
2671        let mut inner = self.inner.borrow_mut();
2672        if inner.virtual_item_offsets != offsets {
2673            inner.virtual_item_offsets.clear();
2674            inner.virtual_item_offsets.extend_from_slice(offsets);
2675        }
2676    }
2677
2678    pub(crate) fn take_pending_virtual_item(&self) -> Option<usize> {
2679        self.inner.borrow_mut().pending_virtual_item.take()
2680    }
2681
2682    fn pending_virtual_item(&self) -> Option<usize> {
2683        self.inner.borrow().pending_virtual_item
2684    }
2685
2686    pub(crate) fn subscribers(&self) -> ScrollStateSubscribers {
2687        let inner = self.inner.borrow();
2688        ScrollStateSubscribers {
2689            scroll_view_id: inner.scroll_view_id,
2690            scroll_content_id: inner.scroll_content_id,
2691            scroll_bar_ids: inner.scroll_bar_ids.clone(),
2692        }
2693    }
2694}
2695
2696impl Default for ScrollState {
2697    fn default() -> Self {
2698        Self {
2699            inner: Rc::new(RefCell::new(ScrollStateInner {
2700                axes: ScrollAxes::Vertical,
2701                viewport: Size::ZERO,
2702                content_size: Size::ZERO,
2703                offset: Vector::ZERO,
2704                pending_virtual_item: None,
2705                virtual_item_offsets: Vec::new(),
2706                scroll_view_id: None,
2707                scroll_content_id: None,
2708                scroll_bar_ids: Vec::new(),
2709            })),
2710        }
2711    }
2712}
2713
2714#[derive(Debug, Clone)]
2715pub(crate) struct ScrollStateSubscribers {
2716    pub(crate) scroll_view_id: Option<WidgetId>,
2717    pub(crate) scroll_content_id: Option<WidgetId>,
2718    pub(crate) scroll_bar_ids: Vec<WidgetId>,
2719}
2720
2721#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2722enum ScrollBarAxis {
2723    Vertical,
2724    Horizontal,
2725}
2726
2727#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2728enum ScrollBarAppearance {
2729    Gutter,
2730    Overlay,
2731}
2732
2733#[derive(Debug, Clone, Copy)]
2734struct ScrollBarMetrics {
2735    track: Rect,
2736    thumb: Rect,
2737    max_scroll: f32,
2738}
2739
2740/// Widget state progress the runtime animates (see [`Progress`]).
2741type AnimatedScalar = crate::Progress;
2742
2743fn set_animation_target(
2744    animation: &mut AnimatedScalar,
2745    target: f32,
2746    duration: f64,
2747    easing: crate::Easing,
2748    ctx: &mut EventCtx,
2749) -> bool {
2750    animation.animate(target, crate::AnimationSpec::tween(duration, easing), ctx)
2751}
2752
2753fn set_hover_animation_target(
2754    animation: &mut AnimatedScalar,
2755    target: f32,
2756    theme: &DefaultTheme,
2757    ctx: &mut EventCtx,
2758) -> bool {
2759    set_animation_target(
2760        animation,
2761        target,
2762        theme.motion.hover_duration(),
2763        theme.motion.hover_easing(),
2764        ctx,
2765    )
2766}
2767
2768fn set_press_animation_target(
2769    animation: &mut AnimatedScalar,
2770    target: f32,
2771    theme: &DefaultTheme,
2772    ctx: &mut EventCtx,
2773) -> bool {
2774    set_animation_target(
2775        animation,
2776        target,
2777        theme.motion.press_duration(),
2778        theme.motion.press_easing(),
2779        ctx,
2780    )
2781}
2782
2783fn set_focus_animation_target(
2784    animation: &mut AnimatedScalar,
2785    target: f32,
2786    theme: &DefaultTheme,
2787    ctx: &mut EventCtx,
2788) -> bool {
2789    set_animation_target(
2790        animation,
2791        target,
2792        theme.motion.focus_duration(),
2793        theme.motion.focus_easing(),
2794        ctx,
2795    )
2796}
2797
2798pub struct ScrollBar {
2799    theme: Box<DefaultTheme>,
2800    theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
2801    state: ScrollState,
2802    axis: ScrollBarAxis,
2803    name: Option<String>,
2804    width: Option<f32>,
2805    hovered: bool,
2806    dragging: bool,
2807    hover_animation: AnimatedScalar,
2808    drag_animation: AnimatedScalar,
2809    focus_animation: AnimatedScalar,
2810    pointer_id: Option<u64>,
2811    drag_thumb_offset: f32,
2812    appearance: ScrollBarAppearance,
2813    focusable: bool,
2814}
2815
2816impl ScrollBar {
2817    pub fn vertical(state: ScrollState) -> Self {
2818        Self {
2819            theme: Box::new(DefaultTheme::default()),
2820            theme_reader: None,
2821            state,
2822            axis: ScrollBarAxis::Vertical,
2823            name: None,
2824            width: None,
2825            hovered: false,
2826            dragging: false,
2827            hover_animation: AnimatedScalar::new(0.0),
2828            drag_animation: AnimatedScalar::new(0.0),
2829            focus_animation: AnimatedScalar::new(0.0),
2830            pointer_id: None,
2831            drag_thumb_offset: 0.0,
2832            appearance: ScrollBarAppearance::Gutter,
2833            focusable: true,
2834        }
2835    }
2836
2837    pub fn horizontal(state: ScrollState) -> Self {
2838        Self {
2839            axis: ScrollBarAxis::Horizontal,
2840            ..Self::vertical(state)
2841        }
2842    }
2843
2844    pub fn theme(mut self, theme: DefaultTheme) -> Self {
2845        self.theme = Box::new(theme);
2846        self.theme_reader = None;
2847        self
2848    }
2849
2850    pub fn theme_when<F>(mut self, theme: F) -> Self
2851    where
2852        F: Fn() -> DefaultTheme + 'static,
2853    {
2854        self.theme_reader = Some(Box::new(theme));
2855        self
2856    }
2857
2858    pub fn name(mut self, name: impl Into<String>) -> Self {
2859        self.name = Some(name.into());
2860        self
2861    }
2862
2863    pub fn width(mut self, width: f32) -> Self {
2864        self.width = Some(width.max(8.0));
2865        self
2866    }
2867
2868    fn overlay(mut self) -> Self {
2869        self.appearance = ScrollBarAppearance::Overlay;
2870        self.focusable = false;
2871        self
2872    }
2873
2874    fn resolved_width(&self) -> f32 {
2875        let theme = self.resolved_theme();
2876        self.width.unwrap_or(theme.metrics.scroll_bar_thickness)
2877    }
2878
2879    fn resolved_track_width(&self, clock: &impl FrameClock) -> f32 {
2880        let expanded = self.resolved_width();
2881        match self.appearance {
2882            ScrollBarAppearance::Gutter => expanded,
2883            ScrollBarAppearance::Overlay => {
2884                let collapsed = OVERLAY_SCROLL_BAR_IDLE_THICKNESS.min(expanded);
2885                collapsed + (expanded - collapsed) * self.hover_animation.get(clock).clamp(0.0, 1.0)
2886            }
2887        }
2888    }
2889
2890    fn resolved_min_thumb_length(&self) -> f32 {
2891        self.resolved_theme().metrics.scroll_bar_min_thumb_length
2892    }
2893
2894    fn resolved_theme(&self) -> DefaultTheme {
2895        self.theme_reader
2896            .as_ref()
2897            .map(|reader| reader())
2898            .unwrap_or_else(|| *self.theme)
2899    }
2900
2901    fn track_rect(&self, bounds: Rect, clock: &impl FrameClock) -> Rect {
2902        let width = self.resolved_track_width(clock);
2903        match self.axis {
2904            ScrollBarAxis::Vertical => {
2905                let x = match self.appearance {
2906                    ScrollBarAppearance::Gutter => {
2907                        bounds.x() + ((bounds.width() - width) * 0.5).max(0.0)
2908                    }
2909                    ScrollBarAppearance::Overlay => (bounds.max_x() - width).max(bounds.x()),
2910                };
2911                Rect::new(x, bounds.y(), width.min(bounds.width()), bounds.height())
2912            }
2913            ScrollBarAxis::Horizontal => {
2914                let y = match self.appearance {
2915                    ScrollBarAppearance::Gutter => {
2916                        bounds.y() + ((bounds.height() - width) * 0.5).max(0.0)
2917                    }
2918                    ScrollBarAppearance::Overlay => (bounds.max_y() - width).max(bounds.y()),
2919                };
2920                Rect::new(bounds.x(), y, bounds.width(), width.min(bounds.height()))
2921            }
2922        }
2923    }
2924
2925    fn metrics(&self, bounds: Rect, clock: &impl FrameClock) -> Option<ScrollBarMetrics> {
2926        let viewport = self.state.viewport_size();
2927        let content = self.state.content_size();
2928        let viewport_extent = self.axis_size(viewport);
2929        let content_extent = self.axis_size(content);
2930        let bounds_extent = self.axis_rect_length(bounds);
2931        if viewport_extent <= 0.0 || content_extent <= viewport_extent || bounds_extent <= 0.0 {
2932            return None;
2933        }
2934
2935        let track = self.track_rect(bounds, clock);
2936        let track_extent = self.axis_rect_length(track);
2937        let ratio = (viewport_extent / content_extent).clamp(0.08, 1.0);
2938        let thumb_extent = (track_extent * ratio)
2939            .max(self.resolved_min_thumb_length())
2940            .min(track_extent);
2941        let max_scroll = (content_extent - viewport_extent).max(0.0);
2942        let travel = (track_extent - thumb_extent).max(0.0);
2943        let offset = self
2944            .axis_offset(self.state.current_offset())
2945            .clamp(0.0, max_scroll.max(0.0));
2946        let thumb_start = self.axis_rect_start(track)
2947            + if travel <= f32::EPSILON || max_scroll <= f32::EPSILON {
2948                0.0
2949            } else {
2950                travel * (offset / max_scroll)
2951            };
2952        let thumb = match self.axis {
2953            ScrollBarAxis::Vertical => {
2954                Rect::new(track.x(), thumb_start, track.width(), thumb_extent)
2955            }
2956            ScrollBarAxis::Horizontal => {
2957                Rect::new(thumb_start, track.y(), thumb_extent, track.height())
2958            }
2959        };
2960
2961        Some(ScrollBarMetrics {
2962            track,
2963            thumb,
2964            max_scroll,
2965        })
2966    }
2967
2968    fn axis_size(&self, size: Size) -> f32 {
2969        match self.axis {
2970            ScrollBarAxis::Vertical => size.height,
2971            ScrollBarAxis::Horizontal => size.width,
2972        }
2973    }
2974
2975    fn axis_offset(&self, offset: Vector) -> f32 {
2976        match self.axis {
2977            ScrollBarAxis::Vertical => offset.y,
2978            ScrollBarAxis::Horizontal => offset.x,
2979        }
2980    }
2981
2982    fn axis_rect_start(&self, rect: Rect) -> f32 {
2983        match self.axis {
2984            ScrollBarAxis::Vertical => rect.y(),
2985            ScrollBarAxis::Horizontal => rect.x(),
2986        }
2987    }
2988
2989    fn axis_rect_length(&self, rect: Rect) -> f32 {
2990        match self.axis {
2991            ScrollBarAxis::Vertical => rect.height(),
2992            ScrollBarAxis::Horizontal => rect.width(),
2993        }
2994    }
2995
2996    fn axis_rect_max(&self, rect: Rect) -> f32 {
2997        match self.axis {
2998            ScrollBarAxis::Vertical => rect.max_y(),
2999            ScrollBarAxis::Horizontal => rect.max_x(),
3000        }
3001    }
3002
3003    fn pointer_position(&self, position: Point) -> f32 {
3004        match self.axis {
3005            ScrollBarAxis::Vertical => position.y,
3006            ScrollBarAxis::Horizontal => position.x,
3007        }
3008    }
3009
3010    fn set_hovered(&mut self, hovered: bool, ctx: &mut EventCtx) {
3011        if self.hovered != hovered {
3012            let theme = self.resolved_theme();
3013            self.hovered = hovered;
3014            set_hover_animation_target(
3015                &mut self.hover_animation,
3016                hovered as u8 as f32,
3017                &theme,
3018                ctx,
3019            );
3020            ctx.request_paint();
3021            ctx.request_semantics();
3022        }
3023    }
3024
3025    fn set_dragging(&mut self, dragging: bool, ctx: &mut EventCtx) {
3026        if self.dragging != dragging {
3027            let theme = self.resolved_theme();
3028            self.dragging = dragging;
3029            set_press_animation_target(
3030                &mut self.drag_animation,
3031                dragging as u8 as f32,
3032                &theme,
3033                ctx,
3034            );
3035            ctx.request_paint();
3036            ctx.request_semantics();
3037        }
3038    }
3039
3040    fn request_dependents<C>(&self, ctx: &mut C, source_widget_id: WidgetId)
3041    where
3042        C: ScrollInvalidationCtx,
3043    {
3044        let subscribers = self.state.subscribers();
3045        if let Some(scroll_view_id) = subscribers.scroll_view_id
3046            && scroll_view_id != source_widget_id
3047        {
3048            request_scroll_view_refresh(ctx, scroll_view_id, subscribers.scroll_content_id);
3049        }
3050        for scroll_bar_id in subscribers.scroll_bar_ids {
3051            if scroll_bar_id != source_widget_id {
3052                request_scroll_bar_refresh(ctx, scroll_bar_id);
3053            }
3054        }
3055    }
3056
3057    fn set_axis_offset<C>(
3058        &mut self,
3059        ctx: &mut C,
3060        source_widget_id: WidgetId,
3061        axis_offset: f32,
3062    ) -> bool
3063    where
3064        C: ScrollInvalidationCtx,
3065    {
3066        let current = self.state.current_offset();
3067        let next = match self.axis {
3068            ScrollBarAxis::Vertical => Vector::new(current.x, axis_offset),
3069            ScrollBarAxis::Horizontal => Vector::new(axis_offset, current.y),
3070        };
3071        if !self.state.set_offset(next) {
3072            return false;
3073        }
3074        self.request_dependents(ctx, source_widget_id);
3075        true
3076    }
3077
3078    fn set_from_pointer_position<C>(
3079        &mut self,
3080        ctx: &mut C,
3081        source_widget_id: WidgetId,
3082        metrics: ScrollBarMetrics,
3083        pointer_position: f32,
3084        drag_anchor: f32,
3085    ) -> bool
3086    where
3087        C: ScrollInvalidationCtx,
3088    {
3089        let thumb_extent = self.axis_rect_length(metrics.thumb);
3090        let travel = (self.axis_rect_length(metrics.track) - thumb_extent).max(0.0);
3091        let thumb_start = (pointer_position - drag_anchor).clamp(
3092            self.axis_rect_start(metrics.track),
3093            self.axis_rect_max(metrics.track) - thumb_extent,
3094        );
3095        let fraction = if travel <= f32::EPSILON {
3096            0.0
3097        } else {
3098            (thumb_start - self.axis_rect_start(metrics.track)) / travel
3099        };
3100        self.set_axis_offset(ctx, source_widget_id, metrics.max_scroll * fraction)
3101    }
3102
3103    fn page_step(&self) -> f32 {
3104        let viewport = self.state.viewport_size();
3105        (self.axis_size(viewport) * 0.85).max(40.0)
3106    }
3107}
3108
3109impl Widget for ScrollBar {
3110    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
3111        let metrics = self.metrics(ctx.bounds(), ctx);
3112
3113        match event {
3114            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Move => {
3115                self.set_hovered(
3116                    pointer_supports_hover(pointer.pointer_kind)
3117                        && ctx.bounds().contains(pointer.position),
3118                    ctx,
3119                );
3120                if self.dragging
3121                    && self.pointer_id == Some(pointer.pointer_id)
3122                    && let Some(metrics) = metrics
3123                    && self.set_from_pointer_position(
3124                        ctx,
3125                        ctx.widget_id(),
3126                        metrics,
3127                        self.pointer_position(pointer.position),
3128                        self.drag_thumb_offset,
3129                    )
3130                {
3131                    ctx.request_paint();
3132                    ctx.request_semantics();
3133                    ctx.set_handled();
3134                }
3135            }
3136            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Enter => {
3137                self.set_hovered(pointer_supports_hover(pointer.pointer_kind), ctx);
3138            }
3139            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Leave => {
3140                if !self.dragging || self.pointer_id != Some(pointer.pointer_id) {
3141                    self.set_hovered(false, ctx);
3142                }
3143            }
3144            Event::Pointer(pointer)
3145                if pointer.kind == PointerEventKind::Down
3146                    && pointer.button == Some(PointerButton::Primary)
3147                    && ctx.bounds().contains(pointer.position) =>
3148            {
3149                let Some(metrics) = metrics else {
3150                    return;
3151                };
3152
3153                self.set_hovered(pointer_supports_hover(pointer.pointer_kind), ctx);
3154                self.set_dragging(true, ctx);
3155                self.pointer_id = Some(pointer.pointer_id);
3156                self.drag_thumb_offset = if metrics.thumb.contains(pointer.position) {
3157                    self.pointer_position(pointer.position) - self.axis_rect_start(metrics.thumb)
3158                } else {
3159                    self.axis_rect_length(metrics.thumb) * 0.5
3160                };
3161                let _ = self.set_from_pointer_position(
3162                    ctx,
3163                    ctx.widget_id(),
3164                    metrics,
3165                    self.pointer_position(pointer.position),
3166                    self.drag_thumb_offset,
3167                );
3168                ctx.request_pointer_capture(pointer.pointer_id);
3169                if self.focusable {
3170                    ctx.request_focus();
3171                }
3172                ctx.request_paint();
3173                ctx.request_semantics();
3174                ctx.set_handled();
3175            }
3176            Event::Pointer(pointer)
3177                if pointer.kind == PointerEventKind::Up
3178                    && pointer.button == Some(PointerButton::Primary)
3179                    && self.pointer_id == Some(pointer.pointer_id) =>
3180            {
3181                if self.dragging
3182                    && let Some(metrics) = metrics
3183                {
3184                    let _ = self.set_from_pointer_position(
3185                        ctx,
3186                        ctx.widget_id(),
3187                        metrics,
3188                        self.pointer_position(pointer.position),
3189                        self.drag_thumb_offset,
3190                    );
3191                }
3192                self.set_dragging(false, ctx);
3193                self.pointer_id = None;
3194                self.set_hovered(
3195                    pointer_supports_hover(pointer.pointer_kind)
3196                        && ctx.bounds().contains(pointer.position),
3197                    ctx,
3198                );
3199                ctx.release_pointer_capture(pointer.pointer_id);
3200                ctx.set_handled();
3201            }
3202            Event::Pointer(pointer)
3203                if pointer.kind == PointerEventKind::Cancel
3204                    && self.pointer_id == Some(pointer.pointer_id) =>
3205            {
3206                self.set_dragging(false, ctx);
3207                self.pointer_id = None;
3208                self.set_hovered(false, ctx);
3209                ctx.release_pointer_capture(pointer.pointer_id);
3210                ctx.set_handled();
3211            }
3212            Event::Semantics(semantics) if semantics.target == ctx.widget_id() => {
3213                let current = f64::from(self.axis_offset(self.state.current_offset()));
3214                let next = match &semantics.action {
3215                    SemanticsActionRequest::Increment => Some(current + 40.0),
3216                    SemanticsActionRequest::Decrement => Some(current - 40.0),
3217                    SemanticsActionRequest::SetValue(SemanticsValue::Number(value)) => Some(*value),
3218                    SemanticsActionRequest::SetValue(SemanticsValue::Range { value, .. }) => {
3219                        Some(*value)
3220                    }
3221                    _ => None,
3222                };
3223                let Some(next) = next.filter(|value| value.is_finite()) else {
3224                    return;
3225                };
3226                let next = next as f32;
3227                if !next.is_finite() {
3228                    return;
3229                }
3230                if self.set_axis_offset(ctx, ctx.widget_id(), next) {
3231                    ctx.request_paint();
3232                    ctx.request_semantics();
3233                }
3234                ctx.set_handled();
3235            }
3236            Event::Keyboard(key) if ctx.is_focused() && key.state == KeyState::Pressed => {
3237                let max_scroll = self.axis_offset(self.state.max_offset());
3238                if max_scroll <= f32::EPSILON {
3239                    return;
3240                }
3241
3242                let current = self.axis_offset(self.state.current_offset());
3243                let next = match key.key.as_str() {
3244                    "ArrowUp" if self.axis == ScrollBarAxis::Vertical => Some(current - 40.0),
3245                    "ArrowDown" if self.axis == ScrollBarAxis::Vertical => Some(current + 40.0),
3246                    "ArrowLeft" if self.axis == ScrollBarAxis::Horizontal => Some(current - 40.0),
3247                    "ArrowRight" if self.axis == ScrollBarAxis::Horizontal => Some(current + 40.0),
3248                    "PageUp" => Some(current - self.page_step()),
3249                    "PageDown" => Some(current + self.page_step()),
3250                    "Home" => Some(0.0),
3251                    "End" => Some(max_scroll),
3252                    _ => None,
3253                };
3254
3255                if let Some(next) = next {
3256                    if self.set_axis_offset(ctx, ctx.widget_id(), next) {
3257                        ctx.request_paint();
3258                        ctx.request_semantics();
3259                    }
3260                    ctx.set_handled();
3261                }
3262            }
3263            _ => {}
3264        }
3265    }
3266
3267    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
3268        self.state.bind_scroll_bar(ctx.widget_id());
3269        let width = self.resolved_width();
3270        let desired = match self.axis {
3271            ScrollBarAxis::Vertical => Size::new(
3272                width,
3273                if constraints.max.height.is_finite() {
3274                    constraints.max.height.max(0.0)
3275                } else {
3276                    40.0
3277                }
3278                .max(40.0),
3279            ),
3280            ScrollBarAxis::Horizontal => Size::new(
3281                if constraints.max.width.is_finite() {
3282                    constraints.max.width.max(0.0)
3283                } else {
3284                    40.0
3285                }
3286                .max(40.0),
3287                width,
3288            ),
3289        };
3290        constraints.clamp(desired)
3291    }
3292
3293    fn paint(&self, ctx: &mut PaintCtx) {
3294        let Some(metrics) = self.metrics(ctx.bounds(), ctx) else {
3295            return;
3296        };
3297
3298        let theme = self.resolved_theme();
3299        let palette = theme.palette;
3300        let track = metrics.track;
3301        let thumb = metrics.thumb;
3302        let track_radius = (track.width() * 0.5).min(track.height() * 0.5);
3303        let thumb_radius = (thumb.width() * 0.5).min(thumb.height() * 0.5);
3304        let interaction = self
3305            .hover_animation
3306            .get(ctx)
3307            .max(self.drag_animation.get(ctx))
3308            .max(self.focus_animation.get(ctx));
3309        let track_alpha = match self.appearance {
3310            ScrollBarAppearance::Gutter => 0.7,
3311            ScrollBarAppearance::Overlay => 0.08 + 0.32 * interaction,
3312        };
3313        let thumb_alpha = match self.appearance {
3314            ScrollBarAppearance::Gutter => 0.95,
3315            ScrollBarAppearance::Overlay => 0.68 + 0.27 * interaction,
3316        };
3317        let border_alpha = match self.appearance {
3318            ScrollBarAppearance::Gutter => 0.9,
3319            ScrollBarAppearance::Overlay => 0.42 + 0.36 * interaction,
3320        };
3321        ctx.fill(
3322            Path::rounded_rect(track, track_radius),
3323            palette.control_active.with_alpha(track_alpha),
3324        );
3325        let thumb = snap_to_pixels(ctx, thumb);
3326        ctx.fill(
3327            Path::rounded_rect(thumb, thumb_radius),
3328            mix_color(
3329                mix_color(
3330                    palette.placeholder,
3331                    palette.border_strong,
3332                    self.hover_animation
3333                        .get(ctx)
3334                        .max(self.focus_animation.get(ctx)),
3335                ),
3336                palette.text_muted,
3337                self.drag_animation.get(ctx),
3338            )
3339            .clamped()
3340            .with_alpha(thumb_alpha),
3341        );
3342        stroke_border(
3343            ctx,
3344            thumb,
3345            thumb_radius,
3346            physical_pixels(ctx, theme.metrics.border_width.max(1.0)),
3347            mix_color(
3348                palette.border.with_alpha(border_alpha),
3349                palette.focus_ring,
3350                self.focus_animation.get(ctx),
3351            )
3352            .clamped(),
3353        );
3354    }
3355
3356    fn semantics(&self, ctx: &mut SemanticsCtx) {
3357        let max_scroll = self.axis_offset(self.state.max_offset()).max(0.0);
3358        let current = self
3359            .axis_offset(self.state.current_offset())
3360            .clamp(0.0, max_scroll.max(0.0));
3361        let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::Slider, ctx.bounds());
3362        node.name = self.name.clone();
3363        node.value = Some(SemanticsValue::Range {
3364            value: f64::from(current),
3365            min: 0.0,
3366            max: f64::from(max_scroll),
3367        });
3368        node.state.disabled = max_scroll <= f32::EPSILON;
3369        node.state.focused = ctx.is_focused();
3370        node.state.hovered = self.hovered;
3371        node.actions = if self.focusable {
3372            vec![
3373                SemanticsAction::Focus,
3374                SemanticsAction::Increment,
3375                SemanticsAction::Decrement,
3376                SemanticsAction::SetValue,
3377            ]
3378        } else {
3379            vec![
3380                SemanticsAction::Increment,
3381                SemanticsAction::Decrement,
3382                SemanticsAction::SetValue,
3383            ]
3384        };
3385        ctx.push(node);
3386    }
3387
3388    fn accepts_focus(&self) -> bool {
3389        self.focusable
3390    }
3391
3392    fn focus_changed(&mut self, ctx: &mut EventCtx, focused: bool) {
3393        let theme = self.resolved_theme();
3394        set_focus_animation_target(&mut self.focus_animation, focused as u8 as f32, &theme, ctx);
3395        ctx.request_paint();
3396        ctx.request_semantics();
3397    }
3398}
3399
3400const OVERLAY_SCROLL_BAR_IDLE_THICKNESS: f32 = 4.0;
3401
3402fn pointer_supports_hover(pointer_kind: PointerKind) -> bool {
3403    matches!(pointer_kind, PointerKind::Mouse | PointerKind::Pen)
3404}
3405
3406/// Resolve classic scrollbar gutters from an initially unobstructed viewport.
3407/// A gutter on either axis can make the opposite axis overflow as well.
3408pub(crate) fn scroll_bar_gutter(
3409    enabled: bool,
3410    axes: ScrollAxes,
3411    outer: Size,
3412    content: Size,
3413    thickness: f32,
3414) -> Size {
3415    let mut gutter = Size::ZERO;
3416    if enabled {
3417        for _ in 0..3 {
3418            sui_runtime::record_scrollbar_gutter_iteration();
3419            let viewport = scroll_viewport_size(outer, gutter);
3420            let next = Size::new(
3421                if axes.allows_vertical() && content.height > viewport.height + f32::EPSILON {
3422                    thickness.max(0.0).min(outer.width.max(0.0))
3423                } else {
3424                    gutter.width
3425                },
3426                if axes.allows_horizontal() && content.width > viewport.width + f32::EPSILON {
3427                    thickness.max(0.0).min(outer.height.max(0.0))
3428                } else {
3429                    gutter.height
3430                },
3431            );
3432            if next == gutter {
3433                break;
3434            }
3435            gutter = next;
3436        }
3437    }
3438    gutter
3439}
3440
3441pub(crate) fn scroll_viewport_size(outer: Size, gutter: Size) -> Size {
3442    Size::new(
3443        (outer.width - gutter.width).max(0.0),
3444        (outer.height - gutter.height).max(0.0),
3445    )
3446}
3447
3448pub(crate) struct ScrollBars {
3449    corner: SingleChild,
3450    vertical: Option<SingleChild>,
3451    horizontal: Option<SingleChild>,
3452    show_vertical: bool,
3453    show_horizontal: bool,
3454}
3455
3456impl ScrollBars {
3457    pub(crate) fn new(
3458        state: ScrollState,
3459        theme: Rc<RefCell<DefaultTheme>>,
3460        name: Option<&str>,
3461        axes: ScrollAxes,
3462    ) -> Self {
3463        // Compact thumb styling is independent of layout: the full hit area
3464        // lives inside a reserved gutter, outside the content viewport.
3465        let vertical = axes.allows_vertical().then(|| {
3466            let vertical_theme = Rc::clone(&theme);
3467            let vertical_name = name
3468                .map(|name| format!("{name} vertical scroll bar"))
3469                .unwrap_or_else(|| "Vertical scroll bar".to_string());
3470            SingleChild::new_with_paint_boundary(
3471                ScrollBar::vertical(state.clone())
3472                    .theme_when(move || *vertical_theme.borrow())
3473                    .name(vertical_name)
3474                    .overlay(),
3475            )
3476        });
3477
3478        let horizontal = axes.allows_horizontal().then(|| {
3479            let horizontal_theme = Rc::clone(&theme);
3480            let horizontal_name = name
3481                .map(|name| format!("{name} horizontal scroll bar"))
3482                .unwrap_or_else(|| "Horizontal scroll bar".to_string());
3483            SingleChild::new_with_paint_boundary(
3484                ScrollBar::horizontal(state)
3485                    .theme_when(move || *horizontal_theme.borrow())
3486                    .name(horizontal_name)
3487                    .overlay(),
3488            )
3489        });
3490
3491        Self {
3492            corner: SingleChild::new(SizedBox::new()),
3493            vertical,
3494            horizontal,
3495            show_vertical: false,
3496            show_horizontal: false,
3497        }
3498    }
3499
3500    pub(crate) fn set_visibility(&mut self, axes: ScrollAxes, max_offset: Vector) {
3501        let show_vertical =
3502            self.vertical.is_some() && axes.allows_vertical() && max_offset.y > f32::EPSILON;
3503        let show_horizontal =
3504            self.horizontal.is_some() && axes.allows_horizontal() && max_offset.x > f32::EPSILON;
3505        self.show_vertical = show_vertical;
3506        self.show_horizontal = show_horizontal;
3507    }
3508
3509    pub(crate) fn measure(&mut self, ctx: &mut MeasureCtx, viewport: Size, thickness: f32) {
3510        self.corner
3511            .measure(ctx, Constraints::tight(Size::new(thickness, thickness)));
3512        if let Some(vertical) = &mut self.vertical {
3513            vertical.measure(
3514                ctx,
3515                Constraints::tight(Size::new(thickness, viewport.height.max(0.0))),
3516            );
3517        }
3518        if let Some(horizontal) = &mut self.horizontal {
3519            horizontal.measure(
3520                ctx,
3521                Constraints::tight(Size::new(viewport.width.max(0.0), thickness)),
3522            );
3523        }
3524    }
3525
3526    pub(crate) fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect, thickness: f32) {
3527        let gutter = Size::new(
3528            if self.show_vertical {
3529                thickness.min(bounds.width()).max(0.0)
3530            } else {
3531                0.0
3532            },
3533            if self.show_horizontal {
3534                thickness.min(bounds.height()).max(0.0)
3535            } else {
3536                0.0
3537            },
3538        );
3539        let viewport = scroll_viewport_size(bounds.size, gutter);
3540        if let Some(vertical) = &mut self.vertical {
3541            vertical.arrange(
3542                ctx,
3543                Rect::new(
3544                    bounds.x() + viewport.width,
3545                    bounds.y(),
3546                    gutter.width,
3547                    if self.show_vertical {
3548                        viewport.height
3549                    } else {
3550                        0.0
3551                    },
3552                ),
3553            );
3554        }
3555        if let Some(horizontal) = &mut self.horizontal {
3556            horizontal.arrange(
3557                ctx,
3558                Rect::new(
3559                    bounds.x(),
3560                    bounds.y() + viewport.height,
3561                    if self.show_horizontal {
3562                        viewport.width
3563                    } else {
3564                        0.0
3565                    },
3566                    gutter.height,
3567                ),
3568            );
3569        }
3570        // The shared corner also owns its hit area so clicks cannot reach
3571        // scrolled content painted behind the two gutters.
3572        self.corner.arrange(
3573            ctx,
3574            Rect::new(
3575                bounds.x() + viewport.width,
3576                bounds.y() + viewport.height,
3577                gutter.width,
3578                gutter.height,
3579            ),
3580        );
3581    }
3582
3583    pub(crate) fn paint(&self, ctx: &mut PaintCtx) {
3584        if let Some(vertical) = &self.vertical {
3585            vertical.paint(ctx);
3586        }
3587        if let Some(horizontal) = &self.horizontal {
3588            horizontal.paint(ctx);
3589        }
3590    }
3591
3592    pub(crate) fn semantics(&self, ctx: &mut SemanticsCtx) {
3593        if self.show_vertical
3594            && let Some(vertical) = &self.vertical
3595        {
3596            vertical.semantics(ctx);
3597        }
3598        if self.show_horizontal
3599            && let Some(horizontal) = &self.horizontal
3600        {
3601            horizontal.semantics(ctx);
3602        }
3603    }
3604
3605    pub(crate) fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
3606        self.corner.visit_children(visitor);
3607        if let Some(vertical) = &self.vertical {
3608            vertical.visit_children(visitor);
3609        }
3610        if let Some(horizontal) = &self.horizontal {
3611            horizontal.visit_children(visitor);
3612        }
3613    }
3614
3615    pub(crate) fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
3616        self.corner.visit_children_mut(visitor);
3617        if let Some(vertical) = &mut self.vertical {
3618            vertical.visit_children_mut(visitor);
3619        }
3620        if let Some(horizontal) = &mut self.horizontal {
3621            horizontal.visit_children_mut(visitor);
3622        }
3623    }
3624}
3625
3626pub struct ScrollView {
3627    theme: Box<DefaultTheme>,
3628    theme_reader: Option<Rc<dyn Fn() -> DefaultTheme>>,
3629    scroll_bar_theme: Rc<RefCell<DefaultTheme>>,
3630    name: Option<String>,
3631    state: ScrollState,
3632    overflow_x: Overflow,
3633    overflow_y: Overflow,
3634    content_width: ContentExtent,
3635    content_height: ContentExtent,
3636    shrink_height: bool,
3637    gutter: Size,
3638    offset: Vector,
3639    content_size: Size,
3640    focus_animation: AnimatedScalar,
3641    retain_content: bool,
3642    scroll_bars: bool,
3643    bars: Option<ScrollBars>,
3644    touch_scroll: Option<TouchScrollGesture>,
3645    touch_fling: TouchFling,
3646    offset_change: OffsetChange,
3647    drag_auto_scroll: DragAutoScroll,
3648    child: SingleChild,
3649}
3650
3651impl ScrollView {
3652    pub fn new<W>(child: W) -> Self
3653    where
3654        W: Widget + 'static,
3655    {
3656        let theme = DefaultTheme::default();
3657        Self {
3658            theme: Box::new(theme),
3659            theme_reader: None,
3660            scroll_bar_theme: Rc::new(RefCell::new(theme)),
3661            name: None,
3662            state: ScrollState::new(),
3663            overflow_x: Overflow::Clip,
3664            overflow_y: Overflow::Auto,
3665            content_width: ContentExtent::Natural,
3666            content_height: ContentExtent::Natural,
3667            shrink_height: false,
3668            gutter: Size::ZERO,
3669            offset: Vector::ZERO,
3670            content_size: Size::ZERO,
3671            focus_animation: AnimatedScalar::new(0.0),
3672            retain_content: false,
3673            scroll_bars: true,
3674            bars: None,
3675            touch_scroll: None,
3676            touch_fling: TouchFling::default(),
3677            offset_change: OffsetChange::default(),
3678            drag_auto_scroll: DragAutoScroll::default(),
3679            child: SingleChild::new(child),
3680        }
3681    }
3682
3683    pub fn vertical<W>(child: W) -> Self
3684    where
3685        W: Widget + 'static,
3686    {
3687        Self::new(child)
3688    }
3689
3690    pub fn horizontal<W>(child: W) -> Self
3691    where
3692        W: Widget + 'static,
3693    {
3694        Self::new(child).axes(ScrollAxes::Horizontal)
3695    }
3696
3697    pub fn both<W>(child: W) -> Self
3698    where
3699        W: Widget + 'static,
3700    {
3701        Self::new(child).axes(ScrollAxes::Both)
3702    }
3703
3704    pub fn axes(mut self, axes: ScrollAxes) -> Self {
3705        self.overflow_x = if axes.allows_horizontal() {
3706            Overflow::Auto
3707        } else {
3708            Overflow::Clip
3709        };
3710        self.overflow_y = if axes.allows_vertical() {
3711            Overflow::Auto
3712        } else {
3713            Overflow::Clip
3714        };
3715        self.content_width = ContentExtent::Natural;
3716        self.content_height = ContentExtent::Natural;
3717        self.state.sync_unmeasured_axes(self.scroll_axes());
3718        self
3719    }
3720
3721    pub fn overflow(mut self, overflow: Overflow) -> Self {
3722        self.overflow_x = overflow;
3723        self.overflow_y = overflow;
3724        self.content_width = if overflow.is_scrollable() {
3725            ContentExtent::Viewport
3726        } else {
3727            ContentExtent::Natural
3728        };
3729        self.state.sync_unmeasured_axes(self.scroll_axes());
3730        self
3731    }
3732
3733    pub fn overflow_x(mut self, overflow: Overflow) -> Self {
3734        self.overflow_x = overflow;
3735        self.content_width = if overflow.is_scrollable() {
3736            ContentExtent::Viewport
3737        } else {
3738            ContentExtent::Natural
3739        };
3740        self.state.sync_unmeasured_axes(self.scroll_axes());
3741        self
3742    }
3743
3744    pub fn overflow_y(mut self, overflow: Overflow) -> Self {
3745        self.overflow_y = overflow;
3746        self.state.sync_unmeasured_axes(self.scroll_axes());
3747        self
3748    }
3749
3750    /// Select how the child width is derived when horizontal overflow is enabled.
3751    pub const fn content_width(mut self, extent: ContentExtent) -> Self {
3752        self.content_width = extent;
3753        self
3754    }
3755
3756    /// Select how the child height is derived when vertical overflow is enabled.
3757    pub const fn content_height(mut self, extent: ContentExtent) -> Self {
3758        self.content_height = extent;
3759        self
3760    }
3761
3762    /// Fit short content while retaining vertical scrolling when it exceeds
3763    /// the available height. Parent minimum constraints still take precedence.
3764    pub const fn shrink_height(mut self, enabled: bool) -> Self {
3765        self.shrink_height = enabled;
3766        self
3767    }
3768
3769    pub fn name(mut self, name: impl Into<String>) -> Self {
3770        self.name = Some(name.into());
3771        self
3772    }
3773
3774    pub fn theme(mut self, theme: DefaultTheme) -> Self {
3775        self.theme = Box::new(theme);
3776        self.theme_reader = None;
3777        *self.scroll_bar_theme.borrow_mut() = theme;
3778        self
3779    }
3780
3781    pub fn theme_when<F>(mut self, theme: F) -> Self
3782    where
3783        F: Fn() -> DefaultTheme + 'static,
3784    {
3785        self.theme_reader = Some(Rc::new(theme));
3786        self
3787    }
3788
3789    pub fn state(mut self, state: ScrollState) -> Self {
3790        self.state = state;
3791        self.state.sync_unmeasured_axes(self.scroll_axes());
3792        self.bars = None;
3793        self
3794    }
3795
3796    /// Controls the built-in scroll bars beside overflowing content.
3797    /// Disable this when composing a standalone [`ScrollBar`] with the same
3798    /// [`ScrollState`].
3799    /// Compatibility name for `scroll_bars`. Built-in bars reserve layout space.
3800    pub fn overlay_scroll_bars(self, enabled: bool) -> Self {
3801        self.scroll_bars(enabled)
3802    }
3803
3804    /// Whether a drag held near an edge scrolls the view. On by default.
3805    pub fn auto_scroll_on_drag(mut self, enabled: bool) -> Self {
3806        self.drag_auto_scroll.enabled = enabled;
3807        self
3808    }
3809
3810    /// Called with the new offset whenever the view scrolls, whatever moved
3811    /// it: the wheel, a touch drag or fling, keys, a scroll bar, or code.
3812    /// Changes made during layout, such as a scroll bar drag or a jump to an
3813    /// item, arrive on the next animation frame.
3814    pub fn on_offset_change<F>(mut self, callback: F) -> Self
3815    where
3816        F: Fn(Vector) + 'static,
3817    {
3818        self.offset_change.callback = Some(Rc::new(callback));
3819        self
3820    }
3821
3822    pub fn on_offset_change_with_ctx<F>(mut self, callback: F) -> Self
3823    where
3824        F: Fn(&mut EventCtx, Vector) + 'static,
3825    {
3826        self.offset_change.callback_with_ctx = Some(Rc::new(callback));
3827        self
3828    }
3829
3830    /// Show built-in scrollbars in their own gutters when content overflows.
3831    pub fn scroll_bars(mut self, enabled: bool) -> Self {
3832        self.scroll_bars = enabled;
3833        if !enabled {
3834            self.bars = None;
3835        }
3836        self
3837    }
3838
3839    pub const fn viewport_size_hint(mut self, enabled: bool) -> Self {
3840        self.content_width = if enabled {
3841            ContentExtent::Viewport
3842        } else {
3843            ContentExtent::Natural
3844        };
3845        self.content_height = if enabled {
3846            ContentExtent::Viewport
3847        } else {
3848            ContentExtent::Natural
3849        };
3850        self
3851    }
3852
3853    pub const fn viewport_width_hint(mut self, enabled: bool) -> Self {
3854        self.content_width = if enabled {
3855            ContentExtent::Viewport
3856        } else {
3857            ContentExtent::Natural
3858        };
3859        self
3860    }
3861
3862    pub const fn viewport_height_hint(mut self, enabled: bool) -> Self {
3863        self.content_height = if enabled {
3864            ContentExtent::Viewport
3865        } else {
3866            ContentExtent::Natural
3867        };
3868        self
3869    }
3870
3871    /// Retains the complete child subtree behind a paint boundary so scrolling
3872    /// can move it with a composition-only transform.
3873    ///
3874    /// This is best for content that is expensive to repaint but cheap to
3875    /// composite. Very large text or deeply layered scenes may render faster
3876    /// with the default flattened path.
3877    pub fn retain_content_layer(mut self) -> Self {
3878        self.retain_content = true;
3879        let child = self.child;
3880        self.child = child.with_paint_boundary();
3881        self
3882    }
3883
3884    pub const fn current_offset(&self) -> Vector {
3885        self.offset
3886    }
3887
3888    pub fn set_offset(&mut self, offset: Vector) {
3889        self.state.sync_unmeasured_axes(self.scroll_axes());
3890        let _ = self.state.set_offset(offset);
3891        self.offset = self.state.current_offset();
3892    }
3893
3894    pub fn child_pod(&self) -> &WidgetPod {
3895        self.child.child()
3896    }
3897
3898    pub fn child_mut(&mut self) -> &mut WidgetPod {
3899        self.child.child_mut()
3900    }
3901
3902    pub fn replace_child<W>(&mut self, child: W)
3903    where
3904        W: Widget + 'static,
3905    {
3906        self.child = if self.retain_content {
3907            SingleChild::new_with_paint_boundary(child)
3908        } else {
3909            SingleChild::new(child)
3910        };
3911    }
3912
3913    fn clamp_offset(&self, viewport: Size, offset: Vector) -> Vector {
3914        let max_x = (self.content_size.width - viewport.width).max(0.0);
3915        let max_y = (self.content_size.height - viewport.height).max(0.0);
3916
3917        Vector::new(
3918            if self.overflow_x.is_scrollable() {
3919                offset.x.clamp(0.0, max_x)
3920            } else {
3921                0.0
3922            },
3923            if self.overflow_y.is_scrollable() {
3924                offset.y.clamp(0.0, max_y)
3925            } else {
3926                0.0
3927            },
3928        )
3929    }
3930
3931    fn scroll_axes(&self) -> ScrollAxes {
3932        match (
3933            self.overflow_x.is_scrollable(),
3934            self.overflow_y.is_scrollable(),
3935        ) {
3936            (true, true) => ScrollAxes::Both,
3937            (true, false) => ScrollAxes::Horizontal,
3938            (false, true) => ScrollAxes::Vertical,
3939            (false, false) => ScrollAxes::None,
3940        }
3941    }
3942
3943    fn resolved_theme(&self) -> DefaultTheme {
3944        self.theme_reader
3945            .as_ref()
3946            .map(|reader| reader())
3947            .unwrap_or_else(|| *self.theme)
3948    }
3949
3950    fn sync_scroll_bar_theme(&self) -> DefaultTheme {
3951        let theme = self.resolved_theme();
3952        *self.scroll_bar_theme.borrow_mut() = theme;
3953        theme
3954    }
3955
3956    fn ensure_scroll_bars(&mut self) {
3957        let axes = self.scroll_axes();
3958        if self.scroll_bars && axes != ScrollAxes::None && self.bars.is_none() {
3959            self.bars = Some(ScrollBars::new(
3960                self.state.clone(),
3961                Rc::clone(&self.scroll_bar_theme),
3962                self.name.as_deref(),
3963                axes,
3964            ));
3965        }
3966    }
3967
3968    fn touch_delta(&self, pointer: &PointerEvent) -> Vector {
3969        let delta = Vector::new(-pointer.delta.x, -pointer.delta.y);
3970        match self.scroll_axes() {
3971            ScrollAxes::None => Vector::ZERO,
3972            ScrollAxes::Vertical => Vector::new(0.0, delta.y),
3973            ScrollAxes::Horizontal => Vector::new(delta.x, 0.0),
3974            ScrollAxes::Both => delta,
3975        }
3976    }
3977
3978    fn has_touch_overflow(&self) -> bool {
3979        let max_offset = self.state.max_offset();
3980        (self.scroll_axes().allows_horizontal() && max_offset.x > f32::EPSILON)
3981            || (self.scroll_axes().allows_vertical() && max_offset.y > f32::EPSILON)
3982    }
3983
3984    fn handle_touch_pointer(&mut self, ctx: &mut EventCtx, pointer: &PointerEvent, viewport: Size) {
3985        if pointer.pointer_kind != PointerKind::Touch {
3986            if pointer.kind == PointerEventKind::Down && ctx.bounds().contains(pointer.position) {
3987                self.touch_fling.stop();
3988            }
3989            return;
3990        }
3991
3992        match pointer.kind {
3993            PointerEventKind::Down
3994                if pointer.is_primary
3995                    && pointer.button == Some(PointerButton::Primary)
3996                    && self.viewport_rect(ctx.bounds()).contains(pointer.position)
3997                    && self.has_touch_overflow() =>
3998            {
3999                self.touch_scroll = Some(TouchScrollGesture::new(pointer, ctx.current_time()));
4000                // A touch that catches a fling only stops it, rather than also
4001                // pressing whatever lies beneath.
4002                if self.touch_fling.stop() {
4003                    ctx.set_handled();
4004                }
4005            }
4006            PointerEventKind::Move => {
4007                let Some(gesture) = self.touch_scroll else {
4008                    return;
4009                };
4010                if !gesture.matches(pointer) || ctx.phase() == EventPhase::Capture {
4011                    return;
4012                }
4013                if let Some(gesture) = &mut self.touch_scroll {
4014                    gesture.velocity.push(ctx.current_time(), pointer.position);
4015                }
4016                if !gesture.dragging && !gesture.passed_threshold(pointer, self.scroll_axes()) {
4017                    return;
4018                }
4019
4020                let delta = self.touch_delta(pointer);
4021                let relevant_delta = delta.x.abs().max(delta.y.abs());
4022                if relevant_delta <= f32::EPSILON {
4023                    if gesture.dragging {
4024                        ctx.set_handled();
4025                    }
4026                    return;
4027                }
4028
4029                if self.scroll_by(viewport, delta, ctx) {
4030                    if !gesture.dragging {
4031                        if let Some(gesture) = &mut self.touch_scroll {
4032                            gesture.dragging = true;
4033                        }
4034                        ctx.request_pointer_capture(pointer.pointer_id);
4035                    }
4036                    ctx.set_handled();
4037                } else if !gesture.dragging {
4038                    if let Some(gesture) = &mut self.touch_scroll {
4039                        gesture.dragging = true;
4040                    }
4041                    // Claim the pan even at a hard boundary so controls beneath it receive
4042                    // Cancel and the gesture can reverse direction. Leave the event unhandled
4043                    // so an enclosing scroll view can still take ownership and move instead.
4044                    ctx.request_pointer_capture(pointer.pointer_id);
4045                }
4046            }
4047            PointerEventKind::Up | PointerEventKind::Cancel => {
4048                let Some(gesture) = self.touch_scroll else {
4049                    return;
4050                };
4051                if !gesture.matches(pointer) {
4052                    return;
4053                }
4054                self.touch_scroll = None;
4055                if gesture.dragging && ctx.phase() != EventPhase::Capture {
4056                    ctx.release_pointer_capture(pointer.pointer_id);
4057                    ctx.set_handled();
4058                    if pointer.kind == PointerEventKind::Up {
4059                        let velocity =
4060                            gesture.release_velocity(ctx.current_time(), self.scroll_axes());
4061                        self.touch_fling.start(ctx, velocity);
4062                    }
4063                }
4064            }
4065            _ => {}
4066        }
4067    }
4068
4069    fn should_clip_paint(&self) -> bool {
4070        self.overflow_x.clips_paint() || self.overflow_y.clips_paint()
4071    }
4072
4073    fn viewport_rect(&self, bounds: Rect) -> Rect {
4074        Rect::from_origin_size(
4075            bounds.origin,
4076            scroll_viewport_size(bounds.size, self.gutter),
4077        )
4078    }
4079
4080    fn clip_rect(&self, bounds: Rect) -> Rect {
4081        let bounds = self.viewport_rect(bounds);
4082        let large = 1_000_000.0;
4083        let x = if self.overflow_x.clips_paint() {
4084            bounds.x()
4085        } else {
4086            -large
4087        };
4088        let width = if self.overflow_x.clips_paint() {
4089            bounds.width()
4090        } else {
4091            large * 2.0
4092        };
4093        let y = if self.overflow_y.clips_paint() {
4094            bounds.y()
4095        } else {
4096            -large
4097        };
4098        let height = if self.overflow_y.clips_paint() {
4099            bounds.height()
4100        } else {
4101            large * 2.0
4102        };
4103        Rect::new(x, y, width, height)
4104    }
4105
4106    fn scroll_by(&mut self, viewport: Size, delta: Vector, ctx: &mut EventCtx) -> bool {
4107        let next = self.clamp_offset(viewport, self.offset + delta);
4108        if next != self.offset {
4109            self.offset = next;
4110            self.publish_state(ctx, viewport);
4111            ctx.request_arrange();
4112            if !self.retain_content {
4113                ctx.request_paint();
4114            }
4115            ctx.request(InvalidationRequest::new(
4116                InvalidationTarget::Widget(self.child.child().id()),
4117                InvalidationKind::Transform,
4118            ));
4119            ctx.request_semantics();
4120            ctx.refresh_drag_targets();
4121            self.offset_change.notify(ctx, self.offset);
4122            true
4123        } else {
4124            false
4125        }
4126    }
4127
4128    fn sync_state<C>(&mut self, ctx: &mut C, viewport: Size)
4129    where
4130        C: ScrollInvalidationCtx + ScrollWidgetCtx,
4131    {
4132        let state = &self.state;
4133
4134        state.bind_scroll_view(ctx.widget_id(), self.child.child().id());
4135        if state.sync_metrics(self.scroll_axes(), viewport, self.content_size) {
4136            for scroll_bar_id in state.subscribers().scroll_bar_ids {
4137                request_scroll_bar_refresh(ctx, scroll_bar_id);
4138            }
4139        }
4140        self.offset = self.clamp_offset(viewport, state.current_offset());
4141        if state.set_offset(self.offset) {
4142            for scroll_bar_id in state.subscribers().scroll_bar_ids {
4143                request_scroll_bar_refresh(ctx, scroll_bar_id);
4144            }
4145        }
4146        self.offset_change.defer(ctx, self.offset);
4147    }
4148
4149    fn publish_state(&self, ctx: &mut EventCtx, viewport: Size) {
4150        let state = &self.state;
4151
4152        state.bind_scroll_view(ctx.widget_id(), self.child.child().id());
4153        let _ = state.sync_metrics(self.scroll_axes(), viewport, self.content_size);
4154        if state.set_offset(self.offset) {
4155            for scroll_bar_id in state.subscribers().scroll_bar_ids {
4156                if scroll_bar_id != ctx.widget_id() {
4157                    request_scroll_bar_refresh(ctx, scroll_bar_id);
4158                }
4159            }
4160        }
4161    }
4162}
4163
4164pub struct VirtualScrollView {
4165    theme: Box<DefaultTheme>,
4166    theme_reader: Option<Rc<dyn Fn() -> DefaultTheme>>,
4167    scroll_bar_theme: Rc<RefCell<DefaultTheme>>,
4168    name: Option<String>,
4169    padding: Insets,
4170    spacing: f32,
4171    state: ScrollState,
4172    offset_y: f32,
4173    last_arranged_offset_y: f32,
4174    content_height: f32,
4175    item_offsets: Vec<f32>,
4176    visible_range: Range<usize>,
4177    focus_animation: AnimatedScalar,
4178    scroll_bars: bool,
4179    bars: Option<ScrollBars>,
4180    touch_scroll: Option<TouchScrollGesture>,
4181    touch_fling: TouchFling,
4182    offset_change: OffsetChange,
4183    drag_auto_scroll: DragAutoScroll,
4184    children: WidgetChildren,
4185}
4186
4187impl VirtualScrollView {
4188    pub fn new() -> Self {
4189        let theme = DefaultTheme::default();
4190        Self {
4191            theme: Box::new(theme),
4192            theme_reader: None,
4193            scroll_bar_theme: Rc::new(RefCell::new(theme)),
4194            name: None,
4195            padding: Insets::ZERO,
4196            spacing: 0.0,
4197            state: ScrollState::new(),
4198            offset_y: 0.0,
4199            last_arranged_offset_y: 0.0,
4200            content_height: 0.0,
4201            item_offsets: Vec::new(),
4202            visible_range: 0..0,
4203            focus_animation: AnimatedScalar::new(0.0),
4204            scroll_bars: true,
4205            bars: None,
4206            touch_scroll: None,
4207            touch_fling: TouchFling::default(),
4208            offset_change: OffsetChange::default(),
4209            drag_auto_scroll: DragAutoScroll::default(),
4210            children: WidgetChildren::new(),
4211        }
4212    }
4213
4214    pub fn name(mut self, name: impl Into<String>) -> Self {
4215        self.name = Some(name.into());
4216        self
4217    }
4218
4219    pub fn theme(mut self, theme: DefaultTheme) -> Self {
4220        self.theme = Box::new(theme);
4221        self.theme_reader = None;
4222        *self.scroll_bar_theme.borrow_mut() = theme;
4223        self
4224    }
4225
4226    pub fn theme_when<F>(mut self, theme: F) -> Self
4227    where
4228        F: Fn() -> DefaultTheme + 'static,
4229    {
4230        self.theme_reader = Some(Rc::new(theme));
4231        self
4232    }
4233
4234    pub fn padding(mut self, padding: Insets) -> Self {
4235        self.padding = padding;
4236        self
4237    }
4238
4239    pub fn gap(mut self, gap: f32) -> Self {
4240        self.spacing = gap.max(0.0);
4241        self
4242    }
4243
4244    pub fn state(mut self, state: ScrollState) -> Self {
4245        self.state = state;
4246        self.state.sync_unmeasured_axes(ScrollAxes::Vertical);
4247        self.bars = None;
4248        self
4249    }
4250
4251    /// Controls the built-in vertical scroll bar painted over overflowing
4252    /// content. Disable this when composing a standalone [`ScrollBar`] with
4253    /// the same [`ScrollState`].
4254    /// Compatibility name for `scroll_bars`. Built-in bars reserve layout space.
4255    pub fn overlay_scroll_bars(self, enabled: bool) -> Self {
4256        self.scroll_bars(enabled)
4257    }
4258
4259    /// Whether a drag held near an edge scrolls the view. On by default.
4260    pub fn auto_scroll_on_drag(mut self, enabled: bool) -> Self {
4261        self.drag_auto_scroll.enabled = enabled;
4262        self
4263    }
4264
4265    /// Called with the new offset whenever the view scrolls, whatever moved
4266    /// it: the wheel, a touch drag or fling, keys, a scroll bar, or code.
4267    /// Changes made during layout, such as a scroll bar drag or a jump to an
4268    /// item, arrive on the next animation frame.
4269    pub fn on_offset_change<F>(mut self, callback: F) -> Self
4270    where
4271        F: Fn(Vector) + 'static,
4272    {
4273        self.offset_change.callback = Some(Rc::new(callback));
4274        self
4275    }
4276
4277    pub fn on_offset_change_with_ctx<F>(mut self, callback: F) -> Self
4278    where
4279        F: Fn(&mut EventCtx, Vector) + 'static,
4280    {
4281        self.offset_change.callback_with_ctx = Some(Rc::new(callback));
4282        self
4283    }
4284
4285    /// Show built-in scrollbars in their own gutters when content overflows.
4286    pub fn scroll_bars(mut self, enabled: bool) -> Self {
4287        self.scroll_bars = enabled;
4288        if !enabled {
4289            self.bars = None;
4290        }
4291        self
4292    }
4293
4294    pub fn with_child<W>(mut self, child: W) -> Self
4295    where
4296        W: Widget + 'static,
4297    {
4298        self.children.push(child);
4299        self
4300    }
4301
4302    pub fn push<W>(&mut self, child: W)
4303    where
4304        W: Widget + 'static,
4305    {
4306        self.children.push(child);
4307    }
4308
4309    pub const fn current_offset(&self) -> Vector {
4310        Vector::new(0.0, self.offset_y)
4311    }
4312
4313    pub fn set_offset(&mut self, offset: Vector) {
4314        self.offset_y = offset.y.max(0.0);
4315        let _ = self.state.set_offset(Vector::new(0.0, self.offset_y));
4316        self.offset_y = self.state.current_offset().y;
4317    }
4318
4319    fn resolved_theme(&self) -> DefaultTheme {
4320        self.theme_reader
4321            .as_ref()
4322            .map(|reader| reader())
4323            .unwrap_or_else(|| *self.theme)
4324    }
4325
4326    fn sync_scroll_bar_theme(&self) -> DefaultTheme {
4327        let theme = self.resolved_theme();
4328        *self.scroll_bar_theme.borrow_mut() = theme;
4329        theme
4330    }
4331
4332    fn ensure_scroll_bars(&mut self) {
4333        if self.scroll_bars && self.bars.is_none() {
4334            self.bars = Some(ScrollBars::new(
4335                self.state.clone(),
4336                Rc::clone(&self.scroll_bar_theme),
4337                self.name.as_deref(),
4338                ScrollAxes::Vertical,
4339            ));
4340        }
4341    }
4342
4343    fn has_touch_overflow(&self) -> bool {
4344        self.state.max_offset().y > f32::EPSILON
4345    }
4346
4347    fn handle_touch_pointer(&mut self, ctx: &mut EventCtx, pointer: &PointerEvent, viewport: Rect) {
4348        if pointer.pointer_kind != PointerKind::Touch {
4349            if pointer.kind == PointerEventKind::Down && ctx.bounds().contains(pointer.position) {
4350                self.touch_fling.stop();
4351            }
4352            return;
4353        }
4354
4355        match pointer.kind {
4356            PointerEventKind::Down
4357                if pointer.is_primary
4358                    && pointer.button == Some(PointerButton::Primary)
4359                    && ctx.bounds().contains(pointer.position)
4360                    && self.has_touch_overflow() =>
4361            {
4362                self.touch_scroll = Some(TouchScrollGesture::new(pointer, ctx.current_time()));
4363                // A touch that catches a fling only stops it, rather than also
4364                // pressing whatever lies beneath.
4365                if self.touch_fling.stop() {
4366                    ctx.set_handled();
4367                }
4368            }
4369            PointerEventKind::Move => {
4370                let Some(gesture) = self.touch_scroll else {
4371                    return;
4372                };
4373                if !gesture.matches(pointer) || ctx.phase() == EventPhase::Capture {
4374                    return;
4375                }
4376                if let Some(gesture) = &mut self.touch_scroll {
4377                    gesture.velocity.push(ctx.current_time(), pointer.position);
4378                }
4379                if !gesture.dragging && !gesture.passed_threshold(pointer, ScrollAxes::Vertical) {
4380                    return;
4381                }
4382
4383                let delta_y = -pointer.delta.y;
4384                if delta_y.abs() <= f32::EPSILON {
4385                    if gesture.dragging {
4386                        ctx.set_handled();
4387                    }
4388                    return;
4389                }
4390
4391                if self.scroll_by(viewport, delta_y, ctx) {
4392                    if !gesture.dragging {
4393                        if let Some(gesture) = &mut self.touch_scroll {
4394                            gesture.dragging = true;
4395                        }
4396                        ctx.request_pointer_capture(pointer.pointer_id);
4397                    }
4398                    ctx.set_handled();
4399                } else if !gesture.dragging {
4400                    if let Some(gesture) = &mut self.touch_scroll {
4401                        gesture.dragging = true;
4402                    }
4403                    ctx.request_pointer_capture(pointer.pointer_id);
4404                }
4405            }
4406            PointerEventKind::Up | PointerEventKind::Cancel => {
4407                let Some(gesture) = self.touch_scroll else {
4408                    return;
4409                };
4410                if !gesture.matches(pointer) {
4411                    return;
4412                }
4413                self.touch_scroll = None;
4414                if gesture.dragging && ctx.phase() != EventPhase::Capture {
4415                    ctx.release_pointer_capture(pointer.pointer_id);
4416                    ctx.set_handled();
4417                    if pointer.kind == PointerEventKind::Up {
4418                        let velocity =
4419                            gesture.release_velocity(ctx.current_time(), ScrollAxes::Vertical);
4420                        self.touch_fling.start(ctx, velocity);
4421                    }
4422                }
4423            }
4424            _ => {}
4425        }
4426    }
4427
4428    fn viewport_rect(&self, bounds: Rect) -> Rect {
4429        let viewport = inset_rect(bounds, self.padding);
4430        let gutter = scroll_bar_gutter(
4431            self.scroll_bars,
4432            ScrollAxes::Vertical,
4433            viewport.size,
4434            Size::new(0.0, self.content_height),
4435            self.resolved_theme().metrics.scroll_bar_thickness,
4436        );
4437        Rect::from_origin_size(viewport.origin, scroll_viewport_size(viewport.size, gutter))
4438    }
4439
4440    fn clamp_offset(&self, viewport_height: f32, offset_y: f32) -> f32 {
4441        let max_scroll = (self.content_height - viewport_height).max(0.0);
4442        offset_y.clamp(0.0, max_scroll)
4443    }
4444
4445    fn visible_range_for_offset(&self, viewport_height: f32, offset_y: f32) -> Range<usize> {
4446        let overdraw = viewport_height * 0.75;
4447        let visible_top = (offset_y - overdraw).max(0.0);
4448        let visible_bottom = offset_y + viewport_height + overdraw;
4449        let child_count = self.children.len();
4450        let mut start = 0;
4451        while start < child_count {
4452            let row_top = self.item_offsets[start];
4453            let row_bottom = row_top + self.children.as_slice()[start].measured_size().height;
4454            if row_bottom >= visible_top {
4455                break;
4456            }
4457            start += 1;
4458        }
4459
4460        let mut end = start;
4461        while end < child_count {
4462            if self.item_offsets[end] > visible_bottom {
4463                break;
4464            }
4465            end += 1;
4466        }
4467
4468        start..end
4469    }
4470
4471    fn exposed_viewport_strip(&self, viewport: Rect, previous_offset_y: f32) -> Option<Rect> {
4472        let delta_y = self.offset_y - previous_offset_y;
4473        if delta_y.abs() <= f32::EPSILON || viewport.is_empty() {
4474            return None;
4475        }
4476
4477        let strip_height = delta_y.abs().min(viewport.height());
4478        if strip_height <= 0.0 {
4479            return None;
4480        }
4481
4482        if delta_y > 0.0 {
4483            Some(Rect::new(
4484                viewport.x(),
4485                viewport.max_y() - strip_height,
4486                viewport.width(),
4487                strip_height,
4488            ))
4489        } else {
4490            Some(Rect::new(
4491                viewport.x(),
4492                viewport.y(),
4493                viewport.width(),
4494                strip_height,
4495            ))
4496        }
4497    }
4498
4499    fn scroll_by(&mut self, viewport: Rect, delta_y: f32, ctx: &mut EventCtx) -> bool {
4500        let previous_offset_y = self.offset_y;
4501        let next = self.clamp_offset(viewport.height(), previous_offset_y + delta_y);
4502        if (next - previous_offset_y).abs() > f32::EPSILON {
4503            self.offset_y = next;
4504            self.publish_state(ctx, viewport.size);
4505            ctx.request_arrange();
4506            if let Some(exposed_strip) = self.exposed_viewport_strip(viewport, previous_offset_y) {
4507                ctx.request_paint_rect(exposed_strip);
4508            }
4509            for child in self.visible_children() {
4510                ctx.request(InvalidationRequest::new(
4511                    InvalidationTarget::Widget(child.id()),
4512                    InvalidationKind::Transform,
4513                ));
4514            }
4515            ctx.request_semantics();
4516            ctx.refresh_drag_targets();
4517            self.offset_change
4518                .notify(ctx, Vector::new(0.0, self.offset_y));
4519            true
4520        } else {
4521            false
4522        }
4523    }
4524
4525    fn sync_state<C>(&mut self, ctx: &mut C, viewport: Size)
4526    where
4527        C: ScrollInvalidationCtx + ScrollWidgetCtx,
4528    {
4529        let state = &self.state;
4530
4531        state.bind_scroll_view(ctx.widget_id(), ctx.widget_id());
4532        state.sync_virtual_item_offsets(&self.item_offsets);
4533        let content_size = Size::new(viewport.width, self.content_height);
4534        let mut state_changed = state.sync_metrics(ScrollAxes::Vertical, viewport, content_size);
4535        if let Some(index) = state.take_pending_virtual_item()
4536            && let Some(item_offset) = self.item_offsets.get(index).copied()
4537        {
4538            let target_offset = self.clamp_offset(viewport.height, item_offset);
4539            state_changed |= state.set_offset(Vector::new(0.0, target_offset));
4540        }
4541        self.offset_y = self.clamp_offset(viewport.height, state.current_offset().y);
4542        state_changed |= state.set_offset(Vector::new(0.0, self.offset_y));
4543        if state_changed {
4544            for scroll_bar_id in state.subscribers().scroll_bar_ids {
4545                request_scroll_bar_refresh(ctx, scroll_bar_id);
4546            }
4547        }
4548        self.offset_change
4549            .defer(ctx, Vector::new(0.0, self.offset_y));
4550    }
4551
4552    fn publish_state(&self, ctx: &mut EventCtx, viewport: Size) {
4553        let state = &self.state;
4554
4555        state.bind_scroll_view(ctx.widget_id(), ctx.widget_id());
4556        let content_size = Size::new(viewport.width, self.content_height);
4557        let _ = state.sync_metrics(ScrollAxes::Vertical, viewport, content_size);
4558        if state.set_offset(Vector::new(0.0, self.offset_y)) {
4559            for scroll_bar_id in state.subscribers().scroll_bar_ids {
4560                if scroll_bar_id != ctx.widget_id() {
4561                    request_scroll_bar_refresh(ctx, scroll_bar_id);
4562                }
4563            }
4564        }
4565    }
4566
4567    fn update_visible_range(&mut self, viewport_height: f32) {
4568        // Extend the visible window by a buffer zone so small scrolls keep a
4569        // stable widget set and avoid unnecessary repaint churn.
4570        self.visible_range = self.visible_range_for_offset(viewport_height, self.offset_y);
4571    }
4572
4573    fn visible_children(&self) -> &[WidgetPod] {
4574        &self.children.as_slice()[self.visible_range.clone()]
4575    }
4576
4577    fn pending_visible_range(&self) -> Option<Range<usize>> {
4578        let index = self.state.pending_virtual_item()?;
4579        let offset_y = self.item_offsets.get(index).copied()?;
4580        Some(self.visible_range_for_offset(self.state.viewport_size().height, offset_y))
4581    }
4582}
4583
4584impl Default for VirtualScrollView {
4585    fn default() -> Self {
4586        Self::new()
4587    }
4588}
4589
4590impl Widget for ScrollView {
4591    fn supports_output_reuse(&self) -> bool {
4592        self.theme_reader.is_none()
4593    }
4594    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
4595        self.sync_scroll_bar_theme();
4596        let viewport = self.viewport_rect(ctx.bounds()).size;
4597        if let Event::Pointer(pointer) = event {
4598            self.handle_touch_pointer(ctx, pointer, viewport);
4599        }
4600        if matches!(event, Event::Wake(WakeEvent::AnimationFrame { .. })) {
4601            self.offset_change.notify(ctx, self.offset);
4602        }
4603
4604        match event {
4605            Event::Pointer(pointer)
4606                if pointer.kind == sui_core::PointerEventKind::Scroll
4607                    && ctx.phase() != EventPhase::Capture
4608                    && ctx.bounds().contains(pointer.position) =>
4609            {
4610                let delta = pointer
4611                    .scroll_delta
4612                    .map(scroll_delta_to_offset)
4613                    .unwrap_or(pointer.delta);
4614                self.touch_fling.stop();
4615                if self.scroll_by(viewport, Vector::new(-delta.x, -delta.y), ctx) {
4616                    ctx.set_handled();
4617                }
4618            }
4619            Event::Drag(drag) if ctx.phase() != EventPhase::Capture => {
4620                let axes = (
4621                    self.overflow_x.is_scrollable(),
4622                    self.overflow_y.is_scrollable(),
4623                );
4624                let visible = self.viewport_rect(ctx.bounds());
4625                self.drag_auto_scroll.follow(ctx, drag, visible, axes);
4626            }
4627            Event::Wake(WakeEvent::AnimationFrame { delta, .. })
4628                if self.drag_auto_scroll.is_scrolling() =>
4629            {
4630                let step = self.drag_auto_scroll.step(*delta);
4631                // The first frame of a run has no time behind it yet.
4632                if step == Vector::ZERO || self.scroll_by(viewport, step, ctx) {
4633                    ctx.request_animation_frame();
4634                } else {
4635                    self.drag_auto_scroll.stop();
4636                }
4637            }
4638            Event::Wake(WakeEvent::AnimationFrame { delta, .. })
4639                if self.touch_fling.is_active() =>
4640            {
4641                let step = self.touch_fling.step(*delta);
4642                let before = self.offset;
4643                self.scroll_by(viewport, step, ctx);
4644                self.touch_fling.block(step, self.offset - before);
4645                if self.touch_fling.is_active() {
4646                    ctx.request_animation_frame();
4647                }
4648            }
4649            Event::Keyboard(key)
4650                if ctx.phase() != EventPhase::Capture
4651                    && ctx.is_focused()
4652                    && key.state == sui_core::KeyState::Pressed =>
4653            {
4654                self.touch_fling.stop();
4655                let line = 40.0;
4656                let page = (viewport.height * 0.85).max(line);
4657                let delta = match key.key.as_str() {
4658                    "ArrowUp" => Some(Vector::new(0.0, -line)),
4659                    "ArrowDown" => Some(Vector::new(0.0, line)),
4660                    "ArrowLeft" => Some(Vector::new(-line, 0.0)),
4661                    "ArrowRight" => Some(Vector::new(line, 0.0)),
4662                    "PageUp" => Some(Vector::new(0.0, -page)),
4663                    "PageDown" => Some(Vector::new(0.0, page)),
4664                    "Home" => Some(Vector::new(-self.offset.x, -self.offset.y)),
4665                    "End" => Some(Vector::new(
4666                        self.content_size.width - viewport.width - self.offset.x,
4667                        self.content_size.height - viewport.height - self.offset.y,
4668                    )),
4669                    _ => None,
4670                };
4671
4672                if let Some(delta) = delta
4673                    && self.scroll_by(viewport, delta, ctx)
4674                {
4675                    ctx.set_handled();
4676                }
4677            }
4678            Event::Pointer(pointer)
4679                if pointer.kind == sui_core::PointerEventKind::Down
4680                    && ctx.phase() != EventPhase::Capture
4681                    && ctx.bounds().contains(pointer.position) =>
4682            {
4683                ctx.request_focus();
4684            }
4685            _ => {}
4686        }
4687    }
4688
4689    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
4690        let theme = self.sync_scroll_bar_theme();
4691        self.ensure_scroll_bars();
4692        let previous_gutter = self.gutter;
4693        self.gutter = Size::ZERO;
4694        let mut outer = constraints.min;
4695        // Start without bars on every measure so shrinking content releases its
4696        // gutter. Remeasure after reserving space so wrapped text uses the real
4697        // viewport width; both axes can need one additional resolution pass.
4698        for _ in 0..3 {
4699            let available = scroll_viewport_size(constraints.max, self.gutter);
4700            let hint = Size::new(
4701                if available.width.is_finite() {
4702                    available.width
4703                } else {
4704                    constraints.min.width
4705                },
4706                if available.height.is_finite() {
4707                    available.height
4708                } else {
4709                    constraints.min.height
4710                },
4711            );
4712            let width_intrinsic = if self.overflow_x.is_scrollable()
4713                && self.content_width == ContentExtent::MinContent
4714            {
4715                self.child
4716                    .child_mut()
4717                    .intrinsic_size(ctx, Axis::Horizontal, hint.height)
4718            } else {
4719                IntrinsicSize::default()
4720            };
4721            let height_intrinsic = if self.overflow_y.is_scrollable()
4722                && self.content_height == ContentExtent::MinContent
4723            {
4724                self.child
4725                    .child_mut()
4726                    .intrinsic_size(ctx, Axis::Vertical, hint.width)
4727            } else {
4728                IntrinsicSize::default()
4729            };
4730            let mut child_constraints = Constraints::new(Size::ZERO, available);
4731            if self.overflow_x.is_scrollable() {
4732                (child_constraints.min.width, child_constraints.max.width) = self
4733                    .content_width
4734                    .resolve(hint.width, width_intrinsic.minimum);
4735            } else if available.width.is_finite() {
4736                child_constraints.min.width = available.width;
4737            }
4738            if self.overflow_y.is_scrollable() {
4739                (child_constraints.min.height, child_constraints.max.height) = self
4740                    .content_height
4741                    .resolve(hint.height, height_intrinsic.minimum);
4742            } else if available.height.is_finite() {
4743                child_constraints.min.height = available.height;
4744            }
4745            self.content_size = self.child.measure(ctx, child_constraints);
4746            outer = constraints.clamp(Size::new(
4747                if constraints.max.width.is_finite() {
4748                    constraints.max.width
4749                } else {
4750                    self.content_size.width + self.gutter.width
4751                },
4752                if self.shrink_height || !constraints.max.height.is_finite() {
4753                    self.content_size.height + self.gutter.height
4754                } else {
4755                    constraints.max.height
4756                },
4757            ));
4758            let next = scroll_bar_gutter(
4759                self.scroll_bars,
4760                self.scroll_axes(),
4761                outer,
4762                self.content_size,
4763                theme.metrics.scroll_bar_thickness,
4764            );
4765            if next == self.gutter {
4766                break;
4767            }
4768            self.gutter = next;
4769        }
4770        if self.gutter != previous_gutter {
4771            ctx.request_paint();
4772        }
4773        self.sync_state(ctx, scroll_viewport_size(outer, self.gutter));
4774        let axes = self.scroll_axes();
4775        let max_offset = self.state.max_offset();
4776        if let Some(bars) = &mut self.bars {
4777            bars.set_visibility(axes, max_offset);
4778            bars.measure(ctx, outer, theme.metrics.scroll_bar_thickness);
4779        }
4780        outer
4781    }
4782
4783    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
4784        let theme = self.sync_scroll_bar_theme();
4785        let previous_offset = self.offset;
4786        self.gutter = scroll_bar_gutter(
4787            self.scroll_bars,
4788            self.scroll_axes(),
4789            bounds.size,
4790            self.content_size,
4791            theme.metrics.scroll_bar_thickness,
4792        );
4793        let viewport = self.viewport_rect(bounds);
4794        self.sync_state(ctx, viewport.size);
4795        // A bound scroll bar writes through shared state. Keep flattened content
4796        // dirty when redraw handling eagerly consumes this arrange pass.
4797        if self.offset != previous_offset && !self.retain_content {
4798            ctx.request_paint();
4799        }
4800        let measured = self.child.child().measured_size();
4801        let child_size = Size::new(
4802            if self.overflow_x == Overflow::Clip {
4803                viewport.width()
4804            } else {
4805                measured.width
4806            },
4807            if self.overflow_y == Overflow::Clip {
4808                viewport.height()
4809            } else {
4810                measured.height
4811            },
4812        );
4813        self.child.arrange(
4814            ctx,
4815            Rect::from_origin_size(
4816                Point::new(bounds.x() - self.offset.x, bounds.y() - self.offset.y),
4817                child_size,
4818            ),
4819        );
4820        let axes = self.scroll_axes();
4821        let max_offset = self.state.max_offset();
4822        if let Some(bars) = &mut self.bars {
4823            bars.set_visibility(axes, max_offset);
4824            bars.arrange(ctx, bounds, theme.metrics.scroll_bar_thickness);
4825        }
4826    }
4827
4828    fn paint(&self, ctx: &mut PaintCtx) {
4829        self.sync_scroll_bar_theme();
4830        if self.should_clip_paint() {
4831            ctx.push_clip_rect(self.clip_rect(ctx.bounds()));
4832            self.child.paint(ctx);
4833            ctx.pop_clip();
4834        } else {
4835            self.child.paint(ctx);
4836        }
4837        if let Some(bars) = &self.bars {
4838            ctx.push_clip_rect(ctx.bounds());
4839            bars.paint(ctx);
4840            ctx.pop_clip();
4841        }
4842    }
4843
4844    fn layer_options(&self) -> LayerOptions {
4845        LayerOptions {
4846            paint_boundary: PaintBoundaryMode::Explicit,
4847            composition_mode: if self.scroll_axes() == ScrollAxes::None {
4848                LayerCompositionMode::Normal
4849            } else {
4850                LayerCompositionMode::Scroll
4851            },
4852        }
4853    }
4854
4855    fn semantics(&self, ctx: &mut SemanticsCtx) {
4856        let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::ScrollView, ctx.bounds());
4857        node.name = self.name.clone();
4858        node.actions = vec![SemanticsAction::Focus];
4859        node.state.focused = ctx.is_focused();
4860        ctx.push(node);
4861        self.child.semantics(ctx);
4862        if let Some(bars) = &self.bars {
4863            bars.semantics(ctx);
4864        }
4865    }
4866
4867    fn accepts_focus(&self) -> bool {
4868        true
4869    }
4870
4871    fn focus_changed(&mut self, ctx: &mut EventCtx, focused: bool) {
4872        let theme = self.sync_scroll_bar_theme();
4873        set_focus_animation_target(&mut self.focus_animation, focused as u8 as f32, &theme, ctx);
4874        ctx.request_paint();
4875        ctx.request_semantics();
4876    }
4877
4878    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
4879        self.child.visit_children(visitor);
4880        if let Some(bars) = &self.bars {
4881            bars.visit_children(visitor);
4882        }
4883    }
4884
4885    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
4886        self.child.visit_children_mut(visitor);
4887        if let Some(bars) = &mut self.bars {
4888            bars.visit_children_mut(visitor);
4889        }
4890    }
4891}
4892
4893impl Widget for VirtualScrollView {
4894    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
4895        self.sync_scroll_bar_theme();
4896        let viewport = self.viewport_rect(ctx.bounds());
4897        if let Event::Pointer(pointer) = event {
4898            self.handle_touch_pointer(ctx, pointer, viewport);
4899        }
4900        if matches!(event, Event::Wake(WakeEvent::AnimationFrame { .. })) {
4901            self.offset_change
4902                .notify(ctx, Vector::new(0.0, self.offset_y));
4903        }
4904
4905        match event {
4906            Event::Pointer(pointer)
4907                if pointer.kind == sui_core::PointerEventKind::Scroll
4908                    && ctx.phase() != EventPhase::Capture
4909                    && ctx.bounds().contains(pointer.position) =>
4910            {
4911                let delta = pointer
4912                    .scroll_delta
4913                    .map(scroll_delta_to_offset)
4914                    .unwrap_or(pointer.delta);
4915                self.touch_fling.stop();
4916                if self.scroll_by(viewport, -delta.y, ctx) {
4917                    ctx.set_handled();
4918                }
4919            }
4920            Event::Drag(drag) if ctx.phase() != EventPhase::Capture => {
4921                self.drag_auto_scroll
4922                    .follow(ctx, drag, viewport, (false, true));
4923            }
4924            Event::Wake(WakeEvent::AnimationFrame { delta, .. })
4925                if self.drag_auto_scroll.is_scrolling() =>
4926            {
4927                let step = self.drag_auto_scroll.step(*delta).y;
4928                if step == 0.0 || self.scroll_by(viewport, step, ctx) {
4929                    ctx.request_animation_frame();
4930                } else {
4931                    self.drag_auto_scroll.stop();
4932                }
4933            }
4934            Event::Wake(WakeEvent::AnimationFrame { delta, .. })
4935                if self.touch_fling.is_active() =>
4936            {
4937                let step = self.touch_fling.step(*delta);
4938                let before = self.offset_y;
4939                self.scroll_by(viewport, step.y, ctx);
4940                self.touch_fling
4941                    .block(step, Vector::new(0.0, self.offset_y - before));
4942                if self.touch_fling.is_active() {
4943                    ctx.request_animation_frame();
4944                }
4945            }
4946            Event::Keyboard(key)
4947                if ctx.phase() != EventPhase::Capture
4948                    && ctx.is_focused()
4949                    && key.state == sui_core::KeyState::Pressed =>
4950            {
4951                self.touch_fling.stop();
4952                let line = 40.0;
4953                let page = (viewport.height() * 0.85).max(line);
4954                let delta = match key.key.as_str() {
4955                    "ArrowUp" => Some(-line),
4956                    "ArrowDown" => Some(line),
4957                    "PageUp" => Some(-page),
4958                    "PageDown" => Some(page),
4959                    "Home" => Some(-self.offset_y),
4960                    "End" => Some(self.content_height - viewport.height() - self.offset_y),
4961                    _ => None,
4962                };
4963
4964                if let Some(delta) = delta
4965                    && self.scroll_by(viewport, delta, ctx)
4966                {
4967                    ctx.set_handled();
4968                }
4969            }
4970            Event::Pointer(pointer)
4971                if pointer.kind == sui_core::PointerEventKind::Down
4972                    && ctx.phase() != EventPhase::Capture
4973                    && ctx.bounds().contains(pointer.position) =>
4974            {
4975                ctx.request_focus();
4976            }
4977            _ => {}
4978        }
4979    }
4980
4981    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
4982        let theme = self.sync_scroll_bar_theme();
4983        self.ensure_scroll_bars();
4984        let previous_content_height = self.content_height;
4985        let previous_item_offsets = std::mem::take(&mut self.item_offsets);
4986        let previous_visible_range = self.visible_range.clone();
4987        let mut gutter = 0.0;
4988        let mut size = constraints.min;
4989        for _ in 0..3 {
4990            let available_width = if constraints.max.width.is_finite() {
4991                (constraints.max.width - self.padding.left - self.padding.right - gutter).max(0.0)
4992            } else {
4993                f32::INFINITY
4994            };
4995            let child_constraints = Constraints::new(
4996                Size::new(
4997                    if available_width.is_finite() {
4998                        available_width
4999                    } else {
5000                        0.0
5001                    },
5002                    0.0,
5003                ),
5004                Size::new(available_width, f32::INFINITY),
5005            );
5006            self.item_offsets.clear();
5007            self.item_offsets.reserve(self.children.len());
5008            let mut content_width: f32 = 0.0;
5009            let mut content_height = 0.0;
5010            for child in self.children.as_mut_slice() {
5011                let child_size = child.measure(ctx, child_constraints);
5012                self.item_offsets.push(content_height);
5013                content_width = content_width.max(child_size.width);
5014                content_height += child_size.height + self.spacing;
5015            }
5016            if !self.item_offsets.is_empty() {
5017                content_height -= self.spacing;
5018            }
5019            self.content_height = content_height;
5020            size = constraints.clamp(Size::new(
5021                if constraints.max.width.is_finite() {
5022                    constraints.max.width
5023                } else {
5024                    content_width + self.padding.left + self.padding.right + gutter
5025                },
5026                if constraints.max.height.is_finite() {
5027                    constraints.max.height
5028                } else {
5029                    content_height + self.padding.top + self.padding.bottom
5030                },
5031            ));
5032            let inner = inset_rect(Rect::from_origin_size(Point::ZERO, size), self.padding);
5033            let next = scroll_bar_gutter(
5034                self.scroll_bars,
5035                ScrollAxes::Vertical,
5036                inner.size,
5037                Size::new(0.0, self.content_height),
5038                theme.metrics.scroll_bar_thickness,
5039            )
5040            .width;
5041            if next == gutter {
5042                break;
5043            }
5044            gutter = next;
5045        }
5046        let viewport = self.viewport_rect(Rect::from_origin_size(Point::ZERO, size));
5047        self.sync_state(ctx, viewport.size);
5048        self.update_visible_range(viewport.height());
5049        let max_offset = self.state.max_offset();
5050        if let Some(bars) = &mut self.bars {
5051            bars.set_visibility(ScrollAxes::Vertical, max_offset);
5052            bars.measure(ctx, size, theme.metrics.scroll_bar_thickness);
5053        }
5054        if previous_content_height != self.content_height
5055            || previous_item_offsets != self.item_offsets
5056            || previous_visible_range != self.visible_range
5057        {
5058            ctx.request_paint();
5059        }
5060        size
5061    }
5062
5063    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
5064        let theme = self.sync_scroll_bar_theme();
5065        let viewport = self.viewport_rect(bounds);
5066        let previous_offset_y = self.offset_y;
5067        self.sync_state(ctx, viewport.size);
5068        // Shared-state movement changes both row positions and the visible window.
5069        if (self.offset_y - previous_offset_y).abs() > f32::EPSILON {
5070            ctx.request_paint();
5071        }
5072        let previous_visible_range = self.visible_range.clone();
5073        let previous_arranged_offset_y = self.last_arranged_offset_y;
5074        self.update_visible_range(viewport.height());
5075        if self.visible_range != previous_visible_range
5076            && (self.offset_y - previous_arranged_offset_y).abs() <= f32::EPSILON
5077        {
5078            ctx.request_paint();
5079        }
5080        self.last_arranged_offset_y = self.offset_y;
5081        let viewport_width = viewport.width();
5082        let visible_range = self.visible_range.clone();
5083        let offset_y = self.offset_y;
5084        let item_offsets = self.item_offsets[visible_range.clone()].to_vec();
5085        for (relative_index, child) in self.children.as_mut_slice()[visible_range]
5086            .iter_mut()
5087            .enumerate()
5088        {
5089            let child_size = child.measured_size();
5090            child.arrange(
5091                ctx,
5092                Rect::from_origin_size(
5093                    Point::new(
5094                        viewport.x(),
5095                        viewport.y() + item_offsets[relative_index] - offset_y,
5096                    ),
5097                    Size::new(
5098                        if viewport_width.is_finite() {
5099                            viewport_width
5100                        } else {
5101                            child_size.width
5102                        },
5103                        child_size.height,
5104                    ),
5105                ),
5106            );
5107        }
5108        let max_offset = self.state.max_offset();
5109        if let Some(bars) = &mut self.bars {
5110            bars.set_visibility(ScrollAxes::Vertical, max_offset);
5111            bars.arrange(ctx, bounds, theme.metrics.scroll_bar_thickness);
5112        }
5113    }
5114
5115    fn paint(&self, ctx: &mut PaintCtx) {
5116        self.sync_scroll_bar_theme();
5117        let viewport = self.viewport_rect(ctx.bounds());
5118        ctx.push_clip_rect(viewport);
5119        for child in self.visible_children() {
5120            child.paint(ctx);
5121        }
5122        ctx.pop_clip();
5123        if let Some(bars) = &self.bars {
5124            ctx.push_clip_rect(ctx.bounds());
5125            bars.paint(ctx);
5126            ctx.pop_clip();
5127        }
5128    }
5129
5130    fn layer_options(&self) -> LayerOptions {
5131        LayerOptions {
5132            paint_boundary: PaintBoundaryMode::Explicit,
5133            composition_mode: LayerCompositionMode::Scroll,
5134        }
5135    }
5136
5137    fn semantics(&self, ctx: &mut SemanticsCtx) {
5138        let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::ScrollView, ctx.bounds());
5139        node.name = self.name.clone();
5140        node.actions = vec![SemanticsAction::Focus];
5141        node.state.focused = ctx.is_focused();
5142        ctx.push(node);
5143        for child in self.visible_children() {
5144            child.semantics(ctx);
5145        }
5146        if let Some(bars) = &self.bars {
5147            bars.semantics(ctx);
5148        }
5149    }
5150
5151    fn accepts_focus(&self) -> bool {
5152        true
5153    }
5154
5155    fn focus_changed(&mut self, ctx: &mut EventCtx, focused: bool) {
5156        let theme = self.sync_scroll_bar_theme();
5157        set_focus_animation_target(&mut self.focus_animation, focused as u8 as f32, &theme, ctx);
5158        ctx.request_paint();
5159        ctx.request_semantics();
5160    }
5161
5162    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
5163        let pending_range = self.pending_visible_range();
5164        for (index, child) in self.children.as_slice().iter().enumerate() {
5165            if self.visible_range.contains(&index)
5166                || pending_range
5167                    .as_ref()
5168                    .is_some_and(|range| range.contains(&index))
5169            {
5170                visitor.visit(child);
5171            }
5172        }
5173        if let Some(bars) = &self.bars {
5174            bars.visit_children(visitor);
5175        }
5176    }
5177
5178    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
5179        let visible_range = self.visible_range.clone();
5180        let pending_range = self.pending_visible_range();
5181        for (index, child) in self.children.as_mut_slice().iter_mut().enumerate() {
5182            if visible_range.contains(&index)
5183                || pending_range
5184                    .as_ref()
5185                    .is_some_and(|range| range.contains(&index))
5186            {
5187                visitor.visit(child);
5188            }
5189        }
5190        if let Some(bars) = &mut self.bars {
5191            bars.visit_children_mut(visitor);
5192        }
5193    }
5194}
5195
5196fn scroll_delta_to_offset(delta: ScrollDelta) -> Vector {
5197    match delta {
5198        ScrollDelta::Lines(delta) => Vector::new(delta.x * 40.0, delta.y * 40.0),
5199        ScrollDelta::Pixels(delta) => delta,
5200    }
5201}
5202
5203fn axis_limited_offset(axes: ScrollAxes, offset: Vector) -> Vector {
5204    Vector::new(
5205        if axes.allows_horizontal() {
5206            offset.x.max(0.0)
5207        } else {
5208            0.0
5209        },
5210        if axes.allows_vertical() {
5211            offset.y.max(0.0)
5212        } else {
5213            0.0
5214        },
5215    )
5216}
5217
5218fn shared_max_offset(viewport: Size, content_size: Size) -> Vector {
5219    Vector::new(
5220        (content_size.width - viewport.width).max(0.0),
5221        (content_size.height - viewport.height).max(0.0),
5222    )
5223}
5224
5225fn clamp_shared_offset(
5226    axes: ScrollAxes,
5227    viewport: Size,
5228    content_size: Size,
5229    offset: Vector,
5230) -> Vector {
5231    let max = shared_max_offset(viewport, content_size);
5232    Vector::new(
5233        if axes.allows_horizontal() {
5234            offset.x.clamp(0.0, max.x)
5235        } else {
5236            0.0
5237        },
5238        if axes.allows_vertical() {
5239            offset.y.clamp(0.0, max.y)
5240        } else {
5241            0.0
5242        },
5243    )
5244}
5245
5246pub(crate) trait ScrollInvalidationCtx {
5247    fn push_invalidation(&mut self, request: InvalidationRequest);
5248    fn request_animation_frame(&mut self);
5249}
5250
5251pub(crate) trait ScrollWidgetCtx {
5252    fn widget_id(&self) -> WidgetId;
5253}
5254
5255impl ScrollInvalidationCtx for EventCtx {
5256    fn push_invalidation(&mut self, request: InvalidationRequest) {
5257        self.request(request);
5258    }
5259
5260    fn request_animation_frame(&mut self) {
5261        EventCtx::request_animation_frame(self);
5262    }
5263}
5264
5265impl ScrollInvalidationCtx for MeasureCtx {
5266    fn push_invalidation(&mut self, request: InvalidationRequest) {
5267        self.request(request);
5268    }
5269
5270    fn request_animation_frame(&mut self) {
5271        MeasureCtx::request_animation_frame(self);
5272    }
5273}
5274
5275impl ScrollInvalidationCtx for ArrangeCtx {
5276    fn push_invalidation(&mut self, request: InvalidationRequest) {
5277        self.request(request);
5278    }
5279
5280    fn request_animation_frame(&mut self) {
5281        ArrangeCtx::request_animation_frame(self);
5282    }
5283}
5284
5285impl ScrollWidgetCtx for EventCtx {
5286    fn widget_id(&self) -> WidgetId {
5287        self.widget_id()
5288    }
5289}
5290
5291impl ScrollWidgetCtx for MeasureCtx {
5292    fn widget_id(&self) -> WidgetId {
5293        self.widget_id()
5294    }
5295}
5296
5297impl ScrollWidgetCtx for ArrangeCtx {
5298    fn widget_id(&self) -> WidgetId {
5299        self.widget_id()
5300    }
5301}
5302
5303pub(crate) fn request_scroll_bar_refresh<C>(ctx: &mut C, widget_id: WidgetId)
5304where
5305    C: ScrollInvalidationCtx,
5306{
5307    for kind in [
5308        InvalidationKind::Paint,
5309        InvalidationKind::HitTest,
5310        InvalidationKind::Semantics,
5311    ] {
5312        ctx.push_invalidation(InvalidationRequest::new(
5313            InvalidationTarget::Widget(widget_id),
5314            kind,
5315        ));
5316    }
5317}
5318
5319fn request_scroll_view_refresh<C>(ctx: &mut C, widget_id: WidgetId, content_id: Option<WidgetId>)
5320where
5321    C: ScrollInvalidationCtx,
5322{
5323    for kind in [InvalidationKind::Arrange, InvalidationKind::Semantics] {
5324        ctx.push_invalidation(InvalidationRequest::new(
5325            InvalidationTarget::Widget(widget_id),
5326            kind,
5327        ));
5328    }
5329    if let Some(content_id) = content_id {
5330        ctx.push_invalidation(InvalidationRequest::new(
5331            InvalidationTarget::Widget(content_id),
5332            InvalidationKind::Transform,
5333        ));
5334    }
5335}
5336
5337fn inset_constraints(constraints: Constraints, insets: Insets) -> Constraints {
5338    let horizontal = insets.left + insets.right;
5339    let vertical = insets.top + insets.bottom;
5340
5341    Constraints::new(
5342        Size::new(
5343            (constraints.min.width - horizontal).max(0.0),
5344            (constraints.min.height - vertical).max(0.0),
5345        ),
5346        Size::new(
5347            (constraints.max.width - horizontal).max(0.0),
5348            (constraints.max.height - vertical).max(0.0),
5349        ),
5350    )
5351}
5352
5353fn expand_size(size: Size, insets: Insets) -> Size {
5354    Size::new(
5355        size.width + insets.left + insets.right,
5356        size.height + insets.top + insets.bottom,
5357    )
5358}
5359
5360fn aligned_child_constraints(
5361    constraints: Constraints,
5362    horizontal: Alignment,
5363    vertical: Alignment,
5364) -> Constraints {
5365    Constraints::new(
5366        Size::new(
5367            if horizontal == Alignment::Stretch && constraints.max.width.is_finite() {
5368                constraints.max.width
5369            } else {
5370                0.0
5371            },
5372            if vertical == Alignment::Stretch && constraints.max.height.is_finite() {
5373                constraints.max.height
5374            } else {
5375                0.0
5376            },
5377        ),
5378        constraints.max,
5379    )
5380}
5381
5382fn stretched_dimension(alignment: Alignment, max: f32, fallback: f32) -> f32 {
5383    if alignment == Alignment::Stretch && max.is_finite() {
5384        max
5385    } else {
5386        fallback
5387    }
5388}
5389
5390fn aligned_offset(alignment: Alignment, remaining: f32) -> f32 {
5391    let remaining = remaining.max(0.0);
5392    match alignment {
5393        Alignment::Start | Alignment::Stretch => 0.0,
5394        Alignment::Center => remaining * 0.5,
5395        Alignment::End => remaining,
5396    }
5397}
5398
5399fn sized_box_constraints(
5400    constraints: Constraints,
5401    width: Option<f32>,
5402    height: Option<f32>,
5403) -> Constraints {
5404    Constraints::new(
5405        Size::new(width.unwrap_or(0.0), height.unwrap_or(0.0)),
5406        Size::new(
5407            width.unwrap_or(constraints.max.width),
5408            height.unwrap_or(constraints.max.height),
5409        ),
5410    )
5411}
5412
5413fn axis_main(axis: Axis, size: Size) -> f32 {
5414    match axis {
5415        Axis::Horizontal => size.width,
5416        Axis::Vertical => size.height,
5417    }
5418}
5419
5420fn axis_cross(axis: Axis, size: Size) -> f32 {
5421    match axis {
5422        Axis::Horizontal => size.height,
5423        Axis::Vertical => size.width,
5424    }
5425}
5426
5427fn axis_size(axis: Axis, main: f32, cross: f32) -> Size {
5428    match axis {
5429        Axis::Horizontal => Size::new(main, cross),
5430        Axis::Vertical => Size::new(cross, main),
5431    }
5432}
5433
5434fn stack_arranged_child_size(
5435    axis: Axis,
5436    alignment: Alignment,
5437    measured: Size,
5438    cross_available: f32,
5439) -> Size {
5440    let main = axis_main(axis, measured);
5441    let measured_cross = axis_cross(axis, measured);
5442    let cross = if alignment == Alignment::Stretch {
5443        cross_available
5444    } else {
5445        measured_cross.min(cross_available)
5446    };
5447    axis_size(axis, main, cross)
5448}
5449
5450fn axis_point(axis: Axis, main: f32, cross: f32) -> Point {
5451    match axis {
5452        Axis::Horizontal => Point::new(main, cross),
5453        Axis::Vertical => Point::new(cross, main),
5454    }
5455}
5456
5457fn stack_child_constraints(
5458    axis: Axis,
5459    remaining_main: f32,
5460    max_cross: f32,
5461    stretch_cross: bool,
5462) -> Constraints {
5463    let min_cross = if stretch_cross { max_cross } else { 0.0 };
5464
5465    match axis {
5466        Axis::Horizontal => Constraints::new(
5467            Size::new(0.0, min_cross),
5468            Size::new(remaining_main, max_cross),
5469        ),
5470        Axis::Vertical => Constraints::new(
5471            Size::new(min_cross, 0.0),
5472            Size::new(max_cross, remaining_main),
5473        ),
5474    }
5475}
5476
5477#[cfg(test)]
5478mod tests {
5479    use std::{
5480        cell::{Cell, RefCell},
5481        rc::Rc,
5482    };
5483
5484    use super::{
5485        Align, Background, ContentExtent, Dock, FixedPaneSplit, Flex, MeasuredBottomDock, Overflow,
5486        Padding, RebuildOnChange, RebuildOnConstraints, ScrollAxes, ScrollBar, ScrollState,
5487        ScrollView, SemanticRegion, SizedBox, Stack, SwitchView, TrailingSlotRow,
5488        VirtualScrollView,
5489    };
5490    use crate::{DefaultTheme, SplitView};
5491    use sui_core::{
5492        Color, Event, InvalidationKind, InvalidationRequest, InvalidationTarget, Point,
5493        PointerButton, PointerButtons, PointerEvent, PointerEventKind, PointerKind, Rect,
5494        ScrollDelta, SemanticsAction, SemanticsActionRequest, SemanticsNode, SemanticsRole,
5495        SemanticsValue, Size, Vector, WidgetId, WindowEvent,
5496    };
5497    use sui_layout::{Alignment, Axis, Constraints, FlexItem, FlexWrap, Padding as Insets};
5498    use sui_reactive::Signal;
5499    use sui_runtime::{
5500        Application, ArrangeCtx, EventCtx, EventPhase, LayerOptions, MeasureCtx, PaintBoundaryMode,
5501        PaintCtx, RenderOutput, Runtime, SemanticsCtx, SingleChild, Widget, WidgetGraphSnapshot,
5502        WidgetNodeSnapshot, WidgetPod, WidgetPodMutVisitor, WidgetPodVisitor, WindowBuilder,
5503    };
5504    use sui_scene::{Brush, LayerCompositionMode, SceneCommand, SceneLayerDescriptor};
5505
5506    #[test]
5507    fn flex_reads_and_replaces_each_childs_flex_item() {
5508        let mut flex = Flex::horizontal()
5509            .with_child(crate::Label::new("Fixed"))
5510            .with_item(crate::Label::new("Fill"), FlexItem::flex(1.0));
5511        assert_eq!(flex.flex_items().len(), 2);
5512        assert_eq!(flex.flex_item(1), Some(FlexItem::flex(1.0)));
5513        assert!(flex.set_flex_item(0, FlexItem::fixed(40.0)));
5514        assert_eq!(flex.flex_item(0), Some(FlexItem::fixed(40.0)));
5515        assert!(!flex.set_flex_item(2, FlexItem::new()));
5516        assert_eq!(flex.flex_item(2), None);
5517    }
5518
5519    #[test]
5520    fn retained_output_matches_full_callbacks_across_text_dpi_and_style_changes() {
5521        use crate::{Button, Grid, Label};
5522        use sui_layout::GridTrack;
5523        use sui_render_wgpu::WgpuRenderer;
5524        struct Gate {
5525            child: SingleChild,
5526            reuse: bool,
5527        }
5528        impl Widget for Gate {
5529            fn supports_output_reuse(&self) -> bool {
5530                self.reuse
5531            }
5532            fn measure(&mut self, c: &mut MeasureCtx, k: Constraints) -> Size {
5533                self.child.measure(c, k)
5534            }
5535            fn arrange(&mut self, c: &mut ArrangeCtx, r: Rect) {
5536                self.child.arrange(c, r);
5537            }
5538            fn paint(&self, c: &mut PaintCtx) {
5539                self.child.paint(c);
5540            }
5541            fn semantics(&self, c: &mut SemanticsCtx) {
5542                self.child.semantics(c);
5543            }
5544            fn visit_children(&self, v: &mut dyn WidgetPodVisitor) {
5545                self.child.visit_children(v);
5546            }
5547            fn visit_children_mut(&mut self, v: &mut dyn WidgetPodMutVisitor) {
5548                self.child.visit_children_mut(v);
5549            }
5550        }
5551        let text = Signal::new("Initial text".to_string());
5552        let mut runtimes = [Runtime::new(), Runtime::new()];
5553        let mut renderers = [WgpuRenderer::new(), WgpuRenderer::new()];
5554        let windows: Vec<_> = runtimes
5555            .iter_mut()
5556            .enumerate()
5557            .map(|(i, runtime)| {
5558                let mut grid =
5559                    Grid::new([GridTrack::Fraction(1.0), GridTrack::Fraction(1.0)]).gap(3.0);
5560                for index in 0..12 {
5561                    let label = if index == 0 {
5562                        Label::new("").text_from(text.clone())
5563                    } else {
5564                        Label::new("Stable text")
5565                    };
5566                    grid.push(
5567                        Stack::horizontal()
5568                            .with_child(label)
5569                            .with_child(Button::new(format!("Button {index}"))),
5570                    );
5571                }
5572                runtime
5573                    .add_window(
5574                        WindowBuilder::new()
5575                            .initial_size(Size::new(640.0, 320.0))
5576                            .root(Gate {
5577                                child: SingleChild::new(grid),
5578                                reuse: i == 0,
5579                            }),
5580                    )
5581                    .unwrap()
5582            })
5583            .collect();
5584        for revision in 0..4 {
5585            text.set(
5586                match revision {
5587                    1 => "A longer line for measurement",
5588                    3 => "Another revision",
5589                    _ => "Short",
5590                }
5591                .to_string(),
5592            );
5593            let mut captures = Vec::new();
5594            let mut semantic_names = Vec::new();
5595            for ((runtime, renderer), window) in
5596                runtimes.iter_mut().zip(&mut renderers).zip(&windows)
5597            {
5598                if revision == 2 {
5599                    runtime
5600                        .handle_event(
5601                            *window,
5602                            Event::Window(sui_core::WindowEvent::ScaleFactorChanged {
5603                                scale_factor: 1.25,
5604                                raw_dpi: None,
5605                                suggested_size: Some(Size::new(640.0, 320.0)),
5606                            }),
5607                        )
5608                        .unwrap();
5609                }
5610                if revision == 3 {
5611                    sui_runtime::set_window_render_options(
5612                        *window,
5613                        sui_runtime::WindowRenderOptions::new(false, 1.0)
5614                            .with_optical_vertical_text_alignment_enabled(false),
5615                    );
5616                }
5617                let output = runtime.render(*window).unwrap();
5618                semantic_names.push(
5619                    output
5620                        .semantics
5621                        .iter()
5622                        .map(|n| n.name.clone())
5623                        .collect::<Vec<_>>(),
5624                );
5625                renderer.render(&output.frame).unwrap();
5626                captures.push(renderer.capture_rgba(*window).unwrap());
5627            }
5628            assert_eq!(semantic_names[0], semantic_names[1]);
5629            assert_eq!(
5630                captures[0].pixels(),
5631                captures[1].pixels(),
5632                "revision {revision}"
5633            );
5634        }
5635    }
5636
5637    #[test]
5638    fn axis_flex_matches_full_probe_geometry_after_text_and_viewport_changes() {
5639        use crate::Label;
5640        use sui_layout::{FlexMeasurePhase, flex_layout, flex_layout_with_probes};
5641        struct ProbeMode {
5642            flex: Flex,
5643            legacy: bool,
5644        }
5645        impl Widget for ProbeMode {
5646            fn measure_axis(&mut self, ctx: &mut MeasureCtx, c: Constraints, axis: Axis) -> f32 {
5647                if !self.legacy {
5648                    return self.flex.measure_axis(ctx, c, axis);
5649                }
5650                let size = self.measure_size(ctx, c);
5651                match axis {
5652                    Axis::Horizontal => size.width,
5653                    Axis::Vertical => size.height,
5654                }
5655            }
5656            fn measure_size(&mut self, ctx: &mut MeasureCtx, c: Constraints) -> Size {
5657                if !self.legacy {
5658                    return self.flex.measure_size(ctx, c);
5659                }
5660                flex_layout(self.flex.style, &self.flex.items, c, |i, c| {
5661                    self.flex.children.as_mut_slice()[i].probe_measure(ctx, c)
5662                })
5663                .size
5664            }
5665            fn measure(&mut self, ctx: &mut MeasureCtx, c: Constraints) -> Size {
5666                if !self.legacy {
5667                    return self.flex.measure(ctx, c);
5668                }
5669                flex_layout_with_probes(self.flex.style, &self.flex.items, c, |i, c, phase| {
5670                    let child = &mut self.flex.children.as_mut_slice()[i];
5671                    match phase {
5672                        FlexMeasurePhase::Probe => child.probe_measure(ctx, c),
5673                        FlexMeasurePhase::Commit => child.measure(ctx, c),
5674                    }
5675                })
5676                .size
5677            }
5678            fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
5679                self.flex.arrange(ctx, bounds);
5680            }
5681            fn visit_children(&self, v: &mut dyn WidgetPodVisitor) {
5682                self.flex.visit_children(v);
5683            }
5684            fn visit_children_mut(&mut self, v: &mut dyn WidgetPodMutVisitor) {
5685                self.flex.visit_children_mut(v);
5686            }
5687        }
5688        fn tree(legacy: bool, depth: usize, text: Signal<String>) -> ProbeMode {
5689            let flex = if depth == 0 {
5690                Flex::vertical()
5691                    .gap(2.0)
5692                    .with_child(Label::new("").text_from(text))
5693                    .with_child(Label::new("A second wrapping label with several words"))
5694            } else {
5695                Flex::horizontal()
5696                    .gap(2.0)
5697                    .with_child(Label::new(format!("Depth {depth}")))
5698                    .with_child(Padding::all(1.0, tree(legacy, depth - 1, text)))
5699            };
5700            ProbeMode { flex, legacy }
5701        }
5702        let text = Signal::new("Wrapping text with variable width".to_string());
5703        let mut runtimes = [Runtime::new(), Runtime::new()];
5704        let windows: Vec<_> = runtimes
5705            .iter_mut()
5706            .enumerate()
5707            .map(|(index, runtime)| {
5708                runtime
5709                    .add_window(
5710                        WindowBuilder::new()
5711                            .initial_size(Size::new(640.0, 320.0))
5712                            .root(tree(index == 0, 5, text.clone())),
5713                    )
5714                    .unwrap()
5715            })
5716            .collect();
5717        for (width, content) in [
5718            (640.0, "Initial contents"),
5719            (347.25, "A much longer revision wrapping at a new width"),
5720            (720.5, "Short"),
5721        ] {
5722            text.set(content.to_string());
5723            let bounds: Vec<Vec<_>> = runtimes
5724                .iter_mut()
5725                .zip(&windows)
5726                .map(|(runtime, window)| {
5727                    runtime
5728                        .handle_event(
5729                            *window,
5730                            Event::Window(sui_core::WindowEvent::Resized(Size::new(width, 320.0))),
5731                        )
5732                        .unwrap();
5733                    runtime.render(*window).unwrap();
5734                    runtime
5735                        .widget_graph(*window)
5736                        .unwrap()
5737                        .nodes
5738                        .iter()
5739                        .map(|n| n.bounds)
5740                        .collect()
5741                })
5742                .collect();
5743            assert_eq!(bounds[0], bounds[1]);
5744        }
5745    }
5746
5747    #[test]
5748    fn projected_flex_queries_match_full_probes_with_wrap_and_cross_dependent_children() {
5749        use std::sync::Arc;
5750        use sui_layout::{FlexStyle, FlexWrap, flex_layout};
5751        struct Responsive(usize);
5752        impl Widget for Responsive {
5753            fn measure_size(&mut self, _: &mut MeasureCtx, c: Constraints) -> Size {
5754                c.clamp(Size::new(
5755                    (45.0 + self.0 as f32 * 7.0).min(c.max.height * 2.0),
5756                    7.0 * (120.0 / c.max.width.max(1.0)).ceil(),
5757                ))
5758            }
5759        }
5760        for axis in [Axis::Horizontal, Axis::Vertical] {
5761            for wrap in [FlexWrap::NoWrap, FlexWrap::Wrap] {
5762                for width in [31.25, 117.5, 480.0] {
5763                    for alignment in [Alignment::Start, Alignment::Stretch] {
5764                        let style = FlexStyle::new(axis)
5765                            .wrap(wrap)
5766                            .gap(3.5)
5767                            .align_items(alignment);
5768                        let items = [
5769                            FlexItem::new(),
5770                            FlexItem::flex(1.0).min_width(8.0).max_height(45.0),
5771                            FlexItem::new().basis_fraction(0.3),
5772                            FlexItem::fixed(23.0),
5773                        ];
5774                        let c = Constraints::new(Size::new(4.0, 9.0), Size::new(width, 180.0));
5775                        let mut ctx = MeasureCtx::with_layout(
5776                            sui_core::WindowId::new(1),
5777                            WidgetId::new(1),
5778                            Rect::ZERO,
5779                            sui_layout::LayoutContext::new(
5780                                sui_core::DpiInfo::default(),
5781                                Arc::new(sui_text::TextSystem::new()),
5782                                Arc::new(sui_text::FontRegistry::new()),
5783                                Arc::new(sui_scene::ImageRegistry::new()),
5784                            ),
5785                        );
5786                        let expected = flex_layout(style, &items, c, |index, c| {
5787                            Responsive(index).measure_size(&mut ctx, c)
5788                        })
5789                        .size;
5790                        let mut flex = Flex::new(axis);
5791                        flex.style = style;
5792                        for (index, item) in items.into_iter().enumerate() {
5793                            flex.push_item(Responsive(index), item);
5794                        }
5795                        assert_eq!(flex.measure_size(&mut ctx, c), expected);
5796                        assert_eq!(
5797                            flex.measure_axis(&mut ctx, c, Axis::Horizontal),
5798                            expected.width
5799                        );
5800                        assert_eq!(
5801                            flex.measure_axis(&mut ctx, c, Axis::Vertical),
5802                            expected.height
5803                        );
5804                    }
5805                }
5806            }
5807        }
5808    }
5809
5810    #[test]
5811    fn nested_flex_probes_commit_leaf_layout_only_after_constraints_are_resolved() {
5812        struct Leaf(Rc<Cell<u32>>, Rc<Cell<f32>>);
5813        impl Widget for Leaf {
5814            fn measure_size(&mut self, _: &mut MeasureCtx, c: Constraints) -> Size {
5815                c.clamp(Size::new(30.0, 12.0))
5816            }
5817            fn measure(&mut self, _: &mut MeasureCtx, c: Constraints) -> Size {
5818                self.0.set(self.0.get() + 1);
5819                self.1.set(c.max.width);
5820                c.clamp(Size::new(30.0, 12.0))
5821            }
5822        }
5823        struct Preview {
5824            child: WidgetPod,
5825            commits: Rc<Cell<u32>>,
5826        }
5827        impl Widget for Preview {
5828            fn measure(&mut self, ctx: &mut MeasureCtx, c: Constraints) -> Size {
5829                let before = self.commits.get();
5830                let provisional = self.child.probe_measure(ctx, c);
5831                assert_eq!(
5832                    self.commits.get(),
5833                    before,
5834                    "provisional Flex traversal committed a leaf"
5835                );
5836                let size = self.child.measure(ctx, c);
5837                assert_eq!(size, provisional);
5838                assert_eq!(
5839                    self.commits.get(),
5840                    before + 1,
5841                    "final traversal should commit the leaf once"
5842                );
5843                size
5844            }
5845            fn arrange(&mut self, ctx: &mut ArrangeCtx, r: Rect) {
5846                self.child.arrange(ctx, r);
5847            }
5848            fn visit_children(&self, v: &mut dyn WidgetPodVisitor) {
5849                v.visit(&self.child);
5850            }
5851            fn visit_children_mut(&mut self, v: &mut dyn WidgetPodMutVisitor) {
5852                v.visit(&mut self.child);
5853            }
5854        }
5855        struct SizeForwarder(WidgetPod);
5856        impl Widget for SizeForwarder {
5857            fn measure_size(&mut self, ctx: &mut MeasureCtx, c: Constraints) -> Size {
5858                self.0.probe_measure(ctx, c)
5859            }
5860            fn measure(&mut self, ctx: &mut MeasureCtx, c: Constraints) -> Size {
5861                self.0.measure(ctx, c)
5862            }
5863            fn arrange(&mut self, ctx: &mut ArrangeCtx, r: Rect) {
5864                self.0.arrange(ctx, r);
5865            }
5866            fn visit_children(&self, v: &mut dyn WidgetPodVisitor) {
5867                v.visit(&self.0);
5868            }
5869            fn visit_children_mut(&mut self, v: &mut dyn WidgetPodMutVisitor) {
5870                v.visit(&mut self.0);
5871            }
5872        }
5873        let commits = Rc::new(Cell::new(0));
5874        let width = Rc::new(Cell::new(0.0));
5875        let mut child = WidgetPod::new(Leaf(commits.clone(), width.clone()));
5876        for _ in 0..6 {
5877            child = WidgetPod::new(
5878                Flex::horizontal().with_child(Padding::all(1.0, SizeForwarder(child))),
5879            );
5880        }
5881        let mut runtime = Runtime::new();
5882        let window = runtime
5883            .add_window(WindowBuilder::new().root(Preview { child, commits }))
5884            .unwrap();
5885        runtime.render(window).unwrap();
5886        assert!(width.get().is_finite() && width.get() > 0.0);
5887    }
5888
5889    struct FixedBox {
5890        size: Size,
5891        color: Color,
5892    }
5893
5894    impl FixedBox {
5895        fn new(size: Size, color: Color) -> Self {
5896            Self { size, color }
5897        }
5898    }
5899
5900    impl Widget for FixedBox {
5901        fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
5902            constraints.clamp(self.size)
5903        }
5904
5905        fn paint(&self, ctx: &mut PaintCtx) {
5906            ctx.fill_bounds(self.color);
5907        }
5908
5909        fn semantics(&self, ctx: &mut SemanticsCtx) {
5910            ctx.push(SemanticsNode::new(
5911                ctx.widget_id(),
5912                SemanticsRole::GenericContainer,
5913                ctx.bounds(),
5914            ));
5915        }
5916    }
5917
5918    #[test]
5919    fn rebuild_on_change_rebuilds_child_only_when_key_changes() {
5920        let key = Rc::new(Cell::new(1usize));
5921        let builds = Rc::new(RefCell::new(Vec::new()));
5922        let key_reader = Rc::clone(&key);
5923        let build_log = Rc::clone(&builds);
5924
5925        let mut host = RebuildOnChange::key_when(
5926            move || key_reader.get(),
5927            move |value| {
5928                build_log.borrow_mut().push(*value);
5929                WidgetPod::new(FixedBox::new(
5930                    Size::new(*value as f32, 10.0),
5931                    Color::srgba(0.0, 0.0, 0.0, 1.0),
5932                ))
5933            },
5934        );
5935
5936        assert_eq!(*builds.borrow(), vec![1]);
5937        assert!(!host.refresh());
5938        assert_eq!(*builds.borrow(), vec![1]);
5939
5940        key.set(2);
5941        assert!(host.refresh());
5942        assert_eq!(*builds.borrow(), vec![1, 2]);
5943    }
5944
5945    #[test]
5946    fn rebuild_on_change_reports_structural_reason() -> sui_core::Result<()> {
5947        let key = Rc::new(Cell::new(1usize));
5948        let key_reader = Rc::clone(&key);
5949        let (mut runtime, window_id) = build_runtime(RebuildOnChange::key_when(
5950            move || key_reader.get(),
5951            |value| {
5952                WidgetPod::new(FixedBox::new(
5953                    Size::new(*value as f32 * 20.0, 20.0),
5954                    Color::BLACK,
5955                ))
5956            },
5957        ));
5958
5959        runtime.render(window_id)?;
5960        key.set(2);
5961        runtime.handle_event(window_id, Event::Window(WindowEvent::RedrawRequested))?;
5962        let output = runtime.render(window_id)?;
5963
5964        assert!(output.diagnostics.widget_rebuilds.iter().any(|sample| {
5965            sample
5966                .reason
5967                .contains("caller-supplied structural key changed")
5968        }));
5969        Ok(())
5970    }
5971
5972    #[test]
5973    fn rebuild_on_change_observable_rebuilds_without_redraw_polling() -> sui_core::Result<()> {
5974        let key = Signal::named("structural_mode", 1usize);
5975        let (mut runtime, window_id) =
5976            build_runtime(RebuildOnChange::key_from(key.clone(), |value| {
5977                WidgetPod::new(FixedBox::new(
5978                    Size::new(*value as f32 * 20.0, 20.0),
5979                    Color::BLACK,
5980                ))
5981            }));
5982
5983        let output = runtime.render(window_id)?;
5984        assert_eq!(output.frame.viewport, Size::new(20.0, 20.0));
5985
5986        assert!(key.set(2));
5987        let output = runtime.render(window_id)?;
5988        assert_eq!(output.frame.viewport, Size::new(40.0, 20.0));
5989        assert!(
5990            output
5991                .diagnostics
5992                .widget_rebuilds
5993                .iter()
5994                .any(|sample| { sample.reason.contains("observable structural key changed") })
5995        );
5996        Ok(())
5997    }
5998
5999    #[test]
6000    fn rebuild_on_constraints_rebuilds_child_when_breakpoint_changes() {
6001        let builds = Rc::new(RefCell::new(Vec::new()));
6002        let build_log = Rc::clone(&builds);
6003        let mut host = RebuildOnConstraints::new(
6004            false,
6005            |constraints| constraints.max.width >= 420.0,
6006            move |wide| {
6007                build_log.borrow_mut().push(*wide);
6008                let width = if *wide { 24.0 } else { 12.0 };
6009                WidgetPod::new(FixedBox::new(
6010                    Size::new(width, 10.0),
6011                    Color::srgba(0.0, 0.0, 0.0, 1.0),
6012                ))
6013            },
6014        );
6015
6016        assert_eq!(*builds.borrow(), vec![false]);
6017        let constraints = Constraints::tight(Size::new(520.0, 80.0));
6018        assert!(host.refresh_for_constraints(constraints));
6019        assert_eq!(*builds.borrow(), vec![false, true]);
6020
6021        let constraints = Constraints::tight(Size::new(560.0, 80.0));
6022        assert!(!host.refresh_for_constraints(constraints));
6023        assert_eq!(*builds.borrow(), vec![false, true]);
6024    }
6025
6026    struct OverflowingBox {
6027        size: Size,
6028        color: Color,
6029    }
6030
6031    impl OverflowingBox {
6032        fn new(size: Size, color: Color) -> Self {
6033            Self { size, color }
6034        }
6035    }
6036
6037    impl Widget for OverflowingBox {
6038        fn measure(&mut self, _ctx: &mut MeasureCtx, _constraints: Constraints) -> Size {
6039            self.size
6040        }
6041
6042        fn paint(&self, ctx: &mut PaintCtx) {
6043            ctx.fill_bounds(self.color);
6044        }
6045    }
6046
6047    struct PaintCounterBox {
6048        size: Size,
6049        color: Color,
6050        counts: Rc<RefCell<Vec<usize>>>,
6051        index: usize,
6052    }
6053
6054    impl PaintCounterBox {
6055        fn new(size: Size, color: Color, counts: Rc<RefCell<Vec<usize>>>, index: usize) -> Self {
6056            Self {
6057                size,
6058                color,
6059                counts,
6060                index,
6061            }
6062        }
6063    }
6064
6065    impl Widget for PaintCounterBox {
6066        fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
6067            constraints.clamp(self.size)
6068        }
6069
6070        fn paint(&self, ctx: &mut PaintCtx) {
6071            self.counts.borrow_mut()[self.index] += 1;
6072            ctx.fill_bounds(self.color);
6073        }
6074    }
6075
6076    struct LayeredScrollPaintBox {
6077        size: Size,
6078        color: Color,
6079        paints: Rc<RefCell<usize>>,
6080    }
6081
6082    impl Widget for LayeredScrollPaintBox {
6083        fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
6084            if ctx.phase() == EventPhase::Target
6085                && matches!(event, Event::Pointer(pointer) if pointer.kind == PointerEventKind::Scroll)
6086            {
6087                ctx.request_paint();
6088            }
6089        }
6090
6091        fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
6092            constraints.clamp(self.size)
6093        }
6094
6095        fn paint(&self, ctx: &mut PaintCtx) {
6096            *self.paints.borrow_mut() += 1;
6097            ctx.fill_bounds(self.color);
6098        }
6099
6100        fn layer_options(&self) -> LayerOptions {
6101            LayerOptions {
6102                paint_boundary: PaintBoundaryMode::Explicit,
6103                composition_mode: LayerCompositionMode::Normal,
6104            }
6105        }
6106    }
6107
6108    struct HitTestBox {
6109        size: Size,
6110        presses: Rc<RefCell<Vec<usize>>>,
6111        index: usize,
6112    }
6113
6114    impl HitTestBox {
6115        fn new(size: Size, presses: Rc<RefCell<Vec<usize>>>, index: usize) -> Self {
6116            Self {
6117                size,
6118                presses,
6119                index,
6120            }
6121        }
6122    }
6123
6124    impl Widget for HitTestBox {
6125        fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
6126            if ctx.phase() == EventPhase::Target
6127                && matches!(
6128                    event,
6129                    Event::Pointer(pointer)
6130                        if pointer.kind == PointerEventKind::Down
6131                            && ctx.bounds().contains(pointer.position)
6132                )
6133            {
6134                self.presses.borrow_mut()[self.index] += 1;
6135                ctx.set_handled();
6136            }
6137        }
6138
6139        fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
6140            constraints.clamp(self.size)
6141        }
6142    }
6143
6144    struct ConstraintProbe {
6145        size: Size,
6146        seen: Rc<RefCell<Vec<Constraints>>>,
6147    }
6148
6149    impl ConstraintProbe {
6150        fn new(size: Size, seen: Rc<RefCell<Vec<Constraints>>>) -> Self {
6151            Self { size, seen }
6152        }
6153    }
6154
6155    impl Widget for ConstraintProbe {
6156        fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
6157            self.seen.borrow_mut().push(constraints);
6158            constraints.clamp(self.size)
6159        }
6160    }
6161
6162    struct ExpandingLayerBox {
6163        collapsed_size: Size,
6164        expanded_size: Size,
6165        color: Color,
6166        counts: Rc<RefCell<Vec<usize>>>,
6167        index: usize,
6168        expanded: bool,
6169    }
6170
6171    impl ExpandingLayerBox {
6172        fn new(
6173            collapsed_size: Size,
6174            expanded_size: Size,
6175            color: Color,
6176            counts: Rc<RefCell<Vec<usize>>>,
6177            index: usize,
6178        ) -> Self {
6179            Self {
6180                collapsed_size,
6181                expanded_size,
6182                color,
6183                counts,
6184                index,
6185                expanded: false,
6186            }
6187        }
6188    }
6189
6190    impl Widget for ExpandingLayerBox {
6191        fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
6192            if let Event::Pointer(pointer) = event
6193                && pointer.kind == PointerEventKind::Down
6194                && ctx.bounds().contains(pointer.position)
6195                && !self.expanded
6196            {
6197                self.expanded = true;
6198                ctx.request_measure();
6199                ctx.request_paint();
6200                ctx.set_handled();
6201            }
6202        }
6203
6204        fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
6205            constraints.clamp(if self.expanded {
6206                self.expanded_size
6207            } else {
6208                self.collapsed_size
6209            })
6210        }
6211
6212        fn paint(&self, ctx: &mut PaintCtx) {
6213            self.counts.borrow_mut()[self.index] += 1;
6214            ctx.fill_bounds(self.color);
6215        }
6216
6217        fn layer_options(&self) -> LayerOptions {
6218            LayerOptions {
6219                paint_boundary: PaintBoundaryMode::Explicit,
6220                composition_mode: LayerCompositionMode::Normal,
6221            }
6222        }
6223    }
6224
6225    struct ScrollViewNoPaint {
6226        axes: ScrollAxes,
6227        name: Option<String>,
6228        offset: Vector,
6229        content_size: Size,
6230        child: SingleChild,
6231    }
6232
6233    impl ScrollViewNoPaint {
6234        fn vertical<W>(child: W) -> Self
6235        where
6236            W: Widget + 'static,
6237        {
6238            Self {
6239                axes: ScrollAxes::Vertical,
6240                name: None,
6241                offset: Vector::ZERO,
6242                content_size: Size::ZERO,
6243                child: SingleChild::new(child),
6244            }
6245        }
6246
6247        fn name(mut self, name: impl Into<String>) -> Self {
6248            self.name = Some(name.into());
6249            self
6250        }
6251
6252        fn clamp_offset(&self, viewport: Size, offset: Vector) -> Vector {
6253            let max_x = (self.content_size.width - viewport.width).max(0.0);
6254            let max_y = (self.content_size.height - viewport.height).max(0.0);
6255
6256            Vector::new(
6257                if self.axes.allows_horizontal() {
6258                    offset.x.clamp(0.0, max_x)
6259                } else {
6260                    0.0
6261                },
6262                if self.axes.allows_vertical() {
6263                    offset.y.clamp(0.0, max_y)
6264                } else {
6265                    0.0
6266                },
6267            )
6268        }
6269    }
6270
6271    impl Widget for ScrollViewNoPaint {
6272        fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
6273            let viewport = ctx.bounds().size;
6274
6275            match event {
6276                Event::Pointer(pointer)
6277                    if pointer.kind == sui_core::PointerEventKind::Scroll
6278                        && ctx.phase() != EventPhase::Capture
6279                        && ctx.bounds().contains(pointer.position) =>
6280                {
6281                    let delta = pointer
6282                        .scroll_delta
6283                        .map(super::scroll_delta_to_offset)
6284                        .unwrap_or(pointer.delta);
6285                    let next =
6286                        self.clamp_offset(viewport, self.offset + Vector::new(-delta.x, -delta.y));
6287                    if next != self.offset {
6288                        self.offset = next;
6289                        ctx.request_arrange();
6290                        ctx.request(InvalidationRequest::new(
6291                            InvalidationTarget::Widget(self.child.child().id()),
6292                            InvalidationKind::Transform,
6293                        ));
6294                        ctx.request_semantics();
6295                        ctx.set_handled();
6296                    }
6297                }
6298                _ => {}
6299            }
6300        }
6301
6302        fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
6303            let mut child_constraints = constraints.loosen();
6304            if self.axes.allows_horizontal() {
6305                child_constraints.max.width = f32::INFINITY;
6306            } else if constraints.max.width.is_finite() {
6307                child_constraints.min.width = constraints.max.width;
6308                child_constraints.max.width = constraints.max.width;
6309            }
6310
6311            if self.axes.allows_vertical() {
6312                child_constraints.max.height = f32::INFINITY;
6313            } else if constraints.max.height.is_finite() {
6314                child_constraints.min.height = constraints.max.height;
6315                child_constraints.max.height = constraints.max.height;
6316            }
6317
6318            let child_size = self.child.measure(ctx, child_constraints);
6319            self.content_size = child_size;
6320
6321            let viewport = constraints.clamp(Size::new(
6322                if constraints.max.width.is_finite() {
6323                    constraints.max.width
6324                } else {
6325                    child_size.width
6326                },
6327                if constraints.max.height.is_finite() {
6328                    constraints.max.height
6329                } else {
6330                    child_size.height
6331                },
6332            ));
6333            self.offset = self.clamp_offset(viewport, self.offset);
6334
6335            viewport
6336        }
6337
6338        fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
6339            self.child.arrange(
6340                ctx,
6341                Rect::from_origin_size(
6342                    Point::new(bounds.x() - self.offset.x, bounds.y() - self.offset.y),
6343                    self.child.child().measured_size(),
6344                ),
6345            );
6346        }
6347
6348        fn paint(&self, ctx: &mut PaintCtx) {
6349            ctx.push_clip_rect(ctx.bounds());
6350            self.child.paint(ctx);
6351            ctx.pop_clip();
6352        }
6353
6354        fn layer_options(&self) -> LayerOptions {
6355            LayerOptions {
6356                paint_boundary: PaintBoundaryMode::Explicit,
6357                composition_mode: LayerCompositionMode::Scroll,
6358            }
6359        }
6360
6361        fn semantics(&self, ctx: &mut SemanticsCtx) {
6362            let mut node =
6363                SemanticsNode::new(ctx.widget_id(), SemanticsRole::ScrollView, ctx.bounds());
6364            node.name = self.name.clone();
6365            node.actions = vec![sui_core::SemanticsAction::Focus];
6366            node.state.focused = ctx.is_focused();
6367            ctx.push(node);
6368            self.child.semantics(ctx);
6369        }
6370
6371        fn accepts_focus(&self) -> bool {
6372            true
6373        }
6374
6375        fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
6376            self.child.visit_children(visitor);
6377        }
6378
6379        fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
6380            self.child.visit_children_mut(visitor);
6381        }
6382    }
6383
6384    struct ScrollBarHost {
6385        spacing: f32,
6386        content: SingleChild,
6387        scroll_bar: SingleChild,
6388    }
6389
6390    impl ScrollBarHost {
6391        fn new<W, S>(content: W, scroll_bar: S) -> Self
6392        where
6393            W: Widget + 'static,
6394            S: Widget + 'static,
6395        {
6396            Self {
6397                spacing: 0.0,
6398                content: SingleChild::new(content),
6399                scroll_bar: SingleChild::new(scroll_bar),
6400            }
6401        }
6402    }
6403
6404    impl Widget for ScrollBarHost {
6405        fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
6406            let scroll_bar_size = self.scroll_bar.measure(
6407                ctx,
6408                Constraints::new(Size::ZERO, Size::new(f32::INFINITY, constraints.max.height)),
6409            );
6410            let content_constraints = Constraints::new(
6411                Size::new(
6412                    (constraints.min.width - scroll_bar_size.width - self.spacing).max(0.0),
6413                    constraints.min.height,
6414                ),
6415                Size::new(
6416                    (constraints.max.width - scroll_bar_size.width - self.spacing).max(0.0),
6417                    constraints.max.height,
6418                ),
6419            );
6420            let content_size = self.content.measure(ctx, content_constraints);
6421            constraints.clamp(Size::new(
6422                content_size.width + scroll_bar_size.width + self.spacing,
6423                content_size.height.max(scroll_bar_size.height),
6424            ))
6425        }
6426
6427        fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
6428            let scroll_bar_size = self.scroll_bar.child().measured_size();
6429            let content_width = (bounds.width() - scroll_bar_size.width - self.spacing).max(0.0);
6430            self.content.arrange(
6431                ctx,
6432                Rect::new(bounds.x(), bounds.y(), content_width, bounds.height()),
6433            );
6434            self.scroll_bar.arrange(
6435                ctx,
6436                Rect::new(
6437                    bounds.max_x() - scroll_bar_size.width,
6438                    bounds.y(),
6439                    scroll_bar_size.width,
6440                    bounds.height(),
6441                ),
6442            );
6443        }
6444
6445        fn paint(&self, ctx: &mut PaintCtx) {
6446            self.content.paint(ctx);
6447            self.scroll_bar.paint(ctx);
6448        }
6449
6450        fn semantics(&self, ctx: &mut SemanticsCtx) {
6451            self.content.semantics(ctx);
6452            self.scroll_bar.semantics(ctx);
6453        }
6454
6455        fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
6456            self.content.visit_children(visitor);
6457            self.scroll_bar.visit_children(visitor);
6458        }
6459
6460        fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
6461            self.content.visit_children_mut(visitor);
6462            self.scroll_bar.visit_children_mut(visitor);
6463        }
6464    }
6465
6466    fn render_root<W>(root: W) -> (RenderOutput, WidgetGraphSnapshot)
6467    where
6468        W: Widget + 'static,
6469    {
6470        let mut runtime = Application::new()
6471            .window(WindowBuilder::new().title("Containers").root(root))
6472            .build()
6473            .unwrap();
6474        let window_id = runtime.window_ids()[0];
6475        let output = runtime.render(window_id).unwrap();
6476        let graph = runtime.widget_graph(window_id).unwrap();
6477        (output, graph)
6478    }
6479
6480    fn layer_descriptor_for(
6481        output: &RenderOutput,
6482        owner: WidgetId,
6483    ) -> Option<SceneLayerDescriptor> {
6484        let mut descriptor = None;
6485        output.frame.scene.visit_layers(&mut |layer| {
6486            if layer.widget_id() == owner {
6487                descriptor = Some(layer.descriptor.clone());
6488            }
6489        });
6490        descriptor
6491    }
6492
6493    fn build_runtime<W>(root: W) -> (Runtime, sui_core::WindowId)
6494    where
6495        W: Widget + 'static,
6496    {
6497        let runtime = Application::new()
6498            .window(WindowBuilder::new().title("Containers").root(root))
6499            .build()
6500            .unwrap();
6501        let window_id = runtime.window_ids()[0];
6502        (runtime, window_id)
6503    }
6504
6505    fn touch_pointer(
6506        kind: PointerEventKind,
6507        pointer_id: u64,
6508        position: Point,
6509        delta: Vector,
6510    ) -> PointerEvent {
6511        let mut pointer = PointerEvent::new(kind, position);
6512        pointer.pointer_id = pointer_id;
6513        pointer.pointer_kind = PointerKind::Touch;
6514        pointer.delta = delta;
6515        pointer.is_primary = true;
6516        match kind {
6517            PointerEventKind::Down => {
6518                pointer.button = Some(PointerButton::Primary);
6519                pointer.buttons = PointerButtons::new(1);
6520            }
6521            PointerEventKind::Move => {
6522                pointer.buttons = PointerButtons::new(1);
6523            }
6524            PointerEventKind::Up => {
6525                pointer.button = Some(PointerButton::Primary);
6526            }
6527            _ => {}
6528        }
6529        pointer
6530    }
6531
6532    fn drag_vertical_scroll_bar(
6533        runtime: &mut Runtime,
6534        window_id: sui_core::WindowId,
6535        bounds: Rect,
6536        pointer_id: u64,
6537        delta_y: f32,
6538    ) {
6539        let start = Point::new(bounds.x() + bounds.width() * 0.5, bounds.y() + 8.0);
6540        let end = Point::new(start.x, start.y + delta_y);
6541        let mut down = PointerEvent::new(PointerEventKind::Down, start);
6542        down.pointer_id = pointer_id;
6543        down.button = Some(PointerButton::Primary);
6544        down.buttons = PointerButtons::new(1);
6545        runtime
6546            .handle_event(window_id, Event::Pointer(down))
6547            .unwrap();
6548
6549        let mut moved = PointerEvent::new(PointerEventKind::Move, end);
6550        moved.pointer_id = pointer_id;
6551        moved.delta = Vector::new(0.0, delta_y);
6552        moved.buttons = PointerButtons::new(1);
6553        runtime
6554            .handle_event(window_id, Event::Pointer(moved))
6555            .unwrap();
6556        runtime
6557            .handle_event(window_id, Event::Window(WindowEvent::RedrawRequested))
6558            .unwrap();
6559    }
6560
6561    fn scroll_view_content_with_height(
6562        graph: &WidgetGraphSnapshot,
6563        content_height: f32,
6564    ) -> &WidgetNodeSnapshot {
6565        graph
6566            .nodes
6567            .iter()
6568            .find(|node| {
6569                (node.measured_size.height - content_height).abs() <= 0.5
6570                    && node
6571                        .parent
6572                        .and_then(|parent_id| {
6573                            graph.nodes.iter().find(|parent| parent.id == parent_id)
6574                        })
6575                        .is_some_and(|parent| parent.paint_boundary == PaintBoundaryMode::Explicit)
6576            })
6577            .expect("scroll content present")
6578    }
6579
6580    fn parent_node<'a>(
6581        graph: &'a WidgetGraphSnapshot,
6582        node: &WidgetNodeSnapshot,
6583    ) -> &'a WidgetNodeSnapshot {
6584        let parent_id = node.parent.expect("node has parent");
6585        graph
6586            .nodes
6587            .iter()
6588            .find(|parent| parent.id == parent_id)
6589            .expect("parent node present")
6590    }
6591
6592    fn solid_fill_colors(output: &RenderOutput) -> Vec<Color> {
6593        let mut colors = Vec::new();
6594        output
6595            .frame
6596            .scene
6597            .visit_commands(&mut |command| match command {
6598                SceneCommand::FillRect {
6599                    brush: Brush::Solid(color),
6600                    ..
6601                }
6602                | SceneCommand::FillPath {
6603                    brush: Brush::Solid(color),
6604                    ..
6605                } => colors.push(*color),
6606                _ => {}
6607            });
6608        colors
6609    }
6610
6611    fn solid_fill_path_bounds(output: &RenderOutput) -> Vec<Rect> {
6612        let mut bounds = Vec::new();
6613        output.frame.scene.visit_commands(&mut |command| {
6614            if let SceneCommand::FillPath {
6615                path,
6616                brush: Brush::Solid(_),
6617            } = command
6618            {
6619                bounds.push(path.bounds());
6620            }
6621        });
6622        bounds
6623    }
6624
6625    fn solid_stroke_colors(output: &RenderOutput) -> Vec<Color> {
6626        let mut colors = Vec::new();
6627        output
6628            .frame
6629            .scene
6630            .visit_commands(&mut |command| match command {
6631                SceneCommand::StrokeRect {
6632                    brush: Brush::Solid(color),
6633                    ..
6634                }
6635                | SceneCommand::StrokePath {
6636                    brush: Brush::Solid(color),
6637                    ..
6638                } => colors.push(*color),
6639                _ => {}
6640            });
6641        colors
6642    }
6643
6644    fn contains_approx_color(colors: &[Color], expected: Color) -> bool {
6645        const CHANNEL_TOLERANCE: f32 = 1.0 / 255.0;
6646        colors.iter().any(|color| {
6647            color.space == expected.space
6648                && (color.red - expected.red).abs() <= CHANNEL_TOLERANCE
6649                && (color.green - expected.green).abs() <= CHANNEL_TOLERANCE
6650                && (color.blue - expected.blue).abs() <= CHANNEL_TOLERANCE
6651                && (color.alpha - expected.alpha).abs() <= CHANNEL_TOLERANCE
6652        })
6653    }
6654
6655    fn handle_ready_events(runtime: &mut Runtime) -> usize {
6656        let ready = runtime.drain_ready_events();
6657        let count = ready.len();
6658        for (ready_window, event) in ready {
6659            runtime
6660                .handle_event(ready_window, event)
6661                .expect("ready event should be handled");
6662        }
6663        count
6664    }
6665
6666    #[test]
6667    fn switch_view_only_exposes_selected_child_semantics() {
6668        let (output, _) = render_root(
6669            SwitchView::new()
6670                .selected(1)
6671                .with_child(crate::Label::new("Brush options"))
6672                .with_child(crate::Label::new("Pan options")),
6673        );
6674
6675        assert!(output.semantics.iter().any(|node| {
6676            node.role == SemanticsRole::Text && node.name.as_deref() == Some("Pan options")
6677        }));
6678        assert!(!output.semantics.iter().any(|node| {
6679            node.role == SemanticsRole::Text && node.name.as_deref() == Some("Brush options")
6680        }));
6681    }
6682
6683    #[test]
6684    fn switch_view_selected_when_updates_active_child() -> sui_core::Result<()> {
6685        let selected = Rc::new(RefCell::new(0_usize));
6686        let selected_reader = Rc::clone(&selected);
6687        let (mut runtime, window_id) = build_runtime(
6688            SwitchView::new()
6689                .selected_when(move || *selected_reader.borrow())
6690                .with_child(
6691                    SizedBox::new()
6692                        .size(Size::new(80.0, 24.0))
6693                        .child(crate::Label::new("Brush options")),
6694                )
6695                .with_child(
6696                    SizedBox::new()
6697                        .size(Size::new(120.0, 36.0))
6698                        .child(crate::Label::new("Fill options")),
6699                ),
6700        );
6701
6702        let output = runtime.render(window_id)?;
6703        assert_eq!(output.frame.viewport, Size::new(80.0, 24.0));
6704        assert!(output.semantics.iter().any(|node| {
6705            node.role == SemanticsRole::Text && node.name.as_deref() == Some("Brush options")
6706        }));
6707
6708        *selected.borrow_mut() = 1;
6709        runtime.handle_event(
6710            window_id,
6711            Event::Window(sui_core::WindowEvent::Resized(Size::new(120.0, 36.0))),
6712        )?;
6713        let output = runtime.render(window_id)?;
6714
6715        assert_eq!(output.frame.viewport, Size::new(120.0, 36.0));
6716        assert!(output.semantics.iter().any(|node| {
6717            node.role == SemanticsRole::Text && node.name.as_deref() == Some("Fill options")
6718        }));
6719        assert!(!output.semantics.iter().any(|node| {
6720            node.role == SemanticsRole::Text && node.name.as_deref() == Some("Brush options")
6721        }));
6722        Ok(())
6723    }
6724
6725    #[test]
6726    fn switch_view_observable_selection_relayouts_retained_child() -> sui_core::Result<()> {
6727        let selected = Signal::named("active_panel", 0_usize);
6728        let (mut runtime, window_id) = build_runtime(
6729            SwitchView::new()
6730                .selected_from(selected.clone())
6731                .with_child(
6732                    SizedBox::new()
6733                        .size(Size::new(80.0, 24.0))
6734                        .child(crate::Label::new("Brush options")),
6735                )
6736                .with_child(
6737                    SizedBox::new()
6738                        .size(Size::new(120.0, 36.0))
6739                        .child(crate::Label::new("Fill options")),
6740                ),
6741        );
6742
6743        let output = runtime.render(window_id)?;
6744        assert_eq!(output.frame.viewport, Size::new(80.0, 24.0));
6745
6746        assert!(selected.set(1));
6747        let output = runtime.render(window_id)?;
6748        assert_eq!(output.frame.viewport, Size::new(120.0, 36.0));
6749        assert!(output.semantics.iter().any(|node| {
6750            node.role == SemanticsRole::Text && node.name.as_deref() == Some("Fill options")
6751        }));
6752        assert!(
6753            output
6754                .diagnostics
6755                .reactive_invalidations
6756                .iter()
6757                .any(|sample| sample.source_name == "active_panel")
6758        );
6759        Ok(())
6760    }
6761
6762    #[test]
6763    fn padding_expands_child_size_and_offsets_bounds() {
6764        let (output, graph) = render_root(Padding::new(
6765            Insets {
6766                left: 8.0,
6767                top: 6.0,
6768                right: 4.0,
6769                bottom: 2.0,
6770            },
6771            FixedBox::new(Size::new(40.0, 20.0), Color::rgba(0.2, 0.3, 0.4, 1.0)),
6772        ));
6773
6774        assert_eq!(output.frame.viewport, Size::new(52.0, 28.0));
6775        assert_eq!(graph.nodes[1].bounds, Rect::new(8.0, 6.0, 40.0, 20.0));
6776    }
6777
6778    #[test]
6779    fn padding_horizontal_constructor_offsets_x_only() {
6780        let (output, graph) = render_root(Padding::horizontal(
6781            9.0,
6782            FixedBox::new(Size::new(40.0, 20.0), Color::rgba(0.2, 0.3, 0.4, 1.0)),
6783        ));
6784
6785        assert_eq!(output.frame.viewport, Size::new(58.0, 20.0));
6786        assert_eq!(graph.nodes[1].bounds, Rect::new(9.0, 0.0, 40.0, 20.0));
6787    }
6788
6789    #[test]
6790    fn padding_can_stretch_child_to_arranged_content_height() {
6791        let (_output, graph) = render_root(
6792            SizedBox::new().size(Size::new(100.0, 80.0)).child(
6793                Padding::new(
6794                    Insets {
6795                        left: 8.0,
6796                        top: 5.0,
6797                        right: 12.0,
6798                        bottom: 7.0,
6799                    },
6800                    FixedBox::new(Size::new(20.0, 10.0), Color::rgba(0.2, 0.3, 0.4, 1.0)),
6801                )
6802                .fill_child_height(true),
6803            ),
6804        );
6805
6806        assert_eq!(graph.nodes[2].bounds, Rect::new(8.0, 5.0, 80.0, 68.0));
6807    }
6808
6809    #[test]
6810    fn padding_fill_flags_turn_off_with_false() {
6811        let child = || FixedBox::new(Size::new(20.0, 10.0), Color::rgba(0.2, 0.3, 0.4, 1.0));
6812        let padding = Padding::all(4.0, child())
6813            .fill_child()
6814            .fill_child_height(false);
6815        assert!(padding.fill_child_width);
6816        assert!(!padding.fill_child_height);
6817
6818        let padding = Padding::all(4.0, child())
6819            .fill_child_width(true)
6820            .fill_child_width(false);
6821        assert!(!padding.fill_child_width);
6822    }
6823
6824    #[test]
6825    fn align_centers_child_within_available_space() {
6826        let (output, graph) = render_root(SizedBox::new().size(Size::new(100.0, 60.0)).child(
6827            Align::center(FixedBox::new(
6828                Size::new(20.0, 10.0),
6829                Color::rgba(0.4, 0.3, 0.2, 1.0),
6830            )),
6831        ));
6832
6833        assert_eq!(output.frame.viewport, Size::new(100.0, 60.0));
6834        assert_eq!(graph.nodes[2].bounds, Rect::new(40.0, 25.0, 20.0, 10.0));
6835    }
6836
6837    #[test]
6838    fn sized_box_applies_explicit_dimensions_to_child() {
6839        let (output, graph) = render_root(SizedBox::new().width(40.0).height(24.0).child(
6840            FixedBox::new(Size::new(12.0, 8.0), Color::rgba(0.1, 0.7, 0.2, 1.0)),
6841        ));
6842
6843        assert_eq!(output.frame.viewport, Size::new(40.0, 24.0));
6844        assert_eq!(graph.nodes[1].bounds, Rect::new(0.0, 0.0, 40.0, 24.0));
6845    }
6846
6847    #[test]
6848    fn trailing_slot_row_places_fixed_trailing_slot() {
6849        let (output, graph) = render_root(
6850            SizedBox::new().size(Size::new(200.0, 80.0)).child(
6851                TrailingSlotRow::new(
6852                    FixedBox::new(Size::new(120.0, 64.0), Color::rgba(0.1, 0.7, 0.2, 1.0)),
6853                    FixedBox::new(Size::new(40.0, 40.0), Color::rgba(0.7, 0.2, 0.2, 1.0)),
6854                )
6855                .trailing_width(50.0)
6856                .trailing_height(40.0)
6857                .gap(8.0),
6858            ),
6859        );
6860
6861        assert_eq!(output.frame.viewport, Size::new(200.0, 80.0));
6862        assert_eq!(graph.nodes[2].bounds, Rect::new(0.0, 0.0, 142.0, 80.0));
6863        assert_eq!(graph.nodes[3].bounds, Rect::new(150.0, 20.0, 50.0, 40.0));
6864    }
6865
6866    #[test]
6867    fn dock_places_fixed_top_bottom_and_fills_body() {
6868        let (output, graph) = render_root(
6869            SizedBox::new().size(Size::new(200.0, 120.0)).child(
6870                Dock::new(FixedBox::new(
6871                    Size::new(50.0, 50.0),
6872                    Color::rgba(0.1, 0.7, 0.2, 1.0),
6873                ))
6874                .top(
6875                    24.0,
6876                    FixedBox::new(Size::new(200.0, 24.0), Color::rgba(0.2, 0.2, 0.8, 1.0)),
6877                )
6878                .bottom(
6879                    18.0,
6880                    FixedBox::new(Size::new(200.0, 18.0), Color::rgba(0.8, 0.2, 0.2, 1.0)),
6881                ),
6882            ),
6883        );
6884
6885        assert_eq!(output.frame.viewport, Size::new(200.0, 120.0));
6886        assert_eq!(graph.nodes[2].bounds, Rect::new(0.0, 0.0, 200.0, 24.0));
6887        assert_eq!(graph.nodes[3].bounds, Rect::new(0.0, 24.0, 200.0, 78.0));
6888        assert_eq!(graph.nodes[4].bounds, Rect::new(0.0, 102.0, 200.0, 18.0));
6889    }
6890
6891    #[test]
6892    fn measured_bottom_dock_places_natural_bottom_at_bottom_edge() {
6893        let (output, graph) = render_root(SizedBox::new().size(Size::new(200.0, 120.0)).child(
6894            MeasuredBottomDock::new(
6895                FixedBox::new(Size::new(50.0, 50.0), Color::rgba(0.1, 0.7, 0.2, 1.0)),
6896                FixedBox::new(Size::new(60.0, 26.0), Color::rgba(0.8, 0.2, 0.2, 1.0)),
6897            ),
6898        ));
6899
6900        assert_eq!(output.frame.viewport, Size::new(200.0, 120.0));
6901        assert_eq!(graph.nodes[2].bounds, Rect::new(0.0, 0.0, 200.0, 94.0));
6902        assert_eq!(graph.nodes[3].bounds, Rect::new(0.0, 94.0, 200.0, 26.0));
6903    }
6904
6905    #[test]
6906    fn fixed_pane_split_preserves_fixed_first_and_stretches_cross_axis() {
6907        let (output, graph) = render_root(
6908            SizedBox::new().size(Size::new(200.0, 80.0)).child(
6909                FixedPaneSplit::horizontal(
6910                    FixedBox::new(Size::new(80.0, 12.0), Color::rgba(0.1, 0.7, 0.2, 1.0)),
6911                    FixedBox::new(Size::new(1.0, 80.0), Color::rgba(0.7, 0.7, 0.7, 1.0)),
6912                    FixedBox::new(Size::new(120.0, 12.0), Color::rgba(0.7, 0.2, 0.2, 1.0)),
6913                )
6914                .fixed_first(64.0)
6915                .divider_extent(1.0),
6916            ),
6917        );
6918
6919        assert_eq!(output.frame.viewport, Size::new(200.0, 80.0));
6920        assert_eq!(graph.nodes[2].bounds, Rect::new(0.0, 0.0, 64.0, 80.0));
6921        assert_eq!(graph.nodes[3].bounds, Rect::new(64.0, 0.0, 1.0, 80.0));
6922        assert_eq!(graph.nodes[4].bounds, Rect::new(65.0, 0.0, 135.0, 80.0));
6923    }
6924
6925    #[test]
6926    fn fixed_pane_split_preserves_fixed_second_and_shrinks_to_fit() {
6927        let (output, graph) = render_root(
6928            SizedBox::new().size(Size::new(90.0, 40.0)).child(
6929                FixedPaneSplit::horizontal(
6930                    FixedBox::new(Size::new(80.0, 12.0), Color::rgba(0.1, 0.7, 0.2, 1.0)),
6931                    FixedBox::new(Size::new(1.0, 40.0), Color::rgba(0.7, 0.7, 0.7, 1.0)),
6932                    FixedBox::new(Size::new(120.0, 12.0), Color::rgba(0.7, 0.2, 0.2, 1.0)),
6933                )
6934                .fixed_second(120.0)
6935                .divider_extent(1.0),
6936            ),
6937        );
6938
6939        assert_eq!(output.frame.viewport, Size::new(90.0, 40.0));
6940        assert_eq!(graph.nodes[2].bounds, Rect::new(0.0, 0.0, 0.0, 40.0));
6941        assert_eq!(graph.nodes[3].bounds, Rect::new(0.0, 0.0, 1.0, 40.0));
6942        assert_eq!(graph.nodes[4].bounds, Rect::new(1.0, 0.0, 89.0, 40.0));
6943    }
6944
6945    #[test]
6946    fn stack_positions_children_with_spacing_and_alignment() {
6947        let (output, graph) = render_root(
6948            SizedBox::new().size(Size::new(100.0, 40.0)).child(
6949                Stack::horizontal()
6950                    .gap(5.0)
6951                    .alignment(Alignment::Center)
6952                    .with_child(FixedBox::new(
6953                        Size::new(30.0, 10.0),
6954                        Color::rgba(0.6, 0.2, 0.2, 1.0),
6955                    ))
6956                    .with_child(FixedBox::new(
6957                        Size::new(20.0, 20.0),
6958                        Color::rgba(0.2, 0.2, 0.6, 1.0),
6959                    )),
6960            ),
6961        );
6962
6963        assert_eq!(output.frame.viewport, Size::new(100.0, 40.0));
6964        assert_eq!(graph.nodes[2].bounds, Rect::new(0.0, 15.0, 30.0, 10.0));
6965        assert_eq!(graph.nodes[3].bounds, Rect::new(35.0, 10.0, 20.0, 20.0));
6966    }
6967
6968    #[test]
6969    fn flex_grows_child_to_fill_available_main_axis_space() {
6970        let (output, graph) = render_root(
6971            SizedBox::new().size(Size::new(100.0, 20.0)).child(
6972                Flex::horizontal()
6973                    .with_child(FixedBox::new(
6974                        Size::new(20.0, 10.0),
6975                        Color::rgba(0.7, 0.2, 0.2, 1.0),
6976                    ))
6977                    .with_item(
6978                        FixedBox::new(Size::new(10.0, 10.0), Color::rgba(0.2, 0.2, 0.7, 1.0)),
6979                        FlexItem::new().grow(1.0),
6980                    ),
6981            ),
6982        );
6983
6984        assert_eq!(output.frame.viewport, Size::new(100.0, 20.0));
6985        assert_eq!(graph.nodes[2].bounds, Rect::new(0.0, 0.0, 20.0, 10.0));
6986        assert_eq!(graph.nodes[3].bounds, Rect::new(20.0, 0.0, 80.0, 10.0));
6987    }
6988
6989    #[test]
6990    fn flex_remeasures_wrapping_label_at_resolved_width() {
6991        const TEXT: &str =
6992            "Provider verification status and usage limits are shared across the cluster.";
6993        let (output, _) = render_root(
6994            SizedBox::new()
6995                .width(240.0)
6996                .child(Flex::horizontal().with_item(crate::Label::new(TEXT), FlexItem::flex(1.0))),
6997        );
6998
6999        let label = output
7000            .semantics
7001            .iter()
7002            .find(|node| node.role == SemanticsRole::Text && node.name.as_deref() == Some(TEXT))
7003            .expect("flex label semantics present");
7004        assert!((label.bounds.width() - 240.0).abs() < 0.01);
7005
7006        let mut shaped_width = None;
7007        let mut line_count = None;
7008        output.frame.scene.visit_commands(&mut |command| {
7009            if let SceneCommand::DrawShapedText(run) = command
7010                && let Some(layout) = run.resolve(output.frame.text_layout_registry.as_ref())
7011                && layout.text() == TEXT
7012            {
7013                shaped_width = Some(layout.box_size().width);
7014                line_count = Some(layout.lines().len());
7015            }
7016        });
7017
7018        assert!(shaped_width.is_some_and(|width| width >= 239.0));
7019        assert!(line_count.is_some_and(|lines| (2..=4).contains(&lines)));
7020        assert!(output.frame.viewport.height < 100.0);
7021    }
7022
7023    #[test]
7024    fn flex_spacer_pushes_following_children_to_remaining_edge() {
7025        let (_, graph) = render_root(
7026            SizedBox::new().size(Size::new(100.0, 10.0)).child(
7027                Flex::horizontal()
7028                    .with_child(FixedBox::new(
7029                        Size::new(10.0, 10.0),
7030                        Color::rgba(0.7, 0.2, 0.2, 1.0),
7031                    ))
7032                    .spacer()
7033                    .with_child(FixedBox::new(
7034                        Size::new(10.0, 10.0),
7035                        Color::rgba(0.2, 0.2, 0.7, 1.0),
7036                    )),
7037            ),
7038        );
7039
7040        assert_eq!(graph.nodes[2].bounds, Rect::new(0.0, 0.0, 10.0, 10.0));
7041        assert_eq!(graph.nodes[4].bounds, Rect::new(90.0, 0.0, 10.0, 10.0));
7042    }
7043
7044    #[test]
7045    fn flex_wraps_children_and_applies_cross_gap() {
7046        let (output, graph) = render_root(
7047            SizedBox::new().size(Size::new(70.0, 25.0)).child(
7048                Flex::horizontal()
7049                    .wrap(FlexWrap::Wrap)
7050                    .main_gap(5.0)
7051                    .cross_gap(5.0)
7052                    .with_child(FixedBox::new(
7053                        Size::new(30.0, 10.0),
7054                        Color::rgba(0.7, 0.2, 0.2, 1.0),
7055                    ))
7056                    .with_child(FixedBox::new(
7057                        Size::new(30.0, 10.0),
7058                        Color::rgba(0.2, 0.7, 0.2, 1.0),
7059                    ))
7060                    .with_child(FixedBox::new(
7061                        Size::new(30.0, 10.0),
7062                        Color::rgba(0.2, 0.2, 0.7, 1.0),
7063                    )),
7064            ),
7065        );
7066
7067        assert_eq!(output.frame.viewport, Size::new(70.0, 25.0));
7068        assert_eq!(graph.nodes[2].bounds, Rect::new(0.0, 0.0, 30.0, 10.0));
7069        assert_eq!(graph.nodes[3].bounds, Rect::new(35.0, 0.0, 30.0, 10.0));
7070        assert_eq!(graph.nodes[4].bounds, Rect::new(0.0, 15.0, 30.0, 10.0));
7071    }
7072
7073    #[test]
7074    fn flex_stretches_children_on_cross_axis() {
7075        let (_, graph) = render_root(
7076            SizedBox::new().size(Size::new(60.0, 20.0)).child(
7077                Flex::horizontal()
7078                    .align_items(Alignment::Stretch)
7079                    .with_child(FixedBox::new(
7080                        Size::new(20.0, 8.0),
7081                        Color::rgba(0.4, 0.3, 0.2, 1.0),
7082                    )),
7083            ),
7084        );
7085
7086        assert_eq!(graph.nodes[2].bounds, Rect::new(0.0, 0.0, 20.0, 20.0));
7087    }
7088
7089    #[test]
7090    fn background_paints_before_child_content() {
7091        let (output, _) = render_root(Background::new(
7092            Brush::Solid(Color::rgba(0.1, 0.1, 0.1, 1.0)),
7093            FixedBox::new(Size::new(16.0, 12.0), Color::rgba(0.9, 0.2, 0.1, 1.0)),
7094        ));
7095
7096        assert_eq!(output.frame.scene.commands().len(), 2);
7097        assert_eq!(
7098            output.frame.scene.commands()[0],
7099            SceneCommand::FillRect {
7100                rect: Rect::new(0.0, 0.0, 16.0, 12.0),
7101                brush: Brush::Solid(Color::rgba(0.1, 0.1, 0.1, 1.0)),
7102            }
7103        );
7104        assert_eq!(
7105            output.frame.scene.commands()[1],
7106            SceneCommand::FillRect {
7107                rect: Rect::new(0.0, 0.0, 16.0, 12.0),
7108                brush: Brush::Solid(Color::rgba(0.9, 0.2, 0.1, 1.0)),
7109            }
7110        );
7111    }
7112
7113    #[test]
7114    fn semantic_region_wraps_child_with_accessible_summary() {
7115        let description = Rc::new(RefCell::new("4 active tasks".to_string()));
7116        let description_reader = Rc::clone(&description);
7117        let (output, graph) = render_root(
7118            SemanticRegion::new(
7119                "File task strip",
7120                FixedBox::new(Size::new(96.0, 28.0), Color::rgba(0.2, 0.4, 0.6, 1.0)),
7121            )
7122            .role(SemanticsRole::Text)
7123            .description_when(move || description_reader.borrow().clone()),
7124        );
7125
7126        let region = output
7127            .semantics
7128            .iter()
7129            .find(|node| {
7130                node.role == SemanticsRole::Text && node.name.as_deref() == Some("File task strip")
7131            })
7132            .expect("semantic region node should exist");
7133        assert_eq!(region.description.as_deref(), Some("4 active tasks"));
7134        assert_eq!(graph.nodes[0].bounds, Rect::new(0.0, 0.0, 96.0, 28.0));
7135        assert_eq!(graph.nodes[1].bounds, Rect::new(0.0, 0.0, 96.0, 28.0));
7136    }
7137
7138    #[test]
7139    fn stack_vertical_axis_is_available() {
7140        let (output, graph) = render_root(
7141            Stack::new(Axis::Vertical)
7142                .gap(4.0)
7143                .with_child(FixedBox::new(
7144                    Size::new(18.0, 10.0),
7145                    Color::rgba(0.5, 0.5, 0.1, 1.0),
7146                ))
7147                .with_child(FixedBox::new(
7148                    Size::new(12.0, 8.0),
7149                    Color::rgba(0.1, 0.5, 0.5, 1.0),
7150                )),
7151        );
7152
7153        assert_eq!(output.frame.viewport, Size::new(18.0, 22.0));
7154        assert_eq!(graph.nodes[1].bounds, Rect::new(0.0, 0.0, 18.0, 10.0));
7155        assert_eq!(graph.nodes[2].bounds, Rect::new(0.0, 14.0, 12.0, 8.0));
7156    }
7157
7158    #[test]
7159    fn nested_containers_preserve_global_child_bounds() {
7160        let (output, graph) = render_root(Padding::all(
7161            24.0,
7162            Background::new(
7163                Brush::Solid(Color::rgba(0.1, 0.1, 0.1, 1.0)),
7164                Padding::all(
7165                    18.0,
7166                    Stack::vertical()
7167                        .gap(10.0)
7168                        .with_child(FixedBox::new(
7169                            Size::new(50.0, 12.0),
7170                            Color::rgba(0.7, 0.2, 0.2, 1.0),
7171                        ))
7172                        .with_child(FixedBox::new(
7173                            Size::new(30.0, 8.0),
7174                            Color::rgba(0.2, 0.7, 0.2, 1.0),
7175                        )),
7176                ),
7177            ),
7178        ));
7179
7180        assert_eq!(output.frame.viewport, Size::new(134.0, 114.0));
7181        assert_eq!(graph.nodes[1].bounds, Rect::new(24.0, 24.0, 86.0, 66.0));
7182        assert_eq!(graph.nodes[2].bounds, Rect::new(24.0, 24.0, 86.0, 66.0));
7183        assert_eq!(graph.nodes[3].bounds, Rect::new(42.0, 42.0, 50.0, 30.0));
7184        assert_eq!(graph.nodes[4].bounds, Rect::new(42.0, 42.0, 50.0, 12.0));
7185        assert_eq!(graph.nodes[5].bounds, Rect::new(42.0, 64.0, 30.0, 8.0));
7186    }
7187
7188    #[test]
7189    fn scroll_view_updates_child_bounds_after_scroll_input() {
7190        let (mut runtime, window_id) = build_runtime(
7191            SizedBox::new()
7192                .size(Size::new(80.0, 40.0))
7193                .child(ScrollView::vertical(FixedBox::new(
7194                    Size::new(80.0, 120.0),
7195                    Color::rgba(0.2, 0.3, 0.7, 1.0),
7196                ))),
7197        );
7198
7199        let _ = runtime.render(window_id).unwrap();
7200        let mut scroll = PointerEvent::new(PointerEventKind::Scroll, Point::new(20.0, 20.0));
7201        scroll.scroll_delta = Some(ScrollDelta::Pixels(Vector::new(0.0, -32.0)));
7202        runtime
7203            .handle_event(window_id, Event::Pointer(scroll))
7204            .unwrap();
7205        let output = runtime.render(window_id).unwrap();
7206        let graph = runtime.widget_graph(window_id).unwrap();
7207
7208        assert_eq!(graph.nodes[1].bounds, Rect::new(0.0, 0.0, 80.0, 40.0));
7209        let content = graph
7210            .nodes
7211            .iter()
7212            .find(|node| {
7213                node.bounds.width() == 80.0 - DefaultTheme::default().metrics.scroll_bar_thickness
7214                    && node.bounds.height() == 120.0
7215            })
7216            .expect("scroll content present");
7217        assert_eq!(
7218            content.bounds,
7219            Rect::new(
7220                0.0,
7221                -32.0,
7222                80.0 - DefaultTheme::default().metrics.scroll_bar_thickness,
7223                120.0
7224            )
7225        );
7226
7227        let semantic_content = output
7228            .semantics
7229            .iter()
7230            .find(|node| node.id == content.id)
7231            .expect("scroll content semantics present");
7232        assert_eq!(semantic_content.bounds, content.bounds);
7233
7234        let scroll_view = parent_node(&graph, content);
7235        let scroll_scene = output
7236            .frame
7237            .scene
7238            .layer_scene(scroll_view.id)
7239            .expect("scroll viewport layer present");
7240        assert!(scroll_scene.commands().iter().any(|command| {
7241            matches!(
7242                command,
7243                SceneCommand::PushClip { rect }
7244                    if *rect == Rect::new(0.0, 0.0, 80.0 - DefaultTheme::default().metrics.scroll_bar_thickness, 40.0)
7245            )
7246        }));
7247    }
7248
7249    #[test]
7250    fn scroll_view_translates_retained_content_without_repainting() {
7251        let counts = Rc::new(RefCell::new(vec![0usize; 2]));
7252        let (mut runtime, window_id) = build_runtime(
7253            SizedBox::new().size(Size::new(80.0, 60.0)).child(
7254                ScrollView::vertical(
7255                    Stack::vertical()
7256                        .with_child(PaintCounterBox::new(
7257                            Size::new(80.0, 60.0),
7258                            Color::rgba(0.8, 0.2, 0.2, 1.0),
7259                            Rc::clone(&counts),
7260                            0,
7261                        ))
7262                        .with_child(PaintCounterBox::new(
7263                            Size::new(80.0, 60.0),
7264                            Color::rgba(0.2, 0.6, 0.8, 1.0),
7265                            Rc::clone(&counts),
7266                            1,
7267                        )),
7268                )
7269                .retain_content_layer(),
7270            ),
7271        );
7272
7273        let _ = runtime.render(window_id).unwrap();
7274        assert_eq!(*counts.borrow(), vec![1, 1]);
7275        let graph = runtime.widget_graph(window_id).unwrap();
7276        let content_id = scroll_view_content_with_height(&graph, 120.0).id;
7277
7278        let mut scroll = PointerEvent::new(PointerEventKind::Scroll, Point::new(20.0, 20.0));
7279        scroll.scroll_delta = Some(ScrollDelta::Pixels(Vector::new(0.0, -32.0)));
7280        runtime
7281            .handle_event(window_id, Event::Pointer(scroll))
7282            .unwrap();
7283        let output = runtime.render(window_id).unwrap();
7284
7285        assert_eq!(*counts.borrow(), vec![1, 1]);
7286        assert!(output.frame.layer_updates.iter().any(|update| {
7287            update.owner == content_id && update.kind == sui_scene::SceneLayerUpdateKind::Transform
7288        }));
7289        assert!(!output.frame.layer_updates.iter().any(|update| {
7290            update.owner == content_id && update.kind == sui_scene::SceneLayerUpdateKind::Content
7291        }));
7292    }
7293
7294    #[test]
7295    fn scroll_view_keeps_retained_content_far_from_the_origin() {
7296        // Row heights that f32 cannot represent exactly make absolute
7297        // positions round differently after each scroll step.
7298        const ROWS: usize = 200;
7299        let counts = Rc::new(RefCell::new(vec![0usize; ROWS]));
7300        let mut stack = Stack::vertical();
7301        for index in 0..ROWS {
7302            stack.push(PaintCounterBox::new(
7303                Size::new(80.0, 21.792),
7304                Color::rgba(0.8, 0.2, 0.2, 1.0),
7305                Rc::clone(&counts),
7306                index,
7307            ));
7308        }
7309        let (mut runtime, window_id) = build_runtime(
7310            SizedBox::new()
7311                .size(Size::new(80.0, 60.0))
7312                .child(ScrollView::vertical(stack).retain_content_layer()),
7313        );
7314
7315        let _ = runtime.render(window_id).unwrap();
7316        let initial = counts.borrow().clone();
7317        for _ in 0..80 {
7318            let mut scroll = PointerEvent::new(PointerEventKind::Scroll, Point::new(20.0, 20.0));
7319            scroll.scroll_delta = Some(ScrollDelta::Pixels(Vector::new(0.0, -48.0)));
7320            runtime
7321                .handle_event(window_id, Event::Pointer(scroll))
7322                .unwrap();
7323            let _ = runtime.render(window_id).unwrap();
7324        }
7325
7326        assert_eq!(*counts.borrow(), initial);
7327    }
7328
7329    #[test]
7330    fn scroll_view_repaints_content_by_default_after_scroll_input() {
7331        let counts = Rc::new(RefCell::new(vec![0usize; 2]));
7332        let (mut runtime, window_id) = build_runtime(
7333            SizedBox::new()
7334                .size(Size::new(80.0, 60.0))
7335                .child(ScrollView::vertical(
7336                    Stack::vertical()
7337                        .with_child(PaintCounterBox::new(
7338                            Size::new(80.0, 60.0),
7339                            Color::rgba(0.8, 0.2, 0.2, 1.0),
7340                            Rc::clone(&counts),
7341                            0,
7342                        ))
7343                        .with_child(PaintCounterBox::new(
7344                            Size::new(80.0, 60.0),
7345                            Color::rgba(0.2, 0.6, 0.8, 1.0),
7346                            Rc::clone(&counts),
7347                            1,
7348                        )),
7349                )),
7350        );
7351
7352        let _ = runtime.render(window_id).unwrap();
7353        let mut scroll = PointerEvent::new(PointerEventKind::Scroll, Point::new(20.0, 20.0));
7354        scroll.scroll_delta = Some(ScrollDelta::Pixels(Vector::new(0.0, -32.0)));
7355        runtime
7356            .handle_event(window_id, Event::Pointer(scroll))
7357            .unwrap();
7358        let output = runtime.render(window_id).unwrap();
7359
7360        assert_eq!(*counts.borrow(), vec![2, 2]);
7361        assert!(
7362            output
7363                .frame
7364                .layer_updates
7365                .iter()
7366                .any(|update| { update.kind == sui_scene::SceneLayerUpdateKind::Content })
7367        );
7368    }
7369
7370    #[test]
7371    fn retained_scroll_repaints_ancestor_when_nested_layer_is_dirty() {
7372        let nested_paints = Rc::new(RefCell::new(0usize));
7373        let sibling_paints = Rc::new(RefCell::new(vec![0usize]));
7374        let (mut runtime, window_id) = build_runtime(
7375            SizedBox::new().size(Size::new(80.0, 60.0)).child(
7376                ScrollView::vertical(
7377                    Stack::vertical()
7378                        .with_child(LayeredScrollPaintBox {
7379                            size: Size::new(80.0, 60.0),
7380                            color: Color::rgba(0.8, 0.2, 0.2, 1.0),
7381                            paints: Rc::clone(&nested_paints),
7382                        })
7383                        .with_child(PaintCounterBox::new(
7384                            Size::new(80.0, 60.0),
7385                            Color::rgba(0.2, 0.6, 0.8, 1.0),
7386                            Rc::clone(&sibling_paints),
7387                            0,
7388                        )),
7389                )
7390                .retain_content_layer(),
7391            ),
7392        );
7393
7394        let _ = runtime.render(window_id).unwrap();
7395        let initial_graph = runtime.widget_graph(window_id).unwrap();
7396        let content = scroll_view_content_with_height(&initial_graph, 120.0);
7397        let content_id = content.id;
7398        let nested_id = content.children[0];
7399
7400        let mut scroll = PointerEvent::new(PointerEventKind::Scroll, Point::new(20.0, 20.0));
7401        scroll.scroll_delta = Some(ScrollDelta::Pixels(Vector::new(0.0, -32.0)));
7402        runtime
7403            .handle_event(window_id, Event::Pointer(scroll))
7404            .unwrap();
7405        let output = runtime.render(window_id).unwrap();
7406        let graph = runtime.widget_graph(window_id).unwrap();
7407        let nested = graph
7408            .nodes
7409            .iter()
7410            .find(|node| node.id == nested_id)
7411            .expect("nested retained layer remains in the graph");
7412        let descriptor = layer_descriptor_for(&output, nested_id)
7413            .expect("nested retained layer remains in the scene");
7414
7415        assert_eq!(*nested_paints.borrow(), 2);
7416        assert_eq!(*sibling_paints.borrow(), vec![2]);
7417        assert_eq!(descriptor.bounds, nested.bounds);
7418        assert!(output.frame.layer_updates.iter().any(|update| {
7419            update.owner == content_id && update.kind == sui_scene::SceneLayerUpdateKind::Content
7420        }));
7421        assert!(!output.frame.layer_updates.iter().any(|update| {
7422            update.owner == content_id && update.kind == sui_scene::SceneLayerUpdateKind::Transform
7423        }));
7424    }
7425
7426    #[test]
7427    fn scroll_view_hit_testing_tracks_retained_content_translation() {
7428        let presses = Rc::new(RefCell::new(vec![0usize; 2]));
7429        let (mut runtime, window_id) = build_runtime(
7430            SizedBox::new().size(Size::new(80.0, 40.0)).child(
7431                ScrollView::vertical(
7432                    Stack::vertical()
7433                        .with_child(HitTestBox::new(
7434                            Size::new(80.0, 40.0),
7435                            Rc::clone(&presses),
7436                            0,
7437                        ))
7438                        .with_child(HitTestBox::new(
7439                            Size::new(80.0, 40.0),
7440                            Rc::clone(&presses),
7441                            1,
7442                        )),
7443                )
7444                .retain_content_layer(),
7445            ),
7446        );
7447
7448        let _ = runtime.render(window_id).unwrap();
7449        let mut scroll = PointerEvent::new(PointerEventKind::Scroll, Point::new(20.0, 20.0));
7450        scroll.scroll_delta = Some(ScrollDelta::Pixels(Vector::new(0.0, -40.0)));
7451        runtime
7452            .handle_event(window_id, Event::Pointer(scroll))
7453            .unwrap();
7454        let _ = runtime.render(window_id).unwrap();
7455
7456        let pointer = PointerEvent::new(PointerEventKind::Down, Point::new(20.0, 20.0));
7457        runtime
7458            .handle_event(window_id, Event::Pointer(pointer))
7459            .unwrap();
7460
7461        assert_eq!(*presses.borrow(), vec![0, 1]);
7462    }
7463
7464    #[test]
7465    fn scroll_view_uses_scroll_layer_metadata() {
7466        let (output, _) = render_root(SizedBox::new().size(Size::new(80.0, 40.0)).child(
7467            ScrollView::vertical(FixedBox::new(
7468                Size::new(80.0, 120.0),
7469                Color::rgba(0.2, 0.3, 0.7, 1.0),
7470            )),
7471        ));
7472
7473        let scroll_id = output
7474            .semantics
7475            .iter()
7476            .find(|node| node.role == SemanticsRole::ScrollView)
7477            .expect("scroll view semantics present")
7478            .id;
7479        let descriptor =
7480            layer_descriptor_for(&output, scroll_id).expect("scroll view layer present");
7481
7482        assert_eq!(descriptor.composition_mode, LayerCompositionMode::Scroll);
7483    }
7484
7485    #[test]
7486    fn scrollbar_gutters_resolve_cross_axis_overflow_and_own_the_corner() {
7487        let thickness = DefaultTheme::default().metrics.scroll_bar_thickness;
7488        for content in [Size::new(96.0, 120.0), Size::new(120.0, 96.0)] {
7489            let state = ScrollState::new();
7490            let presses = Rc::new(RefCell::new(vec![0]));
7491            let (mut runtime, window_id) = build_runtime(
7492                SizedBox::new().size(Size::new(100.0, 100.0)).child(
7493                    ScrollView::both(HitTestBox::new(content, Rc::clone(&presses), 0))
7494                        .state(state.clone())
7495                        .name("Canvas"),
7496                ),
7497            );
7498            let output = runtime.render(window_id).unwrap();
7499            let viewport = 100.0 - thickness;
7500            assert_eq!(state.viewport_size(), Size::new(viewport, viewport));
7501            assert_eq!(
7502                state.max_offset(),
7503                Vector::new(content.width - viewport, content.height - viewport)
7504            );
7505            let bounds = |name| {
7506                output
7507                    .semantics
7508                    .iter()
7509                    .find(|node| node.name.as_deref() == Some(name))
7510                    .unwrap()
7511                    .bounds
7512            };
7513            assert_eq!(
7514                bounds("Canvas vertical scroll bar"),
7515                Rect::new(viewport, 0.0, thickness, viewport)
7516            );
7517            assert_eq!(
7518                bounds("Canvas horizontal scroll bar"),
7519                Rect::new(0.0, viewport, viewport, thickness)
7520            );
7521            for (point, expected) in [
7522                (Point::new(viewport + 1.0, viewport + 1.0), 0),
7523                (Point::new(10.0, 10.0), 1),
7524            ] {
7525                let mut down = PointerEvent::new(PointerEventKind::Down, point);
7526                down.button = Some(PointerButton::Primary);
7527                runtime
7528                    .handle_event(window_id, Event::Pointer(down))
7529                    .unwrap();
7530                assert_eq!(
7531                    presses.borrow()[0],
7532                    expected,
7533                    "gutter corner must not activate content"
7534                );
7535            }
7536        }
7537    }
7538
7539    #[test]
7540    fn scrollbar_gutter_reflows_content_and_releases_space_after_shrinking() {
7541        struct ResponsiveContent {
7542            short: Signal<bool>,
7543        }
7544        impl Widget for ResponsiveContent {
7545            fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
7546                let height = if ctx.observe(&self.short) {
7547                    20.0
7548                } else if constraints.max.width < 100.0 {
7549                    240.0
7550                } else {
7551                    120.0
7552                };
7553                constraints.clamp(Size::new(constraints.max.width, height))
7554            }
7555        }
7556        let short = Signal::new(false);
7557        let state = ScrollState::new();
7558        let (mut runtime, window_id) = build_runtime(
7559            SizedBox::new().size(Size::new(100.0, 80.0)).child(
7560                ScrollView::vertical(ResponsiveContent {
7561                    short: short.clone(),
7562                })
7563                .state(state.clone()),
7564            ),
7565        );
7566        runtime.render(window_id).unwrap();
7567        assert_eq!(
7568            state.viewport_size().width,
7569            100.0 - DefaultTheme::default().metrics.scroll_bar_thickness
7570        );
7571        assert_eq!(
7572            state.content_size().height,
7573            240.0,
7574            "content must reflow inside the gutter"
7575        );
7576        state.set_offset(Vector::new(0.0, 160.0));
7577        short.set(true);
7578        let output = runtime.render(window_id).unwrap();
7579        assert_eq!(state.viewport_size(), Size::new(100.0, 80.0));
7580        assert_eq!(state.current_offset(), Vector::ZERO);
7581        assert!(
7582            output
7583                .semantics
7584                .iter()
7585                .all(|node| node.role != SemanticsRole::Slider)
7586        );
7587    }
7588
7589    #[test]
7590    fn hidden_scrollbars_keep_the_full_scroll_viewport() {
7591        let state = ScrollState::new();
7592        let (output, _) = render_root(
7593            SizedBox::new().size(Size::new(100.0, 80.0)).child(
7594                ScrollView::both(FixedBox::new(Size::new(240.0, 240.0), Color::WHITE))
7595                    .state(state.clone())
7596                    .scroll_bars(false),
7597            ),
7598        );
7599        assert_eq!(state.viewport_size(), Size::new(100.0, 80.0));
7600        assert_eq!(state.max_offset(), Vector::new(140.0, 160.0));
7601        assert!(
7602            output
7603                .semantics
7604                .iter()
7605                .all(|node| node.role != SemanticsRole::Slider)
7606        );
7607    }
7608
7609    #[test]
7610    fn scroll_view_reserves_scroll_bar_space_only_when_content_overflows() {
7611        let theme = DefaultTheme::default();
7612        let (overflowing, graph) = render_root(
7613            SizedBox::new().size(Size::new(80.0, 40.0)).child(
7614                ScrollView::vertical(OverflowingBox::new(
7615                    Size::new(80.0, 120.0),
7616                    Color::rgba(0.2, 0.3, 0.7, 1.0),
7617                ))
7618                .name("Results")
7619                .theme(theme),
7620            ),
7621        );
7622
7623        let scroll_view = overflowing
7624            .semantics
7625            .iter()
7626            .find(|node| node.role == SemanticsRole::ScrollView)
7627            .expect("scroll view semantics present");
7628        let scroll_bar = overflowing
7629            .semantics
7630            .iter()
7631            .find(|node| {
7632                node.role == SemanticsRole::Slider
7633                    && node.name.as_deref() == Some("Results vertical scroll bar")
7634            })
7635            .expect("overflowing content should expose a scroll bar");
7636        assert_eq!(
7637            scroll_bar.bounds.width(),
7638            theme.metrics.scroll_bar_thickness
7639        );
7640        assert!(!scroll_bar.actions.contains(&SemanticsAction::Focus));
7641        assert!(scroll_bar.actions.contains(&SemanticsAction::SetValue));
7642        assert!(scroll_view.bounds.contains(scroll_bar.bounds.origin));
7643        assert!(scroll_bar.bounds.max_x() <= scroll_view.bounds.max_x());
7644        assert!(scroll_bar.bounds.max_y() <= scroll_view.bounds.max_y());
7645        let content = graph
7646            .nodes
7647            .iter()
7648            .find(|node| {
7649                node.bounds.height() == 120.0
7650                    && node.bounds.width() == 80.0 - theme.metrics.scroll_bar_thickness
7651            })
7652            .expect("scroll content leaves space for the bar");
7653        assert_eq!(content.bounds.max_x(), scroll_bar.bounds.x());
7654        assert_eq!(
7655            content.bounds.width() + scroll_bar.bounds.width(),
7656            scroll_view.bounds.width()
7657        );
7658
7659        let (fitting, _) = render_root(
7660            SizedBox::new().size(Size::new(80.0, 40.0)).child(
7661                ScrollView::vertical(FixedBox::new(
7662                    Size::new(80.0, 40.0),
7663                    Color::rgba(0.2, 0.3, 0.7, 1.0),
7664                ))
7665                .name("Results"),
7666            ),
7667        );
7668        assert!(
7669            fitting
7670                .semantics
7671                .iter()
7672                .all(|node| node.role != SemanticsRole::Slider),
7673            "fitting content should not expose scroll-bar chrome"
7674        );
7675    }
7676
7677    #[test]
7678    fn embedded_overlay_scroll_bar_drags_the_shared_view_state() {
7679        let state = ScrollState::new();
7680        let (mut runtime, window_id) = build_runtime(
7681            SizedBox::new().size(Size::new(80.0, 60.0)).child(
7682                ScrollView::vertical(OverflowingBox::new(
7683                    Size::new(80.0, 180.0),
7684                    Color::rgba(0.2, 0.3, 0.7, 1.0),
7685                ))
7686                .name("Results")
7687                .state(state.clone()),
7688            ),
7689        );
7690        let output = runtime.render(window_id).unwrap();
7691        let scroll_bar = output
7692            .semantics
7693            .iter()
7694            .find(|node| node.name.as_deref() == Some("Results vertical scroll bar"))
7695            .expect("embedded scroll bar present");
7696        let point = Point::new(
7697            scroll_bar.bounds.x() + scroll_bar.bounds.width() * 0.5,
7698            scroll_bar.bounds.max_y() - 1.0,
7699        );
7700        let mut down = PointerEvent::new(PointerEventKind::Down, point);
7701        down.pointer_id = 41;
7702        down.button = Some(PointerButton::Primary);
7703        down.buttons = PointerButtons::new(1);
7704        runtime
7705            .handle_event(window_id, Event::Pointer(down))
7706            .unwrap();
7707
7708        assert!(state.current_offset().y > 0.0);
7709        let _ = runtime.render(window_id).unwrap();
7710        let graph = runtime.widget_graph(window_id).unwrap();
7711        let content = graph
7712            .nodes
7713            .iter()
7714            .find(|node| {
7715                node.bounds.size
7716                    == Size::new(
7717                        80.0 - DefaultTheme::default().metrics.scroll_bar_thickness,
7718                        180.0,
7719                    )
7720            })
7721            .expect("scroll content present");
7722        assert_eq!(content.bounds.y(), -state.current_offset().y);
7723    }
7724
7725    #[test]
7726    fn overlay_scroll_bar_drag_repaints_non_retained_content_immediately() {
7727        let state = ScrollState::new();
7728        let counts = Rc::new(RefCell::new(vec![0usize]));
7729        let (mut runtime, window_id) = build_runtime(
7730            SizedBox::new().size(Size::new(80.0, 60.0)).child(
7731                ScrollView::vertical(PaintCounterBox::new(
7732                    Size::new(80.0, 180.0),
7733                    Color::rgba(0.2, 0.3, 0.7, 1.0),
7734                    Rc::clone(&counts),
7735                    0,
7736                ))
7737                .name("Results")
7738                .state(state.clone()),
7739            ),
7740        );
7741        let output = runtime.render(window_id).unwrap();
7742        assert_eq!(*counts.borrow(), vec![1]);
7743        let scroll_bar = output
7744            .semantics
7745            .iter()
7746            .find(|node| node.name.as_deref() == Some("Results vertical scroll bar"))
7747            .expect("embedded scroll bar present");
7748
7749        drag_vertical_scroll_bar(&mut runtime, window_id, scroll_bar.bounds, 42, 20.0);
7750        assert!(state.current_offset().y > 0.0);
7751        let _ = runtime.render(window_id).unwrap();
7752
7753        assert_eq!(
7754            *counts.borrow(),
7755            vec![2],
7756            "the first frame after a scroll-bar drag must repaint moved flattened content"
7757        );
7758    }
7759
7760    #[test]
7761    fn overlay_scroll_bar_drag_keeps_retained_content_transform_only() {
7762        let state = ScrollState::new();
7763        let counts = Rc::new(RefCell::new(vec![0usize]));
7764        let (mut runtime, window_id) = build_runtime(
7765            SizedBox::new().size(Size::new(80.0, 60.0)).child(
7766                ScrollView::vertical(PaintCounterBox::new(
7767                    Size::new(80.0, 180.0),
7768                    Color::rgba(0.2, 0.3, 0.7, 1.0),
7769                    Rc::clone(&counts),
7770                    0,
7771                ))
7772                .name("Retained results")
7773                .state(state.clone())
7774                .retain_content_layer(),
7775            ),
7776        );
7777        let output = runtime.render(window_id).unwrap();
7778        assert_eq!(*counts.borrow(), vec![1]);
7779        let scroll_bar = output
7780            .semantics
7781            .iter()
7782            .find(|node| node.name.as_deref() == Some("Retained results vertical scroll bar"))
7783            .expect("embedded scroll bar present");
7784
7785        drag_vertical_scroll_bar(&mut runtime, window_id, scroll_bar.bounds, 43, 20.0);
7786        assert!(state.current_offset().y > 0.0);
7787        let output = runtime.render(window_id).unwrap();
7788
7789        assert_eq!(
7790            *counts.borrow(),
7791            vec![1],
7792            "retained content should move without rebuilding its paint commands"
7793        );
7794        assert!(
7795            output
7796                .frame
7797                .layer_updates
7798                .iter()
7799                .any(|update| { update.kind == sui_scene::SceneLayerUpdateKind::Transform })
7800        );
7801    }
7802
7803    #[test]
7804    fn virtual_overlay_scroll_bar_drag_repaints_visible_content_immediately() {
7805        let state = ScrollState::new();
7806        let counts = Rc::new(RefCell::new(vec![0usize; 4]));
7807        let mut scroll = VirtualScrollView::new()
7808            .name("Virtual results")
7809            .state(state.clone());
7810        for (index, color) in [
7811            Color::rgba(0.8, 0.2, 0.2, 1.0),
7812            Color::rgba(0.2, 0.8, 0.2, 1.0),
7813            Color::rgba(0.2, 0.2, 0.8, 1.0),
7814            Color::rgba(0.8, 0.8, 0.2, 1.0),
7815        ]
7816        .into_iter()
7817        .enumerate()
7818        {
7819            scroll.push(PaintCounterBox::new(
7820                Size::new(80.0, 30.0),
7821                color,
7822                Rc::clone(&counts),
7823                index,
7824            ));
7825        }
7826        let (mut runtime, window_id) =
7827            build_runtime(SizedBox::new().size(Size::new(80.0, 80.0)).child(scroll));
7828        let output = runtime.render(window_id).unwrap();
7829        assert_eq!(*counts.borrow(), vec![1, 1, 1, 1]);
7830        let scroll_bar = output
7831            .semantics
7832            .iter()
7833            .find(|node| node.name.as_deref() == Some("Virtual results vertical scroll bar"))
7834            .expect("embedded scroll bar present");
7835
7836        drag_vertical_scroll_bar(&mut runtime, window_id, scroll_bar.bounds, 44, 20.0);
7837        assert!(state.current_offset().y > 0.0);
7838        let _ = runtime.render(window_id).unwrap();
7839
7840        assert_eq!(
7841            *counts.borrow(),
7842            vec![2, 2, 2, 2],
7843            "the first frame after a virtual scroll-bar drag must repaint visible rows"
7844        );
7845    }
7846
7847    #[test]
7848    fn both_axis_scroll_bars_reserve_space_and_share_the_corner() {
7849        let (output, graph) = render_root(
7850            SizedBox::new().size(Size::new(80.0, 40.0)).child(
7851                ScrollView::both(OverflowingBox::new(
7852                    Size::new(160.0, 120.0),
7853                    Color::rgba(0.2, 0.3, 0.7, 1.0),
7854                ))
7855                .name("Canvas"),
7856            ),
7857        );
7858
7859        let vertical = output
7860            .semantics
7861            .iter()
7862            .find(|node| node.name.as_deref() == Some("Canvas vertical scroll bar"))
7863            .expect("vertical overlay scroll bar present");
7864        let horizontal = output
7865            .semantics
7866            .iter()
7867            .find(|node| node.name.as_deref() == Some("Canvas horizontal scroll bar"))
7868            .expect("horizontal overlay scroll bar present");
7869        assert!(vertical.bounds.max_y() <= horizontal.bounds.y());
7870        assert!(horizontal.bounds.max_x() <= vertical.bounds.x());
7871
7872        let content = graph
7873            .nodes
7874            .iter()
7875            .find(|node| node.bounds.size == Size::new(160.0, 120.0))
7876            .expect("two-axis content present");
7877        assert_eq!(content.bounds.origin, Point::ZERO);
7878    }
7879
7880    #[test]
7881    fn virtual_scroll_view_overlays_a_synchronized_vertical_scroll_bar() {
7882        let state = ScrollState::new();
7883        let (output, _) = render_root(
7884            SizedBox::new().size(Size::new(80.0, 40.0)).child(
7885                VirtualScrollView::new()
7886                    .name("Timeline")
7887                    .state(state.clone())
7888                    .with_child(FixedBox::new(
7889                        Size::new(80.0, 40.0),
7890                        Color::rgba(0.2, 0.3, 0.7, 1.0),
7891                    ))
7892                    .with_child(FixedBox::new(
7893                        Size::new(80.0, 40.0),
7894                        Color::rgba(0.7, 0.3, 0.2, 1.0),
7895                    )),
7896            ),
7897        );
7898
7899        let scroll_bar = output
7900            .semantics
7901            .iter()
7902            .find(|node| node.name.as_deref() == Some("Timeline vertical scroll bar"))
7903            .expect("virtual scroll bar present");
7904        assert_eq!(
7905            scroll_bar.value,
7906            Some(SemanticsValue::Range {
7907                value: 0.0,
7908                min: 0.0,
7909                max: 40.0,
7910            })
7911        );
7912        assert_eq!(state.max_offset(), Vector::new(0.0, 40.0));
7913    }
7914
7915    #[test]
7916    fn scroll_view_auto_overflow_uses_finite_width_and_natural_height() {
7917        let seen = Rc::new(RefCell::new(Vec::new()));
7918        let (output, _) = render_root(
7919            SizedBox::new().size(Size::new(120.0, 60.0)).child(
7920                ScrollView::both(ConstraintProbe::new(
7921                    Size::new(90.0, 180.0),
7922                    Rc::clone(&seen),
7923                ))
7924                .overflow_x(Overflow::Auto)
7925                .overflow_y(Overflow::Auto),
7926            ),
7927        );
7928
7929        let constraints = seen
7930            .borrow()
7931            .last()
7932            .copied()
7933            .expect("probe should be measured");
7934        assert_eq!(
7935            constraints.max.width,
7936            120.0 - DefaultTheme::default().metrics.scroll_bar_thickness
7937        );
7938        assert!(constraints.max.height.is_infinite());
7939        assert_eq!(output.frame.viewport, Size::new(120.0, 60.0));
7940    }
7941
7942    #[test]
7943    fn scroll_view_content_extent_can_require_at_least_the_viewport() {
7944        let seen = Rc::new(RefCell::new(Vec::new()));
7945        let (_, _) = render_root(
7946            SizedBox::new().size(Size::new(120.0, 60.0)).child(
7947                ScrollView::both(ConstraintProbe::new(
7948                    Size::new(40.0, 20.0),
7949                    Rc::clone(&seen),
7950                ))
7951                .content_width(ContentExtent::AtLeastViewport)
7952                .content_height(ContentExtent::AtLeast(100.0)),
7953            ),
7954        );
7955
7956        let constraints = seen
7957            .borrow()
7958            .last()
7959            .copied()
7960            .expect("probe should be measured");
7961        assert_eq!(
7962            constraints.min,
7963            Size::new(
7964                120.0 - DefaultTheme::default().metrics.scroll_bar_thickness,
7965                100.0
7966            )
7967        );
7968        assert!(constraints.max.width.is_infinite());
7969        assert!(constraints.max.height.is_infinite());
7970    }
7971
7972    #[test]
7973    fn content_extent_normalizes_non_finite_explicit_values() {
7974        assert_eq!(
7975            ContentExtent::AtLeast(f32::NAN).resolve(80.0, 20.0),
7976            (0.0, f32::INFINITY)
7977        );
7978        assert_eq!(ContentExtent::MinContent.resolve(80.0, 24.0), (24.0, 24.0));
7979    }
7980
7981    #[test]
7982    fn vertical_scroll_view_clamps_cross_axis_after_split_arrange() {
7983        let (_, graph) = render_root(
7984            SizedBox::new().size(Size::new(240.0, 80.0)).child(
7985                SplitView::horizontal(
7986                    FixedBox::new(Size::new(40.0, 80.0), Color::rgba(0.1, 0.2, 0.3, 1.0)),
7987                    ScrollView::vertical(Padding::all(
7988                        8.0,
7989                        Stack::vertical()
7990                            .alignment(Alignment::Stretch)
7991                            .with_child(FixedBox::new(
7992                                Size::new(400.0, 32.0),
7993                                Color::rgba(0.4, 0.5, 0.6, 1.0),
7994                            )),
7995                    )),
7996                )
7997                .ratio(0.5)
7998                .min_first(40.0)
7999                .min_second(40.0)
8000                .divider_thickness(8.0),
8001            ),
8002        );
8003
8004        let content = graph
8005            .nodes
8006            .iter()
8007            .find(|node| {
8008                (node.bounds.x() - 132.0).abs() < 0.001
8009                    && (node.bounds.y() - 8.0).abs() < 0.001
8010                    && (node.bounds.height() - 32.0).abs() < 0.001
8011            })
8012            .expect("scroll content child should be arranged inside the narrow pane");
8013        assert_eq!(content.bounds.width(), 100.0);
8014    }
8015
8016    #[test]
8017    fn scroll_view_visible_overflow_does_not_scroll_or_use_scroll_layer() {
8018        let (mut runtime, window_id) = build_runtime(
8019            SizedBox::new().size(Size::new(80.0, 40.0)).child(
8020                ScrollView::vertical(OverflowingBox::new(
8021                    Size::new(80.0, 120.0),
8022                    Color::rgba(0.2, 0.3, 0.7, 1.0),
8023                ))
8024                .overflow(Overflow::Visible),
8025            ),
8026        );
8027
8028        let output = runtime.render(window_id).unwrap();
8029        let scroll_id = output
8030            .semantics
8031            .iter()
8032            .find(|node| node.role == SemanticsRole::ScrollView)
8033            .expect("scroll view semantics present")
8034            .id;
8035        let descriptor =
8036            layer_descriptor_for(&output, scroll_id).expect("scroll view layer present");
8037        assert_eq!(descriptor.composition_mode, LayerCompositionMode::Normal);
8038
8039        let mut scroll = PointerEvent::new(PointerEventKind::Scroll, Point::new(20.0, 20.0));
8040        scroll.scroll_delta = Some(ScrollDelta::Pixels(Vector::new(0.0, -32.0)));
8041        runtime
8042            .handle_event(window_id, Event::Pointer(scroll))
8043            .unwrap();
8044        let _ = runtime.render(window_id).unwrap();
8045        let graph = runtime.widget_graph(window_id).unwrap();
8046        let content = graph
8047            .nodes
8048            .iter()
8049            .find(|node| node.bounds.width() == 80.0 && node.bounds.height() == 120.0)
8050            .expect("visible overflow content present");
8051        assert_eq!(content.bounds, Rect::new(0.0, 0.0, 80.0, 120.0));
8052    }
8053
8054    #[test]
8055    fn virtual_scroll_view_uses_scroll_layer_metadata() {
8056        let (output, _) = render_root(
8057            SizedBox::new().size(Size::new(80.0, 40.0)).child(
8058                VirtualScrollView::new()
8059                    .with_child(FixedBox::new(
8060                        Size::new(80.0, 40.0),
8061                        Color::rgba(0.2, 0.3, 0.7, 1.0),
8062                    ))
8063                    .with_child(FixedBox::new(
8064                        Size::new(80.0, 40.0),
8065                        Color::rgba(0.7, 0.3, 0.2, 1.0),
8066                    )),
8067            ),
8068        );
8069
8070        let scroll_id = output
8071            .semantics
8072            .iter()
8073            .find(|node| node.role == SemanticsRole::ScrollView)
8074            .expect("virtual scroll view semantics present")
8075            .id;
8076        let descriptor =
8077            layer_descriptor_for(&output, scroll_id).expect("virtual scroll view layer present");
8078
8079        assert_eq!(descriptor.composition_mode, LayerCompositionMode::Scroll);
8080    }
8081
8082    #[test]
8083    fn virtual_scroll_state_scroll_to_item_aligns_item_at_viewport_top() {
8084        let state = ScrollState::new();
8085        assert!(state.scroll_to_item(2));
8086
8087        let (output, _) = render_root(
8088            SizedBox::new().size(Size::new(80.0, 40.0)).child(
8089                VirtualScrollView::new()
8090                    .state(state.clone())
8091                    .with_child(SemanticRegion::new(
8092                        "Item 0",
8093                        FixedBox::new(Size::new(80.0, 20.0), Color::rgba(0.8, 0.2, 0.2, 1.0)),
8094                    ))
8095                    .with_child(SemanticRegion::new(
8096                        "Item 1",
8097                        FixedBox::new(Size::new(80.0, 20.0), Color::rgba(0.2, 0.8, 0.2, 1.0)),
8098                    ))
8099                    .with_child(SemanticRegion::new(
8100                        "Item 2",
8101                        FixedBox::new(Size::new(80.0, 40.0), Color::rgba(0.2, 0.2, 0.8, 1.0)),
8102                    )),
8103            ),
8104        );
8105
8106        let viewport = output
8107            .semantics
8108            .iter()
8109            .find(|node| node.role == SemanticsRole::ScrollView)
8110            .expect("virtual scroll view semantics present");
8111        let target = output
8112            .semantics
8113            .iter()
8114            .find(|node| node.name.as_deref() == Some("Item 2"))
8115            .expect("target item semantics present");
8116
8117        assert_eq!(state.current_offset(), Vector::new(0.0, 40.0));
8118        assert_eq!(target.bounds.y(), viewport.bounds.y());
8119    }
8120
8121    #[test]
8122    fn virtual_scroll_state_reports_items_at_content_offsets() {
8123        let state = ScrollState::new();
8124        assert_eq!(state.first_visible_item(), None);
8125        assert!(state.scroll_to_item(1));
8126
8127        let _ = render_root(
8128            SizedBox::new().size(Size::new(80.0, 40.0)).child(
8129                VirtualScrollView::new()
8130                    .state(state.clone())
8131                    .gap(4.0)
8132                    .with_child(FixedBox::new(
8133                        Size::new(80.0, 20.0),
8134                        Color::rgba(0.8, 0.2, 0.2, 1.0),
8135                    ))
8136                    .with_child(FixedBox::new(
8137                        Size::new(80.0, 30.0),
8138                        Color::rgba(0.2, 0.8, 0.2, 1.0),
8139                    ))
8140                    .with_child(FixedBox::new(
8141                        Size::new(80.0, 40.0),
8142                        Color::rgba(0.2, 0.2, 0.8, 1.0),
8143                    )),
8144            ),
8145        );
8146
8147        assert_eq!(state.virtual_item_offset(1), Some(24.0));
8148        assert_eq!(state.virtual_item_offset(2), Some(58.0));
8149        assert_eq!(state.virtual_item_offset(3), None);
8150        assert_eq!(state.first_visible_item(), Some(1));
8151        assert_eq!(state.virtual_item_at(0.0), Some(0));
8152        assert_eq!(state.virtual_item_at(23.9), Some(0));
8153        assert_eq!(state.virtual_item_at(24.0), Some(1));
8154        assert_eq!(state.virtual_item_at(-10.0), Some(0));
8155        assert_eq!(state.virtual_item_at(500.0), Some(2));
8156    }
8157
8158    #[test]
8159    fn virtual_scroll_view_paints_only_visible_children() {
8160        let counts = Rc::new(RefCell::new(vec![0usize; 4]));
8161        let (mut runtime, window_id) = build_runtime(
8162            SizedBox::new().size(Size::new(80.0, 40.0)).child(
8163                VirtualScrollView::new()
8164                    .with_child(PaintCounterBox::new(
8165                        Size::new(80.0, 30.0),
8166                        Color::rgba(0.8, 0.2, 0.2, 1.0),
8167                        Rc::clone(&counts),
8168                        0,
8169                    ))
8170                    .with_child(PaintCounterBox::new(
8171                        Size::new(80.0, 30.0),
8172                        Color::rgba(0.2, 0.8, 0.2, 1.0),
8173                        Rc::clone(&counts),
8174                        1,
8175                    ))
8176                    .with_child(PaintCounterBox::new(
8177                        Size::new(80.0, 30.0),
8178                        Color::rgba(0.2, 0.2, 0.8, 1.0),
8179                        Rc::clone(&counts),
8180                        2,
8181                    ))
8182                    .with_child(PaintCounterBox::new(
8183                        Size::new(80.0, 30.0),
8184                        Color::rgba(0.8, 0.8, 0.2, 1.0),
8185                        Rc::clone(&counts),
8186                        3,
8187                    )),
8188            ),
8189        );
8190
8191        let _ = runtime.render(window_id).unwrap();
8192        // The visible window extends by 75% of the viewport above and below,
8193        // so the third item is included in the initial overdraw buffer.
8194        assert_eq!(*counts.borrow(), vec![1, 1, 1, 0]);
8195
8196        let mut scroll = PointerEvent::new(PointerEventKind::Scroll, Point::new(20.0, 20.0));
8197        scroll.scroll_delta = Some(ScrollDelta::Pixels(Vector::new(0.0, -32.0)));
8198        runtime
8199            .handle_event(window_id, Event::Pointer(scroll))
8200            .unwrap();
8201        let _ = runtime.render(window_id).unwrap();
8202
8203        // After scrolling 32px, the overdraw buffer still includes item 0 and
8204        // extends far enough to bring item 3 into the painted range.
8205        assert_eq!(*counts.borrow(), vec![2, 2, 2, 1]);
8206    }
8207
8208    #[test]
8209    fn scroll_view_emits_transform_updates_after_scroll_offset_changes() {
8210        let counts = Rc::new(RefCell::new(vec![0usize; 1]));
8211        let (mut runtime, window_id) = build_runtime(
8212            SizedBox::new().size(Size::new(80.0, 40.0)).child(
8213                ScrollView::vertical(PaintCounterBox::new(
8214                    Size::new(80.0, 120.0),
8215                    Color::rgba(0.2, 0.3, 0.7, 1.0),
8216                    Rc::clone(&counts),
8217                    0,
8218                ))
8219                .retain_content_layer(),
8220            ),
8221        );
8222
8223        let _ = runtime.render(window_id).unwrap();
8224        assert_eq!(*counts.borrow(), vec![1]);
8225
8226        let mut scroll = PointerEvent::new(PointerEventKind::Scroll, Point::new(20.0, 20.0));
8227        scroll.scroll_delta = Some(ScrollDelta::Pixels(Vector::new(0.0, -32.0)));
8228        runtime
8229            .handle_event(window_id, Event::Pointer(scroll))
8230            .unwrap();
8231        let output = runtime.render(window_id).unwrap();
8232
8233        assert_eq!(*counts.borrow(), vec![1]);
8234        assert!(
8235            output
8236                .frame
8237                .layer_updates
8238                .iter()
8239                .any(|update| update.kind == sui_scene::SceneLayerUpdateKind::Transform)
8240        );
8241    }
8242
8243    #[test]
8244    fn split_view_scroll_without_paint_still_updates_runtime_scene() {
8245        let (mut runtime, window_id) = build_runtime(
8246            SizedBox::new().size(Size::new(360.0, 220.0)).child(
8247                SplitView::horizontal(
8248                    ScrollViewNoPaint::vertical(
8249                        Stack::vertical()
8250                            .with_child(FixedBox::new(
8251                                Size::new(220.0, 120.0),
8252                                Color::rgba(0.82, 0.36, 0.18, 1.0),
8253                            ))
8254                            .with_child(FixedBox::new(
8255                                Size::new(220.0, 120.0),
8256                                Color::rgba(0.18, 0.54, 0.82, 1.0),
8257                            ))
8258                            .with_child(FixedBox::new(
8259                                Size::new(220.0, 120.0),
8260                                Color::rgba(0.24, 0.72, 0.36, 1.0),
8261                            )),
8262                    )
8263                    .name("NoPaint scroll"),
8264                    SizedBox::new().size(Size::new(120.0, 220.0)),
8265                )
8266                .ratio(0.68),
8267            ),
8268        );
8269
8270        let before = runtime.render(window_id).unwrap();
8271
8272        let mut scroll = PointerEvent::new(PointerEventKind::Scroll, Point::new(48.0, 96.0));
8273        scroll.scroll_delta = Some(ScrollDelta::Pixels(Vector::new(0.0, -72.0)));
8274        runtime
8275            .handle_event(window_id, Event::Pointer(scroll))
8276            .unwrap();
8277
8278        let after = runtime.render(window_id).unwrap();
8279        let graph = runtime.widget_graph(window_id).unwrap();
8280
8281        assert!(graph.nodes.iter().any(|node| node.bounds.y() < 0.0));
8282        assert_ne!(before.frame.scene, after.frame.scene);
8283        assert!(!after.frame.layer_updates.is_empty());
8284    }
8285
8286    #[test]
8287    fn virtual_scroll_view_repaints_exposed_strip_while_visible_range_is_unchanged() {
8288        // Use a wider viewport (80px) so the overdraw buffer (35% = 28px)
8289        // is large enough that a small 4px scroll does not bring new items
8290        // into the visible range.
8291        let counts = Rc::new(RefCell::new(vec![0usize; 4]));
8292        let (mut runtime, window_id) = build_runtime(
8293            SizedBox::new().size(Size::new(80.0, 80.0)).child(
8294                VirtualScrollView::new()
8295                    .with_child(PaintCounterBox::new(
8296                        Size::new(80.0, 30.0),
8297                        Color::rgba(0.8, 0.2, 0.2, 1.0),
8298                        Rc::clone(&counts),
8299                        0,
8300                    ))
8301                    .with_child(PaintCounterBox::new(
8302                        Size::new(80.0, 30.0),
8303                        Color::rgba(0.2, 0.8, 0.2, 1.0),
8304                        Rc::clone(&counts),
8305                        1,
8306                    ))
8307                    .with_child(PaintCounterBox::new(
8308                        Size::new(80.0, 30.0),
8309                        Color::rgba(0.2, 0.2, 0.8, 1.0),
8310                        Rc::clone(&counts),
8311                        2,
8312                    ))
8313                    .with_child(PaintCounterBox::new(
8314                        Size::new(80.0, 30.0),
8315                        Color::rgba(0.8, 0.8, 0.2, 1.0),
8316                        Rc::clone(&counts),
8317                        3,
8318                    )),
8319            ),
8320        );
8321
8322        let _ = runtime.render(window_id).unwrap();
8323        // All 4 items fit within the 80px viewport + 28px overdraw = 108px.
8324        assert_eq!(*counts.borrow(), vec![1, 1, 1, 1]);
8325
8326        let mut scroll = PointerEvent::new(PointerEventKind::Scroll, Point::new(20.0, 20.0));
8327        scroll.scroll_delta = Some(ScrollDelta::Pixels(Vector::new(0.0, -4.0)));
8328        runtime
8329            .handle_event(window_id, Event::Pointer(scroll))
8330            .unwrap();
8331        let output = runtime.render(window_id).unwrap();
8332
8333        // A small 4px scroll should not change the visible range when
8334        // the overdraw buffer covers all items, but it still needs to repaint
8335        // the newly exposed strip so equivalent final offsets stay history-independent.
8336        assert_eq!(*counts.borrow(), vec![2, 2, 2, 2]);
8337        assert!(output.frame.layer_updates.iter().any(|update| {
8338            update.kind == sui_scene::SceneLayerUpdateKind::Content
8339                && update.damage
8340                    == Some(Rect::new(
8341                        0.0,
8342                        76.0,
8343                        80.0 - DefaultTheme::default().metrics.scroll_bar_thickness,
8344                        4.0,
8345                    ))
8346        }));
8347    }
8348
8349    #[test]
8350    fn virtual_scroll_view_repaints_when_a_visible_layered_child_changes_height() {
8351        let counts = Rc::new(RefCell::new(vec![0usize; 2]));
8352        let (mut runtime, window_id) = build_runtime(
8353            SizedBox::new().size(Size::new(80.0, 80.0)).child(
8354                VirtualScrollView::new()
8355                    .with_child(ExpandingLayerBox::new(
8356                        Size::new(80.0, 30.0),
8357                        Size::new(80.0, 60.0),
8358                        Color::rgba(0.7, 0.3, 0.2, 1.0),
8359                        Rc::clone(&counts),
8360                        0,
8361                    ))
8362                    .with_child(PaintCounterBox::new(
8363                        Size::new(80.0, 30.0),
8364                        Color::rgba(0.2, 0.5, 0.8, 1.0),
8365                        Rc::clone(&counts),
8366                        1,
8367                    )),
8368            ),
8369        );
8370
8371        let _ = runtime.render(window_id).unwrap();
8372        assert_eq!(*counts.borrow(), vec![1, 1]);
8373
8374        let pointer = PointerEvent::new(PointerEventKind::Down, Point::new(20.0, 20.0));
8375        runtime
8376            .handle_event(window_id, Event::Pointer(pointer))
8377            .unwrap();
8378        let _ = runtime.render(window_id).unwrap();
8379
8380        assert_eq!(*counts.borrow(), vec![2, 2]);
8381    }
8382
8383    #[test]
8384    fn nested_scroll_views_scroll_the_inner_region_first() {
8385        let (mut runtime, window_id) = build_runtime(
8386            SizedBox::new()
8387                .size(Size::new(80.0, 80.0))
8388                .child(ScrollView::vertical(
8389                    Stack::vertical()
8390                        .gap(8.0)
8391                        .with_child(FixedBox::new(
8392                            Size::new(80.0, 32.0),
8393                            Color::rgba(0.8, 0.2, 0.2, 1.0),
8394                        ))
8395                        .with_child(SizedBox::new().height(40.0).child(ScrollView::vertical(
8396                            FixedBox::new(Size::new(80.0, 120.0), Color::rgba(0.2, 0.7, 0.3, 1.0)),
8397                        )))
8398                        .with_child(FixedBox::new(
8399                            Size::new(80.0, 140.0),
8400                            Color::rgba(0.2, 0.3, 0.8, 1.0),
8401                        )),
8402                )),
8403        );
8404
8405        let _ = runtime.render(window_id).unwrap();
8406        let mut scroll = PointerEvent::new(PointerEventKind::Scroll, Point::new(20.0, 52.0));
8407        scroll.scroll_delta = Some(ScrollDelta::Pixels(Vector::new(0.0, -24.0)));
8408        runtime
8409            .handle_event(window_id, Event::Pointer(scroll))
8410            .unwrap();
8411        let output = runtime.render(window_id).unwrap();
8412        let graph = runtime.widget_graph(window_id).unwrap();
8413
8414        let outer_content = graph
8415            .nodes
8416            .iter()
8417            .find(|node| {
8418                node.bounds.width() == 80.0 - DefaultTheme::default().metrics.scroll_bar_thickness
8419                    && node.bounds.height() == 228.0
8420            })
8421            .expect("outer scroll content present");
8422        let inner_content = graph
8423            .nodes
8424            .iter()
8425            .find(|node| {
8426                node.bounds.width()
8427                    == 80.0 - 2.0 * DefaultTheme::default().metrics.scroll_bar_thickness
8428                    && node.bounds.height() == 120.0
8429            })
8430            .expect("inner scroll content present");
8431
8432        assert_eq!(outer_content.bounds.y(), 0.0);
8433        assert_eq!(inner_content.bounds.y(), 16.0);
8434        assert!(!output.frame.layer_updates.is_empty());
8435    }
8436
8437    #[test]
8438    fn nested_scroll_views_fall_back_to_parent_at_inner_limit() {
8439        let (mut runtime, window_id) = build_runtime(
8440            SizedBox::new()
8441                .size(Size::new(80.0, 80.0))
8442                .child(ScrollView::vertical(
8443                    Stack::vertical()
8444                        .gap(8.0)
8445                        .with_child(FixedBox::new(
8446                            Size::new(80.0, 32.0),
8447                            Color::rgba(0.8, 0.2, 0.2, 1.0),
8448                        ))
8449                        .with_child(SizedBox::new().height(40.0).child(ScrollView::vertical(
8450                            FixedBox::new(Size::new(80.0, 120.0), Color::rgba(0.2, 0.7, 0.3, 1.0)),
8451                        )))
8452                        .with_child(FixedBox::new(
8453                            Size::new(80.0, 140.0),
8454                            Color::rgba(0.2, 0.3, 0.8, 1.0),
8455                        )),
8456                )),
8457        );
8458
8459        let _ = runtime.render(window_id).unwrap();
8460
8461        let mut first = PointerEvent::new(PointerEventKind::Scroll, Point::new(20.0, 52.0));
8462        first.scroll_delta = Some(ScrollDelta::Pixels(Vector::new(0.0, -200.0)));
8463        runtime
8464            .handle_event(window_id, Event::Pointer(first))
8465            .unwrap();
8466        let _ = runtime.render(window_id).unwrap();
8467
8468        let mut second = PointerEvent::new(PointerEventKind::Scroll, Point::new(20.0, 52.0));
8469        second.scroll_delta = Some(ScrollDelta::Pixels(Vector::new(0.0, -24.0)));
8470        runtime
8471            .handle_event(window_id, Event::Pointer(second))
8472            .unwrap();
8473        let _ = runtime.render(window_id).unwrap();
8474        let graph = runtime.widget_graph(window_id).unwrap();
8475
8476        let outer_content = graph
8477            .nodes
8478            .iter()
8479            .find(|node| {
8480                node.bounds.width() == 80.0 - DefaultTheme::default().metrics.scroll_bar_thickness
8481                    && node.bounds.height() == 228.0
8482            })
8483            .expect("outer scroll content present");
8484        let inner_content = graph
8485            .nodes
8486            .iter()
8487            .find(|node| {
8488                node.bounds.width()
8489                    == 80.0 - 2.0 * DefaultTheme::default().metrics.scroll_bar_thickness
8490                    && node.bounds.height() == 120.0
8491            })
8492            .expect("inner scroll content present");
8493
8494        assert_eq!(inner_content.bounds.y(), -64.0);
8495        assert_eq!(outer_content.bounds.y(), -24.0);
8496    }
8497
8498    #[test]
8499    fn scroll_view_touch_drag_scrolls_content_after_drag_threshold() {
8500        let state = ScrollState::new();
8501        let (mut runtime, window_id) = build_runtime(
8502            SizedBox::new().size(Size::new(80.0, 40.0)).child(
8503                ScrollView::vertical(OverflowingBox::new(
8504                    Size::new(80.0, 120.0),
8505                    Color::rgba(0.2, 0.3, 0.7, 1.0),
8506                ))
8507                .state(state.clone()),
8508            ),
8509        );
8510        let _ = runtime.render(window_id).unwrap();
8511
8512        runtime
8513            .handle_event(
8514                window_id,
8515                Event::Pointer(touch_pointer(
8516                    PointerEventKind::Down,
8517                    7,
8518                    Point::new(20.0, 30.0),
8519                    Vector::ZERO,
8520                )),
8521            )
8522            .unwrap();
8523        runtime
8524            .handle_event(
8525                window_id,
8526                Event::Pointer(touch_pointer(
8527                    PointerEventKind::Move,
8528                    7,
8529                    Point::new(20.0, 6.0),
8530                    Vector::new(0.0, -24.0),
8531                )),
8532            )
8533            .unwrap();
8534
8535        assert_eq!(state.current_offset(), Vector::new(0.0, 24.0));
8536        runtime
8537            .handle_event(
8538                window_id,
8539                Event::Pointer(touch_pointer(
8540                    PointerEventKind::Up,
8541                    7,
8542                    Point::new(20.0, 6.0),
8543                    Vector::ZERO,
8544                )),
8545            )
8546            .unwrap();
8547    }
8548
8549    #[test]
8550    fn touch_move_below_threshold_or_from_another_pointer_does_not_scroll() {
8551        let state = ScrollState::new();
8552        let (mut runtime, window_id) = build_runtime(
8553            SizedBox::new().size(Size::new(80.0, 40.0)).child(
8554                ScrollView::vertical(OverflowingBox::new(
8555                    Size::new(80.0, 120.0),
8556                    Color::rgba(0.2, 0.3, 0.7, 1.0),
8557                ))
8558                .state(state.clone()),
8559            ),
8560        );
8561        let _ = runtime.render(window_id).unwrap();
8562
8563        runtime
8564            .handle_event(
8565                window_id,
8566                Event::Pointer(touch_pointer(
8567                    PointerEventKind::Down,
8568                    1,
8569                    Point::new(20.0, 20.0),
8570                    Vector::ZERO,
8571                )),
8572            )
8573            .unwrap();
8574        runtime
8575            .handle_event(
8576                window_id,
8577                Event::Pointer(touch_pointer(
8578                    PointerEventKind::Move,
8579                    1,
8580                    Point::new(20.0, 17.0),
8581                    Vector::new(0.0, -3.0),
8582                )),
8583            )
8584            .unwrap();
8585        runtime
8586            .handle_event(
8587                window_id,
8588                Event::Pointer(touch_pointer(
8589                    PointerEventKind::Move,
8590                    2,
8591                    Point::new(20.0, 4.0),
8592                    Vector::new(0.0, -16.0),
8593                )),
8594            )
8595            .unwrap();
8596
8597        assert_eq!(state.current_offset(), Vector::ZERO);
8598    }
8599
8600    #[test]
8601    fn virtual_scroll_view_supports_touch_drag_and_cancelled_gesture_recovery() {
8602        let state = ScrollState::new();
8603        let (mut runtime, window_id) = build_runtime(
8604            SizedBox::new().size(Size::new(80.0, 40.0)).child(
8605                VirtualScrollView::new()
8606                    .state(state.clone())
8607                    .with_child(FixedBox::new(
8608                        Size::new(80.0, 40.0),
8609                        Color::rgba(0.2, 0.3, 0.7, 1.0),
8610                    ))
8611                    .with_child(FixedBox::new(
8612                        Size::new(80.0, 40.0),
8613                        Color::rgba(0.7, 0.3, 0.2, 1.0),
8614                    ))
8615                    .with_child(FixedBox::new(
8616                        Size::new(80.0, 40.0),
8617                        Color::rgba(0.3, 0.7, 0.2, 1.0),
8618                    )),
8619            ),
8620        );
8621        let _ = runtime.render(window_id).unwrap();
8622
8623        for pointer in [
8624            touch_pointer(
8625                PointerEventKind::Down,
8626                3,
8627                Point::new(20.0, 30.0),
8628                Vector::ZERO,
8629            ),
8630            touch_pointer(
8631                PointerEventKind::Move,
8632                3,
8633                Point::new(20.0, 10.0),
8634                Vector::new(0.0, -20.0),
8635            ),
8636            touch_pointer(
8637                PointerEventKind::Cancel,
8638                3,
8639                Point::new(20.0, 10.0),
8640                Vector::ZERO,
8641            ),
8642            touch_pointer(
8643                PointerEventKind::Down,
8644                4,
8645                Point::new(20.0, 30.0),
8646                Vector::ZERO,
8647            ),
8648            touch_pointer(
8649                PointerEventKind::Move,
8650                4,
8651                Point::new(20.0, 18.0),
8652                Vector::new(0.0, -12.0),
8653            ),
8654        ] {
8655            runtime
8656                .handle_event(window_id, Event::Pointer(pointer))
8657                .unwrap();
8658        }
8659
8660        assert_eq!(state.current_offset(), Vector::new(0.0, 32.0));
8661    }
8662
8663    #[test]
8664    fn boundary_touch_gestures_keep_capture_for_reversal_and_accept_fresh_down() {
8665        let state = ScrollState::new();
8666        let (mut runtime, window_id) = build_runtime(
8667            SizedBox::new().size(Size::new(80.0, 40.0)).child(
8668                ScrollView::vertical(OverflowingBox::new(
8669                    Size::new(80.0, 120.0),
8670                    Color::rgba(0.2, 0.3, 0.7, 1.0),
8671                ))
8672                .state(state.clone()),
8673            ),
8674        );
8675        let _ = runtime.render(window_id).unwrap();
8676
8677        for pointer in [
8678            touch_pointer(
8679                PointerEventKind::Down,
8680                20,
8681                Point::new(20.0, 30.0),
8682                Vector::ZERO,
8683            ),
8684            touch_pointer(
8685                PointerEventKind::Move,
8686                20,
8687                Point::new(20.0, 18.0),
8688                Vector::new(0.0, -200.0),
8689            ),
8690            touch_pointer(
8691                PointerEventKind::Up,
8692                20,
8693                Point::new(20.0, -170.0),
8694                Vector::ZERO,
8695            ),
8696            touch_pointer(
8697                PointerEventKind::Down,
8698                21,
8699                Point::new(20.0, 30.0),
8700                Vector::ZERO,
8701            ),
8702            touch_pointer(
8703                PointerEventKind::Move,
8704                21,
8705                Point::new(20.0, 18.0),
8706                Vector::new(0.0, -12.0),
8707            ),
8708            touch_pointer(
8709                PointerEventKind::Move,
8710                21,
8711                Point::new(20.0, 30.0),
8712                Vector::new(0.0, 12.0),
8713            ),
8714        ] {
8715            runtime
8716                .handle_event(window_id, Event::Pointer(pointer))
8717                .unwrap();
8718        }
8719        assert_eq!(
8720            state.current_offset(),
8721            Vector::new(0.0, 68.0),
8722            "a captured pan should reverse away from a hard boundary"
8723        );
8724
8725        for pointer in [
8726            touch_pointer(
8727                PointerEventKind::Down,
8728                21,
8729                Point::new(20.0, 18.0),
8730                Vector::ZERO,
8731            ),
8732            touch_pointer(
8733                PointerEventKind::Move,
8734                21,
8735                Point::new(20.0, 30.0),
8736                Vector::new(0.0, 12.0),
8737            ),
8738        ] {
8739            runtime
8740                .handle_event(window_id, Event::Pointer(pointer))
8741                .unwrap();
8742        }
8743        assert_eq!(state.current_offset(), Vector::new(0.0, 56.0));
8744
8745        let virtual_state = ScrollState::new();
8746        let (mut virtual_runtime, virtual_window) = build_runtime(
8747            SizedBox::new().size(Size::new(80.0, 40.0)).child(
8748                VirtualScrollView::new()
8749                    .state(virtual_state.clone())
8750                    .with_child(FixedBox::new(
8751                        Size::new(80.0, 40.0),
8752                        Color::rgba(0.2, 0.3, 0.7, 1.0),
8753                    ))
8754                    .with_child(FixedBox::new(
8755                        Size::new(80.0, 40.0),
8756                        Color::rgba(0.7, 0.3, 0.2, 1.0),
8757                    ))
8758                    .with_child(FixedBox::new(
8759                        Size::new(80.0, 40.0),
8760                        Color::rgba(0.3, 0.7, 0.2, 1.0),
8761                    )),
8762            ),
8763        );
8764        let _ = virtual_runtime.render(virtual_window).unwrap();
8765
8766        for pointer in [
8767            touch_pointer(
8768                PointerEventKind::Down,
8769                30,
8770                Point::new(20.0, 30.0),
8771                Vector::ZERO,
8772            ),
8773            touch_pointer(
8774                PointerEventKind::Move,
8775                30,
8776                Point::new(20.0, 18.0),
8777                Vector::new(0.0, -200.0),
8778            ),
8779            touch_pointer(
8780                PointerEventKind::Up,
8781                30,
8782                Point::new(20.0, -170.0),
8783                Vector::ZERO,
8784            ),
8785            touch_pointer(
8786                PointerEventKind::Down,
8787                31,
8788                Point::new(20.0, 30.0),
8789                Vector::ZERO,
8790            ),
8791            touch_pointer(
8792                PointerEventKind::Move,
8793                31,
8794                Point::new(20.0, 18.0),
8795                Vector::new(0.0, -12.0),
8796            ),
8797            touch_pointer(
8798                PointerEventKind::Move,
8799                31,
8800                Point::new(20.0, 30.0),
8801                Vector::new(0.0, 12.0),
8802            ),
8803        ] {
8804            virtual_runtime
8805                .handle_event(virtual_window, Event::Pointer(pointer))
8806                .unwrap();
8807        }
8808        assert_eq!(virtual_state.current_offset(), Vector::new(0.0, 68.0));
8809
8810        for pointer in [
8811            touch_pointer(
8812                PointerEventKind::Down,
8813                31,
8814                Point::new(20.0, 18.0),
8815                Vector::ZERO,
8816            ),
8817            touch_pointer(
8818                PointerEventKind::Move,
8819                31,
8820                Point::new(20.0, 30.0),
8821                Vector::new(0.0, 12.0),
8822            ),
8823        ] {
8824            virtual_runtime
8825                .handle_event(virtual_window, Event::Pointer(pointer))
8826                .unwrap();
8827        }
8828        assert_eq!(virtual_state.current_offset(), Vector::new(0.0, 56.0));
8829    }
8830
8831    #[test]
8832    fn nested_touch_scroll_hands_off_from_inner_limit_to_parent() {
8833        let outer_state = ScrollState::new();
8834        let inner_state = ScrollState::new();
8835        let (mut runtime, window_id) = build_runtime(
8836            SizedBox::new().size(Size::new(80.0, 80.0)).child(
8837                ScrollView::vertical(
8838                    Stack::vertical()
8839                        .gap(8.0)
8840                        .with_child(FixedBox::new(
8841                            Size::new(80.0, 32.0),
8842                            Color::rgba(0.8, 0.2, 0.2, 1.0),
8843                        ))
8844                        .with_child(
8845                            SizedBox::new().height(40.0).child(
8846                                ScrollView::vertical(FixedBox::new(
8847                                    Size::new(80.0, 120.0),
8848                                    Color::rgba(0.2, 0.7, 0.3, 1.0),
8849                                ))
8850                                .state(inner_state.clone()),
8851                            ),
8852                        )
8853                        .with_child(FixedBox::new(
8854                            Size::new(80.0, 140.0),
8855                            Color::rgba(0.2, 0.3, 0.8, 1.0),
8856                        )),
8857                )
8858                .state(outer_state.clone()),
8859            ),
8860        );
8861        let _ = runtime.render(window_id).unwrap();
8862
8863        for pointer in [
8864            touch_pointer(
8865                PointerEventKind::Down,
8866                9,
8867                Point::new(20.0, 52.0),
8868                Vector::ZERO,
8869            ),
8870            touch_pointer(
8871                PointerEventKind::Move,
8872                9,
8873                Point::new(20.0, 44.0),
8874                Vector::new(0.0, -8.0),
8875            ),
8876            touch_pointer(
8877                PointerEventKind::Move,
8878                9,
8879                Point::new(20.0, -56.0),
8880                Vector::new(0.0, -100.0),
8881            ),
8882            touch_pointer(
8883                PointerEventKind::Move,
8884                9,
8885                Point::new(20.0, -80.0),
8886                Vector::new(0.0, -24.0),
8887            ),
8888            touch_pointer(
8889                PointerEventKind::Up,
8890                9,
8891                Point::new(20.0, -80.0),
8892                Vector::ZERO,
8893            ),
8894        ] {
8895            runtime
8896                .handle_event(window_id, Event::Pointer(pointer))
8897                .unwrap();
8898        }
8899
8900        assert_eq!(inner_state.current_offset(), Vector::new(0.0, 80.0));
8901        assert_eq!(outer_state.current_offset(), Vector::new(0.0, 24.0));
8902        assert_eq!(runtime.pointer_capture_target(window_id, 9).unwrap(), None);
8903    }
8904
8905    /// Drag touch `pointer_id` up by `step` pixels each sixtieth of a second,
8906    /// `moves` times, starting at `time`; returns the time of the last move.
8907    fn touch_swipe_up(
8908        runtime: &mut Runtime,
8909        window_id: sui_core::WindowId,
8910        pointer_id: u64,
8911        start: Point,
8912        step: f32,
8913        moves: usize,
8914        time: f64,
8915    ) -> (f64, Point) {
8916        runtime.tick(time);
8917        runtime
8918            .handle_event(
8919                window_id,
8920                Event::Pointer(touch_pointer(
8921                    PointerEventKind::Down,
8922                    pointer_id,
8923                    start,
8924                    Vector::ZERO,
8925                )),
8926            )
8927            .unwrap();
8928        let mut time = time;
8929        let mut position = start;
8930        for _ in 0..moves {
8931            time += 1.0 / 60.0;
8932            position = Point::new(position.x, position.y - step);
8933            runtime.tick(time);
8934            runtime
8935                .handle_event(
8936                    window_id,
8937                    Event::Pointer(touch_pointer(
8938                        PointerEventKind::Move,
8939                        pointer_id,
8940                        position,
8941                        Vector::new(0.0, -step),
8942                    )),
8943                )
8944                .unwrap();
8945        }
8946        (time, position)
8947    }
8948
8949    fn touch_up(
8950        runtime: &mut Runtime,
8951        window_id: sui_core::WindowId,
8952        pointer_id: u64,
8953        position: Point,
8954        time: f64,
8955    ) {
8956        runtime.tick(time);
8957        runtime
8958            .handle_event(
8959                window_id,
8960                Event::Pointer(touch_pointer(
8961                    PointerEventKind::Up,
8962                    pointer_id,
8963                    position,
8964                    Vector::ZERO,
8965                )),
8966            )
8967            .unwrap();
8968    }
8969
8970    /// Run animation frames from `time` for `seconds`; returns the end time.
8971    fn run_frames(runtime: &mut Runtime, time: f64, seconds: f64) -> f64 {
8972        let mut now = time;
8973        while now < time + seconds {
8974            now += 1.0 / 120.0;
8975            runtime.tick(now);
8976            handle_ready_events(runtime);
8977        }
8978        now
8979    }
8980
8981    #[test]
8982    fn touch_fling_coasts_after_release_and_slows_to_a_stop() {
8983        let state = ScrollState::new();
8984        let (mut runtime, window_id) = build_runtime(
8985            SizedBox::new().size(Size::new(80.0, 40.0)).child(
8986                ScrollView::vertical(OverflowingBox::new(
8987                    Size::new(80.0, 4_000.0),
8988                    Color::rgba(0.2, 0.3, 0.7, 1.0),
8989                ))
8990                .state(state.clone()),
8991            ),
8992        );
8993        let _ = runtime.render(window_id).unwrap();
8994
8995        // Six moves of 10 pixels each sixtieth of a second: 600 pixels a second.
8996        let (time, position) = touch_swipe_up(
8997            &mut runtime,
8998            window_id,
8999            5,
9000            Point::new(20.0, 30.0),
9001            10.0,
9002            6,
9003            1.0,
9004        );
9005        touch_up(&mut runtime, window_id, 5, position, time);
9006        assert_eq!(state.current_offset(), Vector::new(0.0, 60.0));
9007        assert!(runtime.has_pending_animation_frames(window_id).unwrap());
9008
9009        let time = run_frames(&mut runtime, time, 0.25);
9010        let coasting = state.current_offset().y;
9011        assert!(
9012            coasting > 150.0,
9013            "fling should keep scrolling, at {coasting}"
9014        );
9015
9016        let _ = run_frames(&mut runtime, time, 5.0);
9017        let settled = state.current_offset().y;
9018        assert!(settled > coasting);
9019        // Exponential friction covers at most velocity / friction.
9020        assert!(settled <= 60.0 + 600.0 / super::TOUCH_FLING_FRICTION + 1.0);
9021        assert!(!runtime.has_pending_animation_frames(window_id).unwrap());
9022    }
9023
9024    #[test]
9025    fn touch_release_after_resting_does_not_fling() {
9026        let state = ScrollState::new();
9027        let (mut runtime, window_id) = build_runtime(
9028            SizedBox::new().size(Size::new(80.0, 40.0)).child(
9029                ScrollView::vertical(OverflowingBox::new(
9030                    Size::new(80.0, 4_000.0),
9031                    Color::rgba(0.2, 0.3, 0.7, 1.0),
9032                ))
9033                .state(state.clone()),
9034            ),
9035        );
9036        let _ = runtime.render(window_id).unwrap();
9037
9038        let (time, position) = touch_swipe_up(
9039            &mut runtime,
9040            window_id,
9041            5,
9042            Point::new(20.0, 30.0),
9043            10.0,
9044            6,
9045            1.0,
9046        );
9047        touch_up(&mut runtime, window_id, 5, position, time + 0.2);
9048        let _ = run_frames(&mut runtime, time + 0.2, 0.5);
9049
9050        assert_eq!(state.current_offset(), Vector::new(0.0, 60.0));
9051    }
9052
9053    #[test]
9054    fn touch_catching_a_fling_stops_it_without_pressing_content() {
9055        let presses = Rc::new(Cell::new(0usize));
9056        let mut content = Stack::vertical();
9057        for index in 0..100 {
9058            let presses = Rc::clone(&presses);
9059            content.push(
9060                crate::Button::new(format!("Row {index}"))
9061                    .on_press(move || presses.set(presses.get() + 1)),
9062            );
9063        }
9064        let state = ScrollState::new();
9065        let (mut runtime, window_id) = build_runtime(
9066            SizedBox::new()
9067                .size(Size::new(100.0, 80.0))
9068                .child(ScrollView::vertical(content).state(state.clone())),
9069        );
9070        let _ = runtime.render(window_id).unwrap();
9071
9072        let (time, position) = touch_swipe_up(
9073            &mut runtime,
9074            window_id,
9075            6,
9076            Point::new(20.0, 70.0),
9077            10.0,
9078            6,
9079            1.0,
9080        );
9081        touch_up(&mut runtime, window_id, 6, position, time);
9082        let time = run_frames(&mut runtime, time, 0.1);
9083        let _ = runtime.render(window_id).unwrap();
9084        let caught_at = state.current_offset();
9085
9086        runtime.tick(time);
9087        for kind in [PointerEventKind::Down, PointerEventKind::Up] {
9088            runtime
9089                .handle_event(
9090                    window_id,
9091                    Event::Pointer(touch_pointer(kind, 7, Point::new(20.0, 20.0), Vector::ZERO)),
9092                )
9093                .unwrap();
9094        }
9095        let _ = run_frames(&mut runtime, time, 0.5);
9096
9097        assert_eq!(state.current_offset(), caught_at);
9098        assert_eq!(presses.get(), 0);
9099    }
9100
9101    #[test]
9102    fn virtual_scroll_view_fling_stops_at_the_end() {
9103        let mut view = VirtualScrollView::new();
9104        for _ in 0..3 {
9105            view.push(FixedBox::new(
9106                Size::new(80.0, 40.0),
9107                Color::rgba(0.2, 0.3, 0.7, 1.0),
9108            ));
9109        }
9110        let state = ScrollState::new();
9111        let (mut runtime, window_id) = build_runtime(
9112            SizedBox::new()
9113                .size(Size::new(80.0, 40.0))
9114                .child(view.state(state.clone())),
9115        );
9116        let _ = runtime.render(window_id).unwrap();
9117
9118        // 360 pixels a second coasts up to 180 pixels, past the 50 left.
9119        let (time, position) = touch_swipe_up(
9120            &mut runtime,
9121            window_id,
9122            8,
9123            Point::new(20.0, 35.0),
9124            6.0,
9125            5,
9126            1.0,
9127        );
9128        assert_eq!(state.current_offset(), Vector::new(0.0, 30.0));
9129        touch_up(&mut runtime, window_id, 8, position, time);
9130        let _ = run_frames(&mut runtime, time, 1.0);
9131
9132        assert_eq!(state.current_offset(), Vector::new(0.0, 80.0));
9133        assert!(!runtime.has_pending_animation_frames(window_id).unwrap());
9134    }
9135
9136    fn wheel(position: Point, delta_y: f32) -> Event {
9137        let mut wheel = PointerEvent::new(PointerEventKind::Scroll, position);
9138        wheel.delta = Vector::new(0.0, delta_y);
9139        Event::Pointer(wheel)
9140    }
9141
9142    #[test]
9143    fn offset_change_reports_wheel_and_fling_scrolling_in_order() {
9144        let seen = Rc::new(RefCell::new(Vec::new()));
9145        let plain = Rc::clone(&seen);
9146        let with_ctx = Rc::clone(&seen);
9147        let state = ScrollState::new();
9148        let (mut runtime, window_id) = build_runtime(
9149            SizedBox::new().size(Size::new(80.0, 40.0)).child(
9150                ScrollView::vertical(OverflowingBox::new(
9151                    Size::new(80.0, 4_000.0),
9152                    Color::rgba(0.2, 0.3, 0.7, 1.0),
9153                ))
9154                .state(state.clone())
9155                .on_offset_change(move |offset| plain.borrow_mut().push(("plain", offset.y)))
9156                .on_offset_change_with_ctx(move |_, offset| {
9157                    with_ctx.borrow_mut().push(("ctx", offset.y));
9158                }),
9159            ),
9160        );
9161        let _ = runtime.render(window_id).unwrap();
9162
9163        runtime
9164            .handle_event(window_id, wheel(Point::new(20.0, 20.0), -30.0))
9165            .unwrap();
9166        assert_eq!(*seen.borrow(), vec![("plain", 30.0), ("ctx", 30.0)]);
9167
9168        // A fling keeps reporting after the finger lifts, frame by frame.
9169        let (time, position) = touch_swipe_up(
9170            &mut runtime,
9171            window_id,
9172            5,
9173            Point::new(20.0, 30.0),
9174            10.0,
9175            6,
9176            1.0,
9177        );
9178        touch_up(&mut runtime, window_id, 5, position, time);
9179        let released = seen.borrow().len();
9180        let _ = run_frames(&mut runtime, time, 5.0);
9181        let seen = seen.borrow();
9182        assert!(seen.len() > released + 10);
9183        assert_eq!(seen.last().unwrap().1, state.current_offset().y);
9184        assert!(seen.windows(2).all(|pair| pair[0].1 <= pair[1].1));
9185    }
9186
9187    #[test]
9188    fn offset_change_reports_layout_moves_on_the_next_frame() {
9189        let seen = Rc::new(RefCell::new(Vec::new()));
9190        let seen_by_view = Rc::clone(&seen);
9191        let state = ScrollState::new();
9192        let (mut runtime, window_id) = build_runtime(
9193            SizedBox::new().size(Size::new(80.0, 60.0)).child(
9194                ScrollView::vertical(OverflowingBox::new(
9195                    Size::new(80.0, 180.0),
9196                    Color::rgba(0.2, 0.3, 0.7, 1.0),
9197                ))
9198                .name("Results")
9199                .state(state.clone())
9200                .on_offset_change_with_ctx(move |_, offset| {
9201                    seen_by_view.borrow_mut().push(offset.y);
9202                }),
9203            ),
9204        );
9205        let output = runtime.render(window_id).unwrap();
9206        let scroll_bar = output
9207            .semantics
9208            .iter()
9209            .find(|node| node.name.as_deref() == Some("Results vertical scroll bar"))
9210            .expect("embedded scroll bar present");
9211
9212        drag_vertical_scroll_bar(&mut runtime, window_id, scroll_bar.bounds, 42, 20.0);
9213        let _ = runtime.render(window_id).unwrap();
9214        let moved_to = state.current_offset().y;
9215        assert!(moved_to > 0.0);
9216        assert!(seen.borrow().is_empty(), "layout has no event context");
9217
9218        runtime.tick(1.0);
9219        handle_ready_events(&mut runtime);
9220        assert_eq!(*seen.borrow(), vec![moved_to]);
9221
9222        // Nothing new to report, so no further frames.
9223        runtime.tick(2.0);
9224        handle_ready_events(&mut runtime);
9225        assert_eq!(*seen.borrow(), vec![moved_to]);
9226    }
9227
9228    #[test]
9229    fn virtual_scroll_view_reports_offset_changes() {
9230        let seen = Rc::new(RefCell::new(Vec::new()));
9231        let seen_by_view = Rc::clone(&seen);
9232        let mut view = VirtualScrollView::new().on_offset_change(move |offset| {
9233            seen_by_view.borrow_mut().push(offset);
9234        });
9235        for _ in 0..3 {
9236            view.push(FixedBox::new(
9237                Size::new(80.0, 40.0),
9238                Color::rgba(0.2, 0.3, 0.7, 1.0),
9239            ));
9240        }
9241        let (mut runtime, window_id) =
9242            build_runtime(SizedBox::new().size(Size::new(80.0, 40.0)).child(view));
9243        let _ = runtime.render(window_id).unwrap();
9244
9245        runtime
9246            .handle_event(window_id, wheel(Point::new(20.0, 20.0), -25.0))
9247            .unwrap();
9248        assert_eq!(*seen.borrow(), vec![Vector::new(0.0, 25.0)]);
9249    }
9250
9251    #[test]
9252    fn touch_pan_starting_on_button_cancels_click_but_tap_still_activates() {
9253        let pans = Rc::new(Cell::new(0usize));
9254        let pan_count = Rc::clone(&pans);
9255        let pan_state = ScrollState::new();
9256        let (mut runtime, window_id) = build_runtime(
9257            SizedBox::new().size(Size::new(100.0, 48.0)).child(
9258                ScrollView::vertical(
9259                    Stack::vertical()
9260                        .with_child(crate::Button::new("Open").on_press(move || {
9261                            pan_count.set(pan_count.get() + 1);
9262                        }))
9263                        .with_child(FixedBox::new(
9264                            Size::new(100.0, 120.0),
9265                            Color::rgba(0.2, 0.3, 0.7, 1.0),
9266                        )),
9267                )
9268                .state(pan_state.clone()),
9269            ),
9270        );
9271        let _ = runtime.render(window_id).unwrap();
9272
9273        for pointer in [
9274            touch_pointer(
9275                PointerEventKind::Down,
9276                12,
9277                Point::new(20.0, 20.0),
9278                Vector::ZERO,
9279            ),
9280            touch_pointer(
9281                PointerEventKind::Move,
9282                12,
9283                Point::new(20.0, 4.0),
9284                Vector::new(0.0, -16.0),
9285            ),
9286            touch_pointer(
9287                PointerEventKind::Up,
9288                12,
9289                Point::new(20.0, 4.0),
9290                Vector::ZERO,
9291            ),
9292        ] {
9293            runtime
9294                .handle_event(window_id, Event::Pointer(pointer))
9295                .unwrap();
9296        }
9297        assert_eq!(pans.get(), 0, "a pan must not activate the button");
9298        assert_eq!(pan_state.current_offset(), Vector::new(0.0, 16.0));
9299
9300        let taps = Rc::new(Cell::new(0usize));
9301        let tap_count = Rc::clone(&taps);
9302        let (mut tap_runtime, tap_window) = build_runtime(
9303            SizedBox::new()
9304                .size(Size::new(100.0, 48.0))
9305                .child(ScrollView::vertical(
9306                    Stack::vertical()
9307                        .with_child(crate::Button::new("Open").on_press(move || {
9308                            tap_count.set(tap_count.get() + 1);
9309                        }))
9310                        .with_child(FixedBox::new(
9311                            Size::new(100.0, 120.0),
9312                            Color::rgba(0.2, 0.3, 0.7, 1.0),
9313                        )),
9314                )),
9315        );
9316        let _ = tap_runtime.render(tap_window).unwrap();
9317        for pointer in [
9318            touch_pointer(
9319                PointerEventKind::Down,
9320                13,
9321                Point::new(20.0, 20.0),
9322                Vector::ZERO,
9323            ),
9324            touch_pointer(
9325                PointerEventKind::Up,
9326                13,
9327                Point::new(20.0, 20.0),
9328                Vector::ZERO,
9329            ),
9330        ] {
9331            tap_runtime
9332                .handle_event(tap_window, Event::Pointer(pointer))
9333                .unwrap();
9334        }
9335        assert_eq!(taps.get(), 1, "a tap should still activate exactly once");
9336    }
9337
9338    #[test]
9339    fn touch_pan_at_scroll_boundary_cancels_underlying_button() {
9340        let activations = Rc::new(Cell::new(0usize));
9341        let activation_count = Rc::clone(&activations);
9342        let (mut runtime, window_id) = build_runtime(
9343            SizedBox::new()
9344                .size(Size::new(100.0, 48.0))
9345                .child(ScrollView::vertical(
9346                    Stack::vertical()
9347                        .with_child(FixedBox::new(
9348                            Size::new(100.0, 120.0),
9349                            Color::rgba(0.2, 0.3, 0.7, 1.0),
9350                        ))
9351                        .with_child(crate::Button::new("Bottom").on_press(move || {
9352                            activation_count.set(activation_count.get() + 1);
9353                        })),
9354                )),
9355        );
9356        let _ = runtime.render(window_id).unwrap();
9357
9358        let mut scroll = PointerEvent::new(PointerEventKind::Scroll, Point::new(20.0, 20.0));
9359        scroll.scroll_delta = Some(ScrollDelta::Pixels(Vector::new(0.0, -500.0)));
9360        runtime
9361            .handle_event(window_id, Event::Pointer(scroll))
9362            .unwrap();
9363        let output = runtime.render(window_id).unwrap();
9364        let button = output
9365            .semantics
9366            .iter()
9367            .find(|node| {
9368                node.role == SemanticsRole::Button && node.name.as_deref() == Some("Bottom")
9369            })
9370            .expect("bottom button visible at the scroll boundary");
9371        let down_position = Point::new(
9372            button.bounds.x() + button.bounds.width() * 0.5,
9373            button.bounds.y() + button.bounds.height() * 0.5,
9374        );
9375        let move_position = Point::new(down_position.x, down_position.y - 12.0);
9376
9377        for pointer in [
9378            touch_pointer(PointerEventKind::Down, 14, down_position, Vector::ZERO),
9379            touch_pointer(
9380                PointerEventKind::Move,
9381                14,
9382                move_position,
9383                Vector::new(0.0, -12.0),
9384            ),
9385            touch_pointer(PointerEventKind::Up, 14, move_position, Vector::ZERO),
9386        ] {
9387            runtime
9388                .handle_event(window_id, Event::Pointer(pointer))
9389                .unwrap();
9390        }
9391
9392        assert_eq!(
9393            activations.get(),
9394            0,
9395            "a boundary pan must cancel the pressed control even when content cannot move"
9396        );
9397    }
9398
9399    #[test]
9400    fn shared_scroll_state_accepts_programmatic_offsets() {
9401        let state = ScrollState::new();
9402        state.sync_metrics(
9403            ScrollAxes::Vertical,
9404            Size::new(80.0, 40.0),
9405            Size::new(80.0, 120.0),
9406        );
9407
9408        assert!(state.set_offset(Vector::new(20.0, 32.0)));
9409        assert_eq!(state.current_offset(), Vector::new(0.0, 32.0));
9410        assert!(!state.set_offset(Vector::new(0.0, 32.0)));
9411        assert!(state.set_offset(Vector::new(0.0, 200.0)));
9412        assert_eq!(state.current_offset(), Vector::new(0.0, 80.0));
9413    }
9414
9415    #[test]
9416    fn scroll_bar_updates_after_wheel_scrolling_bound_scroll_view() {
9417        let state = ScrollState::new();
9418        let (mut runtime, window_id) = build_runtime(
9419            SizedBox::new()
9420                .size(Size::new(92.0, 40.0))
9421                .child(ScrollBarHost::new(
9422                    ScrollView::vertical(FixedBox::new(
9423                        Size::new(80.0, 120.0),
9424                        Color::rgba(0.2, 0.3, 0.7, 1.0),
9425                    ))
9426                    .state(state.clone())
9427                    .scroll_bars(false)
9428                    .name("Scrollable content"),
9429                    ScrollBar::vertical(state).name("Scroll bar"),
9430                )),
9431        );
9432
9433        let _ = runtime.render(window_id).unwrap();
9434
9435        let mut scroll = PointerEvent::new(PointerEventKind::Scroll, Point::new(20.0, 20.0));
9436        scroll.scroll_delta = Some(ScrollDelta::Pixels(Vector::new(0.0, -32.0)));
9437        runtime
9438            .handle_event(window_id, Event::Pointer(scroll))
9439            .unwrap();
9440
9441        let output = runtime.render(window_id).unwrap();
9442        let graph = runtime.widget_graph(window_id).unwrap();
9443
9444        let content = scroll_view_content_with_height(&graph, 120.0);
9445        let scroll_view = parent_node(&graph, content);
9446        assert_eq!(
9447            content.bounds,
9448            Rect::new(0.0, -32.0, scroll_view.bounds.width(), 120.0)
9449        );
9450        let scroll_bar = output
9451            .semantics
9452            .iter()
9453            .find(|node| {
9454                node.role == SemanticsRole::Slider && node.name.as_deref() == Some("Scroll bar")
9455            })
9456            .expect("scroll bar semantics present");
9457        assert_eq!(
9458            scroll_bar.value,
9459            Some(SemanticsValue::Range {
9460                value: 32.0,
9461                min: 0.0,
9462                max: 80.0,
9463            })
9464        );
9465    }
9466
9467    #[test]
9468    fn embedded_overlay_scroll_bar_applies_semantic_actions() {
9469        let state = ScrollState::new();
9470        let (mut runtime, window_id) = build_runtime(
9471            SizedBox::new().size(Size::new(80.0, 40.0)).child(
9472                ScrollView::vertical(FixedBox::new(
9473                    Size::new(80.0, 120.0),
9474                    Color::rgba(0.2, 0.3, 0.7, 1.0),
9475                ))
9476                .state(state.clone())
9477                .name("Semantic content"),
9478            ),
9479        );
9480        let scroll_bar_id = runtime
9481            .render(window_id)
9482            .unwrap()
9483            .semantics
9484            .iter()
9485            .find(|node| {
9486                node.role == SemanticsRole::Slider
9487                    && node.name.as_deref() == Some("Semantic content vertical scroll bar")
9488            })
9489            .expect("overlay scroll bar semantics present")
9490            .id;
9491
9492        assert!(
9493            runtime
9494                .handle_semantics_action(
9495                    window_id,
9496                    scroll_bar_id,
9497                    SemanticsActionRequest::Increment,
9498                )
9499                .unwrap()
9500        );
9501        assert_eq!(state.current_offset(), Vector::new(0.0, 40.0));
9502
9503        assert!(
9504            runtime
9505                .handle_semantics_action(
9506                    window_id,
9507                    scroll_bar_id,
9508                    SemanticsActionRequest::SetValue(SemanticsValue::Range {
9509                        value: 72.0,
9510                        min: 0.0,
9511                        max: 80.0,
9512                    }),
9513                )
9514                .unwrap()
9515        );
9516        assert_eq!(state.current_offset(), Vector::new(0.0, 72.0));
9517
9518        assert!(
9519            runtime
9520                .handle_semantics_action(
9521                    window_id,
9522                    scroll_bar_id,
9523                    SemanticsActionRequest::Decrement,
9524                )
9525                .unwrap()
9526        );
9527        assert_eq!(state.current_offset(), Vector::new(0.0, 32.0));
9528        assert!(
9529            !runtime
9530                .handle_semantics_action(
9531                    window_id,
9532                    scroll_bar_id,
9533                    SemanticsActionRequest::SetValue(SemanticsValue::Text("invalid".to_string())),
9534                )
9535                .unwrap()
9536        );
9537    }
9538
9539    #[test]
9540    fn scroll_bar_defaults_follow_theme_density_and_width_override() {
9541        let compact_state = ScrollState::new();
9542        compact_state.sync_metrics(
9543            ScrollAxes::Vertical,
9544            Size::new(80.0, 40.0),
9545            Size::new(80.0, 120.0),
9546        );
9547        let (compact, _) = render_root(
9548            ScrollBar::vertical(compact_state)
9549                .theme(DefaultTheme::compact())
9550                .name("Compact scroll bar"),
9551        );
9552
9553        let touch_state = ScrollState::new();
9554        touch_state.sync_metrics(
9555            ScrollAxes::Vertical,
9556            Size::new(80.0, 40.0),
9557            Size::new(80.0, 120.0),
9558        );
9559        let (touch, _) = render_root(
9560            ScrollBar::vertical(touch_state)
9561                .theme(DefaultTheme::touch())
9562                .name("Touch scroll bar"),
9563        );
9564
9565        assert_eq!(
9566            compact.frame.viewport.width,
9567            DefaultTheme::compact().metrics.scroll_bar_thickness
9568        );
9569        assert_eq!(
9570            touch.frame.viewport.width,
9571            DefaultTheme::touch().metrics.scroll_bar_thickness
9572        );
9573        assert!(touch.frame.viewport.width > compact.frame.viewport.width);
9574
9575        let override_state = ScrollState::new();
9576        override_state.sync_metrics(
9577            ScrollAxes::Vertical,
9578            Size::new(80.0, 40.0),
9579            Size::new(80.0, 120.0),
9580        );
9581        let (overridden, _) = render_root(
9582            ScrollBar::vertical(override_state)
9583                .theme(DefaultTheme::touch())
9584                .width(9.0),
9585        );
9586        assert_eq!(overridden.frame.viewport.width, 9.0);
9587    }
9588
9589    #[test]
9590    fn scroll_bar_theme_when_reads_current_theme() {
9591        let state = ScrollState::new();
9592        state.sync_metrics(
9593            ScrollAxes::Vertical,
9594            Size::new(80.0, 40.0),
9595            Size::new(80.0, 120.0),
9596        );
9597        let theme = Rc::new(RefCell::new(DefaultTheme::touch()));
9598        let theme_reader = Rc::clone(&theme);
9599        let (output, _) = render_root(
9600            ScrollBar::vertical(state)
9601                .theme_when(move || *theme_reader.borrow())
9602                .name("Themed scroll bar"),
9603        );
9604
9605        assert_eq!(
9606            output.frame.viewport.width,
9607            DefaultTheme::touch().metrics.scroll_bar_thickness
9608        );
9609    }
9610
9611    #[test]
9612    fn overlay_scroll_bar_expands_only_for_hover_capable_pointers() {
9613        let theme = DefaultTheme::default();
9614        let state = ScrollState::new();
9615        state.sync_metrics(
9616            ScrollAxes::Vertical,
9617            Size::new(80.0, 40.0),
9618            Size::new(80.0, 120.0),
9619        );
9620        let (mut runtime, window_id) = build_runtime(
9621            ScrollBar::vertical(state)
9622                .theme(theme)
9623                .name("Overlay scroll bar")
9624                .overlay(),
9625        );
9626
9627        let idle = runtime.render(window_id).expect("render should succeed");
9628        let bounds = idle
9629            .semantics
9630            .iter()
9631            .find(|node| node.name.as_deref() == Some("Overlay scroll bar"))
9632            .expect("scroll bar semantics present")
9633            .bounds;
9634        let idle_width =
9635            super::OVERLAY_SCROLL_BAR_IDLE_THICKNESS.min(theme.metrics.scroll_bar_thickness);
9636        let idle_paths = solid_fill_path_bounds(&idle);
9637        assert_eq!(bounds.width(), theme.metrics.scroll_bar_thickness);
9638        assert_eq!(idle_paths.len(), 2);
9639        assert!(
9640            idle_paths
9641                .iter()
9642                .all(|path| (path.width() - idle_width).abs() <= f32::EPSILON)
9643        );
9644
9645        let point = Point::new(bounds.x() + bounds.width() * 0.5, bounds.y() + 8.0);
9646        let mut wheel = PointerEvent::new(PointerEventKind::Scroll, point);
9647        wheel.scroll_delta = Some(ScrollDelta::Pixels(Vector::new(0.0, 24.0)));
9648        runtime
9649            .handle_event(window_id, Event::Pointer(wheel))
9650            .expect("wheel event should be handled");
9651        let after_wheel = runtime.render(window_id).expect("render should succeed");
9652        assert!(
9653            solid_fill_path_bounds(&after_wheel)
9654                .iter()
9655                .all(|path| (path.width() - idle_width).abs() <= f32::EPSILON)
9656        );
9657
9658        runtime
9659            .handle_event(
9660                window_id,
9661                Event::Pointer(touch_pointer(
9662                    PointerEventKind::Move,
9663                    7,
9664                    point,
9665                    Vector::ZERO,
9666                )),
9667            )
9668            .expect("touch move should be handled");
9669        let after_touch = runtime.render(window_id).expect("render should succeed");
9670        assert!(
9671            solid_fill_path_bounds(&after_touch)
9672                .iter()
9673                .all(|path| (path.width() - idle_width).abs() <= f32::EPSILON)
9674        );
9675
9676        runtime
9677            .handle_event(
9678                window_id,
9679                Event::Pointer(PointerEvent::new(PointerEventKind::Move, point)),
9680            )
9681            .expect("mouse hover should be handled");
9682        runtime.tick(theme.motion.hover_duration());
9683        assert_eq!(handle_ready_events(&mut runtime), 0);
9684        let hovered = runtime.render(window_id).expect("render should succeed");
9685        assert!(solid_fill_path_bounds(&hovered).iter().all(|path| {
9686            (path.width() - theme.metrics.scroll_bar_thickness).abs() <= f32::EPSILON
9687        }));
9688    }
9689
9690    #[test]
9691    fn scroll_bar_hover_and_drag_use_theme_motion() {
9692        let theme = DefaultTheme::default();
9693        let state = ScrollState::new();
9694        state.sync_metrics(
9695            ScrollAxes::Vertical,
9696            Size::new(80.0, 40.0),
9697            Size::new(80.0, 120.0),
9698        );
9699        let point = Point::new(theme.metrics.scroll_bar_thickness * 0.5, 8.0);
9700        let expected_hover = theme.palette.border_strong.with_alpha(0.95);
9701        let expected_drag = theme.palette.text_muted.with_alpha(0.95);
9702        let (mut runtime, window_id) =
9703            build_runtime(ScrollBar::vertical(state).theme(theme).name("Scroll bar"));
9704
9705        let _ = runtime.render(window_id).expect("render should succeed");
9706        runtime
9707            .handle_event(
9708                window_id,
9709                Event::Pointer(PointerEvent::new(PointerEventKind::Move, point)),
9710            )
9711            .expect("hover event should be handled");
9712
9713        runtime.tick(theme.motion.hover_duration() * 0.5);
9714        assert_eq!(handle_ready_events(&mut runtime), 0);
9715        let mid_hover = runtime.render(window_id).expect("render should succeed");
9716        assert!(!solid_fill_colors(&mid_hover).contains(&expected_hover));
9717
9718        runtime.tick(theme.motion.hover_duration());
9719        assert_eq!(handle_ready_events(&mut runtime), 0);
9720        let settled_hover = runtime.render(window_id).expect("render should succeed");
9721        assert!(solid_fill_colors(&settled_hover).contains(&expected_hover));
9722
9723        let mut down = PointerEvent::new(PointerEventKind::Down, point);
9724        down.pointer_id = 1;
9725        down.button = Some(PointerButton::Primary);
9726        down.buttons = PointerButtons::new(1);
9727        runtime
9728            .handle_event(window_id, Event::Pointer(down))
9729            .expect("drag event should be handled");
9730
9731        runtime.tick(theme.motion.hover_duration() + theme.motion.press_duration() * 0.5);
9732        assert_eq!(handle_ready_events(&mut runtime), 0);
9733        let mid_drag = runtime.render(window_id).expect("render should succeed");
9734        assert!(!solid_fill_colors(&mid_drag).contains(&expected_drag));
9735
9736        runtime.tick(theme.motion.hover_duration() + theme.motion.press_duration());
9737        assert_eq!(handle_ready_events(&mut runtime), 0);
9738        let settled_drag = runtime.render(window_id).expect("render should succeed");
9739        assert!(solid_fill_colors(&settled_drag).contains(&expected_drag));
9740    }
9741
9742    #[test]
9743    fn scroll_bar_focus_stroke_uses_theme_motion() {
9744        let theme = DefaultTheme::default();
9745        let state = ScrollState::new();
9746        state.sync_metrics(
9747            ScrollAxes::Vertical,
9748            Size::new(80.0, 40.0),
9749            Size::new(80.0, 120.0),
9750        );
9751        let point = Point::new(theme.metrics.scroll_bar_thickness * 0.5, 8.0);
9752        let (mut runtime, window_id) =
9753            build_runtime(ScrollBar::vertical(state).theme(theme).name("Scroll bar"));
9754
9755        let _ = runtime.render(window_id).expect("render should succeed");
9756        let mut down = PointerEvent::new(PointerEventKind::Down, point);
9757        down.pointer_id = 1;
9758        down.button = Some(PointerButton::Primary);
9759        down.buttons = PointerButtons::new(1);
9760        runtime
9761            .handle_event(window_id, Event::Pointer(down))
9762            .expect("focus event should be handled");
9763        let _ = runtime.render(window_id).expect("render should succeed");
9764
9765        runtime.tick(theme.motion.focus_duration() * 0.5);
9766        assert_eq!(handle_ready_events(&mut runtime), 0);
9767        let mid_focus = runtime.render(window_id).expect("render should succeed");
9768        assert!(
9769            !contains_approx_color(&solid_stroke_colors(&mid_focus), theme.palette.focus_ring),
9770            "scroll bar focus stroke should not snap to the settled focus color"
9771        );
9772
9773        runtime.tick(theme.motion.focus_duration() + 0.01);
9774        assert_eq!(handle_ready_events(&mut runtime), 0);
9775        let settled_focus = runtime.render(window_id).expect("render should succeed");
9776        let settled_strokes = solid_stroke_colors(&settled_focus);
9777        assert!(
9778            contains_approx_color(&settled_strokes, theme.palette.focus_ring),
9779            "scroll bar focus stroke should settle to the theme focus color; strokes={settled_strokes:?}"
9780        );
9781    }
9782
9783    #[test]
9784    fn scroll_view_focus_keeps_viewport_chrome_neutral() {
9785        let theme = DefaultTheme::default();
9786        let point = Point::new(20.0, 20.0);
9787        let (mut runtime, window_id) = build_runtime(
9788            SizedBox::new().size(Size::new(80.0, 40.0)).child(
9789                ScrollView::vertical(FixedBox::new(
9790                    Size::new(80.0, 120.0),
9791                    Color::rgba(0.2, 0.3, 0.7, 1.0),
9792                ))
9793                .theme(theme),
9794            ),
9795        );
9796
9797        let _ = runtime.render(window_id).expect("render should succeed");
9798        let mut down = PointerEvent::new(PointerEventKind::Down, point);
9799        down.pointer_id = 1;
9800        down.button = Some(PointerButton::Primary);
9801        down.buttons = PointerButtons::new(1);
9802        runtime
9803            .handle_event(window_id, Event::Pointer(down))
9804            .expect("focus event should be handled");
9805
9806        let focused = runtime.render(window_id).expect("render should succeed");
9807        let focused_strokes = solid_stroke_colors(&focused);
9808        assert!(
9809            !contains_approx_color(&focused_strokes, theme.palette.focus_ring),
9810            "scroll view focus should not paint an activation ring; strokes={focused_strokes:?}"
9811        );
9812    }
9813
9814    #[test]
9815    fn virtual_scroll_view_focus_keeps_viewport_chrome_neutral() {
9816        let theme = DefaultTheme::default();
9817        let point = Point::new(20.0, 20.0);
9818        let (mut runtime, window_id) = build_runtime(
9819            SizedBox::new().size(Size::new(80.0, 40.0)).child(
9820                VirtualScrollView::new()
9821                    .theme(theme)
9822                    .with_child(FixedBox::new(
9823                        Size::new(80.0, 30.0),
9824                        Color::rgba(0.2, 0.3, 0.7, 1.0),
9825                    ))
9826                    .with_child(FixedBox::new(
9827                        Size::new(80.0, 30.0),
9828                        Color::rgba(0.3, 0.4, 0.8, 1.0),
9829                    ))
9830                    .with_child(FixedBox::new(
9831                        Size::new(80.0, 30.0),
9832                        Color::rgba(0.4, 0.5, 0.9, 1.0),
9833                    )),
9834            ),
9835        );
9836
9837        let _ = runtime.render(window_id).expect("render should succeed");
9838        let mut down = PointerEvent::new(PointerEventKind::Down, point);
9839        down.pointer_id = 1;
9840        down.button = Some(PointerButton::Primary);
9841        down.buttons = PointerButtons::new(1);
9842        runtime
9843            .handle_event(window_id, Event::Pointer(down))
9844            .expect("focus event should be handled");
9845
9846        let focused = runtime.render(window_id).expect("render should succeed");
9847        let focused_strokes = solid_stroke_colors(&focused);
9848        assert!(
9849            !contains_approx_color(&focused_strokes, theme.palette.focus_ring),
9850            "virtual scroll view focus should not paint an activation ring; strokes={focused_strokes:?}"
9851        );
9852    }
9853
9854    #[test]
9855    fn scroll_bar_pointer_input_moves_bound_scroll_view() {
9856        let state = ScrollState::new();
9857        let (mut runtime, window_id) = build_runtime(
9858            SizedBox::new()
9859                .size(Size::new(92.0, 40.0))
9860                .child(ScrollBarHost::new(
9861                    ScrollView::vertical(FixedBox::new(
9862                        Size::new(80.0, 120.0),
9863                        Color::rgba(0.2, 0.3, 0.7, 1.0),
9864                    ))
9865                    .state(state.clone())
9866                    .scroll_bars(false),
9867                    ScrollBar::vertical(state),
9868                )),
9869        );
9870
9871        let _ = runtime.render(window_id).unwrap();
9872        let mut down = PointerEvent::new(PointerEventKind::Down, Point::new(86.0, 36.0));
9873        down.button = Some(PointerButton::Primary);
9874        runtime
9875            .handle_event(window_id, Event::Pointer(down))
9876            .unwrap();
9877        let mut up = PointerEvent::new(PointerEventKind::Up, Point::new(86.0, 36.0));
9878        up.button = Some(PointerButton::Primary);
9879        runtime.handle_event(window_id, Event::Pointer(up)).unwrap();
9880
9881        let _ = runtime.render(window_id).unwrap();
9882        let graph = runtime.widget_graph(window_id).unwrap();
9883
9884        let content = scroll_view_content_with_height(&graph, 120.0);
9885        let scroll_view = parent_node(&graph, content);
9886        assert_eq!(
9887            content.bounds,
9888            Rect::new(0.0, -80.0, scroll_view.bounds.width(), 120.0)
9889        );
9890    }
9891}