1#![allow(clippy::too_many_arguments, clippy::type_complexity)]
2
3use std::{
4 cell::Cell,
5 collections::{HashMap, HashSet, hash_map::DefaultHasher},
6 hash::{Hash, Hasher},
7 rc::Rc,
8 sync::{
9 Arc, Mutex,
10 atomic::{AtomicU64, Ordering},
11 },
12};
13
14use crate::{
15 Command, CommandDelivery, CommandKey, CommandSender, CommandTarget,
16 command::{QueuedCommand, queued_command},
17 diagnostics::{WidgetTimingPhase, record_widget_timing},
18 motion::{FrameClock, Motion},
19 overlay::OverlayOptions,
20 reactive::{ObservationPhase, ObservationScope},
21};
22use sui_animation::{AnimationSpec, Interpolate};
23
24use sui_core::{
25 AsyncWakeToken, Clipboard, Color, CursorGrabMode, DpiInfo, DragPayload, DragScopeId,
26 DragSessionId, DropEffect, DropEffects, Event, ImageHandle, InvalidationKind,
27 InvalidationRequest, InvalidationTarget, MotionPolicy, Path, Point, Rect, SemanticsNode, Size,
28 TimerToken, Transform, Vector, WakeEvent, WidgetId, WindowId,
29};
30use sui_layout::{Axis, Constraints, IntrinsicSize, LayoutContext};
31use sui_reactive::{Observable, Signal};
32use sui_scene::{
33 Border, Brush, ImageRegistry, ImageSource, LayerCompositionMode, LayerProperties,
34 RegisteredExternalImage, RegisteredImage, Scene, SceneCommand, SceneLayer,
35 SceneLayerDescriptor, SceneLayerId, ShadowParams, StrokeStyle, TextRenderPolicy, WidgetShader,
36};
37use sui_text::{
38 FontRegistry, PersistentTextLayout, ShapedText, ShapedTextWindow, TextLayout, TextLayoutHandle,
39 TextLayoutRequest, TextMeasurement, TextRun, TextStyle, TextSystem,
40};
41use web_time::Instant;
42
43static NEXT_WIDGET_ID: AtomicU64 = AtomicU64::new(1);
44static NEXT_TIMER_TOKEN: AtomicU64 = AtomicU64::new(1);
45static NEXT_ASYNC_WAKE_TOKEN: AtomicU64 = AtomicU64::new(1);
46static NEXT_DRAG_SESSION_ID: AtomicU64 = AtomicU64::new(1);
47const WIDGET_IMAGE_HANDLE_NAMESPACE: u64 = 1 << 63;
48const TRANSFORM_EQ_ULPS: f32 = 16.0;
49
50fn relative_transform(child: Transform, parent: Transform) -> Transform {
51 if transforms_nearly_equal(child, parent) {
52 return Transform::IDENTITY;
53 }
54 parent
55 .inverse()
56 .map(|inverse| child.then(inverse))
57 .unwrap_or(child)
58}
59
60fn transforms_nearly_equal(left: Transform, right: Transform) -> bool {
61 let nearly_equal = |left: f32, right: f32| {
62 let scale = left.abs().max(right.abs()).max(1.0);
63 (left - right).abs() <= f32::EPSILON * TRANSFORM_EQ_ULPS * scale
64 };
65 nearly_equal(left.xx, right.xx)
66 && nearly_equal(left.yx, right.yx)
67 && nearly_equal(left.xy, right.xy)
68 && nearly_equal(left.yy, right.yy)
69 && nearly_equal(left.dx, right.dx)
70 && nearly_equal(left.dy, right.dy)
71}
72
73fn event_for_transform(event: &Event, inverse: Transform) -> Event {
74 if inverse.is_identity() {
75 return event.clone();
76 }
77 match event {
78 Event::Pointer(pointer) => {
79 let mut pointer = pointer.clone();
80 pointer.position = inverse.transform_point(pointer.position);
81 pointer.delta = inverse.transform_vector(pointer.delta);
82 pointer.scroll_delta = pointer.scroll_delta.map(|delta| match delta {
83 sui_core::ScrollDelta::Pixels(delta) => {
84 sui_core::ScrollDelta::Pixels(inverse.transform_vector(delta))
85 }
86 sui_core::ScrollDelta::Lines(delta) => sui_core::ScrollDelta::Lines(delta),
87 });
88 Event::Pointer(pointer)
89 }
90 Event::Drag(drag) => {
91 let mut drag = drag.clone();
92 drag.position = inverse.transform_point(drag.position);
93 drag.start_position = inverse.transform_point(drag.start_position);
94 Event::Drag(drag)
95 }
96 _ => event.clone(),
97 }
98}
99
100#[derive(Debug, Clone, Copy, PartialEq, Eq)]
101pub enum EventPhase {
102 Capture,
103 Target,
104 Bubble,
105}
106
107pub trait WidgetPodVisitor {
108 fn visit(&mut self, child: &WidgetPod);
109}
110
111pub trait WidgetPodMutVisitor {
112 fn visit(&mut self, child: &mut WidgetPod);
113}
114
115#[derive(Debug, Clone, PartialEq, Eq)]
121pub struct WidgetDiagnostic {
122 pub name: String,
123 pub value: String,
124}
125
126#[derive(Debug, Default)]
128pub struct WidgetDiagnosticsCtx {
129 entries: Vec<WidgetDiagnostic>,
130}
131
132impl WidgetDiagnosticsCtx {
133 pub fn record(&mut self, name: impl Into<String>, value: impl Into<String>) {
134 self.entries.push(WidgetDiagnostic {
135 name: name.into(),
136 value: value.into(),
137 });
138 }
139
140 fn into_entries(self) -> Vec<WidgetDiagnostic> {
141 self.entries
142 }
143}
144
145#[derive(Debug, Clone, PartialEq, Eq)]
147pub struct WidgetDiagnosticsSnapshot {
148 pub widget_id: WidgetId,
149 pub widget_name: &'static str,
150 pub entries: Vec<WidgetDiagnostic>,
151}
152
153pub trait Widget {
154 fn event(&mut self, _ctx: &mut EventCtx, _event: &Event) {}
155
156 fn command(&mut self, _ctx: &mut EventCtx, _command: &Command<'_>) {}
159
160 fn debug_name(&self) -> &'static str {
161 std::any::type_name::<Self>()
162 }
163
164 fn diagnostics(&self, _ctx: &mut WidgetDiagnosticsCtx) {}
169
170 fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
171 constraints.max
172 }
173
174 fn measure_size(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
182 self.measure(ctx, constraints)
183 }
184
185 fn measure_axis(&mut self, ctx: &mut MeasureCtx, constraints: Constraints, axis: Axis) -> f32 {
189 let size = self.measure_size(ctx, constraints);
190 match axis {
191 Axis::Horizontal => size.width,
192 Axis::Vertical => size.height,
193 }
194 }
195
196 fn intrinsic_size(
202 &mut self,
203 ctx: &mut MeasureCtx,
204 axis: Axis,
205 available_cross: f32,
206 ) -> IntrinsicSize {
207 let cross = if available_cross.is_finite() {
208 available_cross.max(0.0)
209 } else {
210 f32::INFINITY
211 };
212 let constraints = match axis {
213 Axis::Horizontal => Constraints::new(Size::ZERO, Size::new(f32::INFINITY, cross)),
214 Axis::Vertical => Constraints::new(Size::ZERO, Size::new(cross, f32::INFINITY)),
215 };
216 let size = self.measure_size(ctx, constraints);
217 IntrinsicSize::fixed(match axis {
218 Axis::Horizontal => size.width,
219 Axis::Vertical => size.height,
220 })
221 }
222
223 fn arrange(&mut self, _ctx: &mut ArrangeCtx, _bounds: Rect) {}
224
225 fn paint(&self, _ctx: &mut PaintCtx) {}
226
227 fn supports_output_reuse(&self) -> bool {
235 false
236 }
237
238 fn layer_options(&self) -> LayerOptions {
239 LayerOptions::default()
240 }
241
242 fn layer_properties(&self) -> LayerProperties {
243 LayerProperties::default()
244 }
245
246 fn layer_properties_at(&self, frame_time: f64) -> LayerProperties {
251 let _ = frame_time;
252 self.layer_properties()
253 }
254
255 fn stack_host_options(&self) -> Option<StackHostOptions> {
256 None
257 }
258
259 fn stack_surface_options(&self) -> Option<StackSurfaceOptions> {
260 None
261 }
262
263 fn overlay_options(&self) -> Option<OverlayOptions> {
269 None
270 }
271
272 fn semantics(&self, _ctx: &mut SemanticsCtx) {}
273
274 fn accepts_focus(&self) -> bool {
275 false
276 }
277
278 fn hit_test_self(&self) -> bool {
283 true
284 }
285
286 fn focus_changed(&mut self, _ctx: &mut EventCtx, _focused: bool) {}
287
288 fn visit_children(&self, _visitor: &mut dyn WidgetPodVisitor) {}
296
297 fn visit_children_mut(&mut self, _visitor: &mut dyn WidgetPodMutVisitor) {}
303}
304
305#[derive(Debug, Clone, Copy, PartialEq, Eq)]
306pub enum PaintBoundaryMode {
307 Flat,
308 Explicit,
309}
310
311#[derive(Debug, Clone, Copy, PartialEq, Eq)]
312pub struct LayerOptions {
313 pub paint_boundary: PaintBoundaryMode,
314 pub composition_mode: LayerCompositionMode,
315}
316
317impl LayerOptions {
318 pub const fn emits_layer(self) -> bool {
319 matches!(self.paint_boundary, PaintBoundaryMode::Explicit)
320 }
321}
322
323#[derive(Debug, Clone, Copy, PartialEq, Eq)]
324pub enum StackOrderPolicy {
325 Stable,
326 FocusFronted,
327}
328
329#[derive(Debug, Clone, Copy, PartialEq, Eq)]
330pub struct StackHostOptions {
331 pub order_policy: StackOrderPolicy,
332}
333
334impl Default for StackHostOptions {
335 fn default() -> Self {
336 Self {
337 order_policy: StackOrderPolicy::Stable,
338 }
339 }
340}
341
342#[derive(Debug, Clone, Copy, PartialEq, Eq)]
343pub struct StackSurfaceOptions {
344 pub dynamic_ordering: bool,
345 pub transient: bool,
346 pub hit_test: bool,
347}
348
349impl Default for StackSurfaceOptions {
350 fn default() -> Self {
351 Self {
352 dynamic_ordering: true,
353 transient: false,
354 hit_test: true,
355 }
356 }
357}
358
359impl Default for LayerOptions {
360 fn default() -> Self {
361 Self {
362 paint_boundary: PaintBoundaryMode::Flat,
363 composition_mode: LayerCompositionMode::Normal,
364 }
365 }
366}
367
368pub struct SingleChild {
369 child: WidgetPod,
370}
371
372impl SingleChild {
373 pub fn new<W>(child: W) -> Self
374 where
375 W: Widget + 'static,
376 {
377 Self::from_pod(WidgetPod::new(child))
378 }
379
380 pub fn new_with_paint_boundary<W>(child: W) -> Self
386 where
387 W: Widget + 'static,
388 {
389 let mut child = WidgetPod::new(child);
390 child.force_paint_boundary = true;
391 Self::from_pod(child)
392 }
393
394 pub fn with_paint_boundary(mut self) -> Self {
397 self.child.force_paint_boundary = true;
398 self
399 }
400
401 pub fn from_pod(child: WidgetPod) -> Self {
402 Self { child }
403 }
404
405 pub fn child(&self) -> &WidgetPod {
406 &self.child
407 }
408
409 pub fn child_mut(&mut self) -> &mut WidgetPod {
410 &mut self.child
411 }
412
413 pub fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
414 self.child.measure(ctx, constraints)
415 }
416
417 pub fn measure_size(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
418 self.child.probe_measure(ctx, constraints)
419 }
420
421 pub fn measure_axis(
422 &mut self,
423 ctx: &mut MeasureCtx,
424 constraints: Constraints,
425 axis: Axis,
426 ) -> f32 {
427 self.child.probe_measure_axis(ctx, constraints, axis)
428 }
429
430 pub fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
431 self.child.arrange(ctx, bounds);
432 }
433
434 pub fn arrange_transformed(
435 &mut self,
436 ctx: &mut ArrangeCtx,
437 bounds: Rect,
438 transform: Transform,
439 ) {
440 self.child.arrange_transformed(ctx, bounds, transform);
441 }
442
443 pub fn set_bounds(&mut self, bounds: Rect) {
444 self.child.set_bounds(bounds);
445 }
446
447 pub fn paint(&self, ctx: &mut PaintCtx) {
448 self.child.paint(ctx);
449 }
450
451 pub fn semantics(&self, ctx: &mut SemanticsCtx) {
452 self.child.semantics(ctx);
453 }
454
455 pub fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
456 visitor.visit(&self.child);
457 }
458
459 pub fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
460 visitor.visit(&mut self.child);
461 }
462}
463
464#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
465pub enum FocusRestorePolicy {
466 LastFocused,
468 FirstFocusable,
470 #[default]
472 LastFocusedOrFirstFocusable,
473}
474
475#[derive(Debug, Default)]
476struct FocusScopeStateInner {
477 last_focused: Option<WidgetId>,
478 restore_requested: bool,
479}
480
481#[derive(Clone, Debug)]
488pub struct FocusScopeState {
489 inner: Arc<Mutex<FocusScopeStateInner>>,
490 restore_revision: Signal<u64>,
491 last_focused_signal: Signal<Option<WidgetId>>,
492}
493
494impl FocusScopeState {
495 pub fn new() -> Self {
496 Self {
497 inner: Arc::new(Mutex::new(FocusScopeStateInner::default())),
498 restore_revision: Signal::named("FocusScopeState::restore", 0),
499 last_focused_signal: Signal::named("FocusScopeState::last_focused", None),
500 }
501 }
502
503 pub fn last_focused(&self) -> Option<WidgetId> {
507 self.lock_inner().last_focused
508 }
509
510 pub fn last_focused_observable(
513 &self,
514 ) -> impl Observable<Option<WidgetId>> + Clone + Send + Sync + 'static {
515 self.last_focused_signal
516 .select_named("FocusScopeState::last_focused", |widget| *widget)
517 }
518
519 pub fn request_restore(&self) -> bool {
520 let changed = {
521 let mut inner = self.lock_inner();
522 if inner.restore_requested {
523 false
524 } else {
525 inner.restore_requested = true;
526 true
527 }
528 };
529 if changed {
530 self.restore_revision
531 .update(|revision| *revision = revision.wrapping_add(1));
532 }
533 changed
534 }
535
536 pub fn clear(&self) {
537 let restore_was_requested = {
538 let mut inner = self.lock_inner();
539 let restore_was_requested = inner.restore_requested;
540 inner.last_focused = None;
541 inner.restore_requested = false;
542 restore_was_requested
543 };
544 self.last_focused_signal.set(None);
545 if restore_was_requested {
546 self.restore_revision
547 .update(|revision| *revision = revision.wrapping_add(1));
548 }
549 }
550
551 fn remember(&self, widget_id: WidgetId) {
552 let changed = {
553 let mut inner = self.lock_inner();
554 let changed = inner.last_focused != Some(widget_id);
555 inner.last_focused = Some(widget_id);
556 changed
557 };
558 if changed {
561 self.last_focused_signal.set(Some(widget_id));
562 }
563 }
564
565 fn restore_requested(&self) -> bool {
566 self.lock_inner().restore_requested
567 }
568
569 fn complete_restore(&self) {
570 self.lock_inner().restore_requested = false;
571 }
572
573 fn lock_inner(&self) -> std::sync::MutexGuard<'_, FocusScopeStateInner> {
574 self.inner
575 .lock()
576 .unwrap_or_else(std::sync::PoisonError::into_inner)
577 }
578}
579
580impl Default for FocusScopeState {
581 fn default() -> Self {
582 Self::new()
583 }
584}
585
586pub struct FocusScope {
592 state: FocusScopeState,
593 restore_policy: FocusRestorePolicy,
594 child: SingleChild,
595}
596
597impl FocusScope {
598 pub fn new<W>(child: W) -> Self
599 where
600 W: Widget + 'static,
601 {
602 Self {
603 state: FocusScopeState::new(),
604 restore_policy: FocusRestorePolicy::default(),
605 child: SingleChild::new(child),
606 }
607 }
608
609 pub fn state(mut self, state: FocusScopeState) -> Self {
610 self.state = state;
611 self
612 }
613
614 pub fn restore_policy(mut self, restore_policy: FocusRestorePolicy) -> Self {
615 self.restore_policy = restore_policy;
616 self
617 }
618
619 pub fn child(&self) -> &WidgetPod {
620 self.child.child()
621 }
622
623 pub fn child_mut(&mut self) -> &mut WidgetPod {
624 self.child.child_mut()
625 }
626
627 fn restore_target(&self) -> Option<WidgetId> {
628 let last_focused = self
629 .state
630 .last_focused()
631 .filter(|target| pod_contains(self.child.child(), *target));
632 match self.restore_policy {
633 FocusRestorePolicy::LastFocused => last_focused,
634 FocusRestorePolicy::FirstFocusable => first_focusable(self.child.child()),
635 FocusRestorePolicy::LastFocusedOrFirstFocusable => {
636 last_focused.or_else(|| first_focusable(self.child.child()))
637 }
638 }
639 }
640
641 fn remember_current_focus(&self, focused_widget_id: Option<WidgetId>) {
642 if let Some(focused) = focused_widget_id
643 && pod_contains(self.child.child(), focused)
644 {
645 self.state.remember(focused);
646 }
647 }
648}
649
650impl Widget for FocusScope {
651 fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
652 self.remember_current_focus(ctx.focused_widget_id());
653 if matches!(event, Event::Wake(WakeEvent::AnimationFrame { .. }))
654 && self.state.restore_requested()
655 {
656 let target = self.restore_target();
657 self.state.complete_restore();
658 let focused_elsewhere = ctx
661 .focused_widget_id()
662 .is_some_and(|focused| !pod_contains(self.child.child(), focused));
663 if !focused_elsewhere && let Some(target) = target {
664 ctx.request_focus_for(target);
665 ctx.request_paint();
666 ctx.request_semantics();
667 ctx.set_handled();
668 }
669 }
670 }
671
672 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
673 let _ = ctx.observe(&self.state.restore_revision);
674 if self.state.restore_requested() {
675 ctx.request_animation_frame();
676 }
677 self.child.measure(ctx, constraints)
678 }
679
680 fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
681 self.child.arrange(ctx, bounds);
682 }
683
684 fn paint(&self, ctx: &mut PaintCtx) {
685 self.remember_current_focus(ctx.focused_widget_id());
686 self.child.paint(ctx);
687 }
688
689 fn semantics(&self, ctx: &mut SemanticsCtx) {
690 self.remember_current_focus(ctx.focused_widget_id());
691 self.child.semantics(ctx);
692 }
693
694 fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
695 self.child.visit_children(visitor);
696 }
697
698 fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
699 self.child.visit_children_mut(visitor);
700 }
701}
702
703fn pod_contains(root: &WidgetPod, target: WidgetId) -> bool {
704 if root.id() == target {
705 return true;
706 }
707
708 struct Finder {
709 target: WidgetId,
710 found: bool,
711 }
712
713 impl WidgetPodVisitor for Finder {
714 fn visit(&mut self, child: &WidgetPod) {
715 if self.found {
716 return;
717 }
718 if child.id() == self.target {
719 self.found = true;
720 } else {
721 child.visit_children(self);
722 }
723 }
724 }
725
726 let mut finder = Finder {
727 target,
728 found: false,
729 };
730 root.visit_children(&mut finder);
731 finder.found
732}
733
734fn first_focusable(root: &WidgetPod) -> Option<WidgetId> {
735 if root.accepts_focus() {
736 return Some(root.id());
737 }
738
739 struct Finder {
740 target: Option<WidgetId>,
741 }
742
743 impl WidgetPodVisitor for Finder {
744 fn visit(&mut self, child: &WidgetPod) {
745 if self.target.is_some() {
746 return;
747 }
748 if child.accepts_focus() {
749 self.target = Some(child.id());
750 } else {
751 child.visit_children(self);
752 }
753 }
754 }
755
756 let mut finder = Finder { target: None };
757 root.visit_children(&mut finder);
758 finder.target
759}
760
761#[derive(Default)]
762pub struct WidgetChildren {
763 children: Vec<WidgetPod>,
764}
765
766impl WidgetChildren {
767 pub fn new() -> Self {
768 Self::default()
769 }
770
771 pub fn with_capacity(capacity: usize) -> Self {
772 Self {
773 children: Vec::with_capacity(capacity),
774 }
775 }
776
777 pub fn push<W>(&mut self, child: W)
778 where
779 W: Widget + 'static,
780 {
781 self.push_pod(WidgetPod::new(child));
782 }
783
784 pub fn push_pod(&mut self, child: WidgetPod) {
785 self.children.push(child);
786 }
787
788 pub fn len(&self) -> usize {
789 self.children.len()
790 }
791
792 pub fn is_empty(&self) -> bool {
793 self.children.is_empty()
794 }
795
796 pub fn as_slice(&self) -> &[WidgetPod] {
797 &self.children
798 }
799
800 pub fn as_mut_slice(&mut self) -> &mut [WidgetPod] {
801 &mut self.children
802 }
803
804 pub fn measure_child(
805 &mut self,
806 index: usize,
807 ctx: &mut MeasureCtx,
808 constraints: Constraints,
809 ) -> Size {
810 self.children[index].measure(ctx, constraints)
811 }
812
813 pub fn intrinsic_size_child(
814 &mut self,
815 index: usize,
816 ctx: &mut MeasureCtx,
817 axis: Axis,
818 available_cross: f32,
819 ) -> IntrinsicSize {
820 self.children[index].intrinsic_size(ctx, axis, available_cross)
821 }
822
823 pub fn arrange_child(&mut self, index: usize, ctx: &mut ArrangeCtx, bounds: Rect) {
824 self.children[index].arrange(ctx, bounds);
825 }
826
827 pub fn paint(&self, ctx: &mut PaintCtx) {
828 for child in &self.children {
829 child.paint(ctx);
830 }
831 }
832
833 pub fn semantics(&self, ctx: &mut SemanticsCtx) {
834 for child in &self.children {
835 child.semantics(ctx);
836 }
837 }
838
839 pub fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
840 for child in &self.children {
841 visitor.visit(child);
842 }
843 }
844
845 pub fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
846 for child in &mut self.children {
847 visitor.visit(child);
848 }
849 }
850}
851
852#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
853pub struct KeyedReconcile {
854 pub inserted: usize,
855 pub removed: usize,
856 pub moved: usize,
857 pub updated: usize,
858 pub unchanged: usize,
859 pub duplicate_keys: usize,
860}
861
862struct KeyedChild<K, T> {
863 key: K,
864 value: Signal<T>,
865 child: WidgetPod,
866}
867
868pub struct KeyedChildren<K, T> {
875 entries: Vec<KeyedChild<K, T>>,
876}
877
878impl<K, T> KeyedChildren<K, T> {
879 pub const fn new() -> Self {
880 Self {
881 entries: Vec::new(),
882 }
883 }
884
885 pub fn len(&self) -> usize {
886 self.entries.len()
887 }
888
889 pub fn is_empty(&self) -> bool {
890 self.entries.is_empty()
891 }
892
893 pub fn iter(&self) -> impl Iterator<Item = (&K, &Signal<T>, &WidgetPod)> {
894 self.entries
895 .iter()
896 .map(|entry| (&entry.key, &entry.value, &entry.child))
897 }
898
899 pub fn iter_mut(&mut self) -> impl Iterator<Item = (&K, &Signal<T>, &mut WidgetPod)> {
900 self.entries
901 .iter_mut()
902 .map(|entry| (&entry.key, &entry.value, &mut entry.child))
903 }
904
905 pub fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
906 for entry in &self.entries {
907 visitor.visit(&entry.child);
908 }
909 }
910
911 pub fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
912 for entry in &mut self.entries {
913 visitor.visit(&mut entry.child);
914 }
915 }
916}
917
918impl<K, T> KeyedChildren<K, T>
919where
920 K: Clone + Eq + Hash,
921 T: Clone + PartialEq + 'static,
922{
923 pub fn reconcile<I, KF, B, W>(
924 &mut self,
925 items: I,
926 mut key_for: KF,
927 mut build: B,
928 ) -> KeyedReconcile
929 where
930 I: IntoIterator<Item = T>,
931 KF: FnMut(&T) -> K,
932 B: FnMut(&K, Signal<T>) -> W,
933 W: Widget + 'static,
934 {
935 let previous_len = self.entries.len();
936 let mut previous = std::mem::take(&mut self.entries)
937 .into_iter()
938 .enumerate()
939 .map(|(index, entry)| (entry.key.clone(), (index, entry)))
940 .collect::<HashMap<_, _>>();
941 let mut seen = HashSet::new();
942 let mut next = Vec::new();
943 let mut report = KeyedReconcile::default();
944
945 for item in items {
946 let key = key_for(&item);
947 if !seen.insert(key.clone()) {
948 report.duplicate_keys += 1;
949 continue;
950 }
951
952 let next_index = next.len();
953 if let Some((previous_index, entry)) = previous.remove(&key) {
954 if previous_index != next_index {
955 report.moved += 1;
956 }
957 if entry.value.set(item) {
958 report.updated += 1;
959 } else {
960 report.unchanged += 1;
961 }
962 next.push(entry);
963 } else {
964 let value = Signal::named("Keyed item", item);
965 let child = WidgetPod::new(build(&key, value.clone()));
966 next.push(KeyedChild { key, value, child });
967 report.inserted += 1;
968 }
969 }
970
971 report.removed = previous.len();
972 debug_assert_eq!(previous_len + report.inserted, next.len() + report.removed);
973 self.entries = next;
974 report
975 }
976}
977
978impl<K, T> Default for KeyedChildren<K, T> {
979 fn default() -> Self {
980 Self::new()
981 }
982}
983
984pub struct WidgetPod {
992 id: WidgetId,
993 layout_state: LayoutState,
994 probe_cache: Option<Box<ProbeCache>>,
995 query_context: Option<crate::measure_cache::QueryContext>,
996 last_probe_invalidation: u64,
997 force_paint_boundary: bool,
998 inert: bool,
999 observed_phases: Cell<u8>,
1000 widget: Box<dyn Widget>,
1001}
1002
1003impl Drop for WidgetPod {
1004 fn drop(&mut self) {
1005 crate::layout_work::record(|work| work.dropped += 1);
1006 crate::reactive::clear_widget(self.id);
1007 }
1008}
1009
1010#[derive(Default)]
1013struct ProbeCache {
1014 revision: u64,
1015 promoted: bool,
1016 measurements: [Option<(Constraints, Option<Axis>, Size)>; 4],
1017 intrinsics: [Option<(f32, IntrinsicSize)>; 2],
1018}
1019
1020#[derive(Debug, Clone, Copy, PartialEq)]
1021struct LayoutState {
1022 measured_size: Size,
1023 arranged_bounds: Rect,
1024 relative_presentation_transform: Transform,
1025 presentation_transform: Transform,
1026 last_constraints: Constraints,
1027 measure_valid: bool,
1028 arrange_valid: bool,
1029}
1030
1031impl Default for LayoutState {
1032 fn default() -> Self {
1033 Self {
1034 measured_size: Size::ZERO,
1035 arranged_bounds: Rect::ZERO,
1036 relative_presentation_transform: Transform::IDENTITY,
1037 presentation_transform: Transform::IDENTITY,
1038 last_constraints: Constraints::default(),
1039 measure_valid: false,
1040 arrange_valid: false,
1041 }
1042 }
1043}
1044
1045impl WidgetPod {
1046 pub fn new<W>(widget: W) -> Self
1047 where
1048 W: Widget + 'static,
1049 {
1050 Self::new_boxed(Box::new(widget))
1051 }
1052
1053 pub fn new_boxed(widget: Box<dyn Widget>) -> Self {
1059 crate::layout_work::record(|work| work.constructed += 1);
1060 Self {
1061 id: WidgetId::new(NEXT_WIDGET_ID.fetch_add(1, Ordering::Relaxed)),
1062 layout_state: LayoutState::default(),
1063 probe_cache: None,
1064 query_context: None,
1065 last_probe_invalidation: 0,
1066 force_paint_boundary: false,
1067 inert: false,
1068 observed_phases: Cell::new(0),
1069 widget,
1070 }
1071 }
1072
1073 pub const fn id(&self) -> WidgetId {
1074 self.id
1075 }
1076
1077 pub const fn is_inert(&self) -> bool {
1081 self.inert
1082 }
1083
1084 pub fn set_inert(&mut self, inert: bool) {
1089 self.inert = inert;
1090 }
1091
1092 pub fn debug_name(&self) -> &'static str {
1093 self.widget.debug_name()
1094 }
1095
1096 pub fn diagnostics_snapshot(&self) -> WidgetDiagnosticsSnapshot {
1097 let mut ctx = WidgetDiagnosticsCtx::default();
1098 self.widget.diagnostics(&mut ctx);
1099 WidgetDiagnosticsSnapshot {
1100 widget_id: self.id,
1101 widget_name: self.widget.debug_name(),
1102 entries: ctx.into_entries(),
1103 }
1104 }
1105
1106 pub fn collect_diagnostics(&self, output: &mut Vec<WidgetDiagnosticsSnapshot>) {
1107 let snapshot = self.diagnostics_snapshot();
1108 if !snapshot.entries.is_empty() {
1109 output.push(snapshot);
1110 }
1111 let mut visitor = CollectDiagnosticsVisitor { output };
1112 self.visit_children(&mut visitor);
1113 }
1114
1115 pub const fn bounds(&self) -> Rect {
1116 self.layout_state.arranged_bounds
1117 }
1118
1119 pub const fn measured_size(&self) -> Size {
1120 self.layout_state.measured_size
1121 }
1122
1123 pub const fn presentation_transform(&self) -> Transform {
1124 self.layout_state.presentation_transform
1125 }
1126
1127 pub fn set_bounds(&mut self, bounds: Rect) {
1128 let delta = bounds.origin - self.layout_state.arranged_bounds.origin;
1129 crate::layout_work::record(|work| work.translations += u64::from(delta != Vector::ZERO));
1130 self.layout_state.arranged_bounds = bounds;
1131 self.layout_state.measured_size = bounds.size;
1132 self.layout_state.arrange_valid = true;
1133 self.translate_descendants(delta);
1134 }
1135
1136 pub fn probe_measure(&mut self, parent_ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
1144 self.probe_measure_query(parent_ctx, constraints, None)
1145 }
1146
1147 pub fn probe_measure_axis(
1150 &mut self,
1151 parent_ctx: &mut MeasureCtx,
1152 constraints: Constraints,
1153 axis: Axis,
1154 ) -> f32 {
1155 let size = self.probe_measure_query(parent_ctx, constraints, Some(axis));
1156 match axis {
1157 Axis::Horizontal => size.width,
1158 Axis::Vertical => size.height,
1159 }
1160 }
1161
1162 fn probe_measure_query(
1163 &mut self,
1164 parent_ctx: &mut MeasureCtx,
1165 constraints: Constraints,
1166 axis: Option<Axis>,
1167 ) -> Size {
1168 crate::layout_work::record(|work| work.probe_requests += 1);
1169 self.invalidate_probes(parent_ctx);
1170 if let Some(size) = self.probe_cache.as_ref().and_then(|cache| {
1171 cache
1172 .measurements
1173 .iter()
1174 .flatten()
1175 .find(|(key, kind, _)| *key == constraints && *kind == axis)
1176 .map(|(_, _, size)| *size)
1177 }) {
1178 crate::layout_work::record(|work| work.probe_cache_hits += 1);
1179 return size;
1180 }
1181 let cache = self.probe_cache.get_or_insert_with(Default::default);
1182 let revision = cache.revision;
1183 let shared = parent_ctx
1184 .query_cache
1185 .as_ref()
1186 .filter(|_| parent_ctx.scope.reusable_queries && cache.measurements[3].is_some());
1187 let key = shared
1188 .and_then(|_| crate::measure_cache::QueryKey::new(self.id, revision, constraints))
1189 .map(|key| key.with_axis(axis));
1190 let cached = shared
1191 .zip(parent_ctx.query_context)
1192 .zip(key.as_ref())
1193 .and_then(|((shared, context), key)| {
1194 let mut window = shared.borrow_mut();
1195 if !cache.promoted {
1196 for (constraints, axis, size) in cache.measurements.iter().flatten() {
1197 if let Some(key) =
1198 crate::measure_cache::QueryKey::new(self.id, revision, *constraints)
1199 {
1200 window.put(context, key.with_axis(*axis), *size);
1201 }
1202 }
1203 cache.promoted = true;
1204 }
1205 window.get(context, key)
1206 });
1207 let size = if let Some(size) = cached {
1208 crate::layout_work::record(|work| {
1209 work.probe_cache_hits += 1;
1210 work.shared_probe_cache_hits += 1;
1211 });
1212 size
1213 } else {
1214 let size = self.measure_impl(parent_ctx, constraints, true, axis);
1215 if let Some(cache) = parent_ctx
1216 .query_cache
1217 .as_ref()
1218 .filter(|_| parent_ctx.scope.reusable_queries)
1219 && let Some(context) = parent_ctx.query_context
1220 && let Some(key) = key
1221 {
1222 cache.borrow_mut().put(context, key, size);
1223 }
1224 size
1225 };
1226 let cache = self.probe_cache.get_or_insert_with(Default::default);
1227 if cache.measurements[0].is_none_or(|(key, kind, _)| key != constraints || kind != axis) {
1228 cache.measurements.rotate_right(1);
1229 }
1230 cache.measurements[0] = Some((constraints, axis, size));
1231 size
1232 }
1233
1234 fn invalidate_probes(&mut self, ctx: &MeasureCtx) -> bool {
1235 let context = ctx.query_context;
1236 let context_changed = self.query_context != context;
1237 self.query_context = context;
1238 let dirty = context_changed || ctx.child_force() || ctx.scope().must_remeasure(self.id);
1239 if context_changed {
1240 self.layout_state.measure_valid = false;
1241 self.layout_state.arrange_valid = false;
1242 }
1243 if dirty
1244 && (context_changed
1245 || !ctx.scope().reusable_queries
1246 || self.last_probe_invalidation != ctx.scope().generation)
1247 {
1248 if let Some(cache) = &mut self.probe_cache {
1249 let revision = cache.revision.wrapping_add(1);
1250 **cache = ProbeCache {
1251 revision,
1252 ..Default::default()
1253 };
1254 }
1255 if context_changed || self.last_probe_invalidation != ctx.scope().generation {
1258 crate::reactive::clear_probe_observations(self.id, &self.observed_phases);
1259 }
1260 self.last_probe_invalidation = ctx.scope().generation;
1261 }
1262 dirty
1263 }
1264
1265 pub fn measure(&mut self, parent_ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
1266 self.measure_impl(parent_ctx, constraints, false, None)
1267 }
1268
1269 fn measure_impl(
1270 &mut self,
1271 parent_ctx: &mut MeasureCtx,
1272 constraints: Constraints,
1273 size_only: bool,
1274 axis: Option<Axis>,
1275 ) -> Size {
1276 let probing = size_only || parent_ctx.probing;
1277 crate::layout_work::record(|work| work.measure_requests += 1);
1278 let force = parent_ctx.child_force();
1289 let must_remeasure = self.invalidate_probes(parent_ctx);
1290 if !probing
1291 && !must_remeasure
1292 && self.layout_state.measure_valid
1293 && self.layout_state.last_constraints == constraints
1294 {
1295 crate::layout_work::record(|work| work.measure_cache_hits += 1);
1296 return self.layout_state.measured_size;
1297 }
1298 crate::layout_work::record(|work| {
1299 work.measure_executions += 1;
1300 work.size_measure_executions += u64::from(size_only);
1301 work.forced_measures += u64::from(must_remeasure);
1302 work.constraint_changes += u64::from(
1303 self.layout_state.measure_valid
1304 && self.layout_state.last_constraints != constraints,
1305 );
1306 work.first_measures += u64::from(!self.layout_state.measure_valid);
1307 });
1308
1309 let mut child_ctx = parent_ctx.child(self.id, self.layout_state.arranged_bounds, force);
1310 child_ctx.probing = probing;
1311 let started = Instant::now();
1312 let observations = ObservationScope::new(
1313 parent_ctx.window_id(),
1314 self.id,
1315 if probing {
1316 ObservationPhase::MeasureProbe
1317 } else {
1318 ObservationPhase::Measure
1319 },
1320 &self.observed_phases,
1321 );
1322 let size = if let Some(axis) = axis {
1323 let extent = self.widget.measure_axis(&mut child_ctx, constraints, axis);
1324 match axis {
1325 Axis::Horizontal => Size::new(extent, 0.0),
1326 Axis::Vertical => Size::new(0.0, extent),
1327 }
1328 } else if size_only {
1329 self.widget.measure_size(&mut child_ctx, constraints)
1330 } else {
1331 self.widget.measure(&mut child_ctx, constraints)
1332 };
1333 drop(observations);
1334 record_widget_timing(
1335 self.id,
1336 self.widget.debug_name(),
1337 WidgetTimingPhase::Measure,
1338 started.elapsed(),
1339 );
1340 if axis.is_none() {
1342 self.layout_state.measured_size = size;
1343 self.layout_state.last_constraints = constraints;
1344 }
1345 self.layout_state.measure_valid = !size_only;
1346 if must_remeasure {
1352 self.layout_state.arrange_valid = false;
1353 }
1354 parent_ctx.extend_invalidations(child_ctx.take_invalidations());
1355 parent_ctx.extend_wake_requests(child_ctx.take_wake_requests());
1356 size
1357 }
1358
1359 pub fn intrinsic_size(
1360 &mut self,
1361 parent_ctx: &mut MeasureCtx,
1362 axis: Axis,
1363 available_cross: f32,
1364 ) -> IntrinsicSize {
1365 crate::layout_work::record(|work| match axis {
1366 Axis::Horizontal => work.intrinsic_horizontal += 1,
1367 Axis::Vertical => work.intrinsic_vertical += 1,
1368 });
1369 self.invalidate_probes(parent_ctx);
1370 let axis_index = match axis {
1371 Axis::Horizontal => 0,
1372 Axis::Vertical => 1,
1373 };
1374 let cross = available_cross;
1375 if let Some((key, size)) = self
1376 .probe_cache
1377 .as_ref()
1378 .and_then(|cache| cache.intrinsics[axis_index])
1379 && key == cross
1380 {
1381 crate::layout_work::record(|work| work.intrinsic_cache_hits += 1);
1382 return size;
1383 }
1384 crate::layout_work::record(|work| work.intrinsic_executions += 1);
1385 let force = parent_ctx.child_force();
1386 let mut child_ctx = parent_ctx.child(self.id, self.layout_state.arranged_bounds, force);
1387 child_ctx.probing = true;
1388 self.layout_state.measure_valid = false;
1391 let started = Instant::now();
1392 let phase = match axis {
1393 Axis::Horizontal => ObservationPhase::IntrinsicHorizontal,
1394 Axis::Vertical => ObservationPhase::IntrinsicVertical,
1395 };
1396 let observations = ObservationScope::new(
1397 parent_ctx.window_id(),
1398 self.id,
1399 phase,
1400 &self.observed_phases,
1401 );
1402 let intrinsic = self.widget.intrinsic_size(&mut child_ctx, axis, cross);
1403 drop(observations);
1404 record_widget_timing(
1405 self.id,
1406 self.widget.debug_name(),
1407 WidgetTimingPhase::Measure,
1408 started.elapsed(),
1409 );
1410 parent_ctx.extend_invalidations(child_ctx.take_invalidations());
1411 parent_ctx.extend_wake_requests(child_ctx.take_wake_requests());
1412 let intrinsic = IntrinsicSize::new(intrinsic.minimum, intrinsic.natural);
1413 self.probe_cache
1414 .get_or_insert_with(Default::default)
1415 .intrinsics[axis_index] = Some((cross, intrinsic));
1416 intrinsic
1417 }
1418
1419 pub fn arrange(&mut self, parent_ctx: &mut ArrangeCtx, bounds: Rect) {
1420 self.arrange_with_transform(parent_ctx, bounds, Transform::IDENTITY);
1421 }
1422
1423 pub fn arrange_transformed(
1426 &mut self,
1427 parent_ctx: &mut ArrangeCtx,
1428 bounds: Rect,
1429 transform: Transform,
1430 ) {
1431 self.arrange_with_transform(parent_ctx, bounds, transform);
1432 }
1433
1434 fn arrange_with_transform(
1435 &mut self,
1436 parent_ctx: &mut ArrangeCtx,
1437 bounds: Rect,
1438 transform: Transform,
1439 ) {
1440 crate::layout_work::record(|work| work.arrange_requests += 1);
1441 let presentation_transform = transform.then(parent_ctx.presentation_transform());
1442 if self.layout_state.arrange_valid
1443 && !parent_ctx.scope().must_rearrange(self.id)
1444 && self.layout_state.arranged_bounds == bounds
1445 {
1446 self.layout_state.relative_presentation_transform = transform;
1447 if self.layout_state.presentation_transform != presentation_transform {
1448 self.layout_state.presentation_transform = presentation_transform;
1449 let mut visitor = ReprojectPresentationVisitor {
1450 parent_transform: presentation_transform,
1451 };
1452 self.visit_children_mut(&mut visitor);
1453 }
1454 crate::layout_work::record(|work| work.arrange_cache_hits += 1);
1455 return;
1456 }
1457 crate::layout_work::record(|work| work.arrange_executions += 1);
1458 let size_changed = self.layout_state.arranged_bounds.size != bounds.size;
1459 let delta = bounds.origin - self.layout_state.arranged_bounds.origin;
1460 crate::layout_work::record(|work| work.translations += u64::from(delta != Vector::ZERO));
1461 self.layout_state.arranged_bounds = bounds;
1462 self.layout_state.relative_presentation_transform = transform;
1463 self.layout_state.presentation_transform = presentation_transform;
1464 self.layout_state.arrange_valid = true;
1465 self.translate_descendants(delta);
1466
1467 let mut child_ctx = ArrangeCtx::new_at_with_transform(
1468 parent_ctx.window_id(),
1469 self.id,
1470 parent_ctx.dpi(),
1471 parent_ctx.current_time(),
1472 self.layout_state.presentation_transform,
1473 Rc::clone(parent_ctx.scope_rc()),
1474 );
1475 if size_changed {
1478 child_ctx.request_paint();
1479 }
1480 let started = Instant::now();
1481 let observations = ObservationScope::new(
1482 parent_ctx.window_id(),
1483 self.id,
1484 ObservationPhase::Arrange,
1485 &self.observed_phases,
1486 );
1487 self.widget.arrange(&mut child_ctx, bounds);
1488 drop(observations);
1489 record_widget_timing(
1490 self.id,
1491 self.widget.debug_name(),
1492 WidgetTimingPhase::Arrange,
1493 started.elapsed(),
1494 );
1495 parent_ctx.extend_invalidations(child_ctx.take_invalidations());
1496 parent_ctx.extend_wake_requests(child_ctx.take_wake_requests());
1497 }
1498
1499 pub fn paint(&self, parent_ctx: &mut PaintCtx) {
1500 self.paint_into(parent_ctx, true);
1501 }
1502
1503 fn paint_into(&self, parent_ctx: &mut PaintCtx, emit_layer: bool) {
1504 let presentation_transform = self.layout_state.presentation_transform;
1505 let relative_transform =
1506 relative_transform(presentation_transform, parent_ctx.presentation_transform());
1507 let reusable = self.widget.supports_output_reuse();
1508 parent_ctx.output_reusable &= reusable;
1509 let output_cache = parent_ctx
1510 .output_cache
1511 .as_ref()
1512 .filter(|_| reusable)
1513 .cloned();
1514 let key = crate::output_cache::GeometryKey {
1515 bounds: self.bounds(),
1516 transform: presentation_transform,
1517 };
1518 let cached = output_cache.as_ref().and_then(|cache| {
1519 cache.paint(self.id, key, &parent_ctx.text_system.text_layout_registry())
1520 });
1521 if let Some(fragment) = &cached
1522 && relative_transform.is_identity()
1523 && !(emit_layer
1524 && presentation_transform.is_identity()
1525 && self.current_layer_options().emits_layer())
1526 {
1527 crate::layout_work::record(|work| work.paint_cache_hits += 1);
1528 parent_ctx.record_widget_paint_bounds(
1529 self.id,
1530 fragment
1531 .scene
1532 .paint_bounds()
1533 .unwrap_or(self.layout_state.arranged_bounds),
1534 );
1535 parent_ctx.scene.append_ref(&fragment.scene);
1536 parent_ctx
1537 .widget_paint_bounds
1538 .extend(fragment.bounds.iter().map(|(&id, &rect)| (id, rect)));
1539 parent_ctx.extend_ime_composition_rect(fragment.ime);
1540 return;
1541 }
1542 let mut child_ctx = PaintCtx::new_with_transform(
1543 parent_ctx.window_id(),
1544 self.id,
1545 self.layout_state.arranged_bounds,
1546 parent_ctx.focused_widget_id(),
1547 parent_ctx.dpi(),
1548 Arc::clone(&parent_ctx.text_system),
1549 Arc::clone(&parent_ctx.font_registry),
1550 Arc::clone(&parent_ctx.image_registry),
1551 presentation_transform,
1552 )
1553 .with_frame_time(parent_ctx.frame_time);
1554 child_ctx.output_cache = output_cache.clone();
1555 let (mut scene, images, mut widget_paint_bounds, mut ime_composition_rect) =
1556 if let Some(fragment) = cached {
1557 crate::layout_work::record(|work| work.paint_cache_hits += 1);
1558 (
1559 fragment.scene.clone(),
1560 Vec::new(),
1561 fragment.bounds.clone(),
1562 fragment.ime,
1563 )
1564 } else {
1565 crate::layout_work::record(|work| work.paint_executions += 1);
1566 let started = Instant::now();
1567 let observations = ObservationScope::new(
1568 parent_ctx.window_id(),
1569 self.id,
1570 ObservationPhase::Paint,
1571 &self.observed_phases,
1572 );
1573 self.widget.paint(&mut child_ctx);
1574 drop(observations);
1575 record_widget_timing(
1576 self.id,
1577 self.widget.debug_name(),
1578 WidgetTimingPhase::Paint,
1579 started.elapsed(),
1580 );
1581
1582 parent_ctx.output_reusable &= child_ctx.output_reusable;
1583 let can_reuse = child_ctx.output_reusable;
1584 let parts = child_ctx.into_parts();
1585 if can_reuse
1586 && parts.1.is_empty()
1587 && let Some(cache) = &output_cache
1588 {
1589 cache.put_paint(self.id, key, &parts.0, &parts.2, parts.3);
1590 }
1591 parts
1592 };
1593 if !relative_transform.is_identity() {
1594 let mut transformed = Scene::new();
1595 transformed.push(SceneCommand::PushTransform {
1596 transform: relative_transform,
1597 });
1598 transformed.append(scene);
1599 transformed.push(SceneCommand::PopTransform);
1600 scene = transformed;
1601 for bounds in widget_paint_bounds.values_mut() {
1602 *bounds = relative_transform.transform_rect_bbox(*bounds);
1603 }
1604 ime_composition_rect =
1605 ime_composition_rect.map(|bounds| relative_transform.transform_rect_bbox(bounds));
1606 }
1607 let paint_bounds = scene.paint_bounds().unwrap_or_else(|| {
1608 relative_transform.transform_rect_bbox(self.layout_state.arranged_bounds)
1609 });
1610 parent_ctx.record_widget_paint_bounds(self.id, paint_bounds);
1611 if emit_layer
1612 && presentation_transform.is_identity()
1613 && self.current_layer_options().emits_layer()
1614 {
1615 parent_ctx.push_layer(
1616 self.build_layer_descriptor(&scene, parent_ctx.frame_time),
1617 scene,
1618 );
1619 } else {
1620 parent_ctx.append_scene(scene);
1621 }
1622 parent_ctx.extend_widget_paint_bounds(widget_paint_bounds);
1623 parent_ctx.extend_images(images);
1624 parent_ctx.extend_ime_composition_rect(ime_composition_rect);
1625 }
1626
1627 pub(crate) fn paint_layer_contents_for(
1628 &mut self,
1629 target: WidgetId,
1630 parent_ctx: &mut PaintCtx,
1631 ) -> bool {
1632 self.find_mut(target, &mut |pod| {
1633 pod.paint_into(parent_ctx, false);
1634 })
1635 .is_some()
1636 }
1637
1638 pub(crate) fn layer_descriptor_for(
1639 &mut self,
1640 target: WidgetId,
1641 scene: &Scene,
1642 frame_time: f64,
1643 ) -> Option<SceneLayerDescriptor> {
1644 self.find_mut(target, &mut |pod| {
1645 pod.build_layer_descriptor(scene, frame_time)
1646 })
1647 }
1648
1649 pub fn semantics(&self, parent_ctx: &mut SemanticsCtx) {
1650 if self.inert {
1651 return;
1652 }
1653 let presentation_transform = self.layout_state.presentation_transform;
1654 let relative_transform =
1655 relative_transform(presentation_transform, parent_ctx.presentation_transform());
1656 let reusable = self.widget.supports_output_reuse();
1657 parent_ctx.output_reusable &= reusable;
1658 let output_cache = parent_ctx
1659 .output_cache
1660 .as_ref()
1661 .filter(|_| reusable)
1662 .cloned();
1663 let key = crate::output_cache::GeometryKey {
1664 bounds: self.bounds(),
1665 transform: presentation_transform,
1666 };
1667 if let Some(nodes) = output_cache
1668 .as_ref()
1669 .and_then(|cache| cache.semantics(self.id, key))
1670 {
1671 crate::layout_work::record(|work| work.semantics_cache_hits += 1);
1672 parent_ctx.extend_nodes(nodes.iter().cloned().map(|mut node| {
1673 if !relative_transform.is_identity() {
1674 node.bounds = relative_transform.transform_rect_bbox(node.bounds);
1675 }
1676 node
1677 }));
1678 return;
1679 }
1680 let mut child_ctx = SemanticsCtx::new_with_transform(
1681 parent_ctx.window_id(),
1682 self.id,
1683 parent_ctx.root_widget_id(),
1684 self.layout_state.arranged_bounds,
1685 parent_ctx.focused_widget_id(),
1686 presentation_transform,
1687 );
1688 child_ctx.output_cache = output_cache.clone();
1689 let mut nodes = {
1690 crate::layout_work::record(|work| work.semantics_executions += 1);
1691 let started = Instant::now();
1692 let observations = ObservationScope::new(
1693 parent_ctx.window_id(),
1694 self.id,
1695 ObservationPhase::Semantics,
1696 &self.observed_phases,
1697 );
1698 self.widget.semantics(&mut child_ctx);
1699 drop(observations);
1700 record_widget_timing(
1701 self.id,
1702 self.widget.debug_name(),
1703 WidgetTimingPhase::Semantics,
1704 started.elapsed(),
1705 );
1706 parent_ctx.output_reusable &= child_ctx.output_reusable;
1707 let can_reuse = child_ctx.output_reusable;
1708 let nodes = child_ctx.into_nodes();
1709 if can_reuse && let Some(cache) = &output_cache {
1710 cache.put_semantics(self.id, key, &nodes);
1711 }
1712 nodes
1713 };
1714 if !relative_transform.is_identity() {
1715 for node in &mut nodes {
1716 node.bounds = relative_transform.transform_rect_bbox(node.bounds);
1717 }
1718 }
1719 parent_ctx.extend_nodes(nodes);
1720 }
1721
1722 pub fn accepts_focus(&self) -> bool {
1727 self.widget.accepts_focus()
1728 }
1729
1730 pub fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
1736 self.widget.visit_children(visitor);
1737 }
1738
1739 pub(crate) fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
1740 self.widget.visit_children_mut(visitor);
1741 }
1742
1743 #[allow(clippy::too_many_arguments)]
1744 pub(crate) fn dispatch_event_for_path(
1745 &mut self,
1746 path: &[WidgetId],
1747 window_id: WindowId,
1748 dpi_info: DpiInfo,
1749 current_time: f64,
1750 phase: EventPhase,
1751 focused_widget: Option<WidgetId>,
1752 clipboard: &Clipboard,
1753 command_sender: &CommandSender,
1754 event: &Event,
1755 ) -> Option<EventDispatch> {
1756 self.find_mut_path(path, &mut |pod| {
1757 pod.dispatch_event(
1758 window_id,
1759 dpi_info,
1760 current_time,
1761 phase,
1762 focused_widget,
1763 clipboard,
1764 command_sender,
1765 event,
1766 )
1767 })
1768 }
1769
1770 #[allow(clippy::too_many_arguments)]
1771 pub(crate) fn dispatch_event_for(
1772 &mut self,
1773 target: WidgetId,
1774 window_id: WindowId,
1775 dpi_info: DpiInfo,
1776 current_time: f64,
1777 phase: EventPhase,
1778 focused_widget: Option<WidgetId>,
1779 clipboard: &Clipboard,
1780 command_sender: &CommandSender,
1781 event: &Event,
1782 ) -> Option<EventDispatch> {
1783 self.find_mut(target, &mut |pod| {
1784 pod.dispatch_event(
1785 window_id,
1786 dpi_info,
1787 current_time,
1788 phase,
1789 focused_widget,
1790 clipboard,
1791 command_sender,
1792 event,
1793 )
1794 })
1795 }
1796
1797 #[allow(clippy::too_many_arguments)]
1798 pub(crate) fn dispatch_command_for_path(
1799 &mut self,
1800 path: &[WidgetId],
1801 window_id: WindowId,
1802 dpi_info: DpiInfo,
1803 current_time: f64,
1804 focused_widget: Option<WidgetId>,
1805 clipboard: &Clipboard,
1806 command_sender: &CommandSender,
1807 command: &Command<'_>,
1808 ) -> Option<EventDispatch> {
1809 self.find_mut_path(path, &mut |pod| {
1810 pod.dispatch_command(
1811 window_id,
1812 dpi_info,
1813 current_time,
1814 focused_widget,
1815 clipboard,
1816 command_sender,
1817 command,
1818 )
1819 })
1820 }
1821
1822 #[allow(clippy::too_many_arguments)]
1823 pub(crate) fn dispatch_command_for(
1824 &mut self,
1825 target: WidgetId,
1826 window_id: WindowId,
1827 dpi_info: DpiInfo,
1828 current_time: f64,
1829 focused_widget: Option<WidgetId>,
1830 clipboard: &Clipboard,
1831 command_sender: &CommandSender,
1832 command: &Command<'_>,
1833 ) -> Option<EventDispatch> {
1834 self.find_mut(target, &mut |pod| {
1835 pod.dispatch_command(
1836 window_id,
1837 dpi_info,
1838 current_time,
1839 focused_widget,
1840 clipboard,
1841 command_sender,
1842 command,
1843 )
1844 })
1845 }
1846
1847 #[allow(clippy::too_many_arguments)]
1848 pub(crate) fn notify_focus_change_for(
1849 &mut self,
1850 target: WidgetId,
1851 window_id: WindowId,
1852 dpi_info: DpiInfo,
1853 current_time: f64,
1854 focused_widget: Option<WidgetId>,
1855 clipboard: &Clipboard,
1856 command_sender: &CommandSender,
1857 focused: bool,
1858 ) -> Option<EventDispatch> {
1859 self.find_mut(target, &mut |pod| {
1860 pod.focus_changed(
1861 window_id,
1862 dpi_info,
1863 current_time,
1864 focused_widget,
1865 clipboard,
1866 command_sender,
1867 focused,
1868 )
1869 })
1870 }
1871
1872 #[allow(clippy::too_many_arguments)]
1873 pub(crate) fn notify_focus_change_for_path(
1874 &mut self,
1875 path: &[WidgetId],
1876 window_id: WindowId,
1877 dpi_info: DpiInfo,
1878 current_time: f64,
1879 focused_widget: Option<WidgetId>,
1880 clipboard: &Clipboard,
1881 command_sender: &CommandSender,
1882 focused: bool,
1883 ) -> Option<EventDispatch> {
1884 self.find_mut_path(path, &mut |pod| {
1885 pod.focus_changed(
1886 window_id,
1887 dpi_info,
1888 current_time,
1889 focused_widget,
1890 clipboard,
1891 command_sender,
1892 focused,
1893 )
1894 })
1895 }
1896
1897 #[allow(clippy::too_many_arguments)]
1898 fn dispatch_event(
1899 &mut self,
1900 window_id: WindowId,
1901 dpi_info: DpiInfo,
1902 current_time: f64,
1903 phase: EventPhase,
1904 focused_widget: Option<WidgetId>,
1905 clipboard: &Clipboard,
1906 command_sender: &CommandSender,
1907 event: &Event,
1908 ) -> EventDispatch {
1909 let local_event = event_for_transform(
1910 event,
1911 self.layout_state
1912 .presentation_transform
1913 .inverse()
1914 .unwrap_or(Transform::IDENTITY),
1915 );
1916 let mut ctx = EventCtx::new(
1917 window_id,
1918 self.id,
1919 self.layout_state.arranged_bounds,
1920 dpi_info,
1921 current_time,
1922 phase,
1923 focused_widget,
1924 clipboard.clone(),
1925 command_sender.clone(),
1926 );
1927 self.widget.event(&mut ctx, &local_event);
1928 let mut drag_requests = ctx.take_drag_requests();
1929 for request in &mut drag_requests {
1930 match request {
1931 DragRequest::Begin(request) => {
1932 request.position = self
1933 .layout_state
1934 .presentation_transform
1935 .transform_point(request.position);
1936 }
1937 DragRequest::RefreshTargets => {}
1938 }
1939 }
1940 EventDispatch {
1941 handled: ctx.is_handled(),
1942 invalidations: ctx.take_invalidations(),
1943 focus_request: ctx.take_focus_request(),
1944 wake_requests: ctx.take_wake_requests(),
1945 pointer_capture_requests: ctx.take_pointer_capture_requests(),
1946 cursor_requests: ctx.take_cursor_requests(),
1947 drag_requests,
1948 drop_acceptances: ctx.take_drop_acceptances(),
1949 posted_events: ctx.take_posted_events(),
1950 posted_commands: ctx.take_posted_commands(),
1951 }
1952 }
1953
1954 #[allow(clippy::too_many_arguments)]
1955 fn dispatch_command(
1956 &mut self,
1957 window_id: WindowId,
1958 dpi_info: DpiInfo,
1959 current_time: f64,
1960 focused_widget: Option<WidgetId>,
1961 clipboard: &Clipboard,
1962 command_sender: &CommandSender,
1963 command: &Command<'_>,
1964 ) -> EventDispatch {
1965 let mut ctx = EventCtx::new(
1966 window_id,
1967 self.id,
1968 self.layout_state.arranged_bounds,
1969 dpi_info,
1970 current_time,
1971 EventPhase::Target,
1972 focused_widget,
1973 clipboard.clone(),
1974 command_sender.clone(),
1975 );
1976 self.widget.command(&mut ctx, command);
1977 ctx.into_dispatch()
1978 }
1979
1980 fn focus_changed(
1981 &mut self,
1982 window_id: WindowId,
1983 dpi_info: DpiInfo,
1984 current_time: f64,
1985 focused_widget: Option<WidgetId>,
1986 clipboard: &Clipboard,
1987 command_sender: &CommandSender,
1988 focused: bool,
1989 ) -> EventDispatch {
1990 let mut ctx = EventCtx::new(
1991 window_id,
1992 self.id,
1993 self.layout_state.arranged_bounds,
1994 dpi_info,
1995 current_time,
1996 EventPhase::Target,
1997 focused_widget,
1998 clipboard.clone(),
1999 command_sender.clone(),
2000 );
2001 self.widget.focus_changed(&mut ctx, focused);
2002 EventDispatch {
2003 handled: ctx.is_handled(),
2004 invalidations: ctx.take_invalidations(),
2005 focus_request: ctx.take_focus_request(),
2006 wake_requests: ctx.take_wake_requests(),
2007 pointer_capture_requests: ctx.take_pointer_capture_requests(),
2008 cursor_requests: ctx.take_cursor_requests(),
2009 drag_requests: ctx.take_drag_requests(),
2010 drop_acceptances: ctx.take_drop_acceptances(),
2011 posted_events: ctx.take_posted_events(),
2012 posted_commands: ctx.take_posted_commands(),
2013 }
2014 }
2015
2016 fn find_mut<R, F>(&mut self, target: WidgetId, f: &mut F) -> Option<R>
2017 where
2018 F: FnMut(&mut WidgetPod) -> R,
2019 {
2020 if self.id == target {
2021 return Some(f(self));
2022 }
2023
2024 let mut result = None;
2025 let mut visitor = FindMutVisitor {
2026 target,
2027 callback: f,
2028 result: &mut result,
2029 };
2030 self.visit_children_mut(&mut visitor);
2031 result
2032 }
2033
2034 fn find_mut_path<R, F>(&mut self, path: &[WidgetId], f: &mut F) -> Option<R>
2035 where
2036 F: FnMut(&mut WidgetPod) -> R,
2037 {
2038 let (¤t, rest) = path.split_first()?;
2039 if current != self.id {
2040 return None;
2041 }
2042
2043 if rest.is_empty() {
2044 return Some(f(self));
2045 }
2046
2047 let mut result = None;
2048 let mut visitor = FindPathMutVisitor {
2049 path: rest,
2050 callback: f,
2051 result: &mut result,
2052 };
2053 self.visit_children_mut(&mut visitor);
2054 result
2055 }
2056
2057 fn translate_descendants(&mut self, delta: Vector) {
2058 if delta == Vector::ZERO {
2059 return;
2060 }
2061
2062 let mut visitor = TranslateVisitor { delta };
2063 self.visit_children_mut(&mut visitor);
2064 }
2065
2066 fn translate_subtree(&mut self, delta: Vector) {
2067 if delta == Vector::ZERO {
2068 return;
2069 }
2070
2071 self.layout_state.arranged_bounds = self.layout_state.arranged_bounds.translate(delta);
2072 self.translate_descendants(delta);
2073 }
2074
2075 fn reproject_presentation_subtree(&mut self, parent_transform: Transform) {
2076 self.layout_state.presentation_transform = self
2077 .layout_state
2078 .relative_presentation_transform
2079 .then(parent_transform);
2080 let mut visitor = ReprojectPresentationVisitor {
2081 parent_transform: self.layout_state.presentation_transform,
2082 };
2083 self.visit_children_mut(&mut visitor);
2084 }
2085
2086 pub(crate) fn build_layer_descriptor(
2087 &self,
2088 scene: &Scene,
2089 frame_time: f64,
2090 ) -> SceneLayerDescriptor {
2091 let options = self.current_layer_options();
2092 SceneLayerDescriptor::new(
2093 SceneLayerId::from_widget(self.id),
2094 self.id,
2095 self.layout_state.arranged_bounds,
2096 )
2097 .with_content_bounds(
2098 scene
2099 .content_bounds()
2100 .unwrap_or(self.layout_state.arranged_bounds),
2101 )
2102 .with_paint_bounds(
2103 scene
2104 .paint_bounds()
2105 .unwrap_or(self.layout_state.arranged_bounds),
2106 )
2107 .with_properties(self.current_layer_properties(frame_time))
2108 .with_clip_to_ancestors(matches!(
2109 options.composition_mode,
2110 LayerCompositionMode::Normal
2111 ))
2112 .with_composition_mode(options.composition_mode)
2113 }
2114
2115 pub(crate) fn current_layer_options(&self) -> LayerOptions {
2116 let mut options = self.widget.layer_options();
2117 if self.force_paint_boundary {
2118 options.paint_boundary = PaintBoundaryMode::Explicit;
2119 }
2120 if !self.layout_state.presentation_transform.is_identity() {
2121 options.paint_boundary = PaintBoundaryMode::Flat;
2122 options.composition_mode = LayerCompositionMode::Normal;
2123 }
2124 options
2125 }
2126
2127 pub(crate) fn current_layer_properties(&self, frame_time: f64) -> LayerProperties {
2128 self.widget.layer_properties_at(frame_time)
2129 }
2130
2131 pub(crate) fn current_paint_boundary_mode(&self) -> PaintBoundaryMode {
2132 self.current_layer_options().paint_boundary
2133 }
2134
2135 pub(crate) fn current_stack_host_options(&self) -> Option<StackHostOptions> {
2136 self.widget.stack_host_options()
2137 }
2138
2139 pub(crate) fn current_stack_surface_options(&self) -> Option<StackSurfaceOptions> {
2140 self.widget.stack_surface_options()
2141 }
2142
2143 pub(crate) fn current_hit_test_self(&self) -> bool {
2144 self.widget.hit_test_self()
2145 }
2146
2147 pub(crate) fn current_overlay_options(&self) -> Option<OverlayOptions> {
2148 self.widget.overlay_options()
2149 }
2150
2151 pub(crate) fn layer_composition_mode_for(
2152 &mut self,
2153 target: WidgetId,
2154 ) -> Option<LayerCompositionMode> {
2155 self.find_mut(target, &mut |pod| {
2156 pod.current_layer_options().composition_mode
2157 })
2158 }
2159}
2160
2161struct ReprojectPresentationVisitor {
2162 parent_transform: Transform,
2163}
2164
2165impl WidgetPodMutVisitor for ReprojectPresentationVisitor {
2166 fn visit(&mut self, pod: &mut WidgetPod) {
2167 pod.reproject_presentation_subtree(self.parent_transform);
2168 }
2169}
2170
2171struct TranslateVisitor {
2172 delta: Vector,
2173}
2174
2175impl WidgetPodMutVisitor for TranslateVisitor {
2176 fn visit(&mut self, child: &mut WidgetPod) {
2177 child.translate_subtree(self.delta);
2178 }
2179}
2180
2181struct CollectDiagnosticsVisitor<'a> {
2182 output: &'a mut Vec<WidgetDiagnosticsSnapshot>,
2183}
2184
2185impl WidgetPodVisitor for CollectDiagnosticsVisitor<'_> {
2186 fn visit(&mut self, child: &WidgetPod) {
2187 child.collect_diagnostics(self.output);
2188 }
2189}
2190
2191struct FindMutVisitor<'a, F, R>
2192where
2193 F: FnMut(&mut WidgetPod) -> R,
2194{
2195 target: WidgetId,
2196 callback: &'a mut F,
2197 result: &'a mut Option<R>,
2198}
2199
2200impl<F, R> WidgetPodMutVisitor for FindMutVisitor<'_, F, R>
2201where
2202 F: FnMut(&mut WidgetPod) -> R,
2203{
2204 fn visit(&mut self, child: &mut WidgetPod) {
2205 if self.result.is_none() {
2206 *self.result = child.find_mut(self.target, self.callback);
2207 }
2208 }
2209}
2210
2211struct FindPathMutVisitor<'a, F, R>
2212where
2213 F: FnMut(&mut WidgetPod) -> R,
2214{
2215 path: &'a [WidgetId],
2216 callback: &'a mut F,
2217 result: &'a mut Option<R>,
2218}
2219
2220impl<F, R> WidgetPodMutVisitor for FindPathMutVisitor<'_, F, R>
2221where
2222 F: FnMut(&mut WidgetPod) -> R,
2223{
2224 fn visit(&mut self, child: &mut WidgetPod) {
2225 if self.result.is_none() && self.path.first().copied() == Some(child.id) {
2226 *self.result = child.find_mut_path(self.path, self.callback);
2227 }
2228 }
2229}
2230
2231#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2232pub(crate) enum FocusRequest {
2233 Focus(WidgetId),
2234 Clear,
2235 Keep,
2237}
2238
2239#[derive(Debug, Clone, Copy, PartialEq)]
2240pub(crate) enum WakeRequest {
2241 ScheduleTimer {
2242 token: TimerToken,
2243 deadline: f64,
2244 target: WidgetId,
2245 },
2246 CancelTimer {
2247 token: TimerToken,
2248 },
2249 RegisterAsync {
2250 token: AsyncWakeToken,
2251 target: WidgetId,
2252 },
2253 UnregisterAsync {
2254 token: AsyncWakeToken,
2255 },
2256 RequestAnimationFrame {
2257 target: WidgetId,
2258 },
2259 Motion {
2260 target: WidgetId,
2261 kind: InvalidationKind,
2262 until: f64,
2263 },
2264 MotionEnd {
2265 target: WidgetId,
2266 kind: InvalidationKind,
2267 until: f64,
2268 },
2269}
2270
2271#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2272pub(crate) enum PointerCaptureRequest {
2273 Capture { pointer_id: u64, target: WidgetId },
2274 Release { pointer_id: u64 },
2275}
2276
2277#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2278pub(crate) enum CursorRequest {
2279 Grab {
2280 target: WidgetId,
2281 mode: CursorGrabMode,
2282 },
2283 Visibility {
2284 target: WidgetId,
2285 visible: bool,
2286 },
2287}
2288
2289#[derive(Debug, Clone)]
2290pub(crate) struct BeginDragRequest {
2291 pub session_id: DragSessionId,
2292 pub scope_id: DragScopeId,
2293 pub pointer_id: u64,
2294 pub source: WidgetId,
2295 pub position: Point,
2296 pub payload: DragPayload,
2297 pub allowed_effects: DropEffects,
2298 pub preview_label: Option<String>,
2299}
2300
2301#[derive(Debug, Clone)]
2302pub(crate) enum DragRequest {
2303 Begin(BeginDragRequest),
2304 RefreshTargets,
2305}
2306
2307#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2308pub(crate) struct DropAcceptanceRequest {
2309 pub target: WidgetId,
2310 pub effect: DropEffect,
2311}
2312
2313#[derive(Debug, Clone)]
2316pub(crate) struct PostedEventRequest {
2317 pub target: WidgetId,
2318 pub event: Event,
2319}
2320
2321#[derive(Debug, Clone)]
2323pub(crate) struct PostedCommandRequest {
2324 pub command: QueuedCommand,
2325}
2326
2327#[derive(Debug, Clone)]
2328pub(crate) struct EventDispatch {
2329 pub handled: bool,
2330 pub invalidations: Vec<InvalidationRequest>,
2331 pub focus_request: Option<FocusRequest>,
2332 pub wake_requests: Vec<WakeRequest>,
2333 pub pointer_capture_requests: Vec<PointerCaptureRequest>,
2334 pub cursor_requests: Vec<CursorRequest>,
2335 pub drag_requests: Vec<DragRequest>,
2336 pub drop_acceptances: Vec<DropAcceptanceRequest>,
2337 pub posted_events: Vec<PostedEventRequest>,
2338 pub posted_commands: Vec<PostedCommandRequest>,
2339}
2340
2341#[derive(Debug, Clone)]
2342pub struct EventCtx {
2343 window_id: WindowId,
2344 widget_id: WidgetId,
2345 bounds: Rect,
2346 dpi_info: DpiInfo,
2347 current_time: f64,
2348 phase: EventPhase,
2349 focused_widget_id: Option<WidgetId>,
2350 clipboard: Clipboard,
2351 command_sender: CommandSender,
2352 handled: bool,
2353 invalidations: Vec<InvalidationRequest>,
2354 focus_request: Option<FocusRequest>,
2355 wake_requests: Vec<WakeRequest>,
2356 pointer_capture_requests: Vec<PointerCaptureRequest>,
2357 cursor_requests: Vec<CursorRequest>,
2358 drag_requests: Vec<DragRequest>,
2359 drop_acceptances: Vec<DropAcceptanceRequest>,
2360 posted_events: Vec<PostedEventRequest>,
2361 posted_commands: Vec<PostedCommandRequest>,
2362}
2363
2364impl EventCtx {
2365 #[allow(clippy::too_many_arguments)]
2366 pub(crate) fn new(
2367 window_id: WindowId,
2368 widget_id: WidgetId,
2369 bounds: Rect,
2370 dpi_info: DpiInfo,
2371 current_time: f64,
2372 phase: EventPhase,
2373 focused_widget_id: Option<WidgetId>,
2374 clipboard: Clipboard,
2375 command_sender: CommandSender,
2376 ) -> Self {
2377 Self {
2378 window_id,
2379 widget_id,
2380 bounds,
2381 dpi_info,
2382 current_time,
2383 phase,
2384 focused_widget_id,
2385 clipboard,
2386 command_sender,
2387 handled: false,
2388 invalidations: Vec::new(),
2389 focus_request: None,
2390 wake_requests: Vec::new(),
2391 pointer_capture_requests: Vec::new(),
2392 cursor_requests: Vec::new(),
2393 drag_requests: Vec::new(),
2394 drop_acceptances: Vec::new(),
2395 posted_events: Vec::new(),
2396 posted_commands: Vec::new(),
2397 }
2398 }
2399
2400 fn into_dispatch(mut self) -> EventDispatch {
2401 EventDispatch {
2402 handled: self.is_handled(),
2403 invalidations: self.take_invalidations(),
2404 focus_request: self.take_focus_request(),
2405 wake_requests: self.take_wake_requests(),
2406 pointer_capture_requests: self.take_pointer_capture_requests(),
2407 cursor_requests: self.take_cursor_requests(),
2408 drag_requests: self.take_drag_requests(),
2409 drop_acceptances: self.take_drop_acceptances(),
2410 posted_events: self.take_posted_events(),
2411 posted_commands: self.take_posted_commands(),
2412 }
2413 }
2414
2415 pub const fn window_id(&self) -> WindowId {
2416 self.window_id
2417 }
2418
2419 pub const fn widget_id(&self) -> WidgetId {
2420 self.widget_id
2421 }
2422
2423 pub fn observe<T, O>(&self, observable: &O, kind: InvalidationKind) -> T
2426 where
2427 O: Observable<T> + ?Sized,
2428 {
2429 crate::reactive::observe(self.window_id, self.widget_id, observable, kind)
2430 }
2431
2432 pub fn record_rebuild(&self, widget_name: &'static str, reason: impl Into<String>) {
2434 crate::diagnostics::record_widget_rebuild(
2435 self.window_id,
2436 self.widget_id,
2437 widget_name,
2438 reason,
2439 );
2440 }
2441
2442 pub const fn bounds(&self) -> Rect {
2443 self.bounds
2444 }
2445
2446 pub const fn dpi(&self) -> DpiInfo {
2447 self.dpi_info
2448 }
2449
2450 pub const fn current_time(&self) -> f64 {
2451 self.current_time
2452 }
2453
2454 pub fn motion_policy(&self) -> MotionPolicy {
2456 crate::motion_policy()
2457 }
2458
2459 pub fn animate<T>(&mut self, motion: &mut Motion<T>, target: T, spec: AnimationSpec) -> bool
2464 where
2465 T: Interpolate + Copy + PartialEq,
2466 {
2467 self.animate_after(motion, target, 0.0, spec)
2468 }
2469
2470 pub fn animate_after<T>(
2474 &mut self,
2475 motion: &mut Motion<T>,
2476 target: T,
2477 delay: f64,
2478 spec: AnimationSpec,
2479 ) -> bool
2480 where
2481 T: Interpolate + Copy + PartialEq,
2482 {
2483 let before = motion.target();
2484 let until = motion.start_after(target, self.current_time, delay, spec);
2485 if before != target {
2486 self.request_widget(motion.invalidation());
2489 }
2490 if let Some(until) = until {
2491 self.track_motion(until, motion.invalidation());
2492 }
2493 until.is_some()
2494 }
2495
2496 pub fn track_motion(&mut self, until: f64, kind: InvalidationKind) {
2499 self.track_motion_for(self.widget_id, until, kind);
2500 }
2501
2502 pub fn track_motion_for(&mut self, target: WidgetId, until: f64, kind: InvalidationKind) {
2505 self.wake_requests.push(WakeRequest::Motion {
2506 target,
2507 kind,
2508 until,
2509 });
2510 }
2511
2512 pub fn track_motion_end(&mut self, until: f64, kind: InvalidationKind) {
2516 self.track_motion_end_for(self.widget_id, until, kind);
2517 }
2518
2519 pub fn track_motion_end_for(&mut self, target: WidgetId, until: f64, kind: InvalidationKind) {
2521 self.wake_requests.push(WakeRequest::MotionEnd {
2522 target,
2523 kind,
2524 until,
2525 });
2526 }
2527
2528 pub const fn phase(&self) -> EventPhase {
2529 self.phase
2530 }
2531
2532 pub const fn focused_widget_id(&self) -> Option<WidgetId> {
2533 self.focused_widget_id
2534 }
2535
2536 pub fn is_focused(&self) -> bool {
2537 self.focused_widget_id == Some(self.widget_id)
2538 }
2539
2540 pub const fn is_handled(&self) -> bool {
2541 self.handled
2542 }
2543
2544 pub fn set_handled(&mut self) {
2545 self.handled = true;
2546 }
2547
2548 pub fn clipboard(&self) -> &Clipboard {
2552 &self.clipboard
2553 }
2554
2555 pub fn clipboard_text(&self) -> Option<String> {
2556 self.clipboard.text()
2557 }
2558
2559 pub fn set_clipboard_text(&mut self, text: impl AsRef<str>) {
2560 self.clipboard.set_text(text);
2561 }
2562
2563 pub fn command_sender(&self) -> &CommandSender {
2569 &self.command_sender
2570 }
2571
2572 pub fn post_event(&mut self, target: WidgetId, event: Event) {
2577 self.posted_events
2578 .push(PostedEventRequest { target, event });
2579 }
2580
2581 pub fn post_command<T>(&mut self, target: WidgetId, key: CommandKey<T>, payload: T)
2584 where
2585 T: Send + Sync + 'static,
2586 {
2587 self.posted_commands.push(PostedCommandRequest {
2588 command: queued_command(
2589 CommandTarget::Widget {
2590 window_id: self.window_id,
2591 widget_id: target,
2592 },
2593 CommandDelivery::Directed,
2594 key,
2595 payload,
2596 ),
2597 });
2598 }
2599
2600 pub fn request_focus(&mut self) {
2601 self.focus_request = Some(FocusRequest::Focus(self.widget_id));
2602 }
2603
2604 pub fn request_focus_for(&mut self, widget_id: WidgetId) {
2610 self.focus_request = Some(FocusRequest::Focus(widget_id));
2611 }
2612
2613 pub fn clear_focus(&mut self) {
2614 self.focus_request = Some(FocusRequest::Clear);
2615 }
2616
2617 pub fn keep_focus(&mut self) {
2622 self.focus_request = Some(FocusRequest::Keep);
2623 }
2624
2625 pub fn schedule_timer_at(&mut self, deadline: f64) -> TimerToken {
2626 let token = TimerToken::new(NEXT_TIMER_TOKEN.fetch_add(1, Ordering::Relaxed));
2627 self.wake_requests.push(WakeRequest::ScheduleTimer {
2628 token,
2629 deadline,
2630 target: self.widget_id,
2631 });
2632 token
2633 }
2634
2635 pub fn schedule_timer_after(&mut self, delay: f64) -> TimerToken {
2636 self.schedule_timer_at(self.current_time + delay)
2637 }
2638
2639 pub fn cancel_timer(&mut self, token: TimerToken) {
2640 self.wake_requests.push(WakeRequest::CancelTimer { token });
2641 }
2642
2643 pub fn register_async_wakeup(&mut self) -> AsyncWakeToken {
2644 let token = AsyncWakeToken::new(NEXT_ASYNC_WAKE_TOKEN.fetch_add(1, Ordering::Relaxed));
2645 self.wake_requests.push(WakeRequest::RegisterAsync {
2646 token,
2647 target: self.widget_id,
2648 });
2649 token
2650 }
2651
2652 pub fn unregister_async_wakeup(&mut self, token: AsyncWakeToken) {
2653 self.wake_requests
2654 .push(WakeRequest::UnregisterAsync { token });
2655 }
2656
2657 pub fn request_animation_frame(&mut self) {
2658 self.wake_requests.push(WakeRequest::RequestAnimationFrame {
2659 target: self.widget_id,
2660 });
2661 }
2662
2663 pub fn request_pointer_capture(&mut self, pointer_id: u64) {
2664 self.pointer_capture_requests
2665 .push(PointerCaptureRequest::Capture {
2666 pointer_id,
2667 target: self.widget_id,
2668 });
2669 }
2670
2671 pub fn release_pointer_capture(&mut self, pointer_id: u64) {
2672 self.pointer_capture_requests
2673 .push(PointerCaptureRequest::Release { pointer_id });
2674 }
2675
2676 pub fn request_cursor_grab(&mut self, mode: CursorGrabMode) {
2683 self.cursor_requests.push(CursorRequest::Grab {
2684 target: self.widget_id,
2685 mode,
2686 });
2687 }
2688
2689 pub fn request_cursor_visibility(&mut self, visible: bool) {
2694 self.cursor_requests.push(CursorRequest::Visibility {
2695 target: self.widget_id,
2696 visible,
2697 });
2698 }
2699
2700 pub fn begin_drag(
2705 &mut self,
2706 scope_id: DragScopeId,
2707 pointer_id: u64,
2708 position: Point,
2709 payload: DragPayload,
2710 allowed_effects: impl Into<DropEffects>,
2711 preview_label: Option<String>,
2712 ) -> DragSessionId {
2713 let session_id = DragSessionId::new(NEXT_DRAG_SESSION_ID.fetch_add(1, Ordering::Relaxed));
2714 self.drag_requests
2715 .push(DragRequest::Begin(BeginDragRequest {
2716 session_id,
2717 scope_id,
2718 pointer_id,
2719 source: self.widget_id,
2720 position,
2721 payload,
2722 allowed_effects: allowed_effects.into(),
2723 preview_label,
2724 }));
2725 session_id
2726 }
2727
2728 pub fn refresh_drag_targets(&mut self) {
2732 self.drag_requests.push(DragRequest::RefreshTargets);
2733 }
2734
2735 pub fn accept_drop(&mut self, effect: DropEffect) {
2736 if effect.is_none() {
2737 return;
2738 }
2739 self.drop_acceptances.push(DropAcceptanceRequest {
2740 target: self.widget_id,
2741 effect,
2742 });
2743 }
2744
2745 pub fn request(&mut self, request: InvalidationRequest) {
2746 self.invalidations.push(request);
2747 }
2748
2749 pub fn request_measure(&mut self) {
2750 self.request_widget(InvalidationKind::Measure);
2751 }
2752
2753 pub fn request_arrange(&mut self) {
2754 self.request_widget(InvalidationKind::Arrange);
2755 }
2756
2757 pub fn request_ordering(&mut self) {
2758 self.request_widget(InvalidationKind::Ordering);
2759 }
2760
2761 pub fn request_paint(&mut self) {
2762 self.request_widget(InvalidationKind::Paint);
2763 }
2764
2765 pub fn request_paint_rect(&mut self, rect: Rect) {
2766 self.request(
2767 InvalidationRequest::new(
2768 InvalidationTarget::Widget(self.widget_id),
2769 InvalidationKind::Paint,
2770 )
2771 .with_region(rect),
2772 );
2773 }
2774
2775 pub fn request_transform(&mut self) {
2776 self.request_widget(InvalidationKind::Transform);
2777 }
2778
2779 pub fn request_effect(&mut self) {
2780 self.request_widget(InvalidationKind::Effect);
2781 }
2782
2783 pub fn request_visibility(&mut self) {
2784 self.request_widget(InvalidationKind::Visibility);
2785 }
2786
2787 pub fn request_hit_test(&mut self) {
2788 self.request_widget(InvalidationKind::HitTest);
2789 }
2790
2791 pub fn request_text(&mut self) {
2792 self.request_widget(InvalidationKind::Text);
2793 }
2794
2795 pub fn request_semantics(&mut self) {
2796 self.request_widget(InvalidationKind::Semantics);
2797 }
2798
2799 pub fn request_resources(&mut self) {
2800 self.request_widget(InvalidationKind::Resources);
2801 }
2802
2803 pub fn invalidations(&self) -> &[InvalidationRequest] {
2804 &self.invalidations
2805 }
2806
2807 pub(crate) fn take_invalidations(&mut self) -> Vec<InvalidationRequest> {
2808 std::mem::take(&mut self.invalidations)
2809 }
2810
2811 pub(crate) fn take_focus_request(&mut self) -> Option<FocusRequest> {
2812 self.focus_request.take()
2813 }
2814
2815 pub(crate) fn take_wake_requests(&mut self) -> Vec<WakeRequest> {
2816 std::mem::take(&mut self.wake_requests)
2817 }
2818
2819 pub(crate) fn take_pointer_capture_requests(&mut self) -> Vec<PointerCaptureRequest> {
2820 std::mem::take(&mut self.pointer_capture_requests)
2821 }
2822
2823 pub(crate) fn take_cursor_requests(&mut self) -> Vec<CursorRequest> {
2824 std::mem::take(&mut self.cursor_requests)
2825 }
2826
2827 pub(crate) fn take_drag_requests(&mut self) -> Vec<DragRequest> {
2828 std::mem::take(&mut self.drag_requests)
2829 }
2830
2831 pub(crate) fn take_drop_acceptances(&mut self) -> Vec<DropAcceptanceRequest> {
2832 std::mem::take(&mut self.drop_acceptances)
2833 }
2834
2835 pub(crate) fn take_posted_events(&mut self) -> Vec<PostedEventRequest> {
2836 std::mem::take(&mut self.posted_events)
2837 }
2838
2839 pub(crate) fn take_posted_commands(&mut self) -> Vec<PostedCommandRequest> {
2840 std::mem::take(&mut self.posted_commands)
2841 }
2842
2843 fn request_widget(&mut self, kind: InvalidationKind) {
2844 self.request(InvalidationRequest::new(
2845 InvalidationTarget::Widget(self.widget_id),
2846 kind,
2847 ));
2848 }
2849}
2850
2851static NEXT_MEASURE_GENERATION: AtomicU64 = AtomicU64::new(1);
2862
2863#[derive(Debug)]
2864pub(crate) struct MeasureScope {
2865 generation: u64,
2866 reusable_queries: bool,
2867 force_all: bool,
2868 dirty: HashSet<WidgetId>,
2869 subtree_roots: HashSet<WidgetId>,
2870}
2871
2872#[derive(Debug, Default)]
2874pub(crate) struct ArrangeScope {
2875 force_all: bool,
2876 dirty: HashSet<WidgetId>,
2877}
2878
2879impl ArrangeScope {
2880 pub(crate) fn force_all() -> Self {
2881 Self {
2882 force_all: true,
2883 dirty: HashSet::new(),
2884 }
2885 }
2886
2887 pub(crate) fn scoped(dirty: HashSet<WidgetId>) -> Self {
2888 Self {
2889 force_all: false,
2890 dirty,
2891 }
2892 }
2893
2894 fn must_rearrange(&self, widget_id: WidgetId) -> bool {
2895 self.force_all || self.dirty.contains(&widget_id)
2896 }
2897}
2898
2899impl Default for MeasureScope {
2900 fn default() -> Self {
2901 Self {
2902 generation: NEXT_MEASURE_GENERATION.fetch_add(1, Ordering::Relaxed),
2903 reusable_queries: true,
2904 force_all: false,
2905 dirty: HashSet::new(),
2906 subtree_roots: HashSet::new(),
2907 }
2908 }
2909}
2910
2911impl MeasureScope {
2912 pub(crate) fn is_full_invalidation(&self) -> bool {
2913 self.force_all
2914 }
2915
2916 pub(crate) fn force_all() -> Self {
2917 Self {
2918 force_all: true,
2919 dirty: HashSet::new(),
2920 subtree_roots: HashSet::new(),
2921 ..Self::default()
2922 }
2923 }
2924
2925 pub(crate) fn scoped(dirty: HashSet<WidgetId>, subtree_roots: HashSet<WidgetId>) -> Self {
2926 Self {
2927 force_all: false,
2928 dirty,
2929 subtree_roots,
2930 ..Self::default()
2931 }
2932 }
2933
2934 fn must_remeasure(&self, widget_id: WidgetId) -> bool {
2935 self.force_all || self.dirty.contains(&widget_id)
2936 }
2937
2938 fn forces_subtree(&self, widget_id: WidgetId) -> bool {
2939 self.subtree_roots.contains(&widget_id)
2940 }
2941}
2942
2943#[derive(Debug, Clone)]
2944pub struct MeasureCtx {
2945 window_id: WindowId,
2946 widget_id: WidgetId,
2947 bounds: Rect,
2948 layout: LayoutContext,
2949 current_time: f64,
2950 invalidations: Vec<InvalidationRequest>,
2951 wake_requests: Vec<WakeRequest>,
2952 scope: Rc<MeasureScope>,
2953 force: bool,
2955 probing: bool,
2956 query_cache: Option<crate::measure_cache::SharedQueryCache>,
2957 query_context: Option<crate::measure_cache::QueryContext>,
2958}
2959
2960impl MeasureCtx {
2961 pub fn with_layout(
2962 window_id: WindowId,
2963 widget_id: WidgetId,
2964 bounds: Rect,
2965 layout: LayoutContext,
2966 ) -> Self {
2967 Self::with_layout_scoped(
2969 window_id,
2970 widget_id,
2971 bounds,
2972 layout,
2973 0.0,
2974 Rc::new(MeasureScope {
2975 reusable_queries: false,
2978 ..MeasureScope::force_all()
2979 }),
2980 true,
2981 )
2982 }
2983
2984 pub(crate) fn with_layout_scoped(
2985 window_id: WindowId,
2986 widget_id: WidgetId,
2987 bounds: Rect,
2988 layout: LayoutContext,
2989 current_time: f64,
2990 scope: Rc<MeasureScope>,
2991 force: bool,
2992 ) -> Self {
2993 Self {
2994 window_id,
2995 widget_id,
2996 bounds,
2997 layout,
2998 current_time,
2999 invalidations: Vec::new(),
3000 wake_requests: Vec::new(),
3001 scope,
3002 force,
3003 probing: false,
3004 query_cache: None,
3005 query_context: None,
3006 }
3007 }
3008
3009 #[cfg(test)]
3010 pub(crate) fn new(
3011 window_id: WindowId,
3012 widget_id: WidgetId,
3013 bounds: Rect,
3014 dpi_info: DpiInfo,
3015 text_system: Arc<TextSystem>,
3016 font_registry: Arc<FontRegistry>,
3017 image_registry: Arc<ImageRegistry>,
3018 ) -> Self {
3019 Self::with_layout(
3020 window_id,
3021 widget_id,
3022 bounds,
3023 LayoutContext::new(dpi_info, text_system, font_registry, image_registry),
3024 )
3025 }
3026
3027 pub(crate) fn new_scoped_at(
3028 window_id: WindowId,
3029 widget_id: WidgetId,
3030 bounds: Rect,
3031 dpi_info: DpiInfo,
3032 text_system: Arc<TextSystem>,
3033 font_registry: Arc<FontRegistry>,
3034 image_registry: Arc<ImageRegistry>,
3035 scope: Rc<MeasureScope>,
3036 current_time: f64,
3037 ) -> Self {
3038 Self::with_layout_scoped(
3039 window_id,
3040 widget_id,
3041 bounds,
3042 LayoutContext::new(dpi_info, text_system, font_registry, image_registry),
3043 current_time,
3044 scope,
3045 false,
3046 )
3047 }
3048
3049 pub(crate) fn set_query_cache(&mut self, cache: crate::measure_cache::SharedQueryCache) {
3050 self.query_context = Some(cache.borrow().context());
3051 self.query_cache = Some(cache);
3052 }
3053
3054 pub(crate) fn scope(&self) -> &MeasureScope {
3055 &self.scope
3056 }
3057
3058 pub(crate) fn child_force(&self) -> bool {
3062 self.force || self.scope.forces_subtree(self.widget_id)
3063 }
3064
3065 pub(crate) fn child(&self, widget_id: WidgetId, bounds: Rect, force: bool) -> Self {
3068 let mut child = Self::with_layout_scoped(
3069 self.window_id,
3070 widget_id,
3071 bounds,
3072 self.layout.clone(),
3073 self.current_time,
3074 Rc::clone(&self.scope),
3075 force,
3076 );
3077 child.probing = self.probing;
3078 child.query_cache = self.query_cache.clone();
3079 child.query_context = self.query_context;
3080 child
3081 }
3082
3083 pub const fn window_id(&self) -> WindowId {
3084 self.window_id
3085 }
3086
3087 pub const fn widget_id(&self) -> WidgetId {
3088 self.widget_id
3089 }
3090
3091 pub fn observe<T, O>(&self, observable: &O) -> T
3093 where
3094 O: Observable<T> + ?Sized,
3095 {
3096 self.observe_with(observable, InvalidationKind::Measure)
3097 }
3098
3099 pub fn observe_with<T, O>(&self, observable: &O, kind: InvalidationKind) -> T
3101 where
3102 O: Observable<T> + ?Sized,
3103 {
3104 crate::reactive::observe(self.window_id, self.widget_id, observable, kind)
3105 }
3106
3107 pub fn record_rebuild(&self, widget_name: &'static str, reason: impl Into<String>) {
3109 crate::diagnostics::record_widget_rebuild(
3110 self.window_id,
3111 self.widget_id,
3112 widget_name,
3113 reason,
3114 );
3115 }
3116
3117 pub const fn bounds(&self) -> Rect {
3118 self.bounds
3119 }
3120
3121 pub const fn layout(&self) -> &LayoutContext {
3122 &self.layout
3123 }
3124
3125 pub const fn dpi(&self) -> DpiInfo {
3126 self.layout.dpi()
3127 }
3128
3129 pub const fn current_time(&self) -> f64 {
3130 self.current_time
3131 }
3132
3133 pub fn motion_policy(&self) -> MotionPolicy {
3135 crate::motion_policy()
3136 }
3137
3138 pub fn animate<T>(&mut self, motion: &mut Motion<T>, target: T, spec: AnimationSpec) -> bool
3143 where
3144 T: Interpolate + Copy + PartialEq,
3145 {
3146 self.animate_after(motion, target, 0.0, spec)
3147 }
3148
3149 pub fn animate_after<T>(
3153 &mut self,
3154 motion: &mut Motion<T>,
3155 target: T,
3156 delay: f64,
3157 spec: AnimationSpec,
3158 ) -> bool
3159 where
3160 T: Interpolate + Copy + PartialEq,
3161 {
3162 let before = motion.target();
3163 let until = motion.start_after(target, self.current_time, delay, spec);
3164 if before != target {
3165 self.request_widget(motion.invalidation());
3168 }
3169 if let Some(until) = until {
3170 self.track_motion(until, motion.invalidation());
3171 }
3172 until.is_some()
3173 }
3174
3175 pub fn track_motion(&mut self, until: f64, kind: InvalidationKind) {
3178 self.track_motion_for(self.widget_id, until, kind);
3179 }
3180
3181 pub fn track_motion_for(&mut self, target: WidgetId, until: f64, kind: InvalidationKind) {
3184 self.wake_requests.push(WakeRequest::Motion {
3185 target,
3186 kind,
3187 until,
3188 });
3189 }
3190
3191 pub fn track_motion_end(&mut self, until: f64, kind: InvalidationKind) {
3195 self.track_motion_end_for(self.widget_id, until, kind);
3196 }
3197
3198 pub fn track_motion_end_for(&mut self, target: WidgetId, until: f64, kind: InvalidationKind) {
3200 self.wake_requests.push(WakeRequest::MotionEnd {
3201 target,
3202 kind,
3203 until,
3204 });
3205 }
3206
3207 pub fn request(&mut self, request: InvalidationRequest) {
3208 self.invalidations.push(request);
3209 }
3210
3211 pub fn request_measure(&mut self) {
3212 self.request_widget(InvalidationKind::Measure);
3213 }
3214
3215 pub fn request_arrange(&mut self) {
3216 self.request_widget(InvalidationKind::Arrange);
3217 }
3218
3219 pub fn request_ordering(&mut self) {
3220 self.request_widget(InvalidationKind::Ordering);
3221 }
3222
3223 pub fn request_paint(&mut self) {
3224 self.request_widget(InvalidationKind::Paint);
3225 }
3226
3227 pub fn request_semantics(&mut self) {
3228 self.request_widget(InvalidationKind::Semantics);
3229 }
3230
3231 pub fn request_animation_frame(&mut self) {
3232 self.wake_requests.push(WakeRequest::RequestAnimationFrame {
3233 target: self.widget_id,
3234 });
3235 }
3236
3237 pub fn invalidations(&self) -> &[InvalidationRequest] {
3238 &self.invalidations
3239 }
3240
3241 pub(crate) fn take_invalidations(&mut self) -> Vec<InvalidationRequest> {
3242 std::mem::take(&mut self.invalidations)
3243 }
3244
3245 pub(crate) fn take_wake_requests(&mut self) -> Vec<WakeRequest> {
3246 std::mem::take(&mut self.wake_requests)
3247 }
3248
3249 pub(crate) fn extend_invalidations(&mut self, invalidations: Vec<InvalidationRequest>) {
3250 self.invalidations.extend(invalidations);
3251 }
3252
3253 pub(crate) fn extend_wake_requests(&mut self, wake_requests: Vec<WakeRequest>) {
3254 self.wake_requests.extend(wake_requests);
3255 }
3256
3257 fn request_widget(&mut self, kind: InvalidationKind) {
3258 self.request(InvalidationRequest::new(
3259 InvalidationTarget::Widget(self.widget_id),
3260 kind,
3261 ));
3262 }
3263}
3264
3265#[derive(Debug, Clone)]
3266pub struct ArrangeCtx {
3267 window_id: WindowId,
3268 widget_id: WidgetId,
3269 dpi_info: DpiInfo,
3270 current_time: f64,
3271 presentation_transform: Transform,
3272 scope: Rc<ArrangeScope>,
3273 invalidations: Vec<InvalidationRequest>,
3274 wake_requests: Vec<WakeRequest>,
3275}
3276
3277impl ArrangeCtx {
3278 #[cfg(test)]
3279 pub(crate) fn new(window_id: WindowId, widget_id: WidgetId, dpi_info: DpiInfo) -> Self {
3280 Self::new_at(window_id, widget_id, dpi_info, 0.0)
3281 }
3282
3283 #[cfg(test)]
3284 pub(crate) fn new_at(
3285 window_id: WindowId,
3286 widget_id: WidgetId,
3287 dpi_info: DpiInfo,
3288 current_time: f64,
3289 ) -> Self {
3290 Self::new_at_with_transform(
3291 window_id,
3292 widget_id,
3293 dpi_info,
3294 current_time,
3295 Transform::IDENTITY,
3296 Rc::new(ArrangeScope::force_all()),
3297 )
3298 }
3299
3300 pub(crate) fn new_scoped_at(
3301 window_id: WindowId,
3302 widget_id: WidgetId,
3303 dpi_info: DpiInfo,
3304 current_time: f64,
3305 scope: Rc<ArrangeScope>,
3306 ) -> Self {
3307 Self::new_at_with_transform(
3308 window_id,
3309 widget_id,
3310 dpi_info,
3311 current_time,
3312 Transform::IDENTITY,
3313 scope,
3314 )
3315 }
3316
3317 pub(crate) fn new_at_with_transform(
3318 window_id: WindowId,
3319 widget_id: WidgetId,
3320 dpi_info: DpiInfo,
3321 current_time: f64,
3322 presentation_transform: Transform,
3323 scope: Rc<ArrangeScope>,
3324 ) -> Self {
3325 Self {
3326 window_id,
3327 widget_id,
3328 dpi_info,
3329 current_time,
3330 presentation_transform,
3331 scope,
3332 invalidations: Vec::new(),
3333 wake_requests: Vec::new(),
3334 }
3335 }
3336
3337 pub const fn window_id(&self) -> WindowId {
3338 self.window_id
3339 }
3340
3341 pub const fn widget_id(&self) -> WidgetId {
3342 self.widget_id
3343 }
3344
3345 pub const fn presentation_transform(&self) -> Transform {
3346 self.presentation_transform
3347 }
3348
3349 pub(crate) fn scope(&self) -> &ArrangeScope {
3350 self.scope.as_ref()
3351 }
3352
3353 pub(crate) fn scope_rc(&self) -> &Rc<ArrangeScope> {
3354 &self.scope
3355 }
3356
3357 pub fn observe<T, O>(&self, observable: &O) -> T
3359 where
3360 O: Observable<T> + ?Sized,
3361 {
3362 self.observe_with(observable, InvalidationKind::Arrange)
3363 }
3364
3365 pub fn observe_with<T, O>(&self, observable: &O, kind: InvalidationKind) -> T
3367 where
3368 O: Observable<T> + ?Sized,
3369 {
3370 crate::reactive::observe(self.window_id, self.widget_id, observable, kind)
3371 }
3372
3373 pub const fn dpi(&self) -> DpiInfo {
3374 self.dpi_info
3375 }
3376
3377 pub const fn current_time(&self) -> f64 {
3378 self.current_time
3379 }
3380
3381 pub fn motion_policy(&self) -> MotionPolicy {
3383 crate::motion_policy()
3384 }
3385
3386 pub fn animate<T>(&mut self, motion: &mut Motion<T>, target: T, spec: AnimationSpec) -> bool
3391 where
3392 T: Interpolate + Copy + PartialEq,
3393 {
3394 self.animate_after(motion, target, 0.0, spec)
3395 }
3396
3397 pub fn animate_after<T>(
3401 &mut self,
3402 motion: &mut Motion<T>,
3403 target: T,
3404 delay: f64,
3405 spec: AnimationSpec,
3406 ) -> bool
3407 where
3408 T: Interpolate + Copy + PartialEq,
3409 {
3410 let before = motion.target();
3411 let until = motion.start_after(target, self.current_time, delay, spec);
3412 if before != target {
3413 self.request_widget(motion.invalidation());
3416 }
3417 if let Some(until) = until {
3418 self.track_motion(until, motion.invalidation());
3419 }
3420 until.is_some()
3421 }
3422
3423 pub fn track_motion(&mut self, until: f64, kind: InvalidationKind) {
3426 self.track_motion_for(self.widget_id, until, kind);
3427 }
3428
3429 pub fn track_motion_for(&mut self, target: WidgetId, until: f64, kind: InvalidationKind) {
3432 self.wake_requests.push(WakeRequest::Motion {
3433 target,
3434 kind,
3435 until,
3436 });
3437 }
3438
3439 pub fn track_motion_end(&mut self, until: f64, kind: InvalidationKind) {
3443 self.track_motion_end_for(self.widget_id, until, kind);
3444 }
3445
3446 pub fn track_motion_end_for(&mut self, target: WidgetId, until: f64, kind: InvalidationKind) {
3448 self.wake_requests.push(WakeRequest::MotionEnd {
3449 target,
3450 kind,
3451 until,
3452 });
3453 }
3454
3455 pub fn request(&mut self, request: InvalidationRequest) {
3456 self.invalidations.push(request);
3457 }
3458
3459 pub fn request_measure(&mut self) {
3460 self.request_widget(InvalidationKind::Measure);
3461 }
3462
3463 pub fn request_arrange(&mut self) {
3464 self.request_widget(InvalidationKind::Arrange);
3465 }
3466
3467 pub fn request_ordering(&mut self) {
3468 self.request_widget(InvalidationKind::Ordering);
3469 }
3470
3471 pub fn request_paint(&mut self) {
3472 self.request_widget(InvalidationKind::Paint);
3473 }
3474
3475 pub fn request_semantics(&mut self) {
3476 self.request_widget(InvalidationKind::Semantics);
3477 }
3478
3479 pub fn request_transform(&mut self) {
3480 self.request_widget(InvalidationKind::Transform);
3481 }
3482
3483 pub fn request_animation_frame(&mut self) {
3488 self.wake_requests.push(WakeRequest::RequestAnimationFrame {
3489 target: self.widget_id,
3490 });
3491 }
3492
3493 pub fn invalidations(&self) -> &[InvalidationRequest] {
3494 &self.invalidations
3495 }
3496
3497 pub(crate) fn take_invalidations(&mut self) -> Vec<InvalidationRequest> {
3498 std::mem::take(&mut self.invalidations)
3499 }
3500
3501 pub(crate) fn take_wake_requests(&mut self) -> Vec<WakeRequest> {
3502 std::mem::take(&mut self.wake_requests)
3503 }
3504
3505 pub(crate) fn extend_invalidations(&mut self, invalidations: Vec<InvalidationRequest>) {
3506 self.invalidations.extend(invalidations);
3507 }
3508
3509 pub(crate) fn extend_wake_requests(&mut self, wake_requests: Vec<WakeRequest>) {
3510 self.wake_requests.extend(wake_requests);
3511 }
3512
3513 fn request_widget(&mut self, kind: InvalidationKind) {
3514 self.request(InvalidationRequest::new(
3515 InvalidationTarget::Widget(self.widget_id),
3516 kind,
3517 ));
3518 }
3519}
3520
3521#[derive(Debug, Clone)]
3522pub struct PaintCtx {
3523 pub(crate) output_cache: Option<crate::output_cache::OutputScope>,
3524 output_reusable: bool,
3525 window_id: WindowId,
3526 widget_id: WidgetId,
3527 focused_widget_id: Option<WidgetId>,
3528 bounds: Rect,
3529 presentation_transform: Transform,
3530 dpi_info: DpiInfo,
3531 text_system: Arc<TextSystem>,
3532 font_registry: Arc<FontRegistry>,
3533 image_registry: Arc<ImageRegistry>,
3534 scene: Scene,
3535 images: Vec<(ImageHandle, PaintImageResource)>,
3536 widget_paint_bounds: HashMap<WidgetId, Rect>,
3537 ime_composition_rect: Option<Rect>,
3538 frame_time: f64,
3539}
3540
3541macro_rules! impl_animate_ctx {
3542 ($($ctx:ty),*) => {$(
3543 impl crate::motion::AnimateCtx for $ctx {
3544 fn animate_after<T>(
3545 &mut self,
3546 motion: &mut Motion<T>,
3547 target: T,
3548 delay: f64,
3549 spec: AnimationSpec,
3550 ) -> bool
3551 where
3552 T: Interpolate + Copy + PartialEq,
3553 {
3554 <$ctx>::animate_after(self, motion, target, delay, spec)
3555 }
3556 }
3557 )*};
3558}
3559
3560impl_animate_ctx!(EventCtx, MeasureCtx, ArrangeCtx);
3561
3562impl FrameClock for PaintCtx {
3563 fn frame_time(&self) -> f64 {
3564 self.frame_time
3565 }
3566}
3567
3568impl FrameClock for EventCtx {
3569 fn frame_time(&self) -> f64 {
3570 self.current_time
3571 }
3572}
3573
3574impl FrameClock for MeasureCtx {
3575 fn frame_time(&self) -> f64 {
3576 self.current_time
3577 }
3578}
3579
3580impl FrameClock for ArrangeCtx {
3581 fn frame_time(&self) -> f64 {
3582 self.current_time
3583 }
3584}
3585
3586#[derive(Debug, Clone)]
3587pub(crate) enum PaintImageResource {
3588 Cpu(RegisteredImage),
3589 External(RegisteredExternalImage),
3590}
3591
3592impl PaintCtx {
3593 pub fn motion_policy(&self) -> MotionPolicy {
3596 crate::motion_policy()
3597 }
3598
3599 pub fn output_color_range(&self) -> Option<crate::OutputColorRange> {
3603 self.observe(&crate::window_output_color_range_signal(self.window_id))
3604 }
3605
3606 pub(crate) fn new(
3607 window_id: WindowId,
3608 widget_id: WidgetId,
3609 bounds: Rect,
3610 focused_widget_id: Option<WidgetId>,
3611 dpi_info: DpiInfo,
3612 text_system: Arc<TextSystem>,
3613 font_registry: Arc<FontRegistry>,
3614 image_registry: Arc<ImageRegistry>,
3615 ) -> Self {
3616 Self::new_with_transform(
3617 window_id,
3618 widget_id,
3619 bounds,
3620 focused_widget_id,
3621 dpi_info,
3622 text_system,
3623 font_registry,
3624 image_registry,
3625 Transform::IDENTITY,
3626 )
3627 }
3628
3629 #[allow(clippy::too_many_arguments)]
3630 pub(crate) fn new_with_transform(
3631 window_id: WindowId,
3632 widget_id: WidgetId,
3633 bounds: Rect,
3634 focused_widget_id: Option<WidgetId>,
3635 dpi_info: DpiInfo,
3636 text_system: Arc<TextSystem>,
3637 font_registry: Arc<FontRegistry>,
3638 image_registry: Arc<ImageRegistry>,
3639 presentation_transform: Transform,
3640 ) -> Self {
3641 Self {
3642 output_cache: None,
3643 output_reusable: true,
3644 window_id,
3645 widget_id,
3646 focused_widget_id,
3647 bounds,
3648 presentation_transform,
3649 dpi_info,
3650 text_system,
3651 font_registry,
3652 image_registry,
3653 scene: Scene::new(),
3654 images: Vec::new(),
3655 widget_paint_bounds: HashMap::new(),
3656 ime_composition_rect: None,
3657 frame_time: 0.0,
3658 }
3659 }
3660
3661 pub(crate) const fn with_frame_time(mut self, frame_time: f64) -> Self {
3662 self.frame_time = frame_time;
3663 self
3664 }
3665
3666 pub const fn frame_time(&self) -> f64 {
3669 self.frame_time
3670 }
3671
3672 pub const fn window_id(&self) -> WindowId {
3673 self.window_id
3674 }
3675
3676 pub const fn widget_id(&self) -> WidgetId {
3677 self.widget_id
3678 }
3679
3680 pub const fn presentation_transform(&self) -> Transform {
3681 self.presentation_transform
3682 }
3683
3684 pub fn observe<T, O>(&self, observable: &O) -> T
3686 where
3687 O: Observable<T> + ?Sized,
3688 {
3689 self.observe_with(observable, InvalidationKind::Paint)
3690 }
3691
3692 pub fn observe_with<T, O>(&self, observable: &O, kind: InvalidationKind) -> T
3694 where
3695 O: Observable<T> + ?Sized,
3696 {
3697 crate::reactive::observe(self.window_id, self.widget_id, observable, kind)
3698 }
3699
3700 pub const fn focused_widget_id(&self) -> Option<WidgetId> {
3701 self.focused_widget_id
3702 }
3703
3704 pub fn is_focused(&self) -> bool {
3705 self.focused_widget_id == Some(self.widget_id)
3706 }
3707
3708 pub const fn bounds(&self) -> Rect {
3709 self.bounds
3710 }
3711
3712 pub const fn dpi(&self) -> DpiInfo {
3713 self.dpi_info
3714 }
3715
3716 pub fn measure_text(
3717 &self,
3718 text: impl Into<String>,
3719 style: TextStyle,
3720 ) -> sui_core::Result<TextMeasurement> {
3721 self.text_system
3722 .measure_text(text, style, self.font_registry.as_ref())
3723 }
3724
3725 pub fn shape_text(
3726 &self,
3727 text: impl Into<String>,
3728 box_size: Size,
3729 style: TextStyle,
3730 ) -> sui_core::Result<TextLayout> {
3731 self.text_system
3732 .shape_text(text, box_size, style, self.font_registry.as_ref())
3733 }
3734
3735 pub fn layout_text_document(&self, request: TextLayoutRequest) -> sui_core::Result<TextLayout> {
3736 self.text_system
3737 .layout_document(request, self.font_registry.as_ref())
3738 }
3739
3740 pub fn clear(&mut self, color: Color) {
3741 self.scene.push(SceneCommand::Clear(color));
3742 }
3743
3744 pub fn fill(&mut self, path: impl Into<Path>, brush: impl Into<Brush>) {
3745 self.scene.push(SceneCommand::FillPath {
3746 path: path.into(),
3747 brush: brush.into(),
3748 });
3749 }
3750
3751 pub fn fill_rect(&mut self, rect: Rect, brush: impl Into<Brush>) {
3752 self.scene.push(SceneCommand::FillRect {
3753 rect,
3754 brush: brush.into(),
3755 });
3756 }
3757
3758 pub fn fill_bounds(&mut self, brush: impl Into<Brush>) {
3759 self.fill_rect(self.bounds, brush);
3760 }
3761
3762 pub fn stroke(&mut self, path: impl Into<Path>, brush: impl Into<Brush>, stroke: StrokeStyle) {
3763 self.scene.push(SceneCommand::StrokePath {
3764 path: path.into(),
3765 brush: brush.into(),
3766 stroke,
3767 });
3768 }
3769
3770 pub fn stroke_rect(&mut self, rect: Rect, brush: impl Into<Brush>, stroke: StrokeStyle) {
3771 self.scene.push(SceneCommand::StrokeRect {
3772 rect,
3773 brush: brush.into(),
3774 stroke,
3775 });
3776 }
3777
3778 pub fn stroke_bounds(&mut self, brush: impl Into<Brush>, stroke: StrokeStyle) {
3779 self.stroke_rect(self.bounds, brush, stroke);
3780 }
3781
3782 pub fn draw_text(&mut self, rect: Rect, text: impl Into<String>, style: TextStyle) {
3783 let text = text.into();
3784 let paint_color = style.color;
3785 let mut layout_style = style.clone();
3786 layout_style.color = Color::WHITE;
3787 let layout_run = TextRun {
3788 rect,
3789 text: text.clone(),
3790 style: layout_style,
3791 };
3792 let fallback_run = TextRun { rect, text, style };
3793
3794 match self.text_system.shape_text_run_persistent(
3795 Some(stable_text_run_handle(&layout_run)),
3796 &layout_run,
3797 self.font_registry.as_ref(),
3798 ) {
3799 Ok(layout) => self.scene.push(SceneCommand::DrawShapedText(
3800 ShapedText::new(rect.origin, &layout).with_color(paint_color),
3801 )),
3802 Err(_) => self.scene.push(SceneCommand::DrawText(fallback_run)),
3803 }
3804 }
3805
3806 pub fn draw_text_layout(&mut self, origin: Point, layout: &TextLayout) {
3807 let persistent = self.text_system.adopt_layout(layout.clone());
3808 self.draw_persistent_text_layout(origin, &persistent);
3809 }
3810
3811 pub fn draw_text_layout_with_color(
3812 &mut self,
3813 origin: Point,
3814 layout: &TextLayout,
3815 color: Color,
3816 ) {
3817 let persistent = self.text_system.adopt_layout(layout.clone());
3818 self.draw_persistent_text_layout_with_color(origin, &persistent, color);
3819 }
3820
3821 pub fn draw_persistent_text_layout(&mut self, origin: Point, layout: &PersistentTextLayout) {
3822 self.text_system.touch_persistent_layout(layout);
3823 self.scene
3824 .push(SceneCommand::DrawShapedText(ShapedText::new(
3825 origin, layout,
3826 )));
3827 }
3828
3829 pub fn draw_persistent_text_layout_with_color(
3830 &mut self,
3831 origin: Point,
3832 layout: &PersistentTextLayout,
3833 color: Color,
3834 ) {
3835 self.text_system.touch_persistent_layout(layout);
3836 self.scene.push(SceneCommand::DrawShapedText(
3837 ShapedText::new(origin, layout).with_color(color),
3838 ));
3839 }
3840
3841 pub fn draw_persistent_text_layout_window(
3842 &mut self,
3843 origin: Point,
3844 layout: &PersistentTextLayout,
3845 line_range: std::ops::Range<usize>,
3846 ) {
3847 self.text_system.touch_persistent_layout(layout);
3848 self.scene
3849 .push(SceneCommand::DrawShapedTextWindow(ShapedTextWindow::new(
3850 origin, layout, line_range,
3851 )));
3852 }
3853
3854 pub fn draw_persistent_text_layout_window_with_color(
3855 &mut self,
3856 origin: Point,
3857 layout: &PersistentTextLayout,
3858 line_range: std::ops::Range<usize>,
3859 color: Color,
3860 ) {
3861 self.text_system.touch_persistent_layout(layout);
3862 self.scene.push(SceneCommand::DrawShapedTextWindow(
3863 ShapedTextWindow::new(origin, layout, line_range).with_color(color),
3864 ));
3865 }
3866
3867 pub fn label(&mut self, rect: Rect, text: impl Into<String>, color: Color) {
3868 self.draw_text(rect, text, TextStyle::new(color));
3869 }
3870
3871 pub fn push_text_render_policy(&mut self, policy: TextRenderPolicy) {
3872 self.scene.push(SceneCommand::PushTextRenderPolicy {
3873 policy: policy.normalized(),
3874 });
3875 }
3876
3877 pub fn pop_text_render_policy(&mut self) {
3878 self.scene.push(SceneCommand::PopTextRenderPolicy);
3879 }
3880
3881 pub fn draw_image(&mut self, rect: Rect, image: sui_core::ImageHandle) {
3882 self.scene.push(SceneCommand::DrawImage {
3883 rect,
3884 source: ImageSource::new(image),
3885 });
3886 }
3887
3888 pub fn image_registered(&self, image: ImageHandle) -> bool {
3889 self.image_registry.contains(image)
3890 || self.images.iter().any(|(handle, _)| *handle == image)
3891 }
3892
3893 pub fn draw_image_source(&mut self, rect: Rect, source: ImageSource) {
3894 self.scene.push(SceneCommand::DrawImage { rect, source });
3895 }
3896
3897 pub fn draw_image_quad(&mut self, points: [Point; 4], image: ImageHandle) {
3898 self.draw_image_quad_source(points, ImageSource::new(image));
3899 }
3900
3901 pub fn draw_image_quad_source(&mut self, points: [Point; 4], source: ImageSource) {
3902 self.scene
3903 .push(SceneCommand::DrawImageQuad { points, source });
3904 }
3905
3906 pub fn widget_image_handle(&self, slot: u64) -> ImageHandle {
3907 let mut hasher = DefaultHasher::new();
3908 self.widget_id.hash(&mut hasher);
3909 slot.hash(&mut hasher);
3910 ImageHandle::new(WIDGET_IMAGE_HANDLE_NAMESPACE | (hasher.finish() >> 1))
3911 }
3912
3913 pub fn register_image(&mut self, handle: ImageHandle, image: RegisteredImage) {
3914 self.images.push((handle, PaintImageResource::Cpu(image)));
3915 }
3916
3917 pub fn register_external_image(&mut self, handle: ImageHandle, image: RegisteredExternalImage) {
3924 self.images
3925 .push((handle, PaintImageResource::External(image)));
3926 }
3927
3928 pub fn draw_shader_rect(&mut self, rect: Rect, shader: WidgetShader) {
3929 self.scene
3930 .push(SceneCommand::DrawShaderRect { rect, shader });
3931 }
3932
3933 pub fn fill_rrect(&mut self, rect: Rect, radii: [f32; 4], brush: impl Into<Brush>) {
3935 self.scene.push(SceneCommand::FillRoundedRect {
3936 rect,
3937 radii,
3938 brush: brush.into(),
3939 border: None,
3940 shadow: None,
3941 });
3942 }
3943
3944 pub fn fill_rrect_bordered(
3946 &mut self,
3947 rect: Rect,
3948 radii: [f32; 4],
3949 brush: impl Into<Brush>,
3950 border: Border,
3951 ) {
3952 self.scene.push(SceneCommand::FillRoundedRect {
3953 rect,
3954 radii,
3955 brush: brush.into(),
3956 border: Some(border),
3957 shadow: None,
3958 });
3959 }
3960
3961 pub fn draw_shadow(&mut self, rect: Rect, radii: [f32; 4], shadow: ShadowParams) {
3963 self.scene.push(SceneCommand::FillRoundedRect {
3964 rect,
3965 radii,
3966 brush: Brush::Solid(Color::TRANSPARENT),
3967 border: None,
3968 shadow: Some(shadow),
3969 });
3970 }
3971
3972 pub fn fill_rrect_with_shadow(
3974 &mut self,
3975 rect: Rect,
3976 radii: [f32; 4],
3977 brush: impl Into<Brush>,
3978 shadow: ShadowParams,
3979 ) {
3980 self.scene.push(SceneCommand::FillRoundedRect {
3981 rect,
3982 radii,
3983 brush: brush.into(),
3984 border: None,
3985 shadow: Some(shadow),
3986 });
3987 }
3988
3989 pub fn push_clip(&mut self, path: impl Into<Path>) {
3990 self.scene
3991 .push(SceneCommand::PushClipPath { path: path.into() });
3992 }
3993
3994 pub fn push_clip_rect(&mut self, rect: Rect) {
3995 self.scene.push(SceneCommand::PushClip { rect });
3996 }
3997
3998 pub fn pop_clip(&mut self) {
3999 self.scene.push(SceneCommand::PopClip);
4000 }
4001
4002 pub fn push_transform(&mut self, transform: Transform) {
4003 self.scene.push(SceneCommand::PushTransform { transform });
4004 }
4005
4006 pub fn with_transform<R>(
4017 &mut self,
4018 transform: Transform,
4019 paint: impl FnOnce(&mut PaintCtx) -> R,
4020 ) -> R {
4021 let presentation_transform = transform.then(self.presentation_transform);
4022 let mut child_ctx = PaintCtx::new_with_transform(
4023 self.window_id,
4024 self.widget_id,
4025 self.bounds,
4026 self.focused_widget_id,
4027 self.dpi_info,
4028 Arc::clone(&self.text_system),
4029 Arc::clone(&self.font_registry),
4030 Arc::clone(&self.image_registry),
4031 presentation_transform,
4032 )
4033 .with_frame_time(self.frame_time);
4034 let output = paint(&mut child_ctx);
4035 let (scene, images, mut widget_paint_bounds, ime_composition_rect) = child_ctx.into_parts();
4036
4037 if !scene.commands().is_empty() {
4038 self.scene.push(SceneCommand::PushTransform { transform });
4039 self.scene.append(scene);
4040 self.scene.push(SceneCommand::PopTransform);
4041 }
4042 for bounds in widget_paint_bounds.values_mut() {
4043 *bounds = transform.transform_rect_bbox(*bounds);
4044 }
4045 self.extend_widget_paint_bounds(widget_paint_bounds);
4046 self.extend_images(images);
4047 self.extend_ime_composition_rect(
4048 ime_composition_rect.map(|bounds| transform.transform_rect_bbox(bounds)),
4049 );
4050 output
4051 }
4052
4053 pub fn translate(&mut self, delta: Vector) {
4054 self.push_transform(Transform::translation_vector(delta));
4055 }
4056
4057 pub fn pop_transform(&mut self) {
4058 self.scene.push(SceneCommand::PopTransform);
4059 }
4060
4061 pub fn push(&mut self, command: SceneCommand) {
4062 self.scene.push(command);
4063 }
4064
4065 pub fn push_retained_scene_layer(&mut self, owner: WidgetId, bounds: Rect, scene: Arc<Scene>) {
4073 let content_bounds = scene.content_bounds().unwrap_or(bounds);
4074 let paint_bounds = scene.paint_bounds().unwrap_or(bounds);
4075 let descriptor = SceneLayerDescriptor::new(SceneLayerId::from_widget(owner), owner, bounds)
4076 .with_content_bounds(content_bounds)
4077 .with_paint_bounds(paint_bounds)
4078 .with_hit_test(false);
4079 self.scene
4080 .push(SceneCommand::Layer(SceneLayer::from_shared_descriptor(
4081 descriptor, scene,
4082 )));
4083 self.record_widget_paint_bounds(owner, paint_bounds);
4084 }
4085
4086 pub fn with_retained_scene_layer<R>(
4095 &mut self,
4096 owner: WidgetId,
4097 bounds: Rect,
4098 paint: impl FnOnce(&mut PaintCtx) -> R,
4099 ) -> R {
4100 let mut child_ctx = PaintCtx::new_with_transform(
4101 self.window_id,
4102 owner,
4103 bounds,
4104 self.focused_widget_id,
4105 self.dpi_info,
4106 Arc::clone(&self.text_system),
4107 Arc::clone(&self.font_registry),
4108 Arc::clone(&self.image_registry),
4109 self.presentation_transform,
4110 )
4111 .with_frame_time(self.frame_time);
4112 child_ctx.output_cache = self.output_cache.clone();
4113 let output = paint(&mut child_ctx);
4114 self.output_reusable &= child_ctx.output_reusable;
4115 let (scene, images, widget_paint_bounds, ime_composition_rect) = child_ctx.into_parts();
4116
4117 if !scene.commands().is_empty() {
4118 self.push_retained_scene_layer(owner, bounds, Arc::new(scene));
4119 }
4120 self.extend_widget_paint_bounds(widget_paint_bounds);
4121 self.extend_images(images);
4122 self.extend_ime_composition_rect(ime_composition_rect);
4123 output
4124 }
4125
4126 pub fn scene(&self) -> &Scene {
4127 &self.scene
4128 }
4129
4130 pub fn scene_mut(&mut self) -> &mut Scene {
4131 &mut self.scene
4132 }
4133
4134 pub fn set_ime_composition_rect(&mut self, rect: Rect) {
4135 self.ime_composition_rect = Some(rect);
4136 }
4137
4138 pub fn clear_ime_composition_rect(&mut self) {
4139 self.ime_composition_rect = None;
4140 }
4141
4142 pub const fn ime_composition_rect(&self) -> Option<Rect> {
4143 self.ime_composition_rect
4144 }
4145
4146 pub(crate) fn push_layer(&mut self, descriptor: SceneLayerDescriptor, scene: Scene) {
4147 self.scene
4148 .push(SceneCommand::Layer(SceneLayer::from_descriptor(
4149 descriptor, scene,
4150 )));
4151 }
4152
4153 pub(crate) fn append_scene(&mut self, scene: Scene) {
4154 self.scene.append(scene);
4155 }
4156
4157 pub(crate) fn record_widget_paint_bounds(&mut self, widget_id: WidgetId, paint_bounds: Rect) {
4158 self.widget_paint_bounds.insert(widget_id, paint_bounds);
4159 }
4160
4161 pub(crate) fn extend_widget_paint_bounds(
4162 &mut self,
4163 widget_paint_bounds: HashMap<WidgetId, Rect>,
4164 ) {
4165 self.widget_paint_bounds.extend(widget_paint_bounds);
4166 }
4167
4168 pub(crate) fn extend_images(&mut self, images: Vec<(ImageHandle, PaintImageResource)>) {
4169 self.images.extend(images);
4170 }
4171
4172 pub(crate) fn extend_ime_composition_rect(&mut self, ime_composition_rect: Option<Rect>) {
4173 if ime_composition_rect.is_some() {
4174 self.ime_composition_rect = ime_composition_rect;
4175 }
4176 }
4177
4178 pub(crate) fn into_parts(
4179 self,
4180 ) -> (
4181 Scene,
4182 Vec<(ImageHandle, PaintImageResource)>,
4183 HashMap<WidgetId, Rect>,
4184 Option<Rect>,
4185 ) {
4186 (
4187 self.scene,
4188 self.images,
4189 self.widget_paint_bounds,
4190 self.ime_composition_rect,
4191 )
4192 }
4193}
4194
4195fn stable_text_run_handle(run: &TextRun) -> TextLayoutHandle {
4196 let mut hasher = DefaultHasher::new();
4197 run.text.hash(&mut hasher);
4198 run.rect.size.width.to_bits().hash(&mut hasher);
4199 run.rect.size.height.to_bits().hash(&mut hasher);
4200 run.style.font.map(|font| font.get()).hash(&mut hasher);
4201 run.style.font_size.to_bits().hash(&mut hasher);
4202 run.style.line_height.to_bits().hash(&mut hasher);
4203 run.style.weight.value().hash(&mut hasher);
4204 run.style.style.hash(&mut hasher);
4205 run.style.stretch.hash(&mut hasher);
4206 run.style.features.hash(&mut hasher);
4207 TextLayoutHandle::new(hasher.finish().max(1))
4208}
4209
4210#[derive(Debug, Clone)]
4211pub struct SemanticsCtx {
4212 pub(crate) output_cache: Option<crate::output_cache::OutputScope>,
4213 output_reusable: bool,
4214 window_id: WindowId,
4215 widget_id: WidgetId,
4216 root_widget_id: WidgetId,
4217 focused_widget_id: Option<WidgetId>,
4218 bounds: Rect,
4219 presentation_transform: Transform,
4220 nodes: Vec<SemanticsNode>,
4221}
4222
4223impl SemanticsCtx {
4224 pub(crate) fn new(
4225 window_id: WindowId,
4226 widget_id: WidgetId,
4227 root_widget_id: WidgetId,
4228 bounds: Rect,
4229 focused_widget_id: Option<WidgetId>,
4230 ) -> Self {
4231 Self::new_with_transform(
4232 window_id,
4233 widget_id,
4234 root_widget_id,
4235 bounds,
4236 focused_widget_id,
4237 Transform::IDENTITY,
4238 )
4239 }
4240
4241 pub(crate) fn new_with_transform(
4242 window_id: WindowId,
4243 widget_id: WidgetId,
4244 root_widget_id: WidgetId,
4245 bounds: Rect,
4246 focused_widget_id: Option<WidgetId>,
4247 presentation_transform: Transform,
4248 ) -> Self {
4249 Self {
4250 output_cache: None,
4251 output_reusable: true,
4252 window_id,
4253 widget_id,
4254 root_widget_id,
4255 focused_widget_id,
4256 bounds,
4257 presentation_transform,
4258 nodes: Vec::new(),
4259 }
4260 }
4261
4262 pub const fn window_id(&self) -> WindowId {
4263 self.window_id
4264 }
4265
4266 pub const fn widget_id(&self) -> WidgetId {
4267 self.widget_id
4268 }
4269
4270 pub fn observe<T, O>(&self, observable: &O) -> T
4272 where
4273 O: Observable<T> + ?Sized,
4274 {
4275 self.observe_with(observable, InvalidationKind::Semantics)
4276 }
4277
4278 pub fn observe_with<T, O>(&self, observable: &O, kind: InvalidationKind) -> T
4280 where
4281 O: Observable<T> + ?Sized,
4282 {
4283 crate::reactive::observe(self.window_id, self.widget_id, observable, kind)
4284 }
4285
4286 pub const fn root_widget_id(&self) -> WidgetId {
4287 self.root_widget_id
4288 }
4289
4290 pub const fn focused_widget_id(&self) -> Option<WidgetId> {
4291 self.focused_widget_id
4292 }
4293
4294 pub fn is_focused(&self) -> bool {
4295 self.focused_widget_id == Some(self.widget_id)
4296 }
4297
4298 pub const fn bounds(&self) -> Rect {
4299 self.bounds
4300 }
4301
4302 pub const fn presentation_transform(&self) -> Transform {
4303 self.presentation_transform
4304 }
4305
4306 pub fn push(&mut self, node: SemanticsNode) {
4307 self.nodes.push(node);
4308 }
4309
4310 pub fn nodes(&self) -> &[SemanticsNode] {
4311 &self.nodes
4312 }
4313
4314 pub(crate) fn extend_nodes(&mut self, nodes: impl IntoIterator<Item = SemanticsNode>) {
4315 self.nodes.extend(nodes);
4316 }
4317
4318 pub(crate) fn into_nodes(self) -> Vec<SemanticsNode> {
4319 self.nodes
4320 }
4321}
4322
4323#[cfg(test)]
4324mod tests {
4325 use std::sync::Arc;
4326
4327 use crate::CommandSender;
4328
4329 use super::{
4330 ArrangeCtx, EventCtx, EventPhase, KeyedChildren, MeasureCtx, MeasureScope, PaintCtx,
4331 SemanticsCtx, SingleChild, WakeRequest, Widget, WidgetChildren, WidgetPod,
4332 WidgetPodMutVisitor, WidgetPodVisitor, relative_transform,
4333 };
4334 use std::cell::Cell;
4335 use std::collections::{HashMap, HashSet};
4336 use std::rc::Rc;
4337 use sui_core::{
4338 Clipboard, Color, DpiInfo, ImageHandle, InvalidationKind, Point, Rect, SemanticsNode,
4339 SemanticsRole, Size, Transform, Vector, WidgetId, WindowId,
4340 };
4341
4342 #[test]
4343 fn relative_transform_canonicalizes_shared_transform_roundoff() {
4344 let parent = Transform::new(0.32, 0.0, 0.0, 0.32, 1430.0, 510.0);
4345 let roundoff = Transform::new(0.32000002, 0.0, 0.0, 0.31999996, 1430.0001, 509.99994);
4346 assert_eq!(relative_transform(roundoff, parent), Transform::IDENTITY);
4347
4348 let translated = Transform::new(0.32, 0.0, 0.0, 0.32, 1430.01, 510.0);
4349 assert!(!relative_transform(translated, parent).is_identity());
4350 }
4351 use sui_layout::{Constraints, LayoutContext};
4352 use sui_scene::{ImageRegistry, RegisteredImage, SceneCommand, StrokeStyle};
4353 use sui_text::{FontRegistry, FontWeight, TextRun, TextStyle, TextSystem};
4354
4355 fn measure_ctx(window_id: WindowId, widget_id: WidgetId) -> MeasureCtx {
4356 MeasureCtx::new(
4357 window_id,
4358 widget_id,
4359 Rect::ZERO,
4360 DpiInfo::default(),
4361 std::sync::Arc::new(TextSystem::new()),
4362 std::sync::Arc::new(FontRegistry::new()),
4363 std::sync::Arc::new(ImageRegistry::new()),
4364 )
4365 }
4366
4367 #[test]
4368 fn measure_ctx_wraps_reusable_layout_context() {
4369 let mut images = ImageRegistry::new();
4370 images.insert(
4371 ImageHandle::new(9),
4372 RegisteredImage::from_rgba8(3, 2, vec![255; 3 * 2 * 4]).unwrap(),
4373 );
4374 let layout = LayoutContext::new(
4375 DpiInfo::new(
4376 1.5,
4377 Some(144.0),
4378 Size::new(200.0, 100.0),
4379 Size::new(300.0, 150.0),
4380 ),
4381 Arc::new(TextSystem::new()),
4382 Arc::new(FontRegistry::new()),
4383 Arc::new(images),
4384 );
4385
4386 let measure = MeasureCtx::with_layout(
4387 WindowId::new(1),
4388 WidgetId::new(2),
4389 Rect::new(4.0, 6.0, 32.0, 18.0),
4390 layout.clone(),
4391 );
4392
4393 assert_eq!(measure.dpi(), layout.dpi());
4394 assert_eq!(measure.bounds(), Rect::new(4.0, 6.0, 32.0, 18.0));
4395 assert_eq!(
4396 measure.layout().image_size(ImageHandle::new(9)),
4397 Some(Size::new(3.0, 2.0))
4398 );
4399 }
4400
4401 #[test]
4402 fn measure_and_paint_ctx_expose_dpi_info() {
4403 let dpi = DpiInfo::new(
4404 2.0,
4405 Some(192.0),
4406 sui_core::Size::new(320.0, 180.0),
4407 sui_core::Size::new(640.0, 360.0),
4408 );
4409
4410 let measure = MeasureCtx::new(
4411 WindowId::new(1),
4412 WidgetId::new(2),
4413 Rect::ZERO,
4414 dpi,
4415 std::sync::Arc::new(TextSystem::new()),
4416 std::sync::Arc::new(FontRegistry::new()),
4417 std::sync::Arc::new(ImageRegistry::new()),
4418 );
4419 let paint = PaintCtx::new(
4420 WindowId::new(1),
4421 WidgetId::new(2),
4422 Rect::new(0.0, 0.0, 120.0, 60.0),
4423 None,
4424 dpi,
4425 Arc::new(TextSystem::new()),
4426 Arc::new(FontRegistry::new()),
4427 Arc::new(ImageRegistry::new()),
4428 );
4429 let event = EventCtx::new(
4430 WindowId::new(1),
4431 WidgetId::new(2),
4432 Rect::new(0.0, 0.0, 120.0, 60.0),
4433 dpi,
4434 0.0,
4435 EventPhase::Target,
4436 None,
4437 Clipboard::new(),
4438 CommandSender::new(),
4439 );
4440
4441 assert_eq!(measure.dpi(), dpi);
4442 assert_eq!(paint.dpi(), dpi);
4443 assert_eq!(event.dpi(), dpi);
4444 }
4445
4446 struct LabelWidget;
4447
4448 impl Widget for LabelWidget {
4449 fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> sui_core::Size {
4450 constraints.clamp(sui_core::Size::new(48.0, 20.0))
4451 }
4452
4453 fn paint(&self, ctx: &mut PaintCtx) {
4454 ctx.fill_bounds(Color::rgba(0.2, 0.3, 0.4, 1.0));
4455 }
4456
4457 fn semantics(&self, ctx: &mut SemanticsCtx) {
4458 ctx.push(SemanticsNode::new(
4459 ctx.widget_id(),
4460 SemanticsRole::Text,
4461 ctx.bounds(),
4462 ));
4463 }
4464 }
4465
4466 struct BoundsLeaf;
4467
4468 impl Widget for BoundsLeaf {
4469 fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
4470 constraints.max
4471 }
4472
4473 fn paint(&self, ctx: &mut PaintCtx) {
4474 ctx.fill_rect(
4475 Rect::new(10.0, 10.0, 80.0, 50.0),
4476 Color::rgba(0.2, 0.3, 0.4, 1.0),
4477 );
4478 }
4479 }
4480
4481 struct BoundsWrapper {
4482 child: WidgetPod,
4483 clip: Option<Rect>,
4484 translation: Vector,
4485 }
4486
4487 impl BoundsWrapper {
4488 fn new(child: impl Widget + 'static, clip: Option<Rect>, translation: Vector) -> Self {
4489 Self {
4490 child: WidgetPod::new(child),
4491 clip,
4492 translation,
4493 }
4494 }
4495 }
4496
4497 impl Widget for BoundsWrapper {
4498 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
4499 self.child.measure(ctx, constraints)
4500 }
4501
4502 fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
4503 self.child.arrange(ctx, bounds);
4504 }
4505
4506 fn paint(&self, ctx: &mut PaintCtx) {
4507 if let Some(clip) = self.clip {
4508 ctx.push_clip_rect(clip);
4509 }
4510 if self.translation != Vector::ZERO {
4511 ctx.translate(self.translation);
4512 }
4513
4514 self.child.paint(ctx);
4515
4516 if self.translation != Vector::ZERO {
4517 ctx.pop_transform();
4518 }
4519 if self.clip.is_some() {
4520 ctx.pop_clip();
4521 }
4522 }
4523
4524 fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
4525 visitor.visit(&self.child);
4526 }
4527
4528 fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
4529 visitor.visit(&mut self.child);
4530 }
4531 }
4532
4533 #[test]
4534 fn event_ctx_tracks_widget_scoped_invalidations_and_focus() {
4535 let mut ctx = EventCtx::new(
4536 WindowId::new(1),
4537 WidgetId::new(2),
4538 Rect::new(8.0, 12.0, 24.0, 36.0),
4539 DpiInfo::default(),
4540 0.0,
4541 EventPhase::Target,
4542 None,
4543 Clipboard::new(),
4544 CommandSender::new(),
4545 );
4546
4547 ctx.request_measure();
4548 ctx.request_paint_rect(Rect::new(8.0, 12.0, 24.0, 36.0));
4549 ctx.request_transform();
4550 ctx.request_effect();
4551 ctx.request_visibility();
4552 ctx.request_animation_frame();
4553 ctx.request_focus();
4554 ctx.set_handled();
4555
4556 assert!(ctx.is_handled());
4557 assert_eq!(ctx.bounds(), Rect::new(8.0, 12.0, 24.0, 36.0));
4558 assert_eq!(ctx.invalidations().len(), 5);
4559 assert_eq!(ctx.invalidations()[0].kind, InvalidationKind::Measure);
4560 assert_eq!(
4561 ctx.invalidations()[1].region,
4562 Some(Rect::new(8.0, 12.0, 24.0, 36.0))
4563 );
4564 assert_eq!(ctx.invalidations()[2].kind, InvalidationKind::Transform);
4565 assert_eq!(ctx.invalidations()[3].kind, InvalidationKind::Effect);
4566 assert_eq!(ctx.invalidations()[4].kind, InvalidationKind::Visibility);
4567 assert_eq!(
4568 ctx.take_wake_requests(),
4569 vec![WakeRequest::RequestAnimationFrame {
4570 target: WidgetId::new(2)
4571 }]
4572 );
4573 }
4574
4575 #[test]
4576 fn request_animation_frame_enqueues_widget_for_next_frame() {
4577 let mut ctx = EventCtx::new(
4578 WindowId::new(4),
4579 WidgetId::new(9),
4580 Rect::new(0.0, 0.0, 20.0, 10.0),
4581 DpiInfo::default(),
4582 16.0,
4583 EventPhase::Target,
4584 None,
4585 Clipboard::new(),
4586 CommandSender::new(),
4587 );
4588
4589 ctx.request_animation_frame();
4590
4591 assert_eq!(
4592 ctx.take_wake_requests(),
4593 vec![WakeRequest::RequestAnimationFrame {
4594 target: WidgetId::new(9)
4595 }]
4596 );
4597 }
4598
4599 struct CountingChild {
4600 measures: Rc<Cell<u32>>,
4601 }
4602
4603 impl Widget for CountingChild {
4604 fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> sui_core::Size {
4605 self.measures.set(self.measures.get() + 1);
4606 constraints.clamp(sui_core::Size::new(10.0, 10.0))
4607 }
4608 }
4609
4610 struct PassthroughParent {
4611 child: WidgetPod,
4612 }
4613
4614 impl Widget for PassthroughParent {
4615 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> sui_core::Size {
4616 self.child.measure(ctx, constraints)
4617 }
4618
4619 fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
4620 visitor.visit(&self.child);
4621 }
4622
4623 fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
4624 visitor.visit(&mut self.child);
4625 }
4626 }
4627
4628 fn scoped_measure_ctx(root_id: WidgetId, scope: MeasureScope) -> MeasureCtx {
4629 MeasureCtx::new_scoped_at(
4630 WindowId::new(1),
4631 root_id,
4632 Rect::ZERO,
4633 DpiInfo::default(),
4634 Arc::new(TextSystem::new()),
4635 Arc::new(FontRegistry::new()),
4636 Arc::new(ImageRegistry::new()),
4637 Rc::new(scope),
4638 0.0,
4639 )
4640 }
4641
4642 #[test]
4643 fn scalar_probes_preserve_final_state_and_have_bounded_storage() {
4644 struct Probe {
4645 calls: Rc<Cell<u32>>,
4646 width: Rc<Cell<f32>>,
4647 }
4648 impl Widget for Probe {
4649 fn measure(&mut self, _: &mut MeasureCtx, constraints: Constraints) -> Size {
4650 self.calls.set(self.calls.get() + 1);
4651 self.width.set(constraints.max.width);
4652 constraints.clamp(Size::new(30.0, 10.0))
4653 }
4654 }
4655 let calls = Rc::new(Cell::new(0));
4656 let width = Rc::new(Cell::new(0.0));
4657 let mut pod = WidgetPod::new(Probe {
4658 calls: calls.clone(),
4659 width: width.clone(),
4660 });
4661 let root = WidgetId::new(u64::MAX);
4662 let constraint = |width| Constraints::tight(Size::new(width, 10.0));
4663 let mut clean = scoped_measure_ctx(root, MeasureScope::default());
4664 pod.probe_measure(&mut clean, constraint(10.0));
4665 pod.probe_measure(&mut clean, constraint(20.0));
4666 pod.measure(&mut clean, constraint(100.0));
4667 let before = calls.get();
4668 assert_eq!(pod.probe_measure(&mut clean, constraint(10.0)).width, 10.0);
4669 pod.measure(&mut clean, constraint(100.0));
4670 assert_eq!(calls.get(), before);
4671 assert_eq!(width.get(), 100.0);
4672 assert_eq!(pod.measured_size().width, 100.0);
4673 pod.probe_measure(&mut clean, constraint(30.0));
4674 pod.probe_measure(&mut clean, constraint(40.0));
4675 pod.probe_measure(&mut clean, constraint(50.0));
4676 pod.probe_measure(&mut clean, constraint(10.0)); assert_eq!(calls.get(), before + 4);
4678 assert_eq!(
4679 pod.probe_cache
4680 .as_ref()
4681 .unwrap()
4682 .measurements
4683 .iter()
4684 .flatten()
4685 .count(),
4686 4
4687 );
4688 }
4689
4690 #[test]
4691 fn size_only_hooks_require_explicit_forwarding_and_final_commit() {
4692 struct Leaf {
4693 queries: Rc<Cell<u32>>,
4694 commits: Rc<Cell<u32>>,
4695 width: Rc<Cell<f32>>,
4696 }
4697 impl Widget for Leaf {
4698 fn measure_size(&mut self, _: &mut MeasureCtx, c: Constraints) -> Size {
4699 self.queries.set(self.queries.get() + 1);
4700 c.clamp(Size::new(20.0, 10.0))
4701 }
4702 fn measure(&mut self, _: &mut MeasureCtx, c: Constraints) -> Size {
4703 self.commits.set(self.commits.get() + 1);
4704 self.width.set(c.max.width);
4705 c.clamp(Size::new(20.0, 10.0))
4706 }
4707 }
4708 struct Forwarder(WidgetPod);
4709 impl Widget for Forwarder {
4710 fn measure_size(&mut self, ctx: &mut MeasureCtx, c: Constraints) -> Size {
4711 self.0.probe_measure(ctx, c)
4712 }
4713 fn measure(&mut self, ctx: &mut MeasureCtx, c: Constraints) -> Size {
4714 self.0.measure(ctx, c);
4715 self.0.measured_size()
4716 }
4717 }
4718 let queries = Rc::new(Cell::new(0));
4719 let commits = Rc::new(Cell::new(0));
4720 let width = Rc::new(Cell::new(0.0));
4721 let mut pod = WidgetPod::new(Forwarder(WidgetPod::new(Leaf {
4722 queries: queries.clone(),
4723 commits: commits.clone(),
4724 width: width.clone(),
4725 })));
4726 let mut ctx = scoped_measure_ctx(WidgetId::new(u64::MAX), MeasureScope::default());
4727 let c = Constraints::tight(Size::new(100.0, 10.0));
4728 assert_eq!(pod.probe_measure(&mut ctx, c), c.max);
4729 assert_eq!(queries.get(), 1);
4730 assert_eq!(commits.get(), 0);
4731 assert_eq!(width.get(), 0.0);
4732 assert_eq!(pod.measure(&mut ctx, c), c.max);
4733 assert_eq!(
4734 commits.get(),
4735 1,
4736 "a size probe cannot satisfy final measurement"
4737 );
4738 pod.probe_measure(&mut ctx, Constraints::tight(Size::new(50.0, 10.0)));
4739 pod.measure(&mut ctx, c);
4740 assert_eq!(commits.get(), 2);
4741 assert_eq!(width.get(), 100.0);
4742 }
4743
4744 #[test]
4745 fn default_size_hook_preserves_stateful_child_measure_contract() {
4746 struct Leaf(Rc<Cell<f32>>);
4747 impl Widget for Leaf {
4748 fn measure_size(&mut self, _: &mut MeasureCtx, c: Constraints) -> Size {
4749 Size::new(c.max.width, 10.0)
4750 }
4751 fn measure(&mut self, _: &mut MeasureCtx, c: Constraints) -> Size {
4752 self.0.set(c.max.width);
4753 Size::new(c.max.width, 10.0)
4754 }
4755 }
4756 struct Legacy {
4757 child: WidgetPod,
4758 width: Rc<Cell<f32>>,
4759 }
4760 impl Widget for Legacy {
4761 fn measure(&mut self, ctx: &mut MeasureCtx, c: Constraints) -> Size {
4762 self.child.measure(ctx, c);
4763 Size::new(self.width.get(), 10.0)
4765 }
4766 }
4767 let width = Rc::new(Cell::new(0.0));
4768 let mut pod = WidgetPod::new(Legacy {
4769 child: WidgetPod::new(Leaf(width.clone())),
4770 width: width.clone(),
4771 });
4772 let mut ctx = scoped_measure_ctx(WidgetId::new(u64::MAX), MeasureScope::default());
4773 let c = |width| Constraints::new(Size::ZERO, Size::new(width, 20.0));
4774 assert_eq!(pod.probe_measure(&mut ctx, c(100.0)).width, 100.0);
4775 assert_eq!(pod.probe_measure(&mut ctx, c(200.0)).width, 200.0);
4776 assert_eq!(pod.probe_measure(&mut ctx, c(100.0)).width, 100.0);
4777 assert_eq!(pod.measure(&mut ctx, c(100.0)).width, 100.0);
4778 assert_eq!(width.get(), 100.0);
4779 }
4780
4781 #[test]
4782 fn axis_queries_are_distinct_and_invalidate_with_the_window_context() {
4783 use sui_layout::Axis;
4784 struct Leaf(Rc<Cell<u32>>, Rc<Cell<f32>>);
4785 impl Widget for Leaf {
4786 fn measure(&mut self, _: &mut MeasureCtx, c: Constraints) -> Size {
4787 self.0.set(self.0.get() + 1);
4788 c.clamp(Size::new(self.1.get(), 13.0))
4789 }
4790 }
4791 let calls = Rc::new(Cell::new(0));
4792 let value = Rc::new(Cell::new(27.0));
4793 let mut pod = WidgetPod::new(Leaf(calls.clone(), value.clone()));
4794 let shared = crate::measure_cache::MeasureQueryCache::shared();
4795 let root = WidgetId::new(u64::MAX);
4796 let mut ctx = scoped_measure_ctx(root, MeasureScope::default());
4797 ctx.set_query_cache(shared.clone());
4798 let c = Constraints::new(Size::ZERO, Size::new(100.0, 100.0));
4799 for width in 100..110 {
4800 let c = Constraints::new(Size::ZERO, Size::new(width as f32, 100.0));
4801 assert_eq!(pod.probe_measure_axis(&mut ctx, c, Axis::Horizontal), 27.0);
4802 assert_eq!(pod.probe_measure_axis(&mut ctx, c, Axis::Vertical), 13.0);
4803 assert_eq!(pod.probe_measure(&mut ctx, c), Size::new(27.0, 13.0));
4804 }
4805 let before = calls.get();
4806 assert_eq!(pod.probe_measure_axis(&mut ctx, c, Axis::Horizontal), 27.0);
4807 assert_eq!(pod.probe_measure_axis(&mut ctx, c, Axis::Vertical), 13.0);
4808 assert_eq!(pod.probe_measure(&mut ctx, c), Size::new(27.0, 13.0));
4809 assert_eq!(
4810 calls.get(),
4811 before,
4812 "overflow hits must preserve query kind"
4813 );
4814 assert_eq!(pod.measure(&mut ctx, c), Size::new(27.0, 13.0));
4815 assert_eq!(calls.get(), before + 1, "axis hits cannot commit layout");
4816 value.set(41.0);
4817 shared.borrow_mut().invalidate_context();
4818 let mut next = scoped_measure_ctx(root, MeasureScope::default());
4819 next.set_query_cache(shared);
4820 assert_eq!(pod.probe_measure_axis(&mut next, c, Axis::Horizontal), 41.0);
4821 assert_eq!(pod.measure(&mut next, c), Size::new(41.0, 13.0));
4822 }
4823
4824 #[test]
4825 fn window_query_cache_reuses_evicted_local_entries_and_respects_all_invalidations() {
4826 struct Leaf(Rc<Cell<f32>>, Rc<Cell<u32>>);
4827 impl Widget for Leaf {
4828 fn measure(&mut self, _: &mut MeasureCtx, c: Constraints) -> Size {
4829 self.1.set(self.1.get() + 1);
4830 c.clamp(Size::new(self.0.get(), 10.0))
4831 }
4832 }
4833 let value = Rc::new(Cell::new(20.0));
4834 let calls = Rc::new(Cell::new(0));
4835 let mut pod = WidgetPod::new(Leaf(value.clone(), calls.clone()));
4836 let shared = crate::measure_cache::MeasureQueryCache::shared();
4837 let root = WidgetId::new(u64::MAX);
4838 let mut clean = scoped_measure_ctx(root, MeasureScope::default());
4839 clean.set_query_cache(shared.clone());
4840 let constraint = |width| Constraints::new(Size::ZERO, Size::new(width, 20.0));
4841 for width in 100..104 {
4842 pod.probe_measure(&mut clean, constraint(width as f32));
4843 }
4844 for width in 100..104 {
4845 let key = crate::measure_cache::QueryKey::new(
4846 pod.id(),
4847 pod.probe_cache.as_ref().unwrap().revision,
4848 constraint(width as f32),
4849 )
4850 .unwrap();
4851 let mut window = shared.borrow_mut();
4852 let context = window.context();
4853 assert!(
4854 window.get(context, &key).is_none(),
4855 "small query sets should stay in the local cache"
4856 );
4857 }
4858 for width in 104..110 {
4859 pod.probe_measure(&mut clean, constraint(width as f32));
4860 }
4861 let before = calls.get();
4862 assert_eq!(pod.probe_measure(&mut clean, constraint(100.0)).width, 20.0);
4863 assert_eq!(
4864 calls.get(),
4865 before,
4866 "the window cache should survive local eviction"
4867 );
4868 value.set(30.0);
4869 let mut dirty = scoped_measure_ctx(
4870 root,
4871 MeasureScope::scoped(HashSet::from([pod.id()]), HashSet::new()),
4872 );
4873 dirty.set_query_cache(shared.clone());
4874 assert_eq!(pod.probe_measure(&mut dirty, constraint(100.0)).width, 30.0);
4875 pod.measure(&mut clean, constraint(100.0));
4876 value.set(40.0);
4877 shared.borrow_mut().invalidate_context(); clean.set_query_cache(shared.clone()); assert_eq!(pod.measure(&mut clean, constraint(100.0)).width, 40.0);
4880 let mut external =
4881 MeasureCtx::with_layout(clean.window_id(), root, Rect::ZERO, clean.layout().clone());
4882 value.set(50.0);
4883 assert_eq!(
4884 pod.probe_measure(&mut external, constraint(100.0)).width,
4885 50.0
4886 );
4887 value.set(60.0);
4888 assert_eq!(
4889 pod.probe_measure(&mut external, constraint(100.0)).width,
4890 60.0
4891 );
4892 assert_eq!(pod.probe_measure(&mut clean, constraint(100.0)).width, 60.0);
4893 let mut other = scoped_measure_ctx(root, MeasureScope::default());
4895 other.set_query_cache(crate::measure_cache::MeasureQueryCache::shared());
4896 value.set(70.0);
4897 assert_eq!(pod.measure(&mut other, constraint(100.0)).width, 70.0);
4898 }
4899
4900 #[test]
4901 fn probe_invalidation_discards_all_constraints_and_preserves_forced_callbacks() {
4902 struct Probe(Rc<Cell<u32>>);
4903 impl Widget for Probe {
4904 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
4905 self.0.set(self.0.get() + 1);
4906 ctx.request_paint();
4907 ctx.request_animation_frame();
4908 constraints.clamp(Size::new(self.0.get() as f32, 10.0))
4909 }
4910 }
4911 let calls = Rc::new(Cell::new(0));
4912 let mut pod = WidgetPod::new(Probe(calls.clone()));
4913 let root = WidgetId::new(u64::MAX);
4914 let a = Constraints::new(Size::ZERO, Size::new(100.0, 10.0));
4915 let b = Constraints::new(Size::ZERO, Size::new(200.0, 10.0));
4916 let mut initial = scoped_measure_ctx(root, MeasureScope::force_all());
4917 pod.probe_measure(&mut initial, a);
4918 pod.probe_measure(&mut initial, b);
4919 let mut dirty = scoped_measure_ctx(
4920 root,
4921 MeasureScope::scoped(HashSet::from([pod.id()]), HashSet::new()),
4922 );
4923 pod.probe_measure(&mut dirty, a);
4924 pod.measure(&mut dirty, a);
4925 pod.measure(&mut dirty, a);
4926 assert_eq!(
4927 calls.get(),
4928 5,
4929 "forced ordinary callbacks must still execute"
4930 );
4931 assert_eq!(dirty.invalidations.len(), 3);
4932 assert_eq!(dirty.wake_requests.len(), 3);
4933 let mut clean = scoped_measure_ctx(root, MeasureScope::default());
4934 pod.probe_measure(&mut clean, b);
4935 assert_eq!(
4936 calls.get(),
4937 6,
4938 "an unqueried constraint survived invalidation"
4939 );
4940 let mut subtree = scoped_measure_ctx(
4941 root,
4942 MeasureScope::scoped(HashSet::new(), HashSet::from([root])),
4943 );
4944 pod.probe_measure(&mut subtree, b);
4945 assert_eq!(calls.get(), 7);
4946 let mut resized = scoped_measure_ctx(root, MeasureScope::force_all());
4947 pod.probe_measure(&mut resized, b);
4948 assert_eq!(calls.get(), 8);
4949 }
4950
4951 #[test]
4952 fn external_measure_context_keeps_full_measure_semantics_when_reused() {
4953 struct Leaf(Rc<Cell<f32>>);
4954 impl Widget for Leaf {
4955 fn measure(&mut self, _: &mut MeasureCtx, c: Constraints) -> Size {
4956 c.clamp(Size::new(self.0.get(), 10.0))
4957 }
4958 }
4959 struct Parent(WidgetPod);
4960 impl Widget for Parent {
4961 fn measure(&mut self, ctx: &mut MeasureCtx, c: Constraints) -> Size {
4962 let natural = self.0.probe_measure(ctx, Constraints::UNBOUNDED);
4963 self.0.measure(ctx, c);
4964 c.clamp(natural)
4965 }
4966 }
4967 let value = Rc::new(Cell::new(20.0));
4968 let mut pod = WidgetPod::new(Parent(WidgetPod::new(Leaf(value.clone()))));
4969 let root = WidgetId::new(u64::MAX);
4970 let template = scoped_measure_ctx(root, MeasureScope::force_all());
4971 let mut ctx = MeasureCtx::with_layout(
4972 template.window_id(),
4973 root,
4974 Rect::ZERO,
4975 template.layout().clone(),
4976 );
4977 let constraints = Constraints::new(Size::ZERO, Size::new(100.0, 20.0));
4978 assert_eq!(pod.measure(&mut ctx, constraints).width, 20.0);
4979 value.set(40.0);
4980 assert_eq!(pod.measure(&mut ctx, constraints).width, 40.0);
4981 }
4982
4983 #[test]
4984 fn dirty_probes_reuse_results_within_a_pass_but_final_measurement_still_executes() {
4985 let calls = Rc::new(Cell::new(0));
4986 let mut pod = WidgetPod::new(CountingChild {
4987 measures: calls.clone(),
4988 });
4989 let root = WidgetId::new(u64::MAX);
4990 let constraints = Constraints::tight(Size::new(100.0, 10.0));
4991 let mut pass = scoped_measure_ctx(root, MeasureScope::force_all());
4992 pod.probe_measure(&mut pass, constraints);
4993 pod.probe_measure(&mut pass, constraints);
4994 assert_eq!(calls.get(), 1);
4995 pod.measure(&mut pass, constraints);
4996 pod.measure(&mut pass, constraints);
4997 assert_eq!(calls.get(), 3);
4998 pod.intrinsic_size(&mut pass, sui_layout::Axis::Horizontal, 10.0);
4999 pod.intrinsic_size(&mut pass, sui_layout::Axis::Horizontal, 10.0);
5000 assert_eq!(calls.get(), 4);
5001 let mut next = scoped_measure_ctx(root, MeasureScope::force_all());
5002 pod.probe_measure(&mut next, constraints);
5003 assert_eq!(
5004 calls.get(),
5005 5,
5006 "a new dirty pass must invalidate the previous queries"
5007 );
5008 }
5009
5010 #[test]
5011 fn intrinsic_cache_keys_include_axis_and_cross_extent() {
5012 struct Probe(Rc<Cell<u32>>);
5013 impl Widget for Probe {
5014 fn intrinsic_size(
5015 &mut self,
5016 _: &mut MeasureCtx,
5017 axis: sui_layout::Axis,
5018 cross: f32,
5019 ) -> sui_layout::IntrinsicSize {
5020 self.0.set(self.0.get() + 1);
5021 let offset = if axis == sui_layout::Axis::Horizontal {
5022 1.0
5023 } else {
5024 2.0
5025 };
5026 sui_layout::IntrinsicSize::fixed(cross + offset)
5027 }
5028 }
5029 let calls = Rc::new(Cell::new(0));
5030 let mut pod = WidgetPod::new(Probe(calls.clone()));
5031 let root = WidgetId::new(u64::MAX);
5032 let mut clean = scoped_measure_ctx(root, MeasureScope::default());
5033 for _ in 0..2 {
5034 assert_eq!(
5035 pod.intrinsic_size(&mut clean, sui_layout::Axis::Horizontal, 10.0)
5036 .natural,
5037 11.0
5038 );
5039 assert_eq!(
5040 pod.intrinsic_size(&mut clean, sui_layout::Axis::Vertical, 10.0)
5041 .natural,
5042 12.0
5043 );
5044 }
5045 assert_eq!(calls.get(), 2);
5046 assert_eq!(
5047 pod.intrinsic_size(&mut clean, sui_layout::Axis::Horizontal, 20.0)
5048 .natural,
5049 21.0
5050 );
5051 assert_eq!(calls.get(), 3);
5052 let mut dirty = scoped_measure_ctx(
5053 root,
5054 MeasureScope::scoped(HashSet::from([pod.id()]), HashSet::new()),
5055 );
5056 pod.measure(&mut dirty, Constraints::tight(Size::new(10.0, 10.0)));
5057 pod.intrinsic_size(&mut clean, sui_layout::Axis::Vertical, 10.0);
5058 assert_eq!(
5059 calls.get(),
5060 4,
5061 "ordinary dirty measurement must also clear intrinsic probes"
5062 );
5063 }
5064
5065 #[test]
5066 fn intrinsic_probe_cannot_leave_a_cached_final_layout_in_the_wrong_state() {
5067 struct StatefulMeasure(Rc<Cell<f32>>);
5068 impl Widget for StatefulMeasure {
5069 fn measure(&mut self, _: &mut MeasureCtx, constraints: Constraints) -> Size {
5070 self.0.set(constraints.max.width);
5071 constraints.clamp(Size::new(20.0, 20.0))
5072 }
5073 }
5074 let committed_width = Rc::new(Cell::new(0.0));
5075 let mut pod = WidgetPod::new(StatefulMeasure(committed_width.clone()));
5076 let root = WidgetId::new(u64::MAX);
5077 let final_constraints = Constraints::tight(Size::new(100.0, 20.0));
5078 let mut initial = scoped_measure_ctx(root, MeasureScope::force_all());
5079 pod.measure(&mut initial, final_constraints);
5080 let mut clean =
5081 scoped_measure_ctx(root, MeasureScope::scoped(HashSet::new(), HashSet::new()));
5082 pod.intrinsic_size(&mut clean, sui_layout::Axis::Horizontal, 20.0);
5083 pod.measure(&mut clean, final_constraints);
5084 assert_eq!(
5085 committed_width.get(),
5086 100.0,
5087 "a scalar cache hit did not restore the final layout state"
5088 );
5089 }
5090
5091 #[test]
5092 fn measure_cache_skips_clean_subtrees_and_forces_changed_ones() {
5093 let measures = Rc::new(Cell::new(0u32));
5094 let child = WidgetPod::new(CountingChild {
5095 measures: Rc::clone(&measures),
5096 });
5097 let mut parent = WidgetPod::new(PassthroughParent { child });
5098 let parent_id = parent.id();
5099 let outside = WidgetId::new(u64::MAX);
5100 let constraints = Constraints::tight(sui_core::Size::new(10.0, 10.0));
5101
5102 let mut ctx = scoped_measure_ctx(outside, MeasureScope::force_all());
5104 parent.measure(&mut ctx, constraints);
5105 assert_eq!(measures.get(), 1, "initial pass must measure the child");
5106
5107 let mut ctx = scoped_measure_ctx(
5110 outside,
5111 MeasureScope::scoped(HashSet::new(), HashSet::new()),
5112 );
5113 parent.measure(&mut ctx, constraints);
5114 assert_eq!(measures.get(), 1, "clean subtree must be skipped");
5115
5116 let mut dirty = HashSet::new();
5119 dirty.insert(parent_id);
5120 let mut ctx = scoped_measure_ctx(outside, MeasureScope::scoped(dirty, HashSet::new()));
5121 parent.measure(&mut ctx, constraints);
5122 assert_eq!(
5123 measures.get(),
5124 1,
5125 "ancestor-only re-measure must not force the subtree"
5126 );
5127
5128 let mut dirty = HashSet::new();
5132 dirty.insert(parent_id);
5133 let mut roots = HashSet::new();
5134 roots.insert(parent_id);
5135 let mut ctx = scoped_measure_ctx(outside, MeasureScope::scoped(dirty, roots));
5136 parent.measure(&mut ctx, constraints);
5137 assert_eq!(
5138 measures.get(),
5139 2,
5140 "a changed widget must force its descendants to re-measure"
5141 );
5142 }
5143
5144 #[test]
5145 fn widget_pod_merges_child_measure_arrange_paint_and_semantics() {
5146 let mut pod = WidgetPod::new(LabelWidget);
5147 pod.set_bounds(Rect::new(4.0, 6.0, 0.0, 0.0));
5148
5149 let mut measure = measure_ctx(WindowId::new(3), WidgetId::new(4));
5150 let size = pod.measure(
5151 &mut measure,
5152 Constraints::tight(sui_core::Size::new(64.0, 32.0)),
5153 );
5154 let mut arrange = ArrangeCtx::new(WindowId::new(3), WidgetId::new(4), DpiInfo::default());
5155 pod.arrange(&mut arrange, Rect::new(4.0, 6.0, 64.0, 32.0));
5156
5157 let mut paint = PaintCtx::new(
5158 WindowId::new(3),
5159 WidgetId::new(4),
5160 Rect::new(0.0, 0.0, 120.0, 60.0),
5161 None,
5162 DpiInfo::default(),
5163 Arc::new(TextSystem::new()),
5164 Arc::new(FontRegistry::new()),
5165 Arc::new(ImageRegistry::new()),
5166 );
5167 pod.paint(&mut paint);
5168
5169 let mut semantics = SemanticsCtx::new(
5170 WindowId::new(3),
5171 WidgetId::new(4),
5172 WidgetId::new(4),
5173 Rect::new(0.0, 0.0, 120.0, 60.0),
5174 None,
5175 );
5176 pod.semantics(&mut semantics);
5177
5178 assert_eq!(size, sui_core::Size::new(64.0, 32.0));
5179 assert_eq!(pod.bounds(), Rect::new(4.0, 6.0, 64.0, 32.0));
5180 assert_eq!(paint.scene().commands().len(), 1);
5181 assert!(matches!(
5182 paint.scene().commands()[0],
5183 SceneCommand::FillRect { .. }
5184 ));
5185 assert_eq!(semantics.nodes().len(), 1);
5186 }
5187
5188 #[test]
5189 fn remeasured_subtree_arranges_children_outside_the_dirty_scope() {
5190 let window_id = WindowId::new(1);
5191 let parent_id = WidgetId::new(2);
5192 struct ArrangedBounds(Rc<std::cell::Cell<Rect>>);
5193 impl Widget for ArrangedBounds {
5194 fn measure(&mut self, _: &mut MeasureCtx, constraints: Constraints) -> Size {
5195 constraints.max
5196 }
5197 fn arrange(&mut self, _: &mut ArrangeCtx, bounds: Rect) {
5198 self.0.set(bounds);
5199 }
5200 }
5201 let actual = Rc::new(std::cell::Cell::new(Rect::new(0.0, 0.0, 0.0, 0.0)));
5202 let mut pod = WidgetPod::new(BoundsWrapper::new(
5203 ArrangedBounds(actual.clone()),
5204 None,
5205 Vector::ZERO,
5206 ));
5207 let mut measure = measure_ctx(window_id, parent_id);
5208 pod.measure(&mut measure, Constraints::tight(Size::new(100.0, 80.0)));
5209 let mut arrange = ArrangeCtx::new(window_id, parent_id, DpiInfo::default());
5210 pod.arrange(&mut arrange, Rect::new(0.0, 0.0, 100.0, 80.0));
5211 pod.measure(&mut measure, Constraints::tight(Size::new(180.0, 80.0)));
5214 let mut arrange = ArrangeCtx::new_scoped_at(
5215 window_id,
5216 parent_id,
5217 DpiInfo::default(),
5218 0.0,
5219 Rc::new(super::ArrangeScope::scoped(
5220 [parent_id].into_iter().collect(),
5221 )),
5222 );
5223 pod.arrange(&mut arrange, Rect::new(0.0, 0.0, 180.0, 80.0));
5224 struct BoundsVisitor(Vec<Rect>);
5225 impl WidgetPodVisitor for BoundsVisitor {
5226 fn visit(&mut self, child: &WidgetPod) {
5227 self.0.push(child.bounds());
5228 }
5229 }
5230 let mut visitor = BoundsVisitor(Vec::new());
5231 pod.visit_children(&mut visitor);
5232 assert_eq!(visitor.0, vec![Rect::new(0.0, 0.0, 180.0, 80.0)]);
5233 assert_eq!(actual.get(), Rect::new(0.0, 0.0, 180.0, 80.0));
5234 }
5235
5236 #[test]
5237 fn single_child_wraps_measure_arrange_and_visitation() {
5238 struct CaptureVisitor {
5239 ids: Vec<WidgetId>,
5240 }
5241
5242 impl WidgetPodVisitor for CaptureVisitor {
5243 fn visit(&mut self, child: &WidgetPod) {
5244 self.ids.push(child.id());
5245 }
5246 }
5247
5248 impl WidgetPodMutVisitor for CaptureVisitor {
5249 fn visit(&mut self, child: &mut WidgetPod) {
5250 self.ids.push(child.id());
5251 }
5252 }
5253
5254 let mut child = SingleChild::new(LabelWidget);
5255 let mut measure = measure_ctx(WindowId::new(7), WidgetId::new(8));
5256 let size = child.measure(
5257 &mut measure,
5258 Constraints::tight(sui_core::Size::new(80.0, 24.0)),
5259 );
5260 let mut arrange = ArrangeCtx::new(WindowId::new(7), WidgetId::new(8), DpiInfo::default());
5261 child.arrange(&mut arrange, Rect::new(12.0, 18.0, 80.0, 24.0));
5262
5263 let mut visitor = CaptureVisitor { ids: Vec::new() };
5264 child.visit_children(&mut visitor);
5265 child.visit_children_mut(&mut visitor);
5266
5267 assert_eq!(size, sui_core::Size::new(80.0, 24.0));
5268 assert_eq!(child.child().bounds(), Rect::new(12.0, 18.0, 80.0, 24.0));
5269 assert_eq!(visitor.ids, vec![child.child().id(), child.child().id()]);
5270 }
5271
5272 #[test]
5273 fn widget_children_bulk_paint_and_semantics_delegate_to_all_children() {
5274 let mut children = WidgetChildren::with_capacity(2);
5275 children.push(LabelWidget);
5276 children.push(LabelWidget);
5277
5278 let mut measure = measure_ctx(WindowId::new(9), WidgetId::new(10));
5279 children.measure_child(
5280 0,
5281 &mut measure,
5282 Constraints::tight(sui_core::Size::new(40.0, 18.0)),
5283 );
5284 children.measure_child(
5285 1,
5286 &mut measure,
5287 Constraints::tight(sui_core::Size::new(60.0, 18.0)),
5288 );
5289 let mut arrange = ArrangeCtx::new(WindowId::new(9), WidgetId::new(10), DpiInfo::default());
5290 children.arrange_child(0, &mut arrange, Rect::new(0.0, 0.0, 40.0, 18.0));
5291 children.arrange_child(1, &mut arrange, Rect::new(44.0, 0.0, 60.0, 18.0));
5292
5293 let mut paint = PaintCtx::new(
5294 WindowId::new(9),
5295 WidgetId::new(10),
5296 Rect::new(0.0, 0.0, 120.0, 40.0),
5297 None,
5298 DpiInfo::default(),
5299 Arc::new(TextSystem::new()),
5300 Arc::new(FontRegistry::new()),
5301 Arc::new(ImageRegistry::new()),
5302 );
5303 children.paint(&mut paint);
5304
5305 let mut semantics = SemanticsCtx::new(
5306 WindowId::new(9),
5307 WidgetId::new(10),
5308 WidgetId::new(10),
5309 Rect::new(0.0, 0.0, 120.0, 40.0),
5310 None,
5311 );
5312 children.semantics(&mut semantics);
5313
5314 assert_eq!(children.len(), 2);
5315 assert_eq!(paint.scene().commands().len(), 2);
5316 assert_eq!(semantics.nodes().len(), 2);
5317 }
5318
5319 #[test]
5320 fn keyed_children_preserve_pods_and_update_item_signals() {
5321 let mut children = KeyedChildren::<u64, (u64, String)>::new();
5322 let first = children.reconcile(
5323 [(1, "one".to_string()), (2, "two".to_string())],
5324 |item| item.0,
5325 |_key, _value| LabelWidget,
5326 );
5327 assert_eq!(first.inserted, 2);
5328 let first_ids = children
5329 .iter()
5330 .map(|(key, _, child)| (*key, child.id()))
5331 .collect::<HashMap<_, _>>();
5332
5333 let second = children.reconcile(
5334 [
5335 (2, "two updated".to_string()),
5336 (1, "one".to_string()),
5337 (3, "three".to_string()),
5338 ],
5339 |item| item.0,
5340 |_key, _value| LabelWidget,
5341 );
5342 assert_eq!(second.inserted, 1);
5343 assert_eq!(second.removed, 0);
5344 assert_eq!(second.moved, 2);
5345 assert_eq!(second.updated, 1);
5346 assert_eq!(second.unchanged, 1);
5347
5348 let entries = children
5349 .iter()
5350 .map(|(key, value, child)| (*key, value.get(), child.id()))
5351 .collect::<Vec<_>>();
5352 assert_eq!(
5353 entries.iter().map(|(key, _, _)| *key).collect::<Vec<_>>(),
5354 vec![2, 1, 3]
5355 );
5356 assert_eq!(entries[0].1.1, "two updated");
5357 assert_eq!(entries[0].2, first_ids[&2]);
5358 assert_eq!(entries[1].2, first_ids[&1]);
5359 }
5360
5361 #[test]
5362 fn nested_paint_wrappers_preserve_content_and_clipped_paint_bounds() {
5363 let inner = BoundsWrapper::new(
5364 BoundsLeaf,
5365 Some(Rect::new(0.0, 0.0, 60.0, 60.0)),
5366 Vector::new(0.0, 7.0),
5367 );
5368 let outer = BoundsWrapper::new(
5369 inner,
5370 Some(Rect::new(0.0, 0.0, 100.0, 100.0)),
5371 Vector::new(5.0, 0.0),
5372 );
5373 let mut root = WidgetPod::new(BoundsWrapper::new(outer, None, Vector::ZERO));
5376 let window_id = WindowId::new(17);
5377 let root_id = WidgetId::new(18);
5378 let bounds = Rect::new(0.0, 0.0, 120.0, 100.0);
5379 let mut measure = measure_ctx(window_id, root_id);
5380 root.measure(&mut measure, Constraints::tight(bounds.size));
5381 let mut arrange = ArrangeCtx::new(window_id, root_id, DpiInfo::default());
5382 root.arrange(&mut arrange, bounds);
5383
5384 let mut paint = PaintCtx::new(
5385 window_id,
5386 root_id,
5387 bounds,
5388 None,
5389 DpiInfo::default(),
5390 Arc::new(TextSystem::new()),
5391 Arc::new(FontRegistry::new()),
5392 Arc::new(ImageRegistry::new()),
5393 );
5394 root.paint(&mut paint);
5395
5396 assert_eq!(
5397 paint.scene().content_bounds(),
5398 Some(Rect::new(15.0, 17.0, 80.0, 50.0))
5399 );
5400 assert_eq!(
5401 paint.scene().paint_bounds(),
5402 Some(Rect::new(15.0, 17.0, 50.0, 43.0))
5403 );
5404 assert_eq!(
5405 paint.scene().paint_bounds(),
5406 paint.scene().clone().paint_bounds()
5407 );
5408 }
5409
5410 #[test]
5411 fn paint_ctx_emits_extended_scene_commands() {
5412 let mut paint = PaintCtx::new(
5413 WindowId::new(11),
5414 WidgetId::new(12),
5415 Rect::new(0.0, 0.0, 120.0, 60.0),
5416 None,
5417 DpiInfo::default(),
5418 Arc::new(TextSystem::new()),
5419 Arc::new(FontRegistry::new()),
5420 Arc::new(ImageRegistry::new()),
5421 );
5422
5423 let mut path = sui_core::Path::builder();
5424 path.move_to(Point::new(4.0, 5.0))
5425 .line_to(Point::new(24.0, 5.0))
5426 .line_to(Point::new(14.0, 15.0))
5427 .close();
5428 paint.stroke(path.build(), Color::WHITE, StrokeStyle::new(2.0));
5429 paint.draw_text(
5430 Rect::new(8.0, 10.0, 80.0, 20.0),
5431 "hello",
5432 TextStyle::new(Color::BLACK),
5433 );
5434 paint.draw_image(
5435 Rect::new(0.0, 0.0, 16.0, 16.0),
5436 sui_core::ImageHandle::new(3),
5437 );
5438 paint.push_clip(sui_core::Path::circle(Point::new(12.0, 12.0), 8.0));
5439 paint.push_clip_rect(Rect::new(0.0, 0.0, 50.0, 50.0));
5440 paint.translate(Vector::new(3.0, 4.0));
5441 paint.pop_transform();
5442 paint.pop_clip();
5443 paint.pop_clip();
5444
5445 assert!(matches!(
5446 paint.scene().commands()[0],
5447 SceneCommand::StrokePath { .. }
5448 ));
5449 assert!(matches!(
5450 paint.scene().commands()[1],
5451 SceneCommand::DrawShapedText(_)
5452 ));
5453 assert!(matches!(
5454 paint.scene().commands()[2],
5455 SceneCommand::DrawImage { .. }
5456 ));
5457 assert!(matches!(
5458 paint.scene().commands()[3],
5459 SceneCommand::PushClipPath { .. }
5460 ));
5461 assert!(matches!(
5462 paint.scene().commands()[4],
5463 SceneCommand::PushClip { .. }
5464 ));
5465 assert!(matches!(
5466 paint.scene().commands()[5],
5467 SceneCommand::PushTransform { .. }
5468 ));
5469 assert!(matches!(
5470 paint.scene().commands()[6],
5471 SceneCommand::PopTransform
5472 ));
5473 assert!(matches!(paint.scene().commands()[7], SceneCommand::PopClip));
5474 assert!(matches!(paint.scene().commands()[8], SceneCommand::PopClip));
5475 }
5476
5477 #[test]
5478 fn stable_text_run_handle_ignores_color_and_includes_layout_style() {
5479 let run = TextRun {
5480 rect: Rect::new(8.0, 10.0, 80.0, 20.0),
5481 text: "hello".to_string(),
5482 style: TextStyle::new(Color::BLACK),
5483 };
5484 let mut recolored = run.clone();
5485 recolored.style.color = Color::WHITE;
5486 let mut bold = run.clone();
5487 bold.style.weight = FontWeight::BOLD;
5488
5489 assert_eq!(
5490 super::stable_text_run_handle(&run),
5491 super::stable_text_run_handle(&recolored)
5492 );
5493 assert_ne!(
5494 super::stable_text_run_handle(&run),
5495 super::stable_text_run_handle(&bold)
5496 );
5497 }
5498
5499 #[test]
5500 fn paint_ctx_draw_text_uses_color_override_for_paint_color() {
5501 let text_system = Arc::new(TextSystem::new());
5502 let mut paint = PaintCtx::new(
5503 WindowId::new(12),
5504 WidgetId::new(13),
5505 Rect::new(0.0, 0.0, 120.0, 60.0),
5506 None,
5507 DpiInfo::default(),
5508 Arc::clone(&text_system),
5509 Arc::new(FontRegistry::new()),
5510 Arc::new(ImageRegistry::new()),
5511 );
5512 let paint_color = Color::BLACK;
5513 paint.draw_text(
5514 Rect::new(8.0, 10.0, 80.0, 20.0),
5515 "hello",
5516 TextStyle::new(paint_color),
5517 );
5518
5519 let SceneCommand::DrawShapedText(text) = &paint.scene().commands()[0] else {
5520 panic!("draw_text should emit shaped text when layout succeeds");
5521 };
5522 assert_eq!(text.color_override, Some(paint_color));
5523
5524 let registry = text_system.text_layout_registry();
5525 let layout = text
5526 .resolve(registry.as_ref())
5527 .expect("drawn shaped text should resolve from the registry");
5528 assert_eq!(layout.style().color, Color::WHITE);
5529 }
5530
5531 #[test]
5532 fn paint_ctx_draw_persistent_text_layout_reinserts_pruned_layout() {
5533 let text_system = Arc::new(TextSystem::new());
5534 let layout = text_system
5535 .shape_text_persistent(
5536 None,
5537 "held",
5538 Size::new(80.0, 20.0),
5539 TextStyle::new(Color::WHITE),
5540 &FontRegistry::new(),
5541 )
5542 .unwrap();
5543 text_system.retain_persistent_layouts(&std::collections::HashSet::new());
5544 assert!(!text_system.text_layout_registry().contains(layout.handle()));
5545
5546 let mut paint = PaintCtx::new(
5547 WindowId::new(12),
5548 WidgetId::new(13),
5549 Rect::new(0.0, 0.0, 120.0, 60.0),
5550 None,
5551 DpiInfo::default(),
5552 Arc::clone(&text_system),
5553 Arc::new(FontRegistry::new()),
5554 Arc::new(ImageRegistry::new()),
5555 );
5556 paint.draw_persistent_text_layout(Point::ZERO, &layout);
5557
5558 assert!(text_system.text_layout_registry().contains(layout.handle()));
5559 assert!(matches!(
5560 paint.scene().commands()[0],
5561 SceneCommand::DrawShapedText(_)
5562 ));
5563 }
5564
5565 #[test]
5566 fn text_layout_shapes_in_measure_and_paints_as_shaped_scene_output() {
5567 let layout = measure_ctx(WindowId::new(13), WidgetId::new(14))
5568 .layout()
5569 .shape_text(
5570 "hello",
5571 sui_core::Size::new(80.0, 20.0),
5572 TextStyle::new(Color::BLACK),
5573 )
5574 .unwrap();
5575
5576 let mut paint = PaintCtx::new(
5577 WindowId::new(13),
5578 WidgetId::new(14),
5579 Rect::new(0.0, 0.0, 120.0, 60.0),
5580 None,
5581 DpiInfo::default(),
5582 Arc::new(TextSystem::new()),
5583 Arc::new(FontRegistry::new()),
5584 Arc::new(ImageRegistry::new()),
5585 );
5586 let origin = Point::new(8.0, 10.0);
5587 paint.draw_text_layout(origin, &layout);
5588 paint.set_ime_composition_rect(layout.caret_rect(3).translate(origin.to_vector()));
5589
5590 assert!(matches!(
5591 paint.scene().commands()[0],
5592 SceneCommand::DrawShapedText(_)
5593 ));
5594 assert!(paint.ime_composition_rect().is_some());
5595 assert!(!layout.selection_rects(1..4).is_empty());
5596 }
5597}