1#![forbid(unsafe_code)]
2
3mod diagnostics;
4mod logo;
5mod widget;
6
7use std::{
8 collections::{BTreeSet, HashMap, HashSet, VecDeque},
9 sync::{
10 Arc,
11 atomic::{AtomicU64, Ordering},
12 },
13};
14
15use sui_core::{
16 AsyncWakeToken, Clipboard, ClipboardBackend, CustomEvent, DirtyRegion, DragEvent,
17 DragEventKind, DragOutcome, DragPayload, DragScopeId, DragSessionId, DropEffect, Error, Event,
18 FontHandle, ImageHandle, InvalidationKind, InvalidationRequest, InvalidationTarget, KeyState,
19 Point, PointerButton, PointerButtons, PointerEvent, PointerEventKind, Rect, Result,
20 SemanticsActionRequest, SemanticsEvent, SemanticsNode, Size, TimerToken, Vector, WakeEvent,
21 WidgetId, WindowEvent, WindowId,
22};
23use sui_layout::Constraints;
24use sui_scene::{
25 ImageRegistry, LayerCompositionMode, RegisteredImage, Scene, SceneCommand, SceneFrame,
26 SceneLayer, SceneLayerDescriptor, SceneLayerUpdate, SceneLayerUpdateKind,
27};
28use sui_text::{FontRegistry, RegisteredFont, TextLayoutHandle, TextSystem};
29use web_time::Instant;
30
31pub use diagnostics::{
32 CacheMetrics, CacheMetricsDelta, FramePhase, FramePhaseSample, PresentationLatencyDiagnostics,
33 RenderDiagnostics, RendererSubmissionDiagnostics, RetainedPacketHotspotDiagnostics,
34 RetainedPacketRebuildDiagnostics, SceneStatistics, SceneStatisticsDetailMode,
35 TextCacheDeltaDiagnostics, TextCacheDiagnostics, WidgetTimingPhase, WidgetTimingSample,
36 WindowColorManagementMode, WindowDynamicRangeMode, WindowOutputColorPrimaries,
37 WindowPerformanceSnapshot, WindowPerformanceSummary, WindowRenderOptions, WindowStemDarkening,
38 WindowTextCoveragePolicy, WindowTextHinting, WindowTextSubpixelOrder, WindowToneMappingMode,
39 clear_window_performance_snapshot, clear_window_performance_snapshots,
40 clear_window_render_options, publish_window_performance_snapshot, set_window_render_options,
41 set_window_scene_statistics_detail_mode, window_performance_snapshot,
42 window_performance_summary, window_performance_text_caches, window_render_options,
43 window_scene_statistics_detail_mode,
44};
45pub use logo::{DEFAULT_SUI_LOGO_SVG, default_sui_logo_image};
46use std::rc::Rc;
47pub use sui_core::DpiInfo;
48pub use sui_layout::LayoutContext;
49use widget::MeasureScope;
50pub use widget::{
51 ArrangeCtx, EventCtx, EventPhase, LayerOptions, MeasureCtx, PaintBoundaryMode, PaintCtx,
52 SemanticsCtx, SingleChild, StackHostOptions, StackOrderPolicy, StackSurfaceOptions, Widget,
53 WidgetChildren, WidgetPod, WidgetPodMutVisitor, WidgetPodVisitor,
54};
55use widget::{
56 BeginDragRequest, DragRequest, DropAcceptanceRequest, FocusRequest, PaintImageResource,
57 PointerCaptureRequest, WakeRequest,
58};
59
60type PaintOutput = (
61 Scene,
62 Vec<(ImageHandle, PaintImageResource)>,
63 HashMap<WidgetId, Rect>,
64 Vec<InvalidationRequest>,
65 Option<Rect>,
66);
67
68static NEXT_WINDOW_ID: AtomicU64 = AtomicU64::new(1);
69
70pub struct WindowBuilder {
71 title: String,
72 icon: Option<WindowIcon>,
73 root: Option<WidgetPod>,
74}
75
76impl WindowBuilder {
77 pub fn new() -> Self {
78 Self {
79 title: "SUI Window".to_string(),
80 icon: Some(WindowIcon::sui()),
81 root: None,
82 }
83 }
84
85 pub fn title(mut self, title: impl Into<String>) -> Self {
86 self.title = title.into();
87 self
88 }
89
90 pub fn icon(mut self, icon: WindowIcon) -> Self {
91 self.icon = Some(icon);
92 self
93 }
94
95 pub fn icon_svg(mut self, svg: impl Into<Vec<u8>>) -> Self {
96 self.icon = Some(WindowIcon::from_svg(svg));
97 self
98 }
99
100 pub fn without_icon(mut self) -> Self {
101 self.icon = None;
102 self
103 }
104
105 pub fn root<W>(mut self, root: W) -> Self
106 where
107 W: Widget + 'static,
108 {
109 self.root = Some(WidgetPod::new(root));
110 self
111 }
112
113 fn build(self, window_id: WindowId) -> Result<WindowState> {
114 let root = self
115 .root
116 .ok_or_else(|| Error::new("window root widget must be set before building"))?;
117
118 Ok(WindowState::new(window_id, self.title, self.icon, root))
119 }
120}
121
122impl Default for WindowBuilder {
123 fn default() -> Self {
124 Self::new()
125 }
126}
127
128#[derive(Debug, Clone, PartialEq, Eq)]
129pub enum WindowIcon {
130 Svg {
131 data: Arc<[u8]>,
132 },
133 Rgba8 {
134 width: u32,
135 height: u32,
136 data: Arc<[u8]>,
137 },
138}
139
140impl WindowIcon {
141 pub fn sui() -> Self {
142 Self::from_svg(DEFAULT_SUI_LOGO_SVG)
143 }
144
145 pub fn from_svg(svg: impl Into<Vec<u8>>) -> Self {
146 Self::Svg {
147 data: Arc::from(svg.into()),
148 }
149 }
150
151 pub fn from_rgba8(width: u32, height: u32, data: impl Into<Vec<u8>>) -> Result<Self> {
152 if width == 0 || height == 0 {
153 return Err(Error::new("window icon dimensions must be non-zero"));
154 }
155
156 let data = data.into();
157 let expected_len = (width as usize)
158 .checked_mul(height as usize)
159 .and_then(|pixels| pixels.checked_mul(4))
160 .ok_or_else(|| Error::new("window icon dimensions overflow RGBA buffer length"))?;
161
162 if data.len() != expected_len {
163 return Err(Error::new(format!(
164 "window icon RGBA buffer length mismatch: expected {expected_len}, got {}",
165 data.len()
166 )));
167 }
168
169 Ok(Self::Rgba8 {
170 width,
171 height,
172 data: Arc::from(data),
173 })
174 }
175
176 pub fn as_svg(&self) -> Option<&[u8]> {
177 match self {
178 Self::Svg { data } => Some(data),
179 Self::Rgba8 { .. } => None,
180 }
181 }
182
183 pub fn as_rgba8(&self) -> Option<(u32, u32, &[u8])> {
184 match self {
185 Self::Svg { .. } => None,
186 Self::Rgba8 {
187 width,
188 height,
189 data,
190 } => Some((*width, *height, data)),
191 }
192 }
193}
194
195impl Default for WindowIcon {
196 fn default() -> Self {
197 Self::sui()
198 }
199}
200
201#[derive(Debug, Clone, Copy, PartialEq, Eq)]
202pub struct EmbeddedSvgImageResource {
203 handle: ImageHandle,
204 data: &'static [u8],
205 size: Option<(u32, u32)>,
206}
207
208impl EmbeddedSvgImageResource {
209 pub const fn new(handle: ImageHandle, data: &'static [u8]) -> Self {
210 Self {
211 handle,
212 data,
213 size: None,
214 }
215 }
216
217 pub const fn at_size(
218 handle: ImageHandle,
219 width: u32,
220 height: u32,
221 data: &'static [u8],
222 ) -> Self {
223 Self {
224 handle,
225 data,
226 size: Some((width, height)),
227 }
228 }
229
230 pub const fn handle(self) -> ImageHandle {
231 self.handle
232 }
233
234 pub const fn data(self) -> &'static [u8] {
235 self.data
236 }
237
238 pub const fn size(self) -> Option<(u32, u32)> {
239 self.size
240 }
241
242 pub fn registered_image(self) -> Result<RegisteredImage> {
243 match self.size {
244 Some((width, height)) => RegisteredImage::from_svg_at_size(width, height, self.data),
245 None => RegisteredImage::from_svg(self.data),
246 }
247 }
248}
249
250pub struct Application {
251 windows: Vec<WindowBuilder>,
252 next_font_id: u64,
253 next_image_id: u64,
254 font_registry: Arc<FontRegistry>,
255 image_registry: Arc<ImageRegistry>,
256}
257
258impl Application {
259 pub fn new() -> Self {
260 Self::default()
261 }
262
263 pub fn window(mut self, window: WindowBuilder) -> Self {
264 self.windows.push(window);
265 self
266 }
267
268 pub fn register_font(&mut self, handle: FontHandle, font: RegisteredFont) -> Result<()> {
269 if Arc::make_mut(&mut self.font_registry)
270 .insert(handle, font)
271 .is_some()
272 {
273 return Err(Error::new(format!(
274 "font handle {} is already registered",
275 handle.get()
276 )));
277 }
278
279 self.next_font_id = self.next_font_id.max(handle.get() + 1);
280 Ok(())
281 }
282
283 pub fn register_font_bytes(&mut self, data: impl Into<Vec<u8>>) -> Result<FontHandle> {
284 let handle = FontHandle::new(self.next_font_id.max(1));
285 self.next_font_id = handle.get() + 1;
286 self.register_font(handle, RegisteredFont::from_bytes(data))?;
287 Ok(handle)
288 }
289
290 pub fn register_image(&mut self, handle: ImageHandle, image: RegisteredImage) -> Result<()> {
291 if Arc::make_mut(&mut self.image_registry)
292 .insert(handle, image)
293 .is_some()
294 {
295 return Err(Error::new(format!(
296 "image handle {} is already registered",
297 handle.get()
298 )));
299 }
300
301 self.next_image_id = self.next_image_id.max(handle.get() + 1);
302 Ok(())
303 }
304
305 pub fn register_svg_image_with_handle(
306 &mut self,
307 handle: ImageHandle,
308 data: impl AsRef<[u8]>,
309 ) -> Result<()> {
310 self.register_image(handle, RegisteredImage::from_svg(data)?)
311 }
312
313 pub fn register_rgba_image(
314 &mut self,
315 width: u32,
316 height: u32,
317 data: impl Into<Vec<u8>>,
318 ) -> Result<ImageHandle> {
319 let handle = ImageHandle::new(self.next_image_id.max(1));
320 self.next_image_id = handle.get() + 1;
321 self.register_image(handle, RegisteredImage::from_rgba8(width, height, data)?)?;
322 Ok(handle)
323 }
324
325 pub fn register_svg_image(&mut self, data: impl AsRef<[u8]>) -> Result<ImageHandle> {
326 let handle = ImageHandle::new(self.next_image_id.max(1));
327 self.next_image_id = handle.get() + 1;
328 self.register_image(handle, RegisteredImage::from_svg(data)?)?;
329 Ok(handle)
330 }
331
332 pub fn register_svg_image_at_size_with_handle(
333 &mut self,
334 handle: ImageHandle,
335 width: u32,
336 height: u32,
337 data: impl AsRef<[u8]>,
338 ) -> Result<()> {
339 self.register_image(
340 handle,
341 RegisteredImage::from_svg_at_size(width, height, data)?,
342 )
343 }
344
345 pub fn register_svg_image_at_size(
346 &mut self,
347 width: u32,
348 height: u32,
349 data: impl AsRef<[u8]>,
350 ) -> Result<ImageHandle> {
351 let handle = ImageHandle::new(self.next_image_id.max(1));
352 self.next_image_id = handle.get() + 1;
353 self.register_image(
354 handle,
355 RegisteredImage::from_svg_at_size(width, height, data)?,
356 )?;
357 Ok(handle)
358 }
359
360 pub fn register_embedded_svg_image(
361 &mut self,
362 resource: EmbeddedSvgImageResource,
363 ) -> Result<()> {
364 self.register_image(resource.handle(), resource.registered_image()?)
365 }
366
367 pub fn register_embedded_svg_images(
368 &mut self,
369 resources: impl IntoIterator<Item = EmbeddedSvgImageResource>,
370 ) -> Result<()> {
371 for resource in resources {
372 self.register_embedded_svg_image(resource)?;
373 }
374 Ok(())
375 }
376
377 pub fn build(self) -> Result<Runtime> {
378 let mut runtime = Runtime::with_registries(
379 self.next_font_id,
380 self.font_registry,
381 self.next_image_id,
382 self.image_registry,
383 );
384
385 for window in self.windows {
386 runtime.add_window(window)?;
387 }
388
389 Ok(runtime)
390 }
391}
392
393impl Default for Application {
394 fn default() -> Self {
395 Self {
396 windows: Vec::new(),
397 next_font_id: 1,
398 next_image_id: 1,
399 font_registry: Arc::new(FontRegistry::new()),
400 image_registry: Arc::new(ImageRegistry::new()),
401 }
402 }
403}
404
405pub const EXTERNAL_WAKE_KIND: &str = "sui.external.wake";
409
410pub struct Runtime {
411 next_font_id: u64,
412 next_image_id: u64,
413 font_registry: Arc<FontRegistry>,
414 image_registry: Arc<ImageRegistry>,
415 text_system: Arc<TextSystem>,
416 clipboard: Clipboard,
417 windows: Vec<WindowState>,
418}
419
420impl Runtime {
421 pub fn new() -> Self {
422 Self::with_registries(
423 1,
424 Arc::new(FontRegistry::new()),
425 1,
426 Arc::new(ImageRegistry::new()),
427 )
428 }
429
430 fn with_registries(
431 next_font_id: u64,
432 font_registry: Arc<FontRegistry>,
433 next_image_id: u64,
434 image_registry: Arc<ImageRegistry>,
435 ) -> Self {
436 Self {
437 next_font_id: next_font_id.max(1),
438 next_image_id: next_image_id.max(1),
439 font_registry,
440 image_registry,
441 text_system: Arc::new(TextSystem::new()),
442 clipboard: Clipboard::new(),
443 windows: Vec::new(),
444 }
445 }
446
447 pub fn add_window(&mut self, builder: WindowBuilder) -> Result<WindowId> {
448 let window_id = self.alloc_window_id();
449 let mut window = builder.build(window_id)?;
450 window.clipboard = self.clipboard.clone();
451 self.windows.push(window);
452 Ok(window_id)
453 }
454
455 pub fn clipboard(&self) -> Clipboard {
457 self.clipboard.clone()
458 }
459
460 pub fn set_clipboard_backend(&self, backend: impl ClipboardBackend + 'static) {
463 self.clipboard.set_backend(backend);
464 }
465
466 pub fn remove_window(&mut self, window_id: WindowId) -> Result<()> {
467 let Some(window_index) = self
468 .windows
469 .iter()
470 .position(|window| window.id == window_id)
471 else {
472 return Err(Error::new(format!(
473 "window {} does not exist",
474 window_id.get()
475 )));
476 };
477
478 self.windows.remove(window_index);
479 clear_window_performance_snapshot(window_id);
480 Ok(())
481 }
482
483 pub fn handle_event(&mut self, window_id: WindowId, event: Event) -> Result<()> {
484 let text_system = Arc::clone(&self.text_system);
485 let font_registry = Arc::clone(&self.font_registry);
486 let image_registry = Arc::clone(&self.image_registry);
487 let window = self.window_mut(window_id)?;
488 window.handle_event(event, text_system, font_registry, image_registry);
489 Ok(())
490 }
491
492 pub fn handle_semantics_action(
501 &mut self,
502 window_id: WindowId,
503 target: WidgetId,
504 action: SemanticsActionRequest,
505 ) -> Result<bool> {
506 let text_system = Arc::clone(&self.text_system);
507 let font_registry = Arc::clone(&self.font_registry);
508 let image_registry = Arc::clone(&self.image_registry);
509 let window = self.window_mut(window_id)?;
510 Ok(window.handle_semantics_action(
511 target,
512 action,
513 text_system,
514 font_registry,
515 image_registry,
516 ))
517 }
518
519 pub fn tick(&mut self, frame_time: f64) {
520 for window in &mut self.windows {
521 window.last_tick_time = frame_time;
522 }
523 }
524
525 pub fn drain_ready_events(&mut self) -> Vec<(WindowId, Event)> {
526 let mut ready = Vec::new();
527
528 for window in &mut self.windows {
529 let window_id = window.id;
530 ready.extend(
531 window
532 .drain_ready_events()
533 .into_iter()
534 .map(|event| (window_id, event)),
535 );
536 }
537
538 ready
539 }
540
541 pub fn next_wakeup_time(&self, window_id: WindowId) -> Result<Option<f64>> {
542 let window = self.window(window_id)?;
543 Ok(window.next_wakeup_time())
544 }
545
546 pub fn wake_async(&mut self, window_id: WindowId, token: AsyncWakeToken) -> Result<bool> {
547 let window = self.window_mut(window_id)?;
548 Ok(window.wake_async(token))
549 }
550
551 pub fn wake_root(&mut self, window_id: WindowId) -> Result<()> {
556 self.handle_event(
557 window_id,
558 Event::Custom(CustomEvent::new(EXTERNAL_WAKE_KIND)),
559 )
560 }
561
562 pub fn register_font(&mut self, handle: FontHandle, font: RegisteredFont) -> Result<()> {
563 if Arc::make_mut(&mut self.font_registry)
564 .insert(handle, font)
565 .is_some()
566 {
567 return Err(Error::new(format!(
568 "font handle {} is already registered",
569 handle.get()
570 )));
571 }
572
573 self.next_font_id = self.next_font_id.max(handle.get() + 1);
574 Ok(())
575 }
576
577 pub fn register_font_bytes(&mut self, data: impl Into<Vec<u8>>) -> Result<FontHandle> {
578 let handle = FontHandle::new(self.next_font_id.max(1));
579 self.next_font_id = handle.get() + 1;
580 self.register_font(handle, RegisteredFont::from_bytes(data))?;
581 Ok(handle)
582 }
583
584 pub fn register_image(&mut self, handle: ImageHandle, image: RegisteredImage) -> Result<()> {
585 if Arc::make_mut(&mut self.image_registry)
586 .insert(handle, image)
587 .is_some()
588 {
589 return Err(Error::new(format!(
590 "image handle {} is already registered",
591 handle.get()
592 )));
593 }
594
595 self.next_image_id = self.next_image_id.max(handle.get() + 1);
596 Ok(())
597 }
598
599 pub fn register_svg_image_with_handle(
600 &mut self,
601 handle: ImageHandle,
602 data: impl AsRef<[u8]>,
603 ) -> Result<()> {
604 self.register_image(handle, RegisteredImage::from_svg(data)?)
605 }
606
607 pub fn register_rgba_image(
608 &mut self,
609 width: u32,
610 height: u32,
611 data: impl Into<Vec<u8>>,
612 ) -> Result<ImageHandle> {
613 let handle = ImageHandle::new(self.next_image_id.max(1));
614 self.next_image_id = handle.get() + 1;
615 self.register_image(handle, RegisteredImage::from_rgba8(width, height, data)?)?;
616 Ok(handle)
617 }
618
619 pub fn register_svg_image(&mut self, data: impl AsRef<[u8]>) -> Result<ImageHandle> {
620 let handle = ImageHandle::new(self.next_image_id.max(1));
621 self.next_image_id = handle.get() + 1;
622 self.register_image(handle, RegisteredImage::from_svg(data)?)?;
623 Ok(handle)
624 }
625
626 pub fn register_svg_image_at_size_with_handle(
627 &mut self,
628 handle: ImageHandle,
629 width: u32,
630 height: u32,
631 data: impl AsRef<[u8]>,
632 ) -> Result<()> {
633 self.register_image(
634 handle,
635 RegisteredImage::from_svg_at_size(width, height, data)?,
636 )
637 }
638
639 pub fn register_svg_image_at_size(
640 &mut self,
641 width: u32,
642 height: u32,
643 data: impl AsRef<[u8]>,
644 ) -> Result<ImageHandle> {
645 let handle = ImageHandle::new(self.next_image_id.max(1));
646 self.next_image_id = handle.get() + 1;
647 self.register_image(
648 handle,
649 RegisteredImage::from_svg_at_size(width, height, data)?,
650 )?;
651 Ok(handle)
652 }
653
654 pub fn register_embedded_svg_image(
655 &mut self,
656 resource: EmbeddedSvgImageResource,
657 ) -> Result<()> {
658 self.register_image(resource.handle(), resource.registered_image()?)
659 }
660
661 pub fn register_embedded_svg_images(
662 &mut self,
663 resources: impl IntoIterator<Item = EmbeddedSvgImageResource>,
664 ) -> Result<()> {
665 for resource in resources {
666 self.register_embedded_svg_image(resource)?;
667 }
668 Ok(())
669 }
670
671 pub fn font_registry(&self) -> &Arc<FontRegistry> {
672 &self.font_registry
673 }
674
675 pub fn image_registry(&self) -> &Arc<ImageRegistry> {
676 &self.image_registry
677 }
678
679 pub fn render(&mut self, window_id: WindowId) -> Result<RenderOutput> {
680 let text_system = Arc::clone(&self.text_system);
681 let font_registry = Arc::clone(&self.font_registry);
682 let image_registry = Arc::clone(&self.image_registry);
683 let window = self.window_mut(window_id)?;
684 Ok(window.render(text_system, font_registry, image_registry))
685 }
686
687 pub fn semantics(&self, window_id: WindowId) -> Result<&[SemanticsNode]> {
688 let window = self.window(window_id)?;
689 Ok(&window.last_semantics)
690 }
691
692 pub fn window_title(&self, window_id: WindowId) -> Result<&str> {
693 let window = self.window(window_id)?;
694 Ok(&window.title)
695 }
696
697 pub fn window_icon(&self, window_id: WindowId) -> Result<Option<&WindowIcon>> {
698 let window = self.window(window_id)?;
699 Ok(window.icon.as_ref())
700 }
701
702 pub fn window_ids(&self) -> Vec<WindowId> {
703 self.windows.iter().map(|window| window.id).collect()
704 }
705
706 pub fn needs_render(&self, window_id: WindowId) -> Result<bool> {
707 let window = self.window(window_id)?;
708 Ok(window.needs_render())
709 }
710
711 pub fn schedule(&self, window_id: WindowId) -> Result<FrameSchedule> {
712 let window = self.window(window_id)?;
713 Ok(window.schedule)
714 }
715
716 pub fn focus_state(&self, window_id: WindowId) -> Result<FocusState> {
717 let window = self.window(window_id)?;
718 Ok(window.focus)
719 }
720
721 pub fn focused_widget(&self, window_id: WindowId) -> Result<Option<WidgetId>> {
722 Ok(self.focus_state(window_id)?.focused_widget)
723 }
724
725 pub fn pointer_capture_target(
726 &self,
727 window_id: WindowId,
728 pointer_id: u64,
729 ) -> Result<Option<WidgetId>> {
730 let window = self.window(window_id)?;
731 Ok(window.pointer_capture.get(&pointer_id).copied())
732 }
733
734 pub fn widget_graph(&self, window_id: WindowId) -> Result<WidgetGraphSnapshot> {
735 let window = self.window(window_id)?;
736 Ok(window.graph.snapshot())
737 }
738
739 fn alloc_window_id(&mut self) -> WindowId {
740 WindowId::new(NEXT_WINDOW_ID.fetch_add(1, Ordering::Relaxed))
741 }
742
743 fn window(&self, window_id: WindowId) -> Result<&WindowState> {
744 self.windows
745 .iter()
746 .find(|window| window.id == window_id)
747 .ok_or_else(|| Error::new(format!("window {} does not exist", window_id.get())))
748 }
749
750 fn window_mut(&mut self, window_id: WindowId) -> Result<&mut WindowState> {
751 self.windows
752 .iter_mut()
753 .find(|window| window.id == window_id)
754 .ok_or_else(|| Error::new(format!("window {} does not exist", window_id.get())))
755 }
756}
757
758impl Default for Runtime {
759 fn default() -> Self {
760 Self::new()
761 }
762}
763
764#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
765pub struct FocusState {
766 pub focused_widget: Option<WidgetId>,
767 pub window_focused: bool,
768}
769
770#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
771pub struct FrameSchedule {
772 pub measure: bool,
773 pub arrange: bool,
774 pub ordering: bool,
775 pub paint: bool,
776 pub semantics: bool,
777 pub hit_test: bool,
778 pub text: bool,
779 pub resources: bool,
780}
781
782impl FrameSchedule {
783 fn bootstrap() -> Self {
784 Self {
785 measure: true,
786 arrange: true,
787 ordering: false,
788 paint: true,
789 semantics: true,
790 hit_test: true,
791 text: false,
792 resources: false,
793 }
794 }
795
796 pub const fn any(self) -> bool {
797 self.measure
798 || self.arrange
799 || self.ordering
800 || self.paint
801 || self.semantics
802 || self.hit_test
803 || self.text
804 || self.resources
805 }
806
807 pub const fn needs_render(self) -> bool {
808 self.measure
809 || self.arrange
810 || self.ordering
811 || self.paint
812 || self.semantics
813 || self.text
814 || self.resources
815 }
816
817 fn clear(&mut self) {
818 *self = Self::default();
819 }
820
821 fn mark(&mut self, kind: InvalidationKind) {
822 match kind {
823 InvalidationKind::Measure => {
824 self.measure = true;
825 self.arrange = true;
826 self.ordering = true;
827 self.paint = true;
828 self.hit_test = true;
829 self.semantics = true;
830 }
831 InvalidationKind::Arrange
832 | InvalidationKind::Transform
833 | InvalidationKind::Clip
834 | InvalidationKind::Visibility => {
835 self.ordering = true;
836 self.arrange = true;
837 self.paint = true;
838 self.hit_test = true;
839 self.semantics = true;
840 }
841 InvalidationKind::Ordering => {
842 self.ordering = true;
843 self.hit_test = true;
844 }
845 InvalidationKind::Effect => {
846 self.paint = true;
847 }
848 InvalidationKind::Paint => {
849 self.paint = true;
850 }
851 InvalidationKind::HitTest => {
852 self.hit_test = true;
853 }
854 InvalidationKind::Text => {
855 self.text = true;
856 self.measure = true;
857 self.arrange = true;
858 self.paint = true;
859 self.semantics = true;
860 }
861 InvalidationKind::Semantics => {
862 self.semantics = true;
863 }
864 InvalidationKind::Resources => {
865 self.resources = true;
866 self.paint = true;
867 }
868 }
869 }
870
871 fn extend(&mut self, invalidations: &[InvalidationRequest]) {
872 for request in invalidations {
873 self.mark(request.kind);
874 }
875 }
876}
877
878#[derive(Debug, Clone, PartialEq)]
879pub struct WidgetGeometrySnapshot {
880 pub layout_bounds: Rect,
881 pub input_bounds: Rect,
882 pub paint_bounds: Rect,
883}
884
885impl WidgetGeometrySnapshot {
886 pub const fn new(layout_bounds: Rect, input_bounds: Rect, paint_bounds: Rect) -> Self {
887 Self {
888 layout_bounds,
889 input_bounds,
890 paint_bounds,
891 }
892 }
893}
894
895#[derive(Debug, Clone, PartialEq)]
896pub struct WidgetNodeSnapshot {
897 pub id: WidgetId,
898 pub parent: Option<WidgetId>,
899 pub children: Vec<WidgetId>,
900 pub measured_size: Size,
901 pub geometry: WidgetGeometrySnapshot,
902 pub bounds: Rect,
904 pub paint_boundary: PaintBoundaryMode,
905 pub stack_host: WidgetId,
906 pub stack_surface: WidgetId,
907 pub stack_surface_order: usize,
908 pub transient_owner_surface: Option<WidgetId>,
909 pub is_stack_host: bool,
910 pub is_stack_surface: bool,
911 pub hit_test: bool,
912 pub stack_order_policy: StackOrderPolicy,
913 pub accepts_focus: bool,
914 pub focused: bool,
915}
916
917#[derive(Debug, Clone, PartialEq)]
918pub struct StackHostSnapshot {
919 pub host: WidgetId,
920 pub order_policy: StackOrderPolicy,
921 pub surfaces: Vec<WidgetId>,
922}
923
924#[derive(Debug, Clone, PartialEq)]
925pub struct WidgetGraphSnapshot {
926 pub root: WidgetId,
927 pub nodes: Vec<WidgetNodeSnapshot>,
928 pub stack_hosts: Vec<StackHostSnapshot>,
929}
930
931#[derive(Debug, Clone, Copy, PartialEq)]
932struct ScheduledTimer {
933 token: TimerToken,
934 deadline: f64,
935 target: WidgetId,
936}
937
938#[derive(Debug, Clone, Copy, PartialEq)]
939struct LayerTranslation {
940 widget_id: WidgetId,
941 delta: Vector,
942}
943
944#[derive(Debug, Clone, PartialEq)]
945struct LayerDescriptorRefresh {
946 widget_id: WidgetId,
947 descriptor: SceneLayerDescriptor,
948}
949
950#[derive(Debug, Default)]
951struct GraphChangeSet {
952 repaint_widgets: Vec<WidgetId>,
953 transform_widgets: Vec<LayerTranslation>,
954}
955
956const ANIMATION_FRAME_INTERVAL_SECONDS: f64 = 1.0 / 120.0;
957
958#[derive(Debug, Clone)]
959struct ActiveDrag {
960 session_id: DragSessionId,
961 scope_id: DragScopeId,
962 pointer_id: u64,
963 source: WidgetId,
964 start_position: Point,
965 position: Point,
966 payload: DragPayload,
967 allowed_effect: DropEffect,
968 preview_label: Option<Arc<str>>,
969 hover_path: Vec<WidgetId>,
970 accepted_target: Option<WidgetId>,
971 accepted_effect: DropEffect,
972}
973
974impl ActiveDrag {
975 fn from_request(request: BeginDragRequest) -> Self {
976 Self {
977 session_id: request.session_id,
978 scope_id: request.scope_id,
979 pointer_id: request.pointer_id,
980 source: request.source,
981 start_position: request.position,
982 position: request.position,
983 payload: request.payload,
984 allowed_effect: request.allowed_effect,
985 preview_label: request.preview_label.map(Arc::from),
986 hover_path: Vec::new(),
987 accepted_target: None,
988 accepted_effect: DropEffect::None,
989 }
990 }
991
992 fn event(
993 &self,
994 kind: DragEventKind,
995 position: Point,
996 target: Option<WidgetId>,
997 accepted_effect: DropEffect,
998 outcome: Option<DragOutcome>,
999 ) -> Event {
1000 Event::Drag(DragEvent {
1001 kind,
1002 session_id: self.session_id,
1003 scope_id: self.scope_id,
1004 pointer_id: self.pointer_id,
1005 source: self.source,
1006 target,
1007 position,
1008 start_position: self.start_position,
1009 payload: self.payload.clone(),
1010 allowed_effect: self.allowed_effect,
1011 accepted_effect,
1012 preview_label: self.preview_label.clone(),
1013 outcome,
1014 })
1015 }
1016}
1017
1018struct WindowState {
1019 id: WindowId,
1020 title: String,
1021 icon: Option<WindowIcon>,
1022 root: WidgetPod,
1023 graph: WidgetGraph,
1024 focus: FocusState,
1025 focused_semantics: Option<WidgetId>,
1026 schedule: FrameSchedule,
1027 scale_factor: f32,
1028 raw_dpi: Option<f32>,
1029 viewport_hint: Option<Size>,
1030 viewport: Option<Size>,
1031 last_frame: Option<SceneFrame>,
1032 last_paint_bounds_by_widget: HashMap<WidgetId, Rect>,
1033 last_semantics: Vec<SemanticsNode>,
1034 pending_invalidations: Vec<InvalidationRequest>,
1035 pointer_capture: HashMap<u64, WidgetId>,
1036 last_pointer_events: HashMap<u64, PointerEvent>,
1037 pointer_hover_paths: HashMap<u64, Vec<WidgetId>>,
1038 active_drag: Option<ActiveDrag>,
1039 scheduled_timers: Vec<ScheduledTimer>,
1040 delivering_timers: HashMap<TimerToken, WidgetId>,
1041 async_wake_targets: HashMap<AsyncWakeToken, WidgetId>,
1042 pending_async_wakeups: VecDeque<AsyncWakeToken>,
1043 requested_animation_frames: BTreeSet<WidgetId>,
1044 delivering_animation_frames: VecDeque<WidgetId>,
1045 last_animation_frame_time: Option<f64>,
1046 next_animation_frame_index: u64,
1047 pending_animation_wake_count: usize,
1048 ime_composition_rect: Option<Rect>,
1049 last_tick_time: f64,
1050 clipboard: Clipboard,
1051}
1052
1053impl WindowState {
1054 fn new(id: WindowId, title: String, icon: Option<WindowIcon>, root: WidgetPod) -> Self {
1055 let focus = FocusState {
1056 focused_widget: None,
1057 window_focused: true,
1058 };
1059
1060 Self {
1061 id,
1062 title,
1063 icon,
1064 graph: WidgetGraph::empty(root.id()),
1065 root,
1066 focus,
1067 focused_semantics: None,
1068 schedule: FrameSchedule::bootstrap(),
1069 scale_factor: 1.0,
1070 raw_dpi: None,
1071 viewport_hint: None,
1072 viewport: None,
1073 last_frame: None,
1074 last_paint_bounds_by_widget: HashMap::new(),
1075 last_semantics: Vec::new(),
1076 pending_invalidations: Vec::new(),
1077 pointer_capture: HashMap::new(),
1078 last_pointer_events: HashMap::new(),
1079 pointer_hover_paths: HashMap::new(),
1080 active_drag: None,
1081 scheduled_timers: Vec::new(),
1082 delivering_timers: HashMap::new(),
1083 async_wake_targets: HashMap::new(),
1084 pending_async_wakeups: VecDeque::new(),
1085 requested_animation_frames: BTreeSet::new(),
1086 delivering_animation_frames: VecDeque::new(),
1087 last_animation_frame_time: None,
1088 next_animation_frame_index: 0,
1089 pending_animation_wake_count: 0,
1090 ime_composition_rect: None,
1091 last_tick_time: 0.0,
1092 clipboard: Clipboard::new(),
1093 }
1094 }
1095
1096 fn needs_render(&self) -> bool {
1097 self.last_frame.is_none() || self.schedule.needs_render()
1098 }
1099
1100 fn handle_event(
1101 &mut self,
1102 event: Event,
1103 text_system: Arc<TextSystem>,
1104 font_registry: Arc<FontRegistry>,
1105 image_registry: Arc<ImageRegistry>,
1106 ) {
1107 if matches!(event, Event::Window(WindowEvent::RedrawRequested)) {
1108 diagnostics::begin_widget_timing_collection();
1109 sui_text::begin_text_timing_collection();
1110 }
1111 if matches!(event, Event::Wake(WakeEvent::AnimationFrame { .. })) {
1112 self.pending_animation_wake_count = self.pending_animation_wake_count.saturating_add(1);
1113 }
1114 if let Event::Pointer(pointer) = &event {
1115 self.last_pointer_events
1116 .insert(pointer.pointer_id, pointer.clone());
1117 }
1118
1119 self.preprocess_window_event(&event);
1120 self.ensure_graph_for_event(&event, text_system, font_registry, image_registry);
1121
1122 let captured_target = match &event {
1123 Event::Pointer(pointer) => self.pointer_capture.get(&pointer.pointer_id).copied(),
1124 _ => None,
1125 };
1126
1127 let pointer_hit_target = match &event {
1128 Event::Pointer(pointer) => self.pointer_hit_target(pointer.position),
1129 _ => None,
1130 };
1131 let hit_target = match &event {
1132 Event::Pointer(_) if captured_target.is_some() => None,
1133 Event::Pointer(_) => pointer_hit_target,
1134 _ => None,
1135 };
1136
1137 let mut invalidations = Vec::new();
1138 if matches!(event, Event::Window(WindowEvent::Focused(false))) {
1139 self.cancel_all_pointer_captures(&mut invalidations);
1140 self.pointer_capture.clear();
1141 self.last_pointer_events.clear();
1142 self.active_drag = None;
1143 }
1144 let mut skip_primary_route = false;
1145 if let Event::Pointer(pointer) = &event {
1146 let hover_route = self.update_pointer_hover_path(pointer, hit_target);
1147 self.apply_event_effects(hover_route.effects, &mut invalidations);
1148
1149 if let Some(request) = hover_route.focus_request {
1150 let focus_effects = self.apply_focus_request(request);
1151 self.apply_event_effects(focus_effects, &mut invalidations);
1152 }
1153
1154 skip_primary_route = hover_route.skip_primary_route;
1155 }
1156
1157 if skip_primary_route {
1158 self.finish_event(&event);
1159 self.schedule.extend(&invalidations);
1160 self.pending_invalidations.extend(invalidations);
1161 return;
1162 }
1163
1164 let target = self.resolve_event_target(&event, hit_target);
1165
1166 let route = self.route_event(target, &event);
1167
1168 let focus_request = route
1169 .focus_request
1170 .or_else(|| self.default_focus_request(&event, hit_target, &route.path));
1171 self.apply_event_effects(route.effects, &mut invalidations);
1172
1173 if let Some(request) = focus_request {
1174 let focus_effects = self.apply_focus_request(request);
1175 self.apply_event_effects(focus_effects, &mut invalidations);
1176 }
1177
1178 if let Event::Pointer(pointer) = &event {
1179 let drag_effects = self.handle_drag_pointer_event(pointer, pointer_hit_target);
1180 self.apply_event_effects(drag_effects, &mut invalidations);
1181 }
1182
1183 self.finish_event(&event);
1184 self.schedule.extend(&invalidations);
1185 self.pending_invalidations.extend(invalidations);
1186 }
1187
1188 fn handle_semantics_action(
1189 &mut self,
1190 target: WidgetId,
1191 action: SemanticsActionRequest,
1192 text_system: Arc<TextSystem>,
1193 font_registry: Arc<FontRegistry>,
1194 image_registry: Arc<ImageRegistry>,
1195 ) -> bool {
1196 let Some(node) = self
1197 .last_semantics
1198 .iter()
1199 .find(|node| node.id == target)
1200 .cloned()
1201 else {
1202 return false;
1203 };
1204
1205 if node.state.hidden
1206 || node.state.disabled
1207 || !node.actions.contains(&action.advertised_action())
1208 {
1209 return false;
1210 }
1211
1212 if matches!(
1213 (&action, node.state.expanded),
1214 (SemanticsActionRequest::Expand, Some(true))
1215 | (SemanticsActionRequest::Collapse, Some(false))
1216 ) {
1217 return true;
1218 }
1219
1220 let event = Event::Semantics(SemanticsEvent::new(target, action.clone()));
1221 self.ensure_graph_for_event(
1222 &event,
1223 Arc::clone(&text_system),
1224 Arc::clone(&font_registry),
1225 Arc::clone(&image_registry),
1226 );
1227
1228 let route_target = self.semantics_route_target(target);
1229 let route = self.route_event(route_target, &event);
1230 let handled = route.handled;
1231 let semantics_was_focused = self.focused_semantics == Some(target);
1232 let mut focus_request = route.focus_request;
1233 let widget_requested_focus = matches!(focus_request, Some(FocusRequest::Focus(_)));
1234 let mut focus_succeeded = false;
1235 let mut invalidations = Vec::new();
1236 self.apply_event_effects(route.effects, &mut invalidations);
1237
1238 match action {
1239 SemanticsActionRequest::Focus => {
1240 let runtime_focus_request = focus_request
1241 .is_none()
1242 .then(|| self.focus_request_for(route_target))
1243 .flatten();
1244 focus_succeeded =
1245 handled || widget_requested_focus || runtime_focus_request.is_some();
1246 focus_request = focus_request.or(runtime_focus_request);
1247 }
1248 SemanticsActionRequest::Blur if semantics_was_focused => {
1249 focus_request = Some(FocusRequest::Clear);
1250 }
1251 _ => {}
1252 }
1253
1254 if let Some(request) = focus_request {
1255 let focus_effects = self.apply_focus_request(request);
1256 self.apply_event_effects(focus_effects, &mut invalidations);
1257 }
1258
1259 match action {
1260 SemanticsActionRequest::Focus if focus_succeeded => {
1261 self.focused_semantics = Some(target);
1262 self.schedule.mark(InvalidationKind::Semantics);
1263 }
1264 SemanticsActionRequest::Blur if semantics_was_focused => {
1265 self.focused_semantics = None;
1266 self.schedule.mark(InvalidationKind::Semantics);
1267 }
1268 _ => {}
1269 }
1270
1271 self.schedule.extend(&invalidations);
1272 self.pending_invalidations.extend(invalidations);
1273
1274 let pointer_fallback = matches!(
1275 action,
1276 SemanticsActionRequest::Activate
1277 | SemanticsActionRequest::Expand
1278 | SemanticsActionRequest::Collapse
1279 );
1280 if pointer_fallback && !handled && !node.bounds.is_empty() {
1281 self.dispatch_semantics_pointer_activation(
1282 node.bounds,
1283 text_system,
1284 font_registry,
1285 image_registry,
1286 );
1287 return true;
1288 }
1289
1290 handled
1291 || matches!(action, SemanticsActionRequest::Focus) && focus_succeeded
1292 || matches!(action, SemanticsActionRequest::Blur) && semantics_was_focused
1293 }
1294
1295 fn semantics_route_target(&self, target: WidgetId) -> WidgetId {
1296 let mut current = Some(target);
1297 let mut visited = HashSet::new();
1298
1299 while let Some(candidate) = current {
1300 if !visited.insert(candidate) {
1301 break;
1302 }
1303 if self.graph.contains(candidate) {
1304 return candidate;
1305 }
1306 current = self
1307 .last_semantics
1308 .iter()
1309 .find(|node| node.id == candidate)
1310 .and_then(|node| node.parent);
1311 }
1312
1313 self.root.id()
1314 }
1315
1316 fn focus_request_for(&self, target: WidgetId) -> Option<FocusRequest> {
1317 self.graph.path_to(target).and_then(|path| {
1318 path.into_iter()
1319 .rev()
1320 .find(|widget_id| {
1321 self.graph
1322 .node(*widget_id)
1323 .is_some_and(|node| node.accepts_focus)
1324 })
1325 .map(FocusRequest::Focus)
1326 })
1327 }
1328
1329 fn dispatch_semantics_pointer_activation(
1330 &mut self,
1331 bounds: Rect,
1332 text_system: Arc<TextSystem>,
1333 font_registry: Arc<FontRegistry>,
1334 image_registry: Arc<ImageRegistry>,
1335 ) {
1336 let position = Point::new(
1337 bounds.x() + bounds.width() * 0.5,
1338 bounds.y() + bounds.height() * 0.5,
1339 );
1340
1341 let mut down = PointerEvent::new(PointerEventKind::Down, position);
1342 down.button = Some(PointerButton::Primary);
1343 down.buttons.insert(PointerButton::Primary);
1344 self.handle_event(
1345 Event::Pointer(down),
1346 Arc::clone(&text_system),
1347 Arc::clone(&font_registry),
1348 Arc::clone(&image_registry),
1349 );
1350
1351 let mut up = PointerEvent::new(PointerEventKind::Up, position);
1352 up.button = Some(PointerButton::Primary);
1353 self.handle_event(
1354 Event::Pointer(up),
1355 text_system,
1356 font_registry,
1357 image_registry,
1358 );
1359 }
1360
1361 fn update_pointer_hover_path(
1362 &mut self,
1363 pointer: &PointerEvent,
1364 hit_target: Option<WidgetId>,
1365 ) -> HoverTransitionResult {
1366 let skip_primary_route = matches!(
1367 pointer.kind,
1368 PointerEventKind::Enter | PointerEventKind::Leave
1369 );
1370
1371 let next_path = match pointer.kind {
1372 PointerEventKind::Move | PointerEventKind::Enter
1373 if pointer.buttons.is_empty()
1374 && !self.pointer_capture.contains_key(&pointer.pointer_id) =>
1375 {
1376 self.hover_transition_path(hit_target)
1377 }
1378 PointerEventKind::Leave | PointerEventKind::Cancel => Vec::new(),
1379 _ => {
1380 return HoverTransitionResult {
1381 skip_primary_route,
1382 ..HoverTransitionResult::default()
1383 };
1384 }
1385 };
1386
1387 let previous_path = self
1388 .pointer_hover_paths
1389 .remove(&pointer.pointer_id)
1390 .unwrap_or_default();
1391 if previous_path == next_path {
1392 if !next_path.is_empty() {
1393 self.pointer_hover_paths
1394 .insert(pointer.pointer_id, next_path);
1395 }
1396 return HoverTransitionResult {
1397 skip_primary_route,
1398 ..HoverTransitionResult::default()
1399 };
1400 }
1401
1402 let shared_prefix_len = previous_path
1403 .iter()
1404 .zip(next_path.iter())
1405 .take_while(|(left, right)| left == right)
1406 .count();
1407
1408 let mut result = HoverTransitionResult {
1409 skip_primary_route,
1410 ..HoverTransitionResult::default()
1411 };
1412
1413 let mut leave_pointer = pointer.clone();
1414 leave_pointer.kind = PointerEventKind::Leave;
1415 let leave_event = Event::Pointer(leave_pointer);
1416 for widget_id in previous_path[shared_prefix_len..].iter().rev().copied() {
1417 let dispatch = self.dispatch_direct_event(widget_id, &leave_event);
1418 let dispatch_focus_request = dispatch.focus_request;
1419 result.effects.extend(dispatch);
1420 if dispatch_focus_request.is_some() {
1421 result.focus_request = dispatch_focus_request;
1422 }
1423 }
1424
1425 let mut enter_pointer = pointer.clone();
1426 enter_pointer.kind = PointerEventKind::Enter;
1427 let enter_event = Event::Pointer(enter_pointer);
1428 for widget_id in next_path[shared_prefix_len..].iter().copied() {
1429 let dispatch = self.dispatch_direct_event(widget_id, &enter_event);
1430 let dispatch_focus_request = dispatch.focus_request;
1431 result.effects.extend(dispatch);
1432 if dispatch_focus_request.is_some() {
1433 result.focus_request = dispatch_focus_request;
1434 }
1435 }
1436
1437 if !next_path.is_empty() {
1438 self.pointer_hover_paths
1439 .insert(pointer.pointer_id, next_path);
1440 }
1441
1442 result
1443 }
1444
1445 fn hover_transition_path(&self, hit_target: Option<WidgetId>) -> Vec<WidgetId> {
1446 hit_target
1447 .and_then(|target| self.graph.path_to(target))
1448 .map(|path| path.into_iter().skip(1).collect())
1449 .unwrap_or_default()
1450 }
1451
1452 fn dispatch_direct_event(&mut self, target: WidgetId, event: &Event) -> widget::EventDispatch {
1453 let path = self.graph.path_to(target);
1454 let dpi_info = self.current_dpi_info();
1455 self.root
1456 .dispatch_event_for_path(
1457 path.as_deref().unwrap_or(&[self.root.id()]),
1458 self.id,
1459 dpi_info,
1460 self.last_tick_time,
1461 EventPhase::Target,
1462 self.focus.focused_widget,
1463 &self.clipboard,
1464 event,
1465 )
1466 .or_else(|| {
1467 self.root.dispatch_event_for(
1468 target,
1469 self.id,
1470 dpi_info,
1471 self.last_tick_time,
1472 EventPhase::Target,
1473 self.focus.focused_widget,
1474 &self.clipboard,
1475 event,
1476 )
1477 })
1478 .unwrap_or_else(empty_dispatch)
1479 }
1480
1481 fn pointer_hit_target(&mut self, point: Point) -> Option<WidgetId> {
1482 let floating_hit = self.floating_layer_hit_test(point);
1483 let focused_floating_hit = if floating_hit.is_none() {
1484 self.focused_floating_layer_hit_test(point)
1485 } else {
1486 None
1487 };
1488 floating_hit
1489 .or(focused_floating_hit)
1490 .or_else(|| self.graph.hit_test(point))
1491 }
1492
1493 fn floating_layer_hit_test(&mut self, point: Point) -> Option<WidgetId> {
1494 let effect_hit = {
1495 let scene = self.last_frame.as_ref().map(|frame| &frame.scene)?;
1496 scene_hit_test_for_phase(
1497 scene,
1498 point,
1499 HitTestCompositionPhase::Effect,
1500 HitTestCompositionPhase::Normal,
1501 )
1502 };
1503 if let Some(widget_id) = effect_hit
1504 && self
1505 .current_widget_matches_hit_test_phase(widget_id, HitTestCompositionPhase::Effect)
1506 {
1507 return self
1508 .graph
1509 .hit_test_within(widget_id, point)
1510 .or(Some(widget_id));
1511 }
1512
1513 let overlay_hit = {
1514 let scene = self.last_frame.as_ref().map(|frame| &frame.scene)?;
1515 scene_hit_test_for_phase(
1516 scene,
1517 point,
1518 HitTestCompositionPhase::Overlay,
1519 HitTestCompositionPhase::Normal,
1520 )
1521 };
1522 overlay_hit.and_then(|widget_id| {
1523 self.current_widget_matches_hit_test_phase(widget_id, HitTestCompositionPhase::Overlay)
1524 .then(|| {
1525 self.graph
1526 .hit_test_within(widget_id, point)
1527 .unwrap_or(widget_id)
1528 })
1529 })
1530 }
1531
1532 fn focused_floating_layer_hit_test(&mut self, point: Point) -> Option<WidgetId> {
1533 let focused = self.focus.focused_widget?;
1534 if !self.current_widget_matches_hit_test_phase(focused, HitTestCompositionPhase::Overlay)
1535 && !self.current_widget_matches_hit_test_phase(focused, HitTestCompositionPhase::Effect)
1536 {
1537 return None;
1538 }
1539
1540 let scene = self.last_frame.as_ref().map(|frame| &frame.scene)?;
1541 let descriptor = collect_scene_layers(scene).get(&focused)?.clone();
1542 (descriptor.hit_test && descriptor.paint_bounds.contains(point)).then_some(focused)
1543 }
1544
1545 fn current_widget_matches_hit_test_phase(
1546 &mut self,
1547 widget_id: WidgetId,
1548 target_phase: HitTestCompositionPhase,
1549 ) -> bool {
1550 if !self.graph.node(widget_id).is_some_and(|node| node.hit_test) {
1551 return false;
1552 }
1553 let Some(composition_mode) = self.current_widget_composition_mode(widget_id) else {
1554 return false;
1555 };
1556
1557 next_hit_test_phase(HitTestCompositionPhase::Normal, composition_mode) == target_phase
1558 }
1559
1560 fn current_widget_composition_mode(
1561 &mut self,
1562 widget_id: WidgetId,
1563 ) -> Option<LayerCompositionMode> {
1564 self.root.layer_composition_mode_for(widget_id)
1565 }
1566
1567 fn animation_frame_deadline(&self) -> Option<f64> {
1568 (!self.requested_animation_frames.is_empty()).then_some(
1569 self.last_animation_frame_time
1570 .map_or(self.last_tick_time, |last| {
1571 last + ANIMATION_FRAME_INTERVAL_SECONDS
1572 }),
1573 )
1574 }
1575
1576 fn next_wakeup_time(&self) -> Option<f64> {
1577 let mut next = self
1578 .scheduled_timers
1579 .iter()
1580 .map(|timer| timer.deadline)
1581 .min_by(|left, right| left.total_cmp(right));
1582
1583 if !self.pending_async_wakeups.is_empty() {
1584 next = Some(next.map_or(self.last_tick_time, |deadline| {
1585 deadline.min(self.last_tick_time)
1586 }));
1587 }
1588
1589 if let Some(animation_deadline) = self.animation_frame_deadline() {
1590 next = Some(next.map_or(animation_deadline, |deadline| {
1591 deadline.min(animation_deadline)
1592 }));
1593 }
1594
1595 next
1596 }
1597
1598 fn active_animated_widget_count(&self) -> usize {
1599 self.requested_animation_frames
1600 .iter()
1601 .copied()
1602 .chain(self.delivering_animation_frames.iter().copied())
1603 .collect::<BTreeSet<_>>()
1604 .len()
1605 }
1606
1607 fn animation_frame_is_transform_only(
1608 &self,
1609 repainted: bool,
1610 layer_updates: &[SceneLayerUpdate],
1611 ) -> bool {
1612 !repainted
1613 && !layer_updates.is_empty()
1614 && layer_updates.iter().all(|update| {
1615 matches!(
1616 update.kind,
1617 SceneLayerUpdateKind::Transform
1618 | SceneLayerUpdateKind::Effect
1619 | SceneLayerUpdateKind::Visibility
1620 )
1621 })
1622 }
1623
1624 fn drain_ready_events(&mut self) -> Vec<Event> {
1625 let now = self.last_tick_time;
1626 let mut ready = Vec::new();
1627 let mut pending_timers = Vec::with_capacity(self.scheduled_timers.len());
1628
1629 for timer in self.scheduled_timers.drain(..) {
1630 if timer.deadline <= now {
1631 self.delivering_timers.insert(timer.token, timer.target);
1632 ready.push(Event::Wake(WakeEvent::Timer {
1633 token: timer.token,
1634 time: now,
1635 deadline: timer.deadline,
1636 }));
1637 } else {
1638 pending_timers.push(timer);
1639 }
1640 }
1641 self.scheduled_timers = pending_timers;
1642
1643 while let Some(token) = self.pending_async_wakeups.pop_front() {
1644 if self.async_wake_targets.contains_key(&token) {
1645 ready.push(Event::Wake(WakeEvent::Async { token, time: now }));
1646 }
1647 }
1648
1649 if self
1650 .animation_frame_deadline()
1651 .is_some_and(|deadline| deadline <= now)
1652 {
1653 let delta = self
1654 .last_animation_frame_time
1655 .map(|last| (now - last).max(0.0))
1656 .unwrap_or(0.0);
1657 let frame_index = self.next_animation_frame_index;
1658 self.next_animation_frame_index = self.next_animation_frame_index.saturating_add(1);
1659
1660 let requested = std::mem::take(&mut self.requested_animation_frames);
1661 self.delivering_animation_frames
1662 .extend(requested.iter().copied());
1663 ready.extend(requested.iter().map(|_| {
1664 Event::Wake(WakeEvent::AnimationFrame {
1665 time: now,
1666 delta,
1667 frame_index,
1668 })
1669 }));
1670 self.last_animation_frame_time = Some(now);
1671 } else if self.delivering_animation_frames.is_empty()
1672 && self.requested_animation_frames.is_empty()
1673 {
1674 self.last_animation_frame_time = None;
1675 }
1676
1677 ready
1678 }
1679
1680 fn wake_async(&mut self, token: AsyncWakeToken) -> bool {
1681 if !self.async_wake_targets.contains_key(&token) {
1682 return false;
1683 }
1684
1685 self.pending_async_wakeups.push_back(token);
1686 true
1687 }
1688
1689 fn invalidate_layout_for_viewport_change(&mut self) {
1696 self.schedule.mark(InvalidationKind::Measure);
1697 self.pending_invalidations.push(InvalidationRequest::new(
1698 InvalidationTarget::Window(self.id),
1699 InvalidationKind::Measure,
1700 ));
1701 }
1702
1703 fn preprocess_window_event(&mut self, event: &Event) {
1704 let Event::Window(window_event) = event else {
1705 return;
1706 };
1707
1708 match window_event {
1709 WindowEvent::Resized(size) => {
1710 self.viewport_hint = Some(*size);
1711 self.invalidate_layout_for_viewport_change();
1712 }
1713 WindowEvent::ScaleFactorChanged {
1714 scale_factor,
1715 raw_dpi,
1716 suggested_size,
1717 } => {
1718 self.scale_factor = *scale_factor as f32;
1719 self.raw_dpi = *raw_dpi;
1720 if let Some(size) = suggested_size {
1721 self.viewport_hint = Some(*size);
1722 }
1723 self.invalidate_layout_for_viewport_change();
1724 }
1725 WindowEvent::Focused(focused) => {
1726 self.focus.window_focused = *focused;
1727 }
1728 WindowEvent::RedrawRequested => {
1729 self.schedule.mark(InvalidationKind::Paint);
1730 }
1731 WindowEvent::CloseRequested
1732 | WindowEvent::Occluded(_)
1733 | WindowEvent::ExternalFileHovered(_)
1734 | WindowEvent::ExternalFileHoverCancelled
1735 | WindowEvent::ExternalFileDropped(_) => {}
1736 }
1737 }
1738
1739 fn ensure_graph_for_event(
1740 &mut self,
1741 event: &Event,
1742 text_system: Arc<TextSystem>,
1743 font_registry: Arc<FontRegistry>,
1744 image_registry: Arc<ImageRegistry>,
1745 ) {
1746 if self.schedule.measure || self.schedule.arrange || self.viewport.is_none() {
1747 let scope_source = self.pending_invalidations.clone();
1748 let invalidations = self.run_measure_arrange_pass(
1749 &scope_source,
1750 text_system,
1751 font_registry,
1752 image_registry,
1753 );
1754 self.schedule.extend(&invalidations);
1755 self.pending_invalidations.extend(invalidations);
1756 return;
1757 }
1758
1759 if self.schedule.hit_test || self.graph.is_empty() {
1760 self.refresh_graph();
1761 }
1762
1763 if matches!(event, Event::Keyboard(_) | Event::Ime(_))
1764 && self.focus.focused_widget.is_some()
1765 && !self
1766 .graph
1767 .contains(self.focus.focused_widget.unwrap_or_default())
1768 {
1769 self.focus.focused_widget = None;
1770 self.focused_semantics = None;
1771 }
1772 }
1773
1774 fn resolve_event_target(&self, event: &Event, hit_target: Option<WidgetId>) -> WidgetId {
1775 match event {
1776 Event::Pointer(pointer) => self
1777 .pointer_capture
1778 .get(&pointer.pointer_id)
1779 .copied()
1780 .or(hit_target)
1781 .unwrap_or(self.root.id()),
1782 Event::Keyboard(_) | Event::Ime(_) => {
1783 self.focus.focused_widget.unwrap_or(self.root.id())
1784 }
1785 Event::Semantics(semantics) => self.semantics_route_target(semantics.target),
1786 Event::Wake(wake_event) => self.wake_target(*wake_event).unwrap_or(self.root.id()),
1787 _ => self.root.id(),
1788 }
1789 }
1790
1791 fn wake_target(&self, wake_event: WakeEvent) -> Option<WidgetId> {
1792 match wake_event {
1793 WakeEvent::Timer { token, .. } => self.delivering_timers.get(&token).copied(),
1794 WakeEvent::Async { token, .. } => self.async_wake_targets.get(&token).copied(),
1795 WakeEvent::AnimationFrame { .. } => self.delivering_animation_frames.front().copied(),
1796 }
1797 }
1798
1799 fn apply_event_effects(
1800 &mut self,
1801 effects: EventEffects,
1802 invalidations: &mut Vec<InvalidationRequest>,
1803 ) {
1804 invalidations.extend(effects.invalidations);
1805 self.apply_wake_requests(effects.wake_requests);
1806 self.apply_pointer_capture_requests(effects.pointer_capture_requests, invalidations);
1807 self.apply_drag_requests(effects.drag_requests, invalidations);
1808 self.apply_posted_events(effects.posted_events, invalidations);
1809 }
1810
1811 fn apply_posted_events(
1815 &mut self,
1816 mut posted: Vec<widget::PostedEventRequest>,
1817 invalidations: &mut Vec<InvalidationRequest>,
1818 ) {
1819 const MAX_POSTED_EVENT_ROUNDS: usize = 8;
1820
1821 let mut rounds = 0;
1822 while !posted.is_empty() && rounds < MAX_POSTED_EVENT_ROUNDS {
1823 rounds += 1;
1824 for request in std::mem::take(&mut posted) {
1825 let dispatch = self.dispatch_direct_event(request.target, &request.event);
1826 invalidations.extend(dispatch.invalidations);
1827 self.apply_wake_requests(dispatch.wake_requests);
1828 self.apply_pointer_capture_requests(
1829 dispatch.pointer_capture_requests,
1830 invalidations,
1831 );
1832 self.apply_drag_requests(dispatch.drag_requests, invalidations);
1833 posted.extend(dispatch.posted_events);
1834 if let Some(request) = dispatch.focus_request {
1835 let focus_effects = self.apply_focus_request(request);
1836 invalidations.extend(focus_effects.invalidations);
1837 self.apply_wake_requests(focus_effects.wake_requests);
1838 self.apply_pointer_capture_requests(
1839 focus_effects.pointer_capture_requests,
1840 invalidations,
1841 );
1842 self.apply_drag_requests(focus_effects.drag_requests, invalidations);
1843 posted.extend(focus_effects.posted_events);
1844 }
1845 }
1846 }
1847 }
1848
1849 fn apply_drag_requests(
1850 &mut self,
1851 requests: Vec<DragRequest>,
1852 invalidations: &mut Vec<InvalidationRequest>,
1853 ) {
1854 for request in requests {
1855 match request {
1856 DragRequest::Begin(request) => {
1857 self.active_drag = Some(ActiveDrag::from_request(request));
1858 invalidations.push(InvalidationRequest::new(
1859 InvalidationTarget::Window(self.id),
1860 InvalidationKind::Paint,
1861 ));
1862 }
1863 }
1864 }
1865 }
1866
1867 fn handle_drag_pointer_event(
1868 &mut self,
1869 pointer: &PointerEvent,
1870 hit_target: Option<WidgetId>,
1871 ) -> EventEffects {
1872 if self
1873 .active_drag
1874 .as_ref()
1875 .is_none_or(|drag| drag.pointer_id != pointer.pointer_id)
1876 {
1877 return EventEffects::default();
1878 }
1879
1880 match pointer.kind {
1881 PointerEventKind::Move => self.update_active_drag(pointer.position, hit_target),
1882 PointerEventKind::Up => {
1883 let mut effects = self.update_active_drag(pointer.position, hit_target);
1884 effects.merge(self.finish_active_drag(pointer.position, false));
1885 effects
1886 }
1887 PointerEventKind::Cancel | PointerEventKind::Leave => {
1888 self.finish_active_drag(pointer.position, true)
1889 }
1890 _ => EventEffects::default(),
1891 }
1892 }
1893
1894 fn update_active_drag(
1895 &mut self,
1896 position: Point,
1897 hit_target: Option<WidgetId>,
1898 ) -> EventEffects {
1899 let Some((previous_path, active_snapshot)) = self.active_drag.as_mut().map(|active| {
1900 active.position = position;
1901 (active.hover_path.clone(), active.clone())
1902 }) else {
1903 return EventEffects::default();
1904 };
1905
1906 let next_path = hit_target
1907 .and_then(|target| self.graph.path_to(target))
1908 .unwrap_or_default();
1909
1910 let mut effects = EventEffects::default();
1911 effects.invalidations.push(InvalidationRequest::new(
1912 InvalidationTarget::Window(self.id),
1913 InvalidationKind::Paint,
1914 ));
1915
1916 let shared_prefix_len = previous_path
1917 .iter()
1918 .zip(next_path.iter())
1919 .take_while(|(left, right)| left == right)
1920 .count();
1921
1922 for widget_id in previous_path[shared_prefix_len..].iter().rev().copied() {
1923 let event = active_snapshot.event(
1924 DragEventKind::Leave,
1925 position,
1926 Some(widget_id),
1927 DropEffect::None,
1928 None,
1929 );
1930 effects.extend(self.dispatch_direct_event(widget_id, &event));
1931 }
1932
1933 for widget_id in next_path[shared_prefix_len..].iter().copied() {
1934 let event = active_snapshot.event(
1935 DragEventKind::Enter,
1936 position,
1937 Some(widget_id),
1938 DropEffect::None,
1939 None,
1940 );
1941 effects.extend(self.dispatch_direct_event(widget_id, &event));
1942 }
1943
1944 let mut accepted = None;
1945 if let Some(target) = hit_target {
1946 let event = active_snapshot.event(
1947 DragEventKind::Over,
1948 position,
1949 Some(target),
1950 DropEffect::None,
1951 None,
1952 );
1953 let route = self.route_event(target, &event);
1954 accepted = nearest_drop_acceptance(&route.effects.drop_acceptances, &route.path);
1955 if let Some(request) = route.focus_request {
1956 effects.merge(self.apply_focus_request(request));
1957 }
1958 effects.merge(route.effects);
1959 }
1960
1961 if let Some(active) = self.active_drag.as_mut() {
1962 active.hover_path = next_path;
1963 if let Some(accepted) = accepted {
1964 active.accepted_target = Some(accepted.target);
1965 active.accepted_effect = accepted.effect;
1966 } else {
1967 active.accepted_target = None;
1968 active.accepted_effect = DropEffect::None;
1969 }
1970 }
1971
1972 effects
1973 }
1974
1975 fn finish_active_drag(&mut self, position: Point, cancelled: bool) -> EventEffects {
1976 let Some(active) = self.active_drag.take() else {
1977 return EventEffects::default();
1978 };
1979
1980 let mut effects = EventEffects::default();
1981 let outcome = if !cancelled {
1982 active
1983 .accepted_target
1984 .filter(|_| active.accepted_effect.is_some())
1985 .map(|target| DragOutcome::Dropped {
1986 target,
1987 effect: active.accepted_effect,
1988 })
1989 .unwrap_or(DragOutcome::Cancelled)
1990 } else {
1991 DragOutcome::Cancelled
1992 };
1993
1994 if let DragOutcome::Dropped { target, effect } = outcome {
1995 let event = active.event(
1996 DragEventKind::Drop,
1997 position,
1998 Some(target),
1999 effect,
2000 Some(outcome),
2001 );
2002 effects.extend(self.dispatch_direct_event(target, &event));
2003 }
2004
2005 for widget_id in active.hover_path.iter().rev().copied() {
2006 let event = active.event(
2007 DragEventKind::Leave,
2008 position,
2009 Some(widget_id),
2010 DropEffect::None,
2011 None,
2012 );
2013 effects.extend(self.dispatch_direct_event(widget_id, &event));
2014 }
2015
2016 let end_event = active.event(
2017 DragEventKind::End,
2018 position,
2019 active.accepted_target,
2020 active.accepted_effect,
2021 Some(outcome),
2022 );
2023 effects.extend(self.dispatch_direct_event(active.source, &end_event));
2024 effects.invalidations.push(InvalidationRequest::new(
2025 InvalidationTarget::Window(self.id),
2026 InvalidationKind::Paint,
2027 ));
2028 effects
2029 }
2030
2031 fn apply_wake_requests(&mut self, requests: Vec<WakeRequest>) {
2032 for request in requests {
2033 match request {
2034 WakeRequest::ScheduleTimer {
2035 token,
2036 deadline,
2037 target,
2038 } => {
2039 self.scheduled_timers.retain(|timer| timer.token != token);
2040 self.scheduled_timers.push(ScheduledTimer {
2041 token,
2042 deadline,
2043 target,
2044 });
2045 }
2046 WakeRequest::CancelTimer { token } => {
2047 self.scheduled_timers.retain(|timer| timer.token != token);
2048 self.delivering_timers.remove(&token);
2049 }
2050 WakeRequest::RegisterAsync { token, target } => {
2051 self.async_wake_targets.insert(token, target);
2052 }
2053 WakeRequest::UnregisterAsync { token } => {
2054 self.async_wake_targets.remove(&token);
2055 self.pending_async_wakeups.retain(|queued| *queued != token);
2056 }
2057 WakeRequest::RequestAnimationFrame { target } => {
2058 self.requested_animation_frames.insert(target);
2059 }
2060 }
2061 }
2062 }
2063
2064 fn apply_pointer_capture_requests(
2065 &mut self,
2066 requests: Vec<PointerCaptureRequest>,
2067 invalidations: &mut Vec<InvalidationRequest>,
2068 ) {
2069 for request in requests {
2070 match request {
2071 PointerCaptureRequest::Capture { pointer_id, target } => {
2072 self.reconcile_pointer_capture(pointer_id, Some(target), invalidations);
2073 }
2074 PointerCaptureRequest::Release { pointer_id } => {
2075 self.pointer_capture.remove(&pointer_id);
2076 }
2077 }
2078 }
2079 }
2080
2081 fn cancel_all_pointer_captures(&mut self, invalidations: &mut Vec<InvalidationRequest>) {
2082 let pointer_ids = self.pointer_capture.keys().copied().collect::<Vec<_>>();
2083 for pointer_id in pointer_ids {
2084 self.reconcile_pointer_capture(pointer_id, None, invalidations);
2085 }
2086 }
2087
2088 fn reconcile_pointer_capture(
2089 &mut self,
2090 pointer_id: u64,
2091 requested_target: Option<WidgetId>,
2092 invalidations: &mut Vec<InvalidationRequest>,
2093 ) {
2094 let mut cancelled_owners = HashSet::new();
2095
2096 loop {
2097 let current = self.pointer_capture.get(&pointer_id).copied();
2098 match (current, requested_target) {
2099 (None, Some(target)) => {
2100 self.pointer_capture.insert(pointer_id, target);
2101 return;
2102 }
2103 (None, None) => return,
2104 (Some(owner), Some(target)) if owner == target => return,
2105 (Some(owner), _) => {
2106 self.pointer_capture.remove(&pointer_id);
2107 if !cancelled_owners.insert(owner) {
2108 continue;
2112 }
2113
2114 let cancel = self.pointer_cancel_event(pointer_id);
2115 let dispatch = self.dispatch_direct_event(owner, &Event::Pointer(cancel));
2116 self.apply_pointer_cancel_dispatch(dispatch, invalidations);
2117 }
2118 }
2119 }
2120 }
2121
2122 fn pointer_cancel_event(&self, pointer_id: u64) -> PointerEvent {
2123 let mut pointer = self
2124 .last_pointer_events
2125 .get(&pointer_id)
2126 .cloned()
2127 .unwrap_or_else(|| PointerEvent::new(PointerEventKind::Cancel, Point::ZERO));
2128 pointer.pointer_id = pointer_id;
2129 pointer.kind = PointerEventKind::Cancel;
2130 pointer.delta = Vector::ZERO;
2131 pointer.scroll_delta = None;
2132 pointer.button = None;
2133 pointer.buttons = PointerButtons::NONE;
2134 pointer
2135 }
2136
2137 fn apply_pointer_cancel_dispatch(
2138 &mut self,
2139 dispatch: widget::EventDispatch,
2140 invalidations: &mut Vec<InvalidationRequest>,
2141 ) {
2142 let focus_request = dispatch.focus_request;
2143 let mut effects = EventEffects::default();
2144 effects.extend(dispatch);
2145 self.apply_event_effects(effects, invalidations);
2146
2147 if let Some(request) = focus_request {
2148 let focus_effects = self.apply_focus_request(request);
2149 self.apply_event_effects(focus_effects, invalidations);
2150 }
2151 }
2152
2153 fn finish_event(&mut self, event: &Event) {
2154 match event {
2155 Event::Pointer(pointer)
2156 if matches!(
2157 pointer.kind,
2158 PointerEventKind::Up | PointerEventKind::Cancel
2159 ) =>
2160 {
2161 self.pointer_capture.remove(&pointer.pointer_id);
2162 self.last_pointer_events.remove(&pointer.pointer_id);
2163 }
2164 Event::Wake(WakeEvent::Timer { token, .. }) => {
2165 self.delivering_timers.remove(token);
2166 }
2167 Event::Wake(WakeEvent::AnimationFrame { .. }) => {
2168 self.delivering_animation_frames.pop_front();
2169 if self.delivering_animation_frames.is_empty()
2170 && self.requested_animation_frames.is_empty()
2171 {
2172 self.last_animation_frame_time = None;
2173 }
2174 }
2175 _ => {}
2176 }
2177 }
2178
2179 fn route_event(&mut self, target: WidgetId, event: &Event) -> EventRouteResult {
2180 let path = self
2181 .graph
2182 .path_to(target)
2183 .unwrap_or_else(|| vec![self.root.id()]);
2184 let dpi_info = self.current_dpi_info();
2185 let mut effects = EventEffects::default();
2186 let mut handled = false;
2187 let mut focus_request = None;
2188 let target_only = matches!(event, Event::Wake(_));
2189 let ignore_handled = matches!(event, Event::Drag(_));
2190
2191 if !target_only && path.len() > 1 {
2192 for path_len in 1..path.len() {
2193 let dispatch = self
2194 .root
2195 .dispatch_event_for_path(
2196 &path[..path_len],
2197 self.id,
2198 dpi_info,
2199 self.last_tick_time,
2200 EventPhase::Capture,
2201 self.focus.focused_widget,
2202 &self.clipboard,
2203 event,
2204 )
2205 .unwrap_or_else(empty_dispatch);
2206 let dispatch_handled = dispatch.handled;
2207 let dispatch_focus_request = dispatch.focus_request;
2208 effects.extend(dispatch);
2209 if dispatch_focus_request.is_some() {
2210 focus_request = dispatch_focus_request;
2211 }
2212 if dispatch_handled && !ignore_handled {
2213 handled = true;
2214 break;
2215 }
2216 }
2217 }
2218
2219 if !handled || ignore_handled {
2220 let dispatch = self
2221 .root
2222 .dispatch_event_for_path(
2223 &path,
2224 self.id,
2225 dpi_info,
2226 self.last_tick_time,
2227 EventPhase::Target,
2228 self.focus.focused_widget,
2229 &self.clipboard,
2230 event,
2231 )
2232 .or_else(|| {
2233 self.root.dispatch_event_for(
2234 target,
2235 self.id,
2236 dpi_info,
2237 self.last_tick_time,
2238 EventPhase::Target,
2239 self.focus.focused_widget,
2240 &self.clipboard,
2241 event,
2242 )
2243 })
2244 .unwrap_or_else(empty_dispatch);
2245 let dispatch_handled = dispatch.handled;
2246 let dispatch_focus_request = dispatch.focus_request;
2247 effects.extend(dispatch);
2248 if dispatch_focus_request.is_some() {
2249 focus_request = dispatch_focus_request;
2250 }
2251 handled = dispatch_handled && !ignore_handled;
2252 }
2253
2254 if !target_only && (!handled || ignore_handled) && path.len() > 1 {
2255 for path_len in (1..path.len()).rev() {
2256 let dispatch = self
2257 .root
2258 .dispatch_event_for_path(
2259 &path[..path_len],
2260 self.id,
2261 dpi_info,
2262 self.last_tick_time,
2263 EventPhase::Bubble,
2264 self.focus.focused_widget,
2265 &self.clipboard,
2266 event,
2267 )
2268 .unwrap_or_else(empty_dispatch);
2269 let dispatch_handled = dispatch.handled;
2270 let dispatch_focus_request = dispatch.focus_request;
2271 effects.extend(dispatch);
2272 if dispatch_focus_request.is_some() {
2273 focus_request = dispatch_focus_request;
2274 }
2275 if dispatch_handled && !ignore_handled {
2276 handled = true;
2277 break;
2278 }
2279 }
2280 }
2281
2282 EventRouteResult {
2283 path,
2284 effects,
2285 focus_request,
2286 handled,
2287 }
2288 }
2289
2290 fn default_focus_request(
2291 &self,
2292 event: &Event,
2293 hit_target: Option<WidgetId>,
2294 path: &[WidgetId],
2295 ) -> Option<FocusRequest> {
2296 match event {
2297 Event::Keyboard(keyboard)
2298 if keyboard.state == KeyState::Pressed
2299 && keyboard.key == "Tab"
2300 && !keyboard.repeat
2301 && !keyboard.is_composing
2302 && !keyboard.modifiers.control
2303 && !keyboard.modifiers.alt
2304 && !keyboard.modifiers.meta =>
2305 {
2306 self.graph
2307 .next_focusable(self.focus.focused_widget, keyboard.modifiers.shift)
2308 .map(FocusRequest::Focus)
2309 .or(Some(FocusRequest::Clear))
2310 }
2311 Event::Pointer(pointer) if pointer.kind == PointerEventKind::Down => {
2312 let Some(hit_target) = hit_target else {
2313 return Some(FocusRequest::Clear);
2314 };
2315
2316 path.iter()
2317 .rev()
2318 .copied()
2319 .find(|widget_id| {
2320 self.graph
2321 .node(*widget_id)
2322 .is_some_and(|node| node.accepts_focus)
2323 })
2324 .map(FocusRequest::Focus)
2325 .or(Some(FocusRequest::Clear))
2326 .filter(|request| {
2327 matches!(request, FocusRequest::Focus(id) if *id == hit_target)
2328 || matches!(request, FocusRequest::Clear)
2329 })
2330 }
2331 Event::Window(WindowEvent::Focused(false)) => Some(FocusRequest::Clear),
2332 _ => None,
2333 }
2334 }
2335
2336 fn apply_focus_request(&mut self, request: FocusRequest) -> EventEffects {
2337 let next_focus = match request {
2338 FocusRequest::Focus(widget_id) => Some(widget_id),
2339 FocusRequest::Clear => None,
2340 };
2341
2342 if self.focus.focused_widget == next_focus {
2343 if self.focused_semantics != next_focus {
2344 self.focused_semantics = next_focus;
2345 self.schedule.mark(InvalidationKind::Semantics);
2346 }
2347 return EventEffects::default();
2348 }
2349
2350 let previous_focus = self.focus.focused_widget;
2351 self.focus.focused_widget = next_focus;
2352 self.focused_semantics = next_focus;
2353 let dpi_info = self.current_dpi_info();
2354
2355 let mut effects = EventEffects::default();
2356
2357 if let Some(widget_id) = previous_focus {
2358 effects
2359 .invalidations
2360 .extend(self.focus_transition_invalidations(widget_id));
2361 let extra = self
2362 .graph
2363 .path_to(widget_id)
2364 .and_then(|path| {
2365 self.root.notify_focus_change_for_path(
2366 &path,
2367 self.id,
2368 dpi_info,
2369 self.last_tick_time,
2370 self.focus.focused_widget,
2371 &self.clipboard,
2372 false,
2373 )
2374 })
2375 .or_else(|| {
2376 self.root.notify_focus_change_for(
2377 widget_id,
2378 self.id,
2379 dpi_info,
2380 self.last_tick_time,
2381 self.focus.focused_widget,
2382 &self.clipboard,
2383 false,
2384 )
2385 });
2386 if let Some(extra) = extra {
2387 effects.extend(extra);
2388 }
2389 }
2390
2391 if let Some(widget_id) = next_focus {
2392 effects
2393 .invalidations
2394 .extend(self.focus_transition_invalidations(widget_id));
2395 let extra = self
2396 .graph
2397 .path_to(widget_id)
2398 .and_then(|path| {
2399 self.root.notify_focus_change_for_path(
2400 &path,
2401 self.id,
2402 dpi_info,
2403 self.last_tick_time,
2404 self.focus.focused_widget,
2405 &self.clipboard,
2406 true,
2407 )
2408 })
2409 .or_else(|| {
2410 self.root.notify_focus_change_for(
2411 widget_id,
2412 self.id,
2413 dpi_info,
2414 self.last_tick_time,
2415 self.focus.focused_widget,
2416 &self.clipboard,
2417 true,
2418 )
2419 });
2420 if let Some(extra) = extra {
2421 effects.extend(extra);
2422 }
2423 }
2424
2425 self.schedule.mark(InvalidationKind::Paint);
2426 self.schedule.mark(InvalidationKind::Semantics);
2427 self.schedule.mark(InvalidationKind::HitTest);
2428 self.graph.set_focused_widget(self.focus.focused_widget);
2429
2430 effects
2431 }
2432
2433 fn focus_transition_invalidations(&self, widget_id: WidgetId) -> Vec<InvalidationRequest> {
2434 let mut invalidations = vec![InvalidationRequest::new(
2435 InvalidationTarget::Widget(widget_id),
2436 InvalidationKind::Semantics,
2437 )];
2438
2439 if let Some(node) = self.graph.node(widget_id) {
2440 invalidations.push(
2441 InvalidationRequest::new(
2442 InvalidationTarget::Widget(widget_id),
2443 InvalidationKind::Paint,
2444 )
2445 .with_region(node.geometry.paint_bounds),
2446 );
2447 }
2448
2449 invalidations
2450 }
2451
2452 fn render(
2453 &mut self,
2454 text_system: Arc<TextSystem>,
2455 font_registry: Arc<FontRegistry>,
2456 image_registry: Arc<ImageRegistry>,
2457 ) -> RenderOutput {
2458 let diagnostics_enabled = window_scene_statistics_detail_mode(self.id).is_detailed();
2459 let mut diagnostics = RenderDiagnostics::default();
2460 let mut invalidations = std::mem::take(&mut self.pending_invalidations);
2461 let mut repainted = false;
2462 let mut repaint_layers = Vec::new();
2463 let mut dirty_layers = Vec::new();
2464 let mut layer_updates = Vec::new();
2465 let previous_graph =
2466 if (self.schedule.measure || self.schedule.arrange) && !self.graph.is_empty() {
2467 Some(self.graph.snapshot())
2468 } else {
2469 None
2470 };
2471 let mut graph_changes = GraphChangeSet::default();
2472
2473 if self.last_frame.is_none() {
2474 self.schedule = FrameSchedule::bootstrap();
2475 }
2476
2477 if self.schedule.measure || self.schedule.arrange || self.viewport.is_none() {
2478 let started = Instant::now();
2479 let pass_invalidations = self.run_measure_arrange_pass(
2480 &invalidations,
2481 Arc::clone(&text_system),
2482 Arc::clone(&font_registry),
2483 Arc::clone(&image_registry),
2484 );
2485 self.schedule.extend(&pass_invalidations);
2486 invalidations.extend(pass_invalidations);
2487 graph_changes = self.collect_graph_changes(previous_graph.as_ref());
2488 if diagnostics_enabled {
2489 diagnostics.push(FramePhase::MeasureArrange, started.elapsed());
2490 }
2491 } else if self.schedule.hit_test || self.graph.is_empty() {
2492 let started = Instant::now();
2493 self.refresh_graph();
2494 if diagnostics_enabled {
2495 diagnostics.push(FramePhase::HitTest, started.elapsed());
2496 }
2497 }
2498
2499 let viewport = self.viewport.unwrap_or(Size::ZERO);
2500 let dpi_info = self.dpi_info_for_viewport(viewport);
2501 let previous_scene = self.last_frame.as_ref().map(|frame| &frame.scene);
2502 let mut composition_only_transforms = self
2503 .select_composition_only_transforms(previous_scene, &graph_changes.transform_widgets);
2504 for translation in
2505 self.select_explicit_transform_translations(previous_scene, &invalidations)
2506 {
2507 if composition_only_transforms
2508 .iter()
2509 .all(|existing| existing.widget_id != translation.widget_id)
2510 {
2511 composition_only_transforms.push(translation);
2512 }
2513 }
2514 let previous_scene_for_refresh = self.last_frame.as_ref().map(|frame| frame.scene.clone());
2515 let layer_descriptor_refreshes = self.collect_explicit_layer_descriptor_refreshes(
2516 previous_scene_for_refresh.as_ref(),
2517 &invalidations,
2518 );
2519 let composition_only_transform_ids = composition_only_transforms
2520 .iter()
2521 .map(|translation| translation.widget_id)
2522 .collect::<HashSet<_>>();
2523 let mut repaint_graph_widgets = graph_changes.repaint_widgets.clone();
2524 for translation in &graph_changes.transform_widgets {
2525 if !composition_only_transform_ids.contains(&translation.widget_id) {
2526 repaint_graph_widgets.push(translation.widget_id);
2527 }
2528 }
2529
2530 if self.schedule.paint || self.last_frame.is_none() || !repaint_graph_widgets.is_empty() {
2531 repaint_layers = self.collect_dirty_layers(&invalidations);
2532 dirty_layers = repaint_layers.clone();
2533 for widget_id in repaint_graph_widgets.iter().copied() {
2534 if self.graph.contains(widget_id) && !dirty_layers.contains(&widget_id) {
2535 dirty_layers.push(widget_id);
2536 }
2537 if self.graph.contains(widget_id) && !repaint_layers.contains(&widget_id) {
2538 repaint_layers.push(widget_id);
2539 }
2540 }
2541
2542 let mixed_update_roots = composition_only_transforms
2547 .iter()
2548 .filter(|translation| {
2549 dirty_layers.iter().any(|dirty_widget| {
2550 self.widget_is_ancestor_of(translation.widget_id, *dirty_widget)
2551 })
2552 })
2553 .map(|translation| translation.widget_id)
2554 .collect::<Vec<_>>();
2555 repaint_layers.extend(mixed_update_roots.iter().copied());
2556 dirty_layers.extend(mixed_update_roots);
2557 self.minimize_layer_roots(&mut repaint_layers);
2558 self.minimize_layer_roots(&mut dirty_layers);
2559
2560 composition_only_transforms.retain(|translation| {
2561 !dirty_layers.iter().any(|dirty_widget| {
2562 *dirty_widget == translation.widget_id
2563 || self.widget_is_ancestor_of(*dirty_widget, translation.widget_id)
2564 })
2565 });
2566 }
2567
2568 let mut scene_changed = false;
2569 let has_ordering_updates = invalidations
2570 .iter()
2571 .any(|request| request.kind == InvalidationKind::Ordering);
2572 if self.last_frame.is_none()
2573 || !repaint_layers.is_empty()
2574 || !composition_only_transforms.is_empty()
2575 || !layer_descriptor_refreshes.is_empty()
2576 || has_ordering_updates
2577 {
2578 let started = Instant::now();
2579 repainted = self.last_frame.is_none() || !repaint_layers.is_empty();
2580 scene_changed = true;
2581
2582 let focused_path = self
2583 .focus
2584 .focused_widget
2585 .and_then(|widget_id| self.graph.path_to(widget_id));
2586 let preserve_ime = focused_path.as_ref().is_none_or(|path| {
2587 !repaint_layers
2588 .iter()
2589 .any(|widget_id| path.iter().any(|candidate| candidate == widget_id))
2590 });
2591 let baseline_ime_composition_rect = if preserve_ime {
2592 self.ime_composition_rect
2593 } else {
2594 None
2595 };
2596
2597 let (
2598 scene,
2599 paint_images,
2600 mut paint_bounds_by_widget,
2601 paint_invalidations,
2602 mut ime_composition_rect,
2603 ) = if self.last_frame.is_none() || repaint_layers.contains(&self.root.id()) {
2604 self.paint_full_scene(
2605 dpi_info,
2606 Arc::clone(&text_system),
2607 Arc::clone(&font_registry),
2608 Arc::clone(&image_registry),
2609 )
2610 } else if repaint_layers.is_empty() {
2611 (
2612 self.last_frame
2613 .as_ref()
2614 .map(|frame| frame.scene.clone())
2615 .unwrap_or_default(),
2616 Vec::new(),
2617 self.last_paint_bounds_by_widget.clone(),
2618 Vec::new(),
2619 baseline_ime_composition_rect,
2620 )
2621 } else {
2622 self.repaint_dirty_layers(
2623 dpi_info,
2624 &repaint_layers,
2625 baseline_ime_composition_rect,
2626 Arc::clone(&text_system),
2627 Arc::clone(&font_registry),
2628 Arc::clone(&image_registry),
2629 )
2630 };
2631 let mut scene = scene;
2632 for translation in &composition_only_transforms {
2633 let _ = scene.translate_layer(translation.widget_id, translation.delta);
2634 for widget_id in self.graph.subtree_ids(translation.widget_id) {
2635 if let Some(bounds) = paint_bounds_by_widget.get_mut(&widget_id) {
2636 *bounds = bounds.translate(translation.delta);
2637 }
2638 }
2639 if let Some(moved_bounds) =
2640 paint_bounds_by_widget.get(&translation.widget_id).copied()
2641 {
2642 let mut ancestor = self
2648 .graph
2649 .node(translation.widget_id)
2650 .and_then(|node| node.parent);
2651 while let Some(widget_id) = ancestor {
2652 paint_bounds_by_widget
2653 .entry(widget_id)
2654 .and_modify(|bounds| *bounds = bounds.union(moved_bounds))
2655 .or_insert(moved_bounds);
2656 ancestor = self.graph.node(widget_id).and_then(|node| node.parent);
2657 }
2658 }
2659 if focused_path
2660 .as_ref()
2661 .is_some_and(|path| path.contains(&translation.widget_id))
2662 {
2663 ime_composition_rect =
2664 ime_composition_rect.map(|rect| rect.translate(translation.delta));
2665 }
2666 }
2667 for refresh in &layer_descriptor_refreshes {
2668 let _ =
2669 scene.replace_layer_descriptor(refresh.widget_id, refresh.descriptor.clone());
2670 }
2671 self.sync_scene_stack_metadata(&mut scene);
2672 self.last_paint_bounds_by_widget = paint_bounds_by_widget;
2673 self.graph
2674 .update_paint_bounds_from_snapshot(&self.last_paint_bounds_by_widget);
2675 invalidations.extend(paint_invalidations);
2676 self.ime_composition_rect = ime_composition_rect;
2677 let previous_scene = self.last_frame.as_ref().map(|frame| &frame.scene);
2678 layer_updates = self.collect_layer_updates(
2679 previous_scene,
2680 &scene,
2681 &invalidations,
2682 &dirty_layers,
2683 &composition_only_transforms
2684 .iter()
2685 .map(|translation| translation.widget_id)
2686 .collect::<Vec<_>>(),
2687 );
2688 let frame_image_registry =
2689 self.frame_image_registry(Arc::clone(&image_registry), paint_images);
2690 retain_text_layouts_for_scene(text_system.as_ref(), &scene);
2691 self.last_frame = Some(SceneFrame {
2692 window_id: self.id,
2693 viewport,
2694 surface_size: dpi_info.surface_size,
2695 scale_factor: dpi_info.scale_factor,
2696 dirty_regions: Vec::new(),
2697 layer_updates: layer_updates.clone(),
2698 scene,
2699 font_registry: Arc::clone(&font_registry),
2700 image_registry: frame_image_registry,
2701 text_layout_registry: text_system.text_layout_registry(),
2702 });
2703 if diagnostics_enabled && repainted {
2704 diagnostics.push(FramePhase::Paint, started.elapsed());
2705 }
2706 }
2707
2708 if self.schedule.semantics || self.last_semantics.is_empty() {
2709 let started = Instant::now();
2710 let mut semantics_ctx = SemanticsCtx::new(
2711 self.id,
2712 self.root.id(),
2713 self.root.id(),
2714 self.root.bounds(),
2715 self.focus.focused_widget,
2716 );
2717 self.root.semantics(&mut semantics_ctx);
2718 self.last_semantics = self.assemble_semantics_tree(semantics_ctx.into_nodes());
2719 if diagnostics_enabled {
2720 diagnostics.push(FramePhase::Semantics, started.elapsed());
2721 }
2722 }
2723
2724 let viewport_rect = Rect::from_origin_size(Point::ZERO, viewport);
2725 let dirty_regions = collect_dirty_regions(viewport, &invalidations, repainted, |request| {
2726 self.default_dirty_region_for_request(viewport_rect, request)
2727 });
2728 let mut frame = self
2729 .last_frame
2730 .clone()
2731 .unwrap_or_else(|| SceneFrame::new(self.id, viewport));
2732 frame.viewport = viewport;
2733 frame.surface_size = dpi_info.surface_size;
2734 frame.scale_factor = dpi_info.scale_factor;
2735 frame.dirty_regions = dirty_regions;
2736 frame.layer_updates = if scene_changed {
2737 layer_updates
2738 } else {
2739 self.collect_layer_updates(
2740 self.last_frame.as_ref().map(|stored| &stored.scene),
2741 &frame.scene,
2742 &invalidations,
2743 &[],
2744 &composition_only_transforms
2745 .iter()
2746 .map(|translation| translation.widget_id)
2747 .collect::<Vec<_>>(),
2748 )
2749 };
2750 frame.font_registry = font_registry;
2751 frame.image_registry = self.frame_image_registry(image_registry, Vec::new());
2752
2753 if diagnostics_enabled {
2754 let layout_cache = text_system.layout_cache_snapshot();
2755 diagnostics.text_caches.runtime_layout =
2756 CacheMetrics::new(layout_cache.entries, layout_cache.hits, layout_cache.misses);
2757 }
2758
2759 diagnostics.widget_count = self.graph.nodes.len();
2760 diagnostics.runtime_text_timing = sui_text::take_text_timing_collection();
2761 diagnostics.widget_timings = diagnostics::take_widget_timing_collection();
2762 diagnostics.active_animated_widget_count = self.active_animated_widget_count();
2763 diagnostics.animation_frame_wake_count = self.pending_animation_wake_count;
2764 diagnostics.animation_repaint_frame_count =
2765 usize::from(self.pending_animation_wake_count > 0 && repainted);
2766 diagnostics.animation_transform_effect_only_frame_count = usize::from(
2767 self.pending_animation_wake_count > 0
2768 && self.animation_frame_is_transform_only(repainted, &frame.layer_updates),
2769 );
2770 self.pending_animation_wake_count = 0;
2771
2772 self.schedule.clear();
2773
2774 RenderOutput {
2775 title: self.title.clone(),
2776 frame,
2777 semantics: self.last_semantics.clone(),
2778 ime_composition_rect: self.ime_composition_rect,
2779 diagnostics,
2780 }
2781 }
2782
2783 fn frame_image_registry(
2784 &self,
2785 base: Arc<ImageRegistry>,
2786 paint_images: Vec<(ImageHandle, PaintImageResource)>,
2787 ) -> Arc<ImageRegistry> {
2788 let mut registry = self
2789 .last_frame
2790 .as_ref()
2791 .map(|frame| frame.image_registry.as_ref().clone())
2792 .unwrap_or_else(|| base.as_ref().clone());
2793 for (handle, image) in base.iter() {
2794 registry.insert(handle, image.clone());
2795 }
2796 for (handle, image) in base.iter_external() {
2797 registry.insert_external(handle, *image);
2798 }
2799 for (handle, image) in paint_images {
2800 match image {
2801 PaintImageResource::Cpu(image) => {
2802 registry.insert(handle, image);
2803 }
2804 PaintImageResource::External(image) => {
2805 registry.insert_external(handle, image);
2806 }
2807 }
2808 }
2809 Arc::new(registry)
2810 }
2811
2812 fn paint_full_scene(
2813 &mut self,
2814 dpi_info: DpiInfo,
2815 text_system: Arc<TextSystem>,
2816 font_registry: Arc<FontRegistry>,
2817 image_registry: Arc<ImageRegistry>,
2818 ) -> PaintOutput {
2819 let mut paint_ctx = PaintCtx::new(
2820 self.id,
2821 self.root.id(),
2822 self.root.bounds(),
2823 self.focus.focused_widget,
2824 dpi_info,
2825 text_system,
2826 font_registry,
2827 self.last_frame
2828 .as_ref()
2829 .map(|frame| Arc::clone(&frame.image_registry))
2830 .unwrap_or(image_registry),
2831 );
2832 let _ = self
2833 .root
2834 .paint_layer_contents_for(self.root.id(), &mut paint_ctx);
2835 paint_ctx.into_parts()
2836 }
2837
2838 fn repaint_dirty_layers(
2839 &mut self,
2840 dpi_info: DpiInfo,
2841 dirty_layers: &[WidgetId],
2842 baseline_ime_composition_rect: Option<Rect>,
2843 text_system: Arc<TextSystem>,
2844 font_registry: Arc<FontRegistry>,
2845 image_registry: Arc<ImageRegistry>,
2846 ) -> PaintOutput {
2847 let mut scene = self
2848 .last_frame
2849 .as_ref()
2850 .map(|frame| frame.scene.clone())
2851 .unwrap_or_default();
2852 let mut images = Vec::new();
2853 let mut invalidations = Vec::new();
2854 let mut paint_bounds_by_widget = self.last_paint_bounds_by_widget.clone();
2855 let mut ime_composition_rect = baseline_ime_composition_rect;
2856
2857 for &widget_id in dirty_layers {
2858 let Some(bounds) = self
2859 .graph
2860 .node(widget_id)
2861 .map(|node| node.geometry.layout_bounds)
2862 else {
2863 return self.paint_full_scene(dpi_info, text_system, font_registry, image_registry);
2864 };
2865
2866 let mut paint_ctx = PaintCtx::new(
2867 self.id,
2868 widget_id,
2869 bounds,
2870 self.focus.focused_widget,
2871 dpi_info,
2872 Arc::clone(&text_system),
2873 Arc::clone(&font_registry),
2874 self.last_frame
2875 .as_ref()
2876 .map(|frame| Arc::clone(&frame.image_registry))
2877 .unwrap_or_else(|| Arc::clone(&image_registry)),
2878 );
2879 if !self
2880 .root
2881 .paint_layer_contents_for(widget_id, &mut paint_ctx)
2882 {
2883 return self.paint_full_scene(dpi_info, text_system, font_registry, image_registry);
2884 }
2885
2886 let (
2887 layer_scene,
2888 layer_images,
2889 layer_paint_bounds,
2890 layer_invalidations,
2891 layer_ime_composition_rect,
2892 ) = paint_ctx.into_parts();
2893 let Some(descriptor) = self.root.layer_descriptor_for(widget_id, &layer_scene) else {
2894 return self.paint_full_scene(dpi_info, text_system, font_registry, image_registry);
2895 };
2896 if widget_id == self.root.id()
2897 || !scene.replace_layer(
2898 widget_id,
2899 SceneLayer::from_descriptor(descriptor, layer_scene),
2900 )
2901 {
2902 return self.paint_full_scene(dpi_info, text_system, font_registry, image_registry);
2903 }
2904
2905 images.extend(layer_images);
2906 paint_bounds_by_widget.extend(layer_paint_bounds);
2907 invalidations.extend(layer_invalidations);
2908 if layer_ime_composition_rect.is_some() {
2909 ime_composition_rect = layer_ime_composition_rect;
2910 }
2911 }
2912
2913 (
2914 scene,
2915 images,
2916 paint_bounds_by_widget,
2917 invalidations,
2918 ime_composition_rect,
2919 )
2920 }
2921
2922 fn collect_dirty_layers(&self, invalidations: &[InvalidationRequest]) -> Vec<WidgetId> {
2923 let candidates: HashSet<WidgetId> = invalidations
2924 .iter()
2925 .filter(|request| {
2926 matches!(
2927 request.kind,
2928 InvalidationKind::Measure
2929 | InvalidationKind::Clip
2930 | InvalidationKind::Visibility
2931 | InvalidationKind::Paint
2932 | InvalidationKind::Text
2933 | InvalidationKind::Resources
2934 )
2935 })
2936 .map(|request| match request.target {
2937 InvalidationTarget::Widget(widget_id) if self.graph.contains(widget_id) => self
2938 .graph
2939 .nearest_paint_boundary_ancestor_or_root(widget_id),
2940 InvalidationTarget::Widget(_) => self.root.id(),
2941 InvalidationTarget::Window(_) | InvalidationTarget::Surface(_) => self.root.id(),
2942 })
2943 .collect();
2944
2945 if self.last_frame.is_none() || candidates.contains(&self.root.id()) {
2946 return vec![self.root.id()];
2947 }
2948
2949 let mut candidates: Vec<_> = candidates
2950 .into_iter()
2951 .filter(|widget_id| self.graph.contains(*widget_id))
2952 .collect();
2953 candidates.sort_by_key(|widget_id| {
2954 self.graph
2955 .path_to(*widget_id)
2956 .map_or(usize::MAX, |path| path.len())
2957 });
2958
2959 let mut minimized = Vec::new();
2960 for widget_id in candidates {
2961 if minimized
2962 .iter()
2963 .any(|ancestor| self.widget_is_ancestor_of(*ancestor, widget_id))
2964 {
2965 continue;
2966 }
2967 minimized.push(widget_id);
2968 }
2969
2970 minimized
2971 }
2972
2973 fn collect_graph_changes(&self, previous: Option<&WidgetGraphSnapshot>) -> GraphChangeSet {
2974 let Some(previous) = previous else {
2975 return GraphChangeSet {
2976 repaint_widgets: vec![self.graph.root],
2977 transform_widgets: Vec::new(),
2978 };
2979 };
2980
2981 let current_snapshot = self.graph.snapshot();
2982 let previous_nodes: HashMap<_, _> =
2983 previous.nodes.iter().map(|node| (node.id, node)).collect();
2984 let current_nodes: HashMap<_, _> = current_snapshot
2985 .nodes
2986 .iter()
2987 .map(|node| (node.id, node))
2988 .collect();
2989 let widget_ids = previous_nodes
2990 .keys()
2991 .chain(current_nodes.keys())
2992 .copied()
2993 .collect::<HashSet<_>>();
2994 let mut repaint_candidates = HashSet::new();
2995 let mut transform_candidates = Vec::new();
2996
2997 for widget_id in widget_ids {
2998 match (
2999 previous_nodes.get(&widget_id),
3000 current_nodes.get(&widget_id),
3001 ) {
3002 (Some(previous_node), Some(current_node)) => {
3003 if previous_node.measured_size != current_node.measured_size
3004 || previous_node.geometry.layout_bounds.size
3005 != current_node.geometry.layout_bounds.size
3006 || previous_node.parent != current_node.parent
3007 || previous_node.children != current_node.children
3008 {
3009 repaint_candidates.insert(resolve_snapshot_paint_boundary_or_root(
3010 ¤t_snapshot,
3011 current_node.id,
3012 ));
3013 continue;
3014 }
3015
3016 let delta = current_node.geometry.layout_bounds.origin
3017 - previous_node.geometry.layout_bounds.origin;
3018 if delta != Vector::ZERO {
3019 let resolved_boundary = resolve_snapshot_paint_boundary_or_root(
3020 ¤t_snapshot,
3021 current_node.id,
3022 );
3023 if resolved_boundary == current_node.id
3024 && current_node.paint_boundary == PaintBoundaryMode::Explicit
3025 {
3026 transform_candidates.push(LayerTranslation {
3027 widget_id: current_node.id,
3028 delta,
3029 });
3030 } else if current_nodes
3031 .get(&resolved_boundary)
3032 .zip(previous_nodes.get(&resolved_boundary))
3033 .is_some_and(|(current_boundary, previous_boundary)| {
3034 current_boundary.paint_boundary == PaintBoundaryMode::Explicit
3035 && current_boundary.geometry.layout_bounds.origin
3036 - previous_boundary.geometry.layout_bounds.origin
3037 == delta
3038 })
3039 {
3040 } else {
3045 repaint_candidates.insert(resolved_boundary);
3046 }
3047 }
3048 }
3049 (None, Some(current_node)) => {
3050 repaint_candidates.insert(resolve_snapshot_paint_boundary_or_root(
3051 ¤t_snapshot,
3052 current_node.id,
3053 ));
3054 }
3055 (Some(previous_node), None) => {
3056 repaint_candidates.insert(resolve_snapshot_paint_boundary_or_root(
3057 previous,
3058 previous_node.id,
3059 ));
3060 }
3061 (None, None) => {}
3062 }
3063 }
3064
3065 let mut repaint_widgets = repaint_candidates.into_iter().collect::<Vec<_>>();
3066 repaint_widgets.sort_by_key(|widget_id| self.widget_depth(*widget_id));
3067 let mut minimized_repaint = Vec::new();
3068 for widget_id in repaint_widgets {
3069 if minimized_repaint
3070 .iter()
3071 .any(|ancestor| self.widget_is_ancestor_of(*ancestor, widget_id))
3072 {
3073 continue;
3074 }
3075 minimized_repaint.push(widget_id);
3076 }
3077
3078 transform_candidates.sort_by_key(|translation| self.widget_depth(translation.widget_id));
3079 let mut minimized_transforms = Vec::new();
3080 for candidate in transform_candidates {
3081 if minimized_repaint
3082 .iter()
3083 .any(|ancestor| self.widget_is_ancestor_of(*ancestor, candidate.widget_id))
3084 {
3085 continue;
3086 }
3087
3088 let inherited_delta = minimized_transforms
3089 .iter()
3090 .filter(|translation: &&LayerTranslation| {
3091 self.widget_is_ancestor_of(translation.widget_id, candidate.widget_id)
3092 })
3093 .fold(Vector::ZERO, |current, translation| {
3094 current + translation.delta
3095 });
3096 let residual = candidate.delta - inherited_delta;
3097 if residual == Vector::ZERO {
3098 continue;
3099 }
3100
3101 minimized_transforms.push(LayerTranslation {
3102 widget_id: candidate.widget_id,
3103 delta: residual,
3104 });
3105 }
3106
3107 GraphChangeSet {
3108 repaint_widgets: minimized_repaint,
3109 transform_widgets: minimized_transforms,
3110 }
3111 }
3112
3113 fn select_composition_only_transforms(
3114 &self,
3115 previous_scene: Option<&Scene>,
3116 transform_widgets: &[LayerTranslation],
3117 ) -> Vec<LayerTranslation> {
3118 let previous_layers = previous_scene.map(collect_scene_layers).unwrap_or_default();
3119 transform_widgets
3120 .iter()
3121 .copied()
3122 .filter(|translation| previous_layers.contains_key(&translation.widget_id))
3123 .collect()
3124 }
3125
3126 fn select_explicit_transform_translations(
3127 &self,
3128 previous_scene: Option<&Scene>,
3129 invalidations: &[InvalidationRequest],
3130 ) -> Vec<LayerTranslation> {
3131 let previous_layers = previous_scene.map(collect_scene_layers).unwrap_or_default();
3132 let mut translations = Vec::new();
3133
3134 for request in invalidations {
3135 if request.kind != InvalidationKind::Transform {
3136 continue;
3137 }
3138
3139 let InvalidationTarget::Widget(widget_id) = request.target else {
3140 continue;
3141 };
3142 let resolved_boundary = self
3143 .graph
3144 .nearest_paint_boundary_ancestor_or_root(widget_id);
3145 if resolved_boundary == self.root.id() {
3146 continue;
3147 }
3148 let Some(previous) = previous_layers.get(&resolved_boundary) else {
3149 continue;
3150 };
3151 let Some(current) = self.graph.node(resolved_boundary) else {
3152 continue;
3153 };
3154
3155 let delta = current.geometry.layout_bounds.origin - previous.bounds.origin;
3156 if delta == Vector::ZERO {
3157 continue;
3158 }
3159
3160 if translations
3161 .iter()
3162 .all(|translation: &LayerTranslation| translation.widget_id != resolved_boundary)
3163 {
3164 translations.push(LayerTranslation {
3165 widget_id: resolved_boundary,
3166 delta,
3167 });
3168 }
3169 }
3170
3171 translations
3172 }
3173
3174 fn collect_explicit_layer_descriptor_refreshes(
3175 &mut self,
3176 previous_scene: Option<&Scene>,
3177 invalidations: &[InvalidationRequest],
3178 ) -> Vec<LayerDescriptorRefresh> {
3179 let Some(previous_scene) = previous_scene else {
3180 return Vec::new();
3181 };
3182 if !invalidations.iter().any(|request| {
3183 matches!(
3184 request.kind,
3185 InvalidationKind::Transform | InvalidationKind::Effect
3186 )
3187 }) {
3188 return Vec::new();
3189 }
3190
3191 let previous_layers = collect_scene_layers(previous_scene);
3192 let mut refreshes = Vec::new();
3193
3194 for (widget_id, previous_descriptor) in previous_layers {
3195 let Some(layer_scene) = previous_scene.layer_scene(widget_id).cloned() else {
3196 continue;
3197 };
3198 let Some(descriptor) = self.root.layer_descriptor_for(widget_id, &layer_scene) else {
3199 continue;
3200 };
3201 if descriptor.properties == previous_descriptor.properties {
3202 continue;
3203 }
3204 refreshes.push(LayerDescriptorRefresh {
3205 widget_id,
3206 descriptor,
3207 });
3208 }
3209
3210 refreshes
3211 }
3212
3213 fn widget_depth(&self, widget_id: WidgetId) -> usize {
3214 self.graph.depth(widget_id).unwrap_or(usize::MAX)
3215 }
3216
3217 fn minimize_layer_roots(&self, candidates: &mut Vec<WidgetId>) {
3218 candidates.sort_by_key(|widget_id| (self.widget_depth(*widget_id), widget_id.get()));
3219 candidates.dedup();
3220 let mut minimized = Vec::with_capacity(candidates.len());
3221 for widget_id in candidates.iter().copied() {
3222 if minimized
3223 .iter()
3224 .any(|ancestor| self.widget_is_ancestor_of(*ancestor, widget_id))
3225 {
3226 continue;
3227 }
3228 minimized.push(widget_id);
3229 }
3230 *candidates = minimized;
3231 }
3232
3233 fn default_dirty_region_for_request(
3234 &self,
3235 viewport_rect: Rect,
3236 request: &InvalidationRequest,
3237 ) -> Rect {
3238 match request.target {
3239 InvalidationTarget::Widget(widget_id) => self
3240 .graph
3241 .node(widget_id)
3242 .map(|node| node.geometry.paint_bounds)
3243 .unwrap_or(viewport_rect),
3244 InvalidationTarget::Window(_) | InvalidationTarget::Surface(_) => viewport_rect,
3245 }
3246 }
3247
3248 fn collect_layer_updates(
3249 &self,
3250 previous_scene: Option<&Scene>,
3251 scene: &Scene,
3252 invalidations: &[InvalidationRequest],
3253 dirty_layers: &[WidgetId],
3254 graph_dirty_widgets: &[WidgetId],
3255 ) -> Vec<SceneLayerUpdate> {
3256 let current_layers = collect_scene_layers(scene);
3257 if current_layers.is_empty() {
3258 return Vec::new();
3259 }
3260
3261 let previous_layers = previous_scene.map(collect_scene_layers).unwrap_or_default();
3262 let mut updates = HashMap::<WidgetId, SceneLayerUpdateKind>::new();
3263 let mut damage_regions = HashMap::<WidgetId, Rect>::new();
3264 let explicit_transform_widgets = invalidations
3265 .iter()
3266 .filter_map(|request| {
3267 if request.kind != InvalidationKind::Transform {
3268 return None;
3269 }
3270
3271 match request.target {
3272 InvalidationTarget::Widget(widget_id) if self.graph.contains(widget_id) => {
3273 Some(
3274 self.graph
3275 .nearest_paint_boundary_ancestor_or_root(widget_id),
3276 )
3277 }
3278 _ => None,
3279 }
3280 })
3281 .collect::<HashSet<_>>();
3282
3283 for request in invalidations {
3284 let Some(kind) = invalidation_to_layer_update_kind(request.kind) else {
3285 continue;
3286 };
3287 let widget_id = match request.target {
3288 InvalidationTarget::Widget(widget_id) if self.graph.contains(widget_id) => self
3289 .graph
3290 .nearest_paint_boundary_ancestor_or_root(widget_id),
3291 InvalidationTarget::Widget(_) => self.root.id(),
3292 InvalidationTarget::Window(_) | InvalidationTarget::Surface(_) => self.root.id(),
3293 };
3294 if request.kind == InvalidationKind::Arrange
3295 && explicit_transform_widgets
3296 .iter()
3297 .any(|candidate| self.widget_is_ancestor_of(widget_id, *candidate))
3298 {
3299 continue;
3300 }
3301 merge_layer_update_kind(&mut updates, widget_id, kind);
3302 if let Some(region) = request.region {
3303 damage_regions
3304 .entry(widget_id)
3305 .and_modify(|current| *current = current.union(region))
3306 .or_insert(region);
3307 }
3308 }
3309
3310 for (widget_id, descriptor) in ¤t_layers {
3311 let Some(previous) = previous_layers.get(widget_id) else {
3312 merge_layer_update_kind(&mut updates, *widget_id, SceneLayerUpdateKind::Content);
3313 continue;
3314 };
3315 if descriptor.stack_host != previous.stack_host
3316 || descriptor.stack_order != previous.stack_order
3317 || descriptor.transient_owner_surface != previous.transient_owner_surface
3318 || descriptor.is_stack_surface != previous.is_stack_surface
3319 {
3320 merge_layer_update_kind(&mut updates, *widget_id, SceneLayerUpdateKind::Ordering);
3321 }
3322 if descriptor.properties.translation != previous.properties.translation {
3323 merge_layer_update_kind(&mut updates, *widget_id, SceneLayerUpdateKind::Transform);
3324 }
3325 if descriptor.properties.opacity != previous.properties.opacity {
3326 merge_layer_update_kind(&mut updates, *widget_id, SceneLayerUpdateKind::Effect);
3327 }
3328 }
3329
3330 for widget_id in graph_dirty_widgets.iter().copied() {
3331 merge_layer_update_kind(&mut updates, widget_id, SceneLayerUpdateKind::Transform);
3332 }
3333
3334 for widget_id in dirty_layers.iter().copied() {
3335 merge_layer_update_kind(&mut updates, widget_id, SceneLayerUpdateKind::Content);
3336 }
3337
3338 let mut resolved_updates = Vec::new();
3339 for (widget_id, kind) in updates {
3340 let Some(descriptor) = current_layers.get(&widget_id).cloned() else {
3341 continue;
3342 };
3343 let fallback_damage = previous_layers
3344 .get(&widget_id)
3345 .map(|previous| {
3346 previous
3347 .presented_paint_bounds()
3348 .union(descriptor.presented_paint_bounds())
3349 })
3350 .unwrap_or(descriptor.presented_paint_bounds());
3351 let damage = damage_regions
3352 .get(&widget_id)
3353 .copied()
3354 .unwrap_or(fallback_damage);
3355 resolved_updates
3356 .push(SceneLayerUpdate::from_descriptor(kind, descriptor).with_damage(damage));
3357 }
3358
3359 resolved_updates.sort_by_key(|update| update.owner.get());
3360 resolved_updates
3361 }
3362
3363 fn widget_is_ancestor_of(&self, ancestor: WidgetId, widget_id: WidgetId) -> bool {
3364 self.graph.is_ancestor_of(ancestor, widget_id)
3365 }
3366
3367 fn build_measure_scope(&self, invalidations: &[InvalidationRequest]) -> Rc<MeasureScope> {
3376 let mut subtree_roots: HashSet<WidgetId> = HashSet::new();
3377 let mut force_all = false;
3378 for request in invalidations {
3379 if !matches!(
3380 request.kind,
3381 InvalidationKind::Measure
3382 | InvalidationKind::Text
3383 | InvalidationKind::Visibility
3384 | InvalidationKind::Ordering
3385 ) {
3386 continue;
3387 }
3388 match request.target {
3389 InvalidationTarget::Widget(widget_id) => {
3390 subtree_roots.insert(widget_id);
3391 }
3392 InvalidationTarget::Window(_) | InvalidationTarget::Surface(_) => {
3393 force_all = true;
3394 }
3395 }
3396 }
3397
3398 if force_all || subtree_roots.is_empty() {
3399 return Rc::new(MeasureScope::force_all());
3400 }
3401
3402 let mut dirty: HashSet<WidgetId> = HashSet::new();
3403 for widget_id in &subtree_roots {
3404 if !self.graph.extend_ancestors(*widget_id, &mut dirty) {
3405 return Rc::new(MeasureScope::force_all());
3406 }
3407 }
3408
3409 Rc::new(MeasureScope::scoped(dirty, subtree_roots))
3410 }
3411
3412 fn run_measure_arrange_pass(
3413 &mut self,
3414 invalidations: &[InvalidationRequest],
3415 text_system: Arc<TextSystem>,
3416 font_registry: Arc<FontRegistry>,
3417 image_registry: Arc<ImageRegistry>,
3418 ) -> Vec<InvalidationRequest> {
3419 let constraints = self.measure_constraints();
3420 let scope = self.build_measure_scope(invalidations);
3421 let mut measure_ctx = MeasureCtx::new_scoped_at(
3422 self.id,
3423 self.root.id(),
3424 self.root.bounds(),
3425 self.current_dpi_info(),
3426 text_system,
3427 font_registry,
3428 image_registry,
3429 scope,
3430 self.last_tick_time,
3431 );
3432 let measured_root = if self.schedule.measure || self.viewport.is_none() {
3433 self.root.measure(&mut measure_ctx, constraints)
3434 } else {
3435 self.root.measured_size()
3436 };
3437 let viewport = constraints.clamp(measured_root);
3438
3439 let mut arrange_ctx = ArrangeCtx::new(self.id, self.root.id(), self.current_dpi_info());
3440 self.root.arrange(
3441 &mut arrange_ctx,
3442 Rect::from_origin_size(Point::ZERO, viewport),
3443 );
3444 self.viewport = Some(viewport);
3445 self.schedule.measure = false;
3446 self.schedule.arrange = false;
3447 self.schedule.hit_test = false;
3448 self.refresh_graph();
3449
3450 let mut invalidations = measure_ctx.take_invalidations();
3451 self.apply_wake_requests(measure_ctx.take_wake_requests());
3452 invalidations.extend(arrange_ctx.take_invalidations());
3453 invalidations
3454 }
3455
3456 fn refresh_graph(&mut self) {
3457 self.graph = WidgetGraph::rebuild(
3458 &self.root,
3459 self.focus.focused_widget,
3460 &self.last_paint_bounds_by_widget,
3461 );
3462 self.prune_runtime_state();
3463 self.schedule.hit_test = false;
3464 }
3465
3466 fn sync_scene_stack_metadata(&self, scene: &mut Scene) {
3467 scene.visit_layers_mut(&mut |layer| {
3468 if let Some(node) = self.graph.node(layer.widget_id()) {
3469 layer.descriptor.stack_host = node.stack_host;
3470 layer.descriptor.stack_order = node.stack_surface_order;
3471 layer.descriptor.transient_owner_surface = node.transient_owner_surface;
3472 layer.descriptor.is_stack_surface = node.is_stack_surface;
3473 layer.descriptor.hit_test = node.hit_test;
3474 }
3475 });
3476 scene.reorder_stack_surfaces();
3477 }
3478
3479 fn prune_runtime_state(&mut self) {
3480 self.pointer_capture
3481 .retain(|_, widget_id| self.graph.contains(*widget_id));
3482 if self
3483 .active_drag
3484 .as_ref()
3485 .is_some_and(|drag| !self.graph.contains(drag.source))
3486 {
3487 self.active_drag = None;
3488 }
3489 self.scheduled_timers
3490 .retain(|timer| self.graph.contains(timer.target));
3491 self.delivering_timers
3492 .retain(|_, widget_id| self.graph.contains(*widget_id));
3493 self.async_wake_targets
3494 .retain(|_, widget_id| self.graph.contains(*widget_id));
3495 self.pending_async_wakeups
3496 .retain(|token| self.async_wake_targets.contains_key(token));
3497 self.requested_animation_frames
3498 .retain(|widget_id| self.graph.contains(*widget_id));
3499 self.delivering_animation_frames
3500 .retain(|widget_id| self.graph.contains(*widget_id));
3501 if self.requested_animation_frames.is_empty() && self.delivering_animation_frames.is_empty()
3502 {
3503 self.last_animation_frame_time = None;
3504 }
3505
3506 if self
3507 .focus
3508 .focused_widget
3509 .is_some_and(|widget_id| !self.graph.contains(widget_id))
3510 {
3511 self.focus.focused_widget = None;
3512 self.focused_semantics = None;
3513 }
3514 }
3515
3516 fn measure_constraints(&self) -> Constraints {
3517 self.viewport_hint
3518 .map(Constraints::tight)
3519 .unwrap_or(Constraints::UNBOUNDED)
3520 }
3521
3522 fn dpi_info_for_viewport(&self, viewport: Size) -> DpiInfo {
3523 DpiInfo::new(
3524 self.scale_factor,
3525 self.raw_dpi,
3526 viewport,
3527 scale_viewport_to_surface_size(viewport, self.scale_factor),
3528 )
3529 }
3530
3531 fn current_dpi_info(&self) -> DpiInfo {
3532 let viewport = self.viewport.or(self.viewport_hint).unwrap_or(Size::ZERO);
3533 self.dpi_info_for_viewport(viewport)
3534 }
3535}
3536
3537fn normalize_scale_factor(scale_factor: f32) -> f32 {
3538 if scale_factor.is_finite() && scale_factor > 0.0 {
3539 scale_factor
3540 } else {
3541 1.0
3542 }
3543}
3544
3545fn scale_viewport_to_surface_size(viewport: Size, scale_factor: f32) -> Size {
3546 if viewport.is_empty() {
3547 return Size::ZERO;
3548 }
3549
3550 let scale_factor = normalize_scale_factor(scale_factor);
3551 Size::new(
3552 (viewport.width * scale_factor).round().max(1.0),
3553 (viewport.height * scale_factor).round().max(1.0),
3554 )
3555}
3556
3557impl WindowState {
3558 fn assemble_semantics_tree(&mut self, nodes: Vec<SemanticsNode>) -> Vec<SemanticsNode> {
3559 let semantic_ids: HashSet<_> = nodes.iter().map(|node| node.id).collect();
3560 if self
3561 .focused_semantics
3562 .is_some_and(|focused| !semantic_ids.contains(&focused))
3563 {
3564 self.focused_semantics = self.focus.focused_widget;
3565 }
3566
3567 nodes
3568 .into_iter()
3569 .map(|mut node| {
3570 node.parent = self.resolve_semantics_parent(&semantic_ids, node.id, node.parent);
3571 node.state.focused |= Some(node.id) == self.focused_semantics;
3572 node
3573 })
3574 .collect()
3575 }
3576
3577 fn resolve_semantics_parent(
3578 &self,
3579 semantic_ids: &HashSet<WidgetId>,
3580 widget_id: WidgetId,
3581 explicit_parent: Option<WidgetId>,
3582 ) -> Option<WidgetId> {
3583 if let Some(parent) =
3584 explicit_parent.filter(|parent| *parent != widget_id && semantic_ids.contains(parent))
3585 {
3586 return Some(parent);
3587 }
3588
3589 let mut current = self.graph.node(widget_id).and_then(|node| node.parent);
3590 while let Some(candidate) = current {
3591 if semantic_ids.contains(&candidate) {
3592 return Some(candidate);
3593 }
3594 current = self.graph.node(candidate).and_then(|node| node.parent);
3595 }
3596 None
3597 }
3598}
3599
3600#[derive(Default)]
3601struct WidgetGraph {
3602 root: WidgetId,
3603 nodes: HashMap<WidgetId, WidgetNodeSnapshot>,
3604 order: Vec<WidgetId>,
3605 host_surface_order: HashMap<WidgetId, Vec<WidgetId>>,
3606 host_order_policy: HashMap<WidgetId, StackOrderPolicy>,
3607}
3608
3609impl WidgetGraph {
3610 fn empty(root: WidgetId) -> Self {
3611 Self {
3612 root,
3613 nodes: HashMap::new(),
3614 order: Vec::new(),
3615 host_surface_order: HashMap::new(),
3616 host_order_policy: HashMap::new(),
3617 }
3618 }
3619
3620 fn rebuild(
3621 root: &WidgetPod,
3622 focused_widget: Option<WidgetId>,
3623 paint_bounds_by_widget: &HashMap<WidgetId, Rect>,
3624 ) -> Self {
3625 let mut graph = Self::empty(root.id());
3626 graph.collect(
3627 root,
3628 None,
3629 focused_widget,
3630 paint_bounds_by_widget,
3631 root.id(),
3632 root.id(),
3633 );
3634 graph.recompute_stack_surface_order();
3635 graph
3636 }
3637
3638 fn recompute_stack_surface_order(&mut self) {
3639 let mut position_by_surface = HashMap::<(WidgetId, WidgetId), usize>::new();
3640 for (host, surfaces) in &self.host_surface_order {
3641 for (index, surface) in surfaces.iter().copied().enumerate() {
3642 position_by_surface.insert((*host, surface), index);
3643 }
3644 }
3645
3646 for node in self.nodes.values_mut() {
3647 if let Some(order) = position_by_surface.get(&(node.stack_host, node.stack_surface)) {
3648 node.stack_surface_order = *order;
3649 }
3650 }
3651 }
3652
3653 fn update_paint_bounds_from_snapshot(
3654 &mut self,
3655 paint_bounds_by_widget: &HashMap<WidgetId, Rect>,
3656 ) {
3657 for node in self.nodes.values_mut() {
3658 node.geometry.paint_bounds = paint_bounds_by_widget
3659 .get(&node.id)
3660 .copied()
3661 .unwrap_or(node.geometry.layout_bounds);
3662 }
3663 }
3664
3665 fn set_focused_widget(&mut self, focused_widget: Option<WidgetId>) {
3666 for node in self.nodes.values_mut() {
3667 node.focused = Some(node.id) == focused_widget;
3668 }
3669 }
3670
3671 fn is_empty(&self) -> bool {
3672 self.nodes.is_empty()
3673 }
3674
3675 fn contains(&self, widget_id: WidgetId) -> bool {
3676 self.nodes.contains_key(&widget_id)
3677 }
3678
3679 fn node(&self, widget_id: WidgetId) -> Option<&WidgetNodeSnapshot> {
3680 self.nodes.get(&widget_id)
3681 }
3682
3683 fn snapshot(&self) -> WidgetGraphSnapshot {
3684 let mut stack_hosts = self
3685 .host_order_policy
3686 .iter()
3687 .map(|(host, order_policy)| StackHostSnapshot {
3688 host: *host,
3689 order_policy: *order_policy,
3690 surfaces: self
3691 .host_surface_order
3692 .get(host)
3693 .cloned()
3694 .unwrap_or_default(),
3695 })
3696 .collect::<Vec<_>>();
3697 stack_hosts.sort_by_key(|host| host.host.get());
3698
3699 WidgetGraphSnapshot {
3700 root: self.root,
3701 nodes: self
3702 .order
3703 .iter()
3704 .filter_map(|widget_id| self.nodes.get(widget_id).cloned())
3705 .collect(),
3706 stack_hosts,
3707 }
3708 }
3709
3710 fn hit_test(&self, point: Point) -> Option<WidgetId> {
3711 self.hit_test_node(self.root, point)
3712 }
3713
3714 fn hit_test_within(&self, widget_id: WidgetId, point: Point) -> Option<WidgetId> {
3715 self.hit_test_node(widget_id, point)
3716 }
3717
3718 fn path_to(&self, target: WidgetId) -> Option<Vec<WidgetId>> {
3719 let mut path = Vec::new();
3720 let mut current = Some(target);
3721
3722 while let Some(widget_id) = current {
3723 let node = self.node(widget_id)?;
3724 path.push(widget_id);
3725 current = node.parent;
3726 }
3727
3728 path.reverse();
3729 Some(path)
3730 }
3731
3732 fn depth(&self, target: WidgetId) -> Option<usize> {
3733 let mut depth = 0usize;
3734 let mut current = Some(target);
3735 while let Some(widget_id) = current {
3736 let node = self.node(widget_id)?;
3737 depth += 1;
3738 current = node.parent;
3739 }
3740 Some(depth)
3741 }
3742
3743 fn is_ancestor_of(&self, ancestor: WidgetId, target: WidgetId) -> bool {
3744 let mut current = self.node(target).and_then(|node| node.parent);
3745 while let Some(widget_id) = current {
3746 if widget_id == ancestor {
3747 return true;
3748 }
3749 current = self.node(widget_id).and_then(|node| node.parent);
3750 }
3751 false
3752 }
3753
3754 fn extend_ancestors(&self, target: WidgetId, ancestors: &mut HashSet<WidgetId>) -> bool {
3755 let mut current = Some(target);
3756 while let Some(widget_id) = current {
3757 let Some(node) = self.node(widget_id) else {
3758 return false;
3759 };
3760 ancestors.insert(widget_id);
3761 current = node.parent;
3762 }
3763 true
3764 }
3765
3766 fn subtree_ids(&self, root: WidgetId) -> Vec<WidgetId> {
3767 let mut subtree = Vec::new();
3768 let mut pending = vec![root];
3769 while let Some(widget_id) = pending.pop() {
3770 let Some(node) = self.node(widget_id) else {
3771 continue;
3772 };
3773 subtree.push(widget_id);
3774 pending.extend(node.children.iter().copied());
3775 }
3776 subtree
3777 }
3778
3779 fn nearest_paint_boundary_ancestor_or_root(&self, widget_id: WidgetId) -> WidgetId {
3780 let mut current = Some(widget_id);
3781 while let Some(candidate) = current {
3782 let Some(node) = self.node(candidate) else {
3783 break;
3784 };
3785 if node.paint_boundary == PaintBoundaryMode::Explicit {
3786 return candidate;
3787 }
3788 current = node.parent;
3789 }
3790 self.root
3791 }
3792
3793 fn next_focusable(&self, current: Option<WidgetId>, backwards: bool) -> Option<WidgetId> {
3794 let focusable: Vec<_> = self
3795 .order
3796 .iter()
3797 .copied()
3798 .filter(|widget_id| self.node(*widget_id).is_some_and(|node| node.accepts_focus))
3799 .collect();
3800
3801 if focusable.is_empty() {
3802 return None;
3803 }
3804
3805 let fallback = if backwards {
3806 focusable.last().copied()
3807 } else {
3808 focusable.first().copied()
3809 };
3810
3811 let Some(current) = current else {
3812 return fallback;
3813 };
3814
3815 let Some(index) = focusable.iter().position(|widget_id| *widget_id == current) else {
3816 return fallback;
3817 };
3818
3819 if backwards {
3820 Some(focusable[(index + focusable.len() - 1) % focusable.len()])
3821 } else {
3822 Some(focusable[(index + 1) % focusable.len()])
3823 }
3824 }
3825
3826 fn collect(
3827 &mut self,
3828 pod: &WidgetPod,
3829 parent: Option<WidgetId>,
3830 focused_widget: Option<WidgetId>,
3831 paint_bounds_by_widget: &HashMap<WidgetId, Rect>,
3832 inherited_host: WidgetId,
3833 inherited_surface: WidgetId,
3834 ) {
3835 let id = pod.id();
3836 self.order.push(id);
3837
3838 let host_options = if id == self.root {
3839 Some(pod.current_stack_host_options().unwrap_or_default())
3840 } else {
3841 pod.current_stack_host_options()
3842 };
3843 let is_stack_host = host_options.is_some();
3844 let resolved_host = if is_stack_host { id } else { inherited_host };
3845 let host_policy = host_options
3846 .map(|options| options.order_policy)
3847 .unwrap_or(StackOrderPolicy::Stable);
3848 if is_stack_host {
3849 self.host_order_policy.insert(resolved_host, host_policy);
3850 } else {
3851 self.host_order_policy
3852 .entry(resolved_host)
3853 .or_insert(StackOrderPolicy::Stable);
3854 }
3855 let resolved_policy = *self
3856 .host_order_policy
3857 .get(&resolved_host)
3858 .unwrap_or(&StackOrderPolicy::Stable);
3859
3860 let surface_options = pod.current_stack_surface_options();
3861 let emits_layer = pod.current_layer_options().emits_layer();
3862 let is_direct_child_of_host = parent == Some(resolved_host);
3863 let is_stack_surface =
3864 emits_layer && (surface_options.is_some() || is_direct_child_of_host);
3865 let hit_test = surface_options.is_none_or(|options| options.hit_test);
3866 let resolved_surface = if is_stack_surface {
3867 id
3868 } else {
3869 inherited_surface
3870 };
3871 let transient_owner_surface = surface_options
3872 .filter(|options| emits_layer && options.transient && inherited_surface != id)
3873 .map(|_| inherited_surface);
3874 if is_stack_surface {
3875 let surfaces = self.host_surface_order.entry(resolved_host).or_default();
3876 if !surfaces.contains(&id) {
3877 surfaces.push(id);
3878 }
3879 }
3880 let stack_surface_order = self
3881 .host_surface_order
3882 .get(&resolved_host)
3883 .and_then(|surfaces| {
3884 surfaces
3885 .iter()
3886 .position(|surface| *surface == resolved_surface)
3887 })
3888 .unwrap_or(0);
3889
3890 let children = {
3891 let mut visitor = CollectChildrenVisitor {
3892 graph: self,
3893 parent: id,
3894 focused_widget,
3895 paint_bounds_by_widget,
3896 inherited_host: resolved_host,
3897 inherited_surface: resolved_surface,
3898 children: Vec::new(),
3899 };
3900 pod.visit_children(&mut visitor);
3901 visitor.children
3902 };
3903
3904 let layout_bounds = pod.bounds();
3905 let input_bounds = layout_bounds;
3906 let paint_bounds = paint_bounds_by_widget
3907 .get(&id)
3908 .copied()
3909 .unwrap_or(layout_bounds);
3910
3911 self.nodes.insert(
3912 id,
3913 WidgetNodeSnapshot {
3914 id,
3915 parent,
3916 children,
3917 measured_size: pod.measured_size(),
3918 geometry: WidgetGeometrySnapshot::new(layout_bounds, input_bounds, paint_bounds),
3919 bounds: layout_bounds,
3920 paint_boundary: pod.current_paint_boundary_mode(),
3921 stack_host: resolved_host,
3922 stack_surface: resolved_surface,
3923 stack_surface_order,
3924 transient_owner_surface,
3925 is_stack_host,
3926 is_stack_surface,
3927 hit_test,
3928 stack_order_policy: resolved_policy,
3929 accepts_focus: pod.accepts_focus(),
3930 focused: Some(id) == focused_widget,
3931 },
3932 );
3933 }
3934
3935 fn hit_test_node(&self, widget_id: WidgetId, point: Point) -> Option<WidgetId> {
3936 let node = self.node(widget_id)?;
3937 if !node.hit_test || !node.geometry.input_bounds.contains(point) {
3938 return None;
3939 }
3940
3941 if node.is_stack_host {
3942 let mut tested_surfaces = HashSet::new();
3943 if let Some(ordered_surfaces) = self.host_surface_order.get(&node.id) {
3944 for surface_id in ordered_surfaces.iter().rev().copied() {
3945 tested_surfaces.insert(surface_id);
3946 if let Some(hit) = self.hit_test_node(surface_id, point) {
3947 return Some(hit);
3948 }
3949 }
3950 }
3951
3952 for child_id in node.children.iter().rev() {
3953 if self.node(*child_id).is_some_and(|child| {
3954 child.is_stack_surface || tested_surfaces.contains(child_id)
3955 }) {
3956 continue;
3957 }
3958 if let Some(hit) = self.hit_test_node(*child_id, point) {
3959 return Some(hit);
3960 }
3961 }
3962
3963 return Some(widget_id);
3964 }
3965
3966 for child_id in node.children.iter().rev() {
3967 if let Some(hit) = self.hit_test_node(*child_id, point) {
3968 return Some(hit);
3969 }
3970 }
3971
3972 Some(widget_id)
3973 }
3974}
3975
3976struct CollectChildrenVisitor<'a> {
3977 graph: &'a mut WidgetGraph,
3978 parent: WidgetId,
3979 focused_widget: Option<WidgetId>,
3980 paint_bounds_by_widget: &'a HashMap<WidgetId, Rect>,
3981 inherited_host: WidgetId,
3982 inherited_surface: WidgetId,
3983 children: Vec<WidgetId>,
3984}
3985
3986impl WidgetPodVisitor for CollectChildrenVisitor<'_> {
3987 fn visit(&mut self, child: &WidgetPod) {
3988 self.children.push(child.id());
3989 self.graph.collect(
3990 child,
3991 Some(self.parent),
3992 self.focused_widget,
3993 self.paint_bounds_by_widget,
3994 self.inherited_host,
3995 self.inherited_surface,
3996 );
3997 }
3998}
3999
4000struct EventRouteResult {
4001 path: Vec<WidgetId>,
4002 effects: EventEffects,
4003 focus_request: Option<FocusRequest>,
4004 handled: bool,
4005}
4006
4007#[derive(Default)]
4008struct HoverTransitionResult {
4009 effects: EventEffects,
4010 focus_request: Option<FocusRequest>,
4011 skip_primary_route: bool,
4012}
4013
4014#[derive(Default)]
4015struct EventEffects {
4016 invalidations: Vec<InvalidationRequest>,
4017 wake_requests: Vec<WakeRequest>,
4018 pointer_capture_requests: Vec<PointerCaptureRequest>,
4019 drag_requests: Vec<DragRequest>,
4020 drop_acceptances: Vec<DropAcceptanceRequest>,
4021 posted_events: Vec<widget::PostedEventRequest>,
4022}
4023
4024impl EventEffects {
4025 fn extend(&mut self, dispatch: widget::EventDispatch) {
4026 self.invalidations.extend(dispatch.invalidations);
4027 self.wake_requests.extend(dispatch.wake_requests);
4028 self.pointer_capture_requests
4029 .extend(dispatch.pointer_capture_requests);
4030 self.drag_requests.extend(dispatch.drag_requests);
4031 self.drop_acceptances.extend(dispatch.drop_acceptances);
4032 self.posted_events.extend(dispatch.posted_events);
4033 }
4034
4035 fn merge(&mut self, effects: EventEffects) {
4036 self.invalidations.extend(effects.invalidations);
4037 self.wake_requests.extend(effects.wake_requests);
4038 self.pointer_capture_requests
4039 .extend(effects.pointer_capture_requests);
4040 self.drag_requests.extend(effects.drag_requests);
4041 self.drop_acceptances.extend(effects.drop_acceptances);
4042 self.posted_events.extend(effects.posted_events);
4043 }
4044}
4045
4046fn empty_dispatch() -> widget::EventDispatch {
4047 widget::EventDispatch {
4048 handled: false,
4049 invalidations: Vec::new(),
4050 focus_request: None,
4051 wake_requests: Vec::new(),
4052 pointer_capture_requests: Vec::new(),
4053 drag_requests: Vec::new(),
4054 drop_acceptances: Vec::new(),
4055 posted_events: Vec::new(),
4056 }
4057}
4058
4059fn nearest_drop_acceptance(
4060 acceptances: &[DropAcceptanceRequest],
4061 path: &[WidgetId],
4062) -> Option<DropAcceptanceRequest> {
4063 acceptances
4064 .iter()
4065 .filter_map(|acceptance| {
4066 path.iter()
4067 .position(|widget_id| *widget_id == acceptance.target)
4068 .map(|index| (index, *acceptance))
4069 })
4070 .max_by_key(|(index, _)| *index)
4071 .map(|(_, acceptance)| acceptance)
4072}
4073
4074fn collect_dirty_regions<F>(
4075 viewport: Size,
4076 invalidations: &[InvalidationRequest],
4077 repainted: bool,
4078 default_region_for: F,
4079) -> Vec<DirtyRegion>
4080where
4081 F: FnMut(&InvalidationRequest) -> Rect,
4082{
4083 let viewport_rect = Rect::from_origin_size(Point::ZERO, viewport);
4084 let mut default_region_for = default_region_for;
4085
4086 if invalidations.is_empty() {
4087 return if repainted {
4088 vec![DirtyRegion::new(viewport_rect, InvalidationKind::Paint)]
4089 } else {
4090 Vec::new()
4091 };
4092 }
4093 let mut dirty_regions: Vec<_> = invalidations
4094 .iter()
4095 .map(|request| {
4096 DirtyRegion::new(
4097 request
4098 .region
4099 .unwrap_or_else(|| default_region_for(request)),
4100 request.kind,
4101 )
4102 })
4103 .collect();
4104
4105 if repainted
4106 && dirty_regions
4107 .iter()
4108 .all(|region| region.kind != InvalidationKind::Paint)
4109 {
4110 dirty_regions.push(DirtyRegion::new(viewport_rect, InvalidationKind::Paint));
4111 }
4112
4113 dirty_regions
4114}
4115
4116fn collect_scene_layers(scene: &Scene) -> HashMap<WidgetId, SceneLayerDescriptor> {
4117 let mut layers = HashMap::new();
4118 scene.visit_layers(&mut |layer| {
4119 layers.insert(layer.widget_id(), layer.descriptor.clone());
4120 });
4121 layers
4122}
4123
4124fn retain_text_layouts_for_scene(text_system: &TextSystem, scene: &Scene) {
4125 text_system.retain_persistent_layouts(&active_text_layout_handles(scene));
4126}
4127
4128fn active_text_layout_handles(scene: &Scene) -> HashSet<TextLayoutHandle> {
4129 let mut handles = HashSet::new();
4130 scene.visit_commands(&mut |command| match command {
4131 SceneCommand::DrawShapedText(text) => {
4132 handles.insert(text.layout_handle);
4133 }
4134 SceneCommand::DrawShapedTextWindow(text) => {
4135 handles.insert(text.layout_handle);
4136 }
4137 _ => {}
4138 });
4139 handles
4140}
4141
4142fn resolve_snapshot_paint_boundary_or_root(
4143 snapshot: &WidgetGraphSnapshot,
4144 widget_id: WidgetId,
4145) -> WidgetId {
4146 let nodes = snapshot
4147 .nodes
4148 .iter()
4149 .map(|node| (node.id, node))
4150 .collect::<HashMap<_, _>>();
4151 let mut current = Some(widget_id);
4152 while let Some(candidate) = current {
4153 let Some(node) = nodes.get(&candidate) else {
4154 break;
4155 };
4156 if node.paint_boundary == PaintBoundaryMode::Explicit {
4157 return candidate;
4158 }
4159 current = node.parent;
4160 }
4161 snapshot.root
4162}
4163
4164#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4165enum HitTestCompositionPhase {
4166 Normal,
4167 Overlay,
4168 Effect,
4169}
4170
4171fn scene_hit_test_for_phase(
4172 scene: &Scene,
4173 point: Point,
4174 target_phase: HitTestCompositionPhase,
4175 inherited_phase: HitTestCompositionPhase,
4176) -> Option<WidgetId> {
4177 for command in scene.commands().iter().rev() {
4178 let SceneCommand::Layer(layer) = command else {
4179 continue;
4180 };
4181
4182 let layer_phase = next_hit_test_phase(inherited_phase, layer.descriptor.composition_mode);
4183 if !layer.descriptor.paint_bounds.contains(point) {
4184 continue;
4185 }
4186 if !layer.descriptor.hit_test {
4187 continue;
4188 }
4189
4190 if let Some(hit) = scene_hit_test_for_phase(&layer.scene, point, target_phase, layer_phase)
4191 {
4192 return Some(hit);
4193 }
4194
4195 if layer_phase == target_phase {
4196 return Some(layer.widget_id());
4197 }
4198 }
4199
4200 None
4201}
4202
4203fn next_hit_test_phase(
4204 inherited_phase: HitTestCompositionPhase,
4205 composition_mode: LayerCompositionMode,
4206) -> HitTestCompositionPhase {
4207 match (inherited_phase, composition_mode) {
4208 (HitTestCompositionPhase::Effect, _) | (_, LayerCompositionMode::Effect) => {
4209 HitTestCompositionPhase::Effect
4210 }
4211 (HitTestCompositionPhase::Overlay, _) | (_, LayerCompositionMode::Overlay) => {
4212 HitTestCompositionPhase::Overlay
4213 }
4214 _ => HitTestCompositionPhase::Normal,
4215 }
4216}
4217
4218fn invalidation_to_layer_update_kind(kind: InvalidationKind) -> Option<SceneLayerUpdateKind> {
4219 match kind {
4220 InvalidationKind::Measure | InvalidationKind::Arrange | InvalidationKind::Transform => {
4221 Some(SceneLayerUpdateKind::Transform)
4222 }
4223 InvalidationKind::Ordering => Some(SceneLayerUpdateKind::Ordering),
4224 InvalidationKind::Clip => Some(SceneLayerUpdateKind::Clip),
4225 InvalidationKind::Effect => Some(SceneLayerUpdateKind::Effect),
4226 InvalidationKind::Visibility => Some(SceneLayerUpdateKind::Visibility),
4227 InvalidationKind::Paint | InvalidationKind::Text => Some(SceneLayerUpdateKind::Content),
4228 InvalidationKind::Resources => Some(SceneLayerUpdateKind::Resources),
4229 InvalidationKind::HitTest | InvalidationKind::Semantics => None,
4230 }
4231}
4232
4233fn merge_layer_update_kind(
4234 updates: &mut HashMap<WidgetId, SceneLayerUpdateKind>,
4235 widget_id: WidgetId,
4236 kind: SceneLayerUpdateKind,
4237) {
4238 updates
4239 .entry(widget_id)
4240 .and_modify(|current| {
4241 if layer_update_priority(kind) > layer_update_priority(*current) {
4242 *current = kind;
4243 }
4244 })
4245 .or_insert(kind);
4246}
4247
4248fn layer_update_priority(kind: SceneLayerUpdateKind) -> u8 {
4249 match kind {
4250 SceneLayerUpdateKind::Visibility => 0,
4251 SceneLayerUpdateKind::Ordering => 1,
4252 SceneLayerUpdateKind::Transform => 2,
4253 SceneLayerUpdateKind::Clip => 3,
4254 SceneLayerUpdateKind::Content => 4,
4255 SceneLayerUpdateKind::Effect => 5,
4256 SceneLayerUpdateKind::Resources => 6,
4257 }
4258}
4259
4260#[derive(Debug, Clone, PartialEq)]
4261pub struct RenderOutput {
4262 pub title: String,
4263 pub frame: SceneFrame,
4264 pub semantics: Vec<SemanticsNode>,
4265 pub ime_composition_rect: Option<Rect>,
4266 pub diagnostics: RenderDiagnostics,
4267}
4268
4269#[cfg(test)]
4270mod tests {
4271 use std::{
4272 cell::RefCell,
4273 collections::VecDeque,
4274 path::PathBuf,
4275 rc::Rc,
4276 sync::{Arc, Mutex},
4277 };
4278
4279 use super::{
4280 Application, ArrangeCtx, EventCtx, EventPhase, FocusState, FrameSchedule, LayerOptions,
4281 MeasureCtx, PaintBoundaryMode, PaintCtx, RenderOutput, Runtime, SceneStatisticsDetailMode,
4282 SemanticsCtx, SingleChild, StackSurfaceOptions, Widget, WidgetChildren,
4283 WidgetGraphSnapshot, WidgetNodeSnapshot, WidgetPodMutVisitor, WidgetPodVisitor,
4284 WindowBuilder, WindowIcon, WindowRenderOptions, set_window_render_options,
4285 set_window_scene_statistics_detail_mode, window_render_options,
4286 };
4287 use sui_core::{
4288 AsyncWakeToken, Color, CustomEvent, DragEventKind, DragOutcome, DragPayload, DragScopeId,
4289 DragSessionId, DropEffect, Event, FontHandle, ImageHandle, KeyState, KeyboardEvent, Point,
4290 PointerButton, PointerButtons, PointerEvent, PointerEventKind, PointerKind, Rect,
4291 SemanticsAction, SemanticsActionRequest, SemanticsNode, SemanticsRole, SemanticsValue,
4292 Size, TimerToken, Vector, WakeEvent, WidgetId, WindowEvent,
4293 };
4294 use sui_layout::Constraints;
4295 use sui_scene::{
4296 LayerCompositionMode, LayerProperties, RegisteredExternalImage, RegisteredImage, Scene,
4297 SceneCommand, SceneLayerUpdateKind,
4298 };
4299 use sui_text::{PersistentTextLayout, RegisteredFont, TextStyle, TextSystem};
4300
4301 #[derive(Default)]
4302 struct Counters {
4303 paint: usize,
4304 semantics: usize,
4305 keyboard: usize,
4306 focus_changes: usize,
4307 }
4308
4309 struct FocusLeaf {
4310 counters: Rc<RefCell<Counters>>,
4311 }
4312
4313 struct WindowEventRecorder {
4314 events: Rc<RefCell<Vec<WindowEvent>>>,
4315 }
4316
4317 impl Widget for WindowEventRecorder {
4318 fn event(&mut self, _ctx: &mut EventCtx, event: &Event) {
4319 if let Event::Window(event) = event {
4320 self.events.borrow_mut().push(event.clone());
4321 }
4322 }
4323
4324 fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
4325 constraints.clamp(Size::new(120.0, 80.0))
4326 }
4327 }
4328
4329 const SYNTHETIC_ACTION_ID: WidgetId = WidgetId::new(u64::MAX - 1);
4330
4331 #[derive(Debug, Default)]
4332 struct SemanticActionState {
4333 actions: Vec<(WidgetId, SemanticsActionRequest)>,
4334 pointer_activations: usize,
4335 disabled: bool,
4336 expanded: bool,
4337 }
4338
4339 struct SyntheticSemanticActionLeaf {
4340 state: Rc<RefCell<SemanticActionState>>,
4341 }
4342
4343 struct UnfocusableSemanticLeaf;
4344
4345 impl Widget for UnfocusableSemanticLeaf {
4346 fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
4347 constraints.clamp(Size::new(120.0, 40.0))
4348 }
4349
4350 fn semantics(&self, ctx: &mut SemanticsCtx) {
4351 let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::Button, ctx.bounds());
4352 node.name = Some("unfocusable semantic node".to_string());
4353 node.actions = vec![SemanticsAction::Focus];
4354 ctx.push(node);
4355 }
4356 }
4357
4358 impl Widget for SyntheticSemanticActionLeaf {
4359 fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
4360 match event {
4361 Event::Semantics(event) => {
4362 self.state
4363 .borrow_mut()
4364 .actions
4365 .push((event.target, event.action.clone()));
4366 if !matches!(
4367 event.action,
4368 SemanticsActionRequest::Activate
4369 | SemanticsActionRequest::Blur
4370 | SemanticsActionRequest::Expand
4371 | SemanticsActionRequest::Collapse
4372 ) {
4373 ctx.set_handled();
4374 }
4375 }
4376 Event::Pointer(pointer) if pointer.kind == PointerEventKind::Up => {
4377 let mut state = self.state.borrow_mut();
4378 state.pointer_activations += 1;
4379 state.expanded = !state.expanded;
4380 ctx.set_handled();
4381 }
4382 _ => {}
4383 }
4384 }
4385
4386 fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
4387 constraints.clamp(Size::new(160.0, 64.0))
4388 }
4389
4390 fn paint(&self, ctx: &mut PaintCtx) {
4391 ctx.fill_bounds(Color::rgba(0.16, 0.24, 0.34, 1.0));
4392 }
4393
4394 fn semantics(&self, ctx: &mut SemanticsCtx) {
4395 let mut owner = SemanticsNode::new(
4396 ctx.widget_id(),
4397 SemanticsRole::GenericContainer,
4398 ctx.bounds(),
4399 );
4400 owner.name = Some("semantic action owner".to_string());
4401 ctx.push(owner);
4402
4403 let mut action = SemanticsNode::new(
4404 SYNTHETIC_ACTION_ID,
4405 SemanticsRole::Button,
4406 Rect::new(ctx.bounds().x() + 8.0, ctx.bounds().y() + 8.0, 80.0, 32.0),
4407 );
4408 action.parent = Some(ctx.widget_id());
4409 action.name = Some("virtual action".to_string());
4410 let state = self.state.borrow();
4411 action.state.disabled = state.disabled;
4412 action.state.expanded = Some(state.expanded);
4413 action.actions = vec![
4414 SemanticsAction::Focus,
4415 SemanticsAction::Blur,
4416 SemanticsAction::Activate,
4417 SemanticsAction::Expand,
4418 SemanticsAction::Collapse,
4419 SemanticsAction::SetValue,
4420 SemanticsAction::InsertText,
4421 ];
4422 ctx.push(action);
4423 }
4424
4425 fn accepts_focus(&self) -> bool {
4426 true
4427 }
4428 }
4429
4430 impl Widget for FocusLeaf {
4431 fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
4432 if let Event::Keyboard(_) = event {
4433 self.counters.borrow_mut().keyboard += 1;
4434 ctx.set_handled();
4435 }
4436 }
4437
4438 fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
4439 constraints.clamp(Size::new(120.0, 40.0))
4440 }
4441
4442 fn paint(&self, ctx: &mut PaintCtx) {
4443 self.counters.borrow_mut().paint += 1;
4444 ctx.fill_bounds(Color::rgba(0.22, 0.31, 0.42, 1.0));
4445 }
4446
4447 fn semantics(&self, ctx: &mut SemanticsCtx) {
4448 self.counters.borrow_mut().semantics += 1;
4449 let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::Button, ctx.bounds());
4450 node.name = Some("focus-leaf".to_string());
4451 ctx.push(node);
4452 }
4453
4454 fn accepts_focus(&self) -> bool {
4455 true
4456 }
4457
4458 fn focus_changed(&mut self, ctx: &mut EventCtx, _focused: bool) {
4459 self.counters.borrow_mut().focus_changes += 1;
4460 ctx.request_paint_rect(ctx.bounds());
4461 ctx.request_semantics();
4462 }
4463 }
4464
4465 struct TestRoot {
4466 counters: Rc<RefCell<Counters>>,
4467 child: SingleChild,
4468 }
4469
4470 impl Widget for TestRoot {
4471 fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
4472 if let Event::Custom(custom) = event
4473 && custom.kind == "semantics-only"
4474 {
4475 ctx.request_semantics();
4476 }
4477 }
4478
4479 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
4480 let size = constraints.clamp(Size::new(320.0, 180.0));
4481 self.child
4482 .measure(ctx, Constraints::tight(Size::new(120.0, 40.0)));
4483 size
4484 }
4485
4486 fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
4487 self.child.arrange(
4488 ctx,
4489 Rect::new(bounds.x() + 32.0, bounds.y() + 24.0, 120.0, 40.0),
4490 );
4491 }
4492
4493 fn paint(&self, ctx: &mut PaintCtx) {
4494 self.counters.borrow_mut().paint += 1;
4495 ctx.clear(Color::rgba(0.08, 0.09, 0.11, 1.0));
4496 self.child.paint(ctx);
4497 }
4498
4499 fn semantics(&self, ctx: &mut SemanticsCtx) {
4500 self.counters.borrow_mut().semantics += 1;
4501 ctx.push(SemanticsNode::new(
4502 ctx.widget_id(),
4503 SemanticsRole::Window,
4504 ctx.bounds(),
4505 ));
4506 self.child.semantics(ctx);
4507 }
4508
4509 fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
4510 self.child.visit_children(visitor);
4511 }
4512
4513 fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
4514 self.child.visit_children_mut(visitor);
4515 }
4516 }
4517
4518 #[derive(Debug, Default)]
4519 struct VirtualizedPaintState {
4520 painted: Vec<usize>,
4521 }
4522
4523 struct VirtualizedLeaf {
4524 index: usize,
4525 state: Rc<RefCell<VirtualizedPaintState>>,
4526 }
4527
4528 impl Widget for VirtualizedLeaf {
4529 fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
4530 constraints.clamp(Size::new(48.0, 24.0))
4531 }
4532
4533 fn paint(&self, ctx: &mut PaintCtx) {
4534 self.state.borrow_mut().painted.push(self.index);
4535 ctx.fill_bounds(Color::rgba(0.18, 0.31, 0.42, 1.0));
4536 }
4537 }
4538
4539 struct VirtualizedLogicalRoot {
4540 children: WidgetChildren,
4541 visible_count: usize,
4542 }
4543
4544 impl VirtualizedLogicalRoot {
4545 fn new(
4546 logical_count: usize,
4547 visible_count: usize,
4548 state: Rc<RefCell<VirtualizedPaintState>>,
4549 ) -> Self {
4550 let mut children = WidgetChildren::with_capacity(logical_count);
4551 for index in 0..logical_count {
4552 children.push(VirtualizedLeaf {
4553 index,
4554 state: Rc::clone(&state),
4555 });
4556 }
4557 Self {
4558 children,
4559 visible_count,
4560 }
4561 }
4562 }
4563
4564 impl Widget for VirtualizedLogicalRoot {
4565 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
4566 for index in 0..self.children.len() {
4567 self.children
4568 .measure_child(index, ctx, Constraints::tight(Size::new(48.0, 24.0)));
4569 }
4570 constraints.clamp(Size::new(320.0, 180.0))
4571 }
4572
4573 fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
4574 for index in 0..self.children.len() {
4575 self.children.arrange_child(
4576 index,
4577 ctx,
4578 Rect::new(bounds.x() + (index as f32 * 52.0), bounds.y(), 48.0, 24.0),
4579 );
4580 }
4581 }
4582
4583 fn paint(&self, ctx: &mut PaintCtx) {
4584 ctx.clear(Color::rgba(0.08, 0.09, 0.11, 1.0));
4585 for child in self.children.as_slice().iter().take(self.visible_count) {
4586 child.paint(ctx);
4587 }
4588 }
4589
4590 fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
4591 self.children.visit_children(visitor);
4592 }
4593
4594 fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
4595 self.children.visit_children_mut(visitor);
4596 }
4597 }
4598
4599 #[derive(Debug, Default)]
4600 struct ThreadedSnapshotState {
4601 async_token: Option<AsyncWakeToken>,
4602 latest: Option<String>,
4603 paints: usize,
4604 }
4605
4606 struct ThreadedSnapshotRoot {
4607 local: Rc<RefCell<ThreadedSnapshotState>>,
4608 inbox: Arc<Mutex<VecDeque<String>>>,
4609 }
4610
4611 impl Widget for ThreadedSnapshotRoot {
4612 fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
4613 match event {
4614 Event::Custom(custom) if custom.kind == "arm-threaded-snapshot" => {
4615 self.local.borrow_mut().async_token = Some(ctx.register_async_wakeup());
4616 ctx.set_handled();
4617 }
4618 Event::Wake(WakeEvent::Async { token, .. }) => {
4619 let mut local = self.local.borrow_mut();
4620 if local.async_token == Some(*token) {
4621 while let Some(value) = self.inbox.lock().unwrap().pop_front() {
4622 local.latest = Some(value);
4623 }
4624 ctx.request_paint();
4625 ctx.set_handled();
4626 }
4627 }
4628 _ => {}
4629 }
4630 }
4631
4632 fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
4633 constraints.clamp(Size::new(160.0, 64.0))
4634 }
4635
4636 fn paint(&self, ctx: &mut PaintCtx) {
4637 self.local.borrow_mut().paints += 1;
4638 let active = self.local.borrow().latest.is_some();
4639 let color = if active {
4640 Color::rgba(0.20, 0.46, 0.30, 1.0)
4641 } else {
4642 Color::rgba(0.20, 0.24, 0.32, 1.0)
4643 };
4644 ctx.fill_bounds(color);
4645 }
4646 }
4647
4648 #[derive(Debug, Clone, Copy, PartialEq)]
4649 struct CachedLayerPresentation {
4650 translation: Vector,
4651 opacity: f32,
4652 }
4653
4654 impl Default for CachedLayerPresentation {
4655 fn default() -> Self {
4656 Self {
4657 translation: Vector::ZERO,
4658 opacity: 1.0,
4659 }
4660 }
4661 }
4662
4663 struct CachedMoveLeaf {
4664 counters: Rc<RefCell<Counters>>,
4665 presentation: Rc<RefCell<CachedLayerPresentation>>,
4666 }
4667
4668 impl Widget for CachedMoveLeaf {
4669 fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
4670 constraints.clamp(Size::new(220.0, 72.0))
4671 }
4672
4673 fn paint(&self, ctx: &mut PaintCtx) {
4674 self.counters.borrow_mut().paint += 1;
4675 ctx.fill_bounds(Color::rgba(0.14, 0.42, 0.72, 1.0));
4676 }
4677
4678 fn layer_options(&self) -> LayerOptions {
4679 LayerOptions {
4680 paint_boundary: PaintBoundaryMode::Explicit,
4681 composition_mode: sui_scene::LayerCompositionMode::Scroll,
4682 }
4683 }
4684
4685 fn layer_properties(&self) -> LayerProperties {
4686 let presentation = *self.presentation.borrow();
4687 LayerProperties::default()
4688 .with_translation(presentation.translation)
4689 .with_opacity(presentation.opacity)
4690 }
4691 }
4692
4693 struct DirectMoveLeaf {
4694 counters: Rc<RefCell<Counters>>,
4695 }
4696
4697 impl Widget for DirectMoveLeaf {
4698 fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
4699 constraints.clamp(Size::new(140.0, 48.0))
4700 }
4701
4702 fn paint(&self, ctx: &mut PaintCtx) {
4703 self.counters.borrow_mut().paint += 1;
4704 ctx.fill_bounds(Color::rgba(0.78, 0.43, 0.14, 1.0));
4705 }
4706 }
4707
4708 struct OverpaintLeaf {
4709 size: Size,
4710 color: Color,
4711 bleed: Vector,
4712 }
4713
4714 impl Widget for OverpaintLeaf {
4715 fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
4716 constraints.clamp(self.size)
4717 }
4718
4719 fn paint(&self, ctx: &mut PaintCtx) {
4720 ctx.fill_rect(
4721 ctx.bounds().inflate(self.bleed.x.abs(), self.bleed.y.abs()),
4722 self.color,
4723 );
4724 }
4725 }
4726
4727 struct PointerCountingLeaf {
4728 pointer_downs: Rc<RefCell<usize>>,
4729 }
4730
4731 impl Widget for PointerCountingLeaf {
4732 fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
4733 if matches!(
4734 event,
4735 Event::Pointer(pointer)
4736 if pointer.kind == PointerEventKind::Down
4737 && pointer.button == Some(PointerButton::Primary)
4738 ) {
4739 *self.pointer_downs.borrow_mut() += 1;
4740 ctx.set_handled();
4741 }
4742 }
4743
4744 fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
4745 constraints.clamp(Size::new(120.0, 40.0))
4746 }
4747
4748 fn paint(&self, ctx: &mut PaintCtx) {
4749 ctx.fill_bounds(Color::rgba(0.15, 0.35, 0.58, 1.0));
4750 }
4751 }
4752
4753 struct NonHitTestOverlayLeaf;
4754
4755 impl Widget for NonHitTestOverlayLeaf {
4756 fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
4757 constraints.clamp(Size::new(120.0, 40.0))
4758 }
4759
4760 fn paint(&self, ctx: &mut PaintCtx) {
4761 ctx.fill_bounds(Color::rgba(0.9, 0.2, 0.2, 0.35));
4762 }
4763
4764 fn layer_options(&self) -> LayerOptions {
4765 LayerOptions {
4766 paint_boundary: PaintBoundaryMode::Explicit,
4767 composition_mode: LayerCompositionMode::Overlay,
4768 }
4769 }
4770
4771 fn stack_surface_options(&self) -> Option<StackSurfaceOptions> {
4772 Some(StackSurfaceOptions {
4773 hit_test: false,
4774 ..StackSurfaceOptions::default()
4775 })
4776 }
4777 }
4778
4779 struct OverlayPassThroughRoot {
4780 children: WidgetChildren,
4781 }
4782
4783 impl OverlayPassThroughRoot {
4784 fn new(pointer_downs: Rc<RefCell<usize>>) -> Self {
4785 let mut children = WidgetChildren::with_capacity(2);
4786 children.push(PointerCountingLeaf { pointer_downs });
4787 children.push(NonHitTestOverlayLeaf);
4788 Self { children }
4789 }
4790 }
4791
4792 impl Widget for OverlayPassThroughRoot {
4793 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
4794 let size = constraints.clamp(Size::new(320.0, 180.0));
4795 self.children
4796 .measure_child(0, ctx, Constraints::tight(Size::new(120.0, 40.0)));
4797 self.children
4798 .measure_child(1, ctx, Constraints::tight(Size::new(120.0, 40.0)));
4799 size
4800 }
4801
4802 fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
4803 let child_bounds = Rect::new(bounds.x() + 32.0, bounds.y() + 24.0, 120.0, 40.0);
4804 self.children.arrange_child(0, ctx, child_bounds);
4805 self.children.arrange_child(1, ctx, child_bounds);
4806 }
4807
4808 fn paint(&self, ctx: &mut PaintCtx) {
4809 ctx.clear(Color::rgba(0.08, 0.09, 0.11, 1.0));
4810 self.children.paint(ctx);
4811 }
4812
4813 fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
4814 self.children.visit_children(visitor);
4815 }
4816
4817 fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
4818 self.children.visit_children_mut(visitor);
4819 }
4820 }
4821
4822 struct HitTestOverlaySurface {
4823 child: SingleChild,
4824 }
4825
4826 impl HitTestOverlaySurface {
4827 fn new(pointer_downs: Rc<RefCell<usize>>) -> Self {
4828 Self {
4829 child: SingleChild::new(PointerCountingLeaf { pointer_downs }),
4830 }
4831 }
4832 }
4833
4834 impl Widget for HitTestOverlaySurface {
4835 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
4836 self.child
4837 .measure(ctx, Constraints::tight(Size::new(120.0, 40.0)));
4838 constraints.clamp(Size::new(180.0, 90.0))
4839 }
4840
4841 fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
4842 self.child.arrange(
4843 ctx,
4844 Rect::new(bounds.x() + 24.0, bounds.y() + 20.0, 120.0, 40.0),
4845 );
4846 }
4847
4848 fn paint(&self, ctx: &mut PaintCtx) {
4849 ctx.fill_bounds(Color::rgba(0.9, 0.2, 0.2, 0.35));
4850 self.child.paint(ctx);
4851 }
4852
4853 fn layer_options(&self) -> LayerOptions {
4854 LayerOptions {
4855 paint_boundary: PaintBoundaryMode::Explicit,
4856 composition_mode: LayerCompositionMode::Effect,
4857 }
4858 }
4859
4860 fn stack_surface_options(&self) -> Option<StackSurfaceOptions> {
4861 Some(StackSurfaceOptions::default())
4862 }
4863
4864 fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
4865 self.child.visit_children(visitor);
4866 }
4867
4868 fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
4869 self.child.visit_children_mut(visitor);
4870 }
4871 }
4872
4873 struct HitTestOverlayRoot {
4874 child: SingleChild,
4875 }
4876
4877 impl HitTestOverlayRoot {
4878 fn new(pointer_downs: Rc<RefCell<usize>>) -> Self {
4879 Self {
4880 child: SingleChild::new(HitTestOverlaySurface::new(pointer_downs)),
4881 }
4882 }
4883 }
4884
4885 impl Widget for HitTestOverlayRoot {
4886 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
4887 self.child
4888 .measure(ctx, Constraints::tight(Size::new(180.0, 90.0)));
4889 constraints.clamp(Size::new(320.0, 180.0))
4890 }
4891
4892 fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
4893 self.child.arrange(
4894 ctx,
4895 Rect::new(bounds.x() + 20.0, bounds.y() + 20.0, 180.0, 90.0),
4896 );
4897 }
4898
4899 fn paint(&self, ctx: &mut PaintCtx) {
4900 ctx.clear(Color::rgba(0.08, 0.09, 0.11, 1.0));
4901 self.child.paint(ctx);
4902 }
4903
4904 fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
4905 self.child.visit_children(visitor);
4906 }
4907
4908 fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
4909 self.child.visit_children_mut(visitor);
4910 }
4911 }
4912
4913 struct DirectMoveRoot {
4914 counters: Rc<RefCell<Counters>>,
4915 child: SingleChild,
4916 offset_x: f32,
4917 }
4918
4919 impl Widget for DirectMoveRoot {
4920 fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
4921 if let Event::Custom(custom) = event
4922 && custom.kind == "shift-direct"
4923 {
4924 self.offset_x += 36.0;
4925 ctx.request_arrange();
4926 }
4927 }
4928
4929 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
4930 let size = constraints.clamp(Size::new(320.0, 180.0));
4931 self.child
4932 .measure(ctx, Constraints::tight(Size::new(140.0, 48.0)));
4933 size
4934 }
4935
4936 fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
4937 self.child.arrange(
4938 ctx,
4939 Rect::new(
4940 bounds.x() + 28.0 + self.offset_x,
4941 bounds.y() + 32.0,
4942 140.0,
4943 48.0,
4944 ),
4945 );
4946 }
4947
4948 fn paint(&self, ctx: &mut PaintCtx) {
4949 self.counters.borrow_mut().paint += 1;
4950 ctx.clear(Color::rgba(0.08, 0.09, 0.11, 1.0));
4951 self.child.paint(ctx);
4952 }
4953
4954 fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
4955 self.child.visit_children(visitor);
4956 }
4957
4958 fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
4959 self.child.visit_children_mut(visitor);
4960 }
4961 }
4962
4963 struct CachedMoveRoot {
4964 counters: Rc<RefCell<Counters>>,
4965 child: SingleChild,
4966 presentation: Rc<RefCell<CachedLayerPresentation>>,
4967 offset_x: f32,
4968 paint_background: bool,
4969 }
4970
4971 impl Widget for CachedMoveRoot {
4972 fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
4973 if let Event::Custom(custom) = event
4974 && custom.kind == "shift-cached"
4975 {
4976 self.offset_x += 48.0;
4977 ctx.request_arrange();
4978 }
4979 if let Event::Custom(custom) = event
4980 && custom.kind == "nudge-cached-layer-property"
4981 {
4982 self.presentation.borrow_mut().translation += Vector::new(18.0, 0.0);
4983 ctx.request_transform();
4984 }
4985 if let Event::Custom(custom) = event
4986 && custom.kind == "fade-cached-layer"
4987 {
4988 self.presentation.borrow_mut().opacity = 0.5;
4989 ctx.request_effect();
4990 }
4991 }
4992
4993 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
4994 let size = constraints.clamp(Size::new(320.0, 180.0));
4995 self.child
4996 .measure(ctx, Constraints::tight(Size::new(220.0, 72.0)));
4997 size
4998 }
4999
5000 fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
5001 self.child.arrange(
5002 ctx,
5003 Rect::new(
5004 bounds.x() + 24.0 + self.offset_x,
5005 bounds.y() + 28.0,
5006 220.0,
5007 72.0,
5008 ),
5009 );
5010 }
5011
5012 fn paint(&self, ctx: &mut PaintCtx) {
5013 self.counters.borrow_mut().paint += 1;
5014 if self.paint_background {
5015 ctx.clear(Color::rgba(0.08, 0.09, 0.11, 1.0));
5016 }
5017 self.child.paint(ctx);
5018 }
5019
5020 fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
5021 self.child.visit_children(visitor);
5022 }
5023
5024 fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
5025 self.child.visit_children_mut(visitor);
5026 }
5027 }
5028
5029 struct FocusTraversalRoot {
5030 children: WidgetChildren,
5031 }
5032
5033 impl FocusTraversalRoot {
5034 fn new(first: Rc<RefCell<Counters>>, second: Rc<RefCell<Counters>>) -> Self {
5035 let mut children = WidgetChildren::with_capacity(2);
5036 children.push(FocusLeaf { counters: first });
5037 children.push(FocusLeaf { counters: second });
5038 Self { children }
5039 }
5040 }
5041
5042 impl Widget for FocusTraversalRoot {
5043 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
5044 let size = constraints.clamp(Size::new(320.0, 180.0));
5045 self.children
5046 .measure_child(0, ctx, Constraints::tight(Size::new(120.0, 40.0)));
5047 self.children
5048 .measure_child(1, ctx, Constraints::tight(Size::new(120.0, 40.0)));
5049 size
5050 }
5051
5052 fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
5053 self.children.arrange_child(
5054 0,
5055 ctx,
5056 Rect::new(bounds.x() + 32.0, bounds.y() + 24.0, 120.0, 40.0),
5057 );
5058 self.children.arrange_child(
5059 1,
5060 ctx,
5061 Rect::new(bounds.x() + 32.0, bounds.y() + 80.0, 120.0, 40.0),
5062 );
5063 }
5064
5065 fn paint(&self, ctx: &mut PaintCtx) {
5066 ctx.clear(Color::rgba(0.08, 0.09, 0.11, 1.0));
5067 self.children.paint(ctx);
5068 }
5069
5070 fn semantics(&self, ctx: &mut SemanticsCtx) {
5071 ctx.push(SemanticsNode::new(
5072 ctx.widget_id(),
5073 SemanticsRole::Window,
5074 ctx.bounds(),
5075 ));
5076 self.children.semantics(ctx);
5077 }
5078
5079 fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
5080 self.children.visit_children(visitor);
5081 }
5082
5083 fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
5084 self.children.visit_children_mut(visitor);
5085 }
5086 }
5087
5088 struct HoverTransitionRoot {
5089 children: WidgetChildren,
5090 }
5091
5092 impl HoverTransitionRoot {
5093 fn new(
5094 first: Rc<RefCell<HoverTransitionState>>,
5095 second: Rc<RefCell<HoverTransitionState>>,
5096 ) -> Self {
5097 let mut children = WidgetChildren::with_capacity(2);
5098 children.push(HoverTransitionLeaf {
5099 name: "hover-first",
5100 state: first,
5101 });
5102 children.push(HoverTransitionLeaf {
5103 name: "hover-second",
5104 state: second,
5105 });
5106 Self { children }
5107 }
5108 }
5109
5110 impl Widget for HoverTransitionRoot {
5111 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
5112 let size = constraints.clamp(Size::new(320.0, 180.0));
5113 self.children
5114 .measure_child(0, ctx, Constraints::tight(Size::new(120.0, 40.0)));
5115 self.children
5116 .measure_child(1, ctx, Constraints::tight(Size::new(120.0, 40.0)));
5117 size
5118 }
5119
5120 fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
5121 self.children.arrange_child(
5122 0,
5123 ctx,
5124 Rect::new(bounds.x() + 32.0, bounds.y() + 24.0, 120.0, 40.0),
5125 );
5126 self.children.arrange_child(
5127 1,
5128 ctx,
5129 Rect::new(bounds.x() + 172.0, bounds.y() + 24.0, 120.0, 40.0),
5130 );
5131 }
5132
5133 fn paint(&self, ctx: &mut PaintCtx) {
5134 ctx.clear(Color::rgba(0.08, 0.09, 0.11, 1.0));
5135 self.children.paint(ctx);
5136 }
5137
5138 fn semantics(&self, ctx: &mut SemanticsCtx) {
5139 ctx.push(SemanticsNode::new(
5140 ctx.widget_id(),
5141 SemanticsRole::Window,
5142 ctx.bounds(),
5143 ));
5144 self.children.semantics(ctx);
5145 }
5146
5147 fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
5148 self.children.visit_children(visitor);
5149 }
5150
5151 fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
5152 self.children.visit_children_mut(visitor);
5153 }
5154 }
5155
5156 #[derive(Default)]
5157 struct PointerCaptureState {
5158 moves: usize,
5159 ups: usize,
5160 cancels: usize,
5161 cancel_followups: usize,
5162 last_cancel: Option<PointerEvent>,
5163 }
5164
5165 #[derive(Debug, Default)]
5166 struct RuntimeDragState {
5167 source_moves: usize,
5168 target_overs: usize,
5169 drops: usize,
5170 ends: usize,
5171 outcome: Option<DragOutcome>,
5172 }
5173
5174 #[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]
5175 struct HoverTransitionState {
5176 enters: usize,
5177 leaves: usize,
5178 hovered: bool,
5179 }
5180
5181 struct PointerCaptureLeaf {
5182 state: Rc<RefCell<PointerCaptureState>>,
5183 recapture_on_move: bool,
5184 }
5185
5186 struct PointerCaptureTransferRoot {
5187 child: SingleChild,
5188 }
5189
5190 #[derive(Default)]
5191 struct ReentrantCaptureState {
5192 intermediate_id: Option<WidgetId>,
5193 pointer_id: Option<u64>,
5194 source_cancels: usize,
5195 intermediate_captures: usize,
5196 intermediate_cancels: usize,
5197 }
5198
5199 struct ReentrantCaptureSource {
5200 state: Rc<RefCell<ReentrantCaptureState>>,
5201 }
5202
5203 struct ReentrantCaptureIntermediate {
5204 state: Rc<RefCell<ReentrantCaptureState>>,
5205 }
5206
5207 struct ReentrantCaptureRoot {
5208 children: WidgetChildren,
5209 }
5210
5211 struct RuntimeDragSource {
5212 state: Rc<RefCell<RuntimeDragState>>,
5213 scope: DragScopeId,
5214 session: Option<DragSessionId>,
5215 }
5216
5217 struct RuntimeDragTarget {
5218 state: Rc<RefCell<RuntimeDragState>>,
5219 scope: DragScopeId,
5220 }
5221
5222 struct RuntimeDragRoot {
5223 children: WidgetChildren,
5224 }
5225
5226 struct HoverTransitionLeaf {
5227 name: &'static str,
5228 state: Rc<RefCell<HoverTransitionState>>,
5229 }
5230
5231 impl Widget for PointerCaptureLeaf {
5232 fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
5233 if let Event::Custom(custom) = event
5234 && custom.kind == "pointer-cancel-followup"
5235 {
5236 self.state.borrow_mut().cancel_followups += 1;
5237 return;
5238 }
5239
5240 let Event::Pointer(pointer) = event else {
5241 return;
5242 };
5243
5244 match pointer.kind {
5245 PointerEventKind::Down => {
5246 ctx.request_pointer_capture(pointer.pointer_id);
5247 ctx.set_handled();
5248 }
5249 PointerEventKind::Move => {
5250 self.state.borrow_mut().moves += 1;
5251 if self.recapture_on_move {
5252 ctx.request_pointer_capture(pointer.pointer_id);
5253 }
5254 ctx.set_handled();
5255 }
5256 PointerEventKind::Up => {
5257 self.state.borrow_mut().ups += 1;
5258 ctx.set_handled();
5259 }
5260 PointerEventKind::Cancel => {
5261 let mut state = self.state.borrow_mut();
5262 state.cancels += 1;
5263 state.last_cancel = Some(pointer.clone());
5264 drop(state);
5265 ctx.release_pointer_capture(pointer.pointer_id);
5266 ctx.request_paint();
5267 ctx.post_event(
5268 ctx.widget_id(),
5269 Event::Custom(CustomEvent::new("pointer-cancel-followup")),
5270 );
5271 ctx.set_handled();
5272 }
5273 _ => {}
5274 }
5275 }
5276
5277 fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
5278 constraints.clamp(Size::new(120.0, 40.0))
5279 }
5280 }
5281
5282 impl PointerCaptureTransferRoot {
5283 fn new(child: PointerCaptureLeaf) -> Self {
5284 Self {
5285 child: SingleChild::new(child),
5286 }
5287 }
5288 }
5289
5290 impl Widget for PointerCaptureTransferRoot {
5291 fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
5292 if let Event::Pointer(pointer) = event
5293 && pointer.kind == PointerEventKind::Move
5294 && ctx.phase() == EventPhase::Capture
5295 {
5296 ctx.request_pointer_capture(pointer.pointer_id);
5297 }
5298 }
5299
5300 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
5301 let size = constraints.clamp(Size::new(320.0, 180.0));
5302 self.child
5303 .measure(ctx, Constraints::tight(Size::new(120.0, 40.0)));
5304 size
5305 }
5306
5307 fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
5308 self.child.arrange(
5309 ctx,
5310 Rect::new(bounds.x() + 32.0, bounds.y() + 24.0, 120.0, 40.0),
5311 );
5312 }
5313
5314 fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
5315 self.child.visit_children(visitor);
5316 }
5317
5318 fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
5319 self.child.visit_children_mut(visitor);
5320 }
5321 }
5322
5323 impl ReentrantCaptureRoot {
5324 fn new(state: Rc<RefCell<ReentrantCaptureState>>) -> Self {
5325 let mut children = WidgetChildren::with_capacity(2);
5326 children.push(ReentrantCaptureSource {
5327 state: Rc::clone(&state),
5328 });
5329 children.push(ReentrantCaptureIntermediate { state });
5330 Self { children }
5331 }
5332 }
5333
5334 impl Widget for ReentrantCaptureRoot {
5335 fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
5336 if let Event::Pointer(pointer) = event
5337 && pointer.kind == PointerEventKind::Move
5338 && ctx.phase() == EventPhase::Capture
5339 {
5340 ctx.request_pointer_capture(pointer.pointer_id);
5341 }
5342 }
5343
5344 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
5345 let size = constraints.clamp(Size::new(320.0, 180.0));
5346 self.children
5347 .measure_child(0, ctx, Constraints::tight(Size::new(120.0, 40.0)));
5348 self.children
5349 .measure_child(1, ctx, Constraints::tight(Size::new(80.0, 40.0)));
5350 size
5351 }
5352
5353 fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
5354 self.children.arrange_child(
5355 0,
5356 ctx,
5357 Rect::new(bounds.x() + 32.0, bounds.y() + 24.0, 120.0, 40.0),
5358 );
5359 self.children.arrange_child(
5360 1,
5361 ctx,
5362 Rect::new(bounds.x() + 180.0, bounds.y() + 24.0, 80.0, 40.0),
5363 );
5364 }
5365
5366 fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
5367 self.children.visit_children(visitor);
5368 }
5369
5370 fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
5371 self.children.visit_children_mut(visitor);
5372 }
5373 }
5374
5375 impl Widget for ReentrantCaptureSource {
5376 fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
5377 let Event::Pointer(pointer) = event else {
5378 return;
5379 };
5380
5381 match pointer.kind {
5382 PointerEventKind::Down => {
5383 ctx.request_pointer_capture(pointer.pointer_id);
5384 ctx.set_handled();
5385 }
5386 PointerEventKind::Move => {
5387 ctx.set_handled();
5388 }
5389 PointerEventKind::Cancel => {
5390 let intermediate_id = {
5391 let mut state = self.state.borrow_mut();
5392 state.source_cancels += 1;
5393 state.pointer_id = Some(pointer.pointer_id);
5394 state.intermediate_id.expect("intermediate measured")
5395 };
5396 ctx.release_pointer_capture(pointer.pointer_id);
5397 ctx.post_event(
5398 intermediate_id,
5399 Event::Custom(CustomEvent::new("capture-intermediate")),
5400 );
5401 ctx.set_handled();
5402 }
5403 _ => {}
5404 }
5405 }
5406
5407 fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
5408 constraints.clamp(Size::new(120.0, 40.0))
5409 }
5410 }
5411
5412 impl Widget for ReentrantCaptureIntermediate {
5413 fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
5414 match event {
5415 Event::Custom(custom) if custom.kind == "capture-intermediate" => {
5416 let pointer_id = self.state.borrow().pointer_id.expect("pointer recorded");
5417 self.state.borrow_mut().intermediate_captures += 1;
5418 ctx.request_pointer_capture(pointer_id);
5419 }
5420 Event::Pointer(pointer) if pointer.kind == PointerEventKind::Cancel => {
5421 self.state.borrow_mut().intermediate_cancels += 1;
5422 ctx.release_pointer_capture(pointer.pointer_id);
5423 ctx.set_handled();
5424 }
5425 _ => {}
5426 }
5427 }
5428
5429 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
5430 self.state.borrow_mut().intermediate_id = Some(ctx.widget_id());
5431 constraints.clamp(Size::new(80.0, 40.0))
5432 }
5433 }
5434
5435 impl Widget for RuntimeDragSource {
5436 fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
5437 match event {
5438 Event::Pointer(pointer) => match pointer.kind {
5439 PointerEventKind::Down => {
5440 ctx.request_pointer_capture(pointer.pointer_id);
5441 ctx.set_handled();
5442 }
5443 PointerEventKind::Move if pointer.buttons.contains(PointerButton::Primary) => {
5444 self.state.borrow_mut().source_moves += 1;
5445 if self.session.is_none() {
5446 self.session = Some(ctx.begin_drag(
5447 self.scope,
5448 pointer.pointer_id,
5449 pointer.position,
5450 DragPayload::text("runtime"),
5451 DropEffect::Move,
5452 Some("runtime".to_string()),
5453 ));
5454 }
5455 ctx.set_handled();
5456 }
5457 PointerEventKind::Up => {
5458 ctx.set_handled();
5459 }
5460 _ => {}
5461 },
5462 Event::Drag(drag)
5463 if drag.kind == DragEventKind::End && self.session == Some(drag.session_id) =>
5464 {
5465 let mut state = self.state.borrow_mut();
5466 state.ends += 1;
5467 state.outcome = drag.outcome;
5468 self.session = None;
5469 ctx.set_handled();
5470 }
5471 _ => {}
5472 }
5473 }
5474
5475 fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
5476 constraints.clamp(Size::new(120.0, 40.0))
5477 }
5478 }
5479
5480 impl Widget for RuntimeDragTarget {
5481 fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
5482 let Event::Drag(drag) = event else {
5483 return;
5484 };
5485 if drag.scope_id != self.scope {
5486 return;
5487 }
5488 match drag.kind {
5489 DragEventKind::Over => {
5490 self.state.borrow_mut().target_overs += 1;
5491 ctx.accept_drop(DropEffect::Move);
5492 }
5493 DragEventKind::Drop => {
5494 self.state.borrow_mut().drops += 1;
5495 ctx.set_handled();
5496 }
5497 _ => {}
5498 }
5499 }
5500
5501 fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
5502 constraints.clamp(Size::new(120.0, 40.0))
5503 }
5504 }
5505
5506 impl RuntimeDragRoot {
5507 fn new(state: Rc<RefCell<RuntimeDragState>>) -> Self {
5508 let scope = DragScopeId::new(77);
5509 let mut children = WidgetChildren::with_capacity(2);
5510 children.push(RuntimeDragSource {
5511 state: Rc::clone(&state),
5512 scope,
5513 session: None,
5514 });
5515 children.push(RuntimeDragTarget { state, scope });
5516 Self { children }
5517 }
5518 }
5519
5520 impl Widget for RuntimeDragRoot {
5521 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
5522 let size = constraints.clamp(Size::new(320.0, 180.0));
5523 self.children
5524 .measure_child(0, ctx, Constraints::tight(Size::new(120.0, 40.0)));
5525 self.children
5526 .measure_child(1, ctx, Constraints::tight(Size::new(120.0, 40.0)));
5527 size
5528 }
5529
5530 fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
5531 self.children.arrange_child(
5532 0,
5533 ctx,
5534 Rect::new(bounds.x() + 32.0, bounds.y() + 24.0, 120.0, 40.0),
5535 );
5536 self.children.arrange_child(
5537 1,
5538 ctx,
5539 Rect::new(bounds.x() + 172.0, bounds.y() + 24.0, 120.0, 40.0),
5540 );
5541 }
5542
5543 fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
5544 self.children.visit_children(visitor);
5545 }
5546
5547 fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
5548 self.children.visit_children_mut(visitor);
5549 }
5550 }
5551
5552 impl Widget for HoverTransitionLeaf {
5553 fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
5554 let Event::Pointer(pointer) = event else {
5555 return;
5556 };
5557
5558 let mut state = self.state.borrow_mut();
5559 match pointer.kind {
5560 PointerEventKind::Enter => {
5561 state.enters += 1;
5562 state.hovered = true;
5563 ctx.request_paint();
5564 ctx.request_semantics();
5565 }
5566 PointerEventKind::Leave => {
5567 state.leaves += 1;
5568 state.hovered = false;
5569 ctx.request_paint();
5570 ctx.request_semantics();
5571 }
5572 _ => {}
5573 }
5574 }
5575
5576 fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
5577 constraints.clamp(Size::new(120.0, 40.0))
5578 }
5579
5580 fn paint(&self, ctx: &mut PaintCtx) {
5581 let color = if self.state.borrow().hovered {
5582 Color::rgba(0.28, 0.45, 0.68, 1.0)
5583 } else {
5584 Color::rgba(0.20, 0.28, 0.38, 1.0)
5585 };
5586 ctx.fill_bounds(color);
5587 }
5588
5589 fn semantics(&self, ctx: &mut SemanticsCtx) {
5590 let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::Button, ctx.bounds());
5591 node.name = Some(self.name.to_string());
5592 node.state.hovered = self.state.borrow().hovered;
5593 ctx.push(node);
5594 }
5595 }
5596
5597 #[derive(Default)]
5598 struct WakeState {
5599 timer_token: Option<TimerToken>,
5600 async_token: Option<AsyncWakeToken>,
5601 timer_wakes: usize,
5602 async_wakes: usize,
5603 }
5604
5605 struct WakeLeaf {
5606 state: Rc<RefCell<WakeState>>,
5607 }
5608
5609 impl Widget for WakeLeaf {
5610 fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
5611 match event {
5612 Event::Pointer(pointer) if pointer.kind == PointerEventKind::Down => {
5613 let mut state = self.state.borrow_mut();
5614 state.timer_token = Some(ctx.schedule_timer_after(3.0));
5615 state.async_token = Some(ctx.register_async_wakeup());
5616 ctx.set_handled();
5617 }
5618 Event::Wake(WakeEvent::Timer { token, .. }) => {
5619 let mut state = self.state.borrow_mut();
5620 if state.timer_token == Some(*token) {
5621 state.timer_wakes += 1;
5622 ctx.request_paint();
5623 ctx.set_handled();
5624 }
5625 }
5626 Event::Wake(WakeEvent::Async { token, .. }) => {
5627 let mut state = self.state.borrow_mut();
5628 if state.async_token == Some(*token) {
5629 state.async_wakes += 1;
5630 ctx.request_paint();
5631 ctx.set_handled();
5632 }
5633 }
5634 _ => {}
5635 }
5636 }
5637
5638 fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
5639 constraints.clamp(Size::new(120.0, 40.0))
5640 }
5641 }
5642
5643 #[derive(Default)]
5644 struct AnimationWakeState {
5645 request_twice: bool,
5646 animation_wakes: usize,
5647 last_animation_time: Option<f64>,
5648 last_animation_delta: Option<f64>,
5649 last_animation_frame_index: Option<u64>,
5650 }
5651
5652 struct AnimationWakeLeaf {
5653 state: Rc<RefCell<AnimationWakeState>>,
5654 }
5655
5656 impl Widget for AnimationWakeLeaf {
5657 fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
5658 match event {
5659 Event::Pointer(pointer) if pointer.kind == PointerEventKind::Down => {
5660 let request_twice = self.state.borrow().request_twice;
5661 ctx.request_animation_frame();
5662 if request_twice {
5663 ctx.request_animation_frame();
5664 }
5665 ctx.set_handled();
5666 }
5667 Event::Wake(WakeEvent::AnimationFrame {
5668 time,
5669 delta,
5670 frame_index,
5671 }) => {
5672 let mut state = self.state.borrow_mut();
5673 state.animation_wakes += 1;
5674 state.last_animation_time = Some(*time);
5675 state.last_animation_delta = Some(*delta);
5676 state.last_animation_frame_index = Some(*frame_index);
5677 ctx.request_paint();
5678 ctx.set_handled();
5679 }
5680 _ => {}
5681 }
5682 }
5683
5684 fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
5685 constraints.clamp(Size::new(120.0, 40.0))
5686 }
5687 }
5688
5689 struct AnimationWakeCapturingRoot {
5690 child: SingleChild,
5691 ancestor_wakes: Rc<RefCell<usize>>,
5692 }
5693
5694 impl Widget for AnimationWakeCapturingRoot {
5695 fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
5696 if matches!(event, Event::Wake(WakeEvent::AnimationFrame { .. })) {
5697 *self.ancestor_wakes.borrow_mut() += 1;
5698 ctx.set_handled();
5699 }
5700 }
5701
5702 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
5703 let size = constraints.clamp(Size::new(320.0, 180.0));
5704 self.child
5705 .measure(ctx, Constraints::tight(Size::new(120.0, 40.0)));
5706 size
5707 }
5708
5709 fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
5710 self.child.arrange(
5711 ctx,
5712 Rect::new(bounds.x() + 32.0, bounds.y() + 24.0, 120.0, 40.0),
5713 );
5714 }
5715
5716 fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
5717 self.child.visit_children(visitor);
5718 }
5719
5720 fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
5721 self.child.visit_children_mut(visitor);
5722 }
5723 }
5724
5725 struct RemovableAnimationRoot {
5726 child: Option<SingleChild>,
5727 }
5728
5729 impl Widget for RemovableAnimationRoot {
5730 fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
5731 if let Event::Custom(custom) = event
5732 && custom.kind == "drop-animation-child"
5733 {
5734 self.child = None;
5735 ctx.request_measure();
5736 ctx.set_handled();
5737 }
5738 }
5739
5740 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
5741 let size = constraints.clamp(Size::new(320.0, 180.0));
5742 if let Some(child) = &mut self.child {
5743 child.measure(ctx, Constraints::tight(Size::new(120.0, 40.0)));
5744 }
5745 size
5746 }
5747
5748 fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
5749 if let Some(child) = &mut self.child {
5750 child.arrange(
5751 ctx,
5752 Rect::new(bounds.x() + 32.0, bounds.y() + 24.0, 120.0, 40.0),
5753 );
5754 }
5755 }
5756
5757 fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
5758 if let Some(child) = &self.child {
5759 child.visit_children(visitor);
5760 }
5761 }
5762
5763 fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
5764 if let Some(child) = &mut self.child {
5765 child.visit_children_mut(visitor);
5766 }
5767 }
5768 }
5769
5770 struct TextImeLeaf {
5771 layout: RefCell<Option<PersistentTextLayout>>,
5772 }
5773
5774 impl Widget for TextImeLeaf {
5775 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
5776 let size = constraints.clamp(Size::new(160.0, 32.0));
5777 let layout = ctx
5778 .layout()
5779 .shape_text_persistent(None, "compose", size, TextStyle::new(Color::WHITE))
5780 .unwrap();
5781 *self.layout.borrow_mut() = Some(layout);
5782 size
5783 }
5784
5785 fn paint(&self, ctx: &mut PaintCtx) {
5786 let layout = self.layout.borrow();
5787 let layout = layout
5788 .as_ref()
5789 .expect("measure pass should shape text first");
5790 let origin = ctx.bounds().origin;
5791 ctx.draw_persistent_text_layout(origin, layout);
5792 ctx.set_ime_composition_rect(layout.caret_rect(3).translate(origin.to_vector()));
5793 }
5794
5795 fn accepts_focus(&self) -> bool {
5796 true
5797 }
5798 }
5799
5800 struct ChildRoot<W> {
5801 child: SingleChild,
5802 _marker: std::marker::PhantomData<W>,
5803 }
5804
5805 impl<W> ChildRoot<W> {
5806 fn new(child: W) -> Self
5807 where
5808 W: Widget + 'static,
5809 {
5810 Self {
5811 child: SingleChild::new(child),
5812 _marker: std::marker::PhantomData,
5813 }
5814 }
5815 }
5816
5817 impl<W> Widget for ChildRoot<W>
5818 where
5819 W: Widget + 'static,
5820 {
5821 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
5822 let size = constraints.clamp(Size::new(320.0, 180.0));
5823 self.child
5824 .measure(ctx, Constraints::tight(Size::new(120.0, 40.0)));
5825 size
5826 }
5827
5828 fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
5829 self.child.arrange(
5830 ctx,
5831 Rect::new(bounds.x() + 32.0, bounds.y() + 24.0, 120.0, 40.0),
5832 );
5833 }
5834
5835 fn semantics(&self, ctx: &mut SemanticsCtx) {
5836 self.child.semantics(ctx);
5837 }
5838
5839 fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
5840 self.child.visit_children(visitor);
5841 }
5842
5843 fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
5844 self.child.visit_children_mut(visitor);
5845 }
5846 }
5847
5848 struct PaintedChildRoot<W> {
5849 child: SingleChild,
5850 _marker: std::marker::PhantomData<W>,
5851 }
5852
5853 impl<W> PaintedChildRoot<W> {
5854 fn new(child: W) -> Self
5855 where
5856 W: Widget + 'static,
5857 {
5858 Self {
5859 child: SingleChild::new(child),
5860 _marker: std::marker::PhantomData,
5861 }
5862 }
5863 }
5864
5865 impl<W> Widget for PaintedChildRoot<W>
5866 where
5867 W: Widget + 'static,
5868 {
5869 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
5870 let size = constraints.clamp(Size::new(320.0, 180.0));
5871 self.child
5872 .measure(ctx, Constraints::tight(Size::new(160.0, 32.0)));
5873 size
5874 }
5875
5876 fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
5877 self.child.arrange(
5878 ctx,
5879 Rect::new(bounds.x() + 32.0, bounds.y() + 24.0, 160.0, 32.0),
5880 );
5881 }
5882
5883 fn paint(&self, ctx: &mut PaintCtx) {
5884 self.child.paint(ctx);
5885 }
5886
5887 fn semantics(&self, ctx: &mut SemanticsCtx) {
5888 self.child.semantics(ctx);
5889 }
5890
5891 fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
5892 self.child.visit_children(visitor);
5893 }
5894
5895 fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
5896 self.child.visit_children_mut(visitor);
5897 }
5898 }
5899
5900 fn build_runtime() -> (
5901 Runtime,
5902 sui_core::WindowId,
5903 Rc<RefCell<Counters>>,
5904 Rc<RefCell<Counters>>,
5905 ) {
5906 let root_counters = Rc::new(RefCell::new(Counters::default()));
5907 let leaf_counters = Rc::new(RefCell::new(Counters::default()));
5908
5909 let runtime = Application::new()
5910 .window(WindowBuilder::new().title("Test").root(TestRoot {
5911 counters: Rc::clone(&root_counters),
5912 child: SingleChild::new(FocusLeaf {
5913 counters: Rc::clone(&leaf_counters),
5914 }),
5915 }))
5916 .build()
5917 .unwrap();
5918
5919 let window_id = runtime.window_ids()[0];
5920 (runtime, window_id, root_counters, leaf_counters)
5921 }
5922
5923 fn build_semantics_action_runtime() -> (
5924 Runtime,
5925 sui_core::WindowId,
5926 Rc<RefCell<SemanticActionState>>,
5927 ) {
5928 let state = Rc::new(RefCell::new(SemanticActionState::default()));
5929 let runtime = Application::new()
5930 .window(
5931 WindowBuilder::new()
5932 .title("Semantic Actions")
5933 .root(PaintedChildRoot::new(SyntheticSemanticActionLeaf {
5934 state: Rc::clone(&state),
5935 })),
5936 )
5937 .build()
5938 .unwrap();
5939 let window_id = runtime.window_ids()[0];
5940 (runtime, window_id, state)
5941 }
5942
5943 #[test]
5944 fn window_builder_uses_default_sui_icon() {
5945 let (runtime, window_id, _, _) = build_runtime();
5946
5947 let icon = runtime.window_icon(window_id).unwrap().unwrap();
5948 assert!(matches!(icon, WindowIcon::Svg { .. }));
5949 assert!(
5950 std::str::from_utf8(icon.as_svg().unwrap())
5951 .unwrap()
5952 .contains("SUI logo")
5953 );
5954 }
5955
5956 #[test]
5957 fn window_builder_can_override_or_disable_icon() {
5958 let override_icon = WindowIcon::from_svg("<svg viewBox=\"0 0 1 1\"></svg>");
5959 let runtime = Application::new()
5960 .window(
5961 WindowBuilder::new()
5962 .title("Custom icon")
5963 .icon(override_icon.clone())
5964 .root(FocusLeaf {
5965 counters: Rc::new(RefCell::new(Counters::default())),
5966 }),
5967 )
5968 .window(
5969 WindowBuilder::new()
5970 .title("No icon")
5971 .without_icon()
5972 .root(FocusLeaf {
5973 counters: Rc::new(RefCell::new(Counters::default())),
5974 }),
5975 )
5976 .build()
5977 .unwrap();
5978
5979 let window_ids = runtime.window_ids();
5980 assert_eq!(
5981 runtime.window_icon(window_ids[0]).unwrap(),
5982 Some(&override_icon)
5983 );
5984 assert_eq!(runtime.window_icon(window_ids[1]).unwrap(), None);
5985 }
5986
5987 #[test]
5988 fn independent_runtimes_allocate_distinct_window_ids() {
5989 let first = Application::new()
5990 .window(WindowBuilder::new().title("First").root(FocusLeaf {
5991 counters: Rc::new(RefCell::new(Counters::default())),
5992 }))
5993 .build()
5994 .unwrap();
5995 let second = Application::new()
5996 .window(WindowBuilder::new().title("Second").root(FocusLeaf {
5997 counters: Rc::new(RefCell::new(Counters::default())),
5998 }))
5999 .build()
6000 .unwrap();
6001
6002 assert_ne!(first.window_ids()[0], second.window_ids()[0]);
6003 }
6004
6005 #[test]
6006 fn rgba_window_icon_validates_buffer_shape() {
6007 assert!(WindowIcon::from_rgba8(1, 1, vec![0, 0, 0, 255]).is_ok());
6008 assert!(WindowIcon::from_rgba8(0, 1, Vec::new()).is_err());
6009 assert!(WindowIcon::from_rgba8(1, 1, vec![0, 0, 0]).is_err());
6010 }
6011
6012 fn build_cached_move_runtime() -> (
6013 Runtime,
6014 sui_core::WindowId,
6015 Rc<RefCell<Counters>>,
6016 Rc<RefCell<Counters>>,
6017 ) {
6018 let root_counters = Rc::new(RefCell::new(Counters::default()));
6019 let leaf_counters = Rc::new(RefCell::new(Counters::default()));
6020 let presentation = Rc::new(RefCell::new(CachedLayerPresentation::default()));
6021
6022 let runtime = Application::new()
6023 .window(
6024 WindowBuilder::new()
6025 .title("Cached move")
6026 .root(CachedMoveRoot {
6027 counters: Rc::clone(&root_counters),
6028 child: SingleChild::new(CachedMoveLeaf {
6029 counters: Rc::clone(&leaf_counters),
6030 presentation: Rc::clone(&presentation),
6031 }),
6032 presentation,
6033 offset_x: 0.0,
6034 paint_background: true,
6035 }),
6036 )
6037 .build()
6038 .unwrap();
6039
6040 let window_id = runtime.window_ids()[0];
6041 (runtime, window_id, root_counters, leaf_counters)
6042 }
6043
6044 fn build_direct_move_runtime() -> (
6045 Runtime,
6046 sui_core::WindowId,
6047 Rc<RefCell<Counters>>,
6048 Rc<RefCell<Counters>>,
6049 ) {
6050 let root_counters = Rc::new(RefCell::new(Counters::default()));
6051 let leaf_counters = Rc::new(RefCell::new(Counters::default()));
6052
6053 let runtime = Application::new()
6054 .window(
6055 WindowBuilder::new()
6056 .title("Direct move")
6057 .root(DirectMoveRoot {
6058 counters: Rc::clone(&root_counters),
6059 child: SingleChild::new(DirectMoveLeaf {
6060 counters: Rc::clone(&leaf_counters),
6061 }),
6062 offset_x: 0.0,
6063 }),
6064 )
6065 .build()
6066 .unwrap();
6067
6068 let window_id = runtime.window_ids()[0];
6069 (runtime, window_id, root_counters, leaf_counters)
6070 }
6071
6072 fn build_overpaint_runtime() -> (Runtime, sui_core::WindowId) {
6073 let runtime = Application::new()
6074 .window(WindowBuilder::new().title("Overpaint").root(TestRoot {
6075 counters: Rc::new(RefCell::new(Counters::default())),
6076 child: SingleChild::new(OverpaintLeaf {
6077 size: Size::new(120.0, 40.0),
6078 color: Color::rgba(0.92, 0.42, 0.18, 1.0),
6079 bleed: Vector::new(6.0, 4.0),
6080 }),
6081 }))
6082 .build()
6083 .unwrap();
6084
6085 let window_id = runtime.window_ids()[0];
6086 (runtime, window_id)
6087 }
6088
6089 fn build_focus_traversal_runtime() -> (
6090 Runtime,
6091 sui_core::WindowId,
6092 Rc<RefCell<Counters>>,
6093 Rc<RefCell<Counters>>,
6094 ) {
6095 let first = Rc::new(RefCell::new(Counters::default()));
6096 let second = Rc::new(RefCell::new(Counters::default()));
6097
6098 let runtime =
6099 Application::new()
6100 .window(WindowBuilder::new().title("Focus Traversal").root(
6101 FocusTraversalRoot::new(Rc::clone(&first), Rc::clone(&second)),
6102 ))
6103 .build()
6104 .unwrap();
6105
6106 let window_id = runtime.window_ids()[0];
6107 (runtime, window_id, first, second)
6108 }
6109
6110 fn graph_child(graph: &WidgetGraphSnapshot) -> &WidgetNodeSnapshot {
6111 &graph.nodes[1]
6112 }
6113
6114 fn scene_has_layer_for(scene: &sui_scene::Scene, widget_id: sui_core::WidgetId) -> bool {
6115 scene.commands().iter().any(|command| match command {
6116 SceneCommand::Layer(layer) => layer.widget_id() == widget_id,
6117 _ => false,
6118 })
6119 }
6120
6121 fn build_pointer_capture_runtime() -> (
6122 Runtime,
6123 sui_core::WindowId,
6124 Rc<RefCell<PointerCaptureState>>,
6125 ) {
6126 let state = Rc::new(RefCell::new(PointerCaptureState::default()));
6127
6128 let runtime = Application::new()
6129 .window(
6130 WindowBuilder::new()
6131 .title("Pointer Capture")
6132 .root(ChildRoot::new(PointerCaptureLeaf {
6133 state: Rc::clone(&state),
6134 recapture_on_move: false,
6135 })),
6136 )
6137 .build()
6138 .unwrap();
6139
6140 let window_id = runtime.window_ids()[0];
6141 (runtime, window_id, state)
6142 }
6143
6144 fn build_hover_transition_runtime() -> (
6145 Runtime,
6146 sui_core::WindowId,
6147 Rc<RefCell<HoverTransitionState>>,
6148 Rc<RefCell<HoverTransitionState>>,
6149 ) {
6150 let first = Rc::new(RefCell::new(HoverTransitionState::default()));
6151 let second = Rc::new(RefCell::new(HoverTransitionState::default()));
6152
6153 let runtime =
6154 Application::new()
6155 .window(WindowBuilder::new().title("Hover transitions").root(
6156 HoverTransitionRoot::new(Rc::clone(&first), Rc::clone(&second)),
6157 ))
6158 .build()
6159 .unwrap();
6160
6161 let window_id = runtime.window_ids()[0];
6162 (runtime, window_id, first, second)
6163 }
6164
6165 fn build_wake_runtime() -> (Runtime, sui_core::WindowId, Rc<RefCell<WakeState>>) {
6166 let state = Rc::new(RefCell::new(WakeState::default()));
6167
6168 let runtime = Application::new()
6169 .window(
6170 WindowBuilder::new()
6171 .title("Wake")
6172 .root(ChildRoot::new(WakeLeaf {
6173 state: Rc::clone(&state),
6174 })),
6175 )
6176 .build()
6177 .unwrap();
6178
6179 let window_id = runtime.window_ids()[0];
6180 (runtime, window_id, state)
6181 }
6182
6183 fn build_animation_wake_runtime(
6184 request_twice: bool,
6185 ) -> (Runtime, sui_core::WindowId, Rc<RefCell<AnimationWakeState>>) {
6186 let state = Rc::new(RefCell::new(AnimationWakeState {
6187 request_twice,
6188 ..AnimationWakeState::default()
6189 }));
6190
6191 let runtime = Application::new()
6192 .window(
6193 WindowBuilder::new()
6194 .title("Animation Wake")
6195 .root(ChildRoot::new(AnimationWakeLeaf {
6196 state: Rc::clone(&state),
6197 })),
6198 )
6199 .build()
6200 .unwrap();
6201
6202 let window_id = runtime.window_ids()[0];
6203 (runtime, window_id, state)
6204 }
6205
6206 fn build_removable_animation_runtime() -> (Runtime, sui_core::WindowId) {
6207 let state = Rc::new(RefCell::new(AnimationWakeState::default()));
6208 let runtime = Application::new()
6209 .window(WindowBuilder::new().title("Removable Animation").root(
6210 RemovableAnimationRoot {
6211 child: Some(SingleChild::new(AnimationWakeLeaf { state })),
6212 },
6213 ))
6214 .build()
6215 .unwrap();
6216
6217 let window_id = runtime.window_ids()[0];
6218 (runtime, window_id)
6219 }
6220
6221 fn build_text_runtime() -> (Runtime, sui_core::WindowId) {
6222 let runtime = Application::new()
6223 .window(
6224 WindowBuilder::new()
6225 .title("Text")
6226 .root(PaintedChildRoot::new(TextImeLeaf {
6227 layout: RefCell::new(None),
6228 })),
6229 )
6230 .build()
6231 .unwrap();
6232
6233 let window_id = runtime.window_ids()[0];
6234 (runtime, window_id)
6235 }
6236
6237 #[test]
6238 fn runtime_exposes_retained_widget_graph() {
6239 let (mut runtime, window_id, _, _) = build_runtime();
6240
6241 let output = runtime.render(window_id).unwrap();
6242 let graph = runtime.widget_graph(window_id).unwrap();
6243
6244 assert_eq!(graph.nodes.len(), 2);
6245 assert_eq!(graph.nodes[0].id, graph.root);
6246 assert_eq!(graph.nodes[0].stack_host, graph.root);
6247 assert!(graph.nodes[0].is_stack_host);
6248 assert_eq!(graph_child(&graph).parent, Some(graph.root));
6249 assert_eq!(graph_child(&graph).stack_host, graph.root);
6250 assert!(!graph_child(&graph).is_stack_surface);
6251 assert_eq!(graph.stack_hosts.len(), 1);
6252 assert_eq!(graph.stack_hosts[0].host, graph.root);
6253 assert!(graph.stack_hosts[0].surfaces.is_empty());
6254 assert!(graph_child(&graph).accepts_focus);
6255 assert_eq!(
6256 graph_child(&graph).geometry.layout_bounds,
6257 graph_child(&graph).bounds
6258 );
6259 assert_eq!(
6260 graph_child(&graph).geometry.input_bounds,
6261 graph_child(&graph).geometry.layout_bounds
6262 );
6263 assert_eq!(
6264 graph_child(&graph).geometry.paint_bounds,
6265 graph_child(&graph).geometry.layout_bounds
6266 );
6267 assert_eq!(output.frame.viewport, Size::new(320.0, 180.0));
6268 assert_eq!(output.frame.surface_size, Size::new(320.0, 180.0));
6269 assert_eq!(output.frame.scale_factor, 1.0);
6270 }
6271
6272 #[test]
6273 fn synthetic_semantic_activate_falls_back_to_pointer_routing() {
6274 let (mut runtime, window_id, state) = build_semantics_action_runtime();
6275 let _ = runtime.render(window_id).unwrap();
6276
6277 assert!(
6278 runtime
6279 .handle_semantics_action(
6280 window_id,
6281 SYNTHETIC_ACTION_ID,
6282 SemanticsActionRequest::Activate,
6283 )
6284 .unwrap()
6285 );
6286
6287 let state = state.borrow();
6288 assert_eq!(
6289 state.actions,
6290 vec![(SYNTHETIC_ACTION_ID, SemanticsActionRequest::Activate)]
6291 );
6292 assert_eq!(state.pointer_activations, 1);
6293 }
6294
6295 #[test]
6296 fn semantic_expand_and_collapse_use_idempotent_pointer_fallbacks() {
6297 let (mut runtime, window_id, state) = build_semantics_action_runtime();
6298 let _ = runtime.render(window_id).unwrap();
6299
6300 assert!(
6301 runtime
6302 .handle_semantics_action(
6303 window_id,
6304 SYNTHETIC_ACTION_ID,
6305 SemanticsActionRequest::Expand,
6306 )
6307 .unwrap()
6308 );
6309 assert!(state.borrow().expanded);
6310 assert_eq!(state.borrow().pointer_activations, 1);
6311
6312 let _ = runtime.render(window_id).unwrap();
6313 assert!(
6314 runtime
6315 .handle_semantics_action(
6316 window_id,
6317 SYNTHETIC_ACTION_ID,
6318 SemanticsActionRequest::Expand,
6319 )
6320 .unwrap()
6321 );
6322 assert_eq!(state.borrow().pointer_activations, 1);
6323
6324 assert!(
6325 runtime
6326 .handle_semantics_action(
6327 window_id,
6328 SYNTHETIC_ACTION_ID,
6329 SemanticsActionRequest::Collapse,
6330 )
6331 .unwrap()
6332 );
6333 assert!(!state.borrow().expanded);
6334 assert_eq!(state.borrow().pointer_activations, 2);
6335 }
6336
6337 #[test]
6338 fn synthetic_semantic_focus_targets_graph_owner_and_retains_semantic_identity() {
6339 let (mut runtime, window_id, state) = build_semantics_action_runtime();
6340 let first = runtime.render(window_id).unwrap();
6341 let owner_id = first
6342 .semantics
6343 .iter()
6344 .find(|node| node.name.as_deref() == Some("semantic action owner"))
6345 .unwrap()
6346 .id;
6347
6348 assert!(
6349 runtime
6350 .handle_semantics_action(
6351 window_id,
6352 SYNTHETIC_ACTION_ID,
6353 SemanticsActionRequest::Focus,
6354 )
6355 .unwrap()
6356 );
6357 assert_eq!(runtime.focused_widget(window_id).unwrap(), Some(owner_id));
6358
6359 let focused = runtime.render(window_id).unwrap();
6360 assert!(
6361 focused
6362 .semantics
6363 .iter()
6364 .find(|node| node.id == SYNTHETIC_ACTION_ID)
6365 .unwrap()
6366 .state
6367 .focused
6368 );
6369 assert_eq!(
6370 state.borrow().actions,
6371 vec![(SYNTHETIC_ACTION_ID, SemanticsActionRequest::Focus)]
6372 );
6373
6374 let mut pointer = PointerEvent::new(PointerEventKind::Down, Point::new(48.0, 32.0));
6375 pointer.button = Some(PointerButton::Primary);
6376 pointer.buttons.insert(PointerButton::Primary);
6377 runtime
6378 .handle_event(window_id, Event::Pointer(pointer))
6379 .unwrap();
6380 let pointer_focused = runtime.render(window_id).unwrap();
6381 assert!(
6382 pointer_focused
6383 .semantics
6384 .iter()
6385 .find(|node| node.id == owner_id)
6386 .unwrap()
6387 .state
6388 .focused
6389 );
6390 assert!(
6391 !pointer_focused
6392 .semantics
6393 .iter()
6394 .find(|node| node.id == SYNTHETIC_ACTION_ID)
6395 .unwrap()
6396 .state
6397 .focused
6398 );
6399 }
6400
6401 #[test]
6402 fn semantic_blur_only_clears_the_current_semantic_focus_target() {
6403 let (mut runtime, window_id, _state) = build_semantics_action_runtime();
6404 let _ = runtime.render(window_id).unwrap();
6405
6406 assert!(
6407 !runtime
6408 .handle_semantics_action(
6409 window_id,
6410 SYNTHETIC_ACTION_ID,
6411 SemanticsActionRequest::Blur,
6412 )
6413 .unwrap()
6414 );
6415 assert!(
6416 runtime
6417 .handle_semantics_action(
6418 window_id,
6419 SYNTHETIC_ACTION_ID,
6420 SemanticsActionRequest::Focus,
6421 )
6422 .unwrap()
6423 );
6424 assert!(
6425 runtime
6426 .handle_semantics_action(
6427 window_id,
6428 SYNTHETIC_ACTION_ID,
6429 SemanticsActionRequest::Blur,
6430 )
6431 .unwrap()
6432 );
6433 assert_eq!(runtime.focused_widget(window_id).unwrap(), None);
6434 }
6435
6436 #[test]
6437 fn semantic_focus_rejects_an_unhandled_target_without_a_focusable_owner() {
6438 let mut runtime = Application::new()
6439 .window(
6440 WindowBuilder::new()
6441 .title("Unfocusable Semantic Action")
6442 .root(ChildRoot::new(UnfocusableSemanticLeaf)),
6443 )
6444 .build()
6445 .unwrap();
6446 let window_id = runtime.window_ids()[0];
6447 let output = runtime.render(window_id).unwrap();
6448 let target = output
6449 .semantics
6450 .iter()
6451 .find(|node| node.name.as_deref() == Some("unfocusable semantic node"))
6452 .unwrap()
6453 .id;
6454
6455 assert!(
6456 !runtime
6457 .handle_semantics_action(window_id, target, SemanticsActionRequest::Focus,)
6458 .unwrap()
6459 );
6460 assert_eq!(runtime.focused_widget(window_id).unwrap(), None);
6461 assert!(
6462 !runtime
6463 .render(window_id)
6464 .unwrap()
6465 .semantics
6466 .iter()
6467 .find(|node| node.id == target)
6468 .unwrap()
6469 .state
6470 .focused
6471 );
6472 }
6473
6474 #[test]
6475 fn stale_disabled_and_unadvertised_semantic_actions_are_rejected() {
6476 let (mut stale_runtime, stale_window_id, stale_state) = build_semantics_action_runtime();
6477 let _ = stale_runtime.render(stale_window_id).unwrap();
6478
6479 assert!(
6480 !stale_runtime
6481 .handle_semantics_action(
6482 stale_window_id,
6483 WidgetId::new(u64::MAX - 2),
6484 SemanticsActionRequest::Activate,
6485 )
6486 .unwrap()
6487 );
6488 assert!(
6489 !stale_runtime
6490 .handle_semantics_action(
6491 stale_window_id,
6492 SYNTHETIC_ACTION_ID,
6493 SemanticsActionRequest::Increment,
6494 )
6495 .unwrap()
6496 );
6497 assert!(stale_state.borrow().actions.is_empty());
6498
6499 let (mut disabled_runtime, disabled_window_id, disabled_state) =
6500 build_semantics_action_runtime();
6501 disabled_state.borrow_mut().disabled = true;
6502 let _ = disabled_runtime.render(disabled_window_id).unwrap();
6503 assert!(
6504 !disabled_runtime
6505 .handle_semantics_action(
6506 disabled_window_id,
6507 SYNTHETIC_ACTION_ID,
6508 SemanticsActionRequest::Activate,
6509 )
6510 .unwrap()
6511 );
6512 assert!(disabled_state.borrow().actions.is_empty());
6513 }
6514
6515 #[test]
6516 fn semantic_action_payload_is_typed_and_unsupported_actions_are_rejected() {
6517 let (mut runtime, window_id, state) = build_semantics_action_runtime();
6518 let _ = runtime.render(window_id).unwrap();
6519
6520 let set_value_handled = runtime
6521 .handle_semantics_action(
6522 window_id,
6523 SYNTHETIC_ACTION_ID,
6524 SemanticsActionRequest::SetValue(SemanticsValue::Text("forty two".into())),
6525 )
6526 .unwrap();
6527 assert!(
6528 set_value_handled,
6529 "state after SetValue: {:?}; semantics: {:?}; graph: {:?}",
6530 state.borrow(),
6531 runtime.semantics(window_id).unwrap(),
6532 runtime.widget_graph(window_id).unwrap()
6533 );
6534 assert!(
6535 runtime
6536 .handle_semantics_action(
6537 window_id,
6538 SYNTHETIC_ACTION_ID,
6539 SemanticsActionRequest::InsertText("hello".into()),
6540 )
6541 .unwrap()
6542 );
6543 assert!(
6544 !runtime
6545 .handle_semantics_action(
6546 window_id,
6547 SYNTHETIC_ACTION_ID,
6548 SemanticsActionRequest::Increment,
6549 )
6550 .unwrap()
6551 );
6552
6553 assert_eq!(
6554 state.borrow().actions,
6555 vec![
6556 (
6557 SYNTHETIC_ACTION_ID,
6558 SemanticsActionRequest::SetValue(SemanticsValue::Text("forty two".into())),
6559 ),
6560 (
6561 SYNTHETIC_ACTION_ID,
6562 SemanticsActionRequest::InsertText("hello".into()),
6563 ),
6564 ]
6565 );
6566 }
6567
6568 #[test]
6569 fn render_output_is_send_sync() {
6570 fn assert_send_sync<T: Send + Sync>() {}
6571
6572 assert_send_sync::<RenderOutput>();
6573 }
6574
6575 #[test]
6576 fn widget_graph_visits_logical_children_even_when_paint_is_virtualized() {
6577 let paint_state = Rc::new(RefCell::new(VirtualizedPaintState::default()));
6578 let mut runtime = Application::new()
6579 .window(
6580 WindowBuilder::new()
6581 .title("Virtualized")
6582 .root(VirtualizedLogicalRoot::new(4, 2, Rc::clone(&paint_state))),
6583 )
6584 .build()
6585 .unwrap();
6586 let window_id = runtime.window_ids()[0];
6587
6588 let _ = runtime.render(window_id).unwrap();
6589 let graph = runtime.widget_graph(window_id).unwrap();
6590 let root = graph
6591 .nodes
6592 .iter()
6593 .find(|node| node.id == graph.root)
6594 .unwrap();
6595
6596 assert_eq!(root.children.len(), 4);
6597 assert_eq!(graph.nodes.len(), 5);
6598 assert_eq!(paint_state.borrow().painted, vec![0, 1]);
6599 }
6600
6601 #[test]
6602 fn worker_owned_snapshot_state_reenters_runtime_without_widget_send_sync() {
6603 let local = Rc::new(RefCell::new(ThreadedSnapshotState::default()));
6604 let inbox = Arc::new(Mutex::new(VecDeque::new()));
6605 let mut runtime =
6606 Application::new()
6607 .window(WindowBuilder::new().title("Threaded Snapshot").root(
6608 ThreadedSnapshotRoot {
6609 local: Rc::clone(&local),
6610 inbox: Arc::clone(&inbox),
6611 },
6612 ))
6613 .build()
6614 .unwrap();
6615 let window_id = runtime.window_ids()[0];
6616
6617 let _ = runtime.render(window_id).unwrap();
6618 runtime
6619 .handle_event(
6620 window_id,
6621 Event::Custom(CustomEvent::new("arm-threaded-snapshot")),
6622 )
6623 .unwrap();
6624 let async_token = local.borrow().async_token.unwrap();
6625
6626 let worker_inbox = Arc::clone(&inbox);
6627 std::thread::spawn(move || {
6628 worker_inbox
6629 .lock()
6630 .unwrap()
6631 .push_back("worker-ready".to_string());
6632 })
6633 .join()
6634 .unwrap();
6635
6636 assert!(runtime.wake_async(window_id, async_token).unwrap());
6637 for (ready_window, event) in runtime.drain_ready_events() {
6638 runtime.handle_event(ready_window, event).unwrap();
6639 }
6640
6641 assert_eq!(local.borrow().latest.as_deref(), Some("worker-ready"));
6642 assert!(runtime.needs_render(window_id).unwrap());
6643
6644 let _ = runtime.render(window_id).unwrap();
6645 assert_eq!(local.borrow().paints, 2);
6646 }
6647
6648 struct EventPoster {
6649 log: Rc<RefCell<Vec<String>>>,
6650 }
6651
6652 impl Widget for EventPoster {
6653 fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
6654 if let Event::Custom(custom) = event {
6655 self.log.borrow_mut().push(custom.kind.clone());
6656 if custom.kind == "posted-trigger" {
6657 ctx.post_event(
6658 ctx.widget_id(),
6659 Event::Custom(CustomEvent::new("posted-response")),
6660 );
6661 }
6662 }
6663 }
6664 }
6665
6666 #[test]
6667 fn posted_events_are_delivered_after_the_current_dispatch() {
6668 let log = Rc::new(RefCell::new(Vec::new()));
6669 let mut runtime = Application::new()
6670 .window(WindowBuilder::new().title("Posted").root(EventPoster {
6671 log: Rc::clone(&log),
6672 }))
6673 .build()
6674 .unwrap();
6675 let window_id = runtime.window_ids()[0];
6676 let _ = runtime.render(window_id).unwrap();
6677
6678 runtime
6679 .handle_event(window_id, Event::Custom(CustomEvent::new("posted-trigger")))
6680 .unwrap();
6681
6682 assert_eq!(
6683 log.borrow().as_slice(),
6684 ["posted-trigger".to_string(), "posted-response".to_string()]
6685 );
6686 }
6687
6688 #[test]
6689 fn runtime_clipboard_is_shared_with_window_event_contexts() {
6690 let mut runtime = Application::new()
6691 .window(WindowBuilder::new().title("Clipboard").root(FocusLeaf {
6692 counters: Rc::new(RefCell::new(Counters::default())),
6693 }))
6694 .build()
6695 .unwrap();
6696 let window_id = runtime.window_ids()[0];
6697 let _ = runtime.render(window_id).unwrap();
6698
6699 runtime.clipboard().set_text("shared");
6700 assert_eq!(runtime.clipboard().text().as_deref(), Some("shared"));
6701
6702 runtime.set_clipboard_backend(sui_core::LocalClipboardBackend::new());
6703 assert_eq!(runtime.clipboard().text(), None);
6704 }
6705
6706 #[test]
6707 fn explicit_paint_boundary_direct_child_remains_a_stack_surface() {
6708 let (mut runtime, window_id, _, _) = build_cached_move_runtime();
6709
6710 let _ = runtime.render(window_id).unwrap();
6711 let graph = runtime.widget_graph(window_id).unwrap();
6712 let child = graph_child(&graph);
6713
6714 assert!(child.is_stack_surface);
6715 assert_eq!(graph.stack_hosts.len(), 1);
6716 assert_eq!(graph.stack_hosts[0].host, graph.root);
6717 assert_eq!(graph.stack_hosts[0].surfaces, vec![child.id]);
6718 }
6719
6720 #[test]
6721 fn non_hit_test_stack_surface_allows_underlying_pointer_target() {
6722 let pointer_downs = Rc::new(RefCell::new(0));
6723 let runtime = Application::new()
6724 .window(
6725 WindowBuilder::new()
6726 .title("Overlay pass-through")
6727 .root(OverlayPassThroughRoot::new(Rc::clone(&pointer_downs))),
6728 )
6729 .build()
6730 .unwrap();
6731 let window_id = runtime.window_ids()[0];
6732 let mut runtime = runtime;
6733
6734 let output = runtime.render(window_id).unwrap();
6735 let mut overlay_hit_test = None;
6736 output.frame.scene.visit_layers(&mut |layer| {
6737 if layer.descriptor.composition_mode == LayerCompositionMode::Overlay {
6738 overlay_hit_test = Some(layer.descriptor.hit_test);
6739 }
6740 });
6741 assert_eq!(overlay_hit_test, Some(false));
6742
6743 let mut down = PointerEvent::new(PointerEventKind::Down, Point::new(48.0, 36.0));
6744 down.pointer_id = 1;
6745 down.button = Some(PointerButton::Primary);
6746 down.buttons = PointerButtons::new(1);
6747 runtime
6748 .handle_event(window_id, Event::Pointer(down))
6749 .unwrap();
6750
6751 assert_eq!(*pointer_downs.borrow(), 1);
6752 }
6753
6754 #[test]
6755 fn hit_test_stack_surface_targets_deepest_child() {
6756 let pointer_downs = Rc::new(RefCell::new(0));
6757 let runtime = Application::new()
6758 .window(
6759 WindowBuilder::new()
6760 .title("Overlay child hit")
6761 .root(HitTestOverlayRoot::new(Rc::clone(&pointer_downs))),
6762 )
6763 .build()
6764 .unwrap();
6765 let window_id = runtime.window_ids()[0];
6766 let mut runtime = runtime;
6767
6768 let output = runtime.render(window_id).unwrap();
6769 let mut effect_hit_test = None;
6770 output.frame.scene.visit_layers(&mut |layer| {
6771 if layer.descriptor.composition_mode == LayerCompositionMode::Effect {
6772 effect_hit_test = Some(layer.descriptor.hit_test);
6773 }
6774 });
6775 assert_eq!(effect_hit_test, Some(true));
6776
6777 let mut down = PointerEvent::new(PointerEventKind::Down, Point::new(80.0, 60.0));
6778 down.pointer_id = 1;
6779 down.button = Some(PointerButton::Primary);
6780 down.buttons = PointerButtons::new(1);
6781 runtime
6782 .handle_event(window_id, Event::Pointer(down))
6783 .unwrap();
6784
6785 assert_eq!(*pointer_downs.borrow(), 1);
6786 }
6787
6788 #[test]
6789 fn runtime_reports_surface_size_and_scale_factor_for_hidpi_windows() {
6790 let (mut runtime, window_id, _, _) = build_runtime();
6791
6792 runtime
6793 .handle_event(
6794 window_id,
6795 Event::Window(WindowEvent::ScaleFactorChanged {
6796 scale_factor: 2.0,
6797 raw_dpi: Some(192.0),
6798 suggested_size: Some(Size::new(320.0, 180.0)),
6799 }),
6800 )
6801 .unwrap();
6802
6803 let output = runtime.render(window_id).unwrap();
6804
6805 assert_eq!(output.frame.viewport, Size::new(320.0, 180.0));
6806 assert_eq!(output.frame.surface_size, Size::new(640.0, 360.0));
6807 assert_eq!(output.frame.scale_factor, 2.0);
6808 }
6809
6810 #[test]
6811 fn runtime_delivers_external_file_events_without_changing_window_geometry() {
6812 let events = Rc::new(RefCell::new(Vec::new()));
6813 let mut runtime =
6814 Application::new()
6815 .window(WindowBuilder::new().title("External file events").root(
6816 WindowEventRecorder {
6817 events: Rc::clone(&events),
6818 },
6819 ))
6820 .build()
6821 .unwrap();
6822 let window_id = runtime.window_ids()[0];
6823 let before = runtime.render(window_id).unwrap().frame;
6824 let path = PathBuf::from(r"C:\workspace\agent.json");
6825
6826 for event in [
6827 WindowEvent::ExternalFileHovered(path.clone()),
6828 WindowEvent::ExternalFileDropped(path.clone()),
6829 WindowEvent::ExternalFileHoverCancelled,
6830 ] {
6831 runtime
6832 .handle_event(window_id, Event::Window(event))
6833 .unwrap();
6834 }
6835
6836 assert_eq!(
6837 events.borrow().as_slice(),
6838 &[
6839 WindowEvent::ExternalFileHovered(path.clone()),
6840 WindowEvent::ExternalFileDropped(path),
6841 WindowEvent::ExternalFileHoverCancelled,
6842 ]
6843 );
6844 let after = runtime.render(window_id).unwrap().frame;
6845 assert_eq!(after.viewport, before.viewport);
6846 assert_eq!(after.surface_size, before.surface_size);
6847 assert_eq!(after.scale_factor, before.scale_factor);
6848 }
6849
6850 #[test]
6851 fn runtime_attaches_registered_fonts_to_render_output() {
6852 let (mut runtime, window_id, _, _) = build_runtime();
6853 let handle = FontHandle::new(33);
6854
6855 runtime
6856 .register_font(handle, RegisteredFont::from_bytes(vec![0, 1, 2, 3]))
6857 .unwrap();
6858
6859 let output = runtime.render(window_id).unwrap();
6860
6861 assert!(output.frame.font_registry.contains(handle));
6862 }
6863
6864 #[test]
6865 fn runtime_attaches_registered_images_to_render_output() {
6866 let (mut runtime, window_id, _, _) = build_runtime();
6867 let handle = ImageHandle::new(7);
6868
6869 runtime
6870 .register_image(
6871 handle,
6872 RegisteredImage::from_rgba8(1, 1, vec![255, 0, 0, 255]).unwrap(),
6873 )
6874 .unwrap();
6875
6876 let output = runtime.render(window_id).unwrap();
6877
6878 assert!(output.frame.image_registry.contains(handle));
6879 }
6880
6881 #[test]
6882 fn paint_registered_external_images_are_included_in_render_output() {
6883 struct ExternalImageLeaf {
6884 handle: ImageHandle,
6885 }
6886
6887 impl Widget for ExternalImageLeaf {
6888 fn paint(&self, ctx: &mut PaintCtx) {
6889 ctx.register_external_image(
6890 self.handle,
6891 RegisteredExternalImage::new(640, 360).unwrap(),
6892 );
6893 ctx.draw_image(ctx.bounds(), self.handle);
6894 }
6895 }
6896
6897 let handle = ImageHandle::new(71);
6898 let mut runtime = Application::new()
6899 .window(
6900 WindowBuilder::new()
6901 .title("External image")
6902 .root(ExternalImageLeaf { handle }),
6903 )
6904 .build()
6905 .unwrap();
6906 let window_id = runtime.window_ids()[0];
6907
6908 let output = runtime.render(window_id).unwrap();
6909 assert_eq!(
6910 output.frame.image_registry.dimensions(handle),
6911 Some((640, 360))
6912 );
6913 assert!(output.frame.image_registry.get(handle).is_none());
6914 assert!(output.frame.image_registry.get_external(handle).is_some());
6915 }
6916
6917 #[test]
6918 fn runtime_attaches_registered_svg_images_to_render_output() {
6919 let (mut runtime, window_id, _, _) = build_runtime();
6920 let handle = ImageHandle::new(41);
6921 let svg = br##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 4 4"><rect width="4" height="4" fill="#27B7C8"/></svg>"##;
6922
6923 runtime
6924 .register_svg_image_at_size_with_handle(handle, 16, 16, svg)
6925 .unwrap();
6926
6927 let output = runtime.render(window_id).unwrap();
6928 let image = output.frame.image_registry.get(handle).unwrap();
6929
6930 assert_eq!(image.width(), 16);
6931 assert_eq!(image.height(), 16);
6932 assert!(image.bytes().chunks_exact(4).any(|pixel| pixel[3] > 0));
6933 }
6934
6935 #[test]
6936 fn semantics_only_invalidation_skips_repaint() {
6937 let (mut runtime, window_id, root_counters, leaf_counters) = build_runtime();
6938
6939 let _ = runtime.render(window_id).unwrap();
6940 let root_paint_before = root_counters.borrow().paint;
6941 let leaf_paint_before = leaf_counters.borrow().paint;
6942
6943 runtime
6944 .handle_event(window_id, Event::Custom(CustomEvent::new("semantics-only")))
6945 .unwrap();
6946
6947 assert_eq!(
6948 runtime.schedule(window_id).unwrap(),
6949 FrameSchedule {
6950 semantics: true,
6951 ..FrameSchedule::default()
6952 }
6953 );
6954
6955 let _ = runtime.render(window_id).unwrap();
6956
6957 assert_eq!(root_counters.borrow().paint, root_paint_before);
6958 assert_eq!(leaf_counters.borrow().paint, leaf_paint_before);
6959 assert!(root_counters.borrow().semantics >= 2);
6960 }
6961
6962 #[test]
6963 fn ordinary_widgets_flatten_scene_output_into_root() {
6964 let (mut runtime, window_id, _, _) = build_runtime();
6965
6966 let output = runtime.render(window_id).unwrap();
6967 let leaf_id = graph_child(&runtime.widget_graph(window_id).unwrap()).id;
6968
6969 assert!(!scene_has_layer_for(&output.frame.scene, leaf_id));
6970 }
6971
6972 #[test]
6973 fn explicit_paint_boundary_widgets_emit_layers() {
6974 let (mut runtime, window_id, _, _) = build_cached_move_runtime();
6975
6976 let output = runtime.render(window_id).unwrap();
6977 let layer_id = graph_child(&runtime.widget_graph(window_id).unwrap()).id;
6978
6979 assert!(scene_has_layer_for(&output.frame.scene, layer_id));
6980 }
6981
6982 #[test]
6983 fn flat_widgets_preserve_paint_bounds_larger_than_layout_bounds() {
6984 let (mut runtime, window_id) = build_overpaint_runtime();
6985
6986 let _ = runtime.render(window_id).unwrap();
6987 let graph = runtime.widget_graph(window_id).unwrap();
6988 let child = graph_child(&graph);
6989
6990 assert_eq!(child.bounds, Rect::new(32.0, 24.0, 120.0, 40.0));
6991 assert_eq!(child.geometry.paint_bounds, child.bounds.inflate(6.0, 4.0));
6992 }
6993
6994 #[test]
6995 fn paint_invalidation_repaints_nearest_boundary_root_for_flat_child() {
6996 let (mut runtime, window_id, root_counters, leaf_counters) = build_runtime();
6997
6998 let _ = runtime.render(window_id).unwrap();
6999 let leaf_id = graph_child(&runtime.widget_graph(window_id).unwrap()).id;
7000 let root_paint_before = root_counters.borrow().paint;
7001 let leaf_paint_before = leaf_counters.borrow().paint;
7002
7003 let mut pointer = PointerEvent::new(PointerEventKind::Down, Point::new(48.0, 40.0));
7004 pointer.button = Some(PointerButton::Primary);
7005 pointer.buttons = PointerButtons::new(1);
7006 runtime
7007 .handle_event(window_id, Event::Pointer(pointer))
7008 .unwrap();
7009
7010 let output = runtime.render(window_id).unwrap();
7011
7012 assert_eq!(root_counters.borrow().paint, root_paint_before + 1);
7013 assert_eq!(leaf_counters.borrow().paint, leaf_paint_before + 1);
7014 assert!(!scene_has_layer_for(&output.frame.scene, leaf_id));
7015 assert!(output.frame.layer_updates.is_empty());
7016 }
7017
7018 #[test]
7019 fn cached_layer_translation_updates_scene_without_repaint() {
7020 let (mut runtime, window_id, root_counters, leaf_counters) = build_cached_move_runtime();
7021
7022 let first = runtime.render(window_id).unwrap();
7023 let first_graph = runtime.widget_graph(window_id).unwrap();
7024 let initial_graph_bounds = graph_child(&first_graph).geometry.paint_bounds;
7025 let layer_id = graph_child(&first_graph).id;
7026 let root_paint_before = root_counters.borrow().paint;
7027 let leaf_paint_before = leaf_counters.borrow().paint;
7028 let initial_bounds = first
7029 .frame
7030 .scene
7031 .commands()
7032 .iter()
7033 .find_map(|command| match command {
7034 SceneCommand::Layer(layer) if layer.widget_id() == layer_id => Some(layer.bounds()),
7035 _ => None,
7036 })
7037 .expect("cached layer present before translation");
7038
7039 runtime
7040 .handle_event(window_id, Event::Custom(CustomEvent::new("shift-cached")))
7041 .unwrap();
7042
7043 let second = runtime.render(window_id).unwrap();
7044
7045 assert_eq!(root_counters.borrow().paint, root_paint_before);
7046 assert_eq!(leaf_counters.borrow().paint, leaf_paint_before);
7047 assert_eq!(second.frame.layer_updates.len(), 1);
7048 assert_eq!(second.frame.layer_updates[0].owner, layer_id);
7049 assert_eq!(
7050 second.frame.layer_updates[0].kind,
7051 SceneLayerUpdateKind::Transform
7052 );
7053
7054 let translated_bounds = second
7055 .frame
7056 .scene
7057 .commands()
7058 .iter()
7059 .find_map(|command| match command {
7060 SceneCommand::Layer(layer) if layer.widget_id() == layer_id => Some(layer.bounds()),
7061 _ => None,
7062 })
7063 .expect("cached layer present after translation");
7064
7065 assert_eq!(translated_bounds.x(), initial_bounds.x() + 48.0);
7066 assert_eq!(translated_bounds.y(), initial_bounds.y());
7067 let translated_graph_bounds = graph_child(&runtime.widget_graph(window_id).unwrap())
7068 .geometry
7069 .paint_bounds;
7070 assert_eq!(
7071 translated_graph_bounds,
7072 initial_graph_bounds.translate(Vector::new(48.0, 0.0))
7073 );
7074 }
7075
7076 #[test]
7077 fn composition_only_translation_keeps_ancestor_paint_bounds_conservative() {
7078 let root_counters = Rc::new(RefCell::new(Counters::default()));
7079 let leaf_counters = Rc::new(RefCell::new(Counters::default()));
7080 let presentation = Rc::new(RefCell::new(CachedLayerPresentation::default()));
7081 let mut runtime = Application::new()
7082 .window(
7083 WindowBuilder::new()
7084 .title("Bare cached move")
7085 .root(CachedMoveRoot {
7086 counters: Rc::clone(&root_counters),
7087 child: SingleChild::new(CachedMoveLeaf {
7088 counters: Rc::clone(&leaf_counters),
7089 presentation: Rc::clone(&presentation),
7090 }),
7091 presentation,
7092 offset_x: 0.0,
7093 paint_background: false,
7094 }),
7095 )
7096 .build()
7097 .unwrap();
7098 let window_id = runtime.window_ids()[0];
7099 let _ = runtime.render(window_id).unwrap();
7100 let initial_graph = runtime.widget_graph(window_id).unwrap();
7101 let initial_root_paint = initial_graph.nodes[0].geometry.paint_bounds;
7102 let initial_child_paint = graph_child(&initial_graph).geometry.paint_bounds;
7103 let root_paint_before = root_counters.borrow().paint;
7104 let leaf_paint_before = leaf_counters.borrow().paint;
7105
7106 runtime
7107 .handle_event(window_id, Event::Custom(CustomEvent::new("shift-cached")))
7108 .unwrap();
7109 let _ = runtime.render(window_id).unwrap();
7110 let shifted_graph = runtime.widget_graph(window_id).unwrap();
7111 let shifted_child_paint = graph_child(&shifted_graph).geometry.paint_bounds;
7112
7113 assert_eq!(root_counters.borrow().paint, root_paint_before);
7114 assert_eq!(leaf_counters.borrow().paint, leaf_paint_before);
7115 assert_eq!(
7116 shifted_graph.nodes[0].geometry.paint_bounds,
7117 initial_root_paint.union(shifted_child_paint)
7118 );
7119 assert_eq!(
7120 shifted_child_paint,
7121 initial_child_paint.translate(Vector::new(48.0, 0.0))
7122 );
7123 }
7124
7125 #[test]
7126 fn composition_only_translation_updates_focused_ime_rect() {
7127 let root_counters = Rc::new(RefCell::new(Counters::default()));
7128 let presentation = Rc::new(RefCell::new(CachedLayerPresentation::default()));
7129 let mut runtime = Application::new()
7130 .window(
7131 WindowBuilder::new()
7132 .title("Cached IME move")
7133 .root(CachedMoveRoot {
7134 counters: Rc::clone(&root_counters),
7135 child: SingleChild::new_with_paint_boundary(TextImeLeaf {
7136 layout: RefCell::new(None),
7137 }),
7138 presentation,
7139 offset_x: 0.0,
7140 paint_background: true,
7141 }),
7142 )
7143 .build()
7144 .unwrap();
7145 let window_id = runtime.window_ids()[0];
7146 let _ = runtime.render(window_id).unwrap();
7147
7148 let mut pointer = PointerEvent::new(PointerEventKind::Down, Point::new(40.0, 40.0));
7149 pointer.button = Some(PointerButton::Primary);
7150 pointer.buttons = PointerButtons::new(1);
7151 runtime
7152 .handle_event(window_id, Event::Pointer(pointer))
7153 .unwrap();
7154 let focused = runtime.render(window_id).unwrap();
7155 let initial_ime = focused
7156 .ime_composition_rect
7157 .expect("focused text layer should publish an IME rectangle");
7158 let initial_paint_bounds = graph_child(&runtime.widget_graph(window_id).unwrap())
7159 .geometry
7160 .paint_bounds;
7161 let root_paint_before = root_counters.borrow().paint;
7162
7163 runtime
7164 .handle_event(window_id, Event::Custom(CustomEvent::new("shift-cached")))
7165 .unwrap();
7166 let shifted = runtime.render(window_id).unwrap();
7167
7168 assert_eq!(root_counters.borrow().paint, root_paint_before);
7169 assert_eq!(
7170 shifted.ime_composition_rect,
7171 Some(initial_ime.translate(Vector::new(48.0, 0.0)))
7172 );
7173 assert_eq!(
7174 graph_child(&runtime.widget_graph(window_id).unwrap())
7175 .geometry
7176 .paint_bounds,
7177 initial_paint_bounds.translate(Vector::new(48.0, 0.0))
7178 );
7179 assert!(
7180 shifted
7181 .frame
7182 .layer_updates
7183 .iter()
7184 .any(|update| { update.kind == SceneLayerUpdateKind::Transform })
7185 );
7186 }
7187
7188 #[test]
7189 fn explicit_boundary_layer_property_translation_marks_transform_without_content_rebuild() {
7190 let (mut runtime, window_id, root_counters, leaf_counters) = build_cached_move_runtime();
7191
7192 let first = runtime.render(window_id).unwrap();
7193 let layer_id = graph_child(&runtime.widget_graph(window_id).unwrap()).id;
7194 let root_paint_before = root_counters.borrow().paint;
7195 let leaf_paint_before = leaf_counters.borrow().paint;
7196 let initial_layer = first
7197 .frame
7198 .scene
7199 .commands()
7200 .iter()
7201 .find_map(|command| match command {
7202 SceneCommand::Layer(layer) if layer.widget_id() == layer_id => Some(layer.clone()),
7203 _ => None,
7204 })
7205 .expect("cached layer present before property translation");
7206
7207 runtime
7208 .handle_event(
7209 window_id,
7210 Event::Custom(CustomEvent::new("nudge-cached-layer-property")),
7211 )
7212 .unwrap();
7213
7214 let second = runtime.render(window_id).unwrap();
7215 let updated_layer = second
7216 .frame
7217 .scene
7218 .commands()
7219 .iter()
7220 .find_map(|command| match command {
7221 SceneCommand::Layer(layer) if layer.widget_id() == layer_id => Some(layer.clone()),
7222 _ => None,
7223 })
7224 .expect("cached layer present after property translation");
7225
7226 assert_eq!(root_counters.borrow().paint, root_paint_before);
7227 assert_eq!(leaf_counters.borrow().paint, leaf_paint_before);
7228 assert_eq!(second.frame.layer_updates.len(), 1);
7229 assert_eq!(second.frame.layer_updates[0].owner, layer_id);
7230 assert_eq!(
7231 second.frame.layer_updates[0].kind,
7232 SceneLayerUpdateKind::Transform
7233 );
7234 assert_eq!(updated_layer.bounds(), initial_layer.bounds());
7235 assert_eq!(
7236 updated_layer.descriptor.properties.translation,
7237 Vector::new(18.0, 0.0)
7238 );
7239 assert_eq!(updated_layer.descriptor.properties.opacity, 1.0);
7240 }
7241
7242 #[test]
7243 fn explicit_boundary_layer_opacity_marks_effect_without_content_rebuild() {
7244 let (mut runtime, window_id, root_counters, leaf_counters) = build_cached_move_runtime();
7245
7246 let _ = runtime.render(window_id).unwrap();
7247 let layer_id = graph_child(&runtime.widget_graph(window_id).unwrap()).id;
7248 let root_paint_before = root_counters.borrow().paint;
7249 let leaf_paint_before = leaf_counters.borrow().paint;
7250
7251 runtime
7252 .handle_event(
7253 window_id,
7254 Event::Custom(CustomEvent::new("fade-cached-layer")),
7255 )
7256 .unwrap();
7257
7258 let second = runtime.render(window_id).unwrap();
7259 let updated_layer = second
7260 .frame
7261 .scene
7262 .commands()
7263 .iter()
7264 .find_map(|command| match command {
7265 SceneCommand::Layer(layer) if layer.widget_id() == layer_id => Some(layer.clone()),
7266 _ => None,
7267 })
7268 .expect("cached layer present after opacity update");
7269
7270 assert_eq!(root_counters.borrow().paint, root_paint_before);
7271 assert_eq!(leaf_counters.borrow().paint, leaf_paint_before);
7272 assert_eq!(second.frame.layer_updates.len(), 1);
7273 assert_eq!(second.frame.layer_updates[0].owner, layer_id);
7274 assert_eq!(
7275 second.frame.layer_updates[0].kind,
7276 SceneLayerUpdateKind::Effect
7277 );
7278 assert_eq!(
7279 updated_layer.descriptor.properties.translation,
7280 Vector::ZERO
7281 );
7282 assert_eq!(updated_layer.descriptor.properties.opacity, 0.5);
7283 }
7284
7285 #[test]
7286 fn direct_flat_child_translation_repaints_nearest_boundary_root() {
7287 let (mut runtime, window_id, root_counters, leaf_counters) = build_direct_move_runtime();
7288
7289 let first = runtime.render(window_id).unwrap();
7290 let layer_id = graph_child(&runtime.widget_graph(window_id).unwrap()).id;
7291 let root_paint_before = root_counters.borrow().paint;
7292 let leaf_paint_before = leaf_counters.borrow().paint;
7293 let initial_rect = first
7294 .frame
7295 .scene
7296 .commands()
7297 .iter()
7298 .find_map(|command| match command {
7299 SceneCommand::FillRect { rect, .. }
7300 if *rect != Rect::new(0.0, 0.0, 320.0, 180.0) =>
7301 {
7302 Some(*rect)
7303 }
7304 _ => None,
7305 })
7306 .expect("flat child fill present before translation");
7307
7308 runtime
7309 .handle_event(window_id, Event::Custom(CustomEvent::new("shift-direct")))
7310 .unwrap();
7311
7312 let second = runtime.render(window_id).unwrap();
7313
7314 assert_eq!(root_counters.borrow().paint, root_paint_before + 1);
7315 assert_eq!(leaf_counters.borrow().paint, leaf_paint_before + 1);
7316 assert!(!scene_has_layer_for(&second.frame.scene, layer_id));
7317 assert!(second.frame.layer_updates.is_empty());
7318
7319 let translated_rect = second
7320 .frame
7321 .scene
7322 .commands()
7323 .iter()
7324 .find_map(|command| match command {
7325 SceneCommand::FillRect { rect, .. }
7326 if *rect != Rect::new(0.0, 0.0, 320.0, 180.0) =>
7327 {
7328 Some(*rect)
7329 }
7330 _ => None,
7331 })
7332 .expect("flat child fill present after translation");
7333
7334 assert_eq!(translated_rect.x(), initial_rect.x() + 36.0);
7335 assert_eq!(translated_rect.y(), initial_rect.y());
7336 }
7337
7338 #[test]
7339 fn semantics_attach_to_the_nearest_ancestor_node() {
7340 let root_counters = Rc::new(RefCell::new(Counters::default()));
7341 let leaf_counters = Rc::new(RefCell::new(Counters::default()));
7342
7343 let mut runtime = Application::new()
7344 .window(WindowBuilder::new().title("Test").root(TestRoot {
7345 counters: Rc::clone(&root_counters),
7346 child: SingleChild::new(ChildRoot::new(FocusLeaf {
7347 counters: Rc::clone(&leaf_counters),
7348 })),
7349 }))
7350 .build()
7351 .unwrap();
7352
7353 let window_id = runtime.window_ids()[0];
7354 let output = runtime.render(window_id).unwrap();
7355 let root_id = output
7356 .semantics
7357 .iter()
7358 .find(|node| node.role == SemanticsRole::Window)
7359 .map(|node| node.id)
7360 .unwrap();
7361 let leaf = output
7362 .semantics
7363 .iter()
7364 .find(|node| node.role == SemanticsRole::Button)
7365 .unwrap();
7366
7367 assert_eq!(leaf.parent, Some(root_id));
7368 }
7369
7370 #[test]
7371 fn tab_traversal_moves_focus_between_focusable_widgets() {
7372 let (mut runtime, window_id, first_counters, second_counters) =
7373 build_focus_traversal_runtime();
7374
7375 let _ = runtime.render(window_id).unwrap();
7376 let graph = runtime.widget_graph(window_id).unwrap();
7377 let first_id = graph.nodes[1].id;
7378 let second_id = graph.nodes[2].id;
7379
7380 let mut pointer = PointerEvent::new(PointerEventKind::Down, Point::new(48.0, 40.0));
7381 pointer.button = Some(PointerButton::Primary);
7382 pointer.buttons = PointerButtons::new(1);
7383 runtime
7384 .handle_event(window_id, Event::Pointer(pointer))
7385 .unwrap();
7386
7387 assert_eq!(
7388 runtime.focus_state(window_id).unwrap(),
7389 FocusState {
7390 focused_widget: Some(first_id),
7391 window_focused: true,
7392 }
7393 );
7394 assert!(
7395 runtime
7396 .widget_graph(window_id)
7397 .unwrap()
7398 .nodes
7399 .iter()
7400 .find(|node| node.id == first_id)
7401 .is_some_and(|node| node.focused)
7402 );
7403
7404 runtime
7405 .handle_event(
7406 window_id,
7407 Event::Keyboard(KeyboardEvent::new("Tab", KeyState::Pressed)),
7408 )
7409 .unwrap();
7410
7411 assert_eq!(first_counters.borrow().keyboard, 1);
7412 assert_eq!(
7413 runtime.focus_state(window_id).unwrap(),
7414 FocusState {
7415 focused_widget: Some(second_id),
7416 window_focused: true,
7417 }
7418 );
7419 assert!(
7420 runtime
7421 .widget_graph(window_id)
7422 .unwrap()
7423 .nodes
7424 .iter()
7425 .find(|node| node.id == second_id)
7426 .is_some_and(|node| node.focused)
7427 );
7428
7429 let output = runtime.render(window_id).unwrap();
7430 assert!(
7431 output
7432 .semantics
7433 .iter()
7434 .find(|node| node.id == second_id)
7435 .is_some_and(|node| node.state.focused)
7436 );
7437
7438 let mut reverse_tab = KeyboardEvent::new("Tab", KeyState::Pressed);
7439 reverse_tab.modifiers.shift = true;
7440 runtime
7441 .handle_event(window_id, Event::Keyboard(reverse_tab))
7442 .unwrap();
7443
7444 assert_eq!(second_counters.borrow().keyboard, 1);
7445 assert_eq!(
7446 runtime.focus_state(window_id).unwrap(),
7447 FocusState {
7448 focused_widget: Some(first_id),
7449 window_focused: true,
7450 }
7451 );
7452 assert!(
7453 runtime
7454 .widget_graph(window_id)
7455 .unwrap()
7456 .nodes
7457 .iter()
7458 .find(|node| node.id == first_id)
7459 .is_some_and(|node| node.focused)
7460 );
7461 }
7462
7463 #[test]
7464 fn pointer_capture_routes_drag_events_until_pointer_up() {
7465 let (mut runtime, window_id, state) = build_pointer_capture_runtime();
7466
7467 let _ = runtime.render(window_id).unwrap();
7468 let child_id = graph_child(&runtime.widget_graph(window_id).unwrap()).id;
7469
7470 let mut down = PointerEvent::new(PointerEventKind::Down, Point::new(48.0, 40.0));
7471 down.pointer_id = 7;
7472 down.button = Some(PointerButton::Primary);
7473 down.buttons = PointerButtons::new(1);
7474 runtime
7475 .handle_event(window_id, Event::Pointer(down))
7476 .unwrap();
7477
7478 assert_eq!(
7479 runtime.pointer_capture_target(window_id, 7).unwrap(),
7480 Some(child_id)
7481 );
7482
7483 let mut moved = PointerEvent::new(PointerEventKind::Move, Point::new(260.0, 140.0));
7484 moved.pointer_id = 7;
7485 moved.buttons = PointerButtons::new(1);
7486 runtime
7487 .handle_event(window_id, Event::Pointer(moved))
7488 .unwrap();
7489
7490 let mut up = PointerEvent::new(PointerEventKind::Up, Point::new(260.0, 140.0));
7491 up.pointer_id = 7;
7492 up.button = Some(PointerButton::Primary);
7493 runtime.handle_event(window_id, Event::Pointer(up)).unwrap();
7494
7495 assert_eq!(state.borrow().moves, 1);
7496 assert_eq!(state.borrow().ups, 1);
7497 assert_eq!(state.borrow().cancels, 0);
7498 assert_eq!(runtime.pointer_capture_target(window_id, 7).unwrap(), None);
7499 }
7500
7501 #[test]
7502 fn window_focus_loss_cancels_all_pointer_captures_and_applies_cleanup_effects() {
7503 let (mut runtime, window_id, state) = build_pointer_capture_runtime();
7504
7505 let _ = runtime.render(window_id).unwrap();
7506 let child_id = graph_child(&runtime.widget_graph(window_id).unwrap()).id;
7507
7508 for pointer_id in [31, 47] {
7509 let mut down = PointerEvent::new(PointerEventKind::Down, Point::new(48.0, 40.0));
7510 down.pointer_id = pointer_id;
7511 down.pointer_kind = PointerKind::Touch;
7512 down.button = Some(PointerButton::Primary);
7513 down.buttons = PointerButtons::new(1);
7514 runtime
7515 .handle_event(window_id, Event::Pointer(down))
7516 .unwrap();
7517 assert_eq!(
7518 runtime
7519 .pointer_capture_target(window_id, pointer_id)
7520 .unwrap(),
7521 Some(child_id)
7522 );
7523 }
7524
7525 runtime
7526 .handle_event(window_id, Event::Window(WindowEvent::Focused(false)))
7527 .unwrap();
7528
7529 assert_eq!(state.borrow().cancels, 2);
7530 assert_eq!(state.borrow().cancel_followups, 2);
7531 assert!(runtime.needs_render(window_id).unwrap());
7532 for pointer_id in [31, 47] {
7533 assert_eq!(
7534 runtime
7535 .pointer_capture_target(window_id, pointer_id)
7536 .unwrap(),
7537 None
7538 );
7539 }
7540 }
7541
7542 #[test]
7543 fn pointer_capture_transfer_cancels_displaced_owner_and_preserves_new_owner() {
7544 let state = Rc::new(RefCell::new(PointerCaptureState::default()));
7545 let mut runtime = Application::new()
7546 .window(WindowBuilder::new().title("Pointer Capture Transfer").root(
7547 PointerCaptureTransferRoot::new(PointerCaptureLeaf {
7548 state: Rc::clone(&state),
7549 recapture_on_move: false,
7550 }),
7551 ))
7552 .build()
7553 .unwrap();
7554 let window_id = runtime.window_ids()[0];
7555
7556 let _ = runtime.render(window_id).unwrap();
7557 let graph = runtime.widget_graph(window_id).unwrap();
7558 let root_id = graph.root;
7559 let child_id = graph_child(&graph).id;
7560
7561 let mut down = PointerEvent::new(PointerEventKind::Down, Point::new(48.0, 40.0));
7562 down.pointer_id = 17;
7563 down.pointer_kind = PointerKind::Touch;
7564 down.button = Some(PointerButton::Primary);
7565 down.buttons = PointerButtons::new(1);
7566 runtime
7567 .handle_event(window_id, Event::Pointer(down))
7568 .unwrap();
7569 assert_eq!(
7570 runtime.pointer_capture_target(window_id, 17).unwrap(),
7571 Some(child_id)
7572 );
7573
7574 let mut moved = PointerEvent::new(PointerEventKind::Move, Point::new(48.0, 18.0));
7575 moved.pointer_id = 17;
7576 moved.pointer_kind = PointerKind::Touch;
7577 moved.delta = Vector::new(0.0, -22.0);
7578 moved.buttons = PointerButtons::new(1);
7579 runtime
7580 .handle_event(window_id, Event::Pointer(moved))
7581 .unwrap();
7582
7583 assert_eq!(
7584 runtime.pointer_capture_target(window_id, 17).unwrap(),
7585 Some(root_id),
7586 "the displaced owner's release request must not clear the new capture"
7587 );
7588 assert!(
7589 runtime.needs_render(window_id).unwrap(),
7590 "the displaced owner's invalidations must be applied"
7591 );
7592 let state = state.borrow();
7593 assert_eq!(state.cancels, 1);
7594 assert_eq!(state.cancel_followups, 1);
7595 let cancel = state.last_cancel.as_ref().expect("cancel event recorded");
7596 assert_eq!(cancel.pointer_id, 17);
7597 assert_eq!(cancel.kind, PointerEventKind::Cancel);
7598 assert_eq!(cancel.position, Point::new(48.0, 18.0));
7599 assert_eq!(cancel.delta, Vector::ZERO);
7600 assert_eq!(cancel.pointer_kind, PointerKind::Touch);
7601 assert_eq!(cancel.button, None);
7602 assert_eq!(cancel.buttons, PointerButtons::NONE);
7603 assert_eq!(cancel.scroll_delta, None);
7604 }
7605
7606 #[test]
7607 fn pointer_capture_transfer_cancels_reentrant_intermediate_owner() {
7608 let state = Rc::new(RefCell::new(ReentrantCaptureState::default()));
7609 let mut runtime = Application::new()
7610 .window(
7611 WindowBuilder::new()
7612 .title("Reentrant Pointer Capture Transfer")
7613 .root(ReentrantCaptureRoot::new(Rc::clone(&state))),
7614 )
7615 .build()
7616 .unwrap();
7617 let window_id = runtime.window_ids()[0];
7618
7619 let _ = runtime.render(window_id).unwrap();
7620 let graph = runtime.widget_graph(window_id).unwrap();
7621 let root_id = graph.root;
7622 let source_id = graph.nodes[1].id;
7623
7624 let mut down = PointerEvent::new(PointerEventKind::Down, Point::new(48.0, 40.0));
7625 down.pointer_id = 59;
7626 down.pointer_kind = PointerKind::Touch;
7627 down.button = Some(PointerButton::Primary);
7628 down.buttons = PointerButtons::new(1);
7629 runtime
7630 .handle_event(window_id, Event::Pointer(down))
7631 .unwrap();
7632 assert_eq!(
7633 runtime.pointer_capture_target(window_id, 59).unwrap(),
7634 Some(source_id)
7635 );
7636
7637 let mut moved = PointerEvent::new(PointerEventKind::Move, Point::new(48.0, 18.0));
7638 moved.pointer_id = 59;
7639 moved.pointer_kind = PointerKind::Touch;
7640 moved.delta = Vector::new(0.0, -22.0);
7641 moved.buttons = PointerButtons::new(1);
7642 runtime
7643 .handle_event(window_id, Event::Pointer(moved))
7644 .unwrap();
7645
7646 let state = state.borrow();
7647 assert_eq!(state.source_cancels, 1);
7648 assert_eq!(state.intermediate_captures, 1);
7649 assert_eq!(state.intermediate_cancels, 1);
7650 assert_eq!(
7651 runtime.pointer_capture_target(window_id, 59).unwrap(),
7652 Some(root_id),
7653 "the original transfer target must win after intermediate cleanup"
7654 );
7655 }
7656
7657 #[test]
7658 fn recapturing_pointer_for_same_owner_does_not_emit_cancel() {
7659 let state = Rc::new(RefCell::new(PointerCaptureState::default()));
7660 let mut runtime = Application::new()
7661 .window(
7662 WindowBuilder::new()
7663 .title("Pointer Recapture")
7664 .root(ChildRoot::new(PointerCaptureLeaf {
7665 state: Rc::clone(&state),
7666 recapture_on_move: true,
7667 })),
7668 )
7669 .build()
7670 .unwrap();
7671 let window_id = runtime.window_ids()[0];
7672
7673 let _ = runtime.render(window_id).unwrap();
7674 let child_id = graph_child(&runtime.widget_graph(window_id).unwrap()).id;
7675
7676 let mut down = PointerEvent::new(PointerEventKind::Down, Point::new(48.0, 40.0));
7677 down.pointer_id = 23;
7678 down.button = Some(PointerButton::Primary);
7679 down.buttons = PointerButtons::new(1);
7680 runtime
7681 .handle_event(window_id, Event::Pointer(down))
7682 .unwrap();
7683
7684 let mut moved = PointerEvent::new(PointerEventKind::Move, Point::new(80.0, 40.0));
7685 moved.pointer_id = 23;
7686 moved.delta = Vector::new(32.0, 0.0);
7687 moved.buttons = PointerButtons::new(1);
7688 runtime
7689 .handle_event(window_id, Event::Pointer(moved))
7690 .unwrap();
7691
7692 assert_eq!(state.borrow().cancels, 0);
7693 assert_eq!(
7694 runtime.pointer_capture_target(window_id, 23).unwrap(),
7695 Some(child_id)
7696 );
7697 }
7698
7699 #[test]
7700 fn active_drag_hit_tests_drop_target_while_source_keeps_pointer_capture() {
7701 let state = Rc::new(RefCell::new(RuntimeDragState::default()));
7702 let mut runtime = Application::new()
7703 .window(
7704 WindowBuilder::new()
7705 .title("Runtime Drag")
7706 .root(RuntimeDragRoot::new(Rc::clone(&state))),
7707 )
7708 .build()
7709 .unwrap();
7710 let window_id = runtime.window_ids()[0];
7711
7712 let _ = runtime.render(window_id).unwrap();
7713
7714 let mut down = PointerEvent::new(PointerEventKind::Down, Point::new(48.0, 40.0));
7715 down.pointer_id = 7;
7716 down.button = Some(PointerButton::Primary);
7717 down.buttons = PointerButtons::new(1);
7718 runtime
7719 .handle_event(window_id, Event::Pointer(down))
7720 .unwrap();
7721
7722 let mut moved = PointerEvent::new(PointerEventKind::Move, Point::new(188.0, 40.0));
7723 moved.pointer_id = 7;
7724 moved.buttons = PointerButtons::new(1);
7725 runtime
7726 .handle_event(window_id, Event::Pointer(moved))
7727 .unwrap();
7728
7729 let mut up = PointerEvent::new(PointerEventKind::Up, Point::new(188.0, 40.0));
7730 up.pointer_id = 7;
7731 up.button = Some(PointerButton::Primary);
7732 runtime.handle_event(window_id, Event::Pointer(up)).unwrap();
7733
7734 let state = state.borrow();
7735 assert_eq!(state.source_moves, 1);
7736 assert!(state.target_overs >= 1);
7737 assert_eq!(state.drops, 1);
7738 assert_eq!(state.ends, 1);
7739 assert!(matches!(
7740 state.outcome,
7741 Some(DragOutcome::Dropped {
7742 effect: DropEffect::Move,
7743 ..
7744 })
7745 ));
7746 }
7747
7748 #[test]
7749 fn pointer_move_synthesizes_widget_leave_and_enter_transitions() {
7750 let (mut runtime, window_id, first, second) = build_hover_transition_runtime();
7751
7752 let _ = runtime.render(window_id).unwrap();
7753
7754 runtime
7755 .handle_event(
7756 window_id,
7757 Event::Pointer(PointerEvent::new(
7758 PointerEventKind::Move,
7759 Point::new(48.0, 40.0),
7760 )),
7761 )
7762 .unwrap();
7763
7764 assert_eq!(
7765 *first.borrow(),
7766 HoverTransitionState {
7767 enters: 1,
7768 leaves: 0,
7769 hovered: true,
7770 }
7771 );
7772 assert_eq!(*second.borrow(), HoverTransitionState::default());
7773
7774 runtime
7775 .handle_event(
7776 window_id,
7777 Event::Pointer(PointerEvent::new(
7778 PointerEventKind::Move,
7779 Point::new(280.0, 140.0),
7780 )),
7781 )
7782 .unwrap();
7783
7784 assert_eq!(
7785 *first.borrow(),
7786 HoverTransitionState {
7787 enters: 1,
7788 leaves: 1,
7789 hovered: false,
7790 }
7791 );
7792
7793 runtime
7794 .handle_event(
7795 window_id,
7796 Event::Pointer(PointerEvent::new(
7797 PointerEventKind::Move,
7798 Point::new(188.0, 40.0),
7799 )),
7800 )
7801 .unwrap();
7802
7803 assert_eq!(
7804 *second.borrow(),
7805 HoverTransitionState {
7806 enters: 1,
7807 leaves: 0,
7808 hovered: true,
7809 }
7810 );
7811 }
7812
7813 #[test]
7814 fn timers_and_async_wakeups_reenter_runtime_with_registered_target() {
7815 let (mut runtime, window_id, state) = build_wake_runtime();
7816
7817 let _ = runtime.render(window_id).unwrap();
7818
7819 let mut down = PointerEvent::new(PointerEventKind::Down, Point::new(48.0, 40.0));
7820 down.pointer_id = 11;
7821 down.button = Some(PointerButton::Primary);
7822 down.buttons = PointerButtons::new(1);
7823 runtime
7824 .handle_event(window_id, Event::Pointer(down))
7825 .unwrap();
7826
7827 let async_token = state.borrow().async_token.unwrap();
7828 let timer_token = state.borrow().timer_token.unwrap();
7829
7830 assert_eq!(runtime.next_wakeup_time(window_id).unwrap(), Some(3.0));
7831 assert!(runtime.wake_async(window_id, async_token).unwrap());
7832
7833 let ready = runtime.drain_ready_events();
7834 assert_eq!(ready.len(), 1);
7835 assert!(matches!(
7836 ready[0],
7837 (ready_window, Event::Wake(WakeEvent::Async { token, time }))
7838 if ready_window == window_id && token == async_token && time == 0.0
7839 ));
7840
7841 for (ready_window, event) in ready {
7842 runtime.handle_event(ready_window, event).unwrap();
7843 }
7844
7845 assert_eq!(state.borrow().async_wakes, 1);
7846
7847 runtime.tick(3.0);
7848 let ready = runtime.drain_ready_events();
7849 assert_eq!(ready.len(), 1);
7850 assert!(matches!(
7851 ready[0],
7852 (ready_window, Event::Wake(WakeEvent::Timer { token, time, deadline }))
7853 if ready_window == window_id && token == timer_token && time == 3.0 && deadline == 3.0
7854 ));
7855
7856 for (ready_window, event) in ready {
7857 runtime.handle_event(ready_window, event).unwrap();
7858 }
7859
7860 assert_eq!(state.borrow().timer_wakes, 1);
7861 assert_eq!(runtime.next_wakeup_time(window_id).unwrap(), None);
7862 }
7863
7864 #[test]
7865 fn animation_frame_wakeups_reenter_runtime_with_registered_target() {
7866 let (mut runtime, window_id, state) = build_animation_wake_runtime(false);
7867
7868 let _ = runtime.render(window_id).unwrap();
7869
7870 let mut down = PointerEvent::new(PointerEventKind::Down, Point::new(48.0, 40.0));
7871 down.pointer_id = 12;
7872 down.button = Some(PointerButton::Primary);
7873 down.buttons = PointerButtons::new(1);
7874 runtime
7875 .handle_event(window_id, Event::Pointer(down))
7876 .unwrap();
7877
7878 assert_eq!(runtime.next_wakeup_time(window_id).unwrap(), Some(0.0));
7879
7880 let ready = runtime.drain_ready_events();
7881 assert_eq!(ready.len(), 1);
7882 assert!(matches!(
7883 ready[0],
7884 (
7885 ready_window,
7886 Event::Wake(WakeEvent::AnimationFrame {
7887 time,
7888 delta,
7889 frame_index,
7890 })
7891 ) if ready_window == window_id && time == 0.0 && delta == 0.0 && frame_index == 0
7892 ));
7893
7894 for (ready_window, event) in ready {
7895 runtime.handle_event(ready_window, event).unwrap();
7896 }
7897
7898 let state = state.borrow();
7899 assert_eq!(state.animation_wakes, 1);
7900 assert_eq!(state.last_animation_time, Some(0.0));
7901 assert_eq!(state.last_animation_delta, Some(0.0));
7902 assert_eq!(state.last_animation_frame_index, Some(0));
7903 assert_eq!(runtime.next_wakeup_time(window_id).unwrap(), None);
7904 }
7905
7906 #[test]
7907 fn animation_frame_wakeups_are_target_only_not_captured_by_ancestors() {
7908 let state = Rc::new(RefCell::new(AnimationWakeState::default()));
7909 let ancestor_wakes = Rc::new(RefCell::new(0usize));
7910 let mut runtime = Application::new()
7911 .window(WindowBuilder::new().title("Animation Capture").root(
7912 AnimationWakeCapturingRoot {
7913 child: SingleChild::new(AnimationWakeLeaf {
7914 state: Rc::clone(&state),
7915 }),
7916 ancestor_wakes: Rc::clone(&ancestor_wakes),
7917 },
7918 ))
7919 .build()
7920 .unwrap();
7921 let window_id = runtime.window_ids()[0];
7922
7923 let _ = runtime.render(window_id).unwrap();
7924
7925 let mut down = PointerEvent::new(PointerEventKind::Down, Point::new(48.0, 40.0));
7926 down.pointer_id = 15;
7927 down.button = Some(PointerButton::Primary);
7928 down.buttons = PointerButtons::new(1);
7929 runtime
7930 .handle_event(window_id, Event::Pointer(down))
7931 .unwrap();
7932
7933 let ready = runtime.drain_ready_events();
7934 assert_eq!(ready.len(), 1);
7935 for (ready_window, event) in ready {
7936 runtime.handle_event(ready_window, event).unwrap();
7937 }
7938
7939 assert_eq!(state.borrow().animation_wakes, 1);
7940 assert_eq!(*ancestor_wakes.borrow(), 0);
7941 assert_eq!(runtime.next_wakeup_time(window_id).unwrap(), None);
7942 }
7943
7944 #[test]
7945 fn repeated_animation_frame_requests_are_idempotent_for_the_same_widget() {
7946 let (mut runtime, window_id, state) = build_animation_wake_runtime(true);
7947
7948 let _ = runtime.render(window_id).unwrap();
7949
7950 let mut down = PointerEvent::new(PointerEventKind::Down, Point::new(48.0, 40.0));
7951 down.pointer_id = 13;
7952 down.button = Some(PointerButton::Primary);
7953 down.buttons = PointerButtons::new(1);
7954 runtime
7955 .handle_event(window_id, Event::Pointer(down))
7956 .unwrap();
7957
7958 let ready = runtime.drain_ready_events();
7959 assert_eq!(ready.len(), 1);
7960
7961 for (ready_window, event) in ready {
7962 runtime.handle_event(ready_window, event).unwrap();
7963 }
7964
7965 assert_eq!(state.borrow().animation_wakes, 1);
7966 assert_eq!(runtime.next_wakeup_time(window_id).unwrap(), None);
7967 }
7968
7969 #[test]
7970 fn animated_widget_registration_is_cleaned_up_when_widget_disappears() {
7971 let (mut runtime, window_id) = build_removable_animation_runtime();
7972
7973 let _ = runtime.render(window_id).unwrap();
7974
7975 let mut down = PointerEvent::new(PointerEventKind::Down, Point::new(48.0, 40.0));
7976 down.pointer_id = 14;
7977 down.button = Some(PointerButton::Primary);
7978 down.buttons = PointerButtons::new(1);
7979 runtime
7980 .handle_event(window_id, Event::Pointer(down))
7981 .unwrap();
7982
7983 assert_eq!(runtime.next_wakeup_time(window_id).unwrap(), Some(0.0));
7984
7985 runtime
7986 .handle_event(
7987 window_id,
7988 Event::Custom(CustomEvent::new("drop-animation-child")),
7989 )
7990 .unwrap();
7991 let _ = runtime.render(window_id).unwrap();
7992
7993 assert_eq!(runtime.next_wakeup_time(window_id).unwrap(), None);
7994 assert!(runtime.drain_ready_events().is_empty());
7995 }
7996
7997 #[test]
7998 fn initial_runtime_needs_render() {
7999 let (runtime, window_id, _, _) = build_runtime();
8000
8001 assert!(runtime.needs_render(window_id).unwrap());
8002 }
8003
8004 #[test]
8005 fn runtime_render_populates_widget_count_diagnostics() {
8006 let (mut runtime, window_id, _, _) = build_runtime();
8007
8008 let output = runtime.render(window_id).unwrap();
8009 let graph = runtime.widget_graph(window_id).unwrap();
8010
8011 assert_eq!(output.diagnostics.widget_count, graph.nodes.len());
8012 }
8013
8014 #[test]
8015 fn runtime_render_reports_ime_composition_rect_for_shaped_text_widgets() {
8016 let (mut runtime, window_id) = build_text_runtime();
8017 set_window_scene_statistics_detail_mode(window_id, SceneStatisticsDetailMode::Detailed);
8018
8019 let output = runtime.render(window_id).unwrap();
8020
8021 assert!(output.ime_composition_rect.is_some());
8022 assert!(output.diagnostics.text_caches.runtime_layout.misses > 0);
8023 assert!(!output.frame.scene.commands().is_empty());
8024 let mut saw_shaped_text = false;
8025 output.frame.scene.visit_commands(&mut |command| {
8026 if matches!(command, sui_scene::SceneCommand::DrawShapedText(_)) {
8027 saw_shaped_text = true;
8028 }
8029 });
8030 assert!(saw_shaped_text);
8031 }
8032
8033 #[test]
8034 fn text_layout_retention_follows_retained_scene_handles() {
8035 let system = TextSystem::new();
8036 let first = system
8037 .shape_text_persistent(
8038 None,
8039 "first",
8040 Size::new(120.0, 24.0),
8041 TextStyle::new(Color::WHITE),
8042 &sui_text::FontRegistry::new(),
8043 )
8044 .unwrap();
8045 let second = system
8046 .shape_text_persistent(
8047 None,
8048 "second",
8049 Size::new(120.0, 24.0),
8050 TextStyle::new(Color::WHITE),
8051 &sui_text::FontRegistry::new(),
8052 )
8053 .unwrap();
8054
8055 let mut scene = Scene::new();
8056 scene.push(SceneCommand::DrawShapedText(sui_text::ShapedText::new(
8057 Point::ZERO,
8058 &first,
8059 )));
8060 super::retain_text_layouts_for_scene(&system, &scene);
8061
8062 let registry = system.text_layout_registry();
8063 assert!(registry.contains(first.handle()));
8064 assert!(!registry.contains(second.handle()));
8065 }
8066
8067 #[test]
8068 fn removing_a_window_tears_down_runtime_state() {
8069 let (mut runtime, window_id, _, _) = build_runtime();
8070 set_window_render_options(window_id, WindowRenderOptions::new(false, 1.0));
8071 assert!(window_render_options(window_id).is_some());
8072
8073 runtime.remove_window(window_id).unwrap();
8074
8075 assert!(runtime.window_ids().is_empty());
8076 assert!(window_render_options(window_id).is_none());
8077 assert!(runtime.needs_render(window_id).is_err());
8078 assert!(runtime.focus_state(window_id).is_err());
8079 assert!(runtime.render(window_id).is_err());
8080 }
8081}