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_from_slice(&fragment.bounds);
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 &mut widget_paint_bounds {
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: Vec<(WidgetId, Rect)>,
3580 ime_composition_rect: Option<Rect>,
3581 frame_time: f64,
3582}
3583
3584macro_rules! impl_animate_ctx {
3585 ($($ctx:ty),*) => {$(
3586 impl crate::motion::AnimateCtx for $ctx {
3587 fn animate_after<T>(
3588 &mut self,
3589 motion: &mut Motion<T>,
3590 target: T,
3591 delay: f64,
3592 spec: AnimationSpec,
3593 ) -> bool
3594 where
3595 T: Interpolate + Copy + PartialEq,
3596 {
3597 <$ctx>::animate_after(self, motion, target, delay, spec)
3598 }
3599 }
3600 )*};
3601}
3602
3603impl_animate_ctx!(EventCtx, MeasureCtx, ArrangeCtx);
3604
3605impl FrameClock for PaintCtx {
3606 fn frame_time(&self) -> f64 {
3607 self.frame_time
3608 }
3609}
3610
3611impl FrameClock for EventCtx {
3612 fn frame_time(&self) -> f64 {
3613 self.current_time
3614 }
3615}
3616
3617impl FrameClock for MeasureCtx {
3618 fn frame_time(&self) -> f64 {
3619 self.current_time
3620 }
3621}
3622
3623impl FrameClock for ArrangeCtx {
3624 fn frame_time(&self) -> f64 {
3625 self.current_time
3626 }
3627}
3628
3629#[derive(Debug, Clone)]
3630pub(crate) enum PaintImageResource {
3631 Cpu(RegisteredImage),
3632 External(RegisteredExternalImage),
3633}
3634
3635impl PaintCtx {
3636 pub fn motion_policy(&self) -> MotionPolicy {
3639 crate::motion_policy()
3640 }
3641
3642 pub fn output_color_range(&self) -> Option<crate::OutputColorRange> {
3646 self.observe(&crate::window_output_color_range_signal(self.window_id))
3647 }
3648
3649 pub(crate) fn new(
3650 window_id: WindowId,
3651 widget_id: WidgetId,
3652 bounds: Rect,
3653 focused_widget_id: Option<WidgetId>,
3654 dpi_info: DpiInfo,
3655 text_system: Arc<TextSystem>,
3656 font_registry: Arc<FontRegistry>,
3657 image_registry: Arc<ImageRegistry>,
3658 ) -> Self {
3659 Self::new_with_transform(
3660 window_id,
3661 widget_id,
3662 bounds,
3663 focused_widget_id,
3664 dpi_info,
3665 text_system,
3666 font_registry,
3667 image_registry,
3668 Transform::IDENTITY,
3669 )
3670 }
3671
3672 #[allow(clippy::too_many_arguments)]
3673 pub(crate) fn new_with_transform(
3674 window_id: WindowId,
3675 widget_id: WidgetId,
3676 bounds: Rect,
3677 focused_widget_id: Option<WidgetId>,
3678 dpi_info: DpiInfo,
3679 text_system: Arc<TextSystem>,
3680 font_registry: Arc<FontRegistry>,
3681 image_registry: Arc<ImageRegistry>,
3682 presentation_transform: Transform,
3683 ) -> Self {
3684 Self {
3685 output_cache: None,
3686 output_reusable: true,
3687 window_id,
3688 widget_id,
3689 focused_widget_id,
3690 bounds,
3691 presentation_transform,
3692 dpi_info,
3693 text_system,
3694 font_registry,
3695 image_registry,
3696 scene: Scene::new(),
3697 images: Vec::new(),
3698 widget_paint_bounds: Vec::new(),
3699 ime_composition_rect: None,
3700 frame_time: 0.0,
3701 }
3702 }
3703
3704 pub(crate) const fn with_frame_time(mut self, frame_time: f64) -> Self {
3705 self.frame_time = frame_time;
3706 self
3707 }
3708
3709 pub const fn frame_time(&self) -> f64 {
3712 self.frame_time
3713 }
3714
3715 pub const fn window_id(&self) -> WindowId {
3716 self.window_id
3717 }
3718
3719 pub const fn widget_id(&self) -> WidgetId {
3720 self.widget_id
3721 }
3722
3723 pub const fn presentation_transform(&self) -> Transform {
3724 self.presentation_transform
3725 }
3726
3727 pub fn observe<T, O>(&self, observable: &O) -> T
3729 where
3730 O: Observable<T> + ?Sized,
3731 {
3732 self.observe_with(observable, InvalidationKind::Paint)
3733 }
3734
3735 pub fn observe_with<T, O>(&self, observable: &O, kind: InvalidationKind) -> T
3737 where
3738 O: Observable<T> + ?Sized,
3739 {
3740 crate::reactive::observe(self.window_id, self.widget_id, observable, kind)
3741 }
3742
3743 pub const fn focused_widget_id(&self) -> Option<WidgetId> {
3744 self.focused_widget_id
3745 }
3746
3747 pub fn is_focused(&self) -> bool {
3748 self.focused_widget_id == Some(self.widget_id)
3749 }
3750
3751 pub const fn bounds(&self) -> Rect {
3752 self.bounds
3753 }
3754
3755 pub const fn dpi(&self) -> DpiInfo {
3756 self.dpi_info
3757 }
3758
3759 pub fn measure_text(
3760 &self,
3761 text: impl Into<String>,
3762 style: TextStyle,
3763 ) -> sui_core::Result<TextMeasurement> {
3764 self.text_system
3765 .measure_text(text, style, self.font_registry.as_ref())
3766 }
3767
3768 pub fn shape_text(
3769 &self,
3770 text: impl Into<String>,
3771 box_size: Size,
3772 style: TextStyle,
3773 ) -> sui_core::Result<TextLayout> {
3774 self.text_system
3775 .shape_text(text, box_size, style, self.font_registry.as_ref())
3776 }
3777
3778 pub fn layout_text_document(&self, request: TextLayoutRequest) -> sui_core::Result<TextLayout> {
3779 self.text_system
3780 .layout_document(request, self.font_registry.as_ref())
3781 }
3782
3783 pub fn clear(&mut self, color: Color) {
3784 self.scene.push(SceneCommand::Clear(color));
3785 }
3786
3787 pub fn fill(&mut self, path: impl Into<Path>, brush: impl Into<Brush>) {
3788 self.scene.push(SceneCommand::FillPath {
3789 path: path.into(),
3790 brush: brush.into(),
3791 });
3792 }
3793
3794 pub fn fill_rect(&mut self, rect: Rect, brush: impl Into<Brush>) {
3795 self.scene.push(SceneCommand::FillRect {
3796 rect,
3797 brush: brush.into(),
3798 });
3799 }
3800
3801 pub fn fill_bounds(&mut self, brush: impl Into<Brush>) {
3802 self.fill_rect(self.bounds, brush);
3803 }
3804
3805 pub fn stroke(&mut self, path: impl Into<Path>, brush: impl Into<Brush>, stroke: StrokeStyle) {
3806 self.scene.push(SceneCommand::StrokePath {
3807 path: path.into(),
3808 brush: brush.into(),
3809 stroke,
3810 });
3811 }
3812
3813 pub fn stroke_rect(&mut self, rect: Rect, brush: impl Into<Brush>, stroke: StrokeStyle) {
3814 self.scene.push(SceneCommand::StrokeRect {
3815 rect,
3816 brush: brush.into(),
3817 stroke,
3818 });
3819 }
3820
3821 pub fn stroke_bounds(&mut self, brush: impl Into<Brush>, stroke: StrokeStyle) {
3822 self.stroke_rect(self.bounds, brush, stroke);
3823 }
3824
3825 pub fn draw_text(&mut self, rect: Rect, text: impl Into<String>, style: TextStyle) {
3826 let text = text.into();
3827 let paint_color = style.color;
3828 let mut layout_style = style.clone();
3829 layout_style.color = Color::WHITE;
3830 let layout_run = TextRun {
3831 rect,
3832 text: text.clone(),
3833 style: layout_style,
3834 };
3835 let fallback_run = TextRun { rect, text, style };
3836
3837 match self.text_system.shape_text_run_persistent(
3838 Some(stable_text_run_handle(&layout_run)),
3839 &layout_run,
3840 self.font_registry.as_ref(),
3841 ) {
3842 Ok(layout) => self.scene.push(SceneCommand::DrawShapedText(
3843 ShapedText::new(rect.origin, &layout).with_color(paint_color),
3844 )),
3845 Err(_) => self.scene.push(SceneCommand::DrawText(fallback_run)),
3846 }
3847 }
3848
3849 pub fn draw_text_layout(&mut self, origin: Point, layout: &TextLayout) {
3850 let persistent = self.text_system.adopt_layout(layout.clone());
3851 self.draw_persistent_text_layout(origin, &persistent);
3852 }
3853
3854 pub fn draw_text_layout_with_color(
3855 &mut self,
3856 origin: Point,
3857 layout: &TextLayout,
3858 color: Color,
3859 ) {
3860 let persistent = self.text_system.adopt_layout(layout.clone());
3861 self.draw_persistent_text_layout_with_color(origin, &persistent, color);
3862 }
3863
3864 pub fn draw_persistent_text_layout(&mut self, origin: Point, layout: &PersistentTextLayout) {
3865 self.text_system.touch_persistent_layout(layout);
3866 self.scene
3867 .push(SceneCommand::DrawShapedText(ShapedText::new(
3868 origin, layout,
3869 )));
3870 }
3871
3872 pub fn draw_persistent_text_layout_with_color(
3873 &mut self,
3874 origin: Point,
3875 layout: &PersistentTextLayout,
3876 color: Color,
3877 ) {
3878 self.text_system.touch_persistent_layout(layout);
3879 self.scene.push(SceneCommand::DrawShapedText(
3880 ShapedText::new(origin, layout).with_color(color),
3881 ));
3882 }
3883
3884 pub fn draw_persistent_text_layout_window(
3885 &mut self,
3886 origin: Point,
3887 layout: &PersistentTextLayout,
3888 line_range: std::ops::Range<usize>,
3889 ) {
3890 self.text_system.touch_persistent_layout(layout);
3891 self.scene
3892 .push(SceneCommand::DrawShapedTextWindow(ShapedTextWindow::new(
3893 origin, layout, line_range,
3894 )));
3895 }
3896
3897 pub fn draw_persistent_text_layout_window_with_color(
3898 &mut self,
3899 origin: Point,
3900 layout: &PersistentTextLayout,
3901 line_range: std::ops::Range<usize>,
3902 color: Color,
3903 ) {
3904 self.text_system.touch_persistent_layout(layout);
3905 self.scene.push(SceneCommand::DrawShapedTextWindow(
3906 ShapedTextWindow::new(origin, layout, line_range).with_color(color),
3907 ));
3908 }
3909
3910 pub fn label(&mut self, rect: Rect, text: impl Into<String>, color: Color) {
3911 self.draw_text(rect, text, TextStyle::new(color));
3912 }
3913
3914 pub fn push_text_render_policy(&mut self, policy: TextRenderPolicy) {
3915 self.scene.push(SceneCommand::PushTextRenderPolicy {
3916 policy: policy.normalized(),
3917 });
3918 }
3919
3920 pub fn pop_text_render_policy(&mut self) {
3921 self.scene.push(SceneCommand::PopTextRenderPolicy);
3922 }
3923
3924 pub fn draw_image(&mut self, rect: Rect, image: sui_core::ImageHandle) {
3925 self.scene.push(SceneCommand::DrawImage {
3926 rect,
3927 source: ImageSource::new(image),
3928 });
3929 }
3930
3931 pub fn image_registered(&self, image: ImageHandle) -> bool {
3932 self.image_registry.contains(image)
3933 || self.images.iter().any(|(handle, _)| *handle == image)
3934 }
3935
3936 pub fn draw_image_source(&mut self, rect: Rect, source: ImageSource) {
3937 self.scene.push(SceneCommand::DrawImage { rect, source });
3938 }
3939
3940 pub fn draw_image_quad(&mut self, points: [Point; 4], image: ImageHandle) {
3941 self.draw_image_quad_source(points, ImageSource::new(image));
3942 }
3943
3944 pub fn draw_image_quad_source(&mut self, points: [Point; 4], source: ImageSource) {
3945 self.scene
3946 .push(SceneCommand::DrawImageQuad { points, source });
3947 }
3948
3949 pub fn widget_image_handle(&self, slot: u64) -> ImageHandle {
3950 let mut hasher = DefaultHasher::new();
3951 self.widget_id.hash(&mut hasher);
3952 slot.hash(&mut hasher);
3953 ImageHandle::new(WIDGET_IMAGE_HANDLE_NAMESPACE | (hasher.finish() >> 1))
3954 }
3955
3956 pub fn register_image(&mut self, handle: ImageHandle, image: RegisteredImage) {
3957 self.images.push((handle, PaintImageResource::Cpu(image)));
3958 }
3959
3960 pub fn register_external_image(&mut self, handle: ImageHandle, image: RegisteredExternalImage) {
3967 self.images
3968 .push((handle, PaintImageResource::External(image)));
3969 }
3970
3971 pub fn draw_shader_rect(&mut self, rect: Rect, shader: WidgetShader) {
3972 self.scene
3973 .push(SceneCommand::DrawShaderRect { rect, shader });
3974 }
3975
3976 pub fn fill_rrect(&mut self, rect: Rect, radii: [f32; 4], brush: impl Into<Brush>) {
3978 self.scene.push(SceneCommand::FillRoundedRect {
3979 rect,
3980 radii,
3981 brush: brush.into(),
3982 border: None,
3983 shadow: None,
3984 });
3985 }
3986
3987 pub fn fill_rrect_bordered(
3989 &mut self,
3990 rect: Rect,
3991 radii: [f32; 4],
3992 brush: impl Into<Brush>,
3993 border: Border,
3994 ) {
3995 self.scene.push(SceneCommand::FillRoundedRect {
3996 rect,
3997 radii,
3998 brush: brush.into(),
3999 border: Some(border),
4000 shadow: None,
4001 });
4002 }
4003
4004 pub fn draw_shadow(&mut self, rect: Rect, radii: [f32; 4], shadow: ShadowParams) {
4006 self.scene.push(SceneCommand::FillRoundedRect {
4007 rect,
4008 radii,
4009 brush: Brush::Solid(Color::TRANSPARENT),
4010 border: None,
4011 shadow: Some(shadow),
4012 });
4013 }
4014
4015 pub fn fill_rrect_with_shadow(
4017 &mut self,
4018 rect: Rect,
4019 radii: [f32; 4],
4020 brush: impl Into<Brush>,
4021 shadow: ShadowParams,
4022 ) {
4023 self.scene.push(SceneCommand::FillRoundedRect {
4024 rect,
4025 radii,
4026 brush: brush.into(),
4027 border: None,
4028 shadow: Some(shadow),
4029 });
4030 }
4031
4032 pub fn push_clip(&mut self, path: impl Into<Path>) {
4033 self.scene
4034 .push(SceneCommand::PushClipPath { path: path.into() });
4035 }
4036
4037 pub fn push_clip_rect(&mut self, rect: Rect) {
4038 self.scene.push(SceneCommand::PushClip { rect });
4039 }
4040
4041 pub fn pop_clip(&mut self) {
4042 self.scene.push(SceneCommand::PopClip);
4043 }
4044
4045 pub fn push_transform(&mut self, transform: Transform) {
4046 self.scene.push(SceneCommand::PushTransform { transform });
4047 }
4048
4049 pub fn with_transform<R>(
4060 &mut self,
4061 transform: Transform,
4062 paint: impl FnOnce(&mut PaintCtx) -> R,
4063 ) -> R {
4064 let presentation_transform = transform.then(self.presentation_transform);
4065 let mut child_ctx = PaintCtx::new_with_transform(
4066 self.window_id,
4067 self.widget_id,
4068 self.bounds,
4069 self.focused_widget_id,
4070 self.dpi_info,
4071 Arc::clone(&self.text_system),
4072 Arc::clone(&self.font_registry),
4073 Arc::clone(&self.image_registry),
4074 presentation_transform,
4075 )
4076 .with_frame_time(self.frame_time);
4077 let output = paint(&mut child_ctx);
4078 let (scene, images, mut widget_paint_bounds, ime_composition_rect) = child_ctx.into_parts();
4079
4080 if !scene.commands().is_empty() {
4081 self.scene.push(SceneCommand::PushTransform { transform });
4082 self.scene.append(scene);
4083 self.scene.push(SceneCommand::PopTransform);
4084 }
4085 for (_, bounds) in &mut widget_paint_bounds {
4086 *bounds = transform.transform_rect_bbox(*bounds);
4087 }
4088 self.extend_widget_paint_bounds(widget_paint_bounds);
4089 self.extend_images(images);
4090 self.extend_ime_composition_rect(
4091 ime_composition_rect.map(|bounds| transform.transform_rect_bbox(bounds)),
4092 );
4093 output
4094 }
4095
4096 pub fn translate(&mut self, delta: Vector) {
4097 self.push_transform(Transform::translation_vector(delta));
4098 }
4099
4100 pub fn pop_transform(&mut self) {
4101 self.scene.push(SceneCommand::PopTransform);
4102 }
4103
4104 pub fn push(&mut self, command: SceneCommand) {
4105 self.scene.push(command);
4106 }
4107
4108 pub fn push_retained_scene_layer(&mut self, owner: WidgetId, bounds: Rect, scene: Arc<Scene>) {
4116 let content_bounds = scene.content_bounds().unwrap_or(bounds);
4117 let paint_bounds = scene.paint_bounds().unwrap_or(bounds);
4118 let descriptor = SceneLayerDescriptor::new(SceneLayerId::from_widget(owner), owner, bounds)
4119 .with_content_bounds(content_bounds)
4120 .with_paint_bounds(paint_bounds)
4121 .with_hit_test(false);
4122 self.scene
4123 .push(SceneCommand::Layer(SceneLayer::from_shared_descriptor(
4124 descriptor, scene,
4125 )));
4126 self.record_widget_paint_bounds(owner, paint_bounds);
4127 }
4128
4129 pub fn with_retained_scene_layer<R>(
4138 &mut self,
4139 owner: WidgetId,
4140 bounds: Rect,
4141 paint: impl FnOnce(&mut PaintCtx) -> R,
4142 ) -> R {
4143 let mut child_ctx = PaintCtx::new_with_transform(
4144 self.window_id,
4145 owner,
4146 bounds,
4147 self.focused_widget_id,
4148 self.dpi_info,
4149 Arc::clone(&self.text_system),
4150 Arc::clone(&self.font_registry),
4151 Arc::clone(&self.image_registry),
4152 self.presentation_transform,
4153 )
4154 .with_frame_time(self.frame_time);
4155 child_ctx.output_cache = self.output_cache.clone();
4156 let output = paint(&mut child_ctx);
4157 self.output_reusable &= child_ctx.output_reusable;
4158 let (scene, images, widget_paint_bounds, ime_composition_rect) = child_ctx.into_parts();
4159
4160 if !scene.commands().is_empty() {
4161 self.push_retained_scene_layer(owner, bounds, Arc::new(scene));
4162 }
4163 self.extend_widget_paint_bounds(widget_paint_bounds);
4164 self.extend_images(images);
4165 self.extend_ime_composition_rect(ime_composition_rect);
4166 output
4167 }
4168
4169 pub fn scene(&self) -> &Scene {
4170 &self.scene
4171 }
4172
4173 pub fn scene_mut(&mut self) -> &mut Scene {
4174 &mut self.scene
4175 }
4176
4177 pub fn set_ime_composition_rect(&mut self, rect: Rect) {
4178 self.ime_composition_rect = Some(rect);
4179 }
4180
4181 pub fn clear_ime_composition_rect(&mut self) {
4182 self.ime_composition_rect = None;
4183 }
4184
4185 pub const fn ime_composition_rect(&self) -> Option<Rect> {
4186 self.ime_composition_rect
4187 }
4188
4189 pub(crate) fn push_layer(&mut self, descriptor: SceneLayerDescriptor, scene: Scene) {
4190 self.scene
4191 .push(SceneCommand::Layer(SceneLayer::from_descriptor(
4192 descriptor, scene,
4193 )));
4194 }
4195
4196 pub(crate) fn append_scene(&mut self, scene: Scene) {
4197 self.scene.append(scene);
4198 }
4199
4200 pub(crate) fn record_widget_paint_bounds(&mut self, widget_id: WidgetId, paint_bounds: Rect) {
4201 self.widget_paint_bounds.push((widget_id, paint_bounds));
4202 }
4203
4204 pub(crate) fn extend_widget_paint_bounds(
4205 &mut self,
4206 mut widget_paint_bounds: Vec<(WidgetId, Rect)>,
4207 ) {
4208 if self.widget_paint_bounds.is_empty() {
4209 self.widget_paint_bounds = widget_paint_bounds;
4210 } else {
4211 self.widget_paint_bounds.append(&mut widget_paint_bounds);
4212 }
4213 }
4214
4215 pub(crate) fn extend_images(&mut self, images: Vec<(ImageHandle, PaintImageResource)>) {
4216 self.images.extend(images);
4217 }
4218
4219 pub(crate) fn extend_ime_composition_rect(&mut self, ime_composition_rect: Option<Rect>) {
4220 if ime_composition_rect.is_some() {
4221 self.ime_composition_rect = ime_composition_rect;
4222 }
4223 }
4224
4225 pub(crate) fn into_parts(
4226 self,
4227 ) -> (
4228 Scene,
4229 Vec<(ImageHandle, PaintImageResource)>,
4230 Vec<(WidgetId, Rect)>,
4231 Option<Rect>,
4232 ) {
4233 (
4234 self.scene,
4235 self.images,
4236 self.widget_paint_bounds,
4237 self.ime_composition_rect,
4238 )
4239 }
4240}
4241
4242fn stable_text_run_handle(run: &TextRun) -> TextLayoutHandle {
4243 let mut hasher = DefaultHasher::new();
4244 run.text.hash(&mut hasher);
4245 run.rect.size.width.to_bits().hash(&mut hasher);
4246 run.rect.size.height.to_bits().hash(&mut hasher);
4247 run.style.font.map(|font| font.get()).hash(&mut hasher);
4248 run.style.font_size.to_bits().hash(&mut hasher);
4249 run.style.line_height.to_bits().hash(&mut hasher);
4250 run.style.weight.value().hash(&mut hasher);
4251 run.style.style.hash(&mut hasher);
4252 run.style.stretch.hash(&mut hasher);
4253 run.style.features.hash(&mut hasher);
4254 TextLayoutHandle::new(hasher.finish().max(1))
4255}
4256
4257#[derive(Debug, Clone)]
4258pub struct SemanticsCtx {
4259 pub(crate) output_cache: Option<crate::output_cache::OutputScope>,
4260 output_reusable: bool,
4261 window_id: WindowId,
4262 widget_id: WidgetId,
4263 root_widget_id: WidgetId,
4264 focused_widget_id: Option<WidgetId>,
4265 bounds: Rect,
4266 presentation_transform: Transform,
4267 nodes: Vec<SemanticsNode>,
4268}
4269
4270impl SemanticsCtx {
4271 pub(crate) fn new(
4272 window_id: WindowId,
4273 widget_id: WidgetId,
4274 root_widget_id: WidgetId,
4275 bounds: Rect,
4276 focused_widget_id: Option<WidgetId>,
4277 ) -> Self {
4278 Self::new_with_transform(
4279 window_id,
4280 widget_id,
4281 root_widget_id,
4282 bounds,
4283 focused_widget_id,
4284 Transform::IDENTITY,
4285 )
4286 }
4287
4288 pub(crate) fn new_with_transform(
4289 window_id: WindowId,
4290 widget_id: WidgetId,
4291 root_widget_id: WidgetId,
4292 bounds: Rect,
4293 focused_widget_id: Option<WidgetId>,
4294 presentation_transform: Transform,
4295 ) -> Self {
4296 Self {
4297 output_cache: None,
4298 output_reusable: true,
4299 window_id,
4300 widget_id,
4301 root_widget_id,
4302 focused_widget_id,
4303 bounds,
4304 presentation_transform,
4305 nodes: Vec::new(),
4306 }
4307 }
4308
4309 pub const fn window_id(&self) -> WindowId {
4310 self.window_id
4311 }
4312
4313 pub const fn widget_id(&self) -> WidgetId {
4314 self.widget_id
4315 }
4316
4317 pub fn observe<T, O>(&self, observable: &O) -> T
4319 where
4320 O: Observable<T> + ?Sized,
4321 {
4322 self.observe_with(observable, InvalidationKind::Semantics)
4323 }
4324
4325 pub fn observe_with<T, O>(&self, observable: &O, kind: InvalidationKind) -> T
4327 where
4328 O: Observable<T> + ?Sized,
4329 {
4330 crate::reactive::observe(self.window_id, self.widget_id, observable, kind)
4331 }
4332
4333 pub const fn root_widget_id(&self) -> WidgetId {
4334 self.root_widget_id
4335 }
4336
4337 pub const fn focused_widget_id(&self) -> Option<WidgetId> {
4338 self.focused_widget_id
4339 }
4340
4341 pub fn is_focused(&self) -> bool {
4342 self.focused_widget_id == Some(self.widget_id)
4343 }
4344
4345 pub const fn bounds(&self) -> Rect {
4346 self.bounds
4347 }
4348
4349 pub const fn presentation_transform(&self) -> Transform {
4350 self.presentation_transform
4351 }
4352
4353 pub fn push(&mut self, node: SemanticsNode) {
4354 self.nodes.push(node);
4355 }
4356
4357 pub fn nodes(&self) -> &[SemanticsNode] {
4358 &self.nodes
4359 }
4360
4361 pub(crate) fn extend_nodes(&mut self, nodes: impl IntoIterator<Item = SemanticsNode>) {
4362 self.nodes.extend(nodes);
4363 }
4364
4365 pub(crate) fn into_nodes(self) -> Vec<SemanticsNode> {
4366 self.nodes
4367 }
4368}
4369
4370#[cfg(test)]
4371mod tests {
4372 use std::sync::Arc;
4373
4374 use crate::CommandSender;
4375
4376 use super::{
4377 ArrangeCtx, EventCtx, EventPhase, HostServices, KeyedChildren, MeasureCtx, MeasureScope,
4378 PaintCtx, SemanticsCtx, SingleChild, WakeRequest, Widget, WidgetChildren, WidgetPod,
4379 WidgetPodMutVisitor, WidgetPodVisitor, relative_transform,
4380 };
4381 use std::cell::Cell;
4382 use std::collections::{HashMap, HashSet};
4383 use std::rc::Rc;
4384 use sui_core::{
4385 Color, DpiInfo, ImageHandle, InvalidationKind, Point, Rect, SemanticsNode, SemanticsRole,
4386 Size, Transform, Vector, WidgetId, WindowId,
4387 };
4388
4389 #[test]
4390 fn relative_transform_canonicalizes_shared_transform_roundoff() {
4391 let parent = Transform::new(0.32, 0.0, 0.0, 0.32, 1430.0, 510.0);
4392 let roundoff = Transform::new(0.32000002, 0.0, 0.0, 0.31999996, 1430.0001, 509.99994);
4393 assert_eq!(relative_transform(roundoff, parent), Transform::IDENTITY);
4394
4395 let translated = Transform::new(0.32, 0.0, 0.0, 0.32, 1430.01, 510.0);
4396 assert!(!relative_transform(translated, parent).is_identity());
4397 }
4398 use sui_layout::{Constraints, LayoutContext};
4399 use sui_scene::{ImageRegistry, RegisteredImage, SceneCommand, StrokeStyle};
4400 use sui_text::{FontRegistry, FontWeight, TextRun, TextStyle, TextSystem};
4401
4402 fn measure_ctx(window_id: WindowId, widget_id: WidgetId) -> MeasureCtx {
4403 MeasureCtx::new(
4404 window_id,
4405 widget_id,
4406 Rect::ZERO,
4407 DpiInfo::default(),
4408 std::sync::Arc::new(TextSystem::new()),
4409 std::sync::Arc::new(FontRegistry::new()),
4410 std::sync::Arc::new(ImageRegistry::new()),
4411 )
4412 }
4413
4414 #[test]
4415 fn measure_ctx_wraps_reusable_layout_context() {
4416 let mut images = ImageRegistry::new();
4417 images.insert(
4418 ImageHandle::new(9),
4419 RegisteredImage::from_rgba8(3, 2, vec![255; 3 * 2 * 4]).unwrap(),
4420 );
4421 let layout = LayoutContext::new(
4422 DpiInfo::new(
4423 1.5,
4424 Some(144.0),
4425 Size::new(200.0, 100.0),
4426 Size::new(300.0, 150.0),
4427 ),
4428 Arc::new(TextSystem::new()),
4429 Arc::new(FontRegistry::new()),
4430 Arc::new(images),
4431 );
4432
4433 let measure = MeasureCtx::with_layout(
4434 WindowId::new(1),
4435 WidgetId::new(2),
4436 Rect::new(4.0, 6.0, 32.0, 18.0),
4437 layout.clone(),
4438 );
4439
4440 assert_eq!(measure.dpi(), layout.dpi());
4441 assert_eq!(measure.bounds(), Rect::new(4.0, 6.0, 32.0, 18.0));
4442 assert_eq!(
4443 measure.layout().image_size(ImageHandle::new(9)),
4444 Some(Size::new(3.0, 2.0))
4445 );
4446 }
4447
4448 #[test]
4449 fn measure_and_paint_ctx_expose_dpi_info() {
4450 let dpi = DpiInfo::new(
4451 2.0,
4452 Some(192.0),
4453 sui_core::Size::new(320.0, 180.0),
4454 sui_core::Size::new(640.0, 360.0),
4455 );
4456
4457 let measure = MeasureCtx::new(
4458 WindowId::new(1),
4459 WidgetId::new(2),
4460 Rect::ZERO,
4461 dpi,
4462 std::sync::Arc::new(TextSystem::new()),
4463 std::sync::Arc::new(FontRegistry::new()),
4464 std::sync::Arc::new(ImageRegistry::new()),
4465 );
4466 let paint = PaintCtx::new(
4467 WindowId::new(1),
4468 WidgetId::new(2),
4469 Rect::new(0.0, 0.0, 120.0, 60.0),
4470 None,
4471 dpi,
4472 Arc::new(TextSystem::new()),
4473 Arc::new(FontRegistry::new()),
4474 Arc::new(ImageRegistry::new()),
4475 );
4476 let event = EventCtx::new(
4477 WindowId::new(1),
4478 WidgetId::new(2),
4479 Rect::new(0.0, 0.0, 120.0, 60.0),
4480 dpi,
4481 0.0,
4482 EventPhase::Target,
4483 None,
4484 HostServices::default(),
4485 CommandSender::new(),
4486 );
4487
4488 assert_eq!(measure.dpi(), dpi);
4489 assert_eq!(paint.dpi(), dpi);
4490 assert_eq!(event.dpi(), dpi);
4491 }
4492
4493 struct LabelWidget;
4494
4495 impl Widget for LabelWidget {
4496 fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> sui_core::Size {
4497 constraints.clamp(sui_core::Size::new(48.0, 20.0))
4498 }
4499
4500 fn paint(&self, ctx: &mut PaintCtx) {
4501 ctx.fill_bounds(Color::rgba(0.2, 0.3, 0.4, 1.0));
4502 }
4503
4504 fn semantics(&self, ctx: &mut SemanticsCtx) {
4505 ctx.push(SemanticsNode::new(
4506 ctx.widget_id(),
4507 SemanticsRole::Text,
4508 ctx.bounds(),
4509 ));
4510 }
4511 }
4512
4513 struct BoundsLeaf;
4514
4515 impl Widget for BoundsLeaf {
4516 fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
4517 constraints.max
4518 }
4519
4520 fn paint(&self, ctx: &mut PaintCtx) {
4521 ctx.fill_rect(
4522 Rect::new(10.0, 10.0, 80.0, 50.0),
4523 Color::rgba(0.2, 0.3, 0.4, 1.0),
4524 );
4525 }
4526 }
4527
4528 struct BoundsWrapper {
4529 child: WidgetPod,
4530 clip: Option<Rect>,
4531 translation: Vector,
4532 }
4533
4534 impl BoundsWrapper {
4535 fn new(child: impl Widget + 'static, clip: Option<Rect>, translation: Vector) -> Self {
4536 Self {
4537 child: WidgetPod::new(child),
4538 clip,
4539 translation,
4540 }
4541 }
4542 }
4543
4544 impl Widget for BoundsWrapper {
4545 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
4546 self.child.measure(ctx, constraints)
4547 }
4548
4549 fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
4550 self.child.arrange(ctx, bounds);
4551 }
4552
4553 fn paint(&self, ctx: &mut PaintCtx) {
4554 if let Some(clip) = self.clip {
4555 ctx.push_clip_rect(clip);
4556 }
4557 if self.translation != Vector::ZERO {
4558 ctx.translate(self.translation);
4559 }
4560
4561 self.child.paint(ctx);
4562
4563 if self.translation != Vector::ZERO {
4564 ctx.pop_transform();
4565 }
4566 if self.clip.is_some() {
4567 ctx.pop_clip();
4568 }
4569 }
4570
4571 fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
4572 visitor.visit(&self.child);
4573 }
4574
4575 fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
4576 visitor.visit(&mut self.child);
4577 }
4578 }
4579
4580 #[test]
4581 fn event_ctx_tracks_widget_scoped_invalidations_and_focus() {
4582 let mut ctx = EventCtx::new(
4583 WindowId::new(1),
4584 WidgetId::new(2),
4585 Rect::new(8.0, 12.0, 24.0, 36.0),
4586 DpiInfo::default(),
4587 0.0,
4588 EventPhase::Target,
4589 None,
4590 HostServices::default(),
4591 CommandSender::new(),
4592 );
4593
4594 ctx.request_measure();
4595 ctx.request_paint_rect(Rect::new(8.0, 12.0, 24.0, 36.0));
4596 ctx.request_transform();
4597 ctx.request_effect();
4598 ctx.request_visibility();
4599 ctx.request_animation_frame();
4600 ctx.request_focus();
4601 ctx.set_handled();
4602
4603 assert!(ctx.is_handled());
4604 assert_eq!(ctx.bounds(), Rect::new(8.0, 12.0, 24.0, 36.0));
4605 assert_eq!(ctx.invalidations().len(), 5);
4606 assert_eq!(ctx.invalidations()[0].kind, InvalidationKind::Measure);
4607 assert_eq!(
4608 ctx.invalidations()[1].region,
4609 Some(Rect::new(8.0, 12.0, 24.0, 36.0))
4610 );
4611 assert_eq!(ctx.invalidations()[2].kind, InvalidationKind::Transform);
4612 assert_eq!(ctx.invalidations()[3].kind, InvalidationKind::Effect);
4613 assert_eq!(ctx.invalidations()[4].kind, InvalidationKind::Visibility);
4614 assert_eq!(
4615 ctx.take_wake_requests(),
4616 vec![WakeRequest::RequestAnimationFrame {
4617 target: WidgetId::new(2)
4618 }]
4619 );
4620 }
4621
4622 #[test]
4623 fn request_animation_frame_enqueues_widget_for_next_frame() {
4624 let mut ctx = EventCtx::new(
4625 WindowId::new(4),
4626 WidgetId::new(9),
4627 Rect::new(0.0, 0.0, 20.0, 10.0),
4628 DpiInfo::default(),
4629 16.0,
4630 EventPhase::Target,
4631 None,
4632 HostServices::default(),
4633 CommandSender::new(),
4634 );
4635
4636 ctx.request_animation_frame();
4637
4638 assert_eq!(
4639 ctx.take_wake_requests(),
4640 vec![WakeRequest::RequestAnimationFrame {
4641 target: WidgetId::new(9)
4642 }]
4643 );
4644 }
4645
4646 struct CountingChild {
4647 measures: Rc<Cell<u32>>,
4648 }
4649
4650 impl Widget for CountingChild {
4651 fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> sui_core::Size {
4652 self.measures.set(self.measures.get() + 1);
4653 constraints.clamp(sui_core::Size::new(10.0, 10.0))
4654 }
4655 }
4656
4657 struct PassthroughParent {
4658 child: WidgetPod,
4659 }
4660
4661 impl Widget for PassthroughParent {
4662 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> sui_core::Size {
4663 self.child.measure(ctx, constraints)
4664 }
4665
4666 fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
4667 visitor.visit(&self.child);
4668 }
4669
4670 fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
4671 visitor.visit(&mut self.child);
4672 }
4673 }
4674
4675 fn scoped_measure_ctx(root_id: WidgetId, scope: MeasureScope) -> MeasureCtx {
4676 MeasureCtx::new_scoped_at(
4677 WindowId::new(1),
4678 root_id,
4679 Rect::ZERO,
4680 DpiInfo::default(),
4681 Arc::new(TextSystem::new()),
4682 Arc::new(FontRegistry::new()),
4683 Arc::new(ImageRegistry::new()),
4684 Rc::new(scope),
4685 0.0,
4686 )
4687 }
4688
4689 #[test]
4690 fn scalar_probes_preserve_final_state_and_have_bounded_storage() {
4691 struct Probe {
4692 calls: Rc<Cell<u32>>,
4693 width: Rc<Cell<f32>>,
4694 }
4695 impl Widget for Probe {
4696 fn measure(&mut self, _: &mut MeasureCtx, constraints: Constraints) -> Size {
4697 self.calls.set(self.calls.get() + 1);
4698 self.width.set(constraints.max.width);
4699 constraints.clamp(Size::new(30.0, 10.0))
4700 }
4701 }
4702 let calls = Rc::new(Cell::new(0));
4703 let width = Rc::new(Cell::new(0.0));
4704 let mut pod = WidgetPod::new(Probe {
4705 calls: calls.clone(),
4706 width: width.clone(),
4707 });
4708 let root = WidgetId::new(u64::MAX);
4709 let constraint = |width| Constraints::tight(Size::new(width, 10.0));
4710 let mut clean = scoped_measure_ctx(root, MeasureScope::default());
4711 pod.probe_measure(&mut clean, constraint(10.0));
4712 pod.probe_measure(&mut clean, constraint(20.0));
4713 pod.measure(&mut clean, constraint(100.0));
4714 let before = calls.get();
4715 assert_eq!(pod.probe_measure(&mut clean, constraint(10.0)).width, 10.0);
4716 pod.measure(&mut clean, constraint(100.0));
4717 assert_eq!(calls.get(), before);
4718 assert_eq!(width.get(), 100.0);
4719 assert_eq!(pod.measured_size().width, 100.0);
4720 pod.probe_measure(&mut clean, constraint(30.0));
4721 pod.probe_measure(&mut clean, constraint(40.0));
4722 pod.probe_measure(&mut clean, constraint(50.0));
4723 pod.probe_measure(&mut clean, constraint(10.0)); assert_eq!(calls.get(), before + 4);
4725 assert_eq!(
4726 pod.probe_cache
4727 .as_ref()
4728 .unwrap()
4729 .measurements
4730 .iter()
4731 .flatten()
4732 .count(),
4733 4
4734 );
4735 }
4736
4737 #[test]
4738 fn size_only_hooks_require_explicit_forwarding_and_final_commit() {
4739 struct Leaf {
4740 queries: Rc<Cell<u32>>,
4741 commits: Rc<Cell<u32>>,
4742 width: Rc<Cell<f32>>,
4743 }
4744 impl Widget for Leaf {
4745 fn measure_size(&mut self, _: &mut MeasureCtx, c: Constraints) -> Size {
4746 self.queries.set(self.queries.get() + 1);
4747 c.clamp(Size::new(20.0, 10.0))
4748 }
4749 fn measure(&mut self, _: &mut MeasureCtx, c: Constraints) -> Size {
4750 self.commits.set(self.commits.get() + 1);
4751 self.width.set(c.max.width);
4752 c.clamp(Size::new(20.0, 10.0))
4753 }
4754 }
4755 struct Forwarder(WidgetPod);
4756 impl Widget for Forwarder {
4757 fn measure_size(&mut self, ctx: &mut MeasureCtx, c: Constraints) -> Size {
4758 self.0.probe_measure(ctx, c)
4759 }
4760 fn measure(&mut self, ctx: &mut MeasureCtx, c: Constraints) -> Size {
4761 self.0.measure(ctx, c);
4762 self.0.measured_size()
4763 }
4764 }
4765 let queries = Rc::new(Cell::new(0));
4766 let commits = Rc::new(Cell::new(0));
4767 let width = Rc::new(Cell::new(0.0));
4768 let mut pod = WidgetPod::new(Forwarder(WidgetPod::new(Leaf {
4769 queries: queries.clone(),
4770 commits: commits.clone(),
4771 width: width.clone(),
4772 })));
4773 let mut ctx = scoped_measure_ctx(WidgetId::new(u64::MAX), MeasureScope::default());
4774 let c = Constraints::tight(Size::new(100.0, 10.0));
4775 assert_eq!(pod.probe_measure(&mut ctx, c), c.max);
4776 assert_eq!(queries.get(), 1);
4777 assert_eq!(commits.get(), 0);
4778 assert_eq!(width.get(), 0.0);
4779 assert_eq!(pod.measure(&mut ctx, c), c.max);
4780 assert_eq!(
4781 commits.get(),
4782 1,
4783 "a size probe cannot satisfy final measurement"
4784 );
4785 pod.probe_measure(&mut ctx, Constraints::tight(Size::new(50.0, 10.0)));
4786 pod.measure(&mut ctx, c);
4787 assert_eq!(commits.get(), 2);
4788 assert_eq!(width.get(), 100.0);
4789 }
4790
4791 #[test]
4792 fn default_size_hook_preserves_stateful_child_measure_contract() {
4793 struct Leaf(Rc<Cell<f32>>);
4794 impl Widget for Leaf {
4795 fn measure_size(&mut self, _: &mut MeasureCtx, c: Constraints) -> Size {
4796 Size::new(c.max.width, 10.0)
4797 }
4798 fn measure(&mut self, _: &mut MeasureCtx, c: Constraints) -> Size {
4799 self.0.set(c.max.width);
4800 Size::new(c.max.width, 10.0)
4801 }
4802 }
4803 struct Legacy {
4804 child: WidgetPod,
4805 width: Rc<Cell<f32>>,
4806 }
4807 impl Widget for Legacy {
4808 fn measure(&mut self, ctx: &mut MeasureCtx, c: Constraints) -> Size {
4809 self.child.measure(ctx, c);
4810 Size::new(self.width.get(), 10.0)
4812 }
4813 }
4814 let width = Rc::new(Cell::new(0.0));
4815 let mut pod = WidgetPod::new(Legacy {
4816 child: WidgetPod::new(Leaf(width.clone())),
4817 width: width.clone(),
4818 });
4819 let mut ctx = scoped_measure_ctx(WidgetId::new(u64::MAX), MeasureScope::default());
4820 let c = |width| Constraints::new(Size::ZERO, Size::new(width, 20.0));
4821 assert_eq!(pod.probe_measure(&mut ctx, c(100.0)).width, 100.0);
4822 assert_eq!(pod.probe_measure(&mut ctx, c(200.0)).width, 200.0);
4823 assert_eq!(pod.probe_measure(&mut ctx, c(100.0)).width, 100.0);
4824 assert_eq!(pod.measure(&mut ctx, c(100.0)).width, 100.0);
4825 assert_eq!(width.get(), 100.0);
4826 }
4827
4828 #[test]
4829 fn axis_queries_are_distinct_and_invalidate_with_the_window_context() {
4830 use sui_layout::Axis;
4831 struct Leaf(Rc<Cell<u32>>, Rc<Cell<f32>>);
4832 impl Widget for Leaf {
4833 fn measure(&mut self, _: &mut MeasureCtx, c: Constraints) -> Size {
4834 self.0.set(self.0.get() + 1);
4835 c.clamp(Size::new(self.1.get(), 13.0))
4836 }
4837 }
4838 let calls = Rc::new(Cell::new(0));
4839 let value = Rc::new(Cell::new(27.0));
4840 let mut pod = WidgetPod::new(Leaf(calls.clone(), value.clone()));
4841 let shared = crate::measure_cache::MeasureQueryCache::shared();
4842 let root = WidgetId::new(u64::MAX);
4843 let mut ctx = scoped_measure_ctx(root, MeasureScope::default());
4844 ctx.set_query_cache(shared.clone());
4845 let c = Constraints::new(Size::ZERO, Size::new(100.0, 100.0));
4846 for width in 100..110 {
4847 let c = Constraints::new(Size::ZERO, Size::new(width as f32, 100.0));
4848 assert_eq!(pod.probe_measure_axis(&mut ctx, c, Axis::Horizontal), 27.0);
4849 assert_eq!(pod.probe_measure_axis(&mut ctx, c, Axis::Vertical), 13.0);
4850 assert_eq!(pod.probe_measure(&mut ctx, c), Size::new(27.0, 13.0));
4851 }
4852 let before = calls.get();
4853 assert_eq!(pod.probe_measure_axis(&mut ctx, c, Axis::Horizontal), 27.0);
4854 assert_eq!(pod.probe_measure_axis(&mut ctx, c, Axis::Vertical), 13.0);
4855 assert_eq!(pod.probe_measure(&mut ctx, c), Size::new(27.0, 13.0));
4856 assert_eq!(
4857 calls.get(),
4858 before,
4859 "overflow hits must preserve query kind"
4860 );
4861 assert_eq!(pod.measure(&mut ctx, c), Size::new(27.0, 13.0));
4862 assert_eq!(calls.get(), before + 1, "axis hits cannot commit layout");
4863 value.set(41.0);
4864 shared.borrow_mut().invalidate_context();
4865 let mut next = scoped_measure_ctx(root, MeasureScope::default());
4866 next.set_query_cache(shared);
4867 assert_eq!(pod.probe_measure_axis(&mut next, c, Axis::Horizontal), 41.0);
4868 assert_eq!(pod.measure(&mut next, c), Size::new(41.0, 13.0));
4869 }
4870
4871 #[test]
4872 fn window_query_cache_reuses_evicted_local_entries_and_respects_all_invalidations() {
4873 struct Leaf(Rc<Cell<f32>>, Rc<Cell<u32>>);
4874 impl Widget for Leaf {
4875 fn measure(&mut self, _: &mut MeasureCtx, c: Constraints) -> Size {
4876 self.1.set(self.1.get() + 1);
4877 c.clamp(Size::new(self.0.get(), 10.0))
4878 }
4879 }
4880 let value = Rc::new(Cell::new(20.0));
4881 let calls = Rc::new(Cell::new(0));
4882 let mut pod = WidgetPod::new(Leaf(value.clone(), calls.clone()));
4883 let shared = crate::measure_cache::MeasureQueryCache::shared();
4884 let root = WidgetId::new(u64::MAX);
4885 let mut clean = scoped_measure_ctx(root, MeasureScope::default());
4886 clean.set_query_cache(shared.clone());
4887 let constraint = |width| Constraints::new(Size::ZERO, Size::new(width, 20.0));
4888 for width in 100..104 {
4889 pod.probe_measure(&mut clean, constraint(width as f32));
4890 }
4891 for width in 100..104 {
4892 let key = crate::measure_cache::QueryKey::new(
4893 pod.id(),
4894 pod.probe_cache.as_ref().unwrap().revision,
4895 constraint(width as f32),
4896 )
4897 .unwrap();
4898 let mut window = shared.borrow_mut();
4899 let context = window.context();
4900 assert!(
4901 window.get(context, &key).is_none(),
4902 "small query sets should stay in the local cache"
4903 );
4904 }
4905 for width in 104..110 {
4906 pod.probe_measure(&mut clean, constraint(width as f32));
4907 }
4908 let before = calls.get();
4909 assert_eq!(pod.probe_measure(&mut clean, constraint(100.0)).width, 20.0);
4910 assert_eq!(
4911 calls.get(),
4912 before,
4913 "the window cache should survive local eviction"
4914 );
4915 value.set(30.0);
4916 let mut dirty = scoped_measure_ctx(
4917 root,
4918 MeasureScope::scoped(HashSet::from([pod.id()]), HashSet::new()),
4919 );
4920 dirty.set_query_cache(shared.clone());
4921 assert_eq!(pod.probe_measure(&mut dirty, constraint(100.0)).width, 30.0);
4922 pod.measure(&mut clean, constraint(100.0));
4923 value.set(40.0);
4924 shared.borrow_mut().invalidate_context(); clean.set_query_cache(shared.clone()); assert_eq!(pod.measure(&mut clean, constraint(100.0)).width, 40.0);
4927 let mut external =
4928 MeasureCtx::with_layout(clean.window_id(), root, Rect::ZERO, clean.layout().clone());
4929 value.set(50.0);
4930 assert_eq!(
4931 pod.probe_measure(&mut external, constraint(100.0)).width,
4932 50.0
4933 );
4934 value.set(60.0);
4935 assert_eq!(
4936 pod.probe_measure(&mut external, constraint(100.0)).width,
4937 60.0
4938 );
4939 assert_eq!(pod.probe_measure(&mut clean, constraint(100.0)).width, 60.0);
4940 let mut other = scoped_measure_ctx(root, MeasureScope::default());
4942 other.set_query_cache(crate::measure_cache::MeasureQueryCache::shared());
4943 value.set(70.0);
4944 assert_eq!(pod.measure(&mut other, constraint(100.0)).width, 70.0);
4945 }
4946
4947 #[test]
4948 fn probe_invalidation_discards_all_constraints_and_preserves_forced_callbacks() {
4949 struct Probe(Rc<Cell<u32>>);
4950 impl Widget for Probe {
4951 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
4952 self.0.set(self.0.get() + 1);
4953 ctx.request_paint();
4954 ctx.request_animation_frame();
4955 constraints.clamp(Size::new(self.0.get() as f32, 10.0))
4956 }
4957 }
4958 let calls = Rc::new(Cell::new(0));
4959 let mut pod = WidgetPod::new(Probe(calls.clone()));
4960 let root = WidgetId::new(u64::MAX);
4961 let a = Constraints::new(Size::ZERO, Size::new(100.0, 10.0));
4962 let b = Constraints::new(Size::ZERO, Size::new(200.0, 10.0));
4963 let mut initial = scoped_measure_ctx(root, MeasureScope::force_all());
4964 pod.probe_measure(&mut initial, a);
4965 pod.probe_measure(&mut initial, b);
4966 let mut dirty = scoped_measure_ctx(
4967 root,
4968 MeasureScope::scoped(HashSet::from([pod.id()]), HashSet::new()),
4969 );
4970 pod.probe_measure(&mut dirty, a);
4971 pod.measure(&mut dirty, a);
4972 pod.measure(&mut dirty, a);
4973 assert_eq!(
4974 calls.get(),
4975 5,
4976 "forced ordinary callbacks must still execute"
4977 );
4978 assert_eq!(dirty.invalidations.len(), 3);
4979 assert_eq!(dirty.wake_requests.len(), 3);
4980 let mut clean = scoped_measure_ctx(root, MeasureScope::default());
4981 pod.probe_measure(&mut clean, b);
4982 assert_eq!(
4983 calls.get(),
4984 6,
4985 "an unqueried constraint survived invalidation"
4986 );
4987 let mut subtree = scoped_measure_ctx(
4988 root,
4989 MeasureScope::scoped(HashSet::new(), HashSet::from([root])),
4990 );
4991 pod.probe_measure(&mut subtree, b);
4992 assert_eq!(calls.get(), 7);
4993 let mut resized = scoped_measure_ctx(root, MeasureScope::force_all());
4994 pod.probe_measure(&mut resized, b);
4995 assert_eq!(calls.get(), 8);
4996 }
4997
4998 #[test]
4999 fn external_measure_context_keeps_full_measure_semantics_when_reused() {
5000 struct Leaf(Rc<Cell<f32>>);
5001 impl Widget for Leaf {
5002 fn measure(&mut self, _: &mut MeasureCtx, c: Constraints) -> Size {
5003 c.clamp(Size::new(self.0.get(), 10.0))
5004 }
5005 }
5006 struct Parent(WidgetPod);
5007 impl Widget for Parent {
5008 fn measure(&mut self, ctx: &mut MeasureCtx, c: Constraints) -> Size {
5009 let natural = self.0.probe_measure(ctx, Constraints::UNBOUNDED);
5010 self.0.measure(ctx, c);
5011 c.clamp(natural)
5012 }
5013 }
5014 let value = Rc::new(Cell::new(20.0));
5015 let mut pod = WidgetPod::new(Parent(WidgetPod::new(Leaf(value.clone()))));
5016 let root = WidgetId::new(u64::MAX);
5017 let template = scoped_measure_ctx(root, MeasureScope::force_all());
5018 let mut ctx = MeasureCtx::with_layout(
5019 template.window_id(),
5020 root,
5021 Rect::ZERO,
5022 template.layout().clone(),
5023 );
5024 let constraints = Constraints::new(Size::ZERO, Size::new(100.0, 20.0));
5025 assert_eq!(pod.measure(&mut ctx, constraints).width, 20.0);
5026 value.set(40.0);
5027 assert_eq!(pod.measure(&mut ctx, constraints).width, 40.0);
5028 }
5029
5030 #[test]
5031 fn dirty_probes_reuse_results_within_a_pass_but_final_measurement_still_executes() {
5032 let calls = Rc::new(Cell::new(0));
5033 let mut pod = WidgetPod::new(CountingChild {
5034 measures: calls.clone(),
5035 });
5036 let root = WidgetId::new(u64::MAX);
5037 let constraints = Constraints::tight(Size::new(100.0, 10.0));
5038 let mut pass = scoped_measure_ctx(root, MeasureScope::force_all());
5039 pod.probe_measure(&mut pass, constraints);
5040 pod.probe_measure(&mut pass, constraints);
5041 assert_eq!(calls.get(), 1);
5042 pod.measure(&mut pass, constraints);
5043 pod.measure(&mut pass, constraints);
5044 assert_eq!(calls.get(), 3);
5045 pod.intrinsic_size(&mut pass, sui_layout::Axis::Horizontal, 10.0);
5046 pod.intrinsic_size(&mut pass, sui_layout::Axis::Horizontal, 10.0);
5047 assert_eq!(calls.get(), 4);
5048 let mut next = scoped_measure_ctx(root, MeasureScope::force_all());
5049 pod.probe_measure(&mut next, constraints);
5050 assert_eq!(
5051 calls.get(),
5052 5,
5053 "a new dirty pass must invalidate the previous queries"
5054 );
5055 }
5056
5057 #[test]
5058 fn intrinsic_cache_keys_include_axis_and_cross_extent() {
5059 struct Probe(Rc<Cell<u32>>);
5060 impl Widget for Probe {
5061 fn intrinsic_size(
5062 &mut self,
5063 _: &mut MeasureCtx,
5064 axis: sui_layout::Axis,
5065 cross: f32,
5066 ) -> sui_layout::IntrinsicSize {
5067 self.0.set(self.0.get() + 1);
5068 let offset = if axis == sui_layout::Axis::Horizontal {
5069 1.0
5070 } else {
5071 2.0
5072 };
5073 sui_layout::IntrinsicSize::fixed(cross + offset)
5074 }
5075 }
5076 let calls = Rc::new(Cell::new(0));
5077 let mut pod = WidgetPod::new(Probe(calls.clone()));
5078 let root = WidgetId::new(u64::MAX);
5079 let mut clean = scoped_measure_ctx(root, MeasureScope::default());
5080 for _ in 0..2 {
5081 assert_eq!(
5082 pod.intrinsic_size(&mut clean, sui_layout::Axis::Horizontal, 10.0)
5083 .natural,
5084 11.0
5085 );
5086 assert_eq!(
5087 pod.intrinsic_size(&mut clean, sui_layout::Axis::Vertical, 10.0)
5088 .natural,
5089 12.0
5090 );
5091 }
5092 assert_eq!(calls.get(), 2);
5093 assert_eq!(
5094 pod.intrinsic_size(&mut clean, sui_layout::Axis::Horizontal, 20.0)
5095 .natural,
5096 21.0
5097 );
5098 assert_eq!(calls.get(), 3);
5099 let mut dirty = scoped_measure_ctx(
5100 root,
5101 MeasureScope::scoped(HashSet::from([pod.id()]), HashSet::new()),
5102 );
5103 pod.measure(&mut dirty, Constraints::tight(Size::new(10.0, 10.0)));
5104 pod.intrinsic_size(&mut clean, sui_layout::Axis::Vertical, 10.0);
5105 assert_eq!(
5106 calls.get(),
5107 4,
5108 "ordinary dirty measurement must also clear intrinsic probes"
5109 );
5110 }
5111
5112 #[test]
5113 fn intrinsic_probe_cannot_leave_a_cached_final_layout_in_the_wrong_state() {
5114 struct StatefulMeasure(Rc<Cell<f32>>);
5115 impl Widget for StatefulMeasure {
5116 fn measure(&mut self, _: &mut MeasureCtx, constraints: Constraints) -> Size {
5117 self.0.set(constraints.max.width);
5118 constraints.clamp(Size::new(20.0, 20.0))
5119 }
5120 }
5121 let committed_width = Rc::new(Cell::new(0.0));
5122 let mut pod = WidgetPod::new(StatefulMeasure(committed_width.clone()));
5123 let root = WidgetId::new(u64::MAX);
5124 let final_constraints = Constraints::tight(Size::new(100.0, 20.0));
5125 let mut initial = scoped_measure_ctx(root, MeasureScope::force_all());
5126 pod.measure(&mut initial, final_constraints);
5127 let mut clean =
5128 scoped_measure_ctx(root, MeasureScope::scoped(HashSet::new(), HashSet::new()));
5129 pod.intrinsic_size(&mut clean, sui_layout::Axis::Horizontal, 20.0);
5130 pod.measure(&mut clean, final_constraints);
5131 assert_eq!(
5132 committed_width.get(),
5133 100.0,
5134 "a scalar cache hit did not restore the final layout state"
5135 );
5136 }
5137
5138 #[test]
5139 fn measure_cache_skips_clean_subtrees_and_forces_changed_ones() {
5140 let measures = Rc::new(Cell::new(0u32));
5141 let child = WidgetPod::new(CountingChild {
5142 measures: Rc::clone(&measures),
5143 });
5144 let mut parent = WidgetPod::new(PassthroughParent { child });
5145 let parent_id = parent.id();
5146 let outside = WidgetId::new(u64::MAX);
5147 let constraints = Constraints::tight(sui_core::Size::new(10.0, 10.0));
5148
5149 let mut ctx = scoped_measure_ctx(outside, MeasureScope::force_all());
5151 parent.measure(&mut ctx, constraints);
5152 assert_eq!(measures.get(), 1, "initial pass must measure the child");
5153
5154 let mut ctx = scoped_measure_ctx(
5157 outside,
5158 MeasureScope::scoped(HashSet::new(), HashSet::new()),
5159 );
5160 parent.measure(&mut ctx, constraints);
5161 assert_eq!(measures.get(), 1, "clean subtree must be skipped");
5162
5163 let mut dirty = HashSet::new();
5166 dirty.insert(parent_id);
5167 let mut ctx = scoped_measure_ctx(outside, MeasureScope::scoped(dirty, HashSet::new()));
5168 parent.measure(&mut ctx, constraints);
5169 assert_eq!(
5170 measures.get(),
5171 1,
5172 "ancestor-only re-measure must not force the subtree"
5173 );
5174
5175 let mut dirty = HashSet::new();
5179 dirty.insert(parent_id);
5180 let mut roots = HashSet::new();
5181 roots.insert(parent_id);
5182 let mut ctx = scoped_measure_ctx(outside, MeasureScope::scoped(dirty, roots));
5183 parent.measure(&mut ctx, constraints);
5184 assert_eq!(
5185 measures.get(),
5186 2,
5187 "a changed widget must force its descendants to re-measure"
5188 );
5189 }
5190
5191 #[test]
5192 fn widget_pod_merges_child_measure_arrange_paint_and_semantics() {
5193 let mut pod = WidgetPod::new(LabelWidget);
5194 pod.set_bounds(Rect::new(4.0, 6.0, 0.0, 0.0));
5195
5196 let mut measure = measure_ctx(WindowId::new(3), WidgetId::new(4));
5197 let size = pod.measure(
5198 &mut measure,
5199 Constraints::tight(sui_core::Size::new(64.0, 32.0)),
5200 );
5201 let mut arrange = ArrangeCtx::new(WindowId::new(3), WidgetId::new(4), DpiInfo::default());
5202 pod.arrange(&mut arrange, Rect::new(4.0, 6.0, 64.0, 32.0));
5203
5204 let mut paint = PaintCtx::new(
5205 WindowId::new(3),
5206 WidgetId::new(4),
5207 Rect::new(0.0, 0.0, 120.0, 60.0),
5208 None,
5209 DpiInfo::default(),
5210 Arc::new(TextSystem::new()),
5211 Arc::new(FontRegistry::new()),
5212 Arc::new(ImageRegistry::new()),
5213 );
5214 pod.paint(&mut paint);
5215
5216 let mut semantics = SemanticsCtx::new(
5217 WindowId::new(3),
5218 WidgetId::new(4),
5219 WidgetId::new(4),
5220 Rect::new(0.0, 0.0, 120.0, 60.0),
5221 None,
5222 );
5223 pod.semantics(&mut semantics);
5224
5225 assert_eq!(size, sui_core::Size::new(64.0, 32.0));
5226 assert_eq!(pod.bounds(), Rect::new(4.0, 6.0, 64.0, 32.0));
5227 assert_eq!(paint.scene().commands().len(), 1);
5228 assert!(matches!(
5229 paint.scene().commands()[0],
5230 SceneCommand::FillRect { .. }
5231 ));
5232 assert_eq!(semantics.nodes().len(), 1);
5233 }
5234
5235 #[test]
5236 fn remeasured_subtree_arranges_children_outside_the_dirty_scope() {
5237 let window_id = WindowId::new(1);
5238 let parent_id = WidgetId::new(2);
5239 struct ArrangedBounds(Rc<std::cell::Cell<Rect>>);
5240 impl Widget for ArrangedBounds {
5241 fn measure(&mut self, _: &mut MeasureCtx, constraints: Constraints) -> Size {
5242 constraints.max
5243 }
5244 fn arrange(&mut self, _: &mut ArrangeCtx, bounds: Rect) {
5245 self.0.set(bounds);
5246 }
5247 }
5248 let actual = Rc::new(std::cell::Cell::new(Rect::new(0.0, 0.0, 0.0, 0.0)));
5249 let mut pod = WidgetPod::new(BoundsWrapper::new(
5250 ArrangedBounds(actual.clone()),
5251 None,
5252 Vector::ZERO,
5253 ));
5254 let mut measure = measure_ctx(window_id, parent_id);
5255 pod.measure(&mut measure, Constraints::tight(Size::new(100.0, 80.0)));
5256 let mut arrange = ArrangeCtx::new(window_id, parent_id, DpiInfo::default());
5257 pod.arrange(&mut arrange, Rect::new(0.0, 0.0, 100.0, 80.0));
5258 pod.measure(&mut measure, Constraints::tight(Size::new(180.0, 80.0)));
5261 let mut arrange = ArrangeCtx::new_scoped_at(
5262 window_id,
5263 parent_id,
5264 DpiInfo::default(),
5265 0.0,
5266 Rc::new(super::ArrangeScope::scoped(
5267 [parent_id].into_iter().collect(),
5268 )),
5269 );
5270 pod.arrange(&mut arrange, Rect::new(0.0, 0.0, 180.0, 80.0));
5271 struct BoundsVisitor(Vec<Rect>);
5272 impl WidgetPodVisitor for BoundsVisitor {
5273 fn visit(&mut self, child: &WidgetPod) {
5274 self.0.push(child.bounds());
5275 }
5276 }
5277 let mut visitor = BoundsVisitor(Vec::new());
5278 pod.visit_children(&mut visitor);
5279 assert_eq!(visitor.0, vec![Rect::new(0.0, 0.0, 180.0, 80.0)]);
5280 assert_eq!(actual.get(), Rect::new(0.0, 0.0, 180.0, 80.0));
5281 }
5282
5283 #[test]
5284 fn single_child_wraps_measure_arrange_and_visitation() {
5285 struct CaptureVisitor {
5286 ids: Vec<WidgetId>,
5287 }
5288
5289 impl WidgetPodVisitor for CaptureVisitor {
5290 fn visit(&mut self, child: &WidgetPod) {
5291 self.ids.push(child.id());
5292 }
5293 }
5294
5295 impl WidgetPodMutVisitor for CaptureVisitor {
5296 fn visit(&mut self, child: &mut WidgetPod) {
5297 self.ids.push(child.id());
5298 }
5299 }
5300
5301 let mut child = SingleChild::new(LabelWidget);
5302 let mut measure = measure_ctx(WindowId::new(7), WidgetId::new(8));
5303 let size = child.measure(
5304 &mut measure,
5305 Constraints::tight(sui_core::Size::new(80.0, 24.0)),
5306 );
5307 let mut arrange = ArrangeCtx::new(WindowId::new(7), WidgetId::new(8), DpiInfo::default());
5308 child.arrange(&mut arrange, Rect::new(12.0, 18.0, 80.0, 24.0));
5309
5310 let mut visitor = CaptureVisitor { ids: Vec::new() };
5311 child.visit_children(&mut visitor);
5312 child.visit_children_mut(&mut visitor);
5313
5314 assert_eq!(size, sui_core::Size::new(80.0, 24.0));
5315 assert_eq!(child.child().bounds(), Rect::new(12.0, 18.0, 80.0, 24.0));
5316 assert_eq!(visitor.ids, vec![child.child().id(), child.child().id()]);
5317 }
5318
5319 #[test]
5320 fn widget_children_bulk_paint_and_semantics_delegate_to_all_children() {
5321 let mut children = WidgetChildren::with_capacity(2);
5322 children.push(LabelWidget);
5323 children.push(LabelWidget);
5324
5325 let mut measure = measure_ctx(WindowId::new(9), WidgetId::new(10));
5326 children.measure_child(
5327 0,
5328 &mut measure,
5329 Constraints::tight(sui_core::Size::new(40.0, 18.0)),
5330 );
5331 children.measure_child(
5332 1,
5333 &mut measure,
5334 Constraints::tight(sui_core::Size::new(60.0, 18.0)),
5335 );
5336 let mut arrange = ArrangeCtx::new(WindowId::new(9), WidgetId::new(10), DpiInfo::default());
5337 children.arrange_child(0, &mut arrange, Rect::new(0.0, 0.0, 40.0, 18.0));
5338 children.arrange_child(1, &mut arrange, Rect::new(44.0, 0.0, 60.0, 18.0));
5339
5340 let mut paint = PaintCtx::new(
5341 WindowId::new(9),
5342 WidgetId::new(10),
5343 Rect::new(0.0, 0.0, 120.0, 40.0),
5344 None,
5345 DpiInfo::default(),
5346 Arc::new(TextSystem::new()),
5347 Arc::new(FontRegistry::new()),
5348 Arc::new(ImageRegistry::new()),
5349 );
5350 children.paint(&mut paint);
5351
5352 let mut semantics = SemanticsCtx::new(
5353 WindowId::new(9),
5354 WidgetId::new(10),
5355 WidgetId::new(10),
5356 Rect::new(0.0, 0.0, 120.0, 40.0),
5357 None,
5358 );
5359 children.semantics(&mut semantics);
5360
5361 assert_eq!(children.len(), 2);
5362 assert_eq!(paint.scene().commands().len(), 2);
5363 assert_eq!(semantics.nodes().len(), 2);
5364 }
5365
5366 #[test]
5367 fn keyed_children_preserve_pods_and_update_item_signals() {
5368 let mut children = KeyedChildren::<u64, (u64, String)>::new();
5369 let first = children.reconcile(
5370 [(1, "one".to_string()), (2, "two".to_string())],
5371 |item| item.0,
5372 |_key, _value| LabelWidget,
5373 );
5374 assert_eq!(first.inserted, 2);
5375 let first_ids = children
5376 .iter()
5377 .map(|(key, _, child)| (*key, child.id()))
5378 .collect::<HashMap<_, _>>();
5379
5380 let second = children.reconcile(
5381 [
5382 (2, "two updated".to_string()),
5383 (1, "one".to_string()),
5384 (3, "three".to_string()),
5385 ],
5386 |item| item.0,
5387 |_key, _value| LabelWidget,
5388 );
5389 assert_eq!(second.inserted, 1);
5390 assert_eq!(second.removed, 0);
5391 assert_eq!(second.moved, 2);
5392 assert_eq!(second.updated, 1);
5393 assert_eq!(second.unchanged, 1);
5394
5395 let entries = children
5396 .iter()
5397 .map(|(key, value, child)| (*key, value.get(), child.id()))
5398 .collect::<Vec<_>>();
5399 assert_eq!(
5400 entries.iter().map(|(key, _, _)| *key).collect::<Vec<_>>(),
5401 vec![2, 1, 3]
5402 );
5403 assert_eq!(entries[0].1.1, "two updated");
5404 assert_eq!(entries[0].2, first_ids[&2]);
5405 assert_eq!(entries[1].2, first_ids[&1]);
5406 }
5407
5408 #[test]
5409 fn nested_paint_wrappers_preserve_content_and_clipped_paint_bounds() {
5410 let inner = BoundsWrapper::new(
5411 BoundsLeaf,
5412 Some(Rect::new(0.0, 0.0, 60.0, 60.0)),
5413 Vector::new(0.0, 7.0),
5414 );
5415 let outer = BoundsWrapper::new(
5416 inner,
5417 Some(Rect::new(0.0, 0.0, 100.0, 100.0)),
5418 Vector::new(5.0, 0.0),
5419 );
5420 let mut root = WidgetPod::new(BoundsWrapper::new(outer, None, Vector::ZERO));
5423 let window_id = WindowId::new(17);
5424 let root_id = WidgetId::new(18);
5425 let bounds = Rect::new(0.0, 0.0, 120.0, 100.0);
5426 let mut measure = measure_ctx(window_id, root_id);
5427 root.measure(&mut measure, Constraints::tight(bounds.size));
5428 let mut arrange = ArrangeCtx::new(window_id, root_id, DpiInfo::default());
5429 root.arrange(&mut arrange, bounds);
5430
5431 let mut paint = PaintCtx::new(
5432 window_id,
5433 root_id,
5434 bounds,
5435 None,
5436 DpiInfo::default(),
5437 Arc::new(TextSystem::new()),
5438 Arc::new(FontRegistry::new()),
5439 Arc::new(ImageRegistry::new()),
5440 );
5441 root.paint(&mut paint);
5442
5443 assert_eq!(
5444 paint.scene().content_bounds(),
5445 Some(Rect::new(15.0, 17.0, 80.0, 50.0))
5446 );
5447 assert_eq!(
5448 paint.scene().paint_bounds(),
5449 Some(Rect::new(15.0, 17.0, 50.0, 43.0))
5450 );
5451 assert_eq!(
5452 paint.scene().paint_bounds(),
5453 paint.scene().clone().paint_bounds()
5454 );
5455 }
5456
5457 #[test]
5458 fn paint_ctx_emits_extended_scene_commands() {
5459 let mut paint = PaintCtx::new(
5460 WindowId::new(11),
5461 WidgetId::new(12),
5462 Rect::new(0.0, 0.0, 120.0, 60.0),
5463 None,
5464 DpiInfo::default(),
5465 Arc::new(TextSystem::new()),
5466 Arc::new(FontRegistry::new()),
5467 Arc::new(ImageRegistry::new()),
5468 );
5469
5470 let mut path = sui_core::Path::builder();
5471 path.move_to(Point::new(4.0, 5.0))
5472 .line_to(Point::new(24.0, 5.0))
5473 .line_to(Point::new(14.0, 15.0))
5474 .close();
5475 paint.stroke(path.build(), Color::WHITE, StrokeStyle::new(2.0));
5476 paint.draw_text(
5477 Rect::new(8.0, 10.0, 80.0, 20.0),
5478 "hello",
5479 TextStyle::new(Color::BLACK),
5480 );
5481 paint.draw_image(
5482 Rect::new(0.0, 0.0, 16.0, 16.0),
5483 sui_core::ImageHandle::new(3),
5484 );
5485 paint.push_clip(sui_core::Path::circle(Point::new(12.0, 12.0), 8.0));
5486 paint.push_clip_rect(Rect::new(0.0, 0.0, 50.0, 50.0));
5487 paint.translate(Vector::new(3.0, 4.0));
5488 paint.pop_transform();
5489 paint.pop_clip();
5490 paint.pop_clip();
5491
5492 assert!(matches!(
5493 paint.scene().commands()[0],
5494 SceneCommand::StrokePath { .. }
5495 ));
5496 assert!(matches!(
5497 paint.scene().commands()[1],
5498 SceneCommand::DrawShapedText(_)
5499 ));
5500 assert!(matches!(
5501 paint.scene().commands()[2],
5502 SceneCommand::DrawImage { .. }
5503 ));
5504 assert!(matches!(
5505 paint.scene().commands()[3],
5506 SceneCommand::PushClipPath { .. }
5507 ));
5508 assert!(matches!(
5509 paint.scene().commands()[4],
5510 SceneCommand::PushClip { .. }
5511 ));
5512 assert!(matches!(
5513 paint.scene().commands()[5],
5514 SceneCommand::PushTransform { .. }
5515 ));
5516 assert!(matches!(
5517 paint.scene().commands()[6],
5518 SceneCommand::PopTransform
5519 ));
5520 assert!(matches!(paint.scene().commands()[7], SceneCommand::PopClip));
5521 assert!(matches!(paint.scene().commands()[8], SceneCommand::PopClip));
5522 }
5523
5524 #[test]
5525 fn stable_text_run_handle_ignores_color_and_includes_layout_style() {
5526 let run = TextRun {
5527 rect: Rect::new(8.0, 10.0, 80.0, 20.0),
5528 text: "hello".to_string(),
5529 style: TextStyle::new(Color::BLACK),
5530 };
5531 let mut recolored = run.clone();
5532 recolored.style.color = Color::WHITE;
5533 let mut bold = run.clone();
5534 bold.style.weight = FontWeight::BOLD;
5535
5536 assert_eq!(
5537 super::stable_text_run_handle(&run),
5538 super::stable_text_run_handle(&recolored)
5539 );
5540 assert_ne!(
5541 super::stable_text_run_handle(&run),
5542 super::stable_text_run_handle(&bold)
5543 );
5544 }
5545
5546 #[test]
5547 fn paint_ctx_draw_text_uses_color_override_for_paint_color() {
5548 let text_system = Arc::new(TextSystem::new());
5549 let mut paint = PaintCtx::new(
5550 WindowId::new(12),
5551 WidgetId::new(13),
5552 Rect::new(0.0, 0.0, 120.0, 60.0),
5553 None,
5554 DpiInfo::default(),
5555 Arc::clone(&text_system),
5556 Arc::new(FontRegistry::new()),
5557 Arc::new(ImageRegistry::new()),
5558 );
5559 let paint_color = Color::BLACK;
5560 paint.draw_text(
5561 Rect::new(8.0, 10.0, 80.0, 20.0),
5562 "hello",
5563 TextStyle::new(paint_color),
5564 );
5565
5566 let SceneCommand::DrawShapedText(text) = &paint.scene().commands()[0] else {
5567 panic!("draw_text should emit shaped text when layout succeeds");
5568 };
5569 assert_eq!(text.color_override, Some(paint_color));
5570
5571 let registry = text_system.text_layout_registry();
5572 let layout = text
5573 .resolve(registry.as_ref())
5574 .expect("drawn shaped text should resolve from the registry");
5575 assert_eq!(layout.style().color, Color::WHITE);
5576 }
5577
5578 #[test]
5579 fn paint_ctx_draw_persistent_text_layout_reinserts_pruned_layout() {
5580 let text_system = Arc::new(TextSystem::new());
5581 let layout = text_system
5582 .shape_text_persistent(
5583 None,
5584 "held",
5585 Size::new(80.0, 20.0),
5586 TextStyle::new(Color::WHITE),
5587 &FontRegistry::new(),
5588 )
5589 .unwrap();
5590 text_system.retain_persistent_layouts(&std::collections::HashSet::new());
5591 assert!(!text_system.text_layout_registry().contains(layout.handle()));
5592
5593 let mut paint = PaintCtx::new(
5594 WindowId::new(12),
5595 WidgetId::new(13),
5596 Rect::new(0.0, 0.0, 120.0, 60.0),
5597 None,
5598 DpiInfo::default(),
5599 Arc::clone(&text_system),
5600 Arc::new(FontRegistry::new()),
5601 Arc::new(ImageRegistry::new()),
5602 );
5603 paint.draw_persistent_text_layout(Point::ZERO, &layout);
5604
5605 assert!(text_system.text_layout_registry().contains(layout.handle()));
5606 assert!(matches!(
5607 paint.scene().commands()[0],
5608 SceneCommand::DrawShapedText(_)
5609 ));
5610 }
5611
5612 #[test]
5613 fn text_layout_shapes_in_measure_and_paints_as_shaped_scene_output() {
5614 let layout = measure_ctx(WindowId::new(13), WidgetId::new(14))
5615 .layout()
5616 .shape_text(
5617 "hello",
5618 sui_core::Size::new(80.0, 20.0),
5619 TextStyle::new(Color::BLACK),
5620 )
5621 .unwrap();
5622
5623 let mut paint = PaintCtx::new(
5624 WindowId::new(13),
5625 WidgetId::new(14),
5626 Rect::new(0.0, 0.0, 120.0, 60.0),
5627 None,
5628 DpiInfo::default(),
5629 Arc::new(TextSystem::new()),
5630 Arc::new(FontRegistry::new()),
5631 Arc::new(ImageRegistry::new()),
5632 );
5633 let origin = Point::new(8.0, 10.0);
5634 paint.draw_text_layout(origin, &layout);
5635 paint.set_ime_composition_rect(layout.caret_rect(3).translate(origin.to_vector()));
5636
5637 assert!(matches!(
5638 paint.scene().commands()[0],
5639 SceneCommand::DrawShapedText(_)
5640 ));
5641 assert!(paint.ime_composition_rect().is_some());
5642 assert!(!layout.selection_rects(1..4).is_empty());
5643 }
5644}