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