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