1#[cfg(feature = "profiler")]
2use crate::DebugFrameOverlayMode;
3#[cfg(any(feature = "inspector", debug_assertions))]
4use crate::Inspector;
5#[cfg(feature = "profiler")]
6use crate::profiler;
7use crate::{
8 Action, AnyDrag, AnyElement, AnyImageCache, AnyTooltip, AnyView, App, AppContext, Arena, Asset,
9 AsyncWindowContext, AtlasTile, AvailableSpace, Background, BorderStyle, Bounds, BoxShadow,
10 Capslock, Context, Corners, CursorHideMode, CursorStyle, Decorations, DevicePixels,
11 DispatchActionListener, DispatchNodeId, DispatchTree, DisplayId, Edges, Effect, Entity,
12 EntityId, EventEmitter, FileDropEvent, FontId, Global, GlobalElementId, GlyphId, GpuSpecs,
13 Hsla, InputHandler, IsZero, KeyBinding, KeyContext, KeyDownEvent, KeyEvent, Keystroke,
14 KeystrokeEvent, LayoutId, LineLayoutIndex, Modifiers, ModifiersChangedEvent, MonochromeSprite,
15 MouseButton, MouseEvent, MouseMoveEvent, MouseUpEvent, Path, Pixels, PlatformAtlas,
16 PlatformDisplay, PlatformInput, PlatformInputHandler, PlatformWindow, Point, PolychromeSprite,
17 Priority, PromptButton, PromptLevel, Quad, Render, RenderGlyphParams, RenderImage,
18 RenderImageParams, RenderSvgParams, Replay, ResizeEdge, SMOOTH_SVG_SCALE_FACTOR,
19 SUBPIXEL_VARIANTS_X, SUBPIXEL_VARIANTS_Y, ScaledPixels, Scene, Shadow, SharedString, Size,
20 StrikethroughStyle, Style, SubpixelSprite, SubscriberSet, Subscription, SystemWindowTab,
21 SystemWindowTabController, TabStopMap, TaffyLayoutEngine, Task, TextInputConfiguration,
22 TextInputStateChange, TextRenderingMode, TextStyle, TextStyleRefinement, ThermalState,
23 TransformationMatrix, Underline, UnderlineStyle, WindowAppearance, WindowBackgroundAppearance,
24 WindowBounds, WindowControls, WindowDecorations, WindowOptions, WindowParams, WindowTextSystem,
25 WindowVisibility, point, prelude::*, px, rems, size, transparent_black,
26};
27
28use crate::gestures::{GestureTuning, RecognizedTouchGesture, TouchGestureRecognizer};
29use crate::interactive::TouchEvent;
30use anyhow::{Context as _, Result, anyhow};
31use collections::{FxHashMap, FxHashSet};
32#[cfg(target_os = "macos")]
33use core_video::pixel_buffer::CVPixelBuffer;
34use derive_more::{Deref, DerefMut};
35use futures::channel::oneshot;
36use gpui_util::post_inc;
37use gpui_util::{ResultExt, measure};
38use itertools::FoldWhile::{Continue, Done};
39use itertools::Itertools;
40use parking_lot::RwLock;
41use raw_window_handle::{HandleError, HasDisplayHandle, HasWindowHandle};
42use refineable::Refineable;
43use scheduler::Instant;
44use slotmap::SlotMap;
45use smallvec::SmallVec;
46use std::{
47 any::{Any, TypeId},
48 borrow::Cow,
49 cell::{Cell, RefCell},
50 cmp,
51 fmt::{Debug, Display},
52 hash::{Hash, Hasher},
53 marker::PhantomData,
54 mem,
55 ops::{DerefMut, Range},
56 rc::Rc,
57 sync::{
58 Arc, Weak,
59 atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst},
60 },
61 thread::AccessError,
62 time::Duration,
63};
64use uuid::Uuid;
65
66pub(crate) mod a11y;
67mod prompts;
68
69pub use a11y::A11ySubtreeBuilder;
70
71use self::a11y::A11y;
72#[cfg(not(target_family = "wasm"))]
73use self::a11y::ROOT_NODE_ID;
74use crate::util::{
75 atomic_incr_if_not_zero, ceil_to_device_pixel, floor_to_device_pixel, round_half_toward_zero,
76 round_half_toward_zero_f64, round_stroke_to_device_pixel, round_to_device_pixel,
77};
78pub use prompts::*;
79
80pub const DEFAULT_WINDOW_SIZE: Size<Pixels> = size(px(1536.), px(1095.));
82
83pub const DEFAULT_ADDITIONAL_WINDOW_SIZE: Size<Pixels> = Size {
86 width: Pixels(900.),
87 height: Pixels(750.),
88};
89
90#[derive(Default, Copy, Clone, Debug, Eq, PartialEq)]
92pub enum DispatchPhase {
93 #[default]
98 Bubble,
99 Capture,
105}
106
107impl DispatchPhase {
108 #[inline]
110 pub fn bubble(self) -> bool {
111 self == DispatchPhase::Bubble
112 }
113
114 #[inline]
116 pub fn capture(self) -> bool {
117 self == DispatchPhase::Capture
118 }
119}
120
121struct WindowInvalidatorInner {
122 #[cfg(feature = "profiler")]
123 pub window_id: WindowId,
124 pub dirty: bool,
125 pub draw_phase: DrawPhase,
126 pub dirty_views: FxHashSet<EntityId>,
127 pub update_count: usize,
128 #[cfg(feature = "profiler")]
129 pub frame_dirty: FrameDirtyAccumulator,
130 pub platform_waker: Option<Rc<dyn Fn()>>,
131}
132
133#[cfg(feature = "profiler")]
139#[derive(Default)]
140struct FrameDirtyAccumulator {
141 dirty_at: Option<Instant>,
142 invalidations: u64,
143}
144
145#[derive(Clone)]
146pub(crate) struct WindowInvalidator {
147 inner: Rc<RefCell<WindowInvalidatorInner>>,
148}
149
150impl WindowInvalidator {
151 pub fn new(#[allow(unused_variables)] window_id: WindowId) -> Self {
152 WindowInvalidator {
153 inner: Rc::new(RefCell::new(WindowInvalidatorInner {
154 #[cfg(feature = "profiler")]
155 window_id,
156 dirty: true,
157 draw_phase: DrawPhase::None,
158 dirty_views: FxHashSet::default(),
159 update_count: 0,
160 #[cfg(feature = "profiler")]
161 frame_dirty: FrameDirtyAccumulator::default(),
162 platform_waker: None,
163 })),
164 }
165 }
166
167 pub fn invalidate_view(&self, entity: EntityId, cx: &mut App) -> bool {
168 let mut inner = self.inner.borrow_mut();
169 inner.update_count += 1;
170 inner.dirty_views.insert(entity);
171 if inner.draw_phase == DrawPhase::None {
172 #[cfg(feature = "profiler")]
173 let dirty_at = Self::record_frame_dirty(&mut inner);
174 let became_dirty = !inner.dirty;
175 inner.dirty = true;
176 let waker = became_dirty.then(|| inner.platform_waker.clone()).flatten();
177 #[cfg(feature = "profiler")]
178 let window_id = inner.window_id;
179 drop(inner);
180 #[cfg(feature = "profiler")]
181 if became_dirty {
182 profiler::journal::record_frame_pending(window_id, dirty_at);
183 }
184 cx.push_effect(Effect::Notify { emitter: entity });
185 if let Some(waker) = waker {
186 waker();
187 }
188 true
189 } else {
190 false
191 }
192 }
193
194 pub fn is_dirty(&self) -> bool {
195 self.inner.borrow().dirty
196 }
197
198 pub fn set_dirty(&self, dirty: bool) {
199 let mut inner = self.inner.borrow_mut();
200 let became_dirty = dirty && !inner.dirty;
201 inner.dirty = dirty;
202 if dirty {
203 inner.update_count += 1;
204 }
205 #[cfg(feature = "profiler")]
206 let dirty_at = dirty.then(|| Self::record_frame_dirty(&mut inner));
207 let waker = became_dirty.then(|| inner.platform_waker.clone()).flatten();
208 #[cfg(feature = "profiler")]
209 let window_id = inner.window_id;
210 drop(inner);
211 #[cfg(feature = "profiler")]
212 if became_dirty && let Some(dirty_at) = dirty_at {
213 profiler::journal::record_frame_pending(window_id, dirty_at);
214 }
215 if let Some(waker) = waker {
216 waker();
217 }
218 }
219
220 pub fn set_platform_waker(&self, waker: Option<Rc<dyn Fn()>>) {
221 let mut inner = self.inner.borrow_mut();
222 inner.platform_waker = waker;
223 let waker = inner.dirty.then(|| inner.platform_waker.clone()).flatten();
224 drop(inner);
225 if let Some(waker) = waker {
226 waker();
227 }
228 }
229
230 pub fn wake_platform(&self) {
234 let waker = self.inner.borrow().platform_waker.clone();
235 if let Some(waker) = waker {
236 waker();
237 }
238 }
239
240 pub fn set_phase(&self, phase: DrawPhase) {
241 self.inner.borrow_mut().draw_phase = phase
242 }
243
244 pub fn update_count(&self) -> usize {
245 self.inner.borrow().update_count
246 }
247
248 #[cfg(feature = "profiler")]
249 fn record_frame_dirty(inner: &mut WindowInvalidatorInner) -> Instant {
250 let dirty_at = *inner.frame_dirty.dirty_at.get_or_insert_with(Instant::now);
251 inner.frame_dirty.invalidations += 1;
252 dirty_at
253 }
254
255 #[cfg(feature = "profiler")]
256 fn take_frame_dirty(&self) -> FrameDirtyAccumulator {
257 mem::take(&mut self.inner.borrow_mut().frame_dirty)
258 }
259
260 pub fn take_views(&self) -> FxHashSet<EntityId> {
261 mem::take(&mut self.inner.borrow_mut().dirty_views)
262 }
263
264 pub fn replace_views(&self, views: FxHashSet<EntityId>) {
265 self.inner.borrow_mut().dirty_views = views;
266 }
267
268 pub fn not_drawing(&self) -> bool {
269 self.inner.borrow().draw_phase == DrawPhase::None
270 }
271
272 #[track_caller]
273 pub fn debug_assert_paint(&self) {
274 debug_assert!(
275 matches!(self.inner.borrow().draw_phase, DrawPhase::Paint),
276 "this method can only be called during paint"
277 );
278 }
279
280 #[track_caller]
281 pub fn debug_assert_prepaint(&self) {
282 debug_assert!(
283 matches!(self.inner.borrow().draw_phase, DrawPhase::Prepaint),
284 "this method can only be called during request_layout, or prepaint"
285 );
286 }
287
288 #[track_caller]
289 pub fn debug_assert_paint_or_prepaint(&self) {
290 debug_assert!(
291 matches!(
292 self.inner.borrow().draw_phase,
293 DrawPhase::Paint | DrawPhase::Prepaint
294 ),
295 "this method can only be called during request_layout, prepaint, or paint"
296 );
297 }
298}
299
300type AnyObserver = Box<dyn FnMut(&mut Window, &mut App) -> bool + 'static>;
301
302pub(crate) type AnyWindowFocusListener =
303 Box<dyn FnMut(&WindowFocusEvent, &mut Window, &mut App) -> bool + 'static>;
304
305pub(crate) struct WindowFocusEvent {
306 pub(crate) previous_focus_path: SmallVec<[FocusId; 8]>,
307 pub(crate) current_focus_path: SmallVec<[FocusId; 8]>,
308}
309
310impl WindowFocusEvent {
311 pub fn is_focus_in(&self, focus_id: FocusId) -> bool {
312 !self.previous_focus_path.contains(&focus_id) && self.current_focus_path.contains(&focus_id)
313 }
314
315 pub fn is_focus_out(&self, focus_id: FocusId) -> bool {
316 self.previous_focus_path.contains(&focus_id) && !self.current_focus_path.contains(&focus_id)
317 }
318}
319
320pub struct FocusOutEvent {
322 pub blurred: WeakFocusHandle,
324}
325
326slotmap::new_key_type! {
327 pub struct FocusId;
329}
330
331thread_local! {
332 pub(crate) static ELEMENT_ARENA: RefCell<Arena> = RefCell::new(Arena::new(1024 * 1024));
335
336 static CURRENT_ELEMENT_ARENA: Cell<Option<*const RefCell<Arena>>> = const { Cell::new(None) };
340}
341
342fn draw_in_progress() -> bool {
353 CURRENT_ELEMENT_ARENA.with(|current| current.get().is_some())
354}
355
356#[inline(always)]
359pub(crate) fn with_element_arena<R>(callback: impl FnOnce(&mut Arena) -> R) -> R {
360 let mut callback = Some(callback);
361 let mut result = None;
362 let access = with_element_arena_erased(&mut |arena| {
363 result = Some(callback.take().expect("arena callback runs once")(arena));
364 });
365 drop(callback);
366 access.expect("cannot access a Thread Local Storage value during or after destruction");
367 result.expect("arena callback produces a result")
368}
369
370pub(crate) struct ElementArenaScope {
385 entered: *const RefCell<Arena>,
388 previous: Option<*const RefCell<Arena>>,
389 exited: bool,
390}
391
392impl ElementArenaScope {
393 pub(crate) fn enter(arena: &RefCell<Arena>) -> Self {
395 arena.borrow_mut().begin_scope();
396 let previous = CURRENT_ELEMENT_ARENA.with(|current| {
397 let prev = current.get();
398 current.set(Some(arena as *const RefCell<Arena>));
399 prev
400 });
401 Self {
402 entered: arena as *const RefCell<Arena>,
403 previous,
404 exited: false,
405 }
406 }
407
408 pub(crate) fn exit(mut self, arena: &RefCell<Arena>) -> ArenaClearNeeded {
417 assert!(
418 std::ptr::eq(self.entered, arena),
419 "ElementArenaScope::exit called with a different arena than was entered"
420 );
421 self.exited = true;
422 ArenaClearNeeded::new(arena)
427 }
428}
429
430impl Drop for ElementArenaScope {
431 fn drop(&mut self) {
432 CURRENT_ELEMENT_ARENA.with(|current| {
439 current.set(self.previous);
440 });
441 unsafe { &*self.entered }.borrow_mut().end_scope();
445 if !self.exited && !std::thread::panicking() {
446 debug_assert!(false, "ElementArenaScope dropped without calling exit()");
447 log::error!(
448 "ElementArenaScope dropped without calling exit(); \
449 the arena clear for this draw was never requested"
450 );
451 }
452 }
453}
454
455#[must_use]
457pub struct ArenaClearNeeded {
458 arena: *const RefCell<Arena>,
461}
462
463impl ArenaClearNeeded {
464 fn new(arena: &RefCell<Arena>) -> Self {
467 Self {
468 arena: arena as *const RefCell<Arena>,
469 }
470 }
471
472 pub fn clear(self, cx: &mut App) {
481 assert!(
482 std::ptr::eq(self.arena, &cx.element_arena),
483 "ArenaClearNeeded::clear called with a different App than the draw ran against"
484 );
485 cx.element_arena.borrow_mut().clear();
486 }
487}
488
489pub(crate) type FocusMap = RwLock<SlotMap<FocusId, FocusRef>>;
490pub(crate) struct FocusRef {
491 pub(crate) ref_count: AtomicUsize,
492 pub(crate) tab_index: isize,
493 pub(crate) tab_stop: bool,
494}
495
496impl FocusId {
497 pub fn is_focused(&self, window: &Window) -> bool {
499 window.focus == Some(*self)
500 }
501
502 pub fn contains_focused(&self, window: &Window, cx: &App) -> bool {
505 window
506 .focused(cx)
507 .is_some_and(|focused| self.contains(focused.id, window))
508 }
509
510 pub fn within_focused(&self, window: &Window, cx: &App) -> bool {
513 let focused = window.focused(cx);
514 focused.is_some_and(|focused| focused.id.contains(*self, window))
515 }
516
517 pub(crate) fn contains(&self, other: Self, window: &Window) -> bool {
519 window
520 .rendered_frame
521 .dispatch_tree
522 .focus_contains(*self, other)
523 }
524}
525
526pub struct FocusHandle {
528 pub(crate) id: FocusId,
529 handles: Arc<FocusMap>,
530 pub tab_index: isize,
532 pub tab_stop: bool,
534}
535
536impl std::fmt::Debug for FocusHandle {
537 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
538 f.write_fmt(format_args!("FocusHandle({:?})", self.id))
539 }
540}
541
542impl FocusHandle {
543 pub(crate) fn new(handles: &Arc<FocusMap>) -> Self {
544 let id = handles.write().insert(FocusRef {
545 ref_count: AtomicUsize::new(1),
546 tab_index: 0,
547 tab_stop: false,
548 });
549
550 Self {
551 id,
552 tab_index: 0,
553 tab_stop: false,
554 handles: handles.clone(),
555 }
556 }
557
558 pub(crate) fn for_id(id: FocusId, handles: &Arc<FocusMap>) -> Option<Self> {
559 let lock = handles.read();
560 let focus = lock.get(id)?;
561 if atomic_incr_if_not_zero(&focus.ref_count) == 0 {
562 return None;
563 }
564 Some(Self {
565 id,
566 tab_index: focus.tab_index,
567 tab_stop: focus.tab_stop,
568 handles: handles.clone(),
569 })
570 }
571
572 pub fn tab_index(mut self, index: isize) -> Self {
574 self.tab_index = index;
575 if let Some(focus) = self.handles.write().get_mut(self.id) {
576 focus.tab_index = index;
577 }
578 self
579 }
580
581 pub fn tab_stop(mut self, tab_stop: bool) -> Self {
585 self.tab_stop = tab_stop;
586 if let Some(focus) = self.handles.write().get_mut(self.id) {
587 focus.tab_stop = tab_stop;
588 }
589 self
590 }
591
592 pub fn downgrade(&self) -> WeakFocusHandle {
594 WeakFocusHandle {
595 id: self.id,
596 handles: Arc::downgrade(&self.handles),
597 }
598 }
599
600 pub fn focus(&self, window: &mut Window, cx: &mut App) {
602 window.focus(self, cx)
603 }
604
605 pub fn is_focused(&self, window: &Window) -> bool {
607 self.id.is_focused(window)
608 }
609
610 pub fn contains_focused(&self, window: &Window, cx: &App) -> bool {
613 self.id.contains_focused(window, cx)
614 }
615
616 pub fn within_focused(&self, window: &Window, cx: &mut App) -> bool {
619 self.id.within_focused(window, cx)
620 }
621
622 pub fn contains(&self, other: &Self, window: &Window) -> bool {
624 self.id.contains(other.id, window)
625 }
626
627 pub fn dispatch_action(&self, action: &dyn Action, window: &mut Window, cx: &mut App) {
629 if let Some(node_id) = window
630 .rendered_frame
631 .dispatch_tree
632 .focusable_node_id(self.id)
633 {
634 window.dispatch_action_on_node(node_id, action, cx)
635 }
636 }
637}
638
639impl Clone for FocusHandle {
640 fn clone(&self) -> Self {
641 Self::for_id(self.id, &self.handles).unwrap()
642 }
643}
644
645impl PartialEq for FocusHandle {
646 fn eq(&self, other: &Self) -> bool {
647 self.id == other.id
648 }
649}
650
651impl Eq for FocusHandle {}
652
653impl Drop for FocusHandle {
654 fn drop(&mut self) {
655 self.handles
656 .read()
657 .get(self.id)
658 .unwrap()
659 .ref_count
660 .fetch_sub(1, SeqCst);
661 }
662}
663
664#[derive(Clone, Debug)]
666pub struct WeakFocusHandle {
667 pub(crate) id: FocusId,
668 pub(crate) handles: Weak<FocusMap>,
669}
670
671impl WeakFocusHandle {
672 pub fn upgrade(&self) -> Option<FocusHandle> {
674 let handles = self.handles.upgrade()?;
675 FocusHandle::for_id(self.id, &handles)
676 }
677}
678
679impl PartialEq for WeakFocusHandle {
680 fn eq(&self, other: &WeakFocusHandle) -> bool {
681 self.id == other.id
682 }
683}
684
685impl Eq for WeakFocusHandle {}
686
687impl PartialEq<FocusHandle> for WeakFocusHandle {
688 fn eq(&self, other: &FocusHandle) -> bool {
689 self.id == other.id
690 }
691}
692
693impl PartialEq<WeakFocusHandle> for FocusHandle {
694 fn eq(&self, other: &WeakFocusHandle) -> bool {
695 self.id == other.id
696 }
697}
698
699pub trait Focusable: 'static {
702 fn focus_handle(&self, cx: &App) -> FocusHandle;
704}
705
706impl<V: Focusable> Focusable for Entity<V> {
707 fn focus_handle(&self, cx: &App) -> FocusHandle {
708 self.read(cx).focus_handle(cx)
709 }
710}
711
712pub trait ManagedView: Focusable + EventEmitter<DismissEvent> + Render {}
715
716impl<M: Focusable + EventEmitter<DismissEvent> + Render> ManagedView for M {}
717
718pub struct DismissEvent;
720
721type FrameCallback = Box<dyn FnOnce(&mut Window, &mut App)>;
722
723pub(crate) type AnyMouseListener =
724 Box<dyn FnMut(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static>;
725
726#[derive(Clone)]
727pub(crate) struct CursorStyleRequest {
728 pub(crate) hitbox_id: Option<HitboxId>,
729 pub(crate) style: CursorStyle,
730}
731
732#[derive(Default, Eq, PartialEq)]
733pub(crate) struct HitTest {
734 pub(crate) ids: SmallVec<[HitboxId; 8]>,
735 pub(crate) hover_hitbox_count: usize,
736}
737
738#[derive(Clone, Copy, Debug, Eq, PartialEq)]
740pub enum WindowControlArea {
741 Drag,
743 Close,
745 Max,
747 Min,
749}
750
751#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
753pub struct HitboxId(u64);
754
755#[cfg(feature = "test-support")]
756impl HitboxId {
757 pub const fn placeholder() -> Self {
762 Self(0)
763 }
764}
765
766impl HitboxId {
767 pub fn is_hovered(self, window: &Window) -> bool {
774 if window.captured_hitbox == Some(self) {
776 return true;
777 }
778 if window.last_input_was_keyboard() {
779 return false;
780 }
781 self.hit_test(window)
782 }
783
784 pub(crate) fn is_hovered_ignoring_last_input(self, window: &Window) -> bool {
789 if window.captured_hitbox == Some(self) {
791 return true;
792 }
793 self.hit_test(window)
794 }
795
796 fn hit_test(self, window: &Window) -> bool {
797 let hit_test = &window.mouse_hit_test;
798 for id in hit_test.ids.iter().take(hit_test.hover_hitbox_count) {
799 if self == *id {
800 return true;
801 }
802 }
803 false
804 }
805
806 pub fn should_handle_scroll(self, window: &Window) -> bool {
811 window.mouse_hit_test.ids.contains(&self)
812 }
813
814 fn next(mut self) -> HitboxId {
815 HitboxId(self.0.wrapping_add(1))
816 }
817}
818
819#[derive(Clone, Debug, Deref)]
822pub struct Hitbox {
823 pub id: HitboxId,
825 #[deref]
827 pub bounds: Bounds<Pixels>,
828 pub content_mask: ContentMask<Pixels>,
830 pub behavior: HitboxBehavior,
832}
833
834impl Hitbox {
835 pub fn is_hovered(&self, window: &Window) -> bool {
852 self.id.is_hovered(window)
853 }
854
855 pub fn is_hovered_at(&self, position: Point<Pixels>, window: &Window) -> bool {
858 let hit_test = window.rendered_frame.hit_test(position);
859 hit_test
860 .ids
861 .iter()
862 .take(hit_test.hover_hitbox_count)
863 .any(|id| self.id == *id)
864 }
865
866 pub fn should_handle_scroll(&self, window: &Window) -> bool {
873 self.id.should_handle_scroll(window)
874 }
875}
876
877#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
879pub enum HitboxBehavior {
880 #[default]
882 Normal,
883
884 BlockMouse,
906
907 BlockMouseExceptScroll,
934}
935
936#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
938pub struct TooltipId(usize);
939
940impl TooltipId {
941 pub fn is_hovered(&self, window: &Window) -> bool {
943 window
944 .tooltip_bounds
945 .as_ref()
946 .is_some_and(|tooltip_bounds| {
947 tooltip_bounds.id == *self
948 && tooltip_bounds.bounds.contains(&window.mouse_position())
949 })
950 }
951}
952
953pub(crate) struct TooltipBounds {
954 id: TooltipId,
955 bounds: Bounds<Pixels>,
956}
957
958#[derive(Clone)]
959pub(crate) struct TooltipRequest {
960 id: TooltipId,
961 tooltip: AnyTooltip,
962}
963
964pub(crate) struct DeferredDraw {
965 current_view: EntityId,
966 priority: usize,
967 parent_node: DispatchNodeId,
968 element_id_stack: SmallVec<[ElementId; 32]>,
969 text_style_stack: Vec<TextStyleRefinement>,
970 content_mask: Option<ContentMask<Pixels>>,
971 rem_size: Pixels,
972 element: Option<AnyElement>,
973 absolute_offset: Point<Pixels>,
974 prepaint_range: Range<PrepaintStateIndex>,
975 paint_range: Range<PaintIndex>,
976}
977
978pub(crate) struct Frame {
979 pub(crate) focus: Option<FocusId>,
980 pub(crate) window_active: bool,
981 pub(crate) element_states: FxHashMap<(GlobalElementId, TypeId), ElementStateBox>,
982 accessed_element_states: Vec<(GlobalElementId, TypeId)>,
983 pub(crate) mouse_listeners: Vec<Option<AnyMouseListener>>,
984 pub(crate) dispatch_tree: DispatchTree,
985 pub(crate) scene: Scene,
986 pub(crate) hitboxes: Vec<Hitbox>,
987 pub(crate) window_control_hitboxes: Vec<(WindowControlArea, Hitbox)>,
988 pub(crate) deferred_draws: Vec<DeferredDraw>,
989 pub(crate) input_handlers: Vec<Option<PlatformInputHandler>>,
990 pub(crate) tooltip_requests: Vec<Option<TooltipRequest>>,
991 pub(crate) cursor_styles: Vec<CursorStyleRequest>,
992 #[cfg(any(test, feature = "test-support"))]
993 pub(crate) debug_bounds: FxHashMap<String, Bounds<Pixels>>,
994 #[cfg(any(test, feature = "test-support"))]
995 debug_bounds_records: Vec<(String, Bounds<Pixels>)>,
996 #[cfg(any(feature = "inspector", debug_assertions))]
997 pub(crate) next_inspector_instance_ids: FxHashMap<Rc<crate::InspectorElementPath>, usize>,
998 #[cfg(any(feature = "inspector", debug_assertions))]
999 pub(crate) inspector_hitboxes: FxHashMap<HitboxId, crate::InspectorElementId>,
1000 pub(crate) tab_stops: TabStopMap,
1001}
1002
1003#[derive(Clone, Default)]
1004pub(crate) struct PrepaintStateIndex {
1005 hitboxes_index: usize,
1006 tooltips_index: usize,
1007 deferred_draws_index: usize,
1008 dispatch_tree_index: usize,
1009 accessed_element_states_index: usize,
1010 line_layout_index: LineLayoutIndex,
1011}
1012
1013#[derive(Clone, Default)]
1014pub(crate) struct PaintIndex {
1015 scene_index: usize,
1016 #[cfg(any(test, feature = "test-support"))]
1017 debug_bounds_index: usize,
1018 mouse_listeners_index: usize,
1019 input_handlers_index: usize,
1020 cursor_styles_index: usize,
1021 accessed_element_states_index: usize,
1022 tab_handle_index: usize,
1023 line_layout_index: LineLayoutIndex,
1024}
1025
1026impl Frame {
1027 #[cfg(any(test, feature = "test-support"))]
1028 pub(crate) fn record_debug_bounds(&mut self, selector: String, bounds: Bounds<Pixels>) {
1029 self.debug_bounds.insert(selector.clone(), bounds);
1030 self.debug_bounds_records.push((selector, bounds));
1031 }
1032
1033 pub(crate) fn new(dispatch_tree: DispatchTree) -> Self {
1034 Frame {
1035 focus: None,
1036 window_active: false,
1037 element_states: FxHashMap::default(),
1038 accessed_element_states: Vec::new(),
1039 mouse_listeners: Vec::new(),
1040 dispatch_tree,
1041 scene: Scene::default(),
1042 hitboxes: Vec::new(),
1043 window_control_hitboxes: Vec::new(),
1044 deferred_draws: Vec::new(),
1045 input_handlers: Vec::new(),
1046 tooltip_requests: Vec::new(),
1047 cursor_styles: Vec::new(),
1048
1049 #[cfg(any(test, feature = "test-support"))]
1050 debug_bounds: FxHashMap::default(),
1051 #[cfg(any(test, feature = "test-support"))]
1052 debug_bounds_records: Vec::new(),
1053
1054 #[cfg(any(feature = "inspector", debug_assertions))]
1055 next_inspector_instance_ids: FxHashMap::default(),
1056
1057 #[cfg(any(feature = "inspector", debug_assertions))]
1058 inspector_hitboxes: FxHashMap::default(),
1059 tab_stops: TabStopMap::default(),
1060 }
1061 }
1062
1063 pub(crate) fn clear(&mut self) {
1064 self.element_states.clear();
1065 self.accessed_element_states.clear();
1066 self.mouse_listeners.clear();
1067 self.dispatch_tree.clear();
1068 self.scene.clear();
1069 self.input_handlers.clear();
1070 self.tooltip_requests.clear();
1071 self.cursor_styles.clear();
1072 self.hitboxes.clear();
1073 self.window_control_hitboxes.clear();
1074 self.deferred_draws.clear();
1075 self.tab_stops.clear();
1076 self.focus = None;
1077
1078 #[cfg(any(test, feature = "test-support"))]
1079 {
1080 self.debug_bounds.clear();
1081 self.debug_bounds_records.clear();
1082 }
1083
1084 #[cfg(any(feature = "inspector", debug_assertions))]
1085 {
1086 self.next_inspector_instance_ids.clear();
1087 self.inspector_hitboxes.clear();
1088 }
1089 }
1090
1091 pub(crate) fn cursor_style(&self, window: &Window) -> Option<CursorStyle> {
1092 self.cursor_styles
1093 .iter()
1094 .rev()
1095 .fold_while(None, |style, request| match request.hitbox_id {
1096 None => Done(Some(request.style)),
1097 Some(hitbox_id) => Continue(style.or_else(|| {
1098 hitbox_id
1099 .is_hovered_ignoring_last_input(window)
1100 .then_some(request.style)
1101 })),
1102 })
1103 .into_inner()
1104 }
1105
1106 pub(crate) fn hit_test(&self, position: Point<Pixels>) -> HitTest {
1107 let mut set_hover_hitbox_count = false;
1108 let mut hit_test = HitTest::default();
1109 for hitbox in self.hitboxes.iter().rev() {
1110 let bounds = hitbox.bounds.intersect(&hitbox.content_mask.bounds);
1111 if bounds.contains(&position) {
1112 hit_test.ids.push(hitbox.id);
1113 if !set_hover_hitbox_count
1114 && hitbox.behavior == HitboxBehavior::BlockMouseExceptScroll
1115 {
1116 hit_test.hover_hitbox_count = hit_test.ids.len();
1117 set_hover_hitbox_count = true;
1118 }
1119 if hitbox.behavior == HitboxBehavior::BlockMouse {
1120 break;
1121 }
1122 }
1123 }
1124 if !set_hover_hitbox_count {
1125 hit_test.hover_hitbox_count = hit_test.ids.len();
1126 }
1127 hit_test
1128 }
1129
1130 pub(crate) fn focus_path(&self) -> SmallVec<[FocusId; 8]> {
1131 self.focus
1132 .map(|focus_id| self.dispatch_tree.focus_path(focus_id))
1133 .unwrap_or_default()
1134 }
1135
1136 pub(crate) fn finish(&mut self, prev_frame: &mut Self) {
1137 for element_state_key in &self.accessed_element_states {
1138 if let Some((element_state_key, element_state)) =
1139 prev_frame.element_states.remove_entry(element_state_key)
1140 {
1141 self.element_states.insert(element_state_key, element_state);
1142 }
1143 }
1144
1145 self.scene.finish();
1146 }
1147}
1148
1149#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
1150enum InputModality {
1151 Mouse,
1152 Keyboard,
1153 Touch,
1154}
1155
1156pub struct Window {
1158 pub(crate) handle: AnyWindowHandle,
1159 pub(crate) invalidator: WindowInvalidator,
1160 pub(crate) removed: bool,
1161 pub(crate) platform_window: Box<dyn PlatformWindow>,
1162 display_id: Option<DisplayId>,
1163 is_resizable: bool,
1164 is_minimizable: bool,
1165 sprite_atlas: Arc<dyn PlatformAtlas>,
1166 text_system: Arc<WindowTextSystem>,
1167 text_rendering_mode: Rc<Cell<TextRenderingMode>>,
1168 rem_size: Pixels,
1169 rem_size_override_stack: SmallVec<[Pixels; 8]>,
1174 pub(crate) viewport_size: Size<Pixels>,
1175 layout_engine: Option<TaffyLayoutEngine>,
1176 pub(crate) root: Option<AnyView>,
1177 pub(crate) element_id_stack: SmallVec<[ElementId; 32]>,
1178 pub(crate) text_style_stack: Vec<TextStyleRefinement>,
1179 pub(crate) rendered_entity_stack: Vec<EntityId>,
1180 pub(crate) element_offset_stack: Vec<Point<Pixels>>,
1181 pub(crate) element_opacity: f32,
1182 pub(crate) content_mask_stack: Vec<ContentMask<Pixels>>,
1183 pub(crate) requested_autoscroll: Option<Bounds<Pixels>>,
1184 last_text_input_configuration: Option<TextInputConfiguration>,
1188 focused_text_input_active: bool,
1189 pub(crate) image_cache_stack: Vec<AnyImageCache>,
1190 pub(crate) rendered_frame: Frame,
1191 pub(crate) next_frame: Frame,
1192 next_hitbox_id: HitboxId,
1193 pub(crate) next_tooltip_id: TooltipId,
1194 pub(crate) tooltip_bounds: Option<TooltipBounds>,
1195 pub(crate) next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>>,
1196 pub(crate) dirty_views: FxHashSet<EntityId>,
1197 focus_listeners: SubscriberSet<(), AnyWindowFocusListener>,
1198 pub(crate) focus_lost_listeners: SubscriberSet<(), AnyObserver>,
1199 focus_lost_path: SmallVec<[FocusId; 8]>,
1200 default_prevented: bool,
1201 mouse_position: Point<Pixels>,
1202 mouse_hit_test: HitTest,
1203 modifiers: Modifiers,
1204 capslock: Capslock,
1205 scale_factor: f32,
1206 pub(crate) bounds_observers: SubscriberSet<(), AnyObserver>,
1207 appearance: WindowAppearance,
1208 pub(crate) appearance_observers: SubscriberSet<(), AnyObserver>,
1209 pub(crate) button_layout_observers: SubscriberSet<(), AnyObserver>,
1210 active: Rc<Cell<bool>>,
1211 visibility: WindowVisibility,
1212 pub(crate) visibility_observers:
1213 SubscriberSet<(), Box<dyn FnMut(WindowVisibility, &mut Window, &mut App) -> bool>>,
1214 hovered: Rc<Cell<bool>>,
1215 pub(crate) needs_present: Rc<Cell<bool>>,
1216 pub(crate) input_rate_tracker: Rc<RefCell<InputRateTracker>>,
1219 #[cfg(feature = "profiler")]
1220 window_profiler: profiler::WindowProfiler,
1221 last_input_modality: InputModality,
1222 touch_gestures: TouchGestureRecognizer,
1223 touch_prediction_enabled: bool,
1224 long_press_timer: Option<Task<()>>,
1225 long_press_capture: Option<EntityId>,
1226 pub(crate) refreshing: bool,
1227 pub(crate) activation_observers: SubscriberSet<(), AnyObserver>,
1228 pub(crate) focus: Option<FocusId>,
1229 focus_enabled: bool,
1230 pub(crate) focus_generation: u64,
1233 pending_input: Option<PendingInput>,
1234 pending_modifier: ModifierState,
1235 pub(crate) pending_input_observers: SubscriberSet<(), AnyObserver>,
1236 prompt: Option<RenderablePromptHandle>,
1237 pub(crate) client_inset: Option<Pixels>,
1238 captured_hitbox: Option<HitboxId>,
1241 #[cfg(any(feature = "inspector", debug_assertions))]
1242 inspector: Option<Entity<Inspector>>,
1243 #[cfg(feature = "profiler")]
1244 debug_frame_overlay: crate::debug_overlay::DebugFrameOverlay,
1245 pub(crate) a11y: A11y,
1246}
1247
1248#[derive(Clone, Debug, Default)]
1249struct ModifierState {
1250 modifiers: Modifiers,
1251 saw_other_input: bool,
1252}
1253
1254#[derive(Clone, Debug)]
1257pub(crate) struct InputRateTracker {
1258 timestamps: Vec<Instant>,
1259 window: Duration,
1260 inputs_per_second: u32,
1261 sustain_until: Instant,
1262 sustain_duration: Duration,
1263}
1264
1265impl Default for InputRateTracker {
1266 fn default() -> Self {
1267 Self {
1268 timestamps: Vec::new(),
1269 window: Duration::from_millis(100),
1270 inputs_per_second: 60,
1271 sustain_until: Instant::now(),
1272 sustain_duration: Duration::from_secs(1),
1273 }
1274 }
1275}
1276
1277impl InputRateTracker {
1278 pub fn record_input(&mut self) {
1279 let now = Instant::now();
1280 self.timestamps.push(now);
1281 self.prune_old_timestamps(now);
1282
1283 let min_events = self.inputs_per_second as u128 * self.window.as_millis() / 1000;
1284 if self.timestamps.len() as u128 >= min_events {
1285 self.sustain_until = now + self.sustain_duration;
1286 }
1287 }
1288
1289 pub fn is_high_rate(&self) -> bool {
1290 Instant::now() < self.sustain_until
1291 }
1292
1293 fn prune_old_timestamps(&mut self, now: Instant) {
1294 self.timestamps
1295 .retain(|&t| now.duration_since(t) <= self.window);
1296 }
1297}
1298
1299#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1300pub(crate) enum DrawPhase {
1301 None,
1302 Prepaint,
1303 Paint,
1304 Focus,
1305}
1306
1307pub(crate) const PENDING_INPUT_TIMEOUT: Duration = Duration::from_secs(1);
1308
1309pub struct PendingInputStatus<'a> {
1311 keystrokes: &'a [Keystroke],
1312 timeout: Option<PendingInputTimeoutStatus>,
1313}
1314
1315impl<'a> PendingInputStatus<'a> {
1316 pub fn keystrokes(&self) -> &'a [Keystroke] {
1318 self.keystrokes
1319 }
1320
1321 pub fn timeout(&self) -> Option<PendingInputTimeoutStatus> {
1323 self.timeout
1324 }
1325}
1326
1327#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1329pub struct PendingInputTimeoutStatus {
1330 duration: Duration,
1331 remaining: Duration,
1332 started_at: Option<Instant>,
1333 paused: bool,
1334}
1335
1336impl PendingInputTimeoutStatus {
1337 pub fn duration(&self) -> Duration {
1339 self.duration
1340 }
1341
1342 pub fn remaining(&self, cx: &App) -> Duration {
1344 self.started_at
1345 .map(|started_at| {
1346 self.remaining
1347 .saturating_sub(cx.background_executor().now() - started_at)
1348 })
1349 .unwrap_or(self.remaining)
1350 }
1351
1352 pub fn is_paused(&self) -> bool {
1354 self.paused
1355 }
1356}
1357
1358#[derive(Debug)]
1359struct PendingInputTimeout {
1360 duration: Duration,
1361 remaining: Duration,
1362 state: PendingInputTimeoutState,
1363}
1364
1365#[derive(Debug)]
1366enum PendingInputTimeoutState {
1367 Running { started_at: Instant, task: Task<()> },
1368 Paused { pause: PendingInputTimeoutPause },
1369}
1370
1371#[derive(Debug)]
1372struct PendingInputTimeoutPause {
1373 owner_id: EntityId,
1374 _release_subscription: Subscription,
1375}
1376
1377impl PendingInputTimeout {
1378 fn is_paused(&self) -> bool {
1379 matches!(&self.state, PendingInputTimeoutState::Paused { .. })
1380 }
1381
1382 fn pause(&mut self, pause: PendingInputTimeoutPause, now: Instant) -> bool {
1383 match std::mem::replace(&mut self.state, PendingInputTimeoutState::Paused { pause }) {
1384 PendingInputTimeoutState::Running { started_at, task } => {
1385 self.remaining = self.remaining.saturating_sub(now - started_at);
1386 drop(task);
1387 true
1388 }
1389 previous_state @ PendingInputTimeoutState::Paused { .. } => {
1390 self.state = previous_state;
1391 false
1392 }
1393 }
1394 }
1395
1396 fn pause_owner_id(&self) -> Option<EntityId> {
1397 match &self.state {
1398 PendingInputTimeoutState::Running { .. } => None,
1399 PendingInputTimeoutState::Paused { pause } => Some(pause.owner_id),
1400 }
1401 }
1402
1403 fn resume(&mut self, owner_id: EntityId, started_at: Instant, task: Task<()>) -> bool {
1404 match std::mem::replace(
1405 &mut self.state,
1406 PendingInputTimeoutState::Running { started_at, task },
1407 ) {
1408 PendingInputTimeoutState::Paused { pause } if pause.owner_id == owner_id => true,
1409 previous_state => {
1410 self.state = previous_state;
1411 false
1412 }
1413 }
1414 }
1415
1416 fn reset_duration(&mut self, duration: Duration) {
1417 self.duration = duration;
1418 self.remaining = duration;
1419 }
1420
1421 fn status(&self) -> PendingInputTimeoutStatus {
1422 let (started_at, paused) = match &self.state {
1423 PendingInputTimeoutState::Running { started_at, .. } => (Some(*started_at), false),
1424 PendingInputTimeoutState::Paused { .. } => (None, true),
1425 };
1426 PendingInputTimeoutStatus {
1427 duration: self.duration,
1428 remaining: self.remaining,
1429 started_at,
1430 paused,
1431 }
1432 }
1433}
1434
1435#[derive(Default, Debug)]
1436struct PendingInput {
1437 keystrokes: SmallVec<[Keystroke; 1]>,
1438 focus: Option<FocusId>,
1439 timeout: Option<PendingInputTimeout>,
1440}
1441
1442pub(crate) struct ElementStateBox {
1443 pub(crate) inner: Box<dyn Any>,
1444 #[cfg(debug_assertions)]
1445 pub(crate) type_name: &'static str,
1446}
1447
1448fn default_bounds(display_id: Option<DisplayId>, cx: &mut App) -> WindowBounds {
1449 let active_window_bounds = cx
1454 .active_window()
1455 .and_then(|w| w.update(cx, |_, window, _| window.window_bounds()).ok());
1456
1457 const CASCADE_OFFSET: f32 = 25.0;
1458
1459 let display = display_id
1460 .map(|id| cx.find_display(id))
1461 .unwrap_or_else(|| cx.primary_display());
1462
1463 let default_placement = || Bounds::new(point(px(0.), px(0.)), DEFAULT_WINDOW_SIZE);
1464
1465 let display_bounds = display
1467 .as_ref()
1468 .map(|d| d.visible_bounds())
1469 .unwrap_or_else(default_placement);
1470
1471 let (
1472 Bounds {
1473 origin: base_origin,
1474 size: base_size,
1475 },
1476 window_bounds_ctor,
1477 ): (_, fn(Bounds<Pixels>) -> WindowBounds) = match active_window_bounds {
1478 Some(bounds) => match bounds {
1479 WindowBounds::Windowed(bounds) => (bounds, WindowBounds::Windowed),
1480 WindowBounds::Maximized(bounds) => (bounds, WindowBounds::Maximized),
1481 WindowBounds::Fullscreen(bounds) => (bounds, WindowBounds::Fullscreen),
1482 },
1483 None => (
1484 display
1485 .as_ref()
1486 .map(|d| d.default_bounds())
1487 .unwrap_or_else(default_placement),
1488 WindowBounds::Windowed,
1489 ),
1490 };
1491
1492 let cascade_offset = point(px(CASCADE_OFFSET), px(CASCADE_OFFSET));
1493 let proposed_origin = base_origin + cascade_offset;
1494 let proposed_bounds = Bounds::new(proposed_origin, base_size);
1495
1496 let display_right = display_bounds.origin.x + display_bounds.size.width;
1497 let display_bottom = display_bounds.origin.y + display_bounds.size.height;
1498 let window_right = proposed_bounds.origin.x + proposed_bounds.size.width;
1499 let window_bottom = proposed_bounds.origin.y + proposed_bounds.size.height;
1500
1501 let fits_horizontally = window_right <= display_right;
1502 let fits_vertically = window_bottom <= display_bottom;
1503
1504 let final_origin = match (fits_horizontally, fits_vertically) {
1505 (true, true) => proposed_origin,
1506 (false, true) => point(display_bounds.origin.x, base_origin.y),
1507 (true, false) => point(base_origin.x, display_bounds.origin.y),
1508 (false, false) => display_bounds.origin,
1509 };
1510 window_bounds_ctor(Bounds::new(final_origin, base_size))
1511}
1512
1513impl Window {
1514 pub(crate) fn new(
1515 handle: AnyWindowHandle,
1516 options: WindowOptions,
1517 cx: &mut App,
1518 ) -> Result<Self> {
1519 let WindowOptions {
1520 window_bounds,
1521 titlebar,
1522 focus,
1523 show,
1524 kind,
1525 is_movable,
1526 app_owns_titlebar_drag,
1527 inactive_frame_interval,
1528 is_resizable,
1529 is_minimizable,
1530 display_id,
1531 window_background,
1532 app_id,
1533 window_min_size,
1534 window_decorations,
1535 #[cfg_attr(
1536 not(any(target_os = "linux", target_os = "freebsd")),
1537 allow(unused_variables)
1538 )]
1539 icon,
1540 #[cfg_attr(not(target_os = "macos"), allow(unused_variables))]
1541 tabbing_identifier,
1542 } = options;
1543
1544 let initial_window_title = titlebar
1545 .as_ref()
1546 .and_then(|titlebar| titlebar.title.clone());
1547
1548 let window_bounds = window_bounds.unwrap_or_else(|| default_bounds(display_id, cx));
1549 let mut platform_window = cx.platform.open_window(
1550 handle,
1551 WindowParams {
1552 bounds: window_bounds.get_bounds(),
1553 titlebar,
1554 kind,
1555 is_movable,
1556 app_owns_titlebar_drag,
1557 is_resizable,
1558 is_minimizable,
1559 focus,
1560 show,
1561 display_id,
1562 window_min_size,
1563 app_id: app_id.clone(),
1564 icon,
1565 #[cfg(target_os = "macos")]
1566 tabbing_identifier,
1567 },
1568 )?;
1569
1570 let tab_bar_visible = platform_window.tab_bar_visible();
1571 SystemWindowTabController::init_visible(cx, tab_bar_visible);
1572 if let Some(tabs) = platform_window.tabbed_windows() {
1573 SystemWindowTabController::add_tab(cx, handle.window_id(), tabs);
1574 }
1575
1576 let display_id = platform_window.display().map(|display| display.id());
1577 let sprite_atlas = platform_window.sprite_atlas();
1578 let mouse_position = platform_window.mouse_position();
1579 let modifiers = platform_window.modifiers();
1580 let capslock = platform_window.capslock();
1581 let content_size = platform_window.content_size();
1582 let scale_factor = platform_window.scale_factor();
1583 let appearance = platform_window.appearance();
1584 let text_system = Arc::new(WindowTextSystem::new(cx.text_system().clone()));
1585 let invalidator = WindowInvalidator::new(handle.window_id());
1586 let active = Rc::new(Cell::new(platform_window.is_active()));
1587 let visibility = platform_window.visibility();
1588 #[cfg(feature = "profiler")]
1589 profiler::journal::record_window_visibility(handle.window_id(), visibility);
1590 let hovered = Rc::new(Cell::new(platform_window.is_hovered()));
1591 let needs_present = Rc::new(Cell::new(false));
1592 let next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>> = Default::default();
1593 let input_rate_tracker = Rc::new(RefCell::new(InputRateTracker::default()));
1594 let last_frame_time = Rc::new(Cell::new(None));
1595
1596 platform_window
1597 .request_decorations(window_decorations.unwrap_or(WindowDecorations::Server));
1598 platform_window.set_background_appearance(window_background);
1599
1600 match window_bounds {
1601 WindowBounds::Fullscreen(_) => platform_window.toggle_fullscreen(),
1602 WindowBounds::Maximized(_) => platform_window.zoom(),
1603 WindowBounds::Windowed(_) => {}
1604 }
1605
1606 let accessibility_force_disabled = cx.accessibility_force_disabled;
1607 let a11y_active_flag = Arc::new(AtomicBool::new(false));
1608
1609 #[cfg(not(target_family = "wasm"))]
1610 if !accessibility_force_disabled {
1611 let mut initial_root_node = accesskit::Node::new(accesskit::Role::Window);
1612 if let Some(title) = &initial_window_title {
1613 initial_root_node.set_label(title.to_string());
1614 }
1615 let initial_tree = accesskit::TreeUpdate {
1616 nodes: vec![(ROOT_NODE_ID, initial_root_node)],
1617 tree: Some(accesskit::Tree::new(ROOT_NODE_ID)),
1618 tree_id: accesskit::TreeId::ROOT,
1619 focus: ROOT_NODE_ID,
1620 };
1621 let (activation_sender, activation_receiver) = async_channel::unbounded::<()>();
1622 let (deactivation_sender, deactivation_receiver) = async_channel::unbounded::<()>();
1623 let (action_sender, action_receiver) =
1624 async_channel::unbounded::<accesskit::ActionRequest>();
1625
1626 platform_window.a11y_init(crate::A11yCallbacks {
1627 activation: {
1628 let active_flag = a11y_active_flag.clone();
1629 Box::new(move || {
1630 log::info!("Accessibility activated");
1631 active_flag.store(true, SeqCst);
1632 activation_sender.send_blocking(()).log_err();
1633 Some(initial_tree.clone())
1634 })
1635 },
1636 action: Box::new(move |request| {
1637 action_sender.send_blocking(request).log_err();
1638 }),
1639 deactivation: {
1640 let active_flag = a11y_active_flag.clone();
1641 Box::new(move || {
1642 log::info!("Accessibility deactivated");
1643 active_flag.store(false, SeqCst);
1644 deactivation_sender.send_blocking(()).log_err();
1645 })
1646 },
1647 });
1648
1649 let mut async_cx = cx.to_async();
1655 cx.foreground_executor()
1656 .spawn(async move {
1657 while activation_receiver.recv().await.is_ok() {
1658 handle
1659 .update(&mut async_cx, |_, window, _| window.refresh())
1660 .log_err();
1661 }
1662 })
1663 .detach();
1664
1665 let mut async_cx = cx.to_async();
1666 cx.foreground_executor()
1667 .spawn(async move {
1668 while deactivation_receiver.recv().await.is_ok() {
1669 handle
1670 .update(&mut async_cx, |_, window, _| window.refresh())
1671 .log_err();
1672 }
1673 })
1674 .detach();
1675
1676 let mut async_cx = cx.to_async();
1677 cx.foreground_executor()
1678 .spawn(async move {
1679 while let Ok(request) = action_receiver.recv().await {
1680 handle
1681 .update(&mut async_cx, |_, window, cx| {
1682 window.handle_a11y_action(request, cx);
1683 })
1684 .log_err();
1685 }
1686 })
1687 .detach();
1688 }
1689
1690 platform_window.on_close(Box::new({
1691 let window_id = handle.window_id();
1692 let mut cx = cx.to_async();
1693 move || {
1694 let _ = handle.update(&mut cx, |_, window, _| window.remove_window());
1695 let _ = cx.update(|cx| {
1696 SystemWindowTabController::remove_tab(cx, window_id);
1697 });
1698 }
1699 }));
1700 platform_window.on_request_frame(Box::new({
1701 let mut cx = cx.to_async();
1702 let invalidator = invalidator.clone();
1703 let active = active.clone();
1704 let needs_present = needs_present.clone();
1705 let next_frame_callbacks = next_frame_callbacks.clone();
1706 let input_rate_tracker = input_rate_tracker.clone();
1707 let mut deferred_force_render = false;
1708 move |request_frame_options| {
1709 #[cfg(feature = "profiler")]
1710 let _foreground_turn = profiler::journal::foreground_turn();
1711 if draw_in_progress() {
1727 log::debug!("deferring re-entrant window draw request");
1728 deferred_force_render |= request_frame_options.force_render;
1729 return;
1730 }
1731 let force_render =
1735 mem::take(&mut deferred_force_render) || request_frame_options.force_render;
1736
1737 let thermal_state = handle
1738 .update(&mut cx, |_, _, cx| cx.thermal_state())
1739 .log_err();
1740
1741 let min_frame_interval = if request_frame_options.require_presentation
1745 || (!request_frame_options.force_render
1746 && next_frame_callbacks.borrow().is_empty())
1747 {
1748 None
1749 } else if !active.get() && !input_rate_tracker.borrow_mut().is_high_rate() {
1750 inactive_frame_interval
1751 } else if let Some(ThermalState::Critical | ThermalState::Serious) = thermal_state {
1752 Some(Duration::from_micros(16667))
1753 } else {
1754 None
1755 };
1756
1757 let now = Instant::now();
1758 if let Some(min_interval) = min_frame_interval {
1759 if let Some(last_frame) = last_frame_time.get()
1760 && now.duration_since(last_frame) < min_interval
1761 {
1762 deferred_force_render |= force_render;
1764 handle
1766 .update(&mut cx, |_, window, _| {
1767 window.platform_window.schedule_frame();
1768 })
1769 .log_err();
1770 invalidator.wake_platform();
1775 return;
1776 }
1777 }
1778 last_frame_time.set(Some(now));
1779
1780 let pending_next_frame_callbacks = next_frame_callbacks.take();
1781 if !pending_next_frame_callbacks.is_empty() {
1782 handle
1783 .update(&mut cx, |_, window, cx| {
1784 for callback in pending_next_frame_callbacks {
1785 callback(window, cx);
1786 }
1787 })
1788 .log_err();
1789 }
1790
1791 let needs_present = request_frame_options.require_presentation
1795 || needs_present.get()
1796 || input_rate_tracker.borrow_mut().is_high_rate();
1797
1798 if invalidator.is_dirty() || force_render {
1799 measure("frame duration", || {
1800 handle
1801 .update(&mut cx, |_, window, cx| {
1802 if force_render {
1803 window.refresh();
1806 }
1807 let arena_clear_needed = window.draw(cx);
1808 window.present();
1809 arena_clear_needed.clear(cx);
1810 })
1811 .log_err();
1812 })
1813 } else if needs_present {
1814 handle
1815 .update(&mut cx, |_, window, _| window.present())
1816 .log_err();
1817 }
1818
1819 handle
1820 .update(&mut cx, |_, window, _| {
1821 if window.invalidator.is_dirty()
1822 || !window.next_frame_callbacks.borrow().is_empty()
1823 {
1824 window.platform_window.schedule_frame();
1825 }
1826 })
1827 .log_err();
1828
1829 if invalidator.is_dirty() || !next_frame_callbacks.borrow().is_empty() {
1835 invalidator.wake_platform();
1836 }
1837 }
1838 }));
1839 invalidator.set_platform_waker(platform_window.frame_waker());
1840 platform_window.on_visual_viewport_changed(Box::new({
1841 let mut cx = cx.to_async();
1842 move || {
1843 handle
1844 .update(&mut cx, |_, window, _| window.refresh())
1845 .log_err();
1846 }
1847 }));
1848 platform_window.on_insets_changed(Box::new({
1849 let mut cx = cx.to_async();
1850 move |_| {
1851 handle
1852 .update(&mut cx, |_, window, _| window.refresh())
1853 .log_err();
1854 }
1855 }));
1856 platform_window.on_resize(Box::new({
1857 let mut cx = cx.to_async();
1858 move |_, _| {
1859 handle
1860 .update(&mut cx, |_, window, cx| window.bounds_changed(cx))
1861 .log_err();
1862 }
1863 }));
1864 platform_window.on_moved(Box::new({
1865 let mut cx = cx.to_async();
1866 move || {
1867 handle
1868 .update(&mut cx, |_, window, cx| window.bounds_changed(cx))
1869 .log_err();
1870 }
1871 }));
1872 platform_window.on_appearance_changed(Box::new({
1873 let cx = cx.to_async();
1874 let foreground_executor = cx.foreground_executor().clone();
1875 move || {
1876 let mut cx = cx.clone();
1877 foreground_executor
1880 .spawn(async move {
1881 handle
1882 .update(&mut cx, |_, window, cx| window.appearance_changed(cx))
1883 .log_err();
1884 })
1885 .detach();
1886 }
1887 }));
1888 platform_window.on_button_layout_changed(Box::new({
1889 let mut cx = cx.to_async();
1890 move || {
1891 handle
1892 .update(&mut cx, |_, window, cx| window.button_layout_changed(cx))
1893 .log_err();
1894 }
1895 }));
1896 platform_window.on_active_status_change(Box::new({
1897 let mut cx = cx.to_async();
1898 move |active| {
1899 handle
1900 .update(&mut cx, |_, window, cx| {
1901 window.active.set(active);
1902 window.modifiers = window.platform_window.modifiers();
1903 window.capslock = window.platform_window.capslock();
1904 window
1905 .activation_observers
1906 .clone()
1907 .retain(&(), |callback| callback(window, cx));
1908
1909 window.bounds_changed(cx);
1910 window.refresh();
1911
1912 SystemWindowTabController::update_last_active(cx, window.handle.id);
1913 })
1914 .log_err();
1915 }
1916 }));
1917 platform_window.on_visibility_change(Box::new({
1918 let mut cx = cx.to_async();
1919 move |_| {
1920 handle
1921 .update(&mut cx, |_, window, cx| {
1922 window.refresh_visibility(cx);
1923 })
1924 .log_err();
1925 }
1926 }));
1927 platform_window.on_hover_status_change(Box::new({
1928 let mut cx = cx.to_async();
1929 move |active| {
1930 handle
1931 .update(&mut cx, |_, window, _| {
1932 window.hovered.set(active);
1933 window.refresh();
1934 })
1935 .log_err();
1936 }
1937 }));
1938 platform_window.on_input({
1939 let mut cx = cx.to_async();
1940 Box::new(move |event| {
1941 handle
1942 .update(&mut cx, |_, window, cx| window.dispatch_event(event, cx))
1943 .log_err()
1944 .unwrap_or(DispatchEventResult::default())
1945 })
1946 });
1947 platform_window.on_hit_test_window_control({
1948 let mut cx = cx.to_async();
1949 Box::new(move || {
1950 handle
1951 .update(&mut cx, |_, window, _cx| {
1952 for (area, hitbox) in &window.rendered_frame.window_control_hitboxes {
1953 if window.mouse_hit_test.ids.contains(&hitbox.id) {
1954 return Some(*area);
1955 }
1956 }
1957 None
1958 })
1959 .log_err()
1960 .unwrap_or(None)
1961 })
1962 });
1963 platform_window.on_move_tab_to_new_window({
1964 let mut cx = cx.to_async();
1965 Box::new(move || {
1966 handle
1967 .update(&mut cx, |_, _window, cx| {
1968 SystemWindowTabController::move_tab_to_new_window(cx, handle.window_id());
1969 })
1970 .log_err();
1971 })
1972 });
1973 platform_window.on_merge_all_windows({
1974 let mut cx = cx.to_async();
1975 Box::new(move || {
1976 handle
1977 .update(&mut cx, |_, _window, cx| {
1978 SystemWindowTabController::merge_all_windows(cx, handle.window_id());
1979 })
1980 .log_err();
1981 })
1982 });
1983 platform_window.on_select_next_tab({
1984 let mut cx = cx.to_async();
1985 Box::new(move || {
1986 handle
1987 .update(&mut cx, |_, _window, cx| {
1988 SystemWindowTabController::select_next_tab(cx, handle.window_id());
1989 })
1990 .log_err();
1991 })
1992 });
1993 platform_window.on_select_previous_tab({
1994 let mut cx = cx.to_async();
1995 Box::new(move || {
1996 handle
1997 .update(&mut cx, |_, _window, cx| {
1998 SystemWindowTabController::select_previous_tab(cx, handle.window_id())
1999 })
2000 .log_err();
2001 })
2002 });
2003 platform_window.on_toggle_tab_bar({
2004 let mut cx = cx.to_async();
2005 Box::new(move || {
2006 handle
2007 .update(&mut cx, |_, window, cx| {
2008 let tab_bar_visible = window.platform_window.tab_bar_visible();
2009 SystemWindowTabController::set_visible(cx, tab_bar_visible);
2010 })
2011 .log_err();
2012 })
2013 });
2014
2015 if let Some(app_id) = app_id {
2016 platform_window.set_app_id(&app_id);
2017 }
2018
2019 platform_window.map_window().unwrap();
2020
2021 Ok(Window {
2022 handle,
2023 invalidator,
2024 removed: false,
2025 platform_window,
2026 display_id,
2027 is_resizable,
2028 is_minimizable,
2029 sprite_atlas,
2030 text_system,
2031 text_rendering_mode: cx.text_rendering_mode.clone(),
2032 rem_size: px(16.),
2033 rem_size_override_stack: SmallVec::new(),
2034 viewport_size: content_size,
2035 layout_engine: Some(TaffyLayoutEngine::new()),
2036 root: None,
2037 element_id_stack: SmallVec::default(),
2038 text_style_stack: Vec::new(),
2039 rendered_entity_stack: Vec::new(),
2040 element_offset_stack: Vec::new(),
2041 content_mask_stack: Vec::new(),
2042 element_opacity: 1.0,
2043 requested_autoscroll: None,
2044 last_text_input_configuration: None,
2045 focused_text_input_active: false,
2046 rendered_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
2047 next_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
2048 next_frame_callbacks,
2049 next_hitbox_id: HitboxId(0),
2050 next_tooltip_id: TooltipId::default(),
2051 tooltip_bounds: None,
2052 dirty_views: FxHashSet::default(),
2053 focus_listeners: SubscriberSet::new(),
2054 focus_lost_listeners: SubscriberSet::new(),
2055 focus_lost_path: SmallVec::new(),
2056 default_prevented: true,
2057 mouse_position,
2058 mouse_hit_test: HitTest::default(),
2059 modifiers,
2060 capslock,
2061 scale_factor,
2062 bounds_observers: SubscriberSet::new(),
2063 appearance,
2064 appearance_observers: SubscriberSet::new(),
2065 button_layout_observers: SubscriberSet::new(),
2066 active,
2067 visibility,
2068 visibility_observers: SubscriberSet::new(),
2069 hovered,
2070 needs_present,
2071 input_rate_tracker,
2072 #[cfg(feature = "profiler")]
2073 window_profiler: profiler::WindowProfiler::new(handle.window_id())?,
2074 last_input_modality: InputModality::Mouse,
2075 touch_gestures: TouchGestureRecognizer::new(
2076 cx.platform
2077 .gestures()
2078 .map_or_else(GestureTuning::default, |gestures| gestures.tuning()),
2079 ),
2080 touch_prediction_enabled: true,
2081 long_press_timer: None,
2082 long_press_capture: None,
2083 refreshing: false,
2084 activation_observers: SubscriberSet::new(),
2085 focus: None,
2086 focus_enabled: true,
2087 focus_generation: 0,
2088 pending_input: None,
2089 pending_modifier: ModifierState::default(),
2090 pending_input_observers: SubscriberSet::new(),
2091 prompt: None,
2092 client_inset: None,
2093 image_cache_stack: Vec::new(),
2094 captured_hitbox: None,
2095 #[cfg(any(feature = "inspector", debug_assertions))]
2096 inspector: None,
2097 #[cfg(feature = "profiler")]
2098 debug_frame_overlay: crate::debug_overlay::DebugFrameOverlay::new(),
2099 a11y: A11y::new(
2100 a11y_active_flag,
2101 accessibility_force_disabled,
2102 initial_window_title,
2103 ),
2104 })
2105 }
2106
2107 pub(crate) fn new_focus_listener(
2108 &self,
2109 value: AnyWindowFocusListener,
2110 ) -> (Subscription, impl FnOnce() + use<>) {
2111 self.focus_listeners.insert((), value)
2112 }
2113}
2114
2115#[derive(Clone, Debug, Default, PartialEq, Eq)]
2116#[expect(missing_docs)]
2117pub struct DispatchEventResult {
2118 pub propagate: bool,
2119 pub default_prevented: bool,
2120}
2121
2122#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
2126#[repr(C)]
2127pub struct ContentMask<P: Clone + Debug + Default + PartialEq> {
2128 pub bounds: Bounds<P>,
2130}
2131
2132impl ContentMask<Pixels> {
2133 pub fn scale(&self, factor: f32) -> ContentMask<ScaledPixels> {
2135 ContentMask {
2136 bounds: self.bounds.scale(factor),
2137 }
2138 }
2139
2140 pub fn intersect(&self, other: &Self) -> Self {
2142 let bounds = self.bounds.intersect(&other.bounds);
2143 ContentMask { bounds }
2144 }
2145}
2146
2147impl Window {
2148 fn mark_view_dirty(&mut self, view_id: EntityId) {
2149 for view_id in self
2152 .rendered_frame
2153 .dispatch_tree
2154 .view_path_reversed(view_id)
2155 {
2156 if !self.dirty_views.insert(view_id) {
2157 break;
2158 }
2159 }
2160 }
2161
2162 pub(crate) fn refresh_visibility(&mut self, cx: &mut App) {
2163 let visibility = self.platform_window.visibility();
2164 if self.visibility != visibility {
2165 self.visibility = visibility;
2166 #[cfg(feature = "profiler")]
2167 profiler::journal::record_window_visibility(self.handle.window_id(), visibility);
2168 self.visibility_observers
2169 .clone()
2170 .retain(&(), |callback| callback(visibility, self, cx));
2171 }
2172 #[cfg(feature = "profiler")]
2173 if self.invalidator.is_dirty() || self.needs_present.get() {
2174 profiler::journal::record_frame_pending(self.handle.window_id(), Instant::now());
2175 }
2176 }
2177
2178 pub fn visibility(&self) -> WindowVisibility {
2181 self.visibility
2182 }
2183
2184 pub fn is_visible(&self) -> bool {
2190 self.visibility.is_visible()
2191 }
2192
2193 pub fn observe_window_visibility(
2195 &self,
2196 mut callback: impl FnMut(WindowVisibility, &mut Window, &mut App) + 'static,
2197 ) -> Subscription {
2198 let (subscription, activate) = self.visibility_observers.insert(
2199 (),
2200 Box::new(move |visibility, window, cx| {
2201 callback(visibility, window, cx);
2202 true
2203 }),
2204 );
2205 activate();
2206 subscription
2207 }
2208
2209 pub fn observe_window_appearance(
2211 &self,
2212 mut callback: impl FnMut(&mut Window, &mut App) + 'static,
2213 ) -> Subscription {
2214 let (subscription, activate) = self.appearance_observers.insert(
2215 (),
2216 Box::new(move |window, cx| {
2217 callback(window, cx);
2218 true
2219 }),
2220 );
2221 activate();
2222 subscription
2223 }
2224
2225 pub fn observe_button_layout_changed(
2227 &self,
2228 mut callback: impl FnMut(&mut Window, &mut App) + 'static,
2229 ) -> Subscription {
2230 let (subscription, activate) = self.button_layout_observers.insert(
2231 (),
2232 Box::new(move |window, cx| {
2233 callback(window, cx);
2234 true
2235 }),
2236 );
2237 activate();
2238 subscription
2239 }
2240
2241 pub fn replace_root<E>(
2243 &mut self,
2244 cx: &mut App,
2245 build_view: impl FnOnce(&mut Window, &mut Context<E>) -> E,
2246 ) -> Entity<E>
2247 where
2248 E: 'static + Render,
2249 {
2250 let view = cx.new(|cx| build_view(self, cx));
2251 self.root = Some(view.clone().into());
2252 self.refresh();
2253 view
2254 }
2255
2256 pub fn root<E>(&self) -> Option<Option<Entity<E>>>
2258 where
2259 E: 'static + Render,
2260 {
2261 self.root
2262 .as_ref()
2263 .map(|view| view.clone().downcast::<E>().ok())
2264 }
2265
2266 pub fn window_handle(&self) -> AnyWindowHandle {
2268 self.handle
2269 }
2270
2271 pub fn refresh(&mut self) {
2273 if self.invalidator.not_drawing() {
2274 self.refreshing = true;
2275 self.invalidator.set_dirty(true);
2276 }
2277 }
2278
2279 pub fn remove_window(&mut self) {
2281 self.removed = true;
2282 }
2283
2284 pub fn focused(&self, cx: &App) -> Option<FocusHandle> {
2286 self.focus
2287 .and_then(|id| FocusHandle::for_id(id, &cx.focus_handles))
2288 }
2289
2290 pub fn focus_lost_restore_target(&self, cx: &App) -> Option<FocusHandle> {
2294 let (_leaf, ancestors) = self.focus_lost_path.split_last()?;
2295 ancestors.iter().rev().find_map(|id| {
2296 self.rendered_frame.dispatch_tree.focusable_node_id(*id)?;
2297 FocusHandle::for_id(*id, &cx.focus_handles)
2298 })
2299 }
2300
2301 pub fn focus(&mut self, handle: &FocusHandle, cx: &mut App) {
2303 if !self.focus_enabled || self.focus == Some(handle.id) {
2304 return;
2305 }
2306
2307 self.focus = Some(handle.id);
2308 self.focus_generation = self.focus_generation.wrapping_add(1);
2309 self.clear_pending_keystrokes(cx);
2310
2311 self.refresh();
2312 }
2313
2314 pub fn blur(&mut self, cx: &mut App) {
2316 self.clear_pending_keystrokes(cx);
2317
2318 if !self.focus_enabled {
2319 return;
2320 }
2321
2322 if self.focus.is_some() {
2323 self.focus_generation = self.focus_generation.wrapping_add(1);
2324 }
2325 self.focus = None;
2326 self.refresh();
2327 }
2328
2329 pub fn disable_focus(&mut self, cx: &mut App) {
2331 self.blur(cx);
2332 self.focus_enabled = false;
2333 }
2334
2335 pub fn focus_next(&mut self, cx: &mut App) {
2337 if !self.focus_enabled {
2338 return;
2339 }
2340
2341 if let Some(handle) = self.rendered_frame.tab_stops.next(self.focus.as_ref()) {
2342 self.focus(&handle, cx)
2343 }
2344 }
2345
2346 pub fn focus_prev(&mut self, cx: &mut App) {
2348 if !self.focus_enabled {
2349 return;
2350 }
2351
2352 if let Some(handle) = self.rendered_frame.tab_stops.prev(self.focus.as_ref()) {
2353 self.focus(&handle, cx)
2354 }
2355 }
2356
2357 pub fn text_system(&self) -> &Arc<WindowTextSystem> {
2359 &self.text_system
2360 }
2361
2362 pub fn text_style(&self) -> TextStyle {
2364 let mut style = TextStyle::default();
2365 for refinement in &self.text_style_stack {
2366 style.refine(refinement);
2367 }
2368 style
2369 }
2370
2371 pub fn is_maximized(&self) -> bool {
2375 self.platform_window.is_maximized()
2376 }
2377
2378 pub fn request_decorations(&self, decorations: WindowDecorations) {
2380 self.platform_window.request_decorations(decorations);
2381 }
2382
2383 pub fn set_exclusive_zone(&self, zone: Pixels) {
2389 self.platform_window.set_exclusive_zone(zone);
2390 }
2391
2392 #[cfg(all(target_os = "linux", feature = "wayland"))]
2397 pub fn set_exclusive_edge(&self, edge: crate::layer_shell::Anchor) {
2398 self.platform_window.set_exclusive_edge(edge);
2399 }
2400
2401 pub fn start_window_resize(&self, edge: ResizeEdge) {
2403 if self.is_resizable {
2404 self.platform_window.start_window_resize(edge);
2405 }
2406 }
2407
2408 pub fn set_input_region(&self, region: Option<&[Bounds<Pixels>]>) {
2415 self.platform_window.set_input_region(region);
2416 }
2417
2418 pub fn window_bounds(&self) -> WindowBounds {
2421 self.platform_window.window_bounds()
2422 }
2423
2424 pub fn inner_window_bounds(&self) -> WindowBounds {
2426 self.platform_window.inner_window_bounds()
2427 }
2428
2429 pub fn native_window_state(&self) -> Option<Vec<u8>> {
2432 self.platform_window.native_window_state()
2433 }
2434
2435 pub fn restore_native_window_state(&self, state: &[u8]) {
2438 self.platform_window.restore_native_window_state(state);
2439 }
2440
2441 pub fn dispatch_action(&mut self, action: Box<dyn Action>, cx: &mut App) {
2443 let focus_id = self.focused(cx).map(|handle| handle.id);
2444
2445 let window = self.handle;
2446 cx.defer(move |cx| {
2447 window
2448 .update(cx, |_, window, cx| {
2449 let node_id = window.focus_node_id_in_rendered_frame(focus_id);
2450 window.dispatch_action_on_node(node_id, action.as_ref(), cx);
2451 })
2452 .log_err();
2453 })
2454 }
2455
2456 pub(crate) fn dispatch_keystroke_observers(
2457 &mut self,
2458 event: &dyn Any,
2459 action: Option<Box<dyn Action>>,
2460 context_stack: Vec<KeyContext>,
2461 cx: &mut App,
2462 ) {
2463 let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() else {
2464 return;
2465 };
2466
2467 cx.keystroke_observers.clone().retain(&(), move |callback| {
2468 (callback)(
2469 &KeystrokeEvent {
2470 keystroke: key_down_event.keystroke.clone(),
2471 action: action.as_ref().map(|action| action.boxed_clone()),
2472 context_stack: context_stack.clone(),
2473 },
2474 self,
2475 cx,
2476 )
2477 });
2478 }
2479
2480 pub(crate) fn dispatch_keystroke_interceptors(
2481 &mut self,
2482 event: &dyn Any,
2483 context_stack: Vec<KeyContext>,
2484 cx: &mut App,
2485 ) {
2486 let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() else {
2487 return;
2488 };
2489
2490 cx.keystroke_interceptors
2491 .clone()
2492 .retain(&(), move |callback| {
2493 (callback)(
2494 &KeystrokeEvent {
2495 keystroke: key_down_event.keystroke.clone(),
2496 action: None,
2497 context_stack: context_stack.clone(),
2498 },
2499 self,
2500 cx,
2501 )
2502 });
2503 }
2504
2505 pub fn defer(&self, cx: &mut App, f: impl FnOnce(&mut Window, &mut App) + 'static) {
2508 let handle = self.handle;
2509 cx.defer(move |cx| {
2510 handle.update(cx, |_, window, cx| f(window, cx)).ok();
2511 });
2512 }
2513
2514 pub fn observe<T: 'static>(
2518 &mut self,
2519 observed: &Entity<T>,
2520 cx: &mut App,
2521 mut on_notify: impl FnMut(Entity<T>, &mut Window, &mut App) + 'static,
2522 ) -> Subscription {
2523 let entity_id = observed.entity_id();
2524 let observed = observed.downgrade();
2525 let window_handle = self.handle;
2526 cx.new_observer(
2527 entity_id,
2528 Box::new(move |cx| {
2529 window_handle
2530 .update(cx, |_, window, cx| {
2531 if let Some(handle) = observed.upgrade() {
2532 on_notify(handle, window, cx);
2533 true
2534 } else {
2535 false
2536 }
2537 })
2538 .unwrap_or(false)
2539 }),
2540 )
2541 }
2542
2543 pub fn subscribe<Emitter, Evt>(
2547 &mut self,
2548 entity: &Entity<Emitter>,
2549 cx: &mut App,
2550 mut on_event: impl FnMut(Entity<Emitter>, &Evt, &mut Window, &mut App) + 'static,
2551 ) -> Subscription
2552 where
2553 Emitter: EventEmitter<Evt>,
2554 Evt: 'static,
2555 {
2556 let entity_id = entity.entity_id();
2557 let handle = entity.downgrade();
2558 let window_handle = self.handle;
2559 cx.new_subscription(
2560 entity_id,
2561 (
2562 TypeId::of::<Evt>(),
2563 Box::new(move |event, cx| {
2564 window_handle
2565 .update(cx, |_, window, cx| {
2566 if let Some(entity) = handle.upgrade() {
2567 let event = event.downcast_ref().expect("invalid event type");
2568 on_event(entity, event, window, cx);
2569 true
2570 } else {
2571 false
2572 }
2573 })
2574 .unwrap_or(false)
2575 }),
2576 ),
2577 )
2578 }
2579
2580 pub fn observe_release<T>(
2582 &self,
2583 entity: &Entity<T>,
2584 cx: &mut App,
2585 mut on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,
2586 ) -> Subscription
2587 where
2588 T: 'static,
2589 {
2590 let entity_id = entity.entity_id();
2591 let window_handle = self.handle;
2592 let (subscription, activate) = cx.release_listeners.insert(
2593 entity_id,
2594 Box::new(move |entity, cx| {
2595 let entity = entity.downcast_mut().expect("invalid entity type");
2596 let _ = window_handle.update(cx, |_, window, cx| on_release(entity, window, cx));
2597 }),
2598 );
2599 activate();
2600 subscription
2601 }
2602
2603 pub fn to_async(&self, cx: &App) -> AsyncWindowContext {
2606 AsyncWindowContext::new_context(cx.to_async(), self.handle)
2607 }
2608
2609 pub fn on_next_frame(&self, callback: impl FnOnce(&mut Window, &mut App) + 'static) {
2611 RefCell::borrow_mut(&self.next_frame_callbacks).push(Box::new(callback));
2612 self.platform_window.schedule_frame();
2613 self.invalidator.wake_platform();
2616 }
2617
2618 pub fn request_animation_frame(&self) {
2631 let entity = self.current_view();
2632 self.on_next_frame(move |_, cx| cx.notify(entity));
2633 }
2634
2635 #[cfg(any(test, feature = "test-support"))]
2640 pub fn simulate_next_frame(&mut self, cx: &mut App) -> usize {
2641 let callbacks = self.next_frame_callbacks.take();
2642 let count = callbacks.len();
2643 for callback in callbacks {
2644 callback(self, cx);
2645 }
2646 count
2647 }
2648
2649 #[track_caller]
2653 pub fn spawn<AsyncFn, R>(&self, cx: &App, f: AsyncFn) -> Task<R>
2654 where
2655 R: 'static,
2656 AsyncFn: AsyncFnOnce(&mut AsyncWindowContext) -> R + 'static,
2657 {
2658 let handle = self.handle;
2659 cx.spawn(async move |app| {
2660 let mut async_window_cx = AsyncWindowContext::new_context(app.clone(), handle);
2661 f(&mut async_window_cx).await
2662 })
2663 }
2664
2665 #[track_caller]
2669 pub fn spawn_with_priority<AsyncFn, R>(
2670 &self,
2671 priority: Priority,
2672 cx: &App,
2673 f: AsyncFn,
2674 ) -> Task<R>
2675 where
2676 R: 'static,
2677 AsyncFn: AsyncFnOnce(&mut AsyncWindowContext) -> R + 'static,
2678 {
2679 let handle = self.handle;
2680 cx.spawn_with_priority(priority, async move |app| {
2681 let mut async_window_cx = AsyncWindowContext::new_context(app.clone(), handle);
2682 f(&mut async_window_cx).await
2683 })
2684 }
2685
2686 pub fn bounds_changed(&mut self, cx: &mut App) {
2692 self.scale_factor = self.platform_window.scale_factor();
2693 self.viewport_size = self.platform_window.content_size();
2694 self.display_id = self.platform_window.display().map(|display| display.id());
2695 self.mouse_position = self.platform_window.mouse_position();
2696
2697 self.refresh();
2698
2699 self.bounds_observers
2700 .clone()
2701 .retain(&(), |callback| callback(self, cx));
2702 }
2703
2704 pub fn bounds(&self) -> Bounds<Pixels> {
2706 self.platform_window.bounds()
2707 }
2708
2709 #[cfg(any(test, feature = "test-support"))]
2713 pub fn render_to_image(&self) -> anyhow::Result<image::RgbaImage> {
2714 self.platform_window
2715 .render_to_image(&self.rendered_frame.scene)
2716 }
2717
2718 #[cfg(any(test, feature = "test-support"))]
2723 pub fn painted_quads(&self) -> Vec<Quad> {
2724 self.rendered_frame.scene.quads.clone()
2725 }
2726
2727 #[cfg(any(test, feature = "test-support"))]
2729 pub fn painted_underlines(&self) -> Vec<Underline> {
2730 self.rendered_frame.scene.underlines.clone()
2731 }
2732
2733 pub fn resize(&mut self, size: Size<Pixels>) {
2735 self.platform_window.resize(size);
2736 }
2737
2738 pub fn is_fullscreen(&self) -> bool {
2740 self.platform_window.is_fullscreen()
2741 }
2742
2743 pub fn is_simple_fullscreen(&self) -> bool {
2747 self.platform_window.is_simple_fullscreen()
2748 }
2749
2750 pub(crate) fn appearance_changed(&mut self, cx: &mut App) {
2751 self.appearance = self.platform_window.appearance();
2752
2753 self.appearance_observers
2754 .clone()
2755 .retain(&(), |callback| callback(self, cx));
2756 }
2757
2758 pub(crate) fn button_layout_changed(&mut self, cx: &mut App) {
2759 self.button_layout_observers
2760 .clone()
2761 .retain(&(), |callback| callback(self, cx));
2762 }
2763
2764 pub fn appearance(&self) -> WindowAppearance {
2766 self.appearance
2767 }
2768
2769 pub fn viewport_size(&self) -> Size<Pixels> {
2771 self.viewport_size
2772 }
2773
2774 pub fn visual_viewport_bounds(&self) -> Bounds<Pixels> {
2780 self.platform_window.visual_viewport_bounds()
2781 }
2782
2783 pub fn fully_visible_bounds(&self) -> Bounds<Pixels> {
2788 let insets = self.platform_window.insets().effective();
2789 let viewport = self.viewport_size();
2790 let left = insets.left.max(Pixels::ZERO).min(viewport.width);
2791 let top = insets.top.max(Pixels::ZERO).min(viewport.height);
2792 let right = (viewport.width - insets.right.max(Pixels::ZERO)).max(left);
2793 let bottom = (viewport.height - insets.bottom.max(Pixels::ZERO)).max(top);
2794 let safe_bounds = Bounds::from_corners(point(left, top), point(right, bottom));
2795 let mut visible = safe_bounds.intersect(&self.visual_viewport_bounds());
2796 visible.size.width = visible.size.width.max(Pixels::ZERO);
2797 visible.size.height = visible.size.height.max(Pixels::ZERO);
2798 visible
2799 }
2800
2801 pub fn request_virtual_keyboard(&self) {
2806 self.platform_window.show_soft_keyboard();
2807 }
2808
2809 pub fn dismiss_virtual_keyboard(&self) {
2811 self.platform_window.hide_soft_keyboard();
2812 }
2813
2814 pub fn is_window_active(&self) -> bool {
2816 self.active.get()
2817 }
2818
2819 pub fn is_window_hovered(&self) -> bool {
2823 if cfg!(any(
2824 target_os = "windows",
2825 target_os = "linux",
2826 target_os = "freebsd"
2827 )) {
2828 self.hovered.get()
2829 } else {
2830 self.is_window_active()
2831 }
2832 }
2833
2834 pub fn zoom_window(&self) {
2836 self.platform_window.zoom();
2837 }
2838
2839 pub fn show_window_menu(&self, position: Point<Pixels>) {
2841 self.platform_window.show_window_menu(position)
2842 }
2843
2844 pub fn start_window_move(&self) {
2849 self.platform_window.start_window_move()
2850 }
2851
2852 pub fn set_client_inset(&mut self, inset: Pixels) {
2854 self.client_inset = Some(inset);
2855 self.platform_window.set_client_inset(inset);
2856 }
2857
2858 pub fn client_inset(&self) -> Option<Pixels> {
2860 self.client_inset
2861 }
2862
2863 pub fn window_decorations(&self) -> Decorations {
2865 self.platform_window.window_decorations()
2866 }
2867
2868 pub fn is_resizable(&self) -> bool {
2870 self.is_resizable
2871 }
2872
2873 pub fn is_minimizable(&self) -> bool {
2875 self.is_minimizable
2876 }
2877
2878 pub fn window_controls(&self) -> WindowControls {
2880 self.platform_window.window_controls()
2881 }
2882
2883 pub fn set_window_title(&mut self, title: &str) {
2885 self.platform_window.set_title(title);
2886 self.a11y.set_window_title(title.to_string());
2887 }
2888
2889 #[cfg(target_os = "macos")]
2891 pub fn set_traffic_light_position(&self, position: Point<Pixels>) {
2892 self.platform_window.set_traffic_light_position(position);
2893 }
2894
2895 pub fn set_app_id(&mut self, app_id: &str) {
2897 self.platform_window.set_app_id(app_id);
2898 }
2899
2900 pub fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance) {
2902 self.platform_window
2903 .set_background_appearance(background_appearance);
2904 }
2905
2906 pub fn set_window_edited(&mut self, edited: bool) {
2908 self.platform_window.set_edited(edited);
2909 }
2910
2911 pub fn set_document_path(&self, path: Option<&std::path::Path>) {
2914 self.platform_window.set_document_path(path);
2915 }
2916
2917 pub fn display(&self, cx: &App) -> Option<Rc<dyn PlatformDisplay>> {
2919 cx.platform
2920 .displays()
2921 .into_iter()
2922 .find(|display| Some(display.id()) == self.display_id)
2923 }
2924
2925 pub fn show_character_palette(&self) {
2927 self.platform_window.show_character_palette();
2928 }
2929
2930 pub fn scale_factor(&self) -> f32 {
2934 self.scale_factor
2935 }
2936
2937 #[cfg(any(test, feature = "test-support"))]
2939 pub fn set_scale_factor(&mut self, scale_factor: f32) {
2940 self.scale_factor = scale_factor;
2941 self.refresh();
2942 }
2943
2944 pub fn rem_size(&self) -> Pixels {
2947 self.rem_size_override_stack
2948 .last()
2949 .copied()
2950 .unwrap_or(self.rem_size)
2951 }
2952
2953 pub fn set_rem_size(&mut self, rem_size: impl Into<Pixels>) {
2956 self.rem_size = rem_size.into();
2957 }
2958
2959 pub fn with_global_id<R>(
2962 &mut self,
2963 element_id: ElementId,
2964 f: impl FnOnce(&GlobalElementId, &mut Self) -> R,
2965 ) -> R {
2966 self.with_id(element_id, |this| {
2967 let global_id = GlobalElementId(Arc::from(&*this.element_id_stack));
2968
2969 f(&global_id, this)
2970 })
2971 }
2972
2973 #[inline]
2975 pub fn with_id<R>(
2976 &mut self,
2977 element_id: impl Into<ElementId>,
2978 f: impl FnOnce(&mut Self) -> R,
2979 ) -> R {
2980 self.element_id_stack.push(element_id.into());
2981 let result = f(self);
2982 self.element_id_stack.pop();
2983 result
2984 }
2985
2986 #[inline]
2992 pub fn with_rem_size<F, R>(&mut self, rem_size: Option<impl Into<Pixels>>, f: F) -> R
2993 where
2994 F: FnOnce(&mut Self) -> R,
2995 {
2996 self.invalidator.debug_assert_paint_or_prepaint();
2997
2998 if let Some(rem_size) = rem_size {
2999 self.rem_size_override_stack.push(rem_size.into());
3000 let result = f(self);
3001 self.rem_size_override_stack.pop();
3002 result
3003 } else {
3004 f(self)
3005 }
3006 }
3007
3008 pub fn line_height(&self) -> Pixels {
3010 self.text_style().line_height_in_pixels(self.rem_size())
3011 }
3012
3013 #[inline]
3015 pub fn pixel_snap(&self, value: Pixels) -> Pixels {
3016 px(round_to_device_pixel(value.0, self.scale_factor()) / self.scale_factor())
3017 }
3018
3019 #[inline]
3021 pub fn pixel_snap_f64(&self, value: f64) -> f64 {
3022 let scale_factor = f64::from(self.scale_factor());
3023 round_half_toward_zero_f64(value * scale_factor) / scale_factor
3024 }
3025
3026 #[inline]
3028 pub fn pixel_snap_bounds(&self, bounds: Bounds<Pixels>) -> Bounds<Pixels> {
3029 bounds.map(|c| self.pixel_snap(c))
3030 }
3031
3032 #[inline]
3034 pub fn pixel_snap_point(&self, position: Point<Pixels>) -> Point<Pixels> {
3035 position.map(|c| self.pixel_snap(c))
3036 }
3037
3038 pub fn underline_bounds(
3040 &self,
3041 origin: Point<Pixels>,
3042 width: Pixels,
3043 style: &UnderlineStyle,
3044 ) -> Bounds<ScaledPixels> {
3045 let scale_factor = self.scale_factor();
3046 let thickness = self.snap_stroke(style.thickness);
3047 let height = if style.wavy {
3048 ScaledPixels(thickness.0 * 3.)
3049 } else {
3050 thickness
3051 };
3052 Bounds {
3053 origin: origin.map(|c| ScaledPixels(round_to_device_pixel(c.0, scale_factor))),
3054 size: size(self.snap_stroke(width), height),
3055 }
3056 }
3057
3058 pub fn paint_underline_with_exclusions(
3060 &mut self,
3061 origin: Point<Pixels>,
3062 width: Pixels,
3063 style: &UnderlineStyle,
3064 exclusions: &[Range<ScaledPixels>],
3065 ) {
3066 self.invalidator.debug_assert_paint();
3067 let underline = self.underline(origin, width, style);
3068 if exclusions.is_empty() {
3069 self.next_frame.scene.insert_primitive(underline);
3070 return;
3071 }
3072
3073 let bounds = underline.bounds.intersect(&underline.content_mask.bounds);
3074 if bounds.is_empty() {
3075 return;
3076 }
3077
3078 let mut exclusions = exclusions
3079 .iter()
3080 .filter_map(|span| {
3081 let start = span.start.max(bounds.left());
3082 let end = span.end.min(bounds.right());
3083 (start < end).then_some(start..end)
3084 })
3085 .collect::<SmallVec<[_; 4]>>();
3086 if exclusions.is_empty() {
3087 self.next_frame.scene.insert_primitive(underline);
3088 return;
3089 }
3090 exclusions.sort_unstable_by_key(|span| span.start);
3091
3092 let mut paint_span = |start, end| {
3093 self.next_frame.scene.insert_primitive(Underline {
3094 content_mask: ContentMask {
3095 bounds: Bounds::from_corners(
3096 point(start, bounds.top()),
3097 point(end, bounds.bottom()),
3098 ),
3099 },
3100 ..underline
3101 });
3102 };
3103 let mut start = bounds.left();
3104 for exclusion in exclusions {
3105 if start < exclusion.start {
3106 paint_span(start, exclusion.start);
3107 }
3108 start = start.max(exclusion.end);
3109 }
3110 if start < bounds.right() {
3111 paint_span(start, bounds.right());
3112 }
3113 }
3114
3115 fn underline(&self, origin: Point<Pixels>, width: Pixels, style: &UnderlineStyle) -> Underline {
3116 Underline {
3117 order: 0,
3118 pad: 0,
3119 bounds: self.underline_bounds(origin, width, style),
3120 content_mask: self.snapped_content_mask(),
3121 color: style
3122 .color
3123 .unwrap_or_default()
3124 .opacity(self.element_opacity()),
3125 thickness: self.snap_stroke(style.thickness),
3126 wavy: style.wavy.into(),
3127 }
3128 }
3129
3130 #[inline]
3131 fn snap_bounds(&self, bounds: Bounds<Pixels>) -> Bounds<ScaledPixels> {
3132 let scale_factor = self.scale_factor();
3133 let left = round_to_device_pixel(bounds.left().0, scale_factor);
3134 let top = round_to_device_pixel(bounds.top().0, scale_factor);
3135 let right = round_to_device_pixel(bounds.right().0, scale_factor).max(left);
3136 let bottom = round_to_device_pixel(bounds.bottom().0, scale_factor).max(top);
3137 Bounds::from_corners(
3138 point(ScaledPixels(left), ScaledPixels(top)),
3139 point(ScaledPixels(right), ScaledPixels(bottom)),
3140 )
3141 }
3142
3143 #[inline]
3145 fn snap_stroke(&self, value: Pixels) -> ScaledPixels {
3146 ScaledPixels(round_stroke_to_device_pixel(value.0, self.scale_factor()))
3147 }
3148
3149 #[inline]
3150 fn snap_border_widths(&self, edges: Edges<Pixels>) -> Edges<ScaledPixels> {
3151 edges.map(|e| self.snap_stroke(*e))
3152 }
3153
3154 #[inline]
3156 fn cover_bounds(&self, bounds: Bounds<Pixels>) -> Bounds<ScaledPixels> {
3157 let scale_factor = self.scale_factor();
3158 let left = floor_to_device_pixel(bounds.left().0, scale_factor);
3159 let top = floor_to_device_pixel(bounds.top().0, scale_factor);
3160 let right = ceil_to_device_pixel(bounds.right().0, scale_factor).max(left);
3161 let bottom = ceil_to_device_pixel(bounds.bottom().0, scale_factor).max(top);
3162 Bounds::from_corners(
3163 point(ScaledPixels(left), ScaledPixels(top)),
3164 point(ScaledPixels(right), ScaledPixels(bottom)),
3165 )
3166 }
3167
3168 #[inline]
3169 fn snapped_content_mask(&self) -> ContentMask<ScaledPixels> {
3170 ContentMask {
3171 bounds: self.cover_bounds(self.content_mask().bounds),
3172 }
3173 }
3174
3175 pub fn prevent_default(&mut self) {
3178 self.default_prevented = true;
3179 }
3180
3181 pub fn default_prevented(&self) -> bool {
3183 self.default_prevented
3184 }
3185
3186 pub fn is_action_available(&self, action: &dyn Action, cx: &App) -> bool {
3188 let node_id =
3189 self.focus_node_id_in_rendered_frame(self.focused(cx).map(|handle| handle.id));
3190 self.rendered_frame
3191 .dispatch_tree
3192 .is_action_available(action, node_id)
3193 }
3194
3195 pub fn is_action_available_in(&self, action: &dyn Action, focus_handle: &FocusHandle) -> bool {
3197 let node_id = self.focus_node_id_in_rendered_frame(Some(focus_handle.id));
3198 self.rendered_frame
3199 .dispatch_tree
3200 .is_action_available(action, node_id)
3201 }
3202
3203 pub fn mouse_position(&self) -> Point<Pixels> {
3205 self.mouse_position
3206 }
3207
3208 pub fn capture_pointer(&mut self, hitbox_id: HitboxId) {
3215 self.captured_hitbox = Some(hitbox_id);
3216 }
3217
3218 pub fn release_pointer(&mut self) {
3220 self.captured_hitbox = None;
3221 }
3222
3223 pub fn captured_hitbox(&self) -> Option<HitboxId> {
3225 self.captured_hitbox
3226 }
3227
3228 pub fn capture_long_press<T: 'static>(&mut self, entity: &Entity<T>) {
3234 self.long_press_capture = Some(entity.entity_id());
3235 }
3236
3237 pub fn has_long_press_capture<T: 'static>(&self, entity: &Entity<T>) -> bool {
3239 self.long_press_capture == Some(entity.entity_id())
3240 }
3241
3242 pub fn modifiers(&self) -> Modifiers {
3244 self.modifiers
3245 }
3246
3247 pub fn last_input_was_keyboard(&self) -> bool {
3250 self.last_input_modality == InputModality::Keyboard
3251 }
3252
3253 pub(crate) fn last_input_was_touch(&self) -> bool {
3254 self.last_input_modality == InputModality::Touch
3255 }
3256
3257 pub fn capslock(&self) -> Capslock {
3259 self.capslock
3260 }
3261
3262 #[profiling::function]
3265 pub fn draw(&mut self, cx: &mut App) -> ArenaClearNeeded {
3266 #[cfg(feature = "profiler")]
3269 let frame_dirty = self.invalidator.take_frame_dirty();
3270 #[cfg(feature = "profiler")]
3271 self.window_profiler.begin_draw();
3272
3273 let arena_scope = ElementArenaScope::enter(&cx.element_arena);
3276
3277 if self.platform_window.prepare_frame() {
3278 self.refresh();
3279 }
3280 self.invalidate_entities();
3281 cx.entities.clear_accessed();
3282 debug_assert!(self.rendered_entity_stack.is_empty());
3283 self.invalidator.set_dirty(false);
3284 self.requested_autoscroll = None;
3285
3286 if let Some(input_handler) = self.platform_window.take_input_handler() {
3291 if let Some(slot) = self
3292 .rendered_frame
3293 .input_handlers
3294 .iter_mut()
3295 .rev()
3296 .find(|h| h.is_none())
3297 {
3298 *slot = Some(input_handler);
3299 } else {
3300 self.rendered_frame.input_handlers.push(Some(input_handler));
3301 }
3302 }
3303 if !cx.mode.skip_drawing() {
3304 self.draw_roots(cx);
3305 #[cfg(feature = "profiler")]
3306 {
3307 let viewport_size = self.viewport_size;
3308 let scale_factor = self.scale_factor();
3309 self.debug_frame_overlay.paint(
3310 &mut self.next_frame.scene,
3311 viewport_size,
3312 scale_factor,
3313 );
3314 }
3315 }
3316 self.dirty_views.clear();
3317 self.next_frame.window_active = self.active.get();
3318
3319 let focused_text_input_active = if let Some(mut input_handler) = self
3325 .next_frame
3326 .input_handlers
3327 .iter_mut()
3328 .rev()
3329 .find_map(|h| h.take())
3330 {
3331 let accepts_text_input = input_handler.accepts_text_input(self, cx);
3332 self.platform_window.set_input_handler(input_handler);
3333 accepts_text_input
3334 } else {
3335 false
3336 };
3337 self.apply_text_input_configuration(cx);
3338 if focused_text_input_active != self.focused_text_input_active {
3339 self.focused_text_input_active = focused_text_input_active;
3340 self.platform_window
3341 .text_input_state_changed(if focused_text_input_active {
3342 TextInputStateChange::FocusGained
3343 } else {
3344 TextInputStateChange::FocusLost
3345 });
3346 }
3347
3348 self.layout_engine.as_mut().unwrap().clear();
3349 self.text_system().finish_frame();
3350 self.next_frame.finish(&mut self.rendered_frame);
3351
3352 self.invalidator.set_phase(DrawPhase::Focus);
3353 let previous_focus_path = self.rendered_frame.focus_path();
3354 let previous_window_active = self.rendered_frame.window_active;
3355 mem::swap(&mut self.rendered_frame, &mut self.next_frame);
3356 self.next_frame.clear();
3357 let current_focus_path = self.rendered_frame.focus_path();
3358 let current_window_active = self.rendered_frame.window_active;
3359 let mut focus_before_listeners = self.focus;
3360
3361 if previous_focus_path != current_focus_path
3362 || previous_window_active != current_window_active
3363 {
3364 if !previous_focus_path.is_empty() && current_focus_path.is_empty() {
3365 self.focus_lost_path = previous_focus_path.clone();
3366 self.focus_lost_listeners
3367 .clone()
3368 .retain(&(), |listener| listener(self, cx));
3369 self.focus_lost_path = SmallVec::new();
3370 focus_before_listeners = self.focus;
3375 }
3376
3377 let event = WindowFocusEvent {
3378 previous_focus_path: if previous_window_active {
3379 previous_focus_path
3380 } else {
3381 Default::default()
3382 },
3383 current_focus_path: if current_window_active {
3384 current_focus_path
3385 } else {
3386 Default::default()
3387 },
3388 };
3389 self.focus_listeners
3390 .clone()
3391 .retain(&(), |listener| listener(&event, self, cx));
3392 }
3393
3394 debug_assert!(self.rendered_entity_stack.is_empty());
3395 self.record_entities_accessed(cx);
3396 self.reset_cursor_style(cx);
3397 self.refreshing = false;
3398 self.invalidator.set_phase(DrawPhase::None);
3399 if self.focus != focus_before_listeners {
3404 self.refresh();
3405 }
3406 self.needs_present.set(true);
3407
3408 #[cfg(feature = "profiler")]
3409 {
3410 let draw_duration = self
3411 .window_profiler
3412 .end_draw(frame_dirty.dirty_at, frame_dirty.invalidations);
3413 self.debug_frame_overlay.record_frame(draw_duration);
3414 }
3415
3416 arena_scope.exit(&cx.element_arena)
3419 }
3420
3421 fn record_entities_accessed(&mut self, cx: &mut App) {
3422 let mut entities_ref = cx.entities.accessed_entities.get_mut();
3423 let mut entities = mem::take(entities_ref.deref_mut());
3424 let handle = self.handle;
3425 cx.record_entities_accessed(
3426 handle,
3427 self.invalidator.clone(),
3429 &entities,
3430 );
3431 let mut entities_ref = cx.entities.accessed_entities.get_mut();
3432 mem::swap(&mut entities, entities_ref.deref_mut());
3433 }
3434
3435 fn invalidate_entities(&mut self) {
3436 let mut views = self.invalidator.take_views();
3437 for entity in views.drain() {
3438 self.mark_view_dirty(entity);
3439 }
3440 self.invalidator.replace_views(views);
3441 }
3442
3443 #[profiling::function]
3444 fn present(&mut self) {
3445 #[cfg(feature = "profiler")]
3446 let _foreground_turn = profiler::journal::foreground_turn();
3447 #[cfg(feature = "profiler")]
3448 let present_start = Instant::now();
3449 self.platform_window.draw(&self.rendered_frame.scene);
3450 #[cfg(feature = "profiler")]
3451 self.window_profiler.record_present(
3452 present_start,
3453 Instant::now(),
3454 self.active.get(),
3455 !self.next_frame_callbacks.borrow().is_empty(),
3456 );
3457 self.needs_present.set(false);
3458 profiling::finish_frame!();
3459 }
3460
3461 #[cfg(all(test, feature = "profiler"))]
3463 pub fn present_if_needed(&mut self) {
3464 if self.needs_present.get() {
3465 self.present();
3466 }
3467 }
3468
3469 #[cfg(feature = "profiler")]
3471 pub fn input_latency_snapshot(&self) -> profiler::InputLatencySnapshot {
3472 self.window_profiler.input_latency_snapshot()
3473 }
3474
3475 #[cfg(feature = "profiler")]
3477 pub fn frame_duration_snapshot(&self) -> profiler::FrameDurationSnapshot {
3478 self.window_profiler.frame_duration_snapshot()
3479 }
3480
3481 #[cfg(feature = "profiler")]
3483 pub fn debug_frame_overlay_mode(&self) -> DebugFrameOverlayMode {
3484 self.debug_frame_overlay.mode()
3485 }
3486
3487 #[cfg(feature = "profiler")]
3489 pub fn set_debug_frame_overlay_mode(&mut self, mode: DebugFrameOverlayMode) {
3490 self.debug_frame_overlay.set_mode(mode);
3491 self.refresh();
3492 }
3493
3494 #[cfg(feature = "profiler")]
3497 pub fn cycle_debug_frame_overlay_mode(&mut self) {
3498 self.set_debug_frame_overlay_mode(self.debug_frame_overlay.mode().next());
3499 }
3500
3501 #[cfg(feature = "profiler")]
3504 pub fn reset_debug_frame_overlay_stats(&mut self) {
3505 self.debug_frame_overlay.reset_stats();
3506 self.refresh();
3507 }
3508
3509 fn draw_roots(&mut self, cx: &mut App) {
3510 self.invalidator.set_phase(DrawPhase::Prepaint);
3511 self.tooltip_bounds.take();
3512
3513 self.a11y.sync_active_flag();
3514 if self.a11y.is_active() {
3515 self.a11y.begin_frame();
3516 }
3517
3518 let _inspector_width: Pixels = rems(30.0).to_pixels(self.rem_size());
3519 let root_size = {
3520 #[cfg(any(feature = "inspector", debug_assertions))]
3521 {
3522 if self.inspector.is_some() {
3523 let mut size = self.viewport_size;
3524 size.width = (size.width - _inspector_width).max(px(0.0));
3525 size
3526 } else {
3527 self.viewport_size
3528 }
3529 }
3530 #[cfg(not(any(feature = "inspector", debug_assertions)))]
3531 {
3532 self.viewport_size
3533 }
3534 };
3535
3536 let scale_factor = self.scale_factor();
3540 let mut root_element = self.root.as_ref().unwrap().clone().into_any_element();
3541 let root_layout_id = root_element.request_layout(self, cx);
3542 self.layout_engine
3543 .as_mut()
3544 .unwrap()
3545 .stretch_auto_size_to_fill(root_layout_id, root_size, scale_factor);
3546 root_element.prepaint_as_root(Point::default(), root_size.into(), self, cx);
3547
3548 #[cfg(any(feature = "inspector", debug_assertions))]
3549 let inspector_element = self.prepaint_inspector(_inspector_width, cx);
3550
3551 self.prepaint_deferred_draws(cx);
3552
3553 let mut prompt_element = None;
3554 let mut active_drag_element = None;
3555 let mut tooltip_element = None;
3556 if let Some(prompt) = self.prompt.take() {
3557 let mut element = prompt.view.any_view().into_any_element();
3558 let prompt_layout_id = element.request_layout(self, cx);
3559 self.layout_engine
3560 .as_mut()
3561 .unwrap()
3562 .stretch_auto_size_to_fill(prompt_layout_id, root_size, scale_factor);
3563 element.prepaint_as_root(Point::default(), root_size.into(), self, cx);
3564 prompt_element = Some(element);
3565 self.prompt = Some(prompt);
3566 } else if let Some(active_drag) = cx.active_drag.take() {
3567 let mut element = active_drag.view.clone().into_any_element();
3568 let offset = self.mouse_position() - active_drag.cursor_offset;
3569 element.prepaint_as_root(offset, AvailableSpace::min_size(), self, cx);
3570 active_drag_element = Some(element);
3571 cx.active_drag = Some(active_drag);
3572 } else {
3573 tooltip_element = self.prepaint_tooltip(cx);
3574 }
3575
3576 self.mouse_hit_test = self.next_frame.hit_test(self.mouse_position);
3577
3578 self.invalidator.set_phase(DrawPhase::Paint);
3580 root_element.paint(self, cx);
3581
3582 #[cfg(any(feature = "inspector", debug_assertions))]
3583 self.paint_inspector(inspector_element, cx);
3584
3585 self.paint_deferred_draws(cx);
3586
3587 if let Some(mut prompt_element) = prompt_element {
3588 prompt_element.paint(self, cx);
3589 } else if let Some(mut drag_element) = active_drag_element {
3590 drag_element.paint(self, cx);
3591 } else if let Some(mut tooltip_element) = tooltip_element {
3592 tooltip_element.paint(self, cx);
3593 }
3594
3595 #[cfg(any(feature = "inspector", debug_assertions))]
3596 self.paint_inspector_hitbox(cx);
3597
3598 let a11y_active_start_of_frame = self.a11y.is_active();
3600 self.a11y.sync_active_flag();
3601 let a11y_active_end_of_frame = self.a11y.is_active();
3602
3603 let should_send_a11y_update = a11y_active_start_of_frame && a11y_active_end_of_frame;
3604
3605 if a11y_active_start_of_frame {
3606 let frame_info = crate::window::a11y::debug::FrameDebugInfo {
3609 viewport_size: self.viewport_size,
3610 scale_factor: self.scale_factor,
3611 tab_stop_count: self.next_frame.tab_stops.tab_stop_count(),
3612 };
3613 let tree_update = self.a11y.end_frame(frame_info);
3615
3616 if should_send_a11y_update {
3617 log::debug!(
3618 "Sending a11y tree update: {} nodes",
3619 tree_update.nodes.len()
3620 );
3621 self.platform_window.a11y_tree_update(tree_update);
3622 }
3623 }
3624 }
3625
3626 fn prepaint_tooltip(&mut self, cx: &mut App) -> Option<AnyElement> {
3627 for tooltip_request_index in (0..self.next_frame.tooltip_requests.len()).rev() {
3629 let Some(Some(tooltip_request)) = self
3630 .next_frame
3631 .tooltip_requests
3632 .get(tooltip_request_index)
3633 .cloned()
3634 else {
3635 log::error!("Unexpectedly absent TooltipRequest");
3636 continue;
3637 };
3638 let mut element = tooltip_request.tooltip.view.clone().into_any_element();
3639 let mouse_position = tooltip_request.tooltip.mouse_position;
3640 let tooltip_size = element.layout_as_root(AvailableSpace::min_size(), self, cx);
3641
3642 let mut tooltip_bounds =
3643 Bounds::new(mouse_position + point(px(1.), px(1.)), tooltip_size);
3644 let window_bounds = Bounds {
3645 origin: Point::default(),
3646 size: self.viewport_size(),
3647 };
3648
3649 if tooltip_bounds.right() > window_bounds.right() {
3650 let new_x = mouse_position.x - tooltip_bounds.size.width - px(1.);
3651 if new_x >= Pixels::ZERO {
3652 tooltip_bounds.origin.x = new_x;
3653 } else {
3654 tooltip_bounds.origin.x = cmp::max(
3655 Pixels::ZERO,
3656 tooltip_bounds.origin.x - tooltip_bounds.right() - window_bounds.right(),
3657 );
3658 }
3659 }
3660
3661 if tooltip_bounds.bottom() > window_bounds.bottom() {
3662 let new_y = mouse_position.y - tooltip_bounds.size.height - px(1.);
3663 if new_y >= Pixels::ZERO {
3664 tooltip_bounds.origin.y = new_y;
3665 } else {
3666 tooltip_bounds.origin.y = cmp::max(
3667 Pixels::ZERO,
3668 tooltip_bounds.origin.y - tooltip_bounds.bottom() - window_bounds.bottom(),
3669 );
3670 }
3671 }
3672
3673 let is_visible =
3677 (tooltip_request.tooltip.check_visible_and_update)(tooltip_bounds, self, cx);
3678 if !is_visible {
3679 continue;
3680 }
3681
3682 self.with_absolute_element_offset(tooltip_bounds.origin, |window| {
3683 element.prepaint(window, cx)
3684 });
3685
3686 self.tooltip_bounds = Some(TooltipBounds {
3687 id: tooltip_request.id,
3688 bounds: tooltip_bounds,
3689 });
3690 return Some(element);
3691 }
3692 None
3693 }
3694
3695 fn prepaint_deferred_draws(&mut self, cx: &mut App) {
3696 assert_eq!(self.element_id_stack.len(), 0);
3697
3698 let mut round_start = 0;
3709 let mut depth = 0;
3710 loop {
3711 let round_end = self.next_frame.deferred_draws.len();
3712 if round_start == round_end {
3713 break;
3714 }
3715 assert!(depth < 10, "Exceeded maximum (10) deferred depth");
3717 depth += 1;
3718
3719 let mut traversal_order = (round_start..round_end).collect::<SmallVec<[usize; 8]>>();
3721 traversal_order.sort_by_key(|ix| self.next_frame.deferred_draws[*ix].priority);
3722
3723 for deferred_draw_ix in traversal_order {
3724 let (element, parent_node, current_view, rem_size, absolute_offset, prepaint_range) = {
3725 let deferred_draw = &mut self.next_frame.deferred_draws[deferred_draw_ix];
3726 self.element_id_stack
3727 .clone_from(&deferred_draw.element_id_stack);
3728 self.text_style_stack
3729 .clone_from(&deferred_draw.text_style_stack);
3730 (
3731 deferred_draw.element.take(),
3732 deferred_draw.parent_node,
3733 deferred_draw.current_view,
3734 deferred_draw.rem_size,
3735 deferred_draw.absolute_offset,
3736 deferred_draw.prepaint_range.clone(),
3737 )
3738 };
3739 self.next_frame.dispatch_tree.set_active_node(parent_node);
3740
3741 let prepaint_start = self.prepaint_index();
3742 if let Some(mut element) = element {
3743 self.with_rendered_view(current_view, |window| {
3744 window.with_rem_size(Some(rem_size), |window| {
3745 window.with_absolute_element_offset(absolute_offset, |window| {
3746 element.prepaint(window, cx);
3747 });
3748 });
3749 });
3750 self.next_frame.deferred_draws[deferred_draw_ix].element = Some(element);
3751 } else {
3752 self.reuse_prepaint(prepaint_range);
3753 }
3754 let prepaint_end = self.prepaint_index();
3755 self.next_frame.deferred_draws[deferred_draw_ix].prepaint_range =
3756 prepaint_start..prepaint_end;
3757 }
3758
3759 self.element_id_stack.clear();
3760 self.text_style_stack.clear();
3761 round_start = round_end;
3762 }
3763 }
3764
3765 fn paint_deferred_draws(&mut self, cx: &mut App) {
3766 assert_eq!(self.element_id_stack.len(), 0);
3767
3768 if self.next_frame.deferred_draws.len() == 0 {
3771 return;
3772 }
3773
3774 let traversal_order = self.deferred_draw_traversal_order();
3775 let mut deferred_draws = mem::take(&mut self.next_frame.deferred_draws);
3776 for deferred_draw_ix in traversal_order {
3777 let mut deferred_draw = &mut deferred_draws[deferred_draw_ix];
3778 self.element_id_stack
3779 .clone_from(&deferred_draw.element_id_stack);
3780 self.next_frame
3781 .dispatch_tree
3782 .set_active_node(deferred_draw.parent_node);
3783
3784 let paint_start = self.paint_index();
3785 let content_mask = deferred_draw.content_mask;
3786 if let Some(element) = deferred_draw.element.as_mut() {
3787 self.with_rendered_view(deferred_draw.current_view, |window| {
3788 window.with_content_mask(content_mask, |window| {
3789 window.with_rem_size(Some(deferred_draw.rem_size), |window| {
3790 element.paint(window, cx);
3791 });
3792 })
3793 })
3794 } else {
3795 self.reuse_paint(deferred_draw.paint_range.clone());
3796 }
3797 let paint_end = self.paint_index();
3798 deferred_draw.paint_range = paint_start..paint_end;
3799 }
3800 self.next_frame.deferred_draws = deferred_draws;
3801 self.element_id_stack.clear();
3802 }
3803
3804 fn deferred_draw_traversal_order(&mut self) -> SmallVec<[usize; 8]> {
3805 let deferred_count = self.next_frame.deferred_draws.len();
3806 let mut sorted_indices = (0..deferred_count).collect::<SmallVec<[_; 8]>>();
3807 sorted_indices.sort_by_key(|ix| self.next_frame.deferred_draws[*ix].priority);
3808 sorted_indices
3809 }
3810
3811 pub(crate) fn prepaint_index(&self) -> PrepaintStateIndex {
3812 PrepaintStateIndex {
3813 hitboxes_index: self.next_frame.hitboxes.len(),
3814 tooltips_index: self.next_frame.tooltip_requests.len(),
3815 deferred_draws_index: self.next_frame.deferred_draws.len(),
3816 dispatch_tree_index: self.next_frame.dispatch_tree.len(),
3817 accessed_element_states_index: self.next_frame.accessed_element_states.len(),
3818 line_layout_index: self.text_system.layout_index(),
3819 }
3820 }
3821
3822 pub(crate) fn reuse_prepaint(&mut self, range: Range<PrepaintStateIndex>) {
3823 self.next_frame.hitboxes.extend(
3824 self.rendered_frame.hitboxes[range.start.hitboxes_index..range.end.hitboxes_index]
3825 .iter()
3826 .cloned(),
3827 );
3828 self.next_frame.tooltip_requests.extend(
3829 self.rendered_frame.tooltip_requests
3830 [range.start.tooltips_index..range.end.tooltips_index]
3831 .iter_mut()
3832 .map(|request| request.take()),
3833 );
3834 self.next_frame.accessed_element_states.extend(
3835 self.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
3836 ..range.end.accessed_element_states_index]
3837 .iter()
3838 .map(|(id, type_id)| (id.clone(), *type_id)),
3839 );
3840 self.text_system
3841 .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
3842
3843 let reused_subtree = self.next_frame.dispatch_tree.reuse_subtree(
3844 range.start.dispatch_tree_index..range.end.dispatch_tree_index,
3845 &mut self.rendered_frame.dispatch_tree,
3846 self.focus,
3847 );
3848
3849 if reused_subtree.contains_focus() {
3850 self.next_frame.focus = self.focus;
3851 }
3852
3853 self.next_frame.deferred_draws.extend(
3854 self.rendered_frame.deferred_draws
3855 [range.start.deferred_draws_index..range.end.deferred_draws_index]
3856 .iter()
3857 .map(|deferred_draw| DeferredDraw {
3858 current_view: deferred_draw.current_view,
3859 parent_node: reused_subtree.refresh_node_id(deferred_draw.parent_node),
3860 element_id_stack: deferred_draw.element_id_stack.clone(),
3861 text_style_stack: deferred_draw.text_style_stack.clone(),
3862 content_mask: deferred_draw.content_mask,
3863 rem_size: deferred_draw.rem_size,
3864 priority: deferred_draw.priority,
3865 element: None,
3866 absolute_offset: deferred_draw.absolute_offset,
3867 prepaint_range: deferred_draw.prepaint_range.clone(),
3868 paint_range: deferred_draw.paint_range.clone(),
3869 }),
3870 );
3871 }
3872
3873 pub(crate) fn paint_index(&self) -> PaintIndex {
3874 PaintIndex {
3875 scene_index: self.next_frame.scene.len(),
3876 #[cfg(any(test, feature = "test-support"))]
3877 debug_bounds_index: self.next_frame.debug_bounds_records.len(),
3878 mouse_listeners_index: self.next_frame.mouse_listeners.len(),
3879 input_handlers_index: self.next_frame.input_handlers.len(),
3880 cursor_styles_index: self.next_frame.cursor_styles.len(),
3881 accessed_element_states_index: self.next_frame.accessed_element_states.len(),
3882 tab_handle_index: self.next_frame.tab_stops.paint_index(),
3883 line_layout_index: self.text_system.layout_index(),
3884 }
3885 }
3886
3887 pub(crate) fn reuse_paint(&mut self, range: Range<PaintIndex>) {
3888 #[cfg(any(test, feature = "test-support"))]
3890 for (selector, bounds) in &self.rendered_frame.debug_bounds_records
3891 [range.start.debug_bounds_index..range.end.debug_bounds_index]
3892 {
3893 self.next_frame
3894 .record_debug_bounds(selector.clone(), *bounds);
3895 }
3896 self.next_frame.cursor_styles.extend(
3897 self.rendered_frame.cursor_styles
3898 [range.start.cursor_styles_index..range.end.cursor_styles_index]
3899 .iter()
3900 .cloned(),
3901 );
3902 self.next_frame.input_handlers.extend(
3903 self.rendered_frame.input_handlers
3904 [range.start.input_handlers_index..range.end.input_handlers_index]
3905 .iter_mut()
3906 .map(|handler| handler.take()),
3907 );
3908 self.next_frame.mouse_listeners.extend(
3909 self.rendered_frame.mouse_listeners
3910 [range.start.mouse_listeners_index..range.end.mouse_listeners_index]
3911 .iter_mut()
3912 .map(|listener| listener.take()),
3913 );
3914 self.next_frame.accessed_element_states.extend(
3915 self.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
3916 ..range.end.accessed_element_states_index]
3917 .iter()
3918 .map(|(id, type_id)| (id.clone(), *type_id)),
3919 );
3920 self.next_frame.tab_stops.replay(
3921 &self.rendered_frame.tab_stops.insertion_history
3922 [range.start.tab_handle_index..range.end.tab_handle_index],
3923 );
3924
3925 self.text_system
3926 .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
3927 self.next_frame.scene.replay(
3928 range.start.scene_index..range.end.scene_index,
3929 &self.rendered_frame.scene,
3930 );
3931 }
3932
3933 pub fn with_text_style<F, R>(&mut self, style: Option<TextStyleRefinement>, f: F) -> R
3937 where
3938 F: FnOnce(&mut Self) -> R,
3939 {
3940 self.invalidator.debug_assert_paint_or_prepaint();
3941 if let Some(style) = style {
3942 self.text_style_stack.push(style);
3943 let result = f(self);
3944 self.text_style_stack.pop();
3945 result
3946 } else {
3947 f(self)
3948 }
3949 }
3950
3951 pub fn set_cursor_style(&mut self, style: CursorStyle, hitbox: &Hitbox) {
3954 self.invalidator.debug_assert_paint();
3955 self.next_frame.cursor_styles.push(CursorStyleRequest {
3956 hitbox_id: Some(hitbox.id),
3957 style,
3958 });
3959 }
3960
3961 pub fn set_window_cursor_style(&mut self, style: CursorStyle) {
3966 self.invalidator.debug_assert_paint();
3967 self.next_frame.cursor_styles.push(CursorStyleRequest {
3968 hitbox_id: None,
3969 style,
3970 })
3971 }
3972
3973 pub fn set_tooltip(&mut self, tooltip: AnyTooltip) -> TooltipId {
3976 self.invalidator.debug_assert_prepaint();
3977 let id = TooltipId(post_inc(&mut self.next_tooltip_id.0));
3978 self.next_frame
3979 .tooltip_requests
3980 .push(Some(TooltipRequest { id, tooltip }));
3981 id
3982 }
3983
3984 #[inline]
3989 pub fn with_content_mask<R>(
3990 &mut self,
3991 mask: Option<ContentMask<Pixels>>,
3992 f: impl FnOnce(&mut Self) -> R,
3993 ) -> R {
3994 self.invalidator.debug_assert_paint_or_prepaint();
3995 if let Some(mask) = mask {
3996 let mask = mask.intersect(&self.content_mask());
3997 self.content_mask_stack.push(mask);
3998 let result = f(self);
3999 self.content_mask_stack.pop();
4000 result
4001 } else {
4002 f(self)
4003 }
4004 }
4005
4006 pub fn with_element_offset<R>(
4009 &mut self,
4010 offset: Point<Pixels>,
4011 f: impl FnOnce(&mut Self) -> R,
4012 ) -> R {
4013 self.invalidator.debug_assert_prepaint();
4014
4015 if offset.is_zero() {
4016 return f(self);
4017 };
4018
4019 let abs_offset = self.element_offset() + offset;
4020 self.with_absolute_element_offset(abs_offset, f)
4021 }
4022
4023 pub fn with_absolute_element_offset<R>(
4027 &mut self,
4028 offset: Point<Pixels>,
4029 f: impl FnOnce(&mut Self) -> R,
4030 ) -> R {
4031 self.invalidator.debug_assert_prepaint();
4032 self.element_offset_stack.push(offset);
4033 let result = f(self);
4034 self.element_offset_stack.pop();
4035 result
4036 }
4037
4038 pub(crate) fn with_element_opacity<R>(
4039 &mut self,
4040 opacity: Option<f32>,
4041 f: impl FnOnce(&mut Self) -> R,
4042 ) -> R {
4043 self.invalidator.debug_assert_paint_or_prepaint();
4044
4045 let Some(opacity) = opacity else {
4046 return f(self);
4047 };
4048
4049 let previous_opacity = self.element_opacity;
4050 self.element_opacity = previous_opacity * opacity;
4051 let result = f(self);
4052 self.element_opacity = previous_opacity;
4053 result
4054 }
4055
4056 pub fn transact<T, U>(&mut self, f: impl FnOnce(&mut Self) -> Result<T, U>) -> Result<T, U> {
4062 self.invalidator.debug_assert_prepaint();
4063 let index = self.prepaint_index();
4064 let result = f(self);
4065 if result.is_err() {
4066 self.next_frame.hitboxes.truncate(index.hitboxes_index);
4067 self.next_frame
4068 .tooltip_requests
4069 .truncate(index.tooltips_index);
4070 self.next_frame
4071 .deferred_draws
4072 .truncate(index.deferred_draws_index);
4073 self.next_frame
4074 .dispatch_tree
4075 .truncate(index.dispatch_tree_index);
4076 self.next_frame
4077 .accessed_element_states
4078 .truncate(index.accessed_element_states_index);
4079 self.text_system.truncate_layouts(index.line_layout_index);
4080 }
4081 result
4082 }
4083
4084 pub fn request_autoscroll(&mut self, bounds: Bounds<Pixels>) {
4090 self.invalidator.debug_assert_prepaint();
4091 self.requested_autoscroll = Some(bounds);
4092 }
4093
4094 pub fn take_autoscroll(&mut self) -> Option<Bounds<Pixels>> {
4097 self.invalidator.debug_assert_prepaint();
4098 self.requested_autoscroll.take()
4099 }
4100
4101 pub fn use_asset<A: Asset>(&mut self, source: &A::Source, cx: &mut App) -> Option<A::Output> {
4107 cx.asset_entry::<A>(source).use_by(self.current_view())
4108 }
4109
4110 pub fn get_asset<A: Asset>(&mut self, source: &A::Source, cx: &mut App) -> Option<A::Output> {
4116 cx.fetch_asset::<A>(source)
4117 }
4118 pub fn element_offset(&self) -> Point<Pixels> {
4121 self.invalidator.debug_assert_prepaint();
4122 self.element_offset_stack
4123 .last()
4124 .copied()
4125 .unwrap_or_default()
4126 }
4127
4128 #[inline]
4131 pub(crate) fn element_opacity(&self) -> f32 {
4132 self.invalidator.debug_assert_paint_or_prepaint();
4133 self.element_opacity
4134 }
4135
4136 pub fn content_mask(&self) -> ContentMask<Pixels> {
4138 self.invalidator.debug_assert_paint_or_prepaint();
4139 self.content_mask_stack
4140 .last()
4141 .cloned()
4142 .unwrap_or_else(|| ContentMask {
4143 bounds: Bounds {
4144 origin: Point::default(),
4145 size: self.viewport_size,
4146 },
4147 })
4148 }
4149
4150 pub fn with_element_namespace<R>(
4153 &mut self,
4154 element_id: impl Into<ElementId>,
4155 f: impl FnOnce(&mut Self) -> R,
4156 ) -> R {
4157 self.element_id_stack.push(element_id.into());
4158 let result = f(self);
4159 self.element_id_stack.pop();
4160 result
4161 }
4162
4163 pub fn use_keyed_state<S: 'static>(
4165 &mut self,
4166 key: impl Into<ElementId>,
4167 cx: &mut App,
4168 init: impl FnOnce(&mut Self, &mut Context<S>) -> S,
4169 ) -> Entity<S> {
4170 let current_view = self.current_view();
4171 self.with_global_id(key.into(), |global_id, window| {
4172 window.with_element_state(global_id, |state: Option<Entity<S>>, window| {
4173 if let Some(state) = state {
4174 (state.clone(), state)
4175 } else {
4176 let new_state = cx.new(|cx| init(window, cx));
4177 Self::observe_keyed_state(&new_state, current_view, cx);
4178 (new_state.clone(), new_state)
4179 }
4180 })
4181 })
4182 }
4183
4184 #[track_caller]
4190 pub fn use_state<S: 'static>(
4191 &mut self,
4192 cx: &mut App,
4193 init: impl FnOnce(&mut Self, &mut Context<S>) -> S,
4194 ) -> Entity<S> {
4195 self.use_keyed_state(
4196 ElementId::CodeLocation(*core::panic::Location::caller()),
4197 cx,
4198 init,
4199 )
4200 }
4201
4202 #[inline(always)]
4207 pub fn with_element_state<S, R>(
4208 &mut self,
4209 global_id: &GlobalElementId,
4210 f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
4211 ) -> R
4212 where
4213 S: 'static,
4214 {
4215 self.invalidator.debug_assert_paint_or_prepaint();
4216
4217 let (key, state) = self.take_element_state(global_id, TypeId::of::<S>());
4218
4219 if let Some(any) = state {
4220 let ElementStateBox {
4221 inner,
4222 #[cfg(debug_assertions)]
4223 type_name,
4224 } = any;
4225 let mut state_box = inner
4227 .downcast::<Option<S>>()
4228 .map_err(|_| {
4229 #[cfg(debug_assertions)]
4230 {
4231 anyhow::anyhow!(
4232 "invalid element state type for id, requested {:?}, actual: {:?}",
4233 std::any::type_name::<S>(),
4234 type_name
4235 )
4236 }
4237
4238 #[cfg(not(debug_assertions))]
4239 {
4240 anyhow::anyhow!(
4241 "invalid element state type for id, requested {:?}",
4242 std::any::type_name::<S>(),
4243 )
4244 }
4245 })
4246 .unwrap();
4247
4248 let state = state_box.take().expect(
4249 "reentrant call to with_element_state for the same state type and element id",
4250 );
4251 let (result, state) = f(Some(state), self);
4252 state_box.replace(state);
4253 self.insert_element_state(
4254 key,
4255 ElementStateBox {
4256 inner: state_box,
4257 #[cfg(debug_assertions)]
4258 type_name,
4259 },
4260 );
4261 result
4262 } else {
4263 let (result, state) = f(None, self);
4264 self.insert_element_state(
4265 key,
4266 ElementStateBox {
4267 inner: Box::new(Some(state)),
4268 #[cfg(debug_assertions)]
4269 type_name: std::any::type_name::<S>(),
4270 },
4271 );
4272 result
4273 }
4274 }
4275
4276 pub fn with_optional_element_state<S, R>(
4283 &mut self,
4284 global_id: Option<&GlobalElementId>,
4285 f: impl FnOnce(Option<Option<S>>, &mut Self) -> (R, Option<S>),
4286 ) -> R
4287 where
4288 S: 'static,
4289 {
4290 self.invalidator.debug_assert_paint_or_prepaint();
4291
4292 if let Some(global_id) = global_id {
4293 self.with_element_state(global_id, |state, cx| {
4294 let (result, state) = f(Some(state), cx);
4295 let state =
4296 state.expect("you must return some state when you pass some element id");
4297 (result, state)
4298 })
4299 } else {
4300 let (result, state) = f(None, self);
4301 debug_assert!(
4302 state.is_none(),
4303 "you must not return an element state when passing None for the global id"
4304 );
4305 result
4306 }
4307 }
4308
4309 #[inline]
4311 pub fn with_tab_group<R>(&mut self, index: Option<isize>, f: impl FnOnce(&mut Self) -> R) -> R {
4312 if let Some(index) = index {
4313 self.next_frame.tab_stops.begin_group(index);
4314 let result = f(self);
4315 self.next_frame.tab_stops.end_group();
4316 result
4317 } else {
4318 f(self)
4319 }
4320 }
4321
4322 pub fn defer_draw(
4331 &mut self,
4332 element: AnyElement,
4333 absolute_offset: Point<Pixels>,
4334 priority: usize,
4335 content_mask: Option<ContentMask<Pixels>>,
4336 ) {
4337 self.invalidator.debug_assert_prepaint();
4338 let parent_node = self.next_frame.dispatch_tree.active_node_id().unwrap();
4339 self.next_frame.deferred_draws.push(DeferredDraw {
4340 current_view: self.current_view(),
4341 parent_node,
4342 element_id_stack: self.element_id_stack.clone(),
4343 text_style_stack: self.text_style_stack.clone(),
4344 content_mask,
4345 rem_size: self.rem_size(),
4346 priority,
4347 element: Some(element),
4348 absolute_offset,
4349 prepaint_range: PrepaintStateIndex::default()..PrepaintStateIndex::default(),
4350 paint_range: PaintIndex::default()..PaintIndex::default(),
4351 });
4352 }
4353
4354 pub fn paint_layer<R>(&mut self, bounds: Bounds<Pixels>, f: impl FnOnce(&mut Self) -> R) -> R {
4360 self.invalidator.debug_assert_paint();
4361
4362 let content_mask = self.content_mask();
4363 let clipped_bounds = bounds.intersect(&content_mask.bounds);
4364 if !clipped_bounds.is_empty() {
4365 self.next_frame
4366 .scene
4367 .push_layer(self.cover_bounds(clipped_bounds));
4368 }
4369
4370 let result = f(self);
4371
4372 if !clipped_bounds.is_empty() {
4373 self.next_frame.scene.pop_layer();
4374 }
4375
4376 result
4377 }
4378
4379 pub fn paint_drop_shadows(
4385 &mut self,
4386 bounds: Bounds<Pixels>,
4387 corner_radii: Corners<Pixels>,
4388 shadows: &[BoxShadow],
4389 ) {
4390 self.invalidator.debug_assert_paint();
4391
4392 let scale_factor = self.scale_factor();
4393 let content_mask = self.snapped_content_mask();
4394 let opacity = self.element_opacity();
4395 let element_bounds = self.cover_bounds(bounds);
4396 let element_corner_radii = corner_radii.scale(scale_factor);
4397 for shadow in shadows {
4398 if shadow.inset {
4399 continue;
4400 }
4401 let shadow_bounds = (bounds + shadow.offset).dilate(shadow.spread_radius);
4402 self.next_frame.scene.insert_primitive(Shadow {
4403 order: 0,
4404 blur_radius: shadow.blur_radius.scale(scale_factor),
4405 bounds: self.cover_bounds(shadow_bounds),
4406 content_mask,
4407 corner_radii: corner_radii.scale(scale_factor),
4408 color: shadow.color.opacity(opacity),
4409 element_bounds,
4410 element_corner_radii,
4411 inset: 0,
4412 pad: 0,
4413 });
4414 }
4415 }
4416
4417 pub fn paint_inset_shadows(
4421 &mut self,
4422 bounds: Bounds<Pixels>,
4423 corner_radii: Corners<Pixels>,
4424 shadows: &[BoxShadow],
4425 ) {
4426 self.invalidator.debug_assert_paint();
4427
4428 let scale_factor = self.scale_factor();
4429 let content_mask = self.snapped_content_mask();
4430 let opacity = self.element_opacity();
4431 let element_bounds = self.cover_bounds(bounds);
4432 let element_corner_radii = corner_radii.scale(scale_factor);
4433 for shadow in shadows {
4434 if !shadow.inset {
4435 continue;
4436 }
4437 let hole = (bounds + shadow.offset).dilate(-shadow.spread_radius);
4438 let zero = Pixels::ZERO;
4441 let hole_corner_radii = Corners {
4442 top_left: (corner_radii.top_left - shadow.spread_radius).max(zero),
4443 top_right: (corner_radii.top_right - shadow.spread_radius).max(zero),
4444 bottom_right: (corner_radii.bottom_right - shadow.spread_radius).max(zero),
4445 bottom_left: (corner_radii.bottom_left - shadow.spread_radius).max(zero),
4446 };
4447 self.next_frame.scene.insert_primitive(Shadow {
4448 order: 0,
4449 blur_radius: shadow.blur_radius.scale(scale_factor),
4450 bounds: self.cover_bounds(hole),
4451 content_mask,
4452 corner_radii: hole_corner_radii.scale(scale_factor),
4453 color: shadow.color.opacity(opacity),
4454 element_bounds,
4455 element_corner_radii,
4456 inset: 1,
4457 pad: 0,
4458 });
4459 }
4460 }
4461
4462 fn largest_border_interior(quad: &Quad) -> Bounds<ScaledPixels> {
4463 let radii = &quad.corner_radii;
4464 let widths = &quad.border_widths;
4465 let edge_radii = Edges {
4466 top: radii.top_left.max(radii.top_right),
4467 right: radii.top_right.max(radii.bottom_right),
4468 bottom: radii.bottom_left.max(radii.bottom_right),
4469 left: radii.top_left.max(radii.bottom_left),
4470 };
4471
4472 let antialias_inset = point(ScaledPixels(1.0), ScaledPixels(1.0));
4473 let inset_bounds = |top_left_inset, bottom_right_inset| {
4474 Bounds::from_corners(
4475 quad.bounds.origin + top_left_inset + antialias_inset,
4476 quad.bounds.bottom_right() - bottom_right_inset - antialias_inset,
4477 )
4478 };
4479
4480 let horizontal_band = inset_bounds(
4483 point(widths.left, widths.top.max(edge_radii.top)),
4484 point(widths.right, widths.bottom.max(edge_radii.bottom)),
4485 );
4486 let vertical_band = inset_bounds(
4487 point(widths.left.max(edge_radii.left), widths.top),
4488 point(widths.right.max(edge_radii.right), widths.bottom),
4489 );
4490
4491 let area = |bounds: &Bounds<ScaledPixels>| {
4492 bounds.size.width.0.max(0.) * bounds.size.height.0.max(0.)
4493 };
4494 if area(&horizontal_band) >= area(&vertical_band) {
4495 horizontal_band
4496 } else {
4497 vertical_band
4498 }
4499 }
4500
4501 pub fn paint_quad(&mut self, quad: PaintQuad) {
4511 self.invalidator.debug_assert_paint();
4512
4513 let opacity = self.element_opacity();
4514 let snapped_bounds = self.snap_bounds(quad.bounds);
4515 let snapped_border_widths = self.snap_border_widths(quad.border_widths);
4516 let quad = Quad {
4517 order: 0,
4518 bounds: snapped_bounds,
4519 content_mask: self.snapped_content_mask(),
4520 background: quad.background.opacity(opacity),
4521 border_color: quad.border_color.opacity(opacity),
4522 corner_radii: quad.corner_radii.scale(self.scale_factor()),
4523 border_widths: snapped_border_widths,
4524 border_style: quad.border_style,
4525 };
4526
4527 if !quad.background.is_transparent() {
4528 self.next_frame.scene.insert_primitive(quad);
4529 return;
4530 }
4531
4532 let outer_bounds = quad.bounds;
4535 let inner_bounds = Self::largest_border_interior(&quad);
4536
4537 if inner_bounds.is_empty() {
4538 self.next_frame.scene.insert_primitive(quad);
4539 return;
4540 }
4541
4542 let strips = [
4543 Bounds::from_corners(
4545 outer_bounds.origin,
4546 point(outer_bounds.right(), inner_bounds.top()),
4547 ),
4548 Bounds::from_corners(
4550 point(outer_bounds.left(), inner_bounds.bottom()),
4551 outer_bounds.bottom_right(),
4552 ),
4553 Bounds::from_corners(
4555 point(outer_bounds.left(), inner_bounds.top()),
4556 inner_bounds.bottom_left(),
4557 ),
4558 Bounds::from_corners(
4560 inner_bounds.top_right(),
4561 point(outer_bounds.right(), inner_bounds.bottom()),
4562 ),
4563 ];
4564
4565 for strip in strips {
4566 let content_mask_bounds = quad.content_mask.bounds.intersect(&strip);
4567 if !content_mask_bounds.is_empty() {
4568 self.next_frame.scene.insert_primitive(Quad {
4569 content_mask: ContentMask {
4570 bounds: content_mask_bounds,
4571 },
4572 ..quad
4573 });
4574 }
4575 }
4576 }
4577
4578 pub fn paint_path(&mut self, mut path: Path<Pixels>, color: impl Into<Background>) {
4582 self.invalidator.debug_assert_paint();
4583
4584 let scale_factor = self.scale_factor();
4585 let content_mask = self.content_mask();
4586 let opacity = self.element_opacity();
4587 path.content_mask = content_mask;
4588 let color: Background = color.into();
4589 path.color = color.opacity(opacity);
4590 self.next_frame
4591 .scene
4592 .insert_primitive(path.scale(scale_factor));
4593 }
4594
4595 pub fn paint_path_scaled(&mut self, path: &Path<ScaledPixels>, color: impl Into<Background>) {
4602 self.paint_path_scaled_at(path, point(px(0.), px(0.)), color);
4603 }
4604
4605 pub fn paint_path_scaled_at(
4612 &mut self,
4613 path: &Path<ScaledPixels>,
4614 origin: Point<Pixels>,
4615 color: impl Into<Background>,
4616 ) {
4617 self.invalidator.debug_assert_paint();
4618
4619 let scale_factor = self.scale_factor();
4620 let content_mask = self.content_mask();
4621 let opacity = self.element_opacity();
4622 let mut path = path.clone();
4623 path.content_mask = content_mask.scale(scale_factor);
4624 let color: Background = color.into();
4625 path.color = color.opacity(opacity);
4626 let origin = origin.scale(scale_factor);
4627 path.bounds.origin += origin;
4628 path.origin += origin;
4629 self.next_frame.scene.insert_primitive(path);
4630 }
4631
4632 pub fn paint_underline(
4636 &mut self,
4637 origin: Point<Pixels>,
4638 width: Pixels,
4639 style: &UnderlineStyle,
4640 ) {
4641 self.invalidator.debug_assert_paint();
4642 let underline = self.underline(origin, width, style);
4643 self.next_frame.scene.insert_primitive(underline);
4644 }
4645
4646 pub fn paint_strikethrough(
4650 &mut self,
4651 origin: Point<Pixels>,
4652 width: Pixels,
4653 style: &StrikethroughStyle,
4654 ) {
4655 self.invalidator.debug_assert_paint();
4656
4657 let scale_factor = self.scale_factor();
4658 let height = style.thickness;
4659 let bounds = Bounds {
4660 origin: origin.map(|c| ScaledPixels(round_to_device_pixel(c.0, scale_factor))),
4661 size: size(self.snap_stroke(width), self.snap_stroke(height)),
4662 };
4663 let opacity = self.element_opacity();
4664
4665 self.next_frame.scene.insert_primitive(Underline {
4666 order: 0,
4667 pad: 0,
4668 bounds,
4669 content_mask: self.snapped_content_mask(),
4670 thickness: self.snap_stroke(style.thickness),
4671 color: style.color.unwrap_or_default().opacity(opacity),
4672 wavy: false.into(),
4673 });
4674 }
4675
4676 pub fn paint_glyph(
4685 &mut self,
4686 origin: Point<Pixels>,
4687 font_id: FontId,
4688 glyph_id: GlyphId,
4689 font_size: Pixels,
4690 color: Hsla,
4691 ) -> Result<()> {
4692 self.invalidator.debug_assert_paint();
4693
4694 let element_opacity = self.element_opacity();
4695 let scale_factor = self.scale_factor();
4696 let glyph_origin = origin.scale(scale_factor);
4697
4698 let quantized_origin = Point::new(
4699 round_half_toward_zero(glyph_origin.x.0 * SUBPIXEL_VARIANTS_X as f32)
4700 / SUBPIXEL_VARIANTS_X as f32,
4701 round_half_toward_zero(glyph_origin.y.0 * SUBPIXEL_VARIANTS_Y as f32)
4702 / SUBPIXEL_VARIANTS_Y as f32,
4703 );
4704 let subpixel_variant = Point::new(
4705 (quantized_origin.x.fract() * SUBPIXEL_VARIANTS_X as f32) as u8,
4706 (quantized_origin.y.fract() * SUBPIXEL_VARIANTS_Y as f32) as u8,
4707 );
4708 let integer_origin = quantized_origin.map(|c| ScaledPixels(c.trunc()));
4709 let subpixel_rendering = self.should_use_subpixel_rendering(font_id, font_size);
4710 let dilation = self.text_system().glyph_dilation_for_color(color);
4711 let params = RenderGlyphParams {
4712 font_id,
4713 glyph_id,
4714 font_size,
4715 subpixel_variant,
4716 scale_factor,
4717 is_emoji: false,
4718 subpixel_rendering,
4719 dilation,
4720 };
4721
4722 let raster_bounds = self.text_system().raster_bounds(¶ms)?;
4723 if !raster_bounds.is_zero() {
4724 let tile = self
4725 .sprite_atlas
4726 .get_or_insert_with(params.clone().into(), &mut || {
4727 let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?;
4728 Ok(Some((size, Cow::Owned(bytes))))
4729 })?
4730 .expect("Callback above only errors or returns Some");
4731 let bounds = Bounds {
4732 origin: integer_origin + raster_bounds.origin.map(Into::into),
4733 size: tile.bounds.size.map(Into::into),
4734 };
4735 let content_mask = self.snapped_content_mask();
4736
4737 if subpixel_rendering {
4738 self.next_frame.scene.insert_primitive(SubpixelSprite {
4739 order: 0,
4740 pad: 0,
4741 bounds,
4742 content_mask,
4743 color: color.opacity(element_opacity),
4744 tile,
4745 transformation: TransformationMatrix::unit(),
4746 });
4747 } else {
4748 self.next_frame.scene.insert_primitive(MonochromeSprite {
4749 order: 0,
4750 pad: 0,
4751 bounds,
4752 content_mask,
4753 color: color.opacity(element_opacity),
4754 tile,
4755 transformation: TransformationMatrix::unit(),
4756 });
4757 }
4758 }
4759 Ok(())
4760 }
4761
4762 fn should_use_subpixel_rendering(&self, font_id: FontId, font_size: Pixels) -> bool {
4763 if self.platform_window.background_appearance() != WindowBackgroundAppearance::Opaque {
4764 return false;
4765 }
4766
4767 if !self.platform_window.is_subpixel_rendering_supported() {
4768 return false;
4769 }
4770
4771 let mode = match self.text_rendering_mode.get() {
4772 TextRenderingMode::PlatformDefault => self
4773 .text_system()
4774 .recommended_rendering_mode(font_id, font_size),
4775 mode => mode,
4776 };
4777
4778 mode == TextRenderingMode::Subpixel
4779 }
4780
4781 pub fn paint_emoji(
4790 &mut self,
4791 origin: Point<Pixels>,
4792 font_id: FontId,
4793 glyph_id: GlyphId,
4794 font_size: Pixels,
4795 ) -> Result<()> {
4796 self.invalidator.debug_assert_paint();
4797
4798 let scale_factor = self.scale_factor();
4799 let glyph_origin = origin.scale(scale_factor);
4800 let integer_origin = glyph_origin.map(|c| ScaledPixels(round_half_toward_zero(c.0)));
4801 let params = RenderGlyphParams {
4802 font_id,
4803 glyph_id,
4804 font_size,
4805 subpixel_variant: Default::default(),
4806 scale_factor,
4807 is_emoji: true,
4808 subpixel_rendering: false,
4809 dilation: 0,
4810 };
4811
4812 let raster_bounds = self.text_system().raster_bounds(¶ms)?;
4813 if !raster_bounds.is_zero() {
4814 let tile = self
4815 .sprite_atlas
4816 .get_or_insert_with(params.clone().into(), &mut || {
4817 let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?;
4818 Ok(Some((size, Cow::Owned(bytes))))
4819 })?
4820 .expect("Callback above only errors or returns Some");
4821
4822 let bounds = Bounds {
4823 origin: integer_origin + raster_bounds.origin.map(Into::into),
4824 size: tile.bounds.size.map(Into::into),
4825 };
4826 let content_mask = self.snapped_content_mask();
4827 let opacity = self.element_opacity();
4828
4829 self.next_frame.scene.insert_primitive(PolychromeSprite {
4830 order: 0,
4831 pad: 0,
4832 grayscale: false.into(),
4833 bounds,
4834 corner_radii: Default::default(),
4835 content_mask,
4836 tile,
4837 opacity,
4838 });
4839 }
4840 Ok(())
4841 }
4842
4843 pub fn paint_svg(
4847 &mut self,
4848 bounds: Bounds<Pixels>,
4849 path: SharedString,
4850 mut data: Option<&[u8]>,
4851 transformation: TransformationMatrix,
4852 color: Hsla,
4853 cx: &App,
4854 ) -> Result<()> {
4855 self.invalidator.debug_assert_paint();
4856
4857 let element_opacity = self.element_opacity();
4858 let bounds = self.snap_bounds(bounds);
4859
4860 let params = RenderSvgParams {
4861 path,
4862 size: bounds.size.map(|pixels| {
4863 DevicePixels::from((pixels.0 * SMOOTH_SVG_SCALE_FACTOR).ceil() as i32)
4864 }),
4865 };
4866
4867 let Some(tile) =
4868 self.sprite_atlas
4869 .get_or_insert_with(params.clone().into(), &mut || {
4870 let Some((size, bytes)) = cx.svg_renderer.render_alpha_mask(¶ms, data)?
4871 else {
4872 return Ok(None);
4873 };
4874 Ok(Some((size, Cow::Owned(bytes))))
4875 })?
4876 else {
4877 return Ok(());
4878 };
4879 let content_mask = self.snapped_content_mask();
4880 let svg_bounds = Bounds {
4881 origin: bounds.center()
4882 - Point::new(
4883 ScaledPixels(tile.bounds.size.width.0 as f32 / SMOOTH_SVG_SCALE_FACTOR / 2.),
4884 ScaledPixels(tile.bounds.size.height.0 as f32 / SMOOTH_SVG_SCALE_FACTOR / 2.),
4885 ),
4886 size: tile
4887 .bounds
4888 .size
4889 .map(|value| ScaledPixels(value.0 as f32 / SMOOTH_SVG_SCALE_FACTOR)),
4890 };
4891 let final_bounds = svg_bounds
4892 .map_origin(|value| ScaledPixels(round_half_toward_zero(value.0)))
4893 .map_size(|size| size.ceil());
4894
4895 self.next_frame.scene.insert_primitive(MonochromeSprite {
4896 order: 0,
4897 pad: 0,
4898 bounds: final_bounds,
4899 content_mask,
4900 color: color.opacity(element_opacity),
4901 tile,
4902 transformation,
4903 });
4904
4905 Ok(())
4906 }
4907
4908 pub fn paint_image(
4917 &mut self,
4918 bounds: Bounds<Pixels>,
4919 image_bounds: Bounds<Pixels>,
4920 corner_radii: Corners<Pixels>,
4921 data: Arc<RenderImage>,
4922 frame_index: usize,
4923 grayscale: bool,
4924 ) -> Result<()> {
4925 self.invalidator.debug_assert_paint();
4926
4927 let visible_bounds = bounds.intersect(&image_bounds);
4928 if visible_bounds.size.width <= Pixels::ZERO || visible_bounds.size.height <= Pixels::ZERO {
4929 return Ok(());
4930 }
4931 if image_bounds.size.width <= Pixels::ZERO || image_bounds.size.height <= Pixels::ZERO {
4932 return Ok(());
4933 }
4934
4935 let params = RenderImageParams {
4936 image_id: data.id,
4937 frame_index,
4938 };
4939
4940 let tile = self
4941 .sprite_atlas
4942 .get_or_insert_with(params.into(), &mut || {
4943 Ok(Some((
4944 data.size(frame_index),
4945 Cow::Borrowed(
4946 data.as_bytes(frame_index)
4947 .expect("It's the caller's job to pass a valid frame index"),
4948 ),
4949 )))
4950 })?
4951 .expect("Callback above only returns Some");
4952
4953 let visible_bounds_snapped = self.snap_bounds(visible_bounds);
4954
4955 let sub_tile = if visible_bounds == image_bounds {
4956 tile
4957 } else {
4958 let x_offset_ratio =
4959 (visible_bounds.origin.x - image_bounds.origin.x) / image_bounds.size.width;
4960 let y_offset_ratio =
4961 (visible_bounds.origin.y - image_bounds.origin.y) / image_bounds.size.height;
4962 let width_ratio = visible_bounds.size.width / image_bounds.size.width;
4963 let height_ratio = visible_bounds.size.height / image_bounds.size.height;
4964
4965 let tile_origin_x = tile.bounds.origin.x.0;
4966 let tile_origin_y = tile.bounds.origin.y.0;
4967 let tile_width = tile.bounds.size.width.0;
4968 let tile_height = tile.bounds.size.height.0;
4969
4970 let sub_origin_x = tile_origin_x + (x_offset_ratio * tile_width as f32).round() as i32;
4971 let sub_origin_y = tile_origin_y + (y_offset_ratio * tile_height as f32).round() as i32;
4972 let sub_width = (width_ratio * tile_width as f32).round() as i32;
4973 let sub_height = (height_ratio * tile_height as f32).round() as i32;
4974
4975 let max_x = tile_origin_x + tile_width;
4976 let max_y = tile_origin_y + tile_height;
4977
4978 let clamped_origin_x = sub_origin_x.clamp(tile_origin_x, max_x);
4979 let clamped_origin_y = sub_origin_y.clamp(tile_origin_y, max_y);
4980 let clamped_width = sub_width.min(max_x - clamped_origin_x).max(0);
4981 let clamped_height = sub_height.min(max_y - clamped_origin_y).max(0);
4982
4983 AtlasTile {
4984 bounds: Bounds {
4985 origin: point(
4986 DevicePixels(clamped_origin_x),
4987 DevicePixels(clamped_origin_y),
4988 ),
4989 size: size(DevicePixels(clamped_width), DevicePixels(clamped_height)),
4990 },
4991 ..tile
4992 }
4993 };
4994
4995 let content_mask = self.snapped_content_mask();
4996 let corner_radii = corner_radii
4997 .clamp_radii_for_quad_size(visible_bounds.size)
4998 .scale(self.scale_factor());
4999 let opacity = self.element_opacity();
5000
5001 self.next_frame.scene.insert_primitive(PolychromeSprite {
5002 order: 0,
5003 pad: 0,
5004 grayscale: grayscale.into(),
5005 bounds: visible_bounds_snapped,
5006 content_mask,
5007 corner_radii,
5008 tile: sub_tile,
5009 opacity,
5010 });
5011 Ok(())
5012 }
5013
5014 #[cfg(target_os = "macos")]
5018 pub fn paint_surface(&mut self, bounds: Bounds<Pixels>, image_buffer: CVPixelBuffer) {
5019 use crate::PaintSurface;
5020
5021 self.invalidator.debug_assert_paint();
5022
5023 let bounds = self.snap_bounds(bounds);
5024 let content_mask = self.snapped_content_mask();
5025 self.next_frame.scene.insert_primitive(PaintSurface {
5026 order: 0,
5027 bounds,
5028 content_mask,
5029 image_buffer,
5030 });
5031 }
5032
5033 pub fn drop_image(&mut self, data: Arc<RenderImage>) -> Result<()> {
5035 for frame_index in 0..data.frame_count() {
5036 let params = RenderImageParams {
5037 image_id: data.id,
5038 frame_index,
5039 };
5040
5041 self.sprite_atlas.remove(¶ms.clone().into());
5042 }
5043
5044 Ok(())
5045 }
5046
5047 #[cfg(any(test, feature = "test-support"))]
5049 pub fn has_image_atlas_entry(&self, data: &RenderImage) -> bool {
5050 data.frame_count() > 0
5051 && (0..data.frame_count()).all(|frame_index| {
5052 self.sprite_atlas.contains(
5053 &RenderImageParams {
5054 image_id: data.id,
5055 frame_index,
5056 }
5057 .into(),
5058 )
5059 })
5060 }
5061
5062 #[must_use]
5068 pub fn request_layout(
5069 &mut self,
5070 style: Style,
5071 children: impl IntoIterator<Item = LayoutId>,
5072 cx: &mut App,
5073 ) -> LayoutId {
5074 self.invalidator.debug_assert_prepaint();
5075
5076 cx.layout_id_buffer.clear();
5077 cx.layout_id_buffer.extend(children);
5078 let rem_size = self.rem_size();
5079 let scale_factor = self.scale_factor();
5080
5081 self.layout_engine.as_mut().unwrap().request_layout(
5082 style,
5083 rem_size,
5084 scale_factor,
5085 &cx.layout_id_buffer,
5086 )
5087 }
5088
5089 pub fn request_measured_layout<F>(&mut self, style: Style, measure: F) -> LayoutId
5098 where
5099 F: Fn(Size<Option<Pixels>>, Size<AvailableSpace>, &mut Window, &mut App) -> Size<Pixels>
5100 + 'static,
5101 {
5102 self.invalidator.debug_assert_prepaint();
5103
5104 let rem_size = self.rem_size();
5105 let scale_factor = self.scale_factor();
5106 self.layout_engine
5107 .as_mut()
5108 .unwrap()
5109 .request_measured_layout(style, rem_size, scale_factor, measure)
5110 }
5111
5112 pub fn compute_layout(
5118 &mut self,
5119 layout_id: LayoutId,
5120 available_space: Size<AvailableSpace>,
5121 cx: &mut App,
5122 ) {
5123 self.invalidator.debug_assert_prepaint();
5124
5125 let mut layout_engine = self.layout_engine.take().unwrap();
5126 layout_engine.compute_layout(layout_id, available_space, self, cx);
5127 self.layout_engine = Some(layout_engine);
5128 }
5129
5130 pub fn layout_bounds(&mut self, layout_id: LayoutId) -> Bounds<Pixels> {
5135 self.invalidator.debug_assert_prepaint();
5136
5137 let scale_factor = self.scale_factor();
5138 let mut bounds = self
5139 .layout_engine
5140 .as_mut()
5141 .unwrap()
5142 .layout_bounds(layout_id, scale_factor)
5143 .map(Into::into);
5144 let snapped_offset = self.pixel_snap_point(self.element_offset());
5145 bounds.origin += snapped_offset;
5146 bounds
5147 }
5148
5149 pub fn insert_hitbox(&mut self, bounds: Bounds<Pixels>, behavior: HitboxBehavior) -> Hitbox {
5155 self.invalidator.debug_assert_prepaint();
5156
5157 let content_mask = self.content_mask();
5158 let mut id = self.next_hitbox_id;
5159 self.next_hitbox_id = self.next_hitbox_id.next();
5160 let hitbox = Hitbox {
5161 id,
5162 bounds,
5163 content_mask,
5164 behavior,
5165 };
5166 self.next_frame.hitboxes.push(hitbox.clone());
5167 hitbox
5168 }
5169
5170 pub fn insert_window_control_hitbox(&mut self, area: WindowControlArea, hitbox: Hitbox) {
5174 self.invalidator.debug_assert_paint();
5175 self.next_frame.window_control_hitboxes.push((area, hitbox));
5176 }
5177
5178 pub fn set_key_context(&mut self, context: KeyContext) {
5183 self.invalidator.debug_assert_paint();
5184 self.next_frame.dispatch_tree.set_key_context(context);
5185 }
5186
5187 pub fn set_focus_handle(&mut self, focus_handle: &FocusHandle, _: &App) {
5192 self.invalidator.debug_assert_prepaint();
5193 if focus_handle.is_focused(self) {
5194 self.next_frame.focus = Some(focus_handle.id);
5195 }
5196 self.next_frame.dispatch_tree.set_focus_id(focus_handle.id);
5197 }
5198
5199 pub fn set_view_id(&mut self, view_id: EntityId) {
5205 self.invalidator.debug_assert_prepaint();
5206 self.next_frame.dispatch_tree.set_view_id(view_id);
5207 }
5208
5209 pub fn current_view(&self) -> EntityId {
5211 self.invalidator.debug_assert_paint_or_prepaint();
5212 self.rendered_entity_stack.last().copied().unwrap()
5213 }
5214
5215 #[inline]
5216 pub(crate) fn with_rendered_view<R>(
5217 &mut self,
5218 id: EntityId,
5219 f: impl FnOnce(&mut Self) -> R,
5220 ) -> R {
5221 self.rendered_entity_stack.push(id);
5222 let result = f(self);
5223 self.rendered_entity_stack.pop();
5224 result
5225 }
5226
5227 pub fn with_image_cache<F, R>(&mut self, image_cache: Option<AnyImageCache>, f: F) -> R
5229 where
5230 F: FnOnce(&mut Self) -> R,
5231 {
5232 if let Some(image_cache) = image_cache {
5233 self.image_cache_stack.push(image_cache);
5234 let result = f(self);
5235 self.image_cache_stack.pop();
5236 result
5237 } else {
5238 f(self)
5239 }
5240 }
5241
5242 pub fn handle_input(
5251 &mut self,
5252 focus_handle: &FocusHandle,
5253 input_handler: impl InputHandler,
5254 cx: &App,
5255 ) {
5256 self.invalidator.debug_assert_paint();
5257
5258 if focus_handle.is_focused(self) {
5259 let cx = self.to_async(cx);
5260 self.next_frame
5261 .input_handlers
5262 .push(Some(PlatformInputHandler::new(cx, Box::new(input_handler))));
5263 }
5264 }
5265
5266 fn apply_text_input_configuration(&mut self, cx: &mut App) {
5271 let configuration = match self.platform_window.take_input_handler() {
5272 Some(mut input_handler) => {
5273 let configuration = input_handler.text_input_configuration(self, cx);
5274 self.platform_window.set_input_handler(input_handler);
5275 configuration
5276 }
5277 None => TextInputConfiguration::default(),
5278 };
5279 if self.last_text_input_configuration.as_ref() != Some(&configuration) {
5280 self.platform_window
5281 .set_text_input_configuration(configuration.clone());
5282 self.last_text_input_configuration = Some(configuration);
5283 }
5284 }
5285
5286 pub fn on_mouse_event<Event: MouseEvent>(
5292 &mut self,
5293 mut listener: impl FnMut(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
5294 ) {
5295 self.invalidator.debug_assert_paint();
5296
5297 self.next_frame.mouse_listeners.push(Some(Box::new(
5298 move |event: &dyn Any, phase: DispatchPhase, window: &mut Window, cx: &mut App| {
5299 if let Some(event) = event.downcast_ref() {
5300 listener(event, phase, window, cx)
5301 }
5302 },
5303 )));
5304 }
5305
5306 pub fn on_key_event<Event: KeyEvent>(
5315 &mut self,
5316 listener: impl Fn(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
5317 ) {
5318 self.invalidator.debug_assert_paint();
5319
5320 self.next_frame.dispatch_tree.on_key_event(Rc::new(
5321 move |event: &dyn Any, phase, window: &mut Window, cx: &mut App| {
5322 if let Some(event) = event.downcast_ref::<Event>() {
5323 listener(event, phase, window, cx)
5324 }
5325 },
5326 ));
5327 }
5328
5329 pub fn on_modifiers_changed(
5336 &mut self,
5337 listener: impl Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static,
5338 ) {
5339 self.invalidator.debug_assert_paint();
5340
5341 self.next_frame.dispatch_tree.on_modifiers_changed(Rc::new(
5342 move |event: &ModifiersChangedEvent, window: &mut Window, cx: &mut App| {
5343 listener(event, window, cx)
5344 },
5345 ));
5346 }
5347
5348 pub fn on_focus_in(
5352 &mut self,
5353 handle: &FocusHandle,
5354 cx: &mut App,
5355 mut listener: impl FnMut(&mut Window, &mut App) + 'static,
5356 ) -> Subscription {
5357 let focus_id = handle.id;
5358 let (subscription, activate) =
5359 self.new_focus_listener(Box::new(move |event, window, cx| {
5360 if event.is_focus_in(focus_id) {
5361 listener(window, cx);
5362 }
5363 true
5364 }));
5365 cx.defer(move |_| activate());
5366 subscription
5367 }
5368
5369 pub fn on_focus_out(
5372 &mut self,
5373 handle: &FocusHandle,
5374 cx: &mut App,
5375 mut listener: impl FnMut(FocusOutEvent, &mut Window, &mut App) + 'static,
5376 ) -> Subscription {
5377 let focus_id = handle.id;
5378 let (subscription, activate) =
5379 self.new_focus_listener(Box::new(move |event, window, cx| {
5380 if let Some(blurred_id) = event.previous_focus_path.last().copied()
5381 && event.is_focus_out(focus_id)
5382 {
5383 let event = FocusOutEvent {
5384 blurred: WeakFocusHandle {
5385 id: blurred_id,
5386 handles: Arc::downgrade(&cx.focus_handles),
5387 },
5388 };
5389 listener(event, window, cx)
5390 }
5391 true
5392 }));
5393 cx.defer(move |_| activate());
5394 subscription
5395 }
5396
5397 fn reset_cursor_style(&self, cx: &mut App) {
5398 if self.is_window_hovered() {
5400 let style = self
5401 .rendered_frame
5402 .cursor_style(self)
5403 .unwrap_or(CursorStyle::Arrow);
5404 cx.platform.set_cursor_style(style);
5405 }
5406 }
5407
5408 pub fn dispatch_keystroke(&mut self, keystroke: Keystroke, cx: &mut App) -> bool {
5411 let keystroke = keystroke.with_simulated_ime();
5412 let result = self.dispatch_event(
5413 PlatformInput::KeyDown(KeyDownEvent {
5414 keystroke: keystroke.clone(),
5415 is_held: false,
5416 prefer_character_input: false,
5417 }),
5418 cx,
5419 );
5420 if !result.propagate {
5421 return true;
5422 }
5423
5424 if let Some(input) = keystroke.key_char
5425 && let Some(mut input_handler) = self.platform_window.take_input_handler()
5426 {
5427 input_handler.dispatch_input(&input, self, cx);
5428 self.platform_window.set_input_handler(input_handler);
5429 return true;
5430 }
5431
5432 false
5433 }
5434
5435 pub fn keystroke_text_for(&self, action: &dyn Action) -> String {
5438 self.highest_precedence_binding_for_action(action)
5439 .map(|binding| {
5440 binding
5441 .keystrokes()
5442 .iter()
5443 .map(ToString::to_string)
5444 .collect::<Vec<_>>()
5445 .join(" ")
5446 })
5447 .unwrap_or_else(|| action.name().to_string())
5448 }
5449
5450 #[profiling::function]
5452 pub fn dispatch_event(&mut self, event: PlatformInput, cx: &mut App) -> DispatchEventResult {
5453 #[cfg(feature = "profiler")]
5454 self.window_profiler.begin_input(event.kind_name());
5455 let update_count_before = self.invalidator.update_count();
5456 let old_modality = self.last_input_modality;
5460 self.last_input_modality = match &event {
5461 PlatformInput::KeyDown(_) => InputModality::Keyboard,
5462 PlatformInput::MouseMove(_) | PlatformInput::MouseDown(_) => InputModality::Mouse,
5463 PlatformInput::Touch(_) => InputModality::Touch,
5464 _ => self.last_input_modality,
5465 };
5466 if self.last_input_modality != old_modality {
5467 self.refresh();
5468 }
5469
5470 cx.propagate_event = true;
5472 self.default_prevented = false;
5474
5475 let event = match event {
5476 PlatformInput::MouseMove(mouse_move) => {
5479 self.mouse_position = mouse_move.position;
5480 self.modifiers = mouse_move.modifiers;
5481 PlatformInput::MouseMove(mouse_move)
5482 }
5483 PlatformInput::MouseDown(mouse_down) => {
5484 self.mouse_position = mouse_down.position;
5485 self.modifiers = mouse_down.modifiers;
5486 PlatformInput::MouseDown(mouse_down)
5487 }
5488 PlatformInput::MouseUp(mouse_up) => {
5489 self.mouse_position = mouse_up.position;
5490 self.modifiers = mouse_up.modifiers;
5491 PlatformInput::MouseUp(mouse_up)
5492 }
5493 PlatformInput::MousePressure(mouse_pressure) => {
5494 PlatformInput::MousePressure(mouse_pressure)
5495 }
5496 PlatformInput::MouseExited(mouse_exited) => {
5497 self.modifiers = mouse_exited.modifiers;
5498 PlatformInput::MouseExited(mouse_exited)
5499 }
5500 PlatformInput::ModifiersChanged(modifiers_changed) => {
5501 self.modifiers = modifiers_changed.modifiers;
5502 self.capslock = modifiers_changed.capslock;
5503 PlatformInput::ModifiersChanged(modifiers_changed)
5504 }
5505 PlatformInput::ScrollWheel(scroll_wheel) => {
5506 self.mouse_position = scroll_wheel.position;
5507 self.modifiers = scroll_wheel.modifiers;
5508 PlatformInput::ScrollWheel(scroll_wheel)
5509 }
5510 PlatformInput::Pinch(pinch) => {
5511 self.mouse_position = pinch.position;
5512 self.modifiers = pinch.modifiers;
5513 PlatformInput::Pinch(pinch)
5514 }
5515 PlatformInput::FileDrop(file_drop) => match file_drop {
5518 FileDropEvent::Entered { position, paths } => {
5519 self.mouse_position = position;
5520 let source_window = self.handle.window_id();
5521 if !cx.restore_platform_drag(source_window) && cx.active_drag.is_none() {
5522 cx.active_drag = Some(AnyDrag {
5523 value: Arc::new(paths.clone()),
5524 view: cx.new(|_| paths).into(),
5525 cursor_offset: position,
5526 cursor_style: None,
5527 external_payload_source: None,
5528 });
5529 }
5530 PlatformInput::MouseMove(MouseMoveEvent {
5531 position,
5532 pressed_button: Some(MouseButton::Left),
5533 modifiers: Modifiers::default(),
5534 })
5535 }
5536 FileDropEvent::Pending { position } => {
5537 self.mouse_position = position;
5538 PlatformInput::MouseMove(MouseMoveEvent {
5539 position,
5540 pressed_button: Some(MouseButton::Left),
5541 modifiers: Modifiers::default(),
5542 })
5543 }
5544 FileDropEvent::Submit { position } => {
5545 cx.activate(true);
5546 self.mouse_position = position;
5547 PlatformInput::MouseUp(MouseUpEvent {
5548 button: MouseButton::Left,
5549 position,
5550 modifiers: Modifiers::default(),
5551 click_count: 1,
5552 })
5553 }
5554 FileDropEvent::Exited => {
5555 if !cx.hand_restored_drag_to_platform(self.handle.window_id()) {
5556 cx.active_drag.take();
5557 }
5558 self.refresh();
5559 PlatformInput::FileDrop(FileDropEvent::Exited)
5560 }
5561 FileDropEvent::Ended => {
5562 cx.end_platform_drag(self.handle.window_id());
5563 self.refresh();
5564 PlatformInput::FileDrop(FileDropEvent::Ended)
5565 }
5566 },
5567 PlatformInput::Touch(touch) => PlatformInput::Touch(touch),
5568 PlatformInput::LongPress(long_press) => {
5569 self.mouse_position = if long_press.phase == crate::TouchPhase::Started {
5570 long_press.start_position
5571 } else {
5572 long_press.position
5573 };
5574 if long_press.phase == crate::TouchPhase::Started {
5575 self.long_press_capture = None;
5576 }
5577 PlatformInput::LongPress(long_press)
5578 }
5579 PlatformInput::TouchDrag(touch_drag) => {
5580 self.mouse_position = touch_drag.start_position;
5581 PlatformInput::TouchDrag(touch_drag)
5582 }
5583 PlatformInput::KeyDown(_) | PlatformInput::KeyUp(_) => event,
5584 };
5585
5586 if let Some(any_mouse_event) = event.mouse_event() {
5587 self.dispatch_mouse_event(any_mouse_event, cx);
5588 } else if let Some(any_key_event) = event.keyboard_event() {
5589 self.dispatch_key_event(any_key_event, cx);
5590 } else if let Some(touch_event) = event.touch_event() {
5591 self.dispatch_touch_event(touch_event, cx);
5592 }
5593 if let PlatformInput::LongPress(long_press) = &event {
5594 match long_press.phase {
5595 crate::TouchPhase::Started if !self.default_prevented => {
5596 self.long_press_capture = None;
5597 }
5598 crate::TouchPhase::Ended | crate::TouchPhase::Cancelled => {
5599 self.long_press_capture = None;
5600 }
5601 crate::TouchPhase::Started | crate::TouchPhase::Moved => {}
5602 }
5603 }
5604
5605 self.promote_external_drag_to_platform(&event, cx);
5608
5609 let caused_invalidation = self.invalidator.update_count() > update_count_before;
5610 if caused_invalidation {
5611 self.input_rate_tracker.borrow_mut().record_input();
5612 }
5613 #[cfg(feature = "profiler")]
5614 self.window_profiler.end_input(caused_invalidation);
5615
5616 DispatchEventResult {
5617 propagate: cx.propagate_event,
5618 default_prevented: self.default_prevented,
5619 }
5620 }
5621
5622 fn promote_external_drag_to_platform(&mut self, event: &PlatformInput, cx: &mut App) {
5623 let PlatformInput::MouseMove(mouse_move) = event else {
5624 return;
5625 };
5626 if mouse_move.pressed_button != Some(MouseButton::Left) {
5627 return;
5628 }
5629 if Bounds::new(Point::default(), self.viewport_size).contains(&mouse_move.position) {
5630 return;
5631 }
5632 if !self.platform_window.can_start_external_drag() {
5633 return;
5634 }
5635 let Some(payload_source) = cx
5636 .active_drag
5637 .as_mut()
5638 .and_then(|drag| drag.external_payload_source.take())
5639 else {
5640 return;
5641 };
5642 let Some(payload) = payload_source(self, cx) else {
5643 return;
5644 };
5645 if self.platform_window.start_external_drag(&payload)
5646 && cx.hand_active_drag_to_platform(self.handle.window_id())
5647 {
5648 self.refresh();
5649 }
5650 }
5651
5652 pub fn touch_prediction_enabled(&self) -> bool {
5656 self.touch_prediction_enabled
5657 }
5658
5659 pub fn set_touch_prediction_enabled(&mut self, enabled: bool) {
5663 self.touch_prediction_enabled = enabled;
5664 }
5665
5666 fn dispatch_touch_event(&mut self, event: &TouchEvent, cx: &mut App) {
5670 let mut event = event.clone();
5671 if !self.touch_prediction_enabled {
5672 event.predicted_position = None;
5673 }
5674 let recognized_gestures = self.touch_gestures.handle_event(&event);
5675 if event.phase == crate::TouchPhase::Started
5676 && let Some(touch_drag) = self.touch_gestures.offer_touch_drag(event.id)
5677 {
5678 self.dispatch_recognized_touch_gesture(touch_drag, cx);
5679 }
5680 if event.phase == crate::TouchPhase::Started
5681 && self.touch_gestures.pending_long_press().is_some()
5682 {
5683 self.long_press_capture = None;
5684 }
5685 let mut tapped = false;
5686 for gesture in recognized_gestures {
5687 tapped |= matches!(gesture, RecognizedTouchGesture::Tap { .. });
5688 self.dispatch_recognized_touch_gesture(gesture, cx);
5689 }
5690 if event.phase == crate::TouchPhase::Started {
5691 self.schedule_long_press_timer(cx);
5692 } else if self.touch_gestures.pending_long_press().is_none() {
5693 self.long_press_timer.take();
5694 }
5695 if tapped && self.invalidator.is_dirty() {
5701 self.draw(cx).clear(cx);
5702 }
5703 if self.touch_gestures.has_momentum() {
5704 self.schedule_touch_momentum_tick();
5705 }
5706 }
5707
5708 fn dispatch_recognized_touch_gesture(&mut self, gesture: RecognizedTouchGesture, cx: &mut App) {
5709 match gesture {
5710 RecognizedTouchGesture::Scroll(scroll_wheel) => {
5711 self.mouse_position = scroll_wheel.position;
5712 cx.propagate_event = true;
5713 self.dispatch_mouse_event(&scroll_wheel, cx);
5714 }
5715 RecognizedTouchGesture::Tap { down, up } => {
5716 self.mouse_position = up.position;
5717 cx.propagate_event = true;
5718 self.dispatch_mouse_event(&down, cx);
5719 cx.propagate_event = true;
5720 self.dispatch_mouse_event(&up, cx);
5721 }
5722 RecognizedTouchGesture::TouchDrag(touch_drag) => {
5723 self.mouse_position = touch_drag.start_position;
5724 cx.propagate_event = true;
5725 self.default_prevented = false;
5726 let started = touch_drag.phase == crate::TouchPhase::Started;
5727 self.dispatch_mouse_event(&touch_drag, cx);
5728 if started {
5729 self.touch_gestures
5730 .resolve_touch_drag(self.default_prevented);
5731 }
5732 }
5733 RecognizedTouchGesture::LongPress(long_press) => {
5734 self.mouse_position = if long_press.phase == crate::TouchPhase::Started {
5735 long_press.start_position
5736 } else {
5737 long_press.position
5738 };
5739 cx.propagate_event = true;
5740 self.default_prevented = false;
5741 let started = long_press.phase == crate::TouchPhase::Started;
5742 let ended = matches!(
5743 long_press.phase,
5744 crate::TouchPhase::Ended | crate::TouchPhase::Cancelled
5745 );
5746 self.dispatch_mouse_event(&long_press, cx);
5747 if started {
5748 let claimed = self.default_prevented;
5749 self.touch_gestures.resolve_long_press(claimed);
5750 if !claimed {
5751 self.long_press_capture = None;
5752 }
5753 }
5754 if ended {
5755 self.long_press_capture = None;
5756 }
5757 }
5758 }
5759 }
5760
5761 fn schedule_long_press_timer(&mut self, cx: &mut App) {
5762 self.long_press_timer.take();
5763 let Some((touch_id, duration)) = self.touch_gestures.pending_long_press() else {
5764 return;
5765 };
5766 self.long_press_timer = Some(self.spawn(cx, async move |cx| {
5767 cx.background_executor.timer(duration).await;
5768 cx.update(move |window, cx| {
5769 window.long_press_timer.take();
5770 if let Some(gesture) = window.touch_gestures.offer_long_press(touch_id) {
5771 window.dispatch_recognized_touch_gesture(gesture, cx);
5772 }
5773 })
5774 .log_err();
5775 }));
5776 }
5777
5778 fn schedule_touch_momentum_tick(&mut self) {
5779 self.on_next_frame(|window, cx| {
5780 if let Some(gesture) = window.touch_gestures.tick_momentum() {
5781 window.dispatch_recognized_touch_gesture(gesture, cx);
5782 }
5783 if window.touch_gestures.has_momentum() {
5784 window.schedule_touch_momentum_tick();
5785 }
5786 });
5787 }
5788
5789 fn dispatch_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
5790 let hit_test = self.rendered_frame.hit_test(self.mouse_position());
5791 if hit_test != self.mouse_hit_test {
5792 self.mouse_hit_test = hit_test;
5793 self.reset_cursor_style(cx);
5794 }
5795
5796 #[cfg(any(feature = "inspector", debug_assertions))]
5797 if self.is_inspector_picking(cx) {
5798 self.handle_inspector_mouse_event(event, cx);
5799 return;
5801 }
5802
5803 let mut mouse_listeners = mem::take(&mut self.rendered_frame.mouse_listeners);
5804
5805 for listener in &mut mouse_listeners {
5808 let listener = listener.as_mut().unwrap();
5809 listener(event, DispatchPhase::Capture, self, cx);
5810 if !cx.propagate_event {
5811 break;
5812 }
5813 }
5814
5815 if cx.propagate_event {
5817 for listener in mouse_listeners.iter_mut().rev() {
5818 let listener = listener.as_mut().unwrap();
5819 listener(event, DispatchPhase::Bubble, self, cx);
5820 if !cx.propagate_event {
5821 break;
5822 }
5823 }
5824 }
5825
5826 self.rendered_frame.mouse_listeners = mouse_listeners;
5827
5828 if cx.has_active_drag() {
5829 if event.is::<MouseMoveEvent>() {
5830 self.refresh();
5833 } else if event.is::<MouseUpEvent>() {
5834 cx.active_drag = None;
5837 self.refresh();
5838 }
5839 }
5840
5841 if event.is::<MouseUpEvent>() && self.captured_hitbox.is_some() {
5843 self.captured_hitbox = None;
5844 }
5845 }
5846
5847 fn dispatch_key_event(&mut self, event: &dyn Any, cx: &mut App) {
5848 if self.invalidator.is_dirty() {
5849 self.draw(cx).clear(cx);
5850 }
5851
5852 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
5853 let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
5854
5855 let mut keystroke: Option<Keystroke> = None;
5856
5857 if let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() {
5858 if event.modifiers.number_of_modifiers() == 0
5859 && self.pending_modifier.modifiers.number_of_modifiers() == 1
5860 && !self.pending_modifier.saw_other_input
5861 {
5862 let key = match self.pending_modifier.modifiers {
5863 modifiers if modifiers.shift => Some("shift"),
5864 modifiers if modifiers.control => Some("control"),
5865 modifiers if modifiers.alt => Some("alt"),
5866 modifiers if modifiers.platform => Some("platform"),
5867 modifiers if modifiers.function => Some("function"),
5868 _ => None,
5869 };
5870 if let Some(key) = key {
5871 keystroke = Some(Keystroke {
5872 key: key.to_string(),
5873 key_char: None,
5874 modifiers: Modifiers::default(),
5875 });
5876 }
5877 }
5878
5879 if self.pending_modifier.modifiers.number_of_modifiers() == 0
5880 && event.modifiers.number_of_modifiers() == 1
5881 {
5882 self.pending_modifier.saw_other_input = false
5883 } else if event.modifiers.number_of_modifiers() > 1 {
5884 self.pending_modifier.saw_other_input = true
5885 }
5886 self.pending_modifier.modifiers = event.modifiers
5887 } else if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
5888 self.pending_modifier.saw_other_input = true;
5889 keystroke = Some(key_down_event.keystroke.clone());
5890 if key_down_event.keystroke.key_char.is_some()
5891 && matches!(
5892 cx.cursor_hide_mode,
5893 CursorHideMode::OnTyping | CursorHideMode::OnTypingAndAction
5894 )
5895 {
5896 cx.platform.hide_cursor_until_mouse_moves();
5897 }
5898 }
5899
5900 let Some(keystroke) = keystroke else {
5901 self.finish_dispatch_key_event(event, dispatch_path, self.context_stack(), cx);
5902 return;
5903 };
5904
5905 cx.propagate_event = true;
5906 self.dispatch_keystroke_interceptors(event, self.context_stack(), cx);
5907 if !cx.propagate_event {
5908 self.finish_dispatch_key_event(event, dispatch_path, self.context_stack(), cx);
5909 return;
5910 }
5911
5912 let mut currently_pending = self.pending_input.take().unwrap_or_default();
5913 if currently_pending.focus.is_some() && currently_pending.focus != self.focus {
5914 currently_pending = PendingInput::default();
5915 }
5916
5917 let match_result = self.rendered_frame.dispatch_tree.dispatch_key(
5918 currently_pending.keystrokes,
5919 keystroke,
5920 &dispatch_path,
5921 );
5922
5923 if !match_result.to_replay.is_empty() {
5924 self.replay_pending_input(match_result.to_replay, cx);
5925 cx.propagate_event = true;
5926 }
5927
5928 if !match_result.pending.is_empty() {
5929 let previous_timeout = currently_pending.timeout.take();
5930 currently_pending.keystrokes = match_result.pending;
5931 currently_pending.focus = self.focus;
5932
5933 let text_input_requires_timeout = event
5934 .downcast_ref::<KeyDownEvent>()
5935 .filter(|key_down| key_down.keystroke.key_char.is_some())
5936 .and_then(|_| self.platform_window.take_input_handler())
5937 .map_or(false, |mut input_handler| {
5938 let accepts = input_handler.accepts_text_input(self, cx);
5939 self.platform_window.set_input_handler(input_handler);
5940 accepts
5941 });
5942
5943 let needs_timeout = previous_timeout.is_some()
5944 || match_result.pending_has_binding
5945 || text_input_requires_timeout;
5946 currently_pending.timeout = if needs_timeout {
5947 match previous_timeout {
5948 Some(mut timeout) if timeout.is_paused() => {
5949 timeout.reset_duration(PENDING_INPUT_TIMEOUT);
5950 Some(timeout)
5951 }
5952 previous_timeout => {
5953 drop(previous_timeout);
5954 Some(self.new_pending_input_timeout(PENDING_INPUT_TIMEOUT, cx))
5955 }
5956 }
5957 } else {
5958 None
5959 };
5960 self.pending_input = Some(currently_pending);
5961 self.pending_input_changed(cx);
5962 cx.propagate_event = false;
5963 return;
5964 }
5965
5966 let skip_bindings = event
5967 .downcast_ref::<KeyDownEvent>()
5968 .filter(|key_down_event| key_down_event.prefer_character_input)
5969 .map(|_| {
5970 self.platform_window
5971 .take_input_handler()
5972 .map_or(false, |mut input_handler| {
5973 let accepts = input_handler.accepts_text_input(self, cx);
5974 self.platform_window.set_input_handler(input_handler);
5975 accepts
5978 })
5979 })
5980 .unwrap_or(false);
5981
5982 if !skip_bindings {
5983 for binding in match_result.bindings {
5984 self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
5985 if !cx.propagate_event {
5986 self.dispatch_keystroke_observers(
5987 event,
5988 Some(binding.action),
5989 match_result.context_stack,
5990 cx,
5991 );
5992 self.pending_input_changed(cx);
5993 return;
5994 }
5995 }
5996 }
5997
5998 self.finish_dispatch_key_event(event, dispatch_path, match_result.context_stack, cx);
5999 self.pending_input_changed(cx);
6000 }
6001
6002 fn new_pending_input_timeout(&self, duration: Duration, cx: &App) -> PendingInputTimeout {
6003 let (started_at, task) = self.start_pending_input_timeout(duration, cx);
6004 PendingInputTimeout {
6005 duration,
6006 remaining: duration,
6007 state: PendingInputTimeoutState::Running { started_at, task },
6008 }
6009 }
6010
6011 fn start_pending_input_timeout(&self, remaining: Duration, cx: &App) -> (Instant, Task<()>) {
6012 let started_at = cx.background_executor().now();
6013 let task = self.spawn(cx, async move |cx| {
6014 cx.background_executor.timer(remaining).await;
6015 cx.update(move |window, cx| {
6016 let Some(currently_pending) = window
6017 .pending_input
6018 .take()
6019 .filter(|pending| pending.focus == window.focus)
6020 else {
6021 return;
6022 };
6023
6024 let node_id = window.focus_node_id_in_rendered_frame(window.focus);
6025 let dispatch_path = window.rendered_frame.dispatch_tree.dispatch_path(node_id);
6026
6027 let to_replay = window
6028 .rendered_frame
6029 .dispatch_tree
6030 .flush_dispatch(currently_pending.keystrokes, &dispatch_path);
6031
6032 window.pending_input_changed(cx);
6033 window.replay_pending_input(to_replay, cx)
6034 })
6035 .log_err();
6036 });
6037 (started_at, task)
6038 }
6039
6040 fn finish_dispatch_key_event(
6041 &mut self,
6042 event: &dyn Any,
6043 dispatch_path: SmallVec<[DispatchNodeId; 32]>,
6044 context_stack: Vec<KeyContext>,
6045 cx: &mut App,
6046 ) {
6047 self.dispatch_key_down_up_event(event, &dispatch_path, cx);
6048 if !cx.propagate_event {
6049 return;
6050 }
6051
6052 self.dispatch_modifiers_changed_event(event, &dispatch_path, cx);
6053 if !cx.propagate_event {
6054 return;
6055 }
6056
6057 self.dispatch_keystroke_observers(event, None, context_stack, cx);
6058 }
6059
6060 pub(crate) fn pending_input_changed(&mut self, cx: &mut App) {
6061 self.pending_input_observers
6062 .clone()
6063 .retain(&(), |callback| callback(self, cx));
6064 }
6065
6066 fn defer_pending_input_changed(&self, cx: &mut App) {
6067 let window_handle = self.handle;
6070 cx.defer(move |cx| {
6071 window_handle
6072 .update(cx, |_, window, cx| {
6073 window.pending_input_changed(cx);
6074 })
6075 .ok();
6076 });
6077 }
6078
6079 fn dispatch_key_down_up_event(
6080 &mut self,
6081 event: &dyn Any,
6082 dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
6083 cx: &mut App,
6084 ) {
6085 for node_id in dispatch_path {
6087 let node = self.rendered_frame.dispatch_tree.node(*node_id);
6088
6089 for key_listener in node.key_listeners.clone() {
6090 key_listener(event, DispatchPhase::Capture, self, cx);
6091 if !cx.propagate_event {
6092 return;
6093 }
6094 }
6095 }
6096
6097 for node_id in dispatch_path.iter().rev() {
6099 let node = self.rendered_frame.dispatch_tree.node(*node_id);
6101 for key_listener in node.key_listeners.clone() {
6102 key_listener(event, DispatchPhase::Bubble, self, cx);
6103 if !cx.propagate_event {
6104 return;
6105 }
6106 }
6107 }
6108 }
6109
6110 fn dispatch_modifiers_changed_event(
6111 &mut self,
6112 event: &dyn Any,
6113 dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
6114 cx: &mut App,
6115 ) {
6116 let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() else {
6117 return;
6118 };
6119 for node_id in dispatch_path.iter().rev() {
6120 let node = self.rendered_frame.dispatch_tree.node(*node_id);
6121 for listener in node.modifiers_changed_listeners.clone() {
6122 listener(event, self, cx);
6123 if !cx.propagate_event {
6124 return;
6125 }
6126 }
6127 }
6128 }
6129
6130 pub fn has_pending_keystrokes(&self) -> bool {
6132 self.pending_input().is_some()
6133 }
6134
6135 #[cfg(test)]
6136 pub(crate) fn pending_input_is_none(&self) -> bool {
6137 self.pending_input.is_none()
6138 }
6139
6140 pub(crate) fn clear_pending_keystrokes(&mut self, cx: &mut App) {
6141 if self.pending_input.take().is_some() {
6142 self.defer_pending_input_changed(cx);
6143 }
6144 }
6145
6146 pub fn pending_input(&self) -> Option<PendingInputStatus<'_>> {
6149 self.pending_input
6150 .as_ref()
6151 .filter(|pending_input| pending_input.focus == self.focus)
6152 .map(|pending_input| PendingInputStatus {
6153 keystrokes: pending_input.keystrokes.as_slice(),
6154 timeout: pending_input
6155 .timeout
6156 .as_ref()
6157 .map(PendingInputTimeout::status),
6158 })
6159 }
6160
6161 pub fn set_pending_input_timeout_paused<T: 'static>(
6166 &mut self,
6167 owner: &Entity<T>,
6168 paused: bool,
6169 cx: &mut App,
6170 ) -> bool {
6171 let owner_id = owner.entity_id();
6172 if !paused {
6173 return self.resume_pending_input_timeout(owner_id, cx);
6174 }
6175
6176 let timeout = self
6177 .pending_input
6178 .as_ref()
6179 .filter(|pending_input| pending_input.focus == self.focus)
6180 .and_then(|pending_input| pending_input.timeout.as_ref());
6181 let Some(timeout) = timeout else {
6182 return false;
6183 };
6184 if timeout.is_paused() {
6185 return false;
6186 }
6187
6188 let release_subscription = self.observe_release(owner, cx, move |_, window, cx| {
6189 window.resume_pending_input_timeout(owner_id, cx);
6190 });
6191 let now = cx.background_executor().now();
6192 let changed = self
6193 .pending_input
6194 .as_mut()
6195 .filter(|pending_input| pending_input.focus == self.focus)
6196 .and_then(|pending_input| pending_input.timeout.as_mut())
6197 .is_some_and(|timeout| {
6198 timeout.pause(
6199 PendingInputTimeoutPause {
6200 owner_id,
6201 _release_subscription: release_subscription,
6202 },
6203 now,
6204 )
6205 });
6206
6207 if changed {
6208 self.defer_pending_input_changed(cx);
6209 }
6210 changed
6211 }
6212
6213 fn resume_pending_input_timeout(&mut self, owner_id: EntityId, cx: &mut App) -> bool {
6214 let Some(remaining) = self
6215 .pending_input
6216 .as_ref()
6217 .and_then(|pending_input| pending_input.timeout.as_ref())
6218 .filter(|timeout| timeout.pause_owner_id() == Some(owner_id))
6219 .map(|timeout| timeout.remaining)
6220 else {
6221 return false;
6222 };
6223
6224 let (started_at, task) = self.start_pending_input_timeout(remaining, cx);
6225 let changed = self
6226 .pending_input
6227 .as_mut()
6228 .and_then(|pending_input| pending_input.timeout.as_mut())
6229 .is_some_and(|timeout| timeout.resume(owner_id, started_at, task));
6230
6231 if changed {
6232 self.defer_pending_input_changed(cx);
6233 }
6234 changed
6235 }
6236
6237 pub fn pending_input_keystrokes(&self) -> Option<&[Keystroke]> {
6239 self.pending_input()
6240 .map(|pending_input| pending_input.keystrokes())
6241 }
6242
6243 fn replay_pending_input(&mut self, replays: SmallVec<[Replay; 1]>, cx: &mut App) {
6244 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
6245 let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
6246
6247 'replay: for replay in replays {
6248 let event = KeyDownEvent {
6249 keystroke: replay.keystroke.clone(),
6250 is_held: false,
6251 prefer_character_input: true,
6252 };
6253
6254 cx.propagate_event = true;
6255 for binding in replay.bindings {
6256 self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
6257 if !cx.propagate_event {
6258 self.dispatch_keystroke_observers(
6259 &event,
6260 Some(binding.action),
6261 Vec::default(),
6262 cx,
6263 );
6264 continue 'replay;
6265 }
6266 }
6267
6268 self.dispatch_key_down_up_event(&event, &dispatch_path, cx);
6269 if !cx.propagate_event {
6270 continue 'replay;
6271 }
6272 if let Some(input) = replay.keystroke.key_char.as_ref().cloned()
6273 && let Some(mut input_handler) = self.platform_window.take_input_handler()
6274 {
6275 input_handler.dispatch_input(&input, self, cx);
6276 self.platform_window.set_input_handler(input_handler)
6277 }
6278 }
6279 }
6280
6281 fn focus_node_id_in_rendered_frame(&self, focus_id: Option<FocusId>) -> DispatchNodeId {
6282 focus_id
6283 .and_then(|focus_id| {
6284 self.rendered_frame
6285 .dispatch_tree
6286 .focusable_node_id(focus_id)
6287 })
6288 .unwrap_or_else(|| self.rendered_frame.dispatch_tree.root_node_id())
6289 }
6290
6291 fn dispatch_action_on_node(
6292 &mut self,
6293 node_id: DispatchNodeId,
6294 action: &dyn Action,
6295 cx: &mut App,
6296 ) {
6297 self.dispatch_action_on_node_inner(node_id, action, cx);
6298
6299 if !cx.propagate_event
6300 && cx.cursor_hide_mode == CursorHideMode::OnTypingAndAction
6301 && self.last_input_was_keyboard()
6302 {
6303 cx.platform.hide_cursor_until_mouse_moves();
6304 }
6305 }
6306
6307 fn dispatch_action_on_node_inner(
6308 &mut self,
6309 node_id: DispatchNodeId,
6310 action: &dyn Action,
6311 cx: &mut App,
6312 ) {
6313 let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
6314
6315 cx.propagate_event = true;
6317 if let Some(mut global_listeners) = cx
6318 .global_action_listeners
6319 .remove(&action.as_any().type_id())
6320 {
6321 for listener in &global_listeners {
6322 #[cfg(feature = "profiler")]
6323 self.window_profiler.begin_action_handler(action, cx);
6324 listener(action.as_any(), DispatchPhase::Capture, cx);
6325 #[cfg(feature = "profiler")]
6326 self.window_profiler.end_action_handler();
6327 if !cx.propagate_event {
6328 break;
6329 }
6330 }
6331
6332 global_listeners.extend(
6333 cx.global_action_listeners
6334 .remove(&action.as_any().type_id())
6335 .unwrap_or_default(),
6336 );
6337
6338 cx.global_action_listeners
6339 .insert(action.as_any().type_id(), global_listeners);
6340 }
6341
6342 if !cx.propagate_event {
6343 return;
6344 }
6345
6346 for node_id in &dispatch_path {
6348 let node = self.rendered_frame.dispatch_tree.node(*node_id);
6349 for DispatchActionListener {
6350 action_type,
6351 listener,
6352 } in node.action_listeners.clone()
6353 {
6354 let any_action = action.as_any();
6355 if action_type == any_action.type_id() {
6356 #[cfg(feature = "profiler")]
6357 self.window_profiler.begin_action_handler(action, cx);
6358 listener(any_action, DispatchPhase::Capture, self, cx);
6359 #[cfg(feature = "profiler")]
6360 self.window_profiler.end_action_handler();
6361
6362 if !cx.propagate_event {
6363 return;
6364 }
6365 }
6366 }
6367 }
6368
6369 for node_id in dispatch_path.iter().rev() {
6371 let node = self.rendered_frame.dispatch_tree.node(*node_id);
6372 for DispatchActionListener {
6373 action_type,
6374 listener,
6375 } in node.action_listeners.clone()
6376 {
6377 let any_action = action.as_any();
6378 if action_type == any_action.type_id() {
6379 cx.propagate_event = false; #[cfg(feature = "profiler")]
6381 self.window_profiler.begin_action_handler(action, cx);
6382 listener(any_action, DispatchPhase::Bubble, self, cx);
6383 #[cfg(feature = "profiler")]
6384 self.window_profiler.end_action_handler();
6385
6386 if !cx.propagate_event {
6387 return;
6388 }
6389 }
6390 }
6391 }
6392
6393 if let Some(mut global_listeners) = cx
6395 .global_action_listeners
6396 .remove(&action.as_any().type_id())
6397 {
6398 for listener in global_listeners.iter().rev() {
6399 cx.propagate_event = false; #[cfg(feature = "profiler")]
6402 self.window_profiler.begin_action_handler(action, cx);
6403 listener(action.as_any(), DispatchPhase::Bubble, cx);
6404 #[cfg(feature = "profiler")]
6405 self.window_profiler.end_action_handler();
6406 if !cx.propagate_event {
6407 break;
6408 }
6409 }
6410
6411 global_listeners.extend(
6412 cx.global_action_listeners
6413 .remove(&action.as_any().type_id())
6414 .unwrap_or_default(),
6415 );
6416
6417 cx.global_action_listeners
6418 .insert(action.as_any().type_id(), global_listeners);
6419 }
6420 }
6421
6422 pub fn observe_global<G: Global>(
6425 &mut self,
6426 cx: &mut App,
6427 f: impl Fn(&mut Window, &mut App) + 'static,
6428 ) -> Subscription {
6429 let window_handle = self.handle;
6430 let (subscription, activate) = cx.global_observers.insert(
6431 TypeId::of::<G>(),
6432 Box::new(move |cx| {
6433 window_handle
6434 .update(cx, |_, window, cx| f(window, cx))
6435 .is_ok()
6436 }),
6437 );
6438 cx.defer(move |_| activate());
6439 subscription
6440 }
6441
6442 pub fn activate_window(&self) {
6444 self.platform_window.activate();
6445 }
6446
6447 pub fn request_attention(&self) {
6449 self.platform_window.request_attention();
6450 }
6451
6452 pub fn minimize_window(&self) {
6454 self.platform_window.minimize();
6455 }
6456
6457 pub fn toggle_fullscreen(&self) {
6459 self.platform_window.toggle_fullscreen();
6460 }
6461
6462 pub fn toggle_simple_fullscreen(&self) {
6467 self.platform_window.toggle_simple_fullscreen();
6468 }
6469
6470 pub fn invalidate_character_coordinates(&self) {
6472 self.on_next_frame(|window, cx| {
6473 if let Some(mut input_handler) = window.platform_window.take_input_handler() {
6474 if let Some(bounds) = input_handler.selected_bounds(window, cx) {
6475 window.platform_window.update_ime_position(bounds);
6476 }
6477 window.platform_window.set_input_handler(input_handler);
6478 }
6479 });
6480 }
6481
6482 pub fn prompt<T>(
6486 &mut self,
6487 level: PromptLevel,
6488 message: &str,
6489 detail: Option<&str>,
6490 answers: &[T],
6491 cx: &mut App,
6492 ) -> oneshot::Receiver<usize>
6493 where
6494 T: Clone + Into<PromptButton>,
6495 {
6496 let prompt_builder = cx.prompt_builder.take();
6497 let Some(prompt_builder) = prompt_builder else {
6498 unreachable!("Re-entrant window prompting is not supported by GPUI");
6499 };
6500
6501 let answers = answers
6502 .iter()
6503 .map(|answer| answer.clone().into())
6504 .collect::<Vec<_>>();
6505
6506 let receiver = match &prompt_builder {
6507 PromptBuilder::Default => self
6508 .platform_window
6509 .prompt(level, message, detail, &answers)
6510 .unwrap_or_else(|| {
6511 self.build_custom_prompt(&prompt_builder, level, message, detail, &answers, cx)
6512 }),
6513 PromptBuilder::Custom(_) => {
6514 self.build_custom_prompt(&prompt_builder, level, message, detail, &answers, cx)
6515 }
6516 };
6517
6518 cx.prompt_builder = Some(prompt_builder);
6519
6520 receiver
6521 }
6522
6523 fn build_custom_prompt(
6524 &mut self,
6525 prompt_builder: &PromptBuilder,
6526 level: PromptLevel,
6527 message: &str,
6528 detail: Option<&str>,
6529 answers: &[PromptButton],
6530 cx: &mut App,
6531 ) -> oneshot::Receiver<usize> {
6532 let (sender, receiver) = oneshot::channel();
6533 let handle = PromptHandle::new(sender);
6534 let handle = (prompt_builder)(level, message, detail, answers, handle, self, cx);
6535 self.prompt = Some(handle);
6536 receiver
6537 }
6538
6539 pub fn has_active_prompt(&self) -> bool {
6544 self.prompt.is_some()
6545 }
6546
6547 pub fn context_stack(&self) -> Vec<KeyContext> {
6549 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
6550 let dispatch_tree = &self.rendered_frame.dispatch_tree;
6551 dispatch_tree
6552 .dispatch_path(node_id)
6553 .iter()
6554 .filter_map(move |&node_id| dispatch_tree.node(node_id).context.clone())
6555 .collect()
6556 }
6557
6558 pub fn available_actions(&self, cx: &App) -> Vec<Box<dyn Action>> {
6560 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
6561 let mut actions = self.rendered_frame.dispatch_tree.available_actions(node_id);
6562 for action_type in cx.global_action_listeners.keys() {
6563 if let Err(ix) = actions.binary_search_by_key(action_type, |a| a.as_any().type_id()) {
6564 let action = cx.actions.build_action_type(action_type).ok();
6565 if let Some(action) = action {
6566 actions.insert(ix, action);
6567 }
6568 }
6569 }
6570 actions
6571 }
6572
6573 pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
6576 self.rendered_frame
6577 .dispatch_tree
6578 .bindings_for_action(action, &self.rendered_frame.dispatch_tree.context_stack)
6579 }
6580
6581 pub fn highest_precedence_binding_for_action(&self, action: &dyn Action) -> Option<KeyBinding> {
6584 self.rendered_frame
6585 .dispatch_tree
6586 .highest_precedence_binding_for_action(
6587 action,
6588 &self.rendered_frame.dispatch_tree.context_stack,
6589 )
6590 }
6591
6592 pub fn bindings_for_action_in_context(
6594 &self,
6595 action: &dyn Action,
6596 context: KeyContext,
6597 ) -> Vec<KeyBinding> {
6598 let dispatch_tree = &self.rendered_frame.dispatch_tree;
6599 dispatch_tree.bindings_for_action(action, &[context])
6600 }
6601
6602 pub fn highest_precedence_binding_for_action_in_context(
6605 &self,
6606 action: &dyn Action,
6607 context: KeyContext,
6608 ) -> Option<KeyBinding> {
6609 let dispatch_tree = &self.rendered_frame.dispatch_tree;
6610 dispatch_tree.highest_precedence_binding_for_action(action, &[context])
6611 }
6612
6613 pub fn bindings_for_action_in(
6617 &self,
6618 action: &dyn Action,
6619 focus_handle: &FocusHandle,
6620 ) -> Vec<KeyBinding> {
6621 let dispatch_tree = &self.rendered_frame.dispatch_tree;
6622 let Some(context_stack) = self.context_stack_for_focus_handle(focus_handle) else {
6623 return vec![];
6624 };
6625 dispatch_tree.bindings_for_action(action, &context_stack)
6626 }
6627
6628 pub fn highest_precedence_binding_for_action_in(
6632 &self,
6633 action: &dyn Action,
6634 focus_handle: &FocusHandle,
6635 ) -> Option<KeyBinding> {
6636 let dispatch_tree = &self.rendered_frame.dispatch_tree;
6637 let context_stack = self.context_stack_for_focus_handle(focus_handle)?;
6638 dispatch_tree.highest_precedence_binding_for_action(action, &context_stack)
6639 }
6640
6641 pub fn possible_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
6643 self.rendered_frame
6644 .dispatch_tree
6645 .possible_next_bindings_for_input(input, &self.context_stack())
6646 }
6647
6648 fn context_stack_for_focus_handle(
6649 &self,
6650 focus_handle: &FocusHandle,
6651 ) -> Option<Vec<KeyContext>> {
6652 let dispatch_tree = &self.rendered_frame.dispatch_tree;
6653 let node_id = dispatch_tree.focusable_node_id(focus_handle.id)?;
6654 let context_stack: Vec<_> = dispatch_tree
6655 .dispatch_path(node_id)
6656 .into_iter()
6657 .filter_map(|node_id| dispatch_tree.node(node_id).context.clone())
6658 .collect();
6659 Some(context_stack)
6660 }
6661
6662 pub fn listener_for<T: 'static, E>(
6664 &self,
6665 view: &Entity<T>,
6666 f: impl Fn(&mut T, &E, &mut Window, &mut Context<T>) + 'static,
6667 ) -> impl Fn(&E, &mut Window, &mut App) + 'static {
6668 let view = view.downgrade();
6669 move |e: &E, window: &mut Window, cx: &mut App| {
6670 view.update(cx, |view, cx| f(view, e, window, cx)).ok();
6671 }
6672 }
6673
6674 pub fn handler_for<E: 'static, Callback: Fn(&mut E, &mut Window, &mut Context<E>) + 'static>(
6676 &self,
6677 entity: &Entity<E>,
6678 f: Callback,
6679 ) -> impl Fn(&mut Window, &mut App) + 'static {
6680 let entity = entity.downgrade();
6681 move |window: &mut Window, cx: &mut App| {
6682 entity.update(cx, |entity, cx| f(entity, window, cx)).ok();
6683 }
6684 }
6685
6686 pub fn on_window_should_close(
6689 &self,
6690 cx: &App,
6691 f: impl Fn(&mut Window, &mut App) -> bool + 'static,
6692 ) {
6693 let mut cx = self.to_async(cx);
6694 self.platform_window.on_should_close(Box::new(move || {
6695 cx.update(|window, cx| f(window, cx)).unwrap_or(true)
6696 }))
6697 }
6698
6699 pub fn on_action(
6708 &mut self,
6709 action_type: TypeId,
6710 listener: impl Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static,
6711 ) {
6712 self.invalidator.debug_assert_paint();
6713
6714 self.next_frame
6715 .dispatch_tree
6716 .on_action(action_type, Rc::new(listener));
6717 }
6718
6719 pub fn on_action_when(
6728 &mut self,
6729 condition: bool,
6730 action_type: TypeId,
6731 listener: impl Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static,
6732 ) {
6733 self.invalidator.debug_assert_paint();
6734
6735 if condition {
6736 self.next_frame
6737 .dispatch_tree
6738 .on_action(action_type, Rc::new(listener));
6739 }
6740 }
6741
6742 pub fn gpu_specs(&self) -> Option<GpuSpecs> {
6745 self.platform_window.gpu_specs()
6746 }
6747
6748 pub fn titlebar_double_click(&self) {
6751 self.platform_window
6752 .titlebar_double_click(self.is_resizable, self.is_minimizable);
6753 }
6754
6755 pub fn window_title(&self) -> String {
6758 self.platform_window.get_title()
6759 }
6760
6761 pub fn tabbed_windows(&self) -> Option<Vec<SystemWindowTab>> {
6764 self.platform_window.tabbed_windows()
6765 }
6766
6767 pub fn tab_bar_visible(&self) -> bool {
6770 self.platform_window.tab_bar_visible()
6771 }
6772
6773 pub fn merge_all_windows(&self) {
6776 self.platform_window.merge_all_windows()
6777 }
6778
6779 pub fn move_tab_to_new_window(&self) {
6782 self.platform_window.move_tab_to_new_window()
6783 }
6784
6785 pub fn toggle_window_tab_overview(&self) {
6788 self.platform_window.toggle_window_tab_overview()
6789 }
6790
6791 pub fn set_tabbing_identifier(&self, tabbing_identifier: Option<String>) {
6794 self.platform_window
6795 .set_tabbing_identifier(tabbing_identifier)
6796 }
6797
6798 pub fn play_system_bell(&self) {
6801 self.platform_window.play_system_bell()
6802 }
6803
6804 pub fn is_a11y_active(&self) -> bool {
6815 self.a11y.is_active()
6816 }
6817
6818 pub fn debug_a11y_tree_json(&self) -> Option<String> {
6820 self.a11y.debug_tree_json()
6821 }
6822
6823 pub fn on_a11y_action(
6829 &mut self,
6830 node_id: accesskit::NodeId,
6831 action: accesskit::Action,
6832 listener: impl FnMut(Option<&accesskit::ActionData>, &mut Window, &mut App) + 'static,
6833 ) {
6834 self.a11y
6835 .action_listeners
6836 .entry(node_id)
6837 .or_default()
6838 .push((action, Box::new(listener)));
6839 }
6840
6841 #[cfg(not(target_family = "wasm"))]
6842 pub(crate) fn handle_a11y_action(&mut self, request: accesskit::ActionRequest, cx: &mut App) {
6843 if let Some(mut listeners) = self.a11y.action_listeners.remove(&request.target_node) {
6846 let extra_data = request.data.as_ref();
6847 let mut matched = false;
6848 for (action, listener) in &mut listeners {
6849 if *action == request.action {
6850 listener(extra_data, self, cx);
6851 matched = true;
6852 }
6853 }
6854 self.a11y
6855 .action_listeners
6856 .insert(request.target_node, listeners);
6857 if matched {
6858 return;
6859 }
6860 }
6861
6862 match request.action {
6864 accesskit::Action::Click => {
6865 if let Some(bounds) = self.a11y.node_bounds.get(&request.target_node).copied() {
6866 let center = bounds.center();
6867 let mouse_down = PlatformInput::MouseDown(crate::MouseDownEvent {
6868 button: MouseButton::Left,
6869 position: center,
6870 modifiers: Modifiers::default(),
6871 click_count: 1,
6872 first_mouse: false,
6873 });
6874 let mouse_up = PlatformInput::MouseUp(MouseUpEvent {
6875 button: MouseButton::Left,
6876 position: center,
6877 modifiers: Modifiers::default(),
6878 click_count: 1,
6879 });
6880 self.dispatch_event(mouse_down, cx);
6881 self.dispatch_event(mouse_up, cx);
6882 }
6883 }
6884 accesskit::Action::Focus => {
6885 if let Some(focus_id) = self.a11y.focus_ids.get(&request.target_node).copied()
6886 && let Some(handle) = FocusHandle::for_id(focus_id, &cx.focus_handles)
6887 {
6888 self.focus(&handle, cx);
6889 }
6890 }
6891 accesskit::Action::Blur => {
6892 self.blur(cx);
6893 }
6894 _ => {
6895 log::debug!(
6896 "Unhandled a11y action: {:?} on {:?}",
6897 request.action,
6898 request.target_node
6899 );
6900 }
6901 }
6902 }
6903
6904 #[cfg(any(feature = "inspector", debug_assertions))]
6906 pub fn toggle_inspector(&mut self, cx: &mut App) {
6907 self.inspector = match self.inspector {
6908 None => Some(cx.new(|_| Inspector::new())),
6909 Some(_) => {
6910 self.rendered_frame.next_inspector_instance_ids = FxHashMap::default();
6911 self.rendered_frame.inspector_hitboxes = FxHashMap::default();
6912 self.next_frame.next_inspector_instance_ids = FxHashMap::default();
6913 self.next_frame.inspector_hitboxes = FxHashMap::default();
6914 None
6915 }
6916 };
6917 self.refresh();
6918 }
6919
6920 pub fn is_inspector_picking(&self, _cx: &App) -> bool {
6922 #[cfg(any(feature = "inspector", debug_assertions))]
6923 {
6924 if let Some(inspector) = &self.inspector {
6925 return inspector.read(_cx).is_picking();
6926 }
6927 }
6928 false
6929 }
6930
6931 #[cfg(any(feature = "inspector", debug_assertions))]
6933 pub fn with_inspector_state<T: 'static, R>(
6934 &mut self,
6935 inspector_id: Option<&crate::InspectorElementId>,
6936 cx: &mut App,
6937 f: impl FnOnce(&mut Option<T>, &mut Self) -> R,
6938 ) -> Option<R> {
6939 let inspector_id = inspector_id?;
6940 let inspector = self.inspector.as_ref()?;
6941 if inspector.read(cx).active_element_id() != Some(inspector_id) {
6942 return None;
6943 }
6944 let inspector = inspector.clone();
6945 Some(inspector.update(cx, |inspector, _cx| {
6946 inspector.with_active_element_state(self, f)
6947 }))
6948 }
6949
6950 #[cfg(any(feature = "inspector", debug_assertions))]
6951 pub(crate) fn inspector_enabled(&self) -> bool {
6952 self.inspector.is_some()
6953 }
6954
6955 #[cfg(any(feature = "inspector", debug_assertions))]
6956 pub(crate) fn build_inspector_element_id(
6957 &mut self,
6958 path: crate::InspectorElementPath,
6959 ) -> crate::InspectorElementId {
6960 self.invalidator.debug_assert_paint_or_prepaint();
6961 let path = Rc::new(path);
6962 let next_instance_id = self
6963 .next_frame
6964 .next_inspector_instance_ids
6965 .entry(path.clone())
6966 .or_insert(0);
6967 let instance_id = *next_instance_id;
6968 *next_instance_id += 1;
6969 crate::InspectorElementId { path, instance_id }
6970 }
6971
6972 #[cfg(any(feature = "inspector", debug_assertions))]
6973 fn prepaint_inspector(&mut self, inspector_width: Pixels, cx: &mut App) -> Option<AnyElement> {
6974 if let Some(inspector) = self.inspector.take() {
6975 let mut inspector_element = AnyView::from(inspector.clone()).into_any_element();
6976 inspector_element.prepaint_as_root(
6977 point(self.viewport_size.width - inspector_width, px(0.0)),
6978 size(inspector_width, self.viewport_size.height).into(),
6979 self,
6980 cx,
6981 );
6982 self.inspector = Some(inspector);
6983 Some(inspector_element)
6984 } else {
6985 None
6986 }
6987 }
6988
6989 #[cfg(any(feature = "inspector", debug_assertions))]
6990 fn paint_inspector(&mut self, mut inspector_element: Option<AnyElement>, cx: &mut App) {
6991 if let Some(mut inspector_element) = inspector_element {
6992 inspector_element.paint(self, cx);
6993 };
6994 }
6995
6996 #[cfg(any(feature = "inspector", debug_assertions))]
6999 pub fn insert_inspector_hitbox(
7000 &mut self,
7001 hitbox_id: HitboxId,
7002 inspector_id: Option<&crate::InspectorElementId>,
7003 cx: &App,
7004 ) {
7005 self.invalidator.debug_assert_paint_or_prepaint();
7006 if !self.is_inspector_picking(cx) {
7007 return;
7008 }
7009 if let Some(inspector_id) = inspector_id {
7010 self.next_frame
7011 .inspector_hitboxes
7012 .insert(hitbox_id, inspector_id.clone());
7013 }
7014 }
7015
7016 #[cfg(any(feature = "inspector", debug_assertions))]
7017 fn paint_inspector_hitbox(&mut self, cx: &App) {
7018 if let Some(inspector) = self.inspector.as_ref() {
7019 let inspector = inspector.read(cx);
7020 if let Some((hitbox_id, _)) = self.hovered_inspector_hitbox(inspector, &self.next_frame)
7021 && let Some(hitbox) = self
7022 .next_frame
7023 .hitboxes
7024 .iter()
7025 .find(|hitbox| hitbox.id == hitbox_id)
7026 {
7027 self.paint_quad(crate::fill(hitbox.bounds, crate::rgba(0x61afef4d)));
7028 }
7029 }
7030 }
7031
7032 #[cfg(any(feature = "inspector", debug_assertions))]
7033 fn handle_inspector_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
7034 let Some(inspector) = self.inspector.clone() else {
7035 return;
7036 };
7037 if event.downcast_ref::<MouseMoveEvent>().is_some() {
7038 inspector.update(cx, |inspector, _cx| {
7039 if let Some((_, inspector_id)) =
7040 self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
7041 {
7042 inspector.hover(inspector_id, self);
7043 }
7044 });
7045 } else if event.downcast_ref::<crate::MouseDownEvent>().is_some() {
7046 inspector.update(cx, |inspector, _cx| {
7047 if let Some((_, inspector_id)) =
7048 self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
7049 {
7050 inspector.select(inspector_id, self);
7051 }
7052 });
7053 } else if let Some(event) = event.downcast_ref::<crate::ScrollWheelEvent>() {
7054 const SCROLL_LINES: f32 = 3.0;
7056 const SCROLL_PIXELS_PER_LAYER: f32 = 36.0;
7057 let delta_y = event
7058 .delta
7059 .pixel_delta(px(SCROLL_PIXELS_PER_LAYER / SCROLL_LINES))
7060 .y;
7061 if let Some(inspector) = self.inspector.clone() {
7062 inspector.update(cx, |inspector, _cx| {
7063 if let Some(depth) = inspector.pick_depth.as_mut() {
7064 *depth += f32::from(delta_y) / SCROLL_PIXELS_PER_LAYER;
7065 let max_depth = self.mouse_hit_test.ids.len() as f32 - 0.5;
7066 if *depth < 0.0 {
7067 *depth = 0.0;
7068 } else if *depth > max_depth {
7069 *depth = max_depth;
7070 }
7071 if let Some((_, inspector_id)) =
7072 self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
7073 {
7074 inspector.set_active_element_id(inspector_id, self);
7075 }
7076 }
7077 });
7078 }
7079 }
7080 }
7081
7082 #[cfg(any(feature = "inspector", debug_assertions))]
7083 fn hovered_inspector_hitbox(
7084 &self,
7085 inspector: &Inspector,
7086 frame: &Frame,
7087 ) -> Option<(HitboxId, crate::InspectorElementId)> {
7088 if let Some(pick_depth) = inspector.pick_depth {
7089 let depth = (pick_depth as i64).try_into().unwrap_or(0);
7090 let max_skipped = self.mouse_hit_test.ids.len().saturating_sub(1);
7091 let skip_count = (depth as usize).min(max_skipped);
7092 for hitbox_id in self.mouse_hit_test.ids.iter().skip(skip_count) {
7093 if let Some(inspector_id) = frame.inspector_hitboxes.get(hitbox_id) {
7094 return Some((*hitbox_id, inspector_id.clone()));
7095 }
7096 }
7097 }
7098 None
7099 }
7100
7101 #[cfg(any(test, feature = "test-support"))]
7104 pub fn set_modifiers(&mut self, modifiers: Modifiers) {
7105 self.modifiers = modifiers;
7106 }
7107
7108 #[cfg(any(test, feature = "test-support"))]
7112 pub fn simulate_mouse_move(&mut self, position: Point<Pixels>, cx: &mut App) {
7113 let event = PlatformInput::MouseMove(MouseMoveEvent {
7114 position,
7115 modifiers: self.modifiers,
7116 pressed_button: None,
7117 });
7118 let _ = self.dispatch_event(event, cx);
7119 }
7120
7121 #[inline(never)]
7122 fn take_element_state(
7123 &mut self,
7124 global_id: &GlobalElementId,
7125 state_type: TypeId,
7126 ) -> ((GlobalElementId, TypeId), Option<ElementStateBox>) {
7127 let key = (global_id.clone(), state_type);
7128 self.next_frame.accessed_element_states.push(key.clone());
7129 let state = self
7130 .next_frame
7131 .element_states
7132 .remove(&key)
7133 .or_else(|| self.rendered_frame.element_states.remove(&key));
7134 (key, state)
7135 }
7136
7137 #[inline(never)]
7138 fn insert_element_state(
7139 &mut self,
7140 key: (GlobalElementId, TypeId),
7141 state: ElementStateBox,
7142 ) -> Option<ElementStateBox> {
7143 self.next_frame.element_states.insert(key, state)
7144 }
7145
7146 #[inline(never)]
7147 fn observe_keyed_state<S: 'static>(state: &Entity<S>, current_view: EntityId, cx: &mut App) {
7148 cx.observe(state, move |_, cx| {
7149 cx.notify(current_view);
7150 })
7151 .detach();
7152 }
7153}
7154
7155slotmap::new_key_type! {
7157 pub struct WindowId;
7159}
7160
7161impl WindowId {
7162 pub fn as_u64(&self) -> u64 {
7164 self.0.as_ffi()
7165 }
7166}
7167
7168impl From<u64> for WindowId {
7169 fn from(value: u64) -> Self {
7170 WindowId(slotmap::KeyData::from_ffi(value))
7171 }
7172}
7173
7174#[derive(Deref, DerefMut)]
7177pub struct WindowHandle<V> {
7178 #[deref]
7179 #[deref_mut]
7180 pub(crate) any_handle: AnyWindowHandle,
7181 state_type: PhantomData<fn(V) -> V>,
7182}
7183
7184impl<V> Debug for WindowHandle<V> {
7185 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
7186 f.debug_struct("WindowHandle")
7187 .field("any_handle", &self.any_handle.id.as_u64())
7188 .finish()
7189 }
7190}
7191
7192impl<V: 'static + Render> WindowHandle<V> {
7193 pub fn new(id: WindowId) -> Self {
7196 WindowHandle {
7197 any_handle: AnyWindowHandle {
7198 id,
7199 state_type: TypeId::of::<V>(),
7200 root_entity_type_name: std::any::type_name::<V>(),
7201 },
7202 state_type: PhantomData,
7203 }
7204 }
7205
7206 #[cfg(any(test, feature = "test-support"))]
7210 pub fn root<C>(&self, cx: &mut C) -> Result<Entity<V>>
7211 where
7212 C: AppContext,
7213 {
7214 cx.update_window(self.any_handle, |root_view, _, _| {
7215 root_view
7216 .downcast::<V>()
7217 .map_err(|_| anyhow!("the type of the window's root view has changed"))
7218 })?
7219 }
7220
7221 pub fn update<C, R>(
7225 &self,
7226 cx: &mut C,
7227 update: impl FnOnce(&mut V, &mut Window, &mut Context<V>) -> R,
7228 ) -> Result<R>
7229 where
7230 C: AppContext,
7231 {
7232 cx.update_window(self.any_handle, |root_view, window, cx| {
7233 let view = root_view
7234 .downcast::<V>()
7235 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
7236
7237 Ok(view.update(cx, |view, cx| update(view, window, cx)))
7238 })?
7239 }
7240
7241 pub fn read<'a>(&self, cx: &'a App) -> Result<&'a V> {
7245 let x = cx
7246 .windows
7247 .get(self.id)
7248 .and_then(|window| {
7249 window
7250 .as_deref()
7251 .and_then(|window| window.root.clone())
7252 .map(|root_view| root_view.downcast::<V>())
7253 })
7254 .context("window not found")?
7255 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
7256
7257 Ok(x.read(cx))
7258 }
7259
7260 pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &App) -> R) -> Result<R>
7264 where
7265 C: AppContext,
7266 {
7267 cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
7268 }
7269
7270 pub fn entity<C>(&self, cx: &C) -> Result<Entity<V>>
7274 where
7275 C: AppContext,
7276 {
7277 cx.read_window(self, |root_view, _cx| root_view)
7278 }
7279
7280 pub fn is_active(&self, cx: &mut App) -> Option<bool> {
7285 cx.update_window(self.any_handle, |_, window, _| window.is_window_active())
7286 .ok()
7287 }
7288}
7289
7290impl<V> Copy for WindowHandle<V> {}
7291
7292impl<V> Clone for WindowHandle<V> {
7293 fn clone(&self) -> Self {
7294 *self
7295 }
7296}
7297
7298impl<V> PartialEq for WindowHandle<V> {
7299 fn eq(&self, other: &Self) -> bool {
7300 self.any_handle == other.any_handle
7301 }
7302}
7303
7304impl<V> Eq for WindowHandle<V> {}
7305
7306impl<V> Hash for WindowHandle<V> {
7307 fn hash<H: Hasher>(&self, state: &mut H) {
7308 self.any_handle.hash(state);
7309 }
7310}
7311
7312impl<V: 'static> From<WindowHandle<V>> for AnyWindowHandle {
7313 fn from(val: WindowHandle<V>) -> Self {
7314 val.any_handle
7315 }
7316}
7317
7318#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
7320pub struct AnyWindowHandle {
7321 pub(crate) id: WindowId,
7322 state_type: TypeId,
7323 root_entity_type_name: &'static str,
7324}
7325
7326impl AnyWindowHandle {
7327 pub fn window_id(&self) -> WindowId {
7329 self.id
7330 }
7331
7332 pub fn root_entity_type_name(&self) -> &'static str {
7334 self.root_entity_type_name
7335 }
7336
7337 pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
7340 if TypeId::of::<T>() == self.state_type {
7341 Some(WindowHandle {
7342 any_handle: *self,
7343 state_type: PhantomData,
7344 })
7345 } else {
7346 None
7347 }
7348 }
7349
7350 pub fn update<C, R>(
7354 self,
7355 cx: &mut C,
7356 update: impl FnOnce(AnyView, &mut Window, &mut App) -> R,
7357 ) -> Result<R>
7358 where
7359 C: AppContext,
7360 {
7361 cx.update_window(self, update)
7362 }
7363
7364 pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(Entity<T>, &App) -> R) -> Result<R>
7368 where
7369 C: AppContext,
7370 T: 'static,
7371 {
7372 let view = self
7373 .downcast::<T>()
7374 .context("the type of the window's root view has changed")?;
7375
7376 cx.read_window(&view, read)
7377 }
7378}
7379
7380impl HasWindowHandle for Window {
7381 fn window_handle(&self) -> Result<raw_window_handle::WindowHandle<'_>, HandleError> {
7382 self.platform_window.window_handle()
7383 }
7384}
7385
7386impl HasDisplayHandle for Window {
7387 fn display_handle(
7388 &self,
7389 ) -> std::result::Result<raw_window_handle::DisplayHandle<'_>, HandleError> {
7390 self.platform_window.display_handle()
7391 }
7392}
7393
7394#[derive(Clone, Debug, Eq, PartialEq, Hash)]
7399pub enum ElementId {
7400 View(EntityId),
7402 Integer(u64),
7404 Name(SharedString),
7406 Uuid(Uuid),
7408 FocusHandle(FocusId),
7410 NamedInteger(SharedString, u64),
7412 Path(Arc<std::path::Path>),
7414 CodeLocation(core::panic::Location<'static>),
7416 NamedChild(Arc<ElementId>, SharedString),
7418 OpaqueId([u8; 20]),
7420}
7421
7422impl ElementId {
7423 pub fn named_usize(name: impl Into<SharedString>, integer: usize) -> ElementId {
7425 Self::NamedInteger(name.into(), integer as u64)
7426 }
7427}
7428
7429impl Display for ElementId {
7430 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
7431 match self {
7432 ElementId::View(entity_id) => write!(f, "view-{}", entity_id)?,
7433 ElementId::Integer(ix) => write!(f, "{}", ix)?,
7434 ElementId::Name(name) => write!(f, "{}", name)?,
7435 ElementId::FocusHandle(_) => write!(f, "FocusHandle")?,
7436 ElementId::NamedInteger(s, i) => write!(f, "{}-{}", s, i)?,
7437 ElementId::Uuid(uuid) => write!(f, "{}", uuid)?,
7438 ElementId::Path(path) => write!(f, "{}", path.display())?,
7439 ElementId::CodeLocation(location) => write!(f, "{}", location)?,
7440 ElementId::NamedChild(id, name) => write!(f, "{}-{}", id, name)?,
7441 ElementId::OpaqueId(opaque_id) => write!(f, "{:x?}", opaque_id)?,
7442 }
7443
7444 Ok(())
7445 }
7446}
7447
7448impl TryInto<SharedString> for ElementId {
7449 type Error = anyhow::Error;
7450
7451 fn try_into(self) -> anyhow::Result<SharedString> {
7452 if let ElementId::Name(name) = self {
7453 Ok(name)
7454 } else {
7455 anyhow::bail!("element id is not string")
7456 }
7457 }
7458}
7459
7460impl From<usize> for ElementId {
7461 fn from(id: usize) -> Self {
7462 ElementId::Integer(id as u64)
7463 }
7464}
7465
7466impl From<i32> for ElementId {
7467 fn from(id: i32) -> Self {
7468 Self::Integer(id as u64)
7469 }
7470}
7471
7472impl From<SharedString> for ElementId {
7473 fn from(name: SharedString) -> Self {
7474 ElementId::Name(name)
7475 }
7476}
7477
7478impl From<String> for ElementId {
7479 fn from(name: String) -> Self {
7480 ElementId::Name(name.into())
7481 }
7482}
7483
7484impl From<Arc<str>> for ElementId {
7485 fn from(name: Arc<str>) -> Self {
7486 ElementId::Name(name.into())
7487 }
7488}
7489
7490impl From<Arc<std::path::Path>> for ElementId {
7491 fn from(path: Arc<std::path::Path>) -> Self {
7492 ElementId::Path(path)
7493 }
7494}
7495
7496impl From<&'static str> for ElementId {
7497 fn from(name: &'static str) -> Self {
7498 ElementId::Name(SharedString::new_static(name))
7499 }
7500}
7501
7502impl<'a> From<&'a FocusHandle> for ElementId {
7503 fn from(handle: &'a FocusHandle) -> Self {
7504 ElementId::FocusHandle(handle.id)
7505 }
7506}
7507
7508impl From<(&'static str, EntityId)> for ElementId {
7509 fn from((name, id): (&'static str, EntityId)) -> Self {
7510 ElementId::NamedInteger(SharedString::new_static(name), id.as_u64())
7511 }
7512}
7513
7514impl From<(&'static str, usize)> for ElementId {
7515 fn from((name, id): (&'static str, usize)) -> Self {
7516 ElementId::NamedInteger(SharedString::new_static(name), id as u64)
7517 }
7518}
7519
7520impl From<(SharedString, usize)> for ElementId {
7521 fn from((name, id): (SharedString, usize)) -> Self {
7522 ElementId::NamedInteger(name, id as u64)
7523 }
7524}
7525
7526impl From<(&'static str, u64)> for ElementId {
7527 fn from((name, id): (&'static str, u64)) -> Self {
7528 ElementId::NamedInteger(SharedString::new_static(name), id)
7529 }
7530}
7531
7532impl From<Uuid> for ElementId {
7533 fn from(value: Uuid) -> Self {
7534 Self::Uuid(value)
7535 }
7536}
7537
7538impl From<(&'static str, u32)> for ElementId {
7539 fn from((name, id): (&'static str, u32)) -> Self {
7540 ElementId::NamedInteger(SharedString::new_static(name), u64::from(id))
7541 }
7542}
7543
7544impl<T: Into<SharedString>> From<(ElementId, T)> for ElementId {
7545 fn from((id, name): (ElementId, T)) -> Self {
7546 ElementId::NamedChild(Arc::new(id), name.into())
7547 }
7548}
7549
7550impl From<&'static core::panic::Location<'static>> for ElementId {
7551 fn from(location: &'static core::panic::Location<'static>) -> Self {
7552 ElementId::CodeLocation(*location)
7553 }
7554}
7555
7556impl From<[u8; 20]> for ElementId {
7557 fn from(opaque_id: [u8; 20]) -> Self {
7558 ElementId::OpaqueId(opaque_id)
7559 }
7560}
7561
7562#[derive(Clone)]
7565pub struct PaintQuad {
7566 pub bounds: Bounds<Pixels>,
7568 pub corner_radii: Corners<Pixels>,
7570 pub background: Background,
7572 pub border_widths: Edges<Pixels>,
7574 pub border_color: Hsla,
7576 pub border_style: BorderStyle,
7578}
7579
7580impl PaintQuad {
7581 pub fn corner_radii(self, corner_radii: impl Into<Corners<Pixels>>) -> Self {
7583 PaintQuad {
7584 corner_radii: corner_radii.into(),
7585 ..self
7586 }
7587 }
7588
7589 pub fn border_widths(self, border_widths: impl Into<Edges<Pixels>>) -> Self {
7591 PaintQuad {
7592 border_widths: border_widths.into(),
7593 ..self
7594 }
7595 }
7596
7597 pub fn border_color(self, border_color: impl Into<Hsla>) -> Self {
7599 PaintQuad {
7600 border_color: border_color.into(),
7601 ..self
7602 }
7603 }
7604
7605 pub fn background(self, background: impl Into<Background>) -> Self {
7607 PaintQuad {
7608 background: background.into(),
7609 ..self
7610 }
7611 }
7612}
7613
7614pub fn quad(
7616 bounds: Bounds<Pixels>,
7617 corner_radii: impl Into<Corners<Pixels>>,
7618 background: impl Into<Background>,
7619 border_widths: impl Into<Edges<Pixels>>,
7620 border_color: impl Into<Hsla>,
7621 border_style: BorderStyle,
7622) -> PaintQuad {
7623 PaintQuad {
7624 bounds,
7625 corner_radii: corner_radii.into(),
7626 background: background.into(),
7627 border_widths: border_widths.into(),
7628 border_color: border_color.into(),
7629 border_style,
7630 }
7631}
7632
7633pub fn fill(bounds: impl Into<Bounds<Pixels>>, background: impl Into<Background>) -> PaintQuad {
7635 PaintQuad {
7636 bounds: bounds.into(),
7637 corner_radii: (0.).into(),
7638 background: background.into(),
7639 border_widths: (0.).into(),
7640 border_color: transparent_black(),
7641 border_style: BorderStyle::default(),
7642 }
7643}
7644
7645pub fn outline(
7647 bounds: impl Into<Bounds<Pixels>>,
7648 border_color: impl Into<Hsla>,
7649 border_style: BorderStyle,
7650) -> PaintQuad {
7651 PaintQuad {
7652 bounds: bounds.into(),
7653 corner_radii: (0.).into(),
7654 background: transparent_black().into(),
7655 border_widths: (1.).into(),
7656 border_color: border_color.into(),
7657 border_style,
7658 }
7659}
7660
7661#[inline(never)]
7662fn with_element_arena_erased(callback: &mut dyn FnMut(&mut Arena)) -> Result<(), AccessError> {
7663 if let Some(arena_pointer) = CURRENT_ELEMENT_ARENA.try_with(Cell::get)? {
7664 let arena_cell = unsafe { &*arena_pointer };
7667 callback(&mut arena_cell.borrow_mut());
7668 Ok(())
7669 } else {
7670 ELEMENT_ARENA.try_with(|arena| callback(&mut arena.borrow_mut()))
7671 }
7672}
7673
7674#[cfg(test)]
7675mod tests {
7676 use std::{
7677 cell::{Cell, RefCell},
7678 path::PathBuf,
7679 rc::Rc,
7680 time::Duration,
7681 };
7682
7683 use crate::{
7684 AnyWindowHandle, AppContext as _, Bounds, ContentMask, Context, DispatchPhase,
7685 DragMoveEvent, Empty, ExternalDragPayload, ExternalPaths, FileDragPaths, FileDropEvent,
7686 FocusHandle, InputEvent as _, InteractiveElement as _, IntoElement, KeyDownEvent,
7687 Keystroke, LongPressEvent, MouseButton, MouseDownEvent, MouseMoveEvent, ParentElement,
7688 Pixels, PlatformInput, Point, Render, RequestFrameOptions, ScaledPixels,
7689 StatefulInteractiveElement as _, Styled, TestAppContext, TouchDragEvent, TouchEvent,
7690 TouchId, TouchPhase, Underline, UnderlineStyle, Window, WindowAppearance, WindowOptions,
7691 canvas, div, hsla, point, px, size,
7692 };
7693
7694 #[gpui::test]
7698 fn test_window_visibility(cx: &mut TestAppContext) {
7699 use crate::WindowVisibility;
7700
7701 let window = cx.add_window(|_, _| EmptyView);
7702 let observed = Rc::new(RefCell::new(Vec::new()));
7703 let _subscription = window
7704 .update(cx, {
7705 let observed = observed.clone();
7706 move |_, window, _| {
7707 assert_eq!(window.visibility(), WindowVisibility::Visible);
7708 assert!(window.is_visible());
7709 window.observe_window_visibility(move |visibility, window, _| {
7710 assert_eq!(window.visibility(), visibility);
7711 observed.borrow_mut().push(visibility);
7712 })
7713 }
7714 })
7715 .unwrap();
7716 let test_window = cx.test_window(window.into());
7717 let frame_wake_count = test_window.frame_wake_count();
7718
7719 test_window.simulate_visibility_change(WindowVisibility::Hidden);
7720 assert_eq!(*observed.borrow(), [WindowVisibility::Hidden]);
7721 window
7722 .update(cx, |_, window, _| assert!(!window.is_visible()))
7723 .unwrap();
7724
7725 test_window.simulate_visibility_change(WindowVisibility::Hidden);
7727 assert_eq!(observed.borrow().len(), 1);
7728
7729 test_window.simulate_visibility_change(WindowVisibility::Visible);
7730 assert_eq!(
7731 *observed.borrow(),
7732 [WindowVisibility::Hidden, WindowVisibility::Visible]
7733 );
7734 window
7735 .update(cx, |_, window, _| assert!(window.is_visible()))
7736 .unwrap();
7737 assert_eq!(test_window.frame_wake_count(), frame_wake_count);
7738 }
7739
7740 #[gpui::test]
7741 fn test_fully_visible_bounds_preserve_layout_viewport(cx: &mut TestAppContext) {
7742 let window = cx.add_window(|_, _| EmptyView);
7743 let mut platform_window = cx.test_window(window.into());
7744 platform_window.simulate_resize(size(px(400.), px(800.)));
7745 window
7746 .update(cx, |_, window, _| {
7747 assert_eq!(
7748 window.visual_viewport_bounds(),
7749 Bounds::new(Point::default(), size(px(400.), px(800.)))
7750 );
7751 assert_eq!(
7752 window.fully_visible_bounds(),
7753 window.visual_viewport_bounds()
7754 );
7755 })
7756 .unwrap();
7757
7758 platform_window.simulate_frame_request(RequestFrameOptions::default());
7759 let wakes = platform_window.frame_wake_count();
7760 let visual_bounds = Bounds::new(point(px(10.), px(40.)), size(px(380.), px(460.)));
7761 platform_window.simulate_visual_viewport_change(visual_bounds);
7762 assert!(platform_window.frame_wake_count() > wakes);
7763 platform_window.simulate_frame_request(RequestFrameOptions::default());
7764 let wakes = platform_window.frame_wake_count();
7765 platform_window.simulate_insets_change(crate::WindowInsets {
7766 safe_area: crate::Edges {
7767 top: px(60.),
7768 right: px(20.),
7769 bottom: px(30.),
7770 left: px(-10.),
7771 },
7772 ime: crate::Edges {
7773 bottom: px(350.),
7774 ..Default::default()
7775 },
7776 });
7777 assert!(platform_window.frame_wake_count() > wakes);
7778 window
7779 .update(cx, |_, window, _| {
7780 assert_eq!(window.viewport_size(), size(px(400.), px(800.)));
7781 assert_eq!(window.visual_viewport_bounds(), visual_bounds);
7782 assert_eq!(
7783 window.fully_visible_bounds(),
7784 Bounds::new(point(px(10.), px(60.)), size(px(370.), px(390.)))
7785 );
7786 window.request_virtual_keyboard();
7787 window.dismiss_virtual_keyboard();
7788 assert_eq!(window.viewport_size(), size(px(400.), px(800.)));
7789 })
7790 .unwrap();
7791 assert_eq!(platform_window.virtual_keyboard_requests(), 1);
7792 assert_eq!(platform_window.virtual_keyboard_dismissals(), 1);
7793
7794 platform_window.simulate_insets_change(crate::WindowInsets {
7795 safe_area: crate::Edges {
7796 top: px(900.),
7797 left: px(500.),
7798 ..Default::default()
7799 },
7800 ..Default::default()
7801 });
7802 window
7803 .update(cx, |_, window, _| {
7804 assert_eq!(
7805 window.fully_visible_bounds().size,
7806 size(Pixels::ZERO, Pixels::ZERO)
7807 );
7808 })
7809 .unwrap();
7810 }
7811
7812 struct EmptyView;
7813
7814 impl Render for EmptyView {
7815 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
7816 div()
7817 }
7818 }
7819
7820 struct OpensWindowOnPaint {
7821 opened: Rc<Cell<bool>>,
7822 }
7823
7824 impl Render for OpensWindowOnPaint {
7825 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
7826 let opened = self.opened.clone();
7827 div()
7828 .size_full()
7829 .child(canvas(
7830 |_, _, _| {},
7831 move |_, _, _window, cx| {
7832 if !opened.replace(true) {
7833 cx.open_window(WindowOptions::default(), |_, cx| cx.new(|_| EmptyView))
7834 .unwrap();
7835 }
7836 },
7837 ))
7838 .child(div().child("after"))
7842 }
7843 }
7844
7845 #[test]
7851 fn test_window_opened_during_draw_defers_arena_clear() {
7852 let mut cx = TestAppContext::single();
7853
7854 let opened = Rc::new(Cell::new(false));
7855 let window = cx.add_window({
7857 let opened = opened.clone();
7858 move |_, _| OpensWindowOnPaint { opened }
7859 });
7860
7861 assert!(opened.get());
7862 assert_eq!(cx.windows().len(), 2);
7863
7864 cx.update_window(window.into(), |_, window, cx| window.draw(cx).clear(cx))
7867 .unwrap();
7868 }
7869
7870 #[test]
7871 fn test_scale_factor_change_preserves_bounds_and_survives_resize() {
7872 let mut cx = TestAppContext::single();
7873 let window = cx.add_window(|_, _| EmptyView);
7874 let handle: AnyWindowHandle = window.into();
7875 let window_state = |cx: &mut TestAppContext| {
7876 cx.update_window(handle, |_, window, _| {
7877 (
7878 window.scale_factor(),
7879 window.bounds(),
7880 window.viewport_size(),
7881 )
7882 })
7883 .unwrap()
7884 };
7885
7886 let (scale_factor, mut expected_bounds, _) = window_state(&mut cx);
7887 assert_eq!(scale_factor, 2.0);
7888
7889 for (scale_factor, resized_size) in [
7890 (1.0, size(px(800.), px(600.))),
7891 (1.25, size(px(640.), px(480.))),
7892 (2.0, size(px(1024.), px(768.))),
7893 ] {
7894 cx.simulate_window_scale_factor_change(handle, scale_factor);
7895 assert_eq!(
7896 window_state(&mut cx),
7897 (scale_factor, expected_bounds, expected_bounds.size)
7898 );
7899
7900 cx.simulate_window_resize(handle, resized_size);
7901 expected_bounds.size = resized_size;
7902 assert_eq!(
7903 window_state(&mut cx),
7904 (scale_factor, expected_bounds, resized_size)
7905 );
7906 }
7907 }
7908
7909 #[gpui::test]
7914 fn test_frame_waker_fires_on_frame_demand(cx: &mut TestAppContext) {
7915 let window = cx.add_window(|_, _| EmptyView);
7916 let test_window = cx.test_window(window.into());
7917
7918 assert!(
7922 test_window.frame_wake_count() >= 1,
7923 "opening a window must wake the frame source for the initial frame"
7924 );
7925
7926 test_window.simulate_frame_request(RequestFrameOptions::default());
7928
7929 let baseline = test_window.frame_wake_count();
7932 test_window.simulate_frame_request(RequestFrameOptions::default());
7933 window.update(cx, |_, _, _| {}).unwrap();
7934 assert_eq!(
7935 test_window.frame_wake_count(),
7936 baseline,
7937 "clean frames and non-notifying updates must not wake the frame source"
7938 );
7939
7940 window.update(cx, |_, _, cx| cx.notify()).unwrap();
7942 assert!(
7943 test_window.frame_wake_count() > baseline,
7944 "notifying a view in an idle window must wake the frame source"
7945 );
7946
7947 test_window.simulate_frame_request(RequestFrameOptions::default());
7949 let baseline = test_window.frame_wake_count();
7950 test_window.simulate_frame_request(RequestFrameOptions::default());
7951 assert_eq!(
7952 test_window.frame_wake_count(),
7953 baseline,
7954 "serving demand must return the window to idle"
7955 );
7956
7957 window
7959 .update(cx, |_, window, _| window.on_next_frame(|_, _| {}))
7960 .unwrap();
7961 assert!(
7962 test_window.frame_wake_count() > baseline,
7963 "scheduling a next-frame callback in an idle window must wake the frame source"
7964 );
7965 }
7966
7967 #[gpui::test]
7972 fn test_pending_next_frame_callbacks_are_not_stranded(cx: &mut TestAppContext) {
7973 let window = cx.add_window(|_, _| EmptyView);
7974 let test_window = cx.test_window(window.into());
7975 test_window.simulate_frame_request(RequestFrameOptions::default());
7978
7979 let callback_ran = Rc::new(Cell::new(false));
7980 window
7981 .update(cx, {
7982 let callback_ran = callback_ran.clone();
7983 move |_, window, _| {
7984 window.on_next_frame(move |_, _| callback_ran.set(true));
7985 }
7986 })
7987 .unwrap();
7988
7989 let baseline = test_window.frame_wake_count();
7990 test_window.simulate_frame_request(RequestFrameOptions::default());
7991 assert!(
7998 test_window.frame_wake_count() > baseline || callback_ran.get(),
7999 "a frame request with pending next-frame callbacks must either run them or re-arm the frame source"
8000 );
8001 }
8002
8003 #[gpui::test]
8004 fn test_window_reports_no_raw_handle_instead_of_panicking(cx: &mut TestAppContext) {
8005 use raw_window_handle::{HandleError, HasDisplayHandle as _, HasWindowHandle as _};
8006
8007 let window = cx.add_window(|_, _| EmptyView);
8008 window
8009 .update(cx, |_, window, _| {
8010 assert!(matches!(
8011 window.window_handle(),
8012 Err(HandleError::NotSupported)
8013 ));
8014 assert!(matches!(
8015 window.display_handle(),
8016 Err(HandleError::NotSupported)
8017 ));
8018 })
8019 .unwrap();
8020 }
8021
8022 #[gpui::test]
8023 fn test_appearance_change_runs_after_app_update(cx: &mut TestAppContext) {
8024 let window = cx.add_window(|_, _| EmptyView);
8025 let observed_appearance = Rc::new(Cell::new(None));
8026 let _subscription = window
8027 .update(cx, {
8028 let observed_appearance = observed_appearance.clone();
8029 move |_, window, _| {
8030 window.observe_window_appearance(move |window, _| {
8031 observed_appearance.set(Some(window.appearance()));
8032 })
8033 }
8034 })
8035 .unwrap();
8036 let test_window = cx.test_window(window.into());
8037
8038 cx.update(|_| {
8039 test_window.simulate_appearance_change(WindowAppearance::Dark);
8040 assert_eq!(observed_appearance.get(), None);
8041 });
8042 cx.run_until_parked();
8043
8044 assert_eq!(observed_appearance.get(), Some(WindowAppearance::Dark));
8045 }
8046
8047 #[gpui::test]
8048 fn queued_frame_callback_wakes_a_parked_render_loop(cx: &mut TestAppContext) {
8049 let window = cx.add_window(|_, _| Empty);
8050 let test_window = cx.test_window(window.into());
8051
8052 assert!(test_window.simulate_scheduled_frame());
8053 assert!(test_window.simulate_scheduled_frame());
8054 assert!(!test_window.frame_scheduled());
8055
8056 cx.update_window(window.into(), |_, window, _| {
8057 window.active.set(true);
8058 window.on_next_frame(|_, _| {});
8059 })
8060 .unwrap();
8061 assert!(
8062 test_window.frame_scheduled(),
8063 "queuing work on a parked window must wake the render loop"
8064 );
8065
8066 assert!(test_window.simulate_scheduled_frame());
8067 assert!(
8068 test_window.frame_scheduled(),
8069 "presenting the frame must await one compositor callback"
8070 );
8071 assert!(test_window.simulate_scheduled_frame());
8072 assert!(!test_window.frame_scheduled());
8073 }
8074
8075 #[gpui::test]
8076 fn pending_presentation_wakes_a_parked_render_loop(cx: &mut TestAppContext) {
8077 let window = cx.add_window(|_, _| Empty);
8078 let test_window = cx.test_window(window.into());
8079
8080 assert!(test_window.simulate_scheduled_frame());
8081 assert!(test_window.simulate_scheduled_frame());
8082 assert!(!test_window.frame_scheduled());
8083
8084 cx.update_window(window.into(), |_, window, cx| window.draw(cx).clear(cx))
8085 .unwrap();
8086
8087 assert!(
8088 test_window.frame_scheduled(),
8089 "a rendered scene awaiting presentation must wake the render loop"
8090 );
8091 }
8092
8093 #[gpui::test]
8094 fn callback_queued_during_a_frame_requests_a_follow_up(cx: &mut TestAppContext) {
8095 let window = cx.add_window(|_, _| Empty);
8096 let test_window = cx.test_window(window.into());
8097
8098 let callback_ran = Rc::new(Cell::new(false));
8099 cx.update_window(window.into(), |_, window, _| {
8100 window.active.set(true);
8103 let callback_ran = callback_ran.clone();
8104 window.on_next_frame(move |window, _| {
8105 window.on_next_frame(move |_, _| callback_ran.set(true));
8106 });
8107 })
8108 .unwrap();
8109
8110 assert!(test_window.simulate_scheduled_frame());
8111 assert!(!callback_ran.get());
8112 assert!(
8113 test_window.frame_scheduled(),
8114 "a callback queued mid-frame must schedule a follow-up before the loop parks"
8115 );
8116
8117 assert!(test_window.simulate_scheduled_frame());
8118 assert!(callback_ran.get());
8119 }
8120
8121 struct RootView {
8122 explicit_size: bool,
8123 child_bounds: Rc<Cell<Bounds<Pixels>>>,
8124 }
8125
8126 impl Render for RootView {
8127 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
8128 let child_bounds = self.child_bounds.clone();
8129 let root = div().flex().flex_col().child(
8130 canvas(
8131 move |bounds, _, _| child_bounds.set(bounds),
8132 |_, _, _, _| {},
8133 )
8134 .size_full(),
8135 );
8136 if self.explicit_size {
8137 root.w(px(300.)).h(px(200.))
8138 } else {
8139 root
8140 }
8141 }
8142 }
8143
8144 #[test]
8145 fn auto_sized_window_root_fills_the_window() {
8146 let mut cx = TestAppContext::single();
8147 let child_bounds = Rc::new(Cell::new(Bounds::default()));
8148 let window = cx.add_window({
8149 let child_bounds = child_bounds.clone();
8150 move |_, _| RootView {
8151 explicit_size: false,
8152 child_bounds,
8153 }
8154 });
8155
8156 let viewport_size = cx
8157 .update_window(window.into(), |_, window, cx| {
8158 window.draw(cx).clear(cx);
8159 window.viewport_size()
8160 })
8161 .unwrap();
8162
8163 assert_eq!(child_bounds.get().size, viewport_size);
8164 }
8165
8166 #[test]
8167 fn explicitly_sized_window_root_keeps_its_size() {
8168 let mut cx = TestAppContext::single();
8169 let child_bounds = Rc::new(Cell::new(Bounds::default()));
8170 let window = cx.add_window({
8171 let child_bounds = child_bounds.clone();
8172 move |_, _| RootView {
8173 explicit_size: true,
8174 child_bounds,
8175 }
8176 });
8177
8178 cx.update_window(window.into(), |_, window, cx| {
8179 window.draw(cx).clear(cx);
8180 })
8181 .unwrap();
8182
8183 assert_eq!(child_bounds.get().size, size(px(300.), px(200.)));
8184 }
8185
8186 struct FileDragView {
8187 path: PathBuf,
8188 observed_drag_moves: Rc<RefCell<Vec<Point<Pixels>>>>,
8189 observed_drops: Rc<RefCell<Vec<PathBuf>>>,
8190 }
8191
8192 struct FileDropExitView(Rc<Cell<usize>>);
8193
8194 impl Render for FileDropExitView {
8195 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
8196 div().size_full().on_file_drop_exit({
8197 let observed_file_drop_exit = self.0.clone();
8198 move |_, _, _| observed_file_drop_exit.set(observed_file_drop_exit.get() + 1)
8199 })
8200 }
8201 }
8202
8203 impl Render for FileDragView {
8204 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
8205 div()
8206 .id("file-drag")
8207 .size_full()
8208 .on_drag(self.path.clone(), |_, _, _, cx| cx.new(|_| Empty))
8209 .external_drag_payload(|path: &PathBuf, _, _| {
8210 Some(ExternalDragPayload::Files(FileDragPaths::new([(
8211 path.clone(),
8212 true,
8213 )])))
8214 })
8215 .on_drag_move({
8216 let observed_drag_moves = self.observed_drag_moves.clone();
8217 move |event: &DragMoveEvent<PathBuf>, _, _| {
8218 observed_drag_moves.borrow_mut().push(event.event.position);
8219 }
8220 })
8221 .on_drop({
8222 let observed_drops = self.observed_drops.clone();
8223 move |path: &PathBuf, _, _| observed_drops.borrow_mut().push(path.clone())
8224 })
8225 }
8226 }
8227
8228 #[gpui::test]
8229 fn file_drag_is_promoted_once_and_restored_in_source_window(cx: &mut TestAppContext) {
8230 struct Drag {
8231 window: AnyWindowHandle,
8232 observed_drag_moves: Rc<RefCell<Vec<Point<Pixels>>>>,
8233 observed_drops: Rc<RefCell<Vec<PathBuf>>>,
8234 }
8235
8236 fn start_drag(cx: &mut TestAppContext, path: PathBuf, platform_result: bool) -> Drag {
8237 let observed_drag_moves = Rc::new(RefCell::new(Vec::new()));
8238 let observed_drops = Rc::new(RefCell::new(Vec::new()));
8239 let window: AnyWindowHandle = cx
8240 .add_window({
8241 let observed_drag_moves = observed_drag_moves.clone();
8242 let observed_drops = observed_drops.clone();
8243 move |_, _| FileDragView {
8244 path,
8245 observed_drag_moves,
8246 observed_drops,
8247 }
8248 })
8249 .into();
8250 cx.test_window(window)
8251 .set_start_external_drag_result(platform_result);
8252
8253 let update_result = cx.update_window(window, |_, window, cx| {
8254 window.draw(cx).clear(cx);
8255 window.dispatch_event(
8256 MouseDownEvent {
8257 position: point(px(10.), px(10.)),
8258 button: MouseButton::Left,
8259 modifiers: Default::default(),
8260 click_count: 1,
8261 first_mouse: false,
8262 }
8263 .to_platform_input(),
8264 cx,
8265 );
8266 window.dispatch_event(
8267 MouseMoveEvent {
8268 position: point(px(20.), px(20.)),
8269 pressed_button: Some(MouseButton::Left),
8270 modifiers: Default::default(),
8271 }
8272 .to_platform_input(),
8273 cx,
8274 );
8275 assert!(cx.active_drag.is_some());
8276 });
8277 assert!(
8278 update_result.is_ok(),
8279 "failed to start drag: {update_result:?}"
8280 );
8281
8282 assert!(cx.test_window(window).external_drag_files().is_empty());
8283 Drag {
8284 window,
8285 observed_drag_moves,
8286 observed_drops,
8287 }
8288 }
8289
8290 let successful_path = PathBuf::from("/tmp/successful-drag");
8291 let successful = start_drag(cx, successful_path.clone(), true);
8292 let outside_position = point(px(-1.), px(20.));
8293 let update_result = cx.update_window(successful.window, |_, window, cx| {
8294 window.dispatch_event(
8295 MouseMoveEvent {
8296 position: outside_position,
8297 pressed_button: Some(MouseButton::Left),
8298 modifiers: Default::default(),
8299 }
8300 .to_platform_input(),
8301 cx,
8302 );
8303 assert!(cx.active_drag.is_none());
8304 });
8305 assert!(
8306 update_result.is_ok(),
8307 "failed to promote drag: {update_result:?}"
8308 );
8309 assert_eq!(
8310 cx.test_window(successful.window).external_drag_files(),
8311 [(successful_path.clone(), true)]
8312 );
8313 assert_eq!(
8316 successful.observed_drag_moves.borrow().last(),
8317 Some(&outside_position)
8318 );
8319
8320 let first_destination_exit_count = Rc::new(Cell::new(0));
8321 let first_destination: AnyWindowHandle = cx
8322 .add_window({
8323 let first_destination_exit_count = first_destination_exit_count.clone();
8324 move |_, _| FileDropExitView(first_destination_exit_count)
8325 })
8326 .into();
8327 let second_destination_exit_count = Rc::new(Cell::new(0));
8328 let second_destination: AnyWindowHandle = cx
8329 .add_window({
8330 let second_destination_exit_count = second_destination_exit_count.clone();
8331 move |_, _| FileDropExitView(second_destination_exit_count)
8332 })
8333 .into();
8334 let reentry_position = point(px(30.), px(30.));
8335 let external_paths = || ExternalPaths([successful_path.clone()].into_iter().collect());
8336 let update_result = cx.update_window(first_destination, |_, window, cx| {
8337 window.draw(cx).clear(cx);
8338 window.dispatch_event(
8339 FileDropEvent::Entered {
8340 position: reentry_position,
8341 paths: external_paths(),
8342 }
8343 .to_platform_input(),
8344 cx,
8345 );
8346 assert!(
8347 cx.active_drag
8348 .as_ref()
8349 .is_some_and(|drag| drag.value.downcast_ref::<ExternalPaths>().is_some())
8350 );
8351 window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
8352 assert!(cx.active_drag.is_none());
8353 assert_eq!(first_destination_exit_count.get(), 1);
8354 assert_eq!(second_destination_exit_count.get(), 0);
8355 });
8356 assert!(
8357 update_result.is_ok(),
8358 "failed to handle drag in first destination window: {update_result:?}"
8359 );
8360
8361 let update_result = cx.update_window(second_destination, |_, window, cx| {
8362 window.draw(cx).clear(cx);
8363 window.dispatch_event(
8364 PlatformInput::KeyDown(KeyDownEvent {
8365 keystroke: Keystroke::parse("down").expect("valid keystroke"),
8366 is_held: false,
8367 prefer_character_input: false,
8368 }),
8369 cx,
8370 );
8371 window.dispatch_event(
8372 FileDropEvent::Entered {
8373 position: reentry_position,
8374 paths: external_paths(),
8375 }
8376 .to_platform_input(),
8377 cx,
8378 );
8379 assert!(
8380 cx.active_drag
8381 .as_ref()
8382 .is_some_and(|drag| drag.value.downcast_ref::<ExternalPaths>().is_some())
8383 );
8384 assert_eq!(first_destination_exit_count.get(), 1);
8385 assert_eq!(second_destination_exit_count.get(), 0);
8386
8387 window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
8388 assert!(cx.active_drag.is_none());
8389 assert_eq!(first_destination_exit_count.get(), 1);
8390 assert_eq!(second_destination_exit_count.get(), 1);
8391 });
8392 assert!(
8393 update_result.is_ok(),
8394 "failed to handle drag in second destination window: {update_result:?}"
8395 );
8396
8397 let update_result = cx.update_window(successful.window, |_, window, cx| {
8398 window.dispatch_event(
8399 FileDropEvent::Entered {
8400 position: reentry_position,
8401 paths: external_paths(),
8402 }
8403 .to_platform_input(),
8404 cx,
8405 );
8406 assert!(
8407 cx.active_drag
8408 .as_ref()
8409 .is_some_and(|drag| drag.value.downcast_ref::<PathBuf>().is_some())
8410 );
8411 assert_eq!(
8412 successful.observed_drag_moves.borrow().last(),
8413 Some(&reentry_position)
8414 );
8415
8416 window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
8417 assert!(cx.active_drag.is_none());
8418
8419 window.dispatch_event(
8420 FileDropEvent::Entered {
8421 position: reentry_position,
8422 paths: external_paths(),
8423 }
8424 .to_platform_input(),
8425 cx,
8426 );
8427 assert!(
8428 cx.active_drag
8429 .as_ref()
8430 .is_some_and(|drag| drag.value.downcast_ref::<PathBuf>().is_some())
8431 );
8432
8433 window.dispatch_event(
8434 FileDropEvent::Submit {
8435 position: reentry_position,
8436 }
8437 .to_platform_input(),
8438 cx,
8439 );
8440 assert_eq!(
8441 successful.observed_drops.borrow().as_slice(),
8442 std::slice::from_ref(&successful_path)
8443 );
8444 assert!(cx.active_drag.is_none());
8445
8446 window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
8447 assert!(cx.active_drag.is_none());
8448 window.dispatch_event(FileDropEvent::Ended.to_platform_input(), cx);
8449 assert!(cx.active_drag.is_none());
8450
8451 window.dispatch_event(
8452 FileDropEvent::Entered {
8453 position: reentry_position,
8454 paths: external_paths(),
8455 }
8456 .to_platform_input(),
8457 cx,
8458 );
8459 assert!(
8460 cx.active_drag
8461 .as_ref()
8462 .is_some_and(|drag| drag.value.downcast_ref::<ExternalPaths>().is_some())
8463 );
8464 window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
8465 });
8466 assert!(
8467 update_result.is_ok(),
8468 "failed to restore drag in source window: {update_result:?}"
8469 );
8470
8471 let cancelled_path = PathBuf::from("/tmp/cancelled-drag");
8472 let cancelled = start_drag(cx, cancelled_path.clone(), true);
8473 let update_result = cx.update_window(cancelled.window, |_, window, cx| {
8474 window.dispatch_event(
8475 MouseMoveEvent {
8476 position: outside_position,
8477 pressed_button: Some(MouseButton::Left),
8478 modifiers: Default::default(),
8479 }
8480 .to_platform_input(),
8481 cx,
8482 );
8483 assert!(cx.active_drag.is_none());
8484
8485 window.dispatch_event(
8486 FileDropEvent::Entered {
8487 position: reentry_position,
8488 paths: ExternalPaths([cancelled_path].into_iter().collect()),
8489 }
8490 .to_platform_input(),
8491 cx,
8492 );
8493 assert!(
8494 cx.active_drag
8495 .as_ref()
8496 .is_some_and(|drag| drag.value.downcast_ref::<PathBuf>().is_some())
8497 );
8498 assert!(cx.stop_active_drag(window));
8499 assert!(cx.active_drag.is_none());
8500 });
8501 assert!(
8502 update_result.is_ok(),
8503 "failed to cancel restored drag: {update_result:?}"
8504 );
8505 assert!(!cx.update(|cx| cx.end_platform_drag(cancelled.window.window_id())));
8506
8507 let removed_path = PathBuf::from("/tmp/removed-window-drag");
8508 let removed = start_drag(cx, removed_path, true);
8509 let removed_window_id = removed.window.window_id();
8510 let update_result = cx.update_window(removed.window, |_, window, cx| {
8511 window.dispatch_event(
8512 MouseMoveEvent {
8513 position: outside_position,
8514 pressed_button: Some(MouseButton::Left),
8515 modifiers: Default::default(),
8516 }
8517 .to_platform_input(),
8518 cx,
8519 );
8520 assert!(cx.active_drag.is_none());
8521 window.remove_window();
8522 });
8523 assert!(
8524 update_result.is_ok(),
8525 "failed to remove drag source window: {update_result:?}"
8526 );
8527 assert!(!cx.update(|cx| cx.end_platform_drag(removed_window_id)));
8528
8529 let failed_path = PathBuf::from("/tmp/failed-drag");
8530 let failed = start_drag(cx, failed_path.clone(), false);
8531 let update_result = cx.update_window(failed.window, |_, window, cx| {
8532 for x_position in [-1., -2.] {
8533 window.dispatch_event(
8534 MouseMoveEvent {
8535 position: point(px(x_position), px(20.)),
8536 pressed_button: Some(MouseButton::Left),
8537 modifiers: Default::default(),
8538 }
8539 .to_platform_input(),
8540 cx,
8541 );
8542 }
8543 assert!(cx.active_drag.is_some());
8544 });
8545 assert!(
8546 update_result.is_ok(),
8547 "failed to retain drag after platform failure: {update_result:?}"
8548 );
8549 assert_eq!(
8550 cx.test_window(failed.window).external_drag_files(),
8551 [(failed_path, true)]
8552 );
8553 }
8554
8555 struct FocusForwarder {
8556 a: FocusHandle,
8557 b: FocusHandle,
8558 }
8559
8560 impl Render for FocusForwarder {
8561 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
8562 div()
8563 .size_full()
8564 .child(div().w(px(50.)).h(px(50.)).track_focus(&self.a))
8565 .child(div().w(px(50.)).h(px(50.)).track_focus(&self.b))
8566 }
8567 }
8568
8569 #[gpui::test]
8573 fn test_focus_moved_by_focus_listener_is_dispatched(cx: &mut TestAppContext) {
8574 let b_focus_count = Rc::new(Cell::new(0));
8575 let window = cx.add_window({
8576 let b_focus_count = b_focus_count.clone();
8577 move |window, cx| {
8578 let a = cx.focus_handle();
8579 let b = cx.focus_handle();
8580 cx.on_focus(&a, window, |this: &mut FocusForwarder, window, cx| {
8581 let b = this.b.clone();
8582 window.focus(&b, cx);
8583 })
8584 .detach();
8585 cx.on_focus(&b, window, move |_, _, _| {
8586 b_focus_count.set(b_focus_count.get() + 1);
8587 })
8588 .detach();
8589 FocusForwarder { a, b }
8590 }
8591 });
8592
8593 window
8594 .update(cx, |_, window, _| window.activate_window())
8595 .unwrap();
8596 cx.executor().run_until_parked();
8597
8598 window
8599 .update(cx, |this, window, cx| {
8600 let a = this.a.clone();
8601 window.focus(&a, cx);
8602 })
8603 .unwrap();
8604 cx.executor().run_until_parked();
8605
8606 window
8607 .update(cx, |this, window, _| {
8608 assert!(this.b.is_focused(window));
8609 })
8610 .unwrap();
8611 assert_eq!(b_focus_count.get(), 1);
8612 }
8613
8614 #[gpui::test]
8615 fn claimed_touch_drag_receives_movement_and_release(cx: &mut TestAppContext) {
8616 let events = Rc::new(RefCell::new(Vec::new()));
8617 let window = cx.add_window({
8618 let events = events.clone();
8619 move |_, _| TouchDragListener { events }
8620 });
8621 let touch = TouchId(1);
8622
8623 dispatch_touch(window, cx, touch, TouchPhase::Started, 10.);
8624 dispatch_touch(window, cx, touch, TouchPhase::Moved, 30.);
8625 dispatch_touch(window, cx, touch, TouchPhase::Ended, 40.);
8626
8627 assert_eq!(
8628 events.borrow().as_slice(),
8629 [
8630 (TouchPhase::Started, px(10.)),
8631 (TouchPhase::Moved, px(30.)),
8632 (TouchPhase::Ended, px(40.)),
8633 ]
8634 );
8635 }
8636
8637 struct TouchDragListener {
8638 events: Rc<RefCell<Vec<(TouchPhase, Pixels)>>>,
8639 }
8640
8641 impl Render for TouchDragListener {
8642 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
8643 let events = self.events.clone();
8644 canvas(
8645 |_, _, _| {},
8646 move |_, _, window, _| {
8647 window.on_mouse_event(move |event: &TouchDragEvent, phase, window, _cx| {
8648 if phase != DispatchPhase::Bubble {
8649 return;
8650 }
8651 events.borrow_mut().push((event.phase, event.position.x));
8652 if event.phase == TouchPhase::Started {
8653 window.prevent_default();
8654 }
8655 });
8656 },
8657 )
8658 }
8659 }
8660
8661 #[gpui::test]
8662 fn long_press_is_claimed_only_when_started_prevents_default(cx: &mut TestAppContext) {
8663 for response in [
8664 LongPressResponse::PreventDefault,
8665 LongPressResponse::StopPropagation,
8666 LongPressResponse::None,
8667 ] {
8668 let phases = Rc::new(RefCell::new(Vec::new()));
8669 let window = cx.add_window({
8670 let phases = phases.clone();
8671 move |_, _| LongPressListener { phases, response }
8672 });
8673 dispatch_touch(window, cx, TouchId(1), TouchPhase::Started, 0.);
8674 cx.executor().advance_clock(Duration::from_millis(501));
8675 cx.executor().run_until_parked();
8676 window
8677 .update(cx, |_, window, _| {
8678 assert_eq!(
8679 window.long_press_capture.is_some(),
8680 response == LongPressResponse::PreventDefault
8681 );
8682 })
8683 .unwrap();
8684 dispatch_touch(window, cx, TouchId(1), TouchPhase::Moved, 2.);
8685 dispatch_touch(window, cx, TouchId(1), TouchPhase::Ended, 2.);
8686 window
8687 .update(cx, |_, window, _| {
8688 assert!(window.long_press_capture.is_none());
8689 })
8690 .unwrap();
8691
8692 let phases = phases.borrow();
8693 if response == LongPressResponse::PreventDefault {
8694 assert_eq!(
8695 phases.as_slice(),
8696 [TouchPhase::Started, TouchPhase::Moved, TouchPhase::Ended]
8697 );
8698 } else {
8699 assert_eq!(phases.as_slice(), [TouchPhase::Started]);
8700 }
8701 }
8702 }
8703
8704 #[gpui::test]
8705 fn stale_default_prevention_does_not_claim_long_press(cx: &mut TestAppContext) {
8706 let phases = Rc::new(RefCell::new(Vec::new()));
8707 let window = cx.add_window({
8708 let phases = phases.clone();
8709 move |_, _| LongPressListener {
8710 phases,
8711 response: LongPressResponse::None,
8712 }
8713 });
8714 window
8715 .update(cx, |_, window, _| {
8716 window.prevent_default();
8717 })
8718 .unwrap();
8719
8720 dispatch_touch(window, cx, TouchId(1), TouchPhase::Started, 0.);
8721 cx.executor().advance_clock(Duration::from_millis(501));
8722 cx.executor().run_until_parked();
8723 dispatch_touch(window, cx, TouchId(1), TouchPhase::Moved, 2.);
8724
8725 assert_eq!(phases.borrow().as_slice(), [TouchPhase::Started]);
8726 }
8727
8728 #[gpui::test]
8729 fn resolved_touch_cancels_scheduled_long_press(cx: &mut TestAppContext) {
8730 for (phase, position) in [
8731 (TouchPhase::Ended, 0.),
8732 (TouchPhase::Cancelled, 0.),
8733 (TouchPhase::Moved, 20.),
8734 ] {
8735 let phases = Rc::new(RefCell::new(Vec::new()));
8736 let window = cx.add_window({
8737 let phases = phases.clone();
8738 move |_, _| LongPressListener {
8739 phases,
8740 response: LongPressResponse::PreventDefault,
8741 }
8742 });
8743 dispatch_touch(window, cx, TouchId(1), TouchPhase::Started, 0.);
8744 dispatch_touch(window, cx, TouchId(1), phase, position);
8745 cx.executor().advance_clock(Duration::from_millis(501));
8746 cx.executor().run_until_parked();
8747
8748 assert!(phases.borrow().is_empty(), "{phase:?} allowed long press");
8749 }
8750 }
8751
8752 #[gpui::test]
8753 fn stale_long_press_timer_cannot_affect_replacement_touch(cx: &mut TestAppContext) {
8754 let phases = Rc::new(RefCell::new(Vec::new()));
8755 let window = cx.add_window({
8756 let phases = phases.clone();
8757 move |_, _| LongPressListener {
8758 phases,
8759 response: LongPressResponse::PreventDefault,
8760 }
8761 });
8762 let first_touch = TouchId(1);
8763 dispatch_touch(window, cx, first_touch, TouchPhase::Started, 0.);
8764 cx.executor().advance_clock(Duration::from_millis(250));
8765 dispatch_touch(window, cx, first_touch, TouchPhase::Cancelled, 0.);
8766 dispatch_touch(window, cx, TouchId(2), TouchPhase::Started, 10.);
8767
8768 cx.executor().advance_clock(Duration::from_millis(251));
8769 cx.executor().run_until_parked();
8770 assert!(phases.borrow().is_empty());
8771
8772 cx.executor().advance_clock(Duration::from_millis(250));
8773 cx.executor().run_until_parked();
8774 assert_eq!(phases.borrow().as_slice(), [TouchPhase::Started]);
8775 }
8776
8777 #[gpui::test]
8778 fn test_underline_exclusions_preserve_device_geometry(cx: &mut TestAppContext) {
8779 test_underline_paint_at_scales(cx, |window| {
8780 let (numerator, denominator) = match window.scale_factor() {
8781 1.0 => (1, 1),
8782 1.25 => (5, 4),
8783 1.5 => (3, 2),
8784 2.0 => (2, 1),
8785 3.0 => (3, 1),
8786 scale => panic!("unexpected scale {scale}"),
8787 };
8788 let snap = |quarters: i32| {
8789 let scaled = quarters * numerator;
8790 let divisor = 4 * denominator;
8791 let rounded =
8792 scaled.abs() / divisor + i32::from(2 * (scaled.abs() % divisor) > divisor);
8793 ScaledPixels((scaled.signum() * rounded) as f32)
8794 };
8795 let stroke = |quarters| {
8796 if quarters == 0 {
8797 ScaledPixels(0.)
8798 } else {
8799 snap(quarters).max(ScaledPixels(1.))
8800 }
8801 };
8802
8803 for origin in [-101, -3, -2, -1, 0, 1, 2, 3, 101] {
8804 for width in [0, 1, 3, 84] {
8805 for thickness in [0, 1, 4, 7] {
8806 for wavy in [false, true] {
8807 let style = UnderlineStyle {
8808 thickness: px(thickness as f32 / 4.),
8809 color: Some(hsla(0.25, 0.5, 0.75, 0.5)),
8810 wavy,
8811 };
8812 let bounds = Bounds::new(
8813 point(snap(origin), snap(-origin)),
8814 size(
8815 stroke(width),
8816 stroke(thickness) * if wavy { 3. } else { 1. },
8817 ),
8818 );
8819 let origin = point(px(origin as f32 / 4.), px(-origin as f32 / 4.));
8820 let width = px(width as f32 / 4.);
8821 assert_eq!(window.underline_bounds(origin, width, &style), bounds);
8822 let original = paint_test_underlines(window, |window| {
8823 window.paint_underline(origin, width, &style);
8824 })
8825 .to_vec();
8826 assert_eq!(original.len(), usize::from(!bounds.is_empty()));
8827 if let Some(underline) = original.first() {
8828 assert_eq!(underline.bounds, bounds);
8829 assert_eq!(underline.thickness, stroke(thickness));
8830 assert_eq!(underline.wavy, wavy.into());
8831 assert_eq!(underline.color, hsla(0.25, 0.5, 0.75, 0.5));
8832 }
8833
8834 let underlines = paint_test_underlines(window, |window| {
8835 window.paint_underline_with_exclusions(origin, width, &style, &[]);
8836 });
8837 assert_eq!(underlines.len(), original.len());
8838 for (actual, original) in underlines.iter().zip(&original) {
8839 assert_same_underline_geometry(actual, original);
8840 assert_eq!(actual.content_mask, original.content_mask);
8841 }
8842
8843 let left = bounds.left().0 as i32;
8844 let right = bounds.right().0 as i32;
8845 let exclusions = [
8846 (15, 25),
8847 (3, 7),
8848 (5, 10),
8849 (10, 12),
8850 (0, 0),
8851 (4, 2),
8852 (-50, -1),
8853 (70, 100),
8854 ]
8855 .map(|(start, end)| {
8856 ScaledPixels((left + start) as f32)
8857 ..ScaledPixels((left + end) as f32)
8858 });
8859 let underlines = paint_test_underlines(window, |window| {
8860 window.paint_underline_with_exclusions(
8861 origin,
8862 width,
8863 &style,
8864 &exclusions,
8865 );
8866 });
8867 let expected = (left..right)
8868 .filter(|column| {
8869 !bounds.is_empty()
8870 && !exclusions.iter().any(|span| {
8871 span.contains(&ScaledPixels(*column as f32))
8872 })
8873 })
8874 .collect::<Vec<_>>();
8875 assert_eq!(underline_device_columns(underlines), expected);
8876 for underline in underlines {
8877 assert_same_underline_geometry(underline, &original[0]);
8878 }
8879 }
8880 }
8881 }
8882 }
8883 });
8884 }
8885
8886 #[gpui::test]
8887 fn test_underline_exclusions_preserve_helvetica_warning_edge(cx: &mut TestAppContext) {
8888 test_underline_paint_at_scales(cx, |window| {
8889 if window.scale_factor() != 2.0 {
8890 return;
8891 }
8892 let style = UnderlineStyle {
8893 thickness: px(1.),
8894 color: None,
8895 wavy: true,
8896 };
8897 let origin = point(px(2.888_183_8), px(15.357_917));
8898 let width = px(23.848_145) - origin.x;
8899 let original = paint_test_underlines(window, |window| {
8900 window.paint_underline(origin, width, &style);
8901 })[0];
8902 assert_eq!(original.bounds.left(), ScaledPixels(6.));
8903 assert_eq!(original.bounds.right(), ScaledPixels(48.));
8904 let point_bounds = window.underline_bounds(origin, px(10.829_102), &style);
8905 assert_eq!(point_bounds.left(), ScaledPixels(6.));
8906 assert_eq!(point_bounds.right(), ScaledPixels(28.));
8907
8908 let underlines = paint_test_underlines(window, |window| {
8909 window.paint_underline_with_exclusions(
8910 origin,
8911 width,
8912 &style,
8913 &[point_bounds.left()..point_bounds.right()],
8914 );
8915 });
8916 assert_eq!(underlines.len(), 1);
8917 assert_same_underline_geometry(&underlines[0], &original);
8918 assert_eq!(
8919 underline_device_columns(underlines),
8920 (28..48).collect::<Vec<_>>()
8921 );
8922 });
8923 }
8924
8925 #[gpui::test]
8926 fn test_underline_exclusions_preserve_content_mask_and_opacity(cx: &mut TestAppContext) {
8927 test_underline_paint_at_scales(cx, |window| {
8928 let scale = window.scale_factor();
8929 let original_mask = window.content_mask();
8930 let original_opacity = window.element_opacity();
8931 let mask = ContentMask {
8932 bounds: Bounds::from_corners(point(px(4.), px(10.)), point(px(16.), px(12.))),
8933 };
8934 let style = UnderlineStyle {
8935 thickness: px(2.),
8936 color: Some(hsla(0.25, 0.5, 0.75, 0.5)),
8937 wavy: true,
8938 };
8939 let origin = point(px(-1.25), px(9.25));
8940 let width = px(24.);
8941 window.with_content_mask(Some(mask), |window| {
8942 window.with_element_opacity(Some(0.5), |window| {
8943 window.with_element_opacity(Some(0.5), |window| {
8944 let original = paint_test_underlines(window, |window| {
8945 window.paint_underline(origin, width, &style);
8946 })[0];
8947 assert_eq!(original.color, hsla(0.25, 0.5, 0.75, 0.125));
8948 let underlines = paint_test_underlines(window, |window| {
8949 window.paint_underline_with_exclusions(
8950 origin,
8951 width,
8952 &style,
8953 &[ScaledPixels(6. * scale)..ScaledPixels(8. * scale)],
8954 );
8955 });
8956 assert_eq!(underlines.len(), 2);
8957 let expected = [(4. * scale, 6. * scale), (8. * scale, 16. * scale)].map(
8958 |(left, right)| {
8959 Bounds::from_corners(
8960 point(ScaledPixels(left), ScaledPixels((10. * scale).floor())),
8961 point(ScaledPixels(right), ScaledPixels((12. * scale).ceil())),
8962 )
8963 },
8964 );
8965 assert_eq!(
8966 underlines
8967 .iter()
8968 .map(|underline| underline.content_mask.bounds)
8969 .collect::<Vec<_>>(),
8970 expected
8971 );
8972 for underline in underlines {
8973 assert_same_underline_geometry(underline, &original);
8974 }
8975 });
8976 });
8977 });
8978 assert_eq!(window.content_mask(), original_mask);
8979 assert_eq!(window.element_opacity(), original_opacity);
8980 });
8981 }
8982
8983 #[gpui::test]
8984 fn test_underline_exclusions_adversarial_permutations(cx: &mut TestAppContext) {
8985 test_underline_paint_at_scales(cx, |window| {
8986 let style = UnderlineStyle {
8987 thickness: px(1.),
8988 color: None,
8989 wavy: true,
8990 };
8991 let origin = point(px(-4.), px(-1.));
8992 let width = px(8.);
8993 let left = (-4. * window.scale_factor()) as i32;
8994 let right = (4. * window.scale_factor()) as i32;
8995 let endpoints = [-16, -8, -1, 0, 1, 8, 16];
8996 for first_start in endpoints {
8997 for first_end in endpoints {
8998 for second_start in endpoints {
8999 for second_end in endpoints {
9000 let exclusions = [first_start..first_end, second_start..second_end];
9001 let expected = (left..right)
9002 .filter(|column| {
9003 !exclusions.iter().any(|span| span.contains(column))
9004 })
9005 .collect::<Vec<_>>();
9006 let exclusions = exclusions.map(|span| {
9007 ScaledPixels(span.start as f32)..ScaledPixels(span.end as f32)
9008 });
9009 let underlines = paint_test_underlines(window, |window| {
9010 window.paint_underline_with_exclusions(
9011 origin,
9012 width,
9013 &style,
9014 &exclusions,
9015 );
9016 });
9017 assert_eq!(
9018 underline_device_columns(underlines),
9019 expected,
9020 "{exclusions:?}"
9021 );
9022 }
9023 }
9024 }
9025 }
9026 });
9027 }
9028
9029 #[derive(Clone, Copy, PartialEq)]
9030 enum LongPressResponse {
9031 PreventDefault,
9032 StopPropagation,
9033 None,
9034 }
9035
9036 struct LongPressListener {
9037 phases: Rc<RefCell<Vec<TouchPhase>>>,
9038 response: LongPressResponse,
9039 }
9040
9041 impl Render for LongPressListener {
9042 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
9043 let entity = cx.entity();
9044 let phases = self.phases.clone();
9045 let response = self.response;
9046 canvas(
9047 |_, _, _| {},
9048 move |_, _, window, _| {
9049 window.on_mouse_event(move |event: &LongPressEvent, phase, window, cx| {
9050 if phase != DispatchPhase::Bubble {
9051 return;
9052 }
9053 phases.borrow_mut().push(event.phase);
9054 match response {
9055 LongPressResponse::PreventDefault => {
9056 window.capture_long_press(&entity);
9057 window.prevent_default();
9058 }
9059 LongPressResponse::StopPropagation => cx.stop_propagation(),
9060 LongPressResponse::None => {}
9061 }
9062 });
9063 },
9064 )
9065 }
9066 }
9067
9068 struct UnderlineTestView(Rc<dyn Fn(&mut Window)>);
9069
9070 impl Render for UnderlineTestView {
9071 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
9072 let paint = self.0.clone();
9073 canvas(
9074 |_, _, _| {},
9075 move |_, _, window, _| {
9076 window.content_mask_stack.push(ContentMask {
9077 bounds: Bounds::from_corners(
9078 point(px(-1000.), px(-1000.)),
9079 point(px(1000.), px(1000.)),
9080 ),
9081 });
9082 paint(window);
9083 window.content_mask_stack.pop();
9084 },
9085 )
9086 .size_full()
9087 }
9088 }
9089
9090 fn test_underline_paint_at_scales(
9091 cx: &mut TestAppContext,
9092 paint: impl Fn(&mut Window) + 'static,
9093 ) {
9094 let window = cx.add_window(move |_, _| UnderlineTestView(Rc::new(paint)));
9095 for scale in [1., 1.25, 1.5, 2., 3.] {
9096 cx.simulate_window_scale_factor_change(window.into(), scale);
9097 cx.update_window(window.into(), |_, window, cx| window.draw(cx).clear(cx))
9098 .unwrap();
9099 }
9100 }
9101
9102 fn paint_test_underlines(window: &mut Window, paint: impl FnOnce(&mut Window)) -> &[Underline] {
9103 window.next_frame.scene.clear();
9104 paint(window);
9105 &window.next_frame.scene.underlines
9106 }
9107
9108 fn assert_same_underline_geometry(actual: &Underline, expected: &Underline) {
9109 assert_eq!(actual.bounds, expected.bounds);
9110 assert_eq!(actual.thickness, expected.thickness);
9111 assert_eq!(actual.wavy, expected.wavy);
9112 assert_eq!(actual.color, expected.color);
9113 assert_eq!(actual.pad, expected.pad);
9114 }
9115
9116 fn underline_device_columns(underlines: &[Underline]) -> Vec<i32> {
9117 underlines
9118 .iter()
9119 .flat_map(|underline| {
9120 let bounds = underline.bounds.intersect(&underline.content_mask.bounds);
9121 bounds.left().0 as i32..bounds.right().0 as i32
9122 })
9123 .collect()
9124 }
9125
9126 fn dispatch_touch<T: 'static>(
9127 window: crate::WindowHandle<T>,
9128 cx: &mut TestAppContext,
9129 id: TouchId,
9130 phase: TouchPhase,
9131 x: f32,
9132 ) {
9133 window
9134 .update(cx, |_, window, cx| {
9135 window.dispatch_event(
9136 TouchEvent {
9137 id,
9138 phase,
9139 position: point(px(x), px(0.)),
9140 predicted_position: None,
9141 force: None,
9142 }
9143 .to_platform_input(),
9144 cx,
9145 );
9146 })
9147 .unwrap();
9148 }
9149}
9150
9151#[cfg(all(test, any(feature = "inspector", debug_assertions)))]
9152mod inspector_tests {
9153 use super::*;
9154 use crate::{
9155 DivInspectorState, InspectorElementId, MouseDownEvent, StyleRefinement, TestAppContext, div,
9156 };
9157
9158 #[gpui::test]
9159 fn inspector_only_tracks_its_open_window(cx: &mut TestAppContext) {
9160 let windows = [
9161 cx.add_window(|_, cx| InspectorTestRoot {
9162 child: cx.new(|_| InspectorTestView::default()),
9163 }),
9164 cx.add_window(|_, cx| InspectorTestRoot {
9165 child: cx.new(|_| InspectorTestView::default()),
9166 }),
9167 ];
9168 for window in windows {
9169 assert_closed_inspector(window.into(), cx);
9170 }
9171 for _ in 0..2 {
9172 cx.update_window(windows[0].into(), |root, window, cx| {
9173 let root = root.downcast::<InspectorTestRoot>().expect("test root");
9174 let child_widths = root.read(cx).child.read(cx).child_widths.clone();
9175 window.toggle_inspector(cx);
9176 window.draw(cx).clear(cx);
9177 assert_eq!(child_widths.borrow().as_slice(), &[px(10.); 3]);
9178 let path = window
9179 .rendered_frame
9180 .next_inspector_instance_ids
9181 .iter()
9182 .find_map(|(path, count)| (*count == 3).then(|| path.clone()))
9183 .expect("anonymous siblings share an inspector path");
9184 let selected_id = InspectorElementId {
9185 path,
9186 instance_id: 1,
9187 };
9188 let position = window
9189 .rendered_frame
9190 .hitboxes
9191 .iter()
9192 .find(|hitbox| {
9193 window.rendered_frame.inspector_hitboxes.get(&hitbox.id)
9194 == Some(&selected_id)
9195 })
9196 .expect("middle sibling is pickable")
9197 .bounds
9198 .center();
9199 window.simulate_mouse_move(position, cx);
9200 window.dispatch_event(
9201 PlatformInput::MouseDown(MouseDownEvent {
9202 position,
9203 button: MouseButton::Left,
9204 modifiers: Modifiers::default(),
9205 click_count: 1,
9206 first_mouse: false,
9207 }),
9208 cx,
9209 );
9210 window.dispatch_event(
9211 PlatformInput::MouseUp(MouseUpEvent {
9212 position,
9213 button: MouseButton::Left,
9214 modifiers: Modifiers::default(),
9215 click_count: 1,
9216 }),
9217 cx,
9218 );
9219 assert!(!window.is_inspector_picking(cx));
9220 assert_eq!(
9221 window
9222 .inspector
9223 .as_ref()
9224 .expect("open inspector")
9225 .read(cx)
9226 .active_element_id(),
9227 Some(&selected_id)
9228 );
9229 window.draw(cx).clear(cx);
9230 window.with_inspector_state::<DivInspectorState, _>(
9231 Some(&selected_id),
9232 cx,
9233 |state, _| {
9234 let state = state.as_mut().expect("selected div has style state");
9235 assert_eq!(
9236 state.base_style.size.width,
9237 Some(crate::Length::from(px(10.)))
9238 );
9239 state.base_style.size.width = Some(crate::Length::from(px(25.)));
9240 },
9241 );
9242 window.refresh();
9243 window.draw(cx).clear(cx);
9244 assert_eq!(
9245 child_widths.borrow().as_slice(),
9246 &[px(10.), px(25.), px(10.)]
9247 );
9248 })
9249 .expect("pick and edit a cached child");
9250 assert_closed_inspector(windows[1].into(), cx);
9251 windows[0]
9252 .update(cx, |_, window, cx| window.toggle_inspector(cx))
9253 .expect("close inspector");
9254 assert_closed_inspector(windows[0].into(), cx);
9255 }
9256 }
9257
9258 struct InspectorTestRoot {
9259 child: Entity<InspectorTestView>,
9260 }
9261
9262 impl Render for InspectorTestRoot {
9263 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
9264 self.child
9265 .clone()
9266 .cached(StyleRefinement::default().size(px(100.)))
9267 }
9268 }
9269
9270 #[derive(Default)]
9271 struct InspectorTestView {
9272 child_widths: Rc<RefCell<Vec<Pixels>>>,
9273 }
9274
9275 impl Render for InspectorTestView {
9276 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
9277 let child_widths = self.child_widths.clone();
9278 div()
9279 .on_children_prepainted(move |bounds, _, _| {
9280 *child_widths.borrow_mut() =
9281 bounds.iter().map(|bounds| bounds.size.width).collect();
9282 })
9283 .with_dynamic_prepaint_order(|_, _| SmallVec::from_iter([2, 0, 1]))
9284 .id("inspector-root")
9285 .flex()
9286 .children((0..3).map(|_| div().size(px(10.)).flex_shrink_0()))
9287 }
9288 }
9289
9290 fn assert_closed_inspector(window: AnyWindowHandle, cx: &mut TestAppContext) {
9291 cx.update_window(window, |root, window, cx| {
9292 window.draw(cx).clear(cx);
9293 window.draw(cx).clear(cx);
9294 let root = root.downcast::<InspectorTestRoot>().expect("test root");
9295 assert_eq!(
9296 root.read(cx)
9297 .child
9298 .read(cx)
9299 .child_widths
9300 .borrow()
9301 .as_slice(),
9302 &[px(10.); 3]
9303 );
9304 for frame in [&window.rendered_frame, &window.next_frame] {
9305 assert_eq!(frame.next_inspector_instance_ids.capacity(), 0);
9306 assert_eq!(frame.inspector_hitboxes.capacity(), 0);
9307 }
9308 })
9309 .expect("closed inspector has no bookkeeping and no style overrides");
9310 }
9311}