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