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