1#![allow(clippy::too_many_arguments, clippy::type_complexity)]
2
3use std::{
4 collections::{HashMap, HashSet, hash_map::DefaultHasher},
5 hash::{Hash, Hasher},
6 rc::Rc,
7 sync::{
8 Arc,
9 atomic::{AtomicU64, Ordering},
10 },
11};
12
13use crate::diagnostics::{WidgetTimingPhase, record_widget_timing};
14
15use sui_core::{
16 AsyncWakeToken, Clipboard, Color, DpiInfo, DragPayload, DragScopeId, DragSessionId, DropEffect,
17 Event, ImageHandle, InvalidationKind, InvalidationRequest, InvalidationTarget, Path, Point,
18 Rect, SemanticsNode, Size, TimerToken, Transform, Vector, WidgetId, WindowId,
19};
20use sui_layout::{Constraints, LayoutContext};
21use sui_scene::{
22 Border, Brush, ImageRegistry, ImageSource, LayerCompositionMode, LayerProperties,
23 RegisteredExternalImage, RegisteredImage, Scene, SceneCommand, SceneLayer,
24 SceneLayerDescriptor, SceneLayerId, ShadowParams, StrokeStyle, TextRenderPolicy, WidgetShader,
25};
26use sui_text::{
27 FontRegistry, PersistentTextLayout, ShapedText, ShapedTextWindow, TextLayout, TextLayoutHandle,
28 TextLayoutRequest, TextMeasurement, TextRun, TextStyle, TextSystem,
29};
30use web_time::Instant;
31
32static NEXT_WIDGET_ID: AtomicU64 = AtomicU64::new(1);
33static NEXT_TIMER_TOKEN: AtomicU64 = AtomicU64::new(1);
34static NEXT_ASYNC_WAKE_TOKEN: AtomicU64 = AtomicU64::new(1);
35static NEXT_DRAG_SESSION_ID: AtomicU64 = AtomicU64::new(1);
36const WIDGET_IMAGE_HANDLE_NAMESPACE: u64 = 1 << 63;
37
38#[derive(Debug, Clone, Copy, PartialEq, Eq)]
39pub enum EventPhase {
40 Capture,
41 Target,
42 Bubble,
43}
44
45pub trait WidgetPodVisitor {
46 fn visit(&mut self, child: &WidgetPod);
47}
48
49pub trait WidgetPodMutVisitor {
50 fn visit(&mut self, child: &mut WidgetPod);
51}
52
53pub trait Widget {
54 fn event(&mut self, _ctx: &mut EventCtx, _event: &Event) {}
55
56 fn debug_name(&self) -> &'static str {
57 std::any::type_name::<Self>()
58 }
59
60 fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
61 constraints.max
62 }
63
64 fn arrange(&mut self, _ctx: &mut ArrangeCtx, _bounds: Rect) {}
65
66 fn paint(&self, _ctx: &mut PaintCtx) {}
67
68 fn layer_options(&self) -> LayerOptions {
69 LayerOptions::default()
70 }
71
72 fn layer_properties(&self) -> LayerProperties {
73 LayerProperties::default()
74 }
75
76 fn stack_host_options(&self) -> Option<StackHostOptions> {
77 None
78 }
79
80 fn stack_surface_options(&self) -> Option<StackSurfaceOptions> {
81 None
82 }
83
84 fn semantics(&self, _ctx: &mut SemanticsCtx) {}
85
86 fn accepts_focus(&self) -> bool {
87 false
88 }
89
90 fn focus_changed(&mut self, _ctx: &mut EventCtx, _focused: bool) {}
91
92 fn visit_children(&self, _visitor: &mut dyn WidgetPodVisitor) {}
100
101 fn visit_children_mut(&mut self, _visitor: &mut dyn WidgetPodMutVisitor) {}
107}
108
109#[derive(Debug, Clone, Copy, PartialEq, Eq)]
110pub enum PaintBoundaryMode {
111 Flat,
112 Explicit,
113}
114
115#[derive(Debug, Clone, Copy, PartialEq, Eq)]
116pub struct LayerOptions {
117 pub paint_boundary: PaintBoundaryMode,
118 pub composition_mode: LayerCompositionMode,
119}
120
121impl LayerOptions {
122 pub const fn emits_layer(self) -> bool {
123 matches!(self.paint_boundary, PaintBoundaryMode::Explicit)
124 }
125}
126
127#[derive(Debug, Clone, Copy, PartialEq, Eq)]
128pub enum StackOrderPolicy {
129 Stable,
130 FocusFronted,
131}
132
133#[derive(Debug, Clone, Copy, PartialEq, Eq)]
134pub struct StackHostOptions {
135 pub order_policy: StackOrderPolicy,
136}
137
138impl Default for StackHostOptions {
139 fn default() -> Self {
140 Self {
141 order_policy: StackOrderPolicy::Stable,
142 }
143 }
144}
145
146#[derive(Debug, Clone, Copy, PartialEq, Eq)]
147pub struct StackSurfaceOptions {
148 pub dynamic_ordering: bool,
149 pub transient: bool,
150 pub hit_test: bool,
151}
152
153impl Default for StackSurfaceOptions {
154 fn default() -> Self {
155 Self {
156 dynamic_ordering: true,
157 transient: false,
158 hit_test: true,
159 }
160 }
161}
162
163impl Default for LayerOptions {
164 fn default() -> Self {
165 Self {
166 paint_boundary: PaintBoundaryMode::Flat,
167 composition_mode: LayerCompositionMode::Normal,
168 }
169 }
170}
171
172pub struct SingleChild {
173 child: WidgetPod,
174}
175
176impl SingleChild {
177 pub fn new<W>(child: W) -> Self
178 where
179 W: Widget + 'static,
180 {
181 Self::from_pod(WidgetPod::new(child))
182 }
183
184 pub fn new_with_paint_boundary<W>(child: W) -> Self
190 where
191 W: Widget + 'static,
192 {
193 let mut child = WidgetPod::new(child);
194 child.force_paint_boundary = true;
195 Self::from_pod(child)
196 }
197
198 pub fn with_paint_boundary(mut self) -> Self {
201 self.child.force_paint_boundary = true;
202 self
203 }
204
205 pub fn from_pod(child: WidgetPod) -> Self {
206 Self { child }
207 }
208
209 pub fn child(&self) -> &WidgetPod {
210 &self.child
211 }
212
213 pub fn child_mut(&mut self) -> &mut WidgetPod {
214 &mut self.child
215 }
216
217 pub fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
218 self.child.measure(ctx, constraints)
219 }
220
221 pub fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
222 self.child.arrange(ctx, bounds);
223 }
224
225 pub fn set_bounds(&mut self, bounds: Rect) {
226 self.child.set_bounds(bounds);
227 }
228
229 pub fn paint(&self, ctx: &mut PaintCtx) {
230 self.child.paint(ctx);
231 }
232
233 pub fn semantics(&self, ctx: &mut SemanticsCtx) {
234 self.child.semantics(ctx);
235 }
236
237 pub fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
238 visitor.visit(&self.child);
239 }
240
241 pub fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
242 visitor.visit(&mut self.child);
243 }
244}
245
246#[derive(Default)]
247pub struct WidgetChildren {
248 children: Vec<WidgetPod>,
249}
250
251impl WidgetChildren {
252 pub fn new() -> Self {
253 Self::default()
254 }
255
256 pub fn with_capacity(capacity: usize) -> Self {
257 Self {
258 children: Vec::with_capacity(capacity),
259 }
260 }
261
262 pub fn push<W>(&mut self, child: W)
263 where
264 W: Widget + 'static,
265 {
266 self.push_pod(WidgetPod::new(child));
267 }
268
269 pub fn push_pod(&mut self, child: WidgetPod) {
270 self.children.push(child);
271 }
272
273 pub fn len(&self) -> usize {
274 self.children.len()
275 }
276
277 pub fn is_empty(&self) -> bool {
278 self.children.is_empty()
279 }
280
281 pub fn as_slice(&self) -> &[WidgetPod] {
282 &self.children
283 }
284
285 pub fn as_mut_slice(&mut self) -> &mut [WidgetPod] {
286 &mut self.children
287 }
288
289 pub fn measure_child(
290 &mut self,
291 index: usize,
292 ctx: &mut MeasureCtx,
293 constraints: Constraints,
294 ) -> Size {
295 self.children[index].measure(ctx, constraints)
296 }
297
298 pub fn arrange_child(&mut self, index: usize, ctx: &mut ArrangeCtx, bounds: Rect) {
299 self.children[index].arrange(ctx, bounds);
300 }
301
302 pub fn paint(&self, ctx: &mut PaintCtx) {
303 for child in &self.children {
304 child.paint(ctx);
305 }
306 }
307
308 pub fn semantics(&self, ctx: &mut SemanticsCtx) {
309 for child in &self.children {
310 child.semantics(ctx);
311 }
312 }
313
314 pub fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
315 for child in &self.children {
316 visitor.visit(child);
317 }
318 }
319
320 pub fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
321 for child in &mut self.children {
322 visitor.visit(child);
323 }
324 }
325}
326
327pub struct WidgetPod {
335 id: WidgetId,
336 layout_state: LayoutState,
337 force_paint_boundary: bool,
338 widget: Box<dyn Widget>,
339}
340
341#[derive(Debug, Clone, Copy, PartialEq)]
342struct LayoutState {
343 measured_size: Size,
344 arranged_bounds: Rect,
345 last_constraints: Constraints,
346 measure_valid: bool,
347 arrange_valid: bool,
348}
349
350impl Default for LayoutState {
351 fn default() -> Self {
352 Self {
353 measured_size: Size::ZERO,
354 arranged_bounds: Rect::ZERO,
355 last_constraints: Constraints::default(),
356 measure_valid: false,
357 arrange_valid: false,
358 }
359 }
360}
361
362impl WidgetPod {
363 pub fn new<W>(widget: W) -> Self
364 where
365 W: Widget + 'static,
366 {
367 Self {
368 id: WidgetId::new(NEXT_WIDGET_ID.fetch_add(1, Ordering::Relaxed)),
369 layout_state: LayoutState::default(),
370 force_paint_boundary: false,
371 widget: Box::new(widget),
372 }
373 }
374
375 pub const fn id(&self) -> WidgetId {
376 self.id
377 }
378
379 pub const fn bounds(&self) -> Rect {
380 self.layout_state.arranged_bounds
381 }
382
383 pub const fn measured_size(&self) -> Size {
384 self.layout_state.measured_size
385 }
386
387 pub fn set_bounds(&mut self, bounds: Rect) {
388 let delta = bounds.origin - self.layout_state.arranged_bounds.origin;
389 self.layout_state.arranged_bounds = bounds;
390 self.layout_state.measured_size = bounds.size;
391 self.layout_state.arrange_valid = true;
392 self.translate_descendants(delta);
393 }
394
395 pub fn measure(&mut self, parent_ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
396 let force = parent_ctx.child_force();
407 let must_remeasure = force || parent_ctx.scope().must_remeasure(self.id);
408 if !must_remeasure
409 && self.layout_state.measure_valid
410 && self.layout_state.last_constraints == constraints
411 {
412 return self.layout_state.measured_size;
413 }
414
415 let origin = self.layout_state.arranged_bounds.origin;
416 let mut child_ctx = parent_ctx.child(self.id, self.layout_state.arranged_bounds, force);
417 let started = Instant::now();
418 let size = self.widget.measure(&mut child_ctx, constraints);
419 record_widget_timing(
420 self.id,
421 self.widget.debug_name(),
422 WidgetTimingPhase::Measure,
423 started.elapsed(),
424 );
425 self.layout_state.measured_size = size;
426 self.layout_state.last_constraints = constraints;
427 self.layout_state.measure_valid = true;
428 self.layout_state.arranged_bounds = Rect::from_origin_size(origin, size);
429 parent_ctx.extend_invalidations(child_ctx.take_invalidations());
430 parent_ctx.extend_wake_requests(child_ctx.take_wake_requests());
431 size
432 }
433
434 pub fn arrange(&mut self, parent_ctx: &mut ArrangeCtx, bounds: Rect) {
435 let delta = bounds.origin - self.layout_state.arranged_bounds.origin;
436 self.layout_state.arranged_bounds = bounds;
437 self.layout_state.arrange_valid = true;
438 self.translate_descendants(delta);
439
440 let mut child_ctx = ArrangeCtx::new(parent_ctx.window_id(), self.id, parent_ctx.dpi());
441 let started = Instant::now();
442 self.widget.arrange(&mut child_ctx, bounds);
443 record_widget_timing(
444 self.id,
445 self.widget.debug_name(),
446 WidgetTimingPhase::Arrange,
447 started.elapsed(),
448 );
449 parent_ctx.extend_invalidations(child_ctx.take_invalidations());
450 }
451
452 pub fn paint(&self, parent_ctx: &mut PaintCtx) {
453 let mut child_ctx = PaintCtx::new(
454 parent_ctx.window_id(),
455 self.id,
456 self.layout_state.arranged_bounds,
457 parent_ctx.focused_widget_id(),
458 parent_ctx.dpi(),
459 Arc::clone(&parent_ctx.text_system),
460 Arc::clone(&parent_ctx.font_registry),
461 Arc::clone(&parent_ctx.image_registry),
462 );
463 let started = Instant::now();
464 self.widget.paint(&mut child_ctx);
465 record_widget_timing(
466 self.id,
467 self.widget.debug_name(),
468 WidgetTimingPhase::Paint,
469 started.elapsed(),
470 );
471
472 let (scene, images, widget_paint_bounds, invalidations, ime_composition_rect) =
473 child_ctx.into_parts();
474 let paint_bounds = scene
475 .paint_bounds()
476 .unwrap_or(self.layout_state.arranged_bounds);
477 parent_ctx.record_widget_paint_bounds(self.id, paint_bounds);
478 if self.current_layer_options().emits_layer() {
479 parent_ctx.push_layer(self.build_layer_descriptor(&scene), scene);
480 } else {
481 parent_ctx.append_scene(scene);
482 }
483 parent_ctx.extend_widget_paint_bounds(widget_paint_bounds);
484 parent_ctx.extend_images(images);
485 parent_ctx.extend_invalidations(invalidations);
486 parent_ctx.extend_ime_composition_rect(ime_composition_rect);
487 }
488
489 pub(crate) fn paint_layer_contents_for(
490 &mut self,
491 target: WidgetId,
492 parent_ctx: &mut PaintCtx,
493 ) -> bool {
494 self.find_mut(target, &mut |pod| {
495 let started = Instant::now();
496 pod.widget.paint(parent_ctx);
497 record_widget_timing(
498 pod.id,
499 pod.widget.debug_name(),
500 WidgetTimingPhase::Paint,
501 started.elapsed(),
502 );
503 let paint_bounds = parent_ctx
504 .scene()
505 .paint_bounds()
506 .unwrap_or(pod.layout_state.arranged_bounds);
507 parent_ctx.record_widget_paint_bounds(pod.id, paint_bounds);
508 })
509 .is_some()
510 }
511
512 pub(crate) fn layer_descriptor_for(
513 &mut self,
514 target: WidgetId,
515 scene: &Scene,
516 ) -> Option<SceneLayerDescriptor> {
517 self.find_mut(target, &mut |pod| pod.build_layer_descriptor(scene))
518 }
519
520 pub fn semantics(&self, parent_ctx: &mut SemanticsCtx) {
521 let mut child_ctx = SemanticsCtx::new(
522 parent_ctx.window_id(),
523 self.id,
524 parent_ctx.root_widget_id(),
525 self.layout_state.arranged_bounds,
526 parent_ctx.focused_widget_id(),
527 );
528 let started = Instant::now();
529 self.widget.semantics(&mut child_ctx);
530 record_widget_timing(
531 self.id,
532 self.widget.debug_name(),
533 WidgetTimingPhase::Semantics,
534 started.elapsed(),
535 );
536 parent_ctx.extend_nodes(child_ctx.into_nodes());
537 }
538
539 pub(crate) fn accepts_focus(&self) -> bool {
540 self.widget.accepts_focus()
541 }
542
543 pub fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
549 self.widget.visit_children(visitor);
550 }
551
552 pub(crate) fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
553 self.widget.visit_children_mut(visitor);
554 }
555
556 #[allow(clippy::too_many_arguments)]
557 pub(crate) fn dispatch_event_for_path(
558 &mut self,
559 path: &[WidgetId],
560 window_id: WindowId,
561 dpi_info: DpiInfo,
562 current_time: f64,
563 phase: EventPhase,
564 focused_widget: Option<WidgetId>,
565 clipboard: &Clipboard,
566 event: &Event,
567 ) -> Option<EventDispatch> {
568 self.find_mut_path(path, &mut |pod| {
569 pod.dispatch_event(
570 window_id,
571 dpi_info,
572 current_time,
573 phase,
574 focused_widget,
575 clipboard,
576 event,
577 )
578 })
579 }
580
581 #[allow(clippy::too_many_arguments)]
582 pub(crate) fn dispatch_event_for(
583 &mut self,
584 target: WidgetId,
585 window_id: WindowId,
586 dpi_info: DpiInfo,
587 current_time: f64,
588 phase: EventPhase,
589 focused_widget: Option<WidgetId>,
590 clipboard: &Clipboard,
591 event: &Event,
592 ) -> Option<EventDispatch> {
593 self.find_mut(target, &mut |pod| {
594 pod.dispatch_event(
595 window_id,
596 dpi_info,
597 current_time,
598 phase,
599 focused_widget,
600 clipboard,
601 event,
602 )
603 })
604 }
605
606 #[allow(clippy::too_many_arguments)]
607 pub(crate) fn notify_focus_change_for(
608 &mut self,
609 target: WidgetId,
610 window_id: WindowId,
611 dpi_info: DpiInfo,
612 current_time: f64,
613 focused_widget: Option<WidgetId>,
614 clipboard: &Clipboard,
615 focused: bool,
616 ) -> Option<EventDispatch> {
617 self.find_mut(target, &mut |pod| {
618 pod.focus_changed(
619 window_id,
620 dpi_info,
621 current_time,
622 focused_widget,
623 clipboard,
624 focused,
625 )
626 })
627 }
628
629 #[allow(clippy::too_many_arguments)]
630 pub(crate) fn notify_focus_change_for_path(
631 &mut self,
632 path: &[WidgetId],
633 window_id: WindowId,
634 dpi_info: DpiInfo,
635 current_time: f64,
636 focused_widget: Option<WidgetId>,
637 clipboard: &Clipboard,
638 focused: bool,
639 ) -> Option<EventDispatch> {
640 self.find_mut_path(path, &mut |pod| {
641 pod.focus_changed(
642 window_id,
643 dpi_info,
644 current_time,
645 focused_widget,
646 clipboard,
647 focused,
648 )
649 })
650 }
651
652 #[allow(clippy::too_many_arguments)]
653 fn dispatch_event(
654 &mut self,
655 window_id: WindowId,
656 dpi_info: DpiInfo,
657 current_time: f64,
658 phase: EventPhase,
659 focused_widget: Option<WidgetId>,
660 clipboard: &Clipboard,
661 event: &Event,
662 ) -> EventDispatch {
663 let mut ctx = EventCtx::new(
664 window_id,
665 self.id,
666 self.layout_state.arranged_bounds,
667 dpi_info,
668 current_time,
669 phase,
670 focused_widget,
671 clipboard.clone(),
672 );
673 self.widget.event(&mut ctx, event);
674 EventDispatch {
675 handled: ctx.is_handled(),
676 invalidations: ctx.take_invalidations(),
677 focus_request: ctx.take_focus_request(),
678 wake_requests: ctx.take_wake_requests(),
679 pointer_capture_requests: ctx.take_pointer_capture_requests(),
680 drag_requests: ctx.take_drag_requests(),
681 drop_acceptances: ctx.take_drop_acceptances(),
682 posted_events: ctx.take_posted_events(),
683 }
684 }
685
686 fn focus_changed(
687 &mut self,
688 window_id: WindowId,
689 dpi_info: DpiInfo,
690 current_time: f64,
691 focused_widget: Option<WidgetId>,
692 clipboard: &Clipboard,
693 focused: bool,
694 ) -> EventDispatch {
695 let mut ctx = EventCtx::new(
696 window_id,
697 self.id,
698 self.layout_state.arranged_bounds,
699 dpi_info,
700 current_time,
701 EventPhase::Target,
702 focused_widget,
703 clipboard.clone(),
704 );
705 self.widget.focus_changed(&mut ctx, focused);
706 EventDispatch {
707 handled: ctx.is_handled(),
708 invalidations: ctx.take_invalidations(),
709 focus_request: ctx.take_focus_request(),
710 wake_requests: ctx.take_wake_requests(),
711 pointer_capture_requests: ctx.take_pointer_capture_requests(),
712 drag_requests: ctx.take_drag_requests(),
713 drop_acceptances: ctx.take_drop_acceptances(),
714 posted_events: ctx.take_posted_events(),
715 }
716 }
717
718 fn find_mut<R, F>(&mut self, target: WidgetId, f: &mut F) -> Option<R>
719 where
720 F: FnMut(&mut WidgetPod) -> R,
721 {
722 if self.id == target {
723 return Some(f(self));
724 }
725
726 let mut result = None;
727 let mut visitor = FindMutVisitor {
728 target,
729 callback: f,
730 result: &mut result,
731 };
732 self.visit_children_mut(&mut visitor);
733 result
734 }
735
736 fn find_mut_path<R, F>(&mut self, path: &[WidgetId], f: &mut F) -> Option<R>
737 where
738 F: FnMut(&mut WidgetPod) -> R,
739 {
740 let (¤t, rest) = path.split_first()?;
741 if current != self.id {
742 return None;
743 }
744
745 if rest.is_empty() {
746 return Some(f(self));
747 }
748
749 let mut result = None;
750 let mut visitor = FindPathMutVisitor {
751 path: rest,
752 callback: f,
753 result: &mut result,
754 };
755 self.visit_children_mut(&mut visitor);
756 result
757 }
758
759 fn translate_descendants(&mut self, delta: Vector) {
760 if delta == Vector::ZERO {
761 return;
762 }
763
764 let mut visitor = TranslateVisitor { delta };
765 self.visit_children_mut(&mut visitor);
766 }
767
768 fn translate_subtree(&mut self, delta: Vector) {
769 if delta == Vector::ZERO {
770 return;
771 }
772
773 self.layout_state.arranged_bounds = self.layout_state.arranged_bounds.translate(delta);
774 self.translate_descendants(delta);
775 }
776
777 pub(crate) fn build_layer_descriptor(&self, scene: &Scene) -> SceneLayerDescriptor {
778 let options = self.current_layer_options();
779 SceneLayerDescriptor::new(
780 SceneLayerId::from_widget(self.id),
781 self.id,
782 self.layout_state.arranged_bounds,
783 )
784 .with_content_bounds(
785 scene
786 .content_bounds()
787 .unwrap_or(self.layout_state.arranged_bounds),
788 )
789 .with_paint_bounds(
790 scene
791 .paint_bounds()
792 .unwrap_or(self.layout_state.arranged_bounds),
793 )
794 .with_properties(self.current_layer_properties())
795 .with_composition_mode(options.composition_mode)
796 }
797
798 pub(crate) fn current_layer_options(&self) -> LayerOptions {
799 let mut options = self.widget.layer_options();
800 if self.force_paint_boundary {
801 options.paint_boundary = PaintBoundaryMode::Explicit;
802 }
803 options
804 }
805
806 pub(crate) fn current_layer_properties(&self) -> LayerProperties {
807 self.widget.layer_properties()
808 }
809
810 pub(crate) fn current_paint_boundary_mode(&self) -> PaintBoundaryMode {
811 self.current_layer_options().paint_boundary
812 }
813
814 pub(crate) fn current_stack_host_options(&self) -> Option<StackHostOptions> {
815 self.widget.stack_host_options()
816 }
817
818 pub(crate) fn current_stack_surface_options(&self) -> Option<StackSurfaceOptions> {
819 self.widget.stack_surface_options()
820 }
821
822 pub(crate) fn layer_composition_mode_for(
823 &mut self,
824 target: WidgetId,
825 ) -> Option<LayerCompositionMode> {
826 self.find_mut(target, &mut |pod| {
827 pod.current_layer_options().composition_mode
828 })
829 }
830}
831
832struct TranslateVisitor {
833 delta: Vector,
834}
835
836impl WidgetPodMutVisitor for TranslateVisitor {
837 fn visit(&mut self, child: &mut WidgetPod) {
838 child.translate_subtree(self.delta);
839 }
840}
841
842struct FindMutVisitor<'a, F, R>
843where
844 F: FnMut(&mut WidgetPod) -> R,
845{
846 target: WidgetId,
847 callback: &'a mut F,
848 result: &'a mut Option<R>,
849}
850
851impl<F, R> WidgetPodMutVisitor for FindMutVisitor<'_, F, R>
852where
853 F: FnMut(&mut WidgetPod) -> R,
854{
855 fn visit(&mut self, child: &mut WidgetPod) {
856 if self.result.is_none() {
857 *self.result = child.find_mut(self.target, self.callback);
858 }
859 }
860}
861
862struct FindPathMutVisitor<'a, F, R>
863where
864 F: FnMut(&mut WidgetPod) -> R,
865{
866 path: &'a [WidgetId],
867 callback: &'a mut F,
868 result: &'a mut Option<R>,
869}
870
871impl<F, R> WidgetPodMutVisitor for FindPathMutVisitor<'_, F, R>
872where
873 F: FnMut(&mut WidgetPod) -> R,
874{
875 fn visit(&mut self, child: &mut WidgetPod) {
876 if self.result.is_none() && self.path.first().copied() == Some(child.id) {
877 *self.result = child.find_mut_path(self.path, self.callback);
878 }
879 }
880}
881
882#[derive(Debug, Clone, Copy, PartialEq, Eq)]
883pub(crate) enum FocusRequest {
884 Focus(WidgetId),
885 Clear,
886}
887
888#[derive(Debug, Clone, Copy, PartialEq)]
889pub(crate) enum WakeRequest {
890 ScheduleTimer {
891 token: TimerToken,
892 deadline: f64,
893 target: WidgetId,
894 },
895 CancelTimer {
896 token: TimerToken,
897 },
898 RegisterAsync {
899 token: AsyncWakeToken,
900 target: WidgetId,
901 },
902 UnregisterAsync {
903 token: AsyncWakeToken,
904 },
905 RequestAnimationFrame {
906 target: WidgetId,
907 },
908}
909
910#[derive(Debug, Clone, Copy, PartialEq, Eq)]
911pub(crate) enum PointerCaptureRequest {
912 Capture { pointer_id: u64, target: WidgetId },
913 Release { pointer_id: u64 },
914}
915
916#[derive(Debug, Clone)]
917pub(crate) struct BeginDragRequest {
918 pub session_id: DragSessionId,
919 pub scope_id: DragScopeId,
920 pub pointer_id: u64,
921 pub source: WidgetId,
922 pub position: Point,
923 pub payload: DragPayload,
924 pub allowed_effect: DropEffect,
925 pub preview_label: Option<String>,
926}
927
928#[derive(Debug, Clone)]
929pub(crate) enum DragRequest {
930 Begin(BeginDragRequest),
931}
932
933#[derive(Debug, Clone, Copy, PartialEq, Eq)]
934pub(crate) struct DropAcceptanceRequest {
935 pub target: WidgetId,
936 pub effect: DropEffect,
937}
938
939#[derive(Debug, Clone)]
942pub(crate) struct PostedEventRequest {
943 pub target: WidgetId,
944 pub event: Event,
945}
946
947#[derive(Debug, Clone)]
948pub(crate) struct EventDispatch {
949 pub handled: bool,
950 pub invalidations: Vec<InvalidationRequest>,
951 pub focus_request: Option<FocusRequest>,
952 pub wake_requests: Vec<WakeRequest>,
953 pub pointer_capture_requests: Vec<PointerCaptureRequest>,
954 pub drag_requests: Vec<DragRequest>,
955 pub drop_acceptances: Vec<DropAcceptanceRequest>,
956 pub posted_events: Vec<PostedEventRequest>,
957}
958
959#[derive(Debug, Clone)]
960pub struct EventCtx {
961 window_id: WindowId,
962 widget_id: WidgetId,
963 bounds: Rect,
964 dpi_info: DpiInfo,
965 current_time: f64,
966 phase: EventPhase,
967 focused_widget_id: Option<WidgetId>,
968 clipboard: Clipboard,
969 handled: bool,
970 invalidations: Vec<InvalidationRequest>,
971 focus_request: Option<FocusRequest>,
972 wake_requests: Vec<WakeRequest>,
973 pointer_capture_requests: Vec<PointerCaptureRequest>,
974 drag_requests: Vec<DragRequest>,
975 drop_acceptances: Vec<DropAcceptanceRequest>,
976 posted_events: Vec<PostedEventRequest>,
977}
978
979impl EventCtx {
980 #[allow(clippy::too_many_arguments)]
981 pub(crate) fn new(
982 window_id: WindowId,
983 widget_id: WidgetId,
984 bounds: Rect,
985 dpi_info: DpiInfo,
986 current_time: f64,
987 phase: EventPhase,
988 focused_widget_id: Option<WidgetId>,
989 clipboard: Clipboard,
990 ) -> Self {
991 Self {
992 window_id,
993 widget_id,
994 bounds,
995 dpi_info,
996 current_time,
997 phase,
998 focused_widget_id,
999 clipboard,
1000 handled: false,
1001 invalidations: Vec::new(),
1002 focus_request: None,
1003 wake_requests: Vec::new(),
1004 pointer_capture_requests: Vec::new(),
1005 drag_requests: Vec::new(),
1006 drop_acceptances: Vec::new(),
1007 posted_events: Vec::new(),
1008 }
1009 }
1010
1011 pub const fn window_id(&self) -> WindowId {
1012 self.window_id
1013 }
1014
1015 pub const fn widget_id(&self) -> WidgetId {
1016 self.widget_id
1017 }
1018
1019 pub const fn bounds(&self) -> Rect {
1020 self.bounds
1021 }
1022
1023 pub const fn dpi(&self) -> DpiInfo {
1024 self.dpi_info
1025 }
1026
1027 pub const fn current_time(&self) -> f64 {
1028 self.current_time
1029 }
1030
1031 pub const fn phase(&self) -> EventPhase {
1032 self.phase
1033 }
1034
1035 pub const fn focused_widget_id(&self) -> Option<WidgetId> {
1036 self.focused_widget_id
1037 }
1038
1039 pub fn is_focused(&self) -> bool {
1040 self.focused_widget_id == Some(self.widget_id)
1041 }
1042
1043 pub const fn is_handled(&self) -> bool {
1044 self.handled
1045 }
1046
1047 pub fn set_handled(&mut self) {
1048 self.handled = true;
1049 }
1050
1051 pub fn clipboard(&self) -> &Clipboard {
1055 &self.clipboard
1056 }
1057
1058 pub fn clipboard_text(&self) -> Option<String> {
1059 self.clipboard.text()
1060 }
1061
1062 pub fn set_clipboard_text(&mut self, text: impl AsRef<str>) {
1063 self.clipboard.set_text(text);
1064 }
1065
1066 pub fn post_event(&mut self, target: WidgetId, event: Event) {
1071 self.posted_events
1072 .push(PostedEventRequest { target, event });
1073 }
1074
1075 pub fn request_focus(&mut self) {
1076 self.focus_request = Some(FocusRequest::Focus(self.widget_id));
1077 }
1078
1079 pub fn clear_focus(&mut self) {
1080 self.focus_request = Some(FocusRequest::Clear);
1081 }
1082
1083 pub fn schedule_timer_at(&mut self, deadline: f64) -> TimerToken {
1084 let token = TimerToken::new(NEXT_TIMER_TOKEN.fetch_add(1, Ordering::Relaxed));
1085 self.wake_requests.push(WakeRequest::ScheduleTimer {
1086 token,
1087 deadline,
1088 target: self.widget_id,
1089 });
1090 token
1091 }
1092
1093 pub fn schedule_timer_after(&mut self, delay: f64) -> TimerToken {
1094 self.schedule_timer_at(self.current_time + delay)
1095 }
1096
1097 pub fn cancel_timer(&mut self, token: TimerToken) {
1098 self.wake_requests.push(WakeRequest::CancelTimer { token });
1099 }
1100
1101 pub fn register_async_wakeup(&mut self) -> AsyncWakeToken {
1102 let token = AsyncWakeToken::new(NEXT_ASYNC_WAKE_TOKEN.fetch_add(1, Ordering::Relaxed));
1103 self.wake_requests.push(WakeRequest::RegisterAsync {
1104 token,
1105 target: self.widget_id,
1106 });
1107 token
1108 }
1109
1110 pub fn unregister_async_wakeup(&mut self, token: AsyncWakeToken) {
1111 self.wake_requests
1112 .push(WakeRequest::UnregisterAsync { token });
1113 }
1114
1115 pub fn request_animation_frame(&mut self) {
1116 self.wake_requests.push(WakeRequest::RequestAnimationFrame {
1117 target: self.widget_id,
1118 });
1119 }
1120
1121 pub fn request_pointer_capture(&mut self, pointer_id: u64) {
1122 self.pointer_capture_requests
1123 .push(PointerCaptureRequest::Capture {
1124 pointer_id,
1125 target: self.widget_id,
1126 });
1127 }
1128
1129 pub fn release_pointer_capture(&mut self, pointer_id: u64) {
1130 self.pointer_capture_requests
1131 .push(PointerCaptureRequest::Release { pointer_id });
1132 }
1133
1134 pub fn begin_drag(
1135 &mut self,
1136 scope_id: DragScopeId,
1137 pointer_id: u64,
1138 position: Point,
1139 payload: DragPayload,
1140 allowed_effect: DropEffect,
1141 preview_label: Option<String>,
1142 ) -> DragSessionId {
1143 let session_id = DragSessionId::new(NEXT_DRAG_SESSION_ID.fetch_add(1, Ordering::Relaxed));
1144 self.drag_requests
1145 .push(DragRequest::Begin(BeginDragRequest {
1146 session_id,
1147 scope_id,
1148 pointer_id,
1149 source: self.widget_id,
1150 position,
1151 payload,
1152 allowed_effect,
1153 preview_label,
1154 }));
1155 session_id
1156 }
1157
1158 pub fn accept_drop(&mut self, effect: DropEffect) {
1159 if effect.is_none() {
1160 return;
1161 }
1162 self.drop_acceptances.push(DropAcceptanceRequest {
1163 target: self.widget_id,
1164 effect,
1165 });
1166 }
1167
1168 pub fn request(&mut self, request: InvalidationRequest) {
1169 self.invalidations.push(request);
1170 }
1171
1172 pub fn request_measure(&mut self) {
1173 self.request_widget(InvalidationKind::Measure);
1174 }
1175
1176 pub fn request_arrange(&mut self) {
1177 self.request_widget(InvalidationKind::Arrange);
1178 }
1179
1180 pub fn request_ordering(&mut self) {
1181 self.request_widget(InvalidationKind::Ordering);
1182 }
1183
1184 pub fn request_paint(&mut self) {
1185 self.request_widget(InvalidationKind::Paint);
1186 }
1187
1188 pub fn request_paint_rect(&mut self, rect: Rect) {
1189 self.request(
1190 InvalidationRequest::new(
1191 InvalidationTarget::Widget(self.widget_id),
1192 InvalidationKind::Paint,
1193 )
1194 .with_region(rect),
1195 );
1196 }
1197
1198 pub fn request_transform(&mut self) {
1199 self.request_widget(InvalidationKind::Transform);
1200 }
1201
1202 pub fn request_effect(&mut self) {
1203 self.request_widget(InvalidationKind::Effect);
1204 }
1205
1206 pub fn request_visibility(&mut self) {
1207 self.request_widget(InvalidationKind::Visibility);
1208 }
1209
1210 pub fn request_hit_test(&mut self) {
1211 self.request_widget(InvalidationKind::HitTest);
1212 }
1213
1214 pub fn request_text(&mut self) {
1215 self.request_widget(InvalidationKind::Text);
1216 }
1217
1218 pub fn request_semantics(&mut self) {
1219 self.request_widget(InvalidationKind::Semantics);
1220 }
1221
1222 pub fn request_resources(&mut self) {
1223 self.request_widget(InvalidationKind::Resources);
1224 }
1225
1226 pub fn invalidations(&self) -> &[InvalidationRequest] {
1227 &self.invalidations
1228 }
1229
1230 pub(crate) fn take_invalidations(&mut self) -> Vec<InvalidationRequest> {
1231 std::mem::take(&mut self.invalidations)
1232 }
1233
1234 pub(crate) fn take_focus_request(&mut self) -> Option<FocusRequest> {
1235 self.focus_request.take()
1236 }
1237
1238 pub(crate) fn take_wake_requests(&mut self) -> Vec<WakeRequest> {
1239 std::mem::take(&mut self.wake_requests)
1240 }
1241
1242 pub(crate) fn take_pointer_capture_requests(&mut self) -> Vec<PointerCaptureRequest> {
1243 std::mem::take(&mut self.pointer_capture_requests)
1244 }
1245
1246 pub(crate) fn take_drag_requests(&mut self) -> Vec<DragRequest> {
1247 std::mem::take(&mut self.drag_requests)
1248 }
1249
1250 pub(crate) fn take_drop_acceptances(&mut self) -> Vec<DropAcceptanceRequest> {
1251 std::mem::take(&mut self.drop_acceptances)
1252 }
1253
1254 pub(crate) fn take_posted_events(&mut self) -> Vec<PostedEventRequest> {
1255 std::mem::take(&mut self.posted_events)
1256 }
1257
1258 fn request_widget(&mut self, kind: InvalidationKind) {
1259 self.request(InvalidationRequest::new(
1260 InvalidationTarget::Widget(self.widget_id),
1261 kind,
1262 ));
1263 }
1264}
1265
1266#[derive(Debug, Default)]
1277pub(crate) struct MeasureScope {
1278 force_all: bool,
1279 dirty: HashSet<WidgetId>,
1280 subtree_roots: HashSet<WidgetId>,
1281}
1282
1283impl MeasureScope {
1284 pub(crate) fn force_all() -> Self {
1285 Self {
1286 force_all: true,
1287 dirty: HashSet::new(),
1288 subtree_roots: HashSet::new(),
1289 }
1290 }
1291
1292 pub(crate) fn scoped(dirty: HashSet<WidgetId>, subtree_roots: HashSet<WidgetId>) -> Self {
1293 Self {
1294 force_all: false,
1295 dirty,
1296 subtree_roots,
1297 }
1298 }
1299
1300 fn must_remeasure(&self, widget_id: WidgetId) -> bool {
1301 self.force_all || self.dirty.contains(&widget_id)
1302 }
1303
1304 fn forces_subtree(&self, widget_id: WidgetId) -> bool {
1305 self.subtree_roots.contains(&widget_id)
1306 }
1307}
1308
1309#[derive(Debug, Clone)]
1310pub struct MeasureCtx {
1311 window_id: WindowId,
1312 widget_id: WidgetId,
1313 bounds: Rect,
1314 layout: LayoutContext,
1315 current_time: f64,
1316 invalidations: Vec<InvalidationRequest>,
1317 wake_requests: Vec<WakeRequest>,
1318 scope: Rc<MeasureScope>,
1319 force: bool,
1321}
1322
1323impl MeasureCtx {
1324 pub fn with_layout(
1325 window_id: WindowId,
1326 widget_id: WidgetId,
1327 bounds: Rect,
1328 layout: LayoutContext,
1329 ) -> Self {
1330 Self::with_layout_scoped(
1332 window_id,
1333 widget_id,
1334 bounds,
1335 layout,
1336 0.0,
1337 Rc::new(MeasureScope::force_all()),
1338 true,
1339 )
1340 }
1341
1342 pub(crate) fn with_layout_scoped(
1343 window_id: WindowId,
1344 widget_id: WidgetId,
1345 bounds: Rect,
1346 layout: LayoutContext,
1347 current_time: f64,
1348 scope: Rc<MeasureScope>,
1349 force: bool,
1350 ) -> Self {
1351 Self {
1352 window_id,
1353 widget_id,
1354 bounds,
1355 layout,
1356 current_time,
1357 invalidations: Vec::new(),
1358 wake_requests: Vec::new(),
1359 scope,
1360 force,
1361 }
1362 }
1363
1364 #[cfg(test)]
1365 pub(crate) fn new(
1366 window_id: WindowId,
1367 widget_id: WidgetId,
1368 bounds: Rect,
1369 dpi_info: DpiInfo,
1370 text_system: Arc<TextSystem>,
1371 font_registry: Arc<FontRegistry>,
1372 image_registry: Arc<ImageRegistry>,
1373 ) -> Self {
1374 Self::with_layout(
1375 window_id,
1376 widget_id,
1377 bounds,
1378 LayoutContext::new(dpi_info, text_system, font_registry, image_registry),
1379 )
1380 }
1381
1382 pub(crate) fn new_scoped_at(
1383 window_id: WindowId,
1384 widget_id: WidgetId,
1385 bounds: Rect,
1386 dpi_info: DpiInfo,
1387 text_system: Arc<TextSystem>,
1388 font_registry: Arc<FontRegistry>,
1389 image_registry: Arc<ImageRegistry>,
1390 scope: Rc<MeasureScope>,
1391 current_time: f64,
1392 ) -> Self {
1393 Self::with_layout_scoped(
1394 window_id,
1395 widget_id,
1396 bounds,
1397 LayoutContext::new(dpi_info, text_system, font_registry, image_registry),
1398 current_time,
1399 scope,
1400 false,
1401 )
1402 }
1403
1404 pub(crate) fn scope(&self) -> &MeasureScope {
1405 &self.scope
1406 }
1407
1408 pub(crate) fn child_force(&self) -> bool {
1412 self.force || self.scope.forces_subtree(self.widget_id)
1413 }
1414
1415 pub(crate) fn child(&self, widget_id: WidgetId, bounds: Rect, force: bool) -> Self {
1418 Self::with_layout_scoped(
1419 self.window_id,
1420 widget_id,
1421 bounds,
1422 self.layout.clone(),
1423 self.current_time,
1424 Rc::clone(&self.scope),
1425 force,
1426 )
1427 }
1428
1429 pub const fn window_id(&self) -> WindowId {
1430 self.window_id
1431 }
1432
1433 pub const fn widget_id(&self) -> WidgetId {
1434 self.widget_id
1435 }
1436
1437 pub const fn bounds(&self) -> Rect {
1438 self.bounds
1439 }
1440
1441 pub const fn layout(&self) -> &LayoutContext {
1442 &self.layout
1443 }
1444
1445 pub const fn dpi(&self) -> DpiInfo {
1446 self.layout.dpi()
1447 }
1448
1449 pub const fn current_time(&self) -> f64 {
1450 self.current_time
1451 }
1452
1453 pub fn request(&mut self, request: InvalidationRequest) {
1454 self.invalidations.push(request);
1455 }
1456
1457 pub fn request_measure(&mut self) {
1458 self.request_widget(InvalidationKind::Measure);
1459 }
1460
1461 pub fn request_arrange(&mut self) {
1462 self.request_widget(InvalidationKind::Arrange);
1463 }
1464
1465 pub fn request_ordering(&mut self) {
1466 self.request_widget(InvalidationKind::Ordering);
1467 }
1468
1469 pub fn request_paint(&mut self) {
1470 self.request_widget(InvalidationKind::Paint);
1471 }
1472
1473 pub fn request_semantics(&mut self) {
1474 self.request_widget(InvalidationKind::Semantics);
1475 }
1476
1477 pub fn request_animation_frame(&mut self) {
1478 self.wake_requests.push(WakeRequest::RequestAnimationFrame {
1479 target: self.widget_id,
1480 });
1481 }
1482
1483 pub fn invalidations(&self) -> &[InvalidationRequest] {
1484 &self.invalidations
1485 }
1486
1487 pub(crate) fn take_invalidations(&mut self) -> Vec<InvalidationRequest> {
1488 std::mem::take(&mut self.invalidations)
1489 }
1490
1491 pub(crate) fn take_wake_requests(&mut self) -> Vec<WakeRequest> {
1492 std::mem::take(&mut self.wake_requests)
1493 }
1494
1495 pub(crate) fn extend_invalidations(&mut self, invalidations: Vec<InvalidationRequest>) {
1496 self.invalidations.extend(invalidations);
1497 }
1498
1499 pub(crate) fn extend_wake_requests(&mut self, wake_requests: Vec<WakeRequest>) {
1500 self.wake_requests.extend(wake_requests);
1501 }
1502
1503 fn request_widget(&mut self, kind: InvalidationKind) {
1504 self.request(InvalidationRequest::new(
1505 InvalidationTarget::Widget(self.widget_id),
1506 kind,
1507 ));
1508 }
1509}
1510
1511#[derive(Debug, Clone)]
1512pub struct ArrangeCtx {
1513 window_id: WindowId,
1514 widget_id: WidgetId,
1515 dpi_info: DpiInfo,
1516 invalidations: Vec<InvalidationRequest>,
1517}
1518
1519impl ArrangeCtx {
1520 pub(crate) fn new(window_id: WindowId, widget_id: WidgetId, dpi_info: DpiInfo) -> Self {
1521 Self {
1522 window_id,
1523 widget_id,
1524 dpi_info,
1525 invalidations: Vec::new(),
1526 }
1527 }
1528
1529 pub const fn window_id(&self) -> WindowId {
1530 self.window_id
1531 }
1532
1533 pub const fn widget_id(&self) -> WidgetId {
1534 self.widget_id
1535 }
1536
1537 pub const fn dpi(&self) -> DpiInfo {
1538 self.dpi_info
1539 }
1540
1541 pub fn request(&mut self, request: InvalidationRequest) {
1542 self.invalidations.push(request);
1543 }
1544
1545 pub fn request_arrange(&mut self) {
1546 self.request_widget(InvalidationKind::Arrange);
1547 }
1548
1549 pub fn request_ordering(&mut self) {
1550 self.request_widget(InvalidationKind::Ordering);
1551 }
1552
1553 pub fn request_paint(&mut self) {
1554 self.request_widget(InvalidationKind::Paint);
1555 }
1556
1557 pub fn request_semantics(&mut self) {
1558 self.request_widget(InvalidationKind::Semantics);
1559 }
1560
1561 pub fn invalidations(&self) -> &[InvalidationRequest] {
1562 &self.invalidations
1563 }
1564
1565 pub(crate) fn take_invalidations(&mut self) -> Vec<InvalidationRequest> {
1566 std::mem::take(&mut self.invalidations)
1567 }
1568
1569 pub(crate) fn extend_invalidations(&mut self, invalidations: Vec<InvalidationRequest>) {
1570 self.invalidations.extend(invalidations);
1571 }
1572
1573 fn request_widget(&mut self, kind: InvalidationKind) {
1574 self.request(InvalidationRequest::new(
1575 InvalidationTarget::Widget(self.widget_id),
1576 kind,
1577 ));
1578 }
1579}
1580
1581#[derive(Debug, Clone)]
1582pub struct PaintCtx {
1583 window_id: WindowId,
1584 widget_id: WidgetId,
1585 focused_widget_id: Option<WidgetId>,
1586 bounds: Rect,
1587 dpi_info: DpiInfo,
1588 text_system: Arc<TextSystem>,
1589 font_registry: Arc<FontRegistry>,
1590 image_registry: Arc<ImageRegistry>,
1591 scene: Scene,
1592 images: Vec<(ImageHandle, PaintImageResource)>,
1593 widget_paint_bounds: HashMap<WidgetId, Rect>,
1594 invalidations: Vec<InvalidationRequest>,
1595 ime_composition_rect: Option<Rect>,
1596}
1597
1598#[derive(Debug, Clone)]
1599pub(crate) enum PaintImageResource {
1600 Cpu(RegisteredImage),
1601 External(RegisteredExternalImage),
1602}
1603
1604impl PaintCtx {
1605 pub(crate) fn new(
1606 window_id: WindowId,
1607 widget_id: WidgetId,
1608 bounds: Rect,
1609 focused_widget_id: Option<WidgetId>,
1610 dpi_info: DpiInfo,
1611 text_system: Arc<TextSystem>,
1612 font_registry: Arc<FontRegistry>,
1613 image_registry: Arc<ImageRegistry>,
1614 ) -> Self {
1615 Self {
1616 window_id,
1617 widget_id,
1618 focused_widget_id,
1619 bounds,
1620 dpi_info,
1621 text_system,
1622 font_registry,
1623 image_registry,
1624 scene: Scene::new(),
1625 images: Vec::new(),
1626 widget_paint_bounds: HashMap::new(),
1627 invalidations: Vec::new(),
1628 ime_composition_rect: None,
1629 }
1630 }
1631
1632 pub const fn window_id(&self) -> WindowId {
1633 self.window_id
1634 }
1635
1636 pub const fn widget_id(&self) -> WidgetId {
1637 self.widget_id
1638 }
1639
1640 pub const fn focused_widget_id(&self) -> Option<WidgetId> {
1641 self.focused_widget_id
1642 }
1643
1644 pub fn is_focused(&self) -> bool {
1645 self.focused_widget_id == Some(self.widget_id)
1646 }
1647
1648 pub const fn bounds(&self) -> Rect {
1649 self.bounds
1650 }
1651
1652 pub const fn dpi(&self) -> DpiInfo {
1653 self.dpi_info
1654 }
1655
1656 pub fn measure_text(
1657 &self,
1658 text: impl Into<String>,
1659 style: TextStyle,
1660 ) -> sui_core::Result<TextMeasurement> {
1661 self.text_system
1662 .measure_text(text, style, self.font_registry.as_ref())
1663 }
1664
1665 pub fn shape_text(
1666 &self,
1667 text: impl Into<String>,
1668 box_size: Size,
1669 style: TextStyle,
1670 ) -> sui_core::Result<TextLayout> {
1671 self.text_system
1672 .shape_text(text, box_size, style, self.font_registry.as_ref())
1673 }
1674
1675 pub fn layout_text_document(&self, request: TextLayoutRequest) -> sui_core::Result<TextLayout> {
1676 self.text_system
1677 .layout_document(request, self.font_registry.as_ref())
1678 }
1679
1680 pub fn clear(&mut self, color: Color) {
1681 self.scene.push(SceneCommand::Clear(color));
1682 }
1683
1684 pub fn fill(&mut self, path: impl Into<Path>, brush: impl Into<Brush>) {
1685 self.scene.push(SceneCommand::FillPath {
1686 path: path.into(),
1687 brush: brush.into(),
1688 });
1689 }
1690
1691 pub fn fill_rect(&mut self, rect: Rect, brush: impl Into<Brush>) {
1692 self.scene.push(SceneCommand::FillRect {
1693 rect,
1694 brush: brush.into(),
1695 });
1696 }
1697
1698 pub fn fill_bounds(&mut self, brush: impl Into<Brush>) {
1699 self.fill_rect(self.bounds, brush);
1700 }
1701
1702 pub fn stroke(&mut self, path: impl Into<Path>, brush: impl Into<Brush>, stroke: StrokeStyle) {
1703 self.scene.push(SceneCommand::StrokePath {
1704 path: path.into(),
1705 brush: brush.into(),
1706 stroke,
1707 });
1708 }
1709
1710 pub fn stroke_rect(&mut self, rect: Rect, brush: impl Into<Brush>, stroke: StrokeStyle) {
1711 self.scene.push(SceneCommand::StrokeRect {
1712 rect,
1713 brush: brush.into(),
1714 stroke,
1715 });
1716 }
1717
1718 pub fn stroke_bounds(&mut self, brush: impl Into<Brush>, stroke: StrokeStyle) {
1719 self.stroke_rect(self.bounds, brush, stroke);
1720 }
1721
1722 pub fn draw_text(&mut self, rect: Rect, text: impl Into<String>, style: TextStyle) {
1723 let text = text.into();
1724 let paint_color = style.color;
1725 let mut layout_style = style.clone();
1726 layout_style.color = Color::WHITE;
1727 let layout_run = TextRun {
1728 rect,
1729 text: text.clone(),
1730 style: layout_style,
1731 };
1732 let fallback_run = TextRun { rect, text, style };
1733
1734 match self.text_system.shape_text_run_persistent(
1735 Some(stable_text_run_handle(&layout_run)),
1736 &layout_run,
1737 self.font_registry.as_ref(),
1738 ) {
1739 Ok(layout) => self.scene.push(SceneCommand::DrawShapedText(
1740 ShapedText::new(rect.origin, &layout).with_color(paint_color),
1741 )),
1742 Err(_) => self.scene.push(SceneCommand::DrawText(fallback_run)),
1743 }
1744 }
1745
1746 pub fn draw_text_layout(&mut self, origin: Point, layout: &TextLayout) {
1747 let persistent = self.text_system.adopt_layout(layout.clone());
1748 self.draw_persistent_text_layout(origin, &persistent);
1749 }
1750
1751 pub fn draw_text_layout_with_color(
1752 &mut self,
1753 origin: Point,
1754 layout: &TextLayout,
1755 color: Color,
1756 ) {
1757 let persistent = self.text_system.adopt_layout(layout.clone());
1758 self.draw_persistent_text_layout_with_color(origin, &persistent, color);
1759 }
1760
1761 pub fn draw_persistent_text_layout(&mut self, origin: Point, layout: &PersistentTextLayout) {
1762 self.text_system.touch_persistent_layout(layout);
1763 self.scene
1764 .push(SceneCommand::DrawShapedText(ShapedText::new(
1765 origin, layout,
1766 )));
1767 }
1768
1769 pub fn draw_persistent_text_layout_with_color(
1770 &mut self,
1771 origin: Point,
1772 layout: &PersistentTextLayout,
1773 color: Color,
1774 ) {
1775 self.text_system.touch_persistent_layout(layout);
1776 self.scene.push(SceneCommand::DrawShapedText(
1777 ShapedText::new(origin, layout).with_color(color),
1778 ));
1779 }
1780
1781 pub fn draw_persistent_text_layout_window(
1782 &mut self,
1783 origin: Point,
1784 layout: &PersistentTextLayout,
1785 line_range: std::ops::Range<usize>,
1786 ) {
1787 self.text_system.touch_persistent_layout(layout);
1788 self.scene
1789 .push(SceneCommand::DrawShapedTextWindow(ShapedTextWindow::new(
1790 origin, layout, line_range,
1791 )));
1792 }
1793
1794 pub fn draw_persistent_text_layout_window_with_color(
1795 &mut self,
1796 origin: Point,
1797 layout: &PersistentTextLayout,
1798 line_range: std::ops::Range<usize>,
1799 color: Color,
1800 ) {
1801 self.text_system.touch_persistent_layout(layout);
1802 self.scene.push(SceneCommand::DrawShapedTextWindow(
1803 ShapedTextWindow::new(origin, layout, line_range).with_color(color),
1804 ));
1805 }
1806
1807 pub fn label(&mut self, rect: Rect, text: impl Into<String>, color: Color) {
1808 self.draw_text(rect, text, TextStyle::new(color));
1809 }
1810
1811 pub fn push_text_render_policy(&mut self, policy: TextRenderPolicy) {
1812 self.scene.push(SceneCommand::PushTextRenderPolicy {
1813 policy: policy.normalized(),
1814 });
1815 }
1816
1817 pub fn pop_text_render_policy(&mut self) {
1818 self.scene.push(SceneCommand::PopTextRenderPolicy);
1819 }
1820
1821 pub fn draw_image(&mut self, rect: Rect, image: sui_core::ImageHandle) {
1822 self.scene.push(SceneCommand::DrawImage {
1823 rect,
1824 source: ImageSource::new(image),
1825 });
1826 }
1827
1828 pub fn image_registered(&self, image: ImageHandle) -> bool {
1829 self.image_registry.contains(image)
1830 || self.images.iter().any(|(handle, _)| *handle == image)
1831 }
1832
1833 pub fn draw_image_source(&mut self, rect: Rect, source: ImageSource) {
1834 self.scene.push(SceneCommand::DrawImage { rect, source });
1835 }
1836
1837 pub fn draw_image_quad(&mut self, points: [Point; 4], image: ImageHandle) {
1838 self.draw_image_quad_source(points, ImageSource::new(image));
1839 }
1840
1841 pub fn draw_image_quad_source(&mut self, points: [Point; 4], source: ImageSource) {
1842 self.scene
1843 .push(SceneCommand::DrawImageQuad { points, source });
1844 }
1845
1846 pub fn widget_image_handle(&self, slot: u64) -> ImageHandle {
1847 let mut hasher = DefaultHasher::new();
1848 self.widget_id.hash(&mut hasher);
1849 slot.hash(&mut hasher);
1850 ImageHandle::new(WIDGET_IMAGE_HANDLE_NAMESPACE | (hasher.finish() >> 1))
1851 }
1852
1853 pub fn register_image(&mut self, handle: ImageHandle, image: RegisteredImage) {
1854 self.images.push((handle, PaintImageResource::Cpu(image)));
1855 }
1856
1857 pub fn register_external_image(&mut self, handle: ImageHandle, image: RegisteredExternalImage) {
1864 self.images
1865 .push((handle, PaintImageResource::External(image)));
1866 }
1867
1868 pub fn draw_shader_rect(&mut self, rect: Rect, shader: WidgetShader) {
1869 self.scene
1870 .push(SceneCommand::DrawShaderRect { rect, shader });
1871 }
1872
1873 pub fn fill_rrect(&mut self, rect: Rect, radii: [f32; 4], brush: impl Into<Brush>) {
1875 self.scene.push(SceneCommand::FillRoundedRect {
1876 rect,
1877 radii,
1878 brush: brush.into(),
1879 border: None,
1880 shadow: None,
1881 });
1882 }
1883
1884 pub fn fill_rrect_bordered(
1886 &mut self,
1887 rect: Rect,
1888 radii: [f32; 4],
1889 brush: impl Into<Brush>,
1890 border: Border,
1891 ) {
1892 self.scene.push(SceneCommand::FillRoundedRect {
1893 rect,
1894 radii,
1895 brush: brush.into(),
1896 border: Some(border),
1897 shadow: None,
1898 });
1899 }
1900
1901 pub fn draw_shadow(&mut self, rect: Rect, radii: [f32; 4], shadow: ShadowParams) {
1903 self.scene.push(SceneCommand::FillRoundedRect {
1904 rect,
1905 radii,
1906 brush: Brush::Solid(Color::TRANSPARENT),
1907 border: None,
1908 shadow: Some(shadow),
1909 });
1910 }
1911
1912 pub fn fill_rrect_with_shadow(
1914 &mut self,
1915 rect: Rect,
1916 radii: [f32; 4],
1917 brush: impl Into<Brush>,
1918 shadow: ShadowParams,
1919 ) {
1920 self.scene.push(SceneCommand::FillRoundedRect {
1921 rect,
1922 radii,
1923 brush: brush.into(),
1924 border: None,
1925 shadow: Some(shadow),
1926 });
1927 }
1928
1929 pub fn push_clip(&mut self, path: impl Into<Path>) {
1930 self.scene
1931 .push(SceneCommand::PushClipPath { path: path.into() });
1932 }
1933
1934 pub fn push_clip_rect(&mut self, rect: Rect) {
1935 self.scene.push(SceneCommand::PushClip { rect });
1936 }
1937
1938 pub fn pop_clip(&mut self) {
1939 self.scene.push(SceneCommand::PopClip);
1940 }
1941
1942 pub fn push_transform(&mut self, transform: Transform) {
1943 self.scene.push(SceneCommand::PushTransform { transform });
1944 }
1945
1946 pub fn translate(&mut self, delta: Vector) {
1947 self.push_transform(Transform::translation_vector(delta));
1948 }
1949
1950 pub fn pop_transform(&mut self) {
1951 self.scene.push(SceneCommand::PopTransform);
1952 }
1953
1954 pub fn push(&mut self, command: SceneCommand) {
1955 self.scene.push(command);
1956 }
1957
1958 pub fn scene(&self) -> &Scene {
1959 &self.scene
1960 }
1961
1962 pub fn scene_mut(&mut self) -> &mut Scene {
1963 &mut self.scene
1964 }
1965
1966 pub fn request(&mut self, request: InvalidationRequest) {
1967 self.invalidations.push(request);
1968 }
1969
1970 pub fn request_paint(&mut self) {
1971 self.request_widget(InvalidationKind::Paint);
1972 }
1973
1974 pub fn request_paint_rect(&mut self, rect: Rect) {
1975 self.request(
1976 InvalidationRequest::new(
1977 InvalidationTarget::Widget(self.widget_id),
1978 InvalidationKind::Paint,
1979 )
1980 .with_region(rect),
1981 );
1982 }
1983
1984 pub fn invalidations(&self) -> &[InvalidationRequest] {
1985 &self.invalidations
1986 }
1987
1988 pub fn set_ime_composition_rect(&mut self, rect: Rect) {
1989 self.ime_composition_rect = Some(rect);
1990 }
1991
1992 pub fn clear_ime_composition_rect(&mut self) {
1993 self.ime_composition_rect = None;
1994 }
1995
1996 pub const fn ime_composition_rect(&self) -> Option<Rect> {
1997 self.ime_composition_rect
1998 }
1999
2000 pub(crate) fn push_layer(&mut self, descriptor: SceneLayerDescriptor, scene: Scene) {
2001 self.scene
2002 .push(SceneCommand::Layer(SceneLayer::from_descriptor(
2003 descriptor, scene,
2004 )));
2005 }
2006
2007 pub(crate) fn append_scene(&mut self, scene: Scene) {
2008 self.scene.append(scene);
2009 }
2010
2011 pub(crate) fn record_widget_paint_bounds(&mut self, widget_id: WidgetId, paint_bounds: Rect) {
2012 self.widget_paint_bounds.insert(widget_id, paint_bounds);
2013 }
2014
2015 pub(crate) fn extend_widget_paint_bounds(
2016 &mut self,
2017 widget_paint_bounds: HashMap<WidgetId, Rect>,
2018 ) {
2019 self.widget_paint_bounds.extend(widget_paint_bounds);
2020 }
2021
2022 pub(crate) fn extend_images(&mut self, images: Vec<(ImageHandle, PaintImageResource)>) {
2023 self.images.extend(images);
2024 }
2025
2026 pub(crate) fn extend_invalidations(&mut self, invalidations: Vec<InvalidationRequest>) {
2027 self.invalidations.extend(invalidations);
2028 }
2029
2030 pub(crate) fn extend_ime_composition_rect(&mut self, ime_composition_rect: Option<Rect>) {
2031 if ime_composition_rect.is_some() {
2032 self.ime_composition_rect = ime_composition_rect;
2033 }
2034 }
2035
2036 pub(crate) fn into_parts(
2037 self,
2038 ) -> (
2039 Scene,
2040 Vec<(ImageHandle, PaintImageResource)>,
2041 HashMap<WidgetId, Rect>,
2042 Vec<InvalidationRequest>,
2043 Option<Rect>,
2044 ) {
2045 (
2046 self.scene,
2047 self.images,
2048 self.widget_paint_bounds,
2049 self.invalidations,
2050 self.ime_composition_rect,
2051 )
2052 }
2053
2054 fn request_widget(&mut self, kind: InvalidationKind) {
2055 self.request(InvalidationRequest::new(
2056 InvalidationTarget::Widget(self.widget_id),
2057 kind,
2058 ));
2059 }
2060}
2061
2062fn stable_text_run_handle(run: &TextRun) -> TextLayoutHandle {
2063 let mut hasher = DefaultHasher::new();
2064 run.text.hash(&mut hasher);
2065 run.rect.size.width.to_bits().hash(&mut hasher);
2066 run.rect.size.height.to_bits().hash(&mut hasher);
2067 run.style.font.map(|font| font.get()).hash(&mut hasher);
2068 run.style.font_size.to_bits().hash(&mut hasher);
2069 run.style.line_height.to_bits().hash(&mut hasher);
2070 run.style.weight.value().hash(&mut hasher);
2071 run.style.style.hash(&mut hasher);
2072 run.style.stretch.hash(&mut hasher);
2073 run.style.features.hash(&mut hasher);
2074 TextLayoutHandle::new(hasher.finish().max(1))
2075}
2076
2077#[derive(Debug, Clone)]
2078pub struct SemanticsCtx {
2079 window_id: WindowId,
2080 widget_id: WidgetId,
2081 root_widget_id: WidgetId,
2082 focused_widget_id: Option<WidgetId>,
2083 bounds: Rect,
2084 nodes: Vec<SemanticsNode>,
2085}
2086
2087impl SemanticsCtx {
2088 pub(crate) fn new(
2089 window_id: WindowId,
2090 widget_id: WidgetId,
2091 root_widget_id: WidgetId,
2092 bounds: Rect,
2093 focused_widget_id: Option<WidgetId>,
2094 ) -> Self {
2095 Self {
2096 window_id,
2097 widget_id,
2098 root_widget_id,
2099 focused_widget_id,
2100 bounds,
2101 nodes: Vec::new(),
2102 }
2103 }
2104
2105 pub const fn window_id(&self) -> WindowId {
2106 self.window_id
2107 }
2108
2109 pub const fn widget_id(&self) -> WidgetId {
2110 self.widget_id
2111 }
2112
2113 pub const fn root_widget_id(&self) -> WidgetId {
2114 self.root_widget_id
2115 }
2116
2117 pub const fn focused_widget_id(&self) -> Option<WidgetId> {
2118 self.focused_widget_id
2119 }
2120
2121 pub fn is_focused(&self) -> bool {
2122 self.focused_widget_id == Some(self.widget_id)
2123 }
2124
2125 pub const fn bounds(&self) -> Rect {
2126 self.bounds
2127 }
2128
2129 pub fn push(&mut self, node: SemanticsNode) {
2130 self.nodes.push(node);
2131 }
2132
2133 pub fn nodes(&self) -> &[SemanticsNode] {
2134 &self.nodes
2135 }
2136
2137 pub(crate) fn extend_nodes(&mut self, nodes: Vec<SemanticsNode>) {
2138 self.nodes.extend(nodes);
2139 }
2140
2141 pub(crate) fn into_nodes(self) -> Vec<SemanticsNode> {
2142 self.nodes
2143 }
2144}
2145
2146#[cfg(test)]
2147mod tests {
2148 use std::sync::Arc;
2149
2150 use super::{
2151 ArrangeCtx, EventCtx, EventPhase, MeasureCtx, MeasureScope, PaintCtx, SemanticsCtx,
2152 SingleChild, WakeRequest, Widget, WidgetChildren, WidgetPod, WidgetPodMutVisitor,
2153 WidgetPodVisitor,
2154 };
2155 use std::cell::Cell;
2156 use std::collections::HashSet;
2157 use std::rc::Rc;
2158 use sui_core::{
2159 Clipboard, Color, DpiInfo, ImageHandle, InvalidationKind, Point, Rect, SemanticsNode,
2160 SemanticsRole, Size, Vector, WidgetId, WindowId,
2161 };
2162 use sui_layout::{Constraints, LayoutContext};
2163 use sui_scene::{ImageRegistry, RegisteredImage, SceneCommand, StrokeStyle};
2164 use sui_text::{FontRegistry, FontWeight, TextRun, TextStyle, TextSystem};
2165
2166 fn measure_ctx(window_id: WindowId, widget_id: WidgetId) -> MeasureCtx {
2167 MeasureCtx::new(
2168 window_id,
2169 widget_id,
2170 Rect::ZERO,
2171 DpiInfo::default(),
2172 std::sync::Arc::new(TextSystem::new()),
2173 std::sync::Arc::new(FontRegistry::new()),
2174 std::sync::Arc::new(ImageRegistry::new()),
2175 )
2176 }
2177
2178 #[test]
2179 fn measure_ctx_wraps_reusable_layout_context() {
2180 let mut images = ImageRegistry::new();
2181 images.insert(
2182 ImageHandle::new(9),
2183 RegisteredImage::from_rgba8(3, 2, vec![255; 3 * 2 * 4]).unwrap(),
2184 );
2185 let layout = LayoutContext::new(
2186 DpiInfo::new(
2187 1.5,
2188 Some(144.0),
2189 Size::new(200.0, 100.0),
2190 Size::new(300.0, 150.0),
2191 ),
2192 Arc::new(TextSystem::new()),
2193 Arc::new(FontRegistry::new()),
2194 Arc::new(images),
2195 );
2196
2197 let measure = MeasureCtx::with_layout(
2198 WindowId::new(1),
2199 WidgetId::new(2),
2200 Rect::new(4.0, 6.0, 32.0, 18.0),
2201 layout.clone(),
2202 );
2203
2204 assert_eq!(measure.dpi(), layout.dpi());
2205 assert_eq!(measure.bounds(), Rect::new(4.0, 6.0, 32.0, 18.0));
2206 assert_eq!(
2207 measure.layout().image_size(ImageHandle::new(9)),
2208 Some(Size::new(3.0, 2.0))
2209 );
2210 }
2211
2212 #[test]
2213 fn measure_and_paint_ctx_expose_dpi_info() {
2214 let dpi = DpiInfo::new(
2215 2.0,
2216 Some(192.0),
2217 sui_core::Size::new(320.0, 180.0),
2218 sui_core::Size::new(640.0, 360.0),
2219 );
2220
2221 let measure = MeasureCtx::new(
2222 WindowId::new(1),
2223 WidgetId::new(2),
2224 Rect::ZERO,
2225 dpi,
2226 std::sync::Arc::new(TextSystem::new()),
2227 std::sync::Arc::new(FontRegistry::new()),
2228 std::sync::Arc::new(ImageRegistry::new()),
2229 );
2230 let paint = PaintCtx::new(
2231 WindowId::new(1),
2232 WidgetId::new(2),
2233 Rect::new(0.0, 0.0, 120.0, 60.0),
2234 None,
2235 dpi,
2236 Arc::new(TextSystem::new()),
2237 Arc::new(FontRegistry::new()),
2238 Arc::new(ImageRegistry::new()),
2239 );
2240 let event = EventCtx::new(
2241 WindowId::new(1),
2242 WidgetId::new(2),
2243 Rect::new(0.0, 0.0, 120.0, 60.0),
2244 dpi,
2245 0.0,
2246 EventPhase::Target,
2247 None,
2248 Clipboard::new(),
2249 );
2250
2251 assert_eq!(measure.dpi(), dpi);
2252 assert_eq!(paint.dpi(), dpi);
2253 assert_eq!(event.dpi(), dpi);
2254 }
2255
2256 struct LabelWidget;
2257
2258 impl Widget for LabelWidget {
2259 fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> sui_core::Size {
2260 constraints.clamp(sui_core::Size::new(48.0, 20.0))
2261 }
2262
2263 fn paint(&self, ctx: &mut PaintCtx) {
2264 ctx.fill_bounds(Color::rgba(0.2, 0.3, 0.4, 1.0));
2265 }
2266
2267 fn semantics(&self, ctx: &mut SemanticsCtx) {
2268 ctx.push(SemanticsNode::new(
2269 ctx.widget_id(),
2270 SemanticsRole::Text,
2271 ctx.bounds(),
2272 ));
2273 }
2274 }
2275
2276 struct BoundsLeaf;
2277
2278 impl Widget for BoundsLeaf {
2279 fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
2280 constraints.max
2281 }
2282
2283 fn paint(&self, ctx: &mut PaintCtx) {
2284 ctx.fill_rect(
2285 Rect::new(10.0, 10.0, 80.0, 50.0),
2286 Color::rgba(0.2, 0.3, 0.4, 1.0),
2287 );
2288 }
2289 }
2290
2291 struct BoundsWrapper {
2292 child: WidgetPod,
2293 clip: Option<Rect>,
2294 translation: Vector,
2295 }
2296
2297 impl BoundsWrapper {
2298 fn new(child: impl Widget + 'static, clip: Option<Rect>, translation: Vector) -> Self {
2299 Self {
2300 child: WidgetPod::new(child),
2301 clip,
2302 translation,
2303 }
2304 }
2305 }
2306
2307 impl Widget for BoundsWrapper {
2308 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
2309 self.child.measure(ctx, constraints)
2310 }
2311
2312 fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
2313 self.child.arrange(ctx, bounds);
2314 }
2315
2316 fn paint(&self, ctx: &mut PaintCtx) {
2317 if let Some(clip) = self.clip {
2318 ctx.push_clip_rect(clip);
2319 }
2320 if self.translation != Vector::ZERO {
2321 ctx.translate(self.translation);
2322 }
2323
2324 self.child.paint(ctx);
2325
2326 if self.translation != Vector::ZERO {
2327 ctx.pop_transform();
2328 }
2329 if self.clip.is_some() {
2330 ctx.pop_clip();
2331 }
2332 }
2333
2334 fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
2335 visitor.visit(&self.child);
2336 }
2337
2338 fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
2339 visitor.visit(&mut self.child);
2340 }
2341 }
2342
2343 #[test]
2344 fn event_ctx_tracks_widget_scoped_invalidations_and_focus() {
2345 let mut ctx = EventCtx::new(
2346 WindowId::new(1),
2347 WidgetId::new(2),
2348 Rect::new(8.0, 12.0, 24.0, 36.0),
2349 DpiInfo::default(),
2350 0.0,
2351 EventPhase::Target,
2352 None,
2353 Clipboard::new(),
2354 );
2355
2356 ctx.request_measure();
2357 ctx.request_paint_rect(Rect::new(8.0, 12.0, 24.0, 36.0));
2358 ctx.request_transform();
2359 ctx.request_effect();
2360 ctx.request_visibility();
2361 ctx.request_animation_frame();
2362 ctx.request_focus();
2363 ctx.set_handled();
2364
2365 assert!(ctx.is_handled());
2366 assert_eq!(ctx.bounds(), Rect::new(8.0, 12.0, 24.0, 36.0));
2367 assert_eq!(ctx.invalidations().len(), 5);
2368 assert_eq!(ctx.invalidations()[0].kind, InvalidationKind::Measure);
2369 assert_eq!(
2370 ctx.invalidations()[1].region,
2371 Some(Rect::new(8.0, 12.0, 24.0, 36.0))
2372 );
2373 assert_eq!(ctx.invalidations()[2].kind, InvalidationKind::Transform);
2374 assert_eq!(ctx.invalidations()[3].kind, InvalidationKind::Effect);
2375 assert_eq!(ctx.invalidations()[4].kind, InvalidationKind::Visibility);
2376 assert_eq!(
2377 ctx.take_wake_requests(),
2378 vec![WakeRequest::RequestAnimationFrame {
2379 target: WidgetId::new(2)
2380 }]
2381 );
2382 }
2383
2384 #[test]
2385 fn request_animation_frame_enqueues_widget_for_next_frame() {
2386 let mut ctx = EventCtx::new(
2387 WindowId::new(4),
2388 WidgetId::new(9),
2389 Rect::new(0.0, 0.0, 20.0, 10.0),
2390 DpiInfo::default(),
2391 16.0,
2392 EventPhase::Target,
2393 None,
2394 Clipboard::new(),
2395 );
2396
2397 ctx.request_animation_frame();
2398
2399 assert_eq!(
2400 ctx.take_wake_requests(),
2401 vec![WakeRequest::RequestAnimationFrame {
2402 target: WidgetId::new(9)
2403 }]
2404 );
2405 }
2406
2407 struct CountingChild {
2408 measures: Rc<Cell<u32>>,
2409 }
2410
2411 impl Widget for CountingChild {
2412 fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> sui_core::Size {
2413 self.measures.set(self.measures.get() + 1);
2414 constraints.clamp(sui_core::Size::new(10.0, 10.0))
2415 }
2416 }
2417
2418 struct PassthroughParent {
2419 child: WidgetPod,
2420 }
2421
2422 impl Widget for PassthroughParent {
2423 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> sui_core::Size {
2424 self.child.measure(ctx, constraints)
2425 }
2426
2427 fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
2428 visitor.visit(&self.child);
2429 }
2430
2431 fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
2432 visitor.visit(&mut self.child);
2433 }
2434 }
2435
2436 fn scoped_measure_ctx(root_id: WidgetId, scope: MeasureScope) -> MeasureCtx {
2437 MeasureCtx::new_scoped_at(
2438 WindowId::new(1),
2439 root_id,
2440 Rect::ZERO,
2441 DpiInfo::default(),
2442 Arc::new(TextSystem::new()),
2443 Arc::new(FontRegistry::new()),
2444 Arc::new(ImageRegistry::new()),
2445 Rc::new(scope),
2446 0.0,
2447 )
2448 }
2449
2450 #[test]
2451 fn measure_cache_skips_clean_subtrees_and_forces_changed_ones() {
2452 let measures = Rc::new(Cell::new(0u32));
2453 let child = WidgetPod::new(CountingChild {
2454 measures: Rc::clone(&measures),
2455 });
2456 let mut parent = WidgetPod::new(PassthroughParent { child });
2457 let parent_id = parent.id();
2458 let outside = WidgetId::new(u64::MAX);
2459 let constraints = Constraints::tight(sui_core::Size::new(10.0, 10.0));
2460
2461 let mut ctx = scoped_measure_ctx(outside, MeasureScope::force_all());
2463 parent.measure(&mut ctx, constraints);
2464 assert_eq!(measures.get(), 1, "initial pass must measure the child");
2465
2466 let mut ctx = scoped_measure_ctx(
2469 outside,
2470 MeasureScope::scoped(HashSet::new(), HashSet::new()),
2471 );
2472 parent.measure(&mut ctx, constraints);
2473 assert_eq!(measures.get(), 1, "clean subtree must be skipped");
2474
2475 let mut dirty = HashSet::new();
2478 dirty.insert(parent_id);
2479 let mut ctx = scoped_measure_ctx(outside, MeasureScope::scoped(dirty, HashSet::new()));
2480 parent.measure(&mut ctx, constraints);
2481 assert_eq!(
2482 measures.get(),
2483 1,
2484 "ancestor-only re-measure must not force the subtree"
2485 );
2486
2487 let mut dirty = HashSet::new();
2491 dirty.insert(parent_id);
2492 let mut roots = HashSet::new();
2493 roots.insert(parent_id);
2494 let mut ctx = scoped_measure_ctx(outside, MeasureScope::scoped(dirty, roots));
2495 parent.measure(&mut ctx, constraints);
2496 assert_eq!(
2497 measures.get(),
2498 2,
2499 "a changed widget must force its descendants to re-measure"
2500 );
2501 }
2502
2503 #[test]
2504 fn widget_pod_merges_child_measure_arrange_paint_and_semantics() {
2505 let mut pod = WidgetPod::new(LabelWidget);
2506 pod.set_bounds(Rect::new(4.0, 6.0, 0.0, 0.0));
2507
2508 let mut measure = measure_ctx(WindowId::new(3), WidgetId::new(4));
2509 let size = pod.measure(
2510 &mut measure,
2511 Constraints::tight(sui_core::Size::new(64.0, 32.0)),
2512 );
2513 let mut arrange = ArrangeCtx::new(WindowId::new(3), WidgetId::new(4), DpiInfo::default());
2514 pod.arrange(&mut arrange, Rect::new(4.0, 6.0, 64.0, 32.0));
2515
2516 let mut paint = PaintCtx::new(
2517 WindowId::new(3),
2518 WidgetId::new(4),
2519 Rect::new(0.0, 0.0, 120.0, 60.0),
2520 None,
2521 DpiInfo::default(),
2522 Arc::new(TextSystem::new()),
2523 Arc::new(FontRegistry::new()),
2524 Arc::new(ImageRegistry::new()),
2525 );
2526 pod.paint(&mut paint);
2527
2528 let mut semantics = SemanticsCtx::new(
2529 WindowId::new(3),
2530 WidgetId::new(4),
2531 WidgetId::new(4),
2532 Rect::new(0.0, 0.0, 120.0, 60.0),
2533 None,
2534 );
2535 pod.semantics(&mut semantics);
2536
2537 assert_eq!(size, sui_core::Size::new(64.0, 32.0));
2538 assert_eq!(pod.bounds(), Rect::new(4.0, 6.0, 64.0, 32.0));
2539 assert_eq!(paint.scene().commands().len(), 1);
2540 assert!(matches!(
2541 paint.scene().commands()[0],
2542 SceneCommand::FillRect { .. }
2543 ));
2544 assert_eq!(semantics.nodes().len(), 1);
2545 }
2546
2547 #[test]
2548 fn single_child_wraps_measure_arrange_and_visitation() {
2549 struct CaptureVisitor {
2550 ids: Vec<WidgetId>,
2551 }
2552
2553 impl WidgetPodVisitor for CaptureVisitor {
2554 fn visit(&mut self, child: &WidgetPod) {
2555 self.ids.push(child.id());
2556 }
2557 }
2558
2559 impl WidgetPodMutVisitor for CaptureVisitor {
2560 fn visit(&mut self, child: &mut WidgetPod) {
2561 self.ids.push(child.id());
2562 }
2563 }
2564
2565 let mut child = SingleChild::new(LabelWidget);
2566 let mut measure = measure_ctx(WindowId::new(7), WidgetId::new(8));
2567 let size = child.measure(
2568 &mut measure,
2569 Constraints::tight(sui_core::Size::new(80.0, 24.0)),
2570 );
2571 let mut arrange = ArrangeCtx::new(WindowId::new(7), WidgetId::new(8), DpiInfo::default());
2572 child.arrange(&mut arrange, Rect::new(12.0, 18.0, 80.0, 24.0));
2573
2574 let mut visitor = CaptureVisitor { ids: Vec::new() };
2575 child.visit_children(&mut visitor);
2576 child.visit_children_mut(&mut visitor);
2577
2578 assert_eq!(size, sui_core::Size::new(80.0, 24.0));
2579 assert_eq!(child.child().bounds(), Rect::new(12.0, 18.0, 80.0, 24.0));
2580 assert_eq!(visitor.ids, vec![child.child().id(), child.child().id()]);
2581 }
2582
2583 #[test]
2584 fn widget_children_bulk_paint_and_semantics_delegate_to_all_children() {
2585 let mut children = WidgetChildren::with_capacity(2);
2586 children.push(LabelWidget);
2587 children.push(LabelWidget);
2588
2589 let mut measure = measure_ctx(WindowId::new(9), WidgetId::new(10));
2590 children.measure_child(
2591 0,
2592 &mut measure,
2593 Constraints::tight(sui_core::Size::new(40.0, 18.0)),
2594 );
2595 children.measure_child(
2596 1,
2597 &mut measure,
2598 Constraints::tight(sui_core::Size::new(60.0, 18.0)),
2599 );
2600 let mut arrange = ArrangeCtx::new(WindowId::new(9), WidgetId::new(10), DpiInfo::default());
2601 children.arrange_child(0, &mut arrange, Rect::new(0.0, 0.0, 40.0, 18.0));
2602 children.arrange_child(1, &mut arrange, Rect::new(44.0, 0.0, 60.0, 18.0));
2603
2604 let mut paint = PaintCtx::new(
2605 WindowId::new(9),
2606 WidgetId::new(10),
2607 Rect::new(0.0, 0.0, 120.0, 40.0),
2608 None,
2609 DpiInfo::default(),
2610 Arc::new(TextSystem::new()),
2611 Arc::new(FontRegistry::new()),
2612 Arc::new(ImageRegistry::new()),
2613 );
2614 children.paint(&mut paint);
2615
2616 let mut semantics = SemanticsCtx::new(
2617 WindowId::new(9),
2618 WidgetId::new(10),
2619 WidgetId::new(10),
2620 Rect::new(0.0, 0.0, 120.0, 40.0),
2621 None,
2622 );
2623 children.semantics(&mut semantics);
2624
2625 assert_eq!(children.len(), 2);
2626 assert_eq!(paint.scene().commands().len(), 2);
2627 assert_eq!(semantics.nodes().len(), 2);
2628 }
2629
2630 #[test]
2631 fn nested_paint_wrappers_preserve_content_and_clipped_paint_bounds() {
2632 let inner = BoundsWrapper::new(
2633 BoundsLeaf,
2634 Some(Rect::new(0.0, 0.0, 60.0, 60.0)),
2635 Vector::new(0.0, 7.0),
2636 );
2637 let outer = BoundsWrapper::new(
2638 inner,
2639 Some(Rect::new(0.0, 0.0, 100.0, 100.0)),
2640 Vector::new(5.0, 0.0),
2641 );
2642 let mut root = WidgetPod::new(BoundsWrapper::new(outer, None, Vector::ZERO));
2645 let window_id = WindowId::new(17);
2646 let root_id = WidgetId::new(18);
2647 let bounds = Rect::new(0.0, 0.0, 120.0, 100.0);
2648 let mut measure = measure_ctx(window_id, root_id);
2649 root.measure(&mut measure, Constraints::tight(bounds.size));
2650 let mut arrange = ArrangeCtx::new(window_id, root_id, DpiInfo::default());
2651 root.arrange(&mut arrange, bounds);
2652
2653 let mut paint = PaintCtx::new(
2654 window_id,
2655 root_id,
2656 bounds,
2657 None,
2658 DpiInfo::default(),
2659 Arc::new(TextSystem::new()),
2660 Arc::new(FontRegistry::new()),
2661 Arc::new(ImageRegistry::new()),
2662 );
2663 root.paint(&mut paint);
2664
2665 assert_eq!(
2666 paint.scene().content_bounds(),
2667 Some(Rect::new(15.0, 17.0, 80.0, 50.0))
2668 );
2669 assert_eq!(
2670 paint.scene().paint_bounds(),
2671 Some(Rect::new(15.0, 17.0, 50.0, 43.0))
2672 );
2673 assert_eq!(
2674 paint.scene().paint_bounds(),
2675 paint.scene().clone().paint_bounds()
2676 );
2677 }
2678
2679 #[test]
2680 fn paint_ctx_emits_extended_scene_commands() {
2681 let mut paint = PaintCtx::new(
2682 WindowId::new(11),
2683 WidgetId::new(12),
2684 Rect::new(0.0, 0.0, 120.0, 60.0),
2685 None,
2686 DpiInfo::default(),
2687 Arc::new(TextSystem::new()),
2688 Arc::new(FontRegistry::new()),
2689 Arc::new(ImageRegistry::new()),
2690 );
2691
2692 let mut path = sui_core::Path::builder();
2693 path.move_to(Point::new(4.0, 5.0))
2694 .line_to(Point::new(24.0, 5.0))
2695 .line_to(Point::new(14.0, 15.0))
2696 .close();
2697 paint.stroke(path.build(), Color::WHITE, StrokeStyle::new(2.0));
2698 paint.draw_text(
2699 Rect::new(8.0, 10.0, 80.0, 20.0),
2700 "hello",
2701 TextStyle::new(Color::BLACK),
2702 );
2703 paint.draw_image(
2704 Rect::new(0.0, 0.0, 16.0, 16.0),
2705 sui_core::ImageHandle::new(3),
2706 );
2707 paint.push_clip(sui_core::Path::circle(Point::new(12.0, 12.0), 8.0));
2708 paint.push_clip_rect(Rect::new(0.0, 0.0, 50.0, 50.0));
2709 paint.translate(Vector::new(3.0, 4.0));
2710 paint.pop_transform();
2711 paint.pop_clip();
2712 paint.pop_clip();
2713
2714 assert!(matches!(
2715 paint.scene().commands()[0],
2716 SceneCommand::StrokePath { .. }
2717 ));
2718 assert!(matches!(
2719 paint.scene().commands()[1],
2720 SceneCommand::DrawShapedText(_)
2721 ));
2722 assert!(matches!(
2723 paint.scene().commands()[2],
2724 SceneCommand::DrawImage { .. }
2725 ));
2726 assert!(matches!(
2727 paint.scene().commands()[3],
2728 SceneCommand::PushClipPath { .. }
2729 ));
2730 assert!(matches!(
2731 paint.scene().commands()[4],
2732 SceneCommand::PushClip { .. }
2733 ));
2734 assert!(matches!(
2735 paint.scene().commands()[5],
2736 SceneCommand::PushTransform { .. }
2737 ));
2738 assert!(matches!(
2739 paint.scene().commands()[6],
2740 SceneCommand::PopTransform
2741 ));
2742 assert!(matches!(paint.scene().commands()[7], SceneCommand::PopClip));
2743 assert!(matches!(paint.scene().commands()[8], SceneCommand::PopClip));
2744 }
2745
2746 #[test]
2747 fn stable_text_run_handle_ignores_color_and_includes_layout_style() {
2748 let run = TextRun {
2749 rect: Rect::new(8.0, 10.0, 80.0, 20.0),
2750 text: "hello".to_string(),
2751 style: TextStyle::new(Color::BLACK),
2752 };
2753 let mut recolored = run.clone();
2754 recolored.style.color = Color::WHITE;
2755 let mut bold = run.clone();
2756 bold.style.weight = FontWeight::BOLD;
2757
2758 assert_eq!(
2759 super::stable_text_run_handle(&run),
2760 super::stable_text_run_handle(&recolored)
2761 );
2762 assert_ne!(
2763 super::stable_text_run_handle(&run),
2764 super::stable_text_run_handle(&bold)
2765 );
2766 }
2767
2768 #[test]
2769 fn paint_ctx_draw_text_uses_color_override_for_paint_color() {
2770 let text_system = Arc::new(TextSystem::new());
2771 let mut paint = PaintCtx::new(
2772 WindowId::new(12),
2773 WidgetId::new(13),
2774 Rect::new(0.0, 0.0, 120.0, 60.0),
2775 None,
2776 DpiInfo::default(),
2777 Arc::clone(&text_system),
2778 Arc::new(FontRegistry::new()),
2779 Arc::new(ImageRegistry::new()),
2780 );
2781 let paint_color = Color::BLACK;
2782 paint.draw_text(
2783 Rect::new(8.0, 10.0, 80.0, 20.0),
2784 "hello",
2785 TextStyle::new(paint_color),
2786 );
2787
2788 let SceneCommand::DrawShapedText(text) = &paint.scene().commands()[0] else {
2789 panic!("draw_text should emit shaped text when layout succeeds");
2790 };
2791 assert_eq!(text.color_override, Some(paint_color));
2792
2793 let registry = text_system.text_layout_registry();
2794 let layout = text
2795 .resolve(registry.as_ref())
2796 .expect("drawn shaped text should resolve from the registry");
2797 assert_eq!(layout.style().color, Color::WHITE);
2798 }
2799
2800 #[test]
2801 fn paint_ctx_draw_persistent_text_layout_reinserts_pruned_layout() {
2802 let text_system = Arc::new(TextSystem::new());
2803 let layout = text_system
2804 .shape_text_persistent(
2805 None,
2806 "held",
2807 Size::new(80.0, 20.0),
2808 TextStyle::new(Color::WHITE),
2809 &FontRegistry::new(),
2810 )
2811 .unwrap();
2812 text_system.retain_persistent_layouts(&std::collections::HashSet::new());
2813 assert!(!text_system.text_layout_registry().contains(layout.handle()));
2814
2815 let mut paint = PaintCtx::new(
2816 WindowId::new(12),
2817 WidgetId::new(13),
2818 Rect::new(0.0, 0.0, 120.0, 60.0),
2819 None,
2820 DpiInfo::default(),
2821 Arc::clone(&text_system),
2822 Arc::new(FontRegistry::new()),
2823 Arc::new(ImageRegistry::new()),
2824 );
2825 paint.draw_persistent_text_layout(Point::ZERO, &layout);
2826
2827 assert!(text_system.text_layout_registry().contains(layout.handle()));
2828 assert!(matches!(
2829 paint.scene().commands()[0],
2830 SceneCommand::DrawShapedText(_)
2831 ));
2832 }
2833
2834 #[test]
2835 fn text_layout_shapes_in_measure_and_paints_as_shaped_scene_output() {
2836 let layout = measure_ctx(WindowId::new(13), WidgetId::new(14))
2837 .layout()
2838 .shape_text(
2839 "hello",
2840 sui_core::Size::new(80.0, 20.0),
2841 TextStyle::new(Color::BLACK),
2842 )
2843 .unwrap();
2844
2845 let mut paint = PaintCtx::new(
2846 WindowId::new(13),
2847 WidgetId::new(14),
2848 Rect::new(0.0, 0.0, 120.0, 60.0),
2849 None,
2850 DpiInfo::default(),
2851 Arc::new(TextSystem::new()),
2852 Arc::new(FontRegistry::new()),
2853 Arc::new(ImageRegistry::new()),
2854 );
2855 let origin = Point::new(8.0, 10.0);
2856 paint.draw_text_layout(origin, &layout);
2857 paint.set_ime_composition_rect(layout.caret_rect(3).translate(origin.to_vector()));
2858
2859 assert!(matches!(
2860 paint.scene().commands()[0],
2861 SceneCommand::DrawShapedText(_)
2862 ));
2863 assert!(paint.ime_composition_rect().is_some());
2864 assert!(!layout.selection_rects(1..4).is_empty());
2865 }
2866}