1#[cfg(any(feature = "inspector", debug_assertions))]
2use crate::Inspector;
3use crate::{
4 Action, AnyDrag, AnyElement, AnyImageCache, AnyTooltip, AnyView, App, AppContext, Arena, Asset,
5 AsyncWindowContext, AvailableSpace, Background, BorderStyle, Bounds, BoxShadow, Capslock,
6 Context, Corners, CursorStyle, Decorations, DevicePixels, DispatchActionListener,
7 DispatchNodeId, DispatchTree, DisplayId, Edges, Effect, Entity, EntityId, EventEmitter,
8 FileDropEvent, FontId, Global, GlobalElementId, GlyphId, GpuSpecs, Hsla, InputHandler, IsZero,
9 KeyBinding, KeyContext, KeyDownEvent, KeyEvent, Keystroke, KeystrokeEvent, LayoutId,
10 LineLayoutIndex, Modifiers, ModifiersChangedEvent, MonochromeSprite, MouseButton, MouseEvent,
11 MouseMoveEvent, MouseUpEvent, Path, Pixels, PlatformAtlas, PlatformDisplay, PlatformInput,
12 PlatformInputHandler, PlatformWindow, Point, PolychromeSprite, Priority, PromptButton,
13 PromptLevel, Quad, Render, RenderGlyphParams, RenderImage, RenderImageParams, RenderSvgParams,
14 Replay, ResizeEdge, SMOOTH_SVG_SCALE_FACTOR, SUBPIXEL_VARIANTS_X, SUBPIXEL_VARIANTS_Y,
15 ScaledPixels, Scene, Shadow, SharedString, Size, StrikethroughStyle, Style, SubpixelSprite,
16 SubscriberSet, Subscription, SystemWindowTab, SystemWindowTabController, TabStopMap,
17 TaffyLayoutEngine, Task, TextRenderingMode, TextStyle, TextStyleRefinement, ThermalState,
18 TransformationMatrix, Underline, UnderlineStyle, WindowAppearance, WindowBackgroundAppearance,
19 WindowBounds, WindowControls, WindowDecorations, WindowOptions, WindowParams, WindowTextSystem,
20 point, prelude::*, px, rems, size, transparent_black,
21};
22use anyhow::{Context as _, Result, anyhow};
23use collections::{FxHashMap, FxHashSet};
24#[cfg(target_os = "macos")]
25use core_video::pixel_buffer::CVPixelBuffer;
26use derive_more::{Deref, DerefMut};
27use futures::FutureExt;
28use futures::channel::oneshot;
29use gpui_util::post_inc;
30use gpui_util::{ResultExt, measure};
31use itertools::FoldWhile::{Continue, Done};
32use itertools::Itertools;
33use parking_lot::RwLock;
34use raw_window_handle::{HandleError, HasDisplayHandle, HasWindowHandle};
35use refineable::Refineable;
36use scheduler::Instant;
37use slotmap::SlotMap;
38use smallvec::SmallVec;
39use std::{
40 any::{Any, TypeId},
41 borrow::Cow,
42 cell::{Cell, RefCell},
43 cmp,
44 fmt::{Debug, Display},
45 hash::{Hash, Hasher},
46 marker::PhantomData,
47 mem,
48 ops::{DerefMut, Range},
49 rc::Rc,
50 sync::{
51 Arc, Weak,
52 atomic::{AtomicUsize, Ordering::SeqCst},
53 },
54 time::Duration,
55};
56use uuid::Uuid;
57
58mod prompts;
59
60use crate::util::atomic_incr_if_not_zero;
61pub use prompts::*;
62
63/// Default window size used when no explicit size is provided.
64pub const DEFAULT_WINDOW_SIZE: Size<Pixels> = size(px(1536.), px(864.));
65
66/// A 6:5 aspect ratio minimum window size to be used for functional,
67/// additional-to-main-Zed windows, like the settings and rules library windows.
68pub const DEFAULT_ADDITIONAL_WINDOW_SIZE: Size<Pixels> = Size {
69 width: Pixels(900.),
70 height: Pixels(750.),
71};
72
73/// Represents the two different phases when dispatching events.
74#[derive(Default, Copy, Clone, Debug, Eq, PartialEq)]
75pub enum DispatchPhase {
76 /// After the capture phase comes the bubble phase, in which mouse event listeners are
77 /// invoked front to back and keyboard event listeners are invoked from the focused element
78 /// to the root of the element tree. This is the phase you'll most commonly want to use when
79 /// registering event listeners.
80 #[default]
81 Bubble,
82 /// During the initial capture phase, mouse event listeners are invoked back to front, and keyboard
83 /// listeners are invoked from the root of the tree downward toward the focused element. This phase
84 /// is used for special purposes such as clearing the "pressed" state for click events. If
85 /// you stop event propagation during this phase, you need to know what you're doing. Handlers
86 /// outside of the immediate region may rely on detecting non-local events during this phase.
87 Capture,
88}
89
90impl DispatchPhase {
91 /// Returns true if this represents the "bubble" phase.
92 #[inline]
93 pub fn bubble(self) -> bool {
94 self == DispatchPhase::Bubble
95 }
96
97 /// Returns true if this represents the "capture" phase.
98 #[inline]
99 pub fn capture(self) -> bool {
100 self == DispatchPhase::Capture
101 }
102}
103
104struct WindowInvalidatorInner {
105 pub dirty: bool,
106 pub draw_phase: DrawPhase,
107 pub dirty_views: FxHashSet<EntityId>,
108}
109
110#[derive(Clone)]
111pub(crate) struct WindowInvalidator {
112 inner: Rc<RefCell<WindowInvalidatorInner>>,
113}
114
115impl WindowInvalidator {
116 pub fn new() -> Self {
117 WindowInvalidator {
118 inner: Rc::new(RefCell::new(WindowInvalidatorInner {
119 dirty: true,
120 draw_phase: DrawPhase::None,
121 dirty_views: FxHashSet::default(),
122 })),
123 }
124 }
125
126 pub fn invalidate_view(&self, entity: EntityId, cx: &mut App) -> bool {
127 let mut inner = self.inner.borrow_mut();
128 inner.dirty_views.insert(entity);
129 if inner.draw_phase == DrawPhase::None {
130 inner.dirty = true;
131 cx.push_effect(Effect::Notify { emitter: entity });
132 true
133 } else {
134 false
135 }
136 }
137
138 pub fn is_dirty(&self) -> bool {
139 self.inner.borrow().dirty
140 }
141
142 pub fn set_dirty(&self, dirty: bool) {
143 self.inner.borrow_mut().dirty = dirty
144 }
145
146 pub fn set_phase(&self, phase: DrawPhase) {
147 self.inner.borrow_mut().draw_phase = phase
148 }
149
150 pub fn take_views(&self) -> FxHashSet<EntityId> {
151 mem::take(&mut self.inner.borrow_mut().dirty_views)
152 }
153
154 pub fn replace_views(&self, views: FxHashSet<EntityId>) {
155 self.inner.borrow_mut().dirty_views = views;
156 }
157
158 pub fn not_drawing(&self) -> bool {
159 self.inner.borrow().draw_phase == DrawPhase::None
160 }
161
162 #[track_caller]
163 pub fn debug_assert_paint(&self) {
164 debug_assert!(
165 matches!(self.inner.borrow().draw_phase, DrawPhase::Paint),
166 "this method can only be called during paint"
167 );
168 }
169
170 #[track_caller]
171 pub fn debug_assert_prepaint(&self) {
172 debug_assert!(
173 matches!(self.inner.borrow().draw_phase, DrawPhase::Prepaint),
174 "this method can only be called during request_layout, or prepaint"
175 );
176 }
177
178 #[track_caller]
179 pub fn debug_assert_paint_or_prepaint(&self) {
180 debug_assert!(
181 matches!(
182 self.inner.borrow().draw_phase,
183 DrawPhase::Paint | DrawPhase::Prepaint
184 ),
185 "this method can only be called during request_layout, prepaint, or paint"
186 );
187 }
188}
189
190type AnyObserver = Box<dyn FnMut(&mut Window, &mut App) -> bool + 'static>;
191
192pub(crate) type AnyWindowFocusListener =
193 Box<dyn FnMut(&WindowFocusEvent, &mut Window, &mut App) -> bool + 'static>;
194
195pub(crate) struct WindowFocusEvent {
196 pub(crate) previous_focus_path: SmallVec<[FocusId; 8]>,
197 pub(crate) current_focus_path: SmallVec<[FocusId; 8]>,
198}
199
200impl WindowFocusEvent {
201 pub fn is_focus_in(&self, focus_id: FocusId) -> bool {
202 !self.previous_focus_path.contains(&focus_id) && self.current_focus_path.contains(&focus_id)
203 }
204
205 pub fn is_focus_out(&self, focus_id: FocusId) -> bool {
206 self.previous_focus_path.contains(&focus_id) && !self.current_focus_path.contains(&focus_id)
207 }
208}
209
210/// This is provided when subscribing for `Context::on_focus_out` events.
211pub struct FocusOutEvent {
212 /// A weak focus handle representing what was blurred.
213 pub blurred: WeakFocusHandle,
214}
215
216slotmap::new_key_type! {
217 /// A globally unique identifier for a focusable element.
218 pub struct FocusId;
219}
220
221thread_local! {
222 /// Fallback arena used when no app-specific arena is active.
223 /// In production, each window draw sets CURRENT_ELEMENT_ARENA to the app's arena.
224 pub(crate) static ELEMENT_ARENA: RefCell<Arena> = RefCell::new(Arena::new(1024 * 1024));
225
226 /// Points to the current App's element arena during draw operations.
227 /// This allows multiple test Apps to have isolated arenas, preventing
228 /// cross-session corruption when the scheduler interleaves their tasks.
229 static CURRENT_ELEMENT_ARENA: Cell<Option<*const RefCell<Arena>>> = const { Cell::new(None) };
230}
231
232/// Allocates an element in the current arena. Uses the app-specific arena if one
233/// is active (during draw), otherwise falls back to the thread-local ELEMENT_ARENA.
234pub(crate) fn with_element_arena<R>(f: impl FnOnce(&mut Arena) -> R) -> R {
235 CURRENT_ELEMENT_ARENA.with(|current| {
236 if let Some(arena_ptr) = current.get() {
237 // SAFETY: The pointer is valid for the duration of the draw operation
238 // that set it, and we're being called during that same draw.
239 let arena_cell = unsafe { &*arena_ptr };
240 f(&mut arena_cell.borrow_mut())
241 } else {
242 ELEMENT_ARENA.with_borrow_mut(f)
243 }
244 })
245}
246
247/// RAII guard that sets CURRENT_ELEMENT_ARENA for the duration of a draw operation.
248/// When dropped, restores the previous arena (supporting nested draws).
249pub(crate) struct ElementArenaScope {
250 previous: Option<*const RefCell<Arena>>,
251}
252
253impl ElementArenaScope {
254 /// Enter a scope where element allocations use the given arena.
255 pub(crate) fn enter(arena: &RefCell<Arena>) -> Self {
256 let previous = CURRENT_ELEMENT_ARENA.with(|current| {
257 let prev = current.get();
258 current.set(Some(arena as *const RefCell<Arena>));
259 prev
260 });
261 Self { previous }
262 }
263}
264
265impl Drop for ElementArenaScope {
266 fn drop(&mut self) {
267 CURRENT_ELEMENT_ARENA.with(|current| {
268 current.set(self.previous);
269 });
270 }
271}
272
273/// Returned when the element arena has been used and so must be cleared before the next draw.
274#[must_use]
275pub struct ArenaClearNeeded {
276 arena: *const RefCell<Arena>,
277}
278
279impl ArenaClearNeeded {
280 /// Create a new ArenaClearNeeded that will clear the given arena.
281 pub(crate) fn new(arena: &RefCell<Arena>) -> Self {
282 Self {
283 arena: arena as *const RefCell<Arena>,
284 }
285 }
286
287 /// Clear the element arena.
288 pub fn clear(self) {
289 // SAFETY: The arena pointer is valid because ArenaClearNeeded is created
290 // at the end of draw() and must be cleared before the next draw.
291 let arena_cell = unsafe { &*self.arena };
292 arena_cell.borrow_mut().clear();
293 }
294}
295
296pub(crate) type FocusMap = RwLock<SlotMap<FocusId, FocusRef>>;
297pub(crate) struct FocusRef {
298 pub(crate) ref_count: AtomicUsize,
299 pub(crate) tab_index: isize,
300 pub(crate) tab_stop: bool,
301}
302
303impl FocusId {
304 /// Obtains whether the element associated with this handle is currently focused.
305 pub fn is_focused(&self, window: &Window) -> bool {
306 window.focus == Some(*self)
307 }
308
309 /// Obtains whether the element associated with this handle contains the focused
310 /// element or is itself focused.
311 pub fn contains_focused(&self, window: &Window, cx: &App) -> bool {
312 window
313 .focused(cx)
314 .is_some_and(|focused| self.contains(focused.id, window))
315 }
316
317 /// Obtains whether the element associated with this handle is contained within the
318 /// focused element or is itself focused.
319 pub fn within_focused(&self, window: &Window, cx: &App) -> bool {
320 let focused = window.focused(cx);
321 focused.is_some_and(|focused| focused.id.contains(*self, window))
322 }
323
324 /// Obtains whether this handle contains the given handle in the most recently rendered frame.
325 pub(crate) fn contains(&self, other: Self, window: &Window) -> bool {
326 window
327 .rendered_frame
328 .dispatch_tree
329 .focus_contains(*self, other)
330 }
331}
332
333/// A handle which can be used to track and manipulate the focused element in a window.
334pub struct FocusHandle {
335 pub(crate) id: FocusId,
336 handles: Arc<FocusMap>,
337 /// The index of this element in the tab order.
338 pub tab_index: isize,
339 /// Whether this element can be focused by tab navigation.
340 pub tab_stop: bool,
341}
342
343impl std::fmt::Debug for FocusHandle {
344 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
345 f.write_fmt(format_args!("FocusHandle({:?})", self.id))
346 }
347}
348
349impl FocusHandle {
350 pub(crate) fn new(handles: &Arc<FocusMap>) -> Self {
351 let id = handles.write().insert(FocusRef {
352 ref_count: AtomicUsize::new(1),
353 tab_index: 0,
354 tab_stop: false,
355 });
356
357 Self {
358 id,
359 tab_index: 0,
360 tab_stop: false,
361 handles: handles.clone(),
362 }
363 }
364
365 pub(crate) fn for_id(id: FocusId, handles: &Arc<FocusMap>) -> Option<Self> {
366 let lock = handles.read();
367 let focus = lock.get(id)?;
368 if atomic_incr_if_not_zero(&focus.ref_count) == 0 {
369 return None;
370 }
371 Some(Self {
372 id,
373 tab_index: focus.tab_index,
374 tab_stop: focus.tab_stop,
375 handles: handles.clone(),
376 })
377 }
378
379 /// Sets the tab index of the element associated with this handle.
380 pub fn tab_index(mut self, index: isize) -> Self {
381 self.tab_index = index;
382 if let Some(focus) = self.handles.write().get_mut(self.id) {
383 focus.tab_index = index;
384 }
385 self
386 }
387
388 /// Sets whether the element associated with this handle is a tab stop.
389 ///
390 /// When `false`, the element will not be included in the tab order.
391 pub fn tab_stop(mut self, tab_stop: bool) -> Self {
392 self.tab_stop = tab_stop;
393 if let Some(focus) = self.handles.write().get_mut(self.id) {
394 focus.tab_stop = tab_stop;
395 }
396 self
397 }
398
399 /// Converts this focus handle into a weak variant, which does not prevent it from being released.
400 pub fn downgrade(&self) -> WeakFocusHandle {
401 WeakFocusHandle {
402 id: self.id,
403 handles: Arc::downgrade(&self.handles),
404 }
405 }
406
407 /// Moves the focus to the element associated with this handle.
408 pub fn focus(&self, window: &mut Window, cx: &mut App) {
409 window.focus(self, cx)
410 }
411
412 /// Obtains whether the element associated with this handle is currently focused.
413 pub fn is_focused(&self, window: &Window) -> bool {
414 self.id.is_focused(window)
415 }
416
417 /// Obtains whether the element associated with this handle contains the focused
418 /// element or is itself focused.
419 pub fn contains_focused(&self, window: &Window, cx: &App) -> bool {
420 self.id.contains_focused(window, cx)
421 }
422
423 /// Obtains whether the element associated with this handle is contained within the
424 /// focused element or is itself focused.
425 pub fn within_focused(&self, window: &Window, cx: &mut App) -> bool {
426 self.id.within_focused(window, cx)
427 }
428
429 /// Obtains whether this handle contains the given handle in the most recently rendered frame.
430 pub fn contains(&self, other: &Self, window: &Window) -> bool {
431 self.id.contains(other.id, window)
432 }
433
434 /// Dispatch an action on the element that rendered this focus handle
435 pub fn dispatch_action(&self, action: &dyn Action, window: &mut Window, cx: &mut App) {
436 if let Some(node_id) = window
437 .rendered_frame
438 .dispatch_tree
439 .focusable_node_id(self.id)
440 {
441 window.dispatch_action_on_node(node_id, action, cx)
442 }
443 }
444}
445
446impl Clone for FocusHandle {
447 fn clone(&self) -> Self {
448 Self::for_id(self.id, &self.handles).unwrap()
449 }
450}
451
452impl PartialEq for FocusHandle {
453 fn eq(&self, other: &Self) -> bool {
454 self.id == other.id
455 }
456}
457
458impl Eq for FocusHandle {}
459
460impl Drop for FocusHandle {
461 fn drop(&mut self) {
462 self.handles
463 .read()
464 .get(self.id)
465 .unwrap()
466 .ref_count
467 .fetch_sub(1, SeqCst);
468 }
469}
470
471/// A weak reference to a focus handle.
472#[derive(Clone, Debug)]
473pub struct WeakFocusHandle {
474 pub(crate) id: FocusId,
475 pub(crate) handles: Weak<FocusMap>,
476}
477
478impl WeakFocusHandle {
479 /// Attempts to upgrade the [WeakFocusHandle] to a [FocusHandle].
480 pub fn upgrade(&self) -> Option<FocusHandle> {
481 let handles = self.handles.upgrade()?;
482 FocusHandle::for_id(self.id, &handles)
483 }
484}
485
486impl PartialEq for WeakFocusHandle {
487 fn eq(&self, other: &WeakFocusHandle) -> bool {
488 self.id == other.id
489 }
490}
491
492impl Eq for WeakFocusHandle {}
493
494impl PartialEq<FocusHandle> for WeakFocusHandle {
495 fn eq(&self, other: &FocusHandle) -> bool {
496 self.id == other.id
497 }
498}
499
500impl PartialEq<WeakFocusHandle> for FocusHandle {
501 fn eq(&self, other: &WeakFocusHandle) -> bool {
502 self.id == other.id
503 }
504}
505
506/// Focusable allows users of your view to easily
507/// focus it (using window.focus_view(cx, view))
508pub trait Focusable: 'static {
509 /// Returns the focus handle associated with this view.
510 fn focus_handle(&self, cx: &App) -> FocusHandle;
511}
512
513impl<V: Focusable> Focusable for Entity<V> {
514 fn focus_handle(&self, cx: &App) -> FocusHandle {
515 self.read(cx).focus_handle(cx)
516 }
517}
518
519/// ManagedView is a view (like a Modal, Popover, Menu, etc.)
520/// where the lifecycle of the view is handled by another view.
521pub trait ManagedView: Focusable + EventEmitter<DismissEvent> + Render {}
522
523impl<M: Focusable + EventEmitter<DismissEvent> + Render> ManagedView for M {}
524
525/// Emitted by implementers of [`ManagedView`] to indicate the view should be dismissed, such as when a view is presented as a modal.
526pub struct DismissEvent;
527
528type FrameCallback = Box<dyn FnOnce(&mut Window, &mut App)>;
529
530pub(crate) type AnyMouseListener =
531 Box<dyn FnMut(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static>;
532
533#[derive(Clone)]
534pub(crate) struct CursorStyleRequest {
535 pub(crate) hitbox_id: Option<HitboxId>,
536 pub(crate) style: CursorStyle,
537}
538
539#[derive(Default, Eq, PartialEq)]
540pub(crate) struct HitTest {
541 pub(crate) ids: SmallVec<[HitboxId; 8]>,
542 pub(crate) hover_hitbox_count: usize,
543}
544
545/// A type of window control area that corresponds to the platform window.
546#[derive(Clone, Copy, Debug, Eq, PartialEq)]
547pub enum WindowControlArea {
548 /// An area that allows dragging of the platform window.
549 Drag,
550 /// An area that allows closing of the platform window.
551 Close,
552 /// An area that allows maximizing of the platform window.
553 Max,
554 /// An area that allows minimizing of the platform window.
555 Min,
556}
557
558/// An identifier for a [Hitbox] which also includes [HitboxBehavior].
559#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
560pub struct HitboxId(u64);
561
562impl HitboxId {
563 /// Checks if the hitbox with this ID is currently hovered. Except when handling
564 /// `ScrollWheelEvent`, this is typically what you want when determining whether to handle mouse
565 /// events or paint hover styles.
566 ///
567 /// See [`Hitbox::is_hovered`] for details.
568 pub fn is_hovered(self, window: &Window) -> bool {
569 // If this hitbox has captured the pointer, it's always considered hovered
570 if window.captured_hitbox == Some(self) {
571 return true;
572 }
573 let hit_test = &window.mouse_hit_test;
574 for id in hit_test.ids.iter().take(hit_test.hover_hitbox_count) {
575 if self == *id {
576 return true;
577 }
578 }
579 false
580 }
581
582 /// Checks if the hitbox with this ID contains the mouse and should handle scroll events.
583 /// Typically this should only be used when handling `ScrollWheelEvent`, and otherwise
584 /// `is_hovered` should be used. See the documentation of `Hitbox::is_hovered` for details about
585 /// this distinction.
586 pub fn should_handle_scroll(self, window: &Window) -> bool {
587 window.mouse_hit_test.ids.contains(&self)
588 }
589
590 fn next(mut self) -> HitboxId {
591 HitboxId(self.0.wrapping_add(1))
592 }
593}
594
595/// A rectangular region that potentially blocks hitboxes inserted prior.
596/// See [Window::insert_hitbox] for more details.
597#[derive(Clone, Debug, Deref)]
598pub struct Hitbox {
599 /// A unique identifier for the hitbox.
600 pub id: HitboxId,
601 /// The bounds of the hitbox.
602 #[deref]
603 pub bounds: Bounds<Pixels>,
604 /// The content mask when the hitbox was inserted.
605 pub content_mask: ContentMask<Pixels>,
606 /// Flags that specify hitbox behavior.
607 pub behavior: HitboxBehavior,
608}
609
610impl Hitbox {
611 /// Checks if the hitbox is currently hovered. Except when handling `ScrollWheelEvent`, this is
612 /// typically what you want when determining whether to handle mouse events or paint hover
613 /// styles.
614 ///
615 /// This can return `false` even when the hitbox contains the mouse, if a hitbox in front of
616 /// this sets `HitboxBehavior::BlockMouse` (`InteractiveElement::occlude`) or
617 /// `HitboxBehavior::BlockMouseExceptScroll` (`InteractiveElement::block_mouse_except_scroll`).
618 ///
619 /// Handling of `ScrollWheelEvent` should typically use `should_handle_scroll` instead.
620 /// Concretely, this is due to use-cases like overlays that cause the elements under to be
621 /// non-interactive while still allowing scrolling. More abstractly, this is because
622 /// `is_hovered` is about element interactions directly under the mouse - mouse moves, clicks,
623 /// hover styling, etc. In contrast, scrolling is about finding the current outer scrollable
624 /// container.
625 pub fn is_hovered(&self, window: &Window) -> bool {
626 self.id.is_hovered(window)
627 }
628
629 /// Checks if the hitbox contains the mouse and should handle scroll events. Typically this
630 /// should only be used when handling `ScrollWheelEvent`, and otherwise `is_hovered` should be
631 /// used. See the documentation of `Hitbox::is_hovered` for details about this distinction.
632 ///
633 /// This can return `false` even when the hitbox contains the mouse, if a hitbox in front of
634 /// this sets `HitboxBehavior::BlockMouse` (`InteractiveElement::occlude`).
635 pub fn should_handle_scroll(&self, window: &Window) -> bool {
636 self.id.should_handle_scroll(window)
637 }
638}
639
640/// How the hitbox affects mouse behavior.
641#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
642pub enum HitboxBehavior {
643 /// Normal hitbox mouse behavior, doesn't affect mouse handling for other hitboxes.
644 #[default]
645 Normal,
646
647 /// All hitboxes behind this hitbox will be ignored and so will have `hitbox.is_hovered() ==
648 /// false` and `hitbox.should_handle_scroll() == false`. Typically for elements this causes
649 /// skipping of all mouse events, hover styles, and tooltips. This flag is set by
650 /// [`InteractiveElement::occlude`].
651 ///
652 /// For mouse handlers that check those hitboxes, this behaves the same as registering a
653 /// bubble-phase handler for every mouse event type:
654 ///
655 /// ```ignore
656 /// window.on_mouse_event(move |_: &EveryMouseEventTypeHere, phase, window, cx| {
657 /// if phase == DispatchPhase::Capture && hitbox.is_hovered(window) {
658 /// cx.stop_propagation();
659 /// }
660 /// })
661 /// ```
662 ///
663 /// This has effects beyond event handling - any use of hitbox checking, such as hover
664 /// styles and tooltips. These other behaviors are the main point of this mechanism. An
665 /// alternative might be to not affect mouse event handling - but this would allow
666 /// inconsistent UI where clicks and moves interact with elements that are not considered to
667 /// be hovered.
668 BlockMouse,
669
670 /// All hitboxes behind this hitbox will have `hitbox.is_hovered() == false`, even when
671 /// `hitbox.should_handle_scroll() == true`. Typically for elements this causes all mouse
672 /// interaction except scroll events to be ignored - see the documentation of
673 /// [`Hitbox::is_hovered`] for details. This flag is set by
674 /// [`InteractiveElement::block_mouse_except_scroll`].
675 ///
676 /// For mouse handlers that check those hitboxes, this behaves the same as registering a
677 /// bubble-phase handler for every mouse event type **except** `ScrollWheelEvent`:
678 ///
679 /// ```ignore
680 /// window.on_mouse_event(move |_: &EveryMouseEventTypeExceptScroll, phase, window, cx| {
681 /// if phase == DispatchPhase::Bubble && hitbox.should_handle_scroll(window) {
682 /// cx.stop_propagation();
683 /// }
684 /// })
685 /// ```
686 ///
687 /// See the documentation of [`Hitbox::is_hovered`] for details of why `ScrollWheelEvent` is
688 /// handled differently than other mouse events. If also blocking these scroll events is
689 /// desired, then a `cx.stop_propagation()` handler like the one above can be used.
690 ///
691 /// This has effects beyond event handling - this affects any use of `is_hovered`, such as
692 /// hover styles and tooltips. These other behaviors are the main point of this mechanism.
693 /// An alternative might be to not affect mouse event handling - but this would allow
694 /// inconsistent UI where clicks and moves interact with elements that are not considered to
695 /// be hovered.
696 BlockMouseExceptScroll,
697}
698
699/// An identifier for a tooltip.
700#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
701pub struct TooltipId(usize);
702
703impl TooltipId {
704 /// Checks if the tooltip is currently hovered.
705 pub fn is_hovered(&self, window: &Window) -> bool {
706 window
707 .tooltip_bounds
708 .as_ref()
709 .is_some_and(|tooltip_bounds| {
710 tooltip_bounds.id == *self
711 && tooltip_bounds.bounds.contains(&window.mouse_position())
712 })
713 }
714}
715
716pub(crate) struct TooltipBounds {
717 id: TooltipId,
718 bounds: Bounds<Pixels>,
719}
720
721#[derive(Clone)]
722pub(crate) struct TooltipRequest {
723 id: TooltipId,
724 tooltip: AnyTooltip,
725}
726
727pub(crate) struct DeferredDraw {
728 current_view: EntityId,
729 priority: usize,
730 parent_node: DispatchNodeId,
731 element_id_stack: SmallVec<[ElementId; 32]>,
732 text_style_stack: Vec<TextStyleRefinement>,
733 content_mask: Option<ContentMask<Pixels>>,
734 rem_size: Pixels,
735 element: Option<AnyElement>,
736 absolute_offset: Point<Pixels>,
737 prepaint_range: Range<PrepaintStateIndex>,
738 paint_range: Range<PaintIndex>,
739}
740
741pub(crate) struct Frame {
742 pub(crate) focus: Option<FocusId>,
743 pub(crate) window_active: bool,
744 pub(crate) element_states: FxHashMap<(GlobalElementId, TypeId), ElementStateBox>,
745 accessed_element_states: Vec<(GlobalElementId, TypeId)>,
746 pub(crate) mouse_listeners: Vec<Option<AnyMouseListener>>,
747 pub(crate) dispatch_tree: DispatchTree,
748 pub(crate) scene: Scene,
749 pub(crate) hitboxes: Vec<Hitbox>,
750 pub(crate) window_control_hitboxes: Vec<(WindowControlArea, Hitbox)>,
751 pub(crate) deferred_draws: Vec<DeferredDraw>,
752 pub(crate) input_handlers: Vec<Option<PlatformInputHandler>>,
753 pub(crate) tooltip_requests: Vec<Option<TooltipRequest>>,
754 pub(crate) cursor_styles: Vec<CursorStyleRequest>,
755 #[cfg(any(test, feature = "test-support"))]
756 pub(crate) debug_bounds: FxHashMap<String, Bounds<Pixels>>,
757 #[cfg(any(feature = "inspector", debug_assertions))]
758 pub(crate) next_inspector_instance_ids: FxHashMap<Rc<crate::InspectorElementPath>, usize>,
759 #[cfg(any(feature = "inspector", debug_assertions))]
760 pub(crate) inspector_hitboxes: FxHashMap<HitboxId, crate::InspectorElementId>,
761 pub(crate) tab_stops: TabStopMap,
762}
763
764#[derive(Clone, Default)]
765pub(crate) struct PrepaintStateIndex {
766 hitboxes_index: usize,
767 tooltips_index: usize,
768 deferred_draws_index: usize,
769 dispatch_tree_index: usize,
770 accessed_element_states_index: usize,
771 line_layout_index: LineLayoutIndex,
772}
773
774#[derive(Clone, Default)]
775pub(crate) struct PaintIndex {
776 scene_index: usize,
777 mouse_listeners_index: usize,
778 input_handlers_index: usize,
779 cursor_styles_index: usize,
780 accessed_element_states_index: usize,
781 tab_handle_index: usize,
782 line_layout_index: LineLayoutIndex,
783}
784
785impl Frame {
786 pub(crate) fn new(dispatch_tree: DispatchTree) -> Self {
787 Frame {
788 focus: None,
789 window_active: false,
790 element_states: FxHashMap::default(),
791 accessed_element_states: Vec::new(),
792 mouse_listeners: Vec::new(),
793 dispatch_tree,
794 scene: Scene::default(),
795 hitboxes: Vec::new(),
796 window_control_hitboxes: Vec::new(),
797 deferred_draws: Vec::new(),
798 input_handlers: Vec::new(),
799 tooltip_requests: Vec::new(),
800 cursor_styles: Vec::new(),
801
802 #[cfg(any(test, feature = "test-support"))]
803 debug_bounds: FxHashMap::default(),
804
805 #[cfg(any(feature = "inspector", debug_assertions))]
806 next_inspector_instance_ids: FxHashMap::default(),
807
808 #[cfg(any(feature = "inspector", debug_assertions))]
809 inspector_hitboxes: FxHashMap::default(),
810 tab_stops: TabStopMap::default(),
811 }
812 }
813
814 pub(crate) fn clear(&mut self) {
815 self.element_states.clear();
816 self.accessed_element_states.clear();
817 self.mouse_listeners.clear();
818 self.dispatch_tree.clear();
819 self.scene.clear();
820 self.input_handlers.clear();
821 self.tooltip_requests.clear();
822 self.cursor_styles.clear();
823 self.hitboxes.clear();
824 self.window_control_hitboxes.clear();
825 self.deferred_draws.clear();
826 self.tab_stops.clear();
827 self.focus = None;
828
829 #[cfg(any(test, feature = "test-support"))]
830 {
831 self.debug_bounds.clear();
832 }
833
834 #[cfg(any(feature = "inspector", debug_assertions))]
835 {
836 self.next_inspector_instance_ids.clear();
837 self.inspector_hitboxes.clear();
838 }
839 }
840
841 pub(crate) fn cursor_style(&self, window: &Window) -> Option<CursorStyle> {
842 self.cursor_styles
843 .iter()
844 .rev()
845 .fold_while(None, |style, request| match request.hitbox_id {
846 None => Done(Some(request.style)),
847 Some(hitbox_id) => Continue(
848 style.or_else(|| hitbox_id.is_hovered(window).then_some(request.style)),
849 ),
850 })
851 .into_inner()
852 }
853
854 pub(crate) fn hit_test(&self, position: Point<Pixels>) -> HitTest {
855 let mut set_hover_hitbox_count = false;
856 let mut hit_test = HitTest::default();
857 for hitbox in self.hitboxes.iter().rev() {
858 let bounds = hitbox.bounds.intersect(&hitbox.content_mask.bounds);
859 if bounds.contains(&position) {
860 hit_test.ids.push(hitbox.id);
861 if !set_hover_hitbox_count
862 && hitbox.behavior == HitboxBehavior::BlockMouseExceptScroll
863 {
864 hit_test.hover_hitbox_count = hit_test.ids.len();
865 set_hover_hitbox_count = true;
866 }
867 if hitbox.behavior == HitboxBehavior::BlockMouse {
868 break;
869 }
870 }
871 }
872 if !set_hover_hitbox_count {
873 hit_test.hover_hitbox_count = hit_test.ids.len();
874 }
875 hit_test
876 }
877
878 pub(crate) fn focus_path(&self) -> SmallVec<[FocusId; 8]> {
879 self.focus
880 .map(|focus_id| self.dispatch_tree.focus_path(focus_id))
881 .unwrap_or_default()
882 }
883
884 pub(crate) fn finish(&mut self, prev_frame: &mut Self) {
885 for element_state_key in &self.accessed_element_states {
886 if let Some((element_state_key, element_state)) =
887 prev_frame.element_states.remove_entry(element_state_key)
888 {
889 self.element_states.insert(element_state_key, element_state);
890 }
891 }
892
893 self.scene.finish();
894 }
895}
896
897#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
898enum InputModality {
899 Mouse,
900 Keyboard,
901}
902
903/// Holds the state for a specific window.
904pub struct Window {
905 pub(crate) handle: AnyWindowHandle,
906 pub(crate) invalidator: WindowInvalidator,
907 pub(crate) removed: bool,
908 pub(crate) platform_window: Box<dyn PlatformWindow>,
909 display_id: Option<DisplayId>,
910 sprite_atlas: Arc<dyn PlatformAtlas>,
911 text_system: Arc<WindowTextSystem>,
912 text_rendering_mode: Rc<Cell<TextRenderingMode>>,
913 rem_size: Pixels,
914 /// The stack of override values for the window's rem size.
915 ///
916 /// This is used by `with_rem_size` to allow rendering an element tree with
917 /// a given rem size.
918 rem_size_override_stack: SmallVec<[Pixels; 8]>,
919 pub(crate) viewport_size: Size<Pixels>,
920 layout_engine: Option<TaffyLayoutEngine>,
921 pub(crate) root: Option<AnyView>,
922 pub(crate) element_id_stack: SmallVec<[ElementId; 32]>,
923 pub(crate) text_style_stack: Vec<TextStyleRefinement>,
924 pub(crate) rendered_entity_stack: Vec<EntityId>,
925 pub(crate) element_offset_stack: Vec<Point<Pixels>>,
926 pub(crate) element_opacity: f32,
927 pub(crate) content_mask_stack: Vec<ContentMask<Pixels>>,
928 pub(crate) requested_autoscroll: Option<Bounds<Pixels>>,
929 pub(crate) image_cache_stack: Vec<AnyImageCache>,
930 pub(crate) rendered_frame: Frame,
931 pub(crate) next_frame: Frame,
932 next_hitbox_id: HitboxId,
933 pub(crate) next_tooltip_id: TooltipId,
934 pub(crate) tooltip_bounds: Option<TooltipBounds>,
935 next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>>,
936 pub(crate) dirty_views: FxHashSet<EntityId>,
937 focus_listeners: SubscriberSet<(), AnyWindowFocusListener>,
938 pub(crate) focus_lost_listeners: SubscriberSet<(), AnyObserver>,
939 default_prevented: bool,
940 mouse_position: Point<Pixels>,
941 mouse_hit_test: HitTest,
942 modifiers: Modifiers,
943 capslock: Capslock,
944 scale_factor: f32,
945 pub(crate) bounds_observers: SubscriberSet<(), AnyObserver>,
946 appearance: WindowAppearance,
947 pub(crate) appearance_observers: SubscriberSet<(), AnyObserver>,
948 active: Rc<Cell<bool>>,
949 hovered: Rc<Cell<bool>>,
950 pub(crate) needs_present: Rc<Cell<bool>>,
951 /// Tracks recent input event timestamps to determine if input is arriving at a high rate.
952 /// Used to selectively enable VRR optimization only when input rate exceeds 60fps.
953 pub(crate) input_rate_tracker: Rc<RefCell<InputRateTracker>>,
954 last_input_modality: InputModality,
955 pub(crate) refreshing: bool,
956 pub(crate) activation_observers: SubscriberSet<(), AnyObserver>,
957 pub(crate) focus: Option<FocusId>,
958 focus_enabled: bool,
959 pending_input: Option<PendingInput>,
960 pending_modifier: ModifierState,
961 pub(crate) pending_input_observers: SubscriberSet<(), AnyObserver>,
962 prompt: Option<RenderablePromptHandle>,
963 pub(crate) client_inset: Option<Pixels>,
964 /// The hitbox that has captured the pointer, if any.
965 /// While captured, mouse events route to this hitbox regardless of hit testing.
966 captured_hitbox: Option<HitboxId>,
967 #[cfg(any(feature = "inspector", debug_assertions))]
968 inspector: Option<Entity<Inspector>>,
969}
970
971#[derive(Clone, Debug, Default)]
972struct ModifierState {
973 modifiers: Modifiers,
974 saw_keystroke: bool,
975}
976
977/// Tracks input event timestamps to determine if input is arriving at a high rate.
978/// Used for selective VRR (Variable Refresh Rate) optimization.
979#[derive(Clone, Debug)]
980pub(crate) struct InputRateTracker {
981 timestamps: Vec<Instant>,
982 window: Duration,
983 inputs_per_second: u32,
984 sustain_until: Instant,
985 sustain_duration: Duration,
986}
987
988impl Default for InputRateTracker {
989 fn default() -> Self {
990 Self {
991 timestamps: Vec::new(),
992 window: Duration::from_millis(100),
993 inputs_per_second: 60,
994 sustain_until: Instant::now(),
995 sustain_duration: Duration::from_secs(1),
996 }
997 }
998}
999
1000impl InputRateTracker {
1001 pub fn record_input(&mut self) {
1002 let now = Instant::now();
1003 self.timestamps.push(now);
1004 self.prune_old_timestamps(now);
1005
1006 let min_events = self.inputs_per_second as u128 * self.window.as_millis() / 1000;
1007 if self.timestamps.len() as u128 >= min_events {
1008 self.sustain_until = now + self.sustain_duration;
1009 }
1010 }
1011
1012 pub fn is_high_rate(&self) -> bool {
1013 Instant::now() < self.sustain_until
1014 }
1015
1016 fn prune_old_timestamps(&mut self, now: Instant) {
1017 self.timestamps
1018 .retain(|&t| now.duration_since(t) <= self.window);
1019 }
1020}
1021
1022#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1023pub(crate) enum DrawPhase {
1024 None,
1025 Prepaint,
1026 Paint,
1027 Focus,
1028}
1029
1030#[derive(Default, Debug)]
1031struct PendingInput {
1032 keystrokes: SmallVec<[Keystroke; 1]>,
1033 focus: Option<FocusId>,
1034 timer: Option<Task<()>>,
1035 needs_timeout: bool,
1036}
1037
1038pub(crate) struct ElementStateBox {
1039 pub(crate) inner: Box<dyn Any>,
1040 #[cfg(debug_assertions)]
1041 pub(crate) type_name: &'static str,
1042}
1043
1044fn default_bounds(display_id: Option<DisplayId>, cx: &mut App) -> WindowBounds {
1045 // TODO, BUG: if you open a window with the currently active window
1046 // on the stack, this will erroneously fallback to `None`
1047 //
1048 // TODO these should be the initial window bounds not considering maximized/fullscreen
1049 let active_window_bounds = cx
1050 .active_window()
1051 .and_then(|w| w.update(cx, |_, window, _| window.window_bounds()).ok());
1052
1053 const CASCADE_OFFSET: f32 = 25.0;
1054
1055 let display = display_id
1056 .map(|id| cx.find_display(id))
1057 .unwrap_or_else(|| cx.primary_display());
1058
1059 let default_placement = || Bounds::new(point(px(0.), px(0.)), DEFAULT_WINDOW_SIZE);
1060
1061 // Use visible_bounds to exclude taskbar/dock areas
1062 let display_bounds = display
1063 .as_ref()
1064 .map(|d| d.visible_bounds())
1065 .unwrap_or_else(default_placement);
1066
1067 let (
1068 Bounds {
1069 origin: base_origin,
1070 size: base_size,
1071 },
1072 window_bounds_ctor,
1073 ): (_, fn(Bounds<Pixels>) -> WindowBounds) = match active_window_bounds {
1074 Some(bounds) => match bounds {
1075 WindowBounds::Windowed(bounds) => (bounds, WindowBounds::Windowed),
1076 WindowBounds::Maximized(bounds) => (bounds, WindowBounds::Maximized),
1077 WindowBounds::Fullscreen(bounds) => (bounds, WindowBounds::Fullscreen),
1078 },
1079 None => (
1080 display
1081 .as_ref()
1082 .map(|d| d.default_bounds())
1083 .unwrap_or_else(default_placement),
1084 WindowBounds::Windowed,
1085 ),
1086 };
1087
1088 let cascade_offset = point(px(CASCADE_OFFSET), px(CASCADE_OFFSET));
1089 let proposed_origin = base_origin + cascade_offset;
1090 let proposed_bounds = Bounds::new(proposed_origin, base_size);
1091
1092 let display_right = display_bounds.origin.x + display_bounds.size.width;
1093 let display_bottom = display_bounds.origin.y + display_bounds.size.height;
1094 let window_right = proposed_bounds.origin.x + proposed_bounds.size.width;
1095 let window_bottom = proposed_bounds.origin.y + proposed_bounds.size.height;
1096
1097 let fits_horizontally = window_right <= display_right;
1098 let fits_vertically = window_bottom <= display_bottom;
1099
1100 let final_origin = match (fits_horizontally, fits_vertically) {
1101 (true, true) => proposed_origin,
1102 (false, true) => point(display_bounds.origin.x, base_origin.y),
1103 (true, false) => point(base_origin.x, display_bounds.origin.y),
1104 (false, false) => display_bounds.origin,
1105 };
1106 window_bounds_ctor(Bounds::new(final_origin, base_size))
1107}
1108
1109impl Window {
1110 pub(crate) fn new(
1111 handle: AnyWindowHandle,
1112 options: WindowOptions,
1113 cx: &mut App,
1114 ) -> Result<Self> {
1115 let WindowOptions {
1116 window_bounds,
1117 titlebar,
1118 focus,
1119 show,
1120 kind,
1121 is_movable,
1122 is_resizable,
1123 is_minimizable,
1124 display_id,
1125 window_background,
1126 app_id,
1127 window_min_size,
1128 window_decorations,
1129 #[cfg_attr(not(target_os = "macos"), allow(unused_variables))]
1130 tabbing_identifier,
1131 } = options;
1132
1133 let window_bounds = window_bounds.unwrap_or_else(|| default_bounds(display_id, cx));
1134 let mut platform_window = cx.platform.open_window(
1135 handle,
1136 WindowParams {
1137 bounds: window_bounds.get_bounds(),
1138 titlebar,
1139 kind,
1140 is_movable,
1141 is_resizable,
1142 is_minimizable,
1143 focus,
1144 show,
1145 display_id,
1146 window_min_size,
1147 #[cfg(target_os = "macos")]
1148 tabbing_identifier,
1149 },
1150 )?;
1151
1152 let tab_bar_visible = platform_window.tab_bar_visible();
1153 SystemWindowTabController::init_visible(cx, tab_bar_visible);
1154 if let Some(tabs) = platform_window.tabbed_windows() {
1155 SystemWindowTabController::add_tab(cx, handle.window_id(), tabs);
1156 }
1157
1158 let display_id = platform_window.display().map(|display| display.id());
1159 let sprite_atlas = platform_window.sprite_atlas();
1160 let mouse_position = platform_window.mouse_position();
1161 let modifiers = platform_window.modifiers();
1162 let capslock = platform_window.capslock();
1163 let content_size = platform_window.content_size();
1164 let scale_factor = platform_window.scale_factor();
1165 let appearance = platform_window.appearance();
1166 let text_system = Arc::new(WindowTextSystem::new(cx.text_system().clone()));
1167 let invalidator = WindowInvalidator::new();
1168 let active = Rc::new(Cell::new(platform_window.is_active()));
1169 let hovered = Rc::new(Cell::new(platform_window.is_hovered()));
1170 let needs_present = Rc::new(Cell::new(false));
1171 let next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>> = Default::default();
1172 let input_rate_tracker = Rc::new(RefCell::new(InputRateTracker::default()));
1173 let last_frame_time = Rc::new(Cell::new(None));
1174
1175 platform_window
1176 .request_decorations(window_decorations.unwrap_or(WindowDecorations::Server));
1177 platform_window.set_background_appearance(window_background);
1178
1179 match window_bounds {
1180 WindowBounds::Fullscreen(_) => platform_window.toggle_fullscreen(),
1181 WindowBounds::Maximized(_) => platform_window.zoom(),
1182 WindowBounds::Windowed(_) => {}
1183 }
1184
1185 platform_window.on_close(Box::new({
1186 let window_id = handle.window_id();
1187 let mut cx = cx.to_async();
1188 move || {
1189 let _ = handle.update(&mut cx, |_, window, _| window.remove_window());
1190 let _ = cx.update(|cx| {
1191 SystemWindowTabController::remove_tab(cx, window_id);
1192 });
1193 }
1194 }));
1195 platform_window.on_request_frame(Box::new({
1196 let mut cx = cx.to_async();
1197 let invalidator = invalidator.clone();
1198 let active = active.clone();
1199 let needs_present = needs_present.clone();
1200 let next_frame_callbacks = next_frame_callbacks.clone();
1201 let input_rate_tracker = input_rate_tracker.clone();
1202 move |request_frame_options| {
1203 let thermal_state = handle
1204 .update(&mut cx, |_, _, cx| cx.thermal_state())
1205 .log_err();
1206
1207 if thermal_state == Some(ThermalState::Serious)
1208 || thermal_state == Some(ThermalState::Critical)
1209 {
1210 let now = Instant::now();
1211 let last_frame_time = last_frame_time.replace(Some(now));
1212
1213 if let Some(last_frame) = last_frame_time
1214 && now.duration_since(last_frame) < Duration::from_micros(16667)
1215 {
1216 return;
1217 }
1218 }
1219
1220 let next_frame_callbacks = next_frame_callbacks.take();
1221 if !next_frame_callbacks.is_empty() {
1222 handle
1223 .update(&mut cx, |_, window, cx| {
1224 for callback in next_frame_callbacks {
1225 callback(window, cx);
1226 }
1227 })
1228 .log_err();
1229 }
1230
1231 // Keep presenting if input was recently arriving at a high rate (>= 60fps).
1232 // Once high-rate input is detected, we sustain presentation for 1 second
1233 // to prevent display underclocking during active input.
1234 let needs_present = request_frame_options.require_presentation
1235 || needs_present.get()
1236 || (active.get() && input_rate_tracker.borrow_mut().is_high_rate());
1237
1238 if invalidator.is_dirty() || request_frame_options.force_render {
1239 measure("frame duration", || {
1240 handle
1241 .update(&mut cx, |_, window, cx| {
1242 let arena_clear_needed = window.draw(cx);
1243 window.present();
1244 arena_clear_needed.clear();
1245 })
1246 .log_err();
1247 })
1248 } else if needs_present {
1249 handle
1250 .update(&mut cx, |_, window, _| window.present())
1251 .log_err();
1252 }
1253
1254 handle
1255 .update(&mut cx, |_, window, _| {
1256 window.complete_frame();
1257 })
1258 .log_err();
1259 }
1260 }));
1261 platform_window.on_resize(Box::new({
1262 let mut cx = cx.to_async();
1263 move |_, _| {
1264 handle
1265 .update(&mut cx, |_, window, cx| window.bounds_changed(cx))
1266 .log_err();
1267 }
1268 }));
1269 platform_window.on_moved(Box::new({
1270 let mut cx = cx.to_async();
1271 move || {
1272 handle
1273 .update(&mut cx, |_, window, cx| window.bounds_changed(cx))
1274 .log_err();
1275 }
1276 }));
1277 platform_window.on_appearance_changed(Box::new({
1278 let mut cx = cx.to_async();
1279 move || {
1280 handle
1281 .update(&mut cx, |_, window, cx| window.appearance_changed(cx))
1282 .log_err();
1283 }
1284 }));
1285 platform_window.on_active_status_change(Box::new({
1286 let mut cx = cx.to_async();
1287 move |active| {
1288 handle
1289 .update(&mut cx, |_, window, cx| {
1290 window.active.set(active);
1291 window.modifiers = window.platform_window.modifiers();
1292 window.capslock = window.platform_window.capslock();
1293 window
1294 .activation_observers
1295 .clone()
1296 .retain(&(), |callback| callback(window, cx));
1297
1298 window.bounds_changed(cx);
1299 window.refresh();
1300
1301 SystemWindowTabController::update_last_active(cx, window.handle.id);
1302 })
1303 .log_err();
1304 }
1305 }));
1306 platform_window.on_hover_status_change(Box::new({
1307 let mut cx = cx.to_async();
1308 move |active| {
1309 handle
1310 .update(&mut cx, |_, window, _| {
1311 window.hovered.set(active);
1312 window.refresh();
1313 })
1314 .log_err();
1315 }
1316 }));
1317 platform_window.on_input({
1318 let mut cx = cx.to_async();
1319 Box::new(move |event| {
1320 handle
1321 .update(&mut cx, |_, window, cx| window.dispatch_event(event, cx))
1322 .log_err()
1323 .unwrap_or(DispatchEventResult::default())
1324 })
1325 });
1326 platform_window.on_hit_test_window_control({
1327 let mut cx = cx.to_async();
1328 Box::new(move || {
1329 handle
1330 .update(&mut cx, |_, window, _cx| {
1331 for (area, hitbox) in &window.rendered_frame.window_control_hitboxes {
1332 if window.mouse_hit_test.ids.contains(&hitbox.id) {
1333 return Some(*area);
1334 }
1335 }
1336 None
1337 })
1338 .log_err()
1339 .unwrap_or(None)
1340 })
1341 });
1342 platform_window.on_move_tab_to_new_window({
1343 let mut cx = cx.to_async();
1344 Box::new(move || {
1345 handle
1346 .update(&mut cx, |_, _window, cx| {
1347 SystemWindowTabController::move_tab_to_new_window(cx, handle.window_id());
1348 })
1349 .log_err();
1350 })
1351 });
1352 platform_window.on_merge_all_windows({
1353 let mut cx = cx.to_async();
1354 Box::new(move || {
1355 handle
1356 .update(&mut cx, |_, _window, cx| {
1357 SystemWindowTabController::merge_all_windows(cx, handle.window_id());
1358 })
1359 .log_err();
1360 })
1361 });
1362 platform_window.on_select_next_tab({
1363 let mut cx = cx.to_async();
1364 Box::new(move || {
1365 handle
1366 .update(&mut cx, |_, _window, cx| {
1367 SystemWindowTabController::select_next_tab(cx, handle.window_id());
1368 })
1369 .log_err();
1370 })
1371 });
1372 platform_window.on_select_previous_tab({
1373 let mut cx = cx.to_async();
1374 Box::new(move || {
1375 handle
1376 .update(&mut cx, |_, _window, cx| {
1377 SystemWindowTabController::select_previous_tab(cx, handle.window_id())
1378 })
1379 .log_err();
1380 })
1381 });
1382 platform_window.on_toggle_tab_bar({
1383 let mut cx = cx.to_async();
1384 Box::new(move || {
1385 handle
1386 .update(&mut cx, |_, window, cx| {
1387 let tab_bar_visible = window.platform_window.tab_bar_visible();
1388 SystemWindowTabController::set_visible(cx, tab_bar_visible);
1389 })
1390 .log_err();
1391 })
1392 });
1393
1394 if let Some(app_id) = app_id {
1395 platform_window.set_app_id(&app_id);
1396 }
1397
1398 platform_window.map_window().unwrap();
1399
1400 Ok(Window {
1401 handle,
1402 invalidator,
1403 removed: false,
1404 platform_window,
1405 display_id,
1406 sprite_atlas,
1407 text_system,
1408 text_rendering_mode: cx.text_rendering_mode.clone(),
1409 rem_size: px(16.),
1410 rem_size_override_stack: SmallVec::new(),
1411 viewport_size: content_size,
1412 layout_engine: Some(TaffyLayoutEngine::new()),
1413 root: None,
1414 element_id_stack: SmallVec::default(),
1415 text_style_stack: Vec::new(),
1416 rendered_entity_stack: Vec::new(),
1417 element_offset_stack: Vec::new(),
1418 content_mask_stack: Vec::new(),
1419 element_opacity: 1.0,
1420 requested_autoscroll: None,
1421 rendered_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
1422 next_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
1423 next_frame_callbacks,
1424 next_hitbox_id: HitboxId(0),
1425 next_tooltip_id: TooltipId::default(),
1426 tooltip_bounds: None,
1427 dirty_views: FxHashSet::default(),
1428 focus_listeners: SubscriberSet::new(),
1429 focus_lost_listeners: SubscriberSet::new(),
1430 default_prevented: true,
1431 mouse_position,
1432 mouse_hit_test: HitTest::default(),
1433 modifiers,
1434 capslock,
1435 scale_factor,
1436 bounds_observers: SubscriberSet::new(),
1437 appearance,
1438 appearance_observers: SubscriberSet::new(),
1439 active,
1440 hovered,
1441 needs_present,
1442 input_rate_tracker,
1443 last_input_modality: InputModality::Mouse,
1444 refreshing: false,
1445 activation_observers: SubscriberSet::new(),
1446 focus: None,
1447 focus_enabled: true,
1448 pending_input: None,
1449 pending_modifier: ModifierState::default(),
1450 pending_input_observers: SubscriberSet::new(),
1451 prompt: None,
1452 client_inset: None,
1453 image_cache_stack: Vec::new(),
1454 captured_hitbox: None,
1455 #[cfg(any(feature = "inspector", debug_assertions))]
1456 inspector: None,
1457 })
1458 }
1459
1460 pub(crate) fn new_focus_listener(
1461 &self,
1462 value: AnyWindowFocusListener,
1463 ) -> (Subscription, impl FnOnce() + use<>) {
1464 self.focus_listeners.insert((), value)
1465 }
1466}
1467
1468#[derive(Clone, Debug, Default, PartialEq, Eq)]
1469#[expect(missing_docs)]
1470pub struct DispatchEventResult {
1471 pub propagate: bool,
1472 pub default_prevented: bool,
1473}
1474
1475/// Indicates which region of the window is visible. Content falling outside of this mask will not be
1476/// rendered. Currently, only rectangular content masks are supported, but we give the mask its own type
1477/// to leave room to support more complex shapes in the future.
1478#[derive(Clone, Debug, Default, PartialEq, Eq)]
1479#[repr(C)]
1480pub struct ContentMask<P: Clone + Debug + Default + PartialEq> {
1481 /// The bounds
1482 pub bounds: Bounds<P>,
1483}
1484
1485impl ContentMask<Pixels> {
1486 /// Scale the content mask's pixel units by the given scaling factor.
1487 pub fn scale(&self, factor: f32) -> ContentMask<ScaledPixels> {
1488 ContentMask {
1489 bounds: self.bounds.scale(factor),
1490 }
1491 }
1492
1493 /// Intersect the content mask with the given content mask.
1494 pub fn intersect(&self, other: &Self) -> Self {
1495 let bounds = self.bounds.intersect(&other.bounds);
1496 ContentMask { bounds }
1497 }
1498}
1499
1500impl Window {
1501 fn mark_view_dirty(&mut self, view_id: EntityId) {
1502 // Mark ancestor views as dirty. If already in the `dirty_views` set, then all its ancestors
1503 // should already be dirty.
1504 for view_id in self
1505 .rendered_frame
1506 .dispatch_tree
1507 .view_path_reversed(view_id)
1508 {
1509 if !self.dirty_views.insert(view_id) {
1510 break;
1511 }
1512 }
1513 }
1514
1515 /// Registers a callback to be invoked when the window appearance changes.
1516 pub fn observe_window_appearance(
1517 &self,
1518 mut callback: impl FnMut(&mut Window, &mut App) + 'static,
1519 ) -> Subscription {
1520 let (subscription, activate) = self.appearance_observers.insert(
1521 (),
1522 Box::new(move |window, cx| {
1523 callback(window, cx);
1524 true
1525 }),
1526 );
1527 activate();
1528 subscription
1529 }
1530
1531 /// Replaces the root entity of the window with a new one.
1532 pub fn replace_root<E>(
1533 &mut self,
1534 cx: &mut App,
1535 build_view: impl FnOnce(&mut Window, &mut Context<E>) -> E,
1536 ) -> Entity<E>
1537 where
1538 E: 'static + Render,
1539 {
1540 let view = cx.new(|cx| build_view(self, cx));
1541 self.root = Some(view.clone().into());
1542 self.refresh();
1543 view
1544 }
1545
1546 /// Returns the root entity of the window, if it has one.
1547 pub fn root<E>(&self) -> Option<Option<Entity<E>>>
1548 where
1549 E: 'static + Render,
1550 {
1551 self.root
1552 .as_ref()
1553 .map(|view| view.clone().downcast::<E>().ok())
1554 }
1555
1556 /// Obtain a handle to the window that belongs to this context.
1557 pub fn window_handle(&self) -> AnyWindowHandle {
1558 self.handle
1559 }
1560
1561 /// Mark the window as dirty, scheduling it to be redrawn on the next frame.
1562 pub fn refresh(&mut self) {
1563 if self.invalidator.not_drawing() {
1564 self.refreshing = true;
1565 self.invalidator.set_dirty(true);
1566 }
1567 }
1568
1569 /// Close this window.
1570 pub fn remove_window(&mut self) {
1571 self.removed = true;
1572 }
1573
1574 /// Obtain the currently focused [`FocusHandle`]. If no elements are focused, returns `None`.
1575 pub fn focused(&self, cx: &App) -> Option<FocusHandle> {
1576 self.focus
1577 .and_then(|id| FocusHandle::for_id(id, &cx.focus_handles))
1578 }
1579
1580 /// Move focus to the element associated with the given [`FocusHandle`].
1581 pub fn focus(&mut self, handle: &FocusHandle, cx: &mut App) {
1582 if !self.focus_enabled || self.focus == Some(handle.id) {
1583 return;
1584 }
1585
1586 self.focus = Some(handle.id);
1587 self.clear_pending_keystrokes();
1588
1589 // Avoid re-entrant entity updates by deferring observer notifications to the end of the
1590 // current effect cycle, and only for this window.
1591 let window_handle = self.handle;
1592 cx.defer(move |cx| {
1593 window_handle
1594 .update(cx, |_, window, cx| {
1595 window.pending_input_changed(cx);
1596 })
1597 .ok();
1598 });
1599
1600 self.refresh();
1601 }
1602
1603 /// Remove focus from all elements within this context's window.
1604 pub fn blur(&mut self) {
1605 if !self.focus_enabled {
1606 return;
1607 }
1608
1609 self.focus = None;
1610 self.refresh();
1611 }
1612
1613 /// Blur the window and don't allow anything in it to be focused again.
1614 pub fn disable_focus(&mut self) {
1615 self.blur();
1616 self.focus_enabled = false;
1617 }
1618
1619 /// Move focus to next tab stop.
1620 pub fn focus_next(&mut self, cx: &mut App) {
1621 if !self.focus_enabled {
1622 return;
1623 }
1624
1625 if let Some(handle) = self.rendered_frame.tab_stops.next(self.focus.as_ref()) {
1626 self.focus(&handle, cx)
1627 }
1628 }
1629
1630 /// Move focus to previous tab stop.
1631 pub fn focus_prev(&mut self, cx: &mut App) {
1632 if !self.focus_enabled {
1633 return;
1634 }
1635
1636 if let Some(handle) = self.rendered_frame.tab_stops.prev(self.focus.as_ref()) {
1637 self.focus(&handle, cx)
1638 }
1639 }
1640
1641 /// Accessor for the text system.
1642 pub fn text_system(&self) -> &Arc<WindowTextSystem> {
1643 &self.text_system
1644 }
1645
1646 /// The current text style. Which is composed of all the style refinements provided to `with_text_style`.
1647 pub fn text_style(&self) -> TextStyle {
1648 let mut style = TextStyle::default();
1649 for refinement in &self.text_style_stack {
1650 style.refine(refinement);
1651 }
1652 style
1653 }
1654
1655 /// Check if the platform window is maximized.
1656 ///
1657 /// On some platforms (namely Windows) this is different than the bounds being the size of the display
1658 pub fn is_maximized(&self) -> bool {
1659 self.platform_window.is_maximized()
1660 }
1661
1662 /// request a certain window decoration (Wayland)
1663 pub fn request_decorations(&self, decorations: WindowDecorations) {
1664 self.platform_window.request_decorations(decorations);
1665 }
1666
1667 /// Start a window resize operation (Wayland)
1668 pub fn start_window_resize(&self, edge: ResizeEdge) {
1669 self.platform_window.start_window_resize(edge);
1670 }
1671
1672 /// Return the `WindowBounds` to indicate that how a window should be opened
1673 /// after it has been closed
1674 pub fn window_bounds(&self) -> WindowBounds {
1675 self.platform_window.window_bounds()
1676 }
1677
1678 /// Return the `WindowBounds` excluding insets (Wayland and X11)
1679 pub fn inner_window_bounds(&self) -> WindowBounds {
1680 self.platform_window.inner_window_bounds()
1681 }
1682
1683 /// Dispatch the given action on the currently focused element.
1684 pub fn dispatch_action(&mut self, action: Box<dyn Action>, cx: &mut App) {
1685 let focus_id = self.focused(cx).map(|handle| handle.id);
1686
1687 let window = self.handle;
1688 cx.defer(move |cx| {
1689 window
1690 .update(cx, |_, window, cx| {
1691 let node_id = window.focus_node_id_in_rendered_frame(focus_id);
1692 window.dispatch_action_on_node(node_id, action.as_ref(), cx);
1693 })
1694 .log_err();
1695 })
1696 }
1697
1698 pub(crate) fn dispatch_keystroke_observers(
1699 &mut self,
1700 event: &dyn Any,
1701 action: Option<Box<dyn Action>>,
1702 context_stack: Vec<KeyContext>,
1703 cx: &mut App,
1704 ) {
1705 let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() else {
1706 return;
1707 };
1708
1709 cx.keystroke_observers.clone().retain(&(), move |callback| {
1710 (callback)(
1711 &KeystrokeEvent {
1712 keystroke: key_down_event.keystroke.clone(),
1713 action: action.as_ref().map(|action| action.boxed_clone()),
1714 context_stack: context_stack.clone(),
1715 },
1716 self,
1717 cx,
1718 )
1719 });
1720 }
1721
1722 pub(crate) fn dispatch_keystroke_interceptors(
1723 &mut self,
1724 event: &dyn Any,
1725 context_stack: Vec<KeyContext>,
1726 cx: &mut App,
1727 ) {
1728 let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() else {
1729 return;
1730 };
1731
1732 cx.keystroke_interceptors
1733 .clone()
1734 .retain(&(), move |callback| {
1735 (callback)(
1736 &KeystrokeEvent {
1737 keystroke: key_down_event.keystroke.clone(),
1738 action: None,
1739 context_stack: context_stack.clone(),
1740 },
1741 self,
1742 cx,
1743 )
1744 });
1745 }
1746
1747 /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
1748 /// that are currently on the stack to be returned to the app.
1749 pub fn defer(&self, cx: &mut App, f: impl FnOnce(&mut Window, &mut App) + 'static) {
1750 let handle = self.handle;
1751 cx.defer(move |cx| {
1752 handle.update(cx, |_, window, cx| f(window, cx)).ok();
1753 });
1754 }
1755
1756 /// Subscribe to events emitted by a entity.
1757 /// The entity to which you're subscribing must implement the [`EventEmitter`] trait.
1758 /// The callback will be invoked a handle to the emitting entity, the event, and a window context for the current window.
1759 pub fn observe<T: 'static>(
1760 &mut self,
1761 observed: &Entity<T>,
1762 cx: &mut App,
1763 mut on_notify: impl FnMut(Entity<T>, &mut Window, &mut App) + 'static,
1764 ) -> Subscription {
1765 let entity_id = observed.entity_id();
1766 let observed = observed.downgrade();
1767 let window_handle = self.handle;
1768 cx.new_observer(
1769 entity_id,
1770 Box::new(move |cx| {
1771 window_handle
1772 .update(cx, |_, window, cx| {
1773 if let Some(handle) = observed.upgrade() {
1774 on_notify(handle, window, cx);
1775 true
1776 } else {
1777 false
1778 }
1779 })
1780 .unwrap_or(false)
1781 }),
1782 )
1783 }
1784
1785 /// Subscribe to events emitted by a entity.
1786 /// The entity to which you're subscribing must implement the [`EventEmitter`] trait.
1787 /// The callback will be invoked a handle to the emitting entity, the event, and a window context for the current window.
1788 pub fn subscribe<Emitter, Evt>(
1789 &mut self,
1790 entity: &Entity<Emitter>,
1791 cx: &mut App,
1792 mut on_event: impl FnMut(Entity<Emitter>, &Evt, &mut Window, &mut App) + 'static,
1793 ) -> Subscription
1794 where
1795 Emitter: EventEmitter<Evt>,
1796 Evt: 'static,
1797 {
1798 let entity_id = entity.entity_id();
1799 let handle = entity.downgrade();
1800 let window_handle = self.handle;
1801 cx.new_subscription(
1802 entity_id,
1803 (
1804 TypeId::of::<Evt>(),
1805 Box::new(move |event, cx| {
1806 window_handle
1807 .update(cx, |_, window, cx| {
1808 if let Some(entity) = handle.upgrade() {
1809 let event = event.downcast_ref().expect("invalid event type");
1810 on_event(entity, event, window, cx);
1811 true
1812 } else {
1813 false
1814 }
1815 })
1816 .unwrap_or(false)
1817 }),
1818 ),
1819 )
1820 }
1821
1822 /// Register a callback to be invoked when the given `Entity` is released.
1823 pub fn observe_release<T>(
1824 &self,
1825 entity: &Entity<T>,
1826 cx: &mut App,
1827 mut on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,
1828 ) -> Subscription
1829 where
1830 T: 'static,
1831 {
1832 let entity_id = entity.entity_id();
1833 let window_handle = self.handle;
1834 let (subscription, activate) = cx.release_listeners.insert(
1835 entity_id,
1836 Box::new(move |entity, cx| {
1837 let entity = entity.downcast_mut().expect("invalid entity type");
1838 let _ = window_handle.update(cx, |_, window, cx| on_release(entity, window, cx));
1839 }),
1840 );
1841 activate();
1842 subscription
1843 }
1844
1845 /// Creates an [`AsyncWindowContext`], which has a static lifetime and can be held across
1846 /// await points in async code.
1847 pub fn to_async(&self, cx: &App) -> AsyncWindowContext {
1848 AsyncWindowContext::new_context(cx.to_async(), self.handle)
1849 }
1850
1851 /// Schedule the given closure to be run directly after the current frame is rendered.
1852 pub fn on_next_frame(&self, callback: impl FnOnce(&mut Window, &mut App) + 'static) {
1853 RefCell::borrow_mut(&self.next_frame_callbacks).push(Box::new(callback));
1854 }
1855
1856 /// Schedule a frame to be drawn on the next animation frame.
1857 ///
1858 /// This is useful for elements that need to animate continuously, such as a video player or an animated GIF.
1859 /// It will cause the window to redraw on the next frame, even if no other changes have occurred.
1860 ///
1861 /// If called from within a view, it will notify that view on the next frame. Otherwise, it will refresh the entire window.
1862 pub fn request_animation_frame(&self) {
1863 let entity = self.current_view();
1864 self.on_next_frame(move |_, cx| cx.notify(entity));
1865 }
1866
1867 /// Spawn the future returned by the given closure on the application thread pool.
1868 /// The closure is provided a handle to the current window and an `AsyncWindowContext` for
1869 /// use within your future.
1870 #[track_caller]
1871 pub fn spawn<AsyncFn, R>(&self, cx: &App, f: AsyncFn) -> Task<R>
1872 where
1873 R: 'static,
1874 AsyncFn: AsyncFnOnce(&mut AsyncWindowContext) -> R + 'static,
1875 {
1876 let handle = self.handle;
1877 cx.spawn(async move |app| {
1878 let mut async_window_cx = AsyncWindowContext::new_context(app.clone(), handle);
1879 f(&mut async_window_cx).await
1880 })
1881 }
1882
1883 /// Spawn the future returned by the given closure on the application thread
1884 /// pool, with the given priority. The closure is provided a handle to the
1885 /// current window and an `AsyncWindowContext` for use within your future.
1886 #[track_caller]
1887 pub fn spawn_with_priority<AsyncFn, R>(
1888 &self,
1889 priority: Priority,
1890 cx: &App,
1891 f: AsyncFn,
1892 ) -> Task<R>
1893 where
1894 R: 'static,
1895 AsyncFn: AsyncFnOnce(&mut AsyncWindowContext) -> R + 'static,
1896 {
1897 let handle = self.handle;
1898 cx.spawn_with_priority(priority, async move |app| {
1899 let mut async_window_cx = AsyncWindowContext::new_context(app.clone(), handle);
1900 f(&mut async_window_cx).await
1901 })
1902 }
1903
1904 /// Notify the window that its bounds have changed.
1905 ///
1906 /// This updates internal state like `viewport_size` and `scale_factor` from
1907 /// the platform window, then notifies observers. Normally called automatically
1908 /// by the platform's resize callback, but exposed publicly for test infrastructure.
1909 pub fn bounds_changed(&mut self, cx: &mut App) {
1910 self.scale_factor = self.platform_window.scale_factor();
1911 self.viewport_size = self.platform_window.content_size();
1912 self.display_id = self.platform_window.display().map(|display| display.id());
1913
1914 self.refresh();
1915
1916 self.bounds_observers
1917 .clone()
1918 .retain(&(), |callback| callback(self, cx));
1919 }
1920
1921 /// Returns the bounds of the current window in the global coordinate space, which could span across multiple displays.
1922 pub fn bounds(&self) -> Bounds<Pixels> {
1923 self.platform_window.bounds()
1924 }
1925
1926 /// Renders the current frame's scene to a texture and returns the pixel data as an RGBA image.
1927 /// This does not present the frame to screen - useful for visual testing where we want
1928 /// to capture what would be rendered without displaying it or requiring the window to be visible.
1929 #[cfg(any(test, feature = "test-support"))]
1930 pub fn render_to_image(&self) -> anyhow::Result<image::RgbaImage> {
1931 self.platform_window
1932 .render_to_image(&self.rendered_frame.scene)
1933 }
1934
1935 /// Set the content size of the window.
1936 pub fn resize(&mut self, size: Size<Pixels>) {
1937 self.platform_window.resize(size);
1938 }
1939
1940 /// Returns whether or not the window is currently fullscreen
1941 pub fn is_fullscreen(&self) -> bool {
1942 self.platform_window.is_fullscreen()
1943 }
1944
1945 pub(crate) fn appearance_changed(&mut self, cx: &mut App) {
1946 self.appearance = self.platform_window.appearance();
1947
1948 self.appearance_observers
1949 .clone()
1950 .retain(&(), |callback| callback(self, cx));
1951 }
1952
1953 /// Returns the appearance of the current window.
1954 pub fn appearance(&self) -> WindowAppearance {
1955 self.appearance
1956 }
1957
1958 /// Returns the size of the drawable area within the window.
1959 pub fn viewport_size(&self) -> Size<Pixels> {
1960 self.viewport_size
1961 }
1962
1963 /// Returns whether this window is focused by the operating system (receiving key events).
1964 pub fn is_window_active(&self) -> bool {
1965 self.active.get()
1966 }
1967
1968 /// Returns whether this window is considered to be the window
1969 /// that currently owns the mouse cursor.
1970 /// On mac, this is equivalent to `is_window_active`.
1971 pub fn is_window_hovered(&self) -> bool {
1972 if cfg!(any(
1973 target_os = "windows",
1974 target_os = "linux",
1975 target_os = "freebsd"
1976 )) {
1977 self.hovered.get()
1978 } else {
1979 self.is_window_active()
1980 }
1981 }
1982
1983 /// Toggle zoom on the window.
1984 pub fn zoom_window(&self) {
1985 self.platform_window.zoom();
1986 }
1987
1988 /// Opens the native title bar context menu, useful when implementing client side decorations (Wayland and X11)
1989 pub fn show_window_menu(&self, position: Point<Pixels>) {
1990 self.platform_window.show_window_menu(position)
1991 }
1992
1993 /// Handle window movement for Linux and macOS.
1994 /// Tells the compositor to take control of window movement (Wayland and X11)
1995 ///
1996 /// Events may not be received during a move operation.
1997 pub fn start_window_move(&self) {
1998 self.platform_window.start_window_move()
1999 }
2000
2001 /// When using client side decorations, set this to the width of the invisible decorations (Wayland and X11)
2002 pub fn set_client_inset(&mut self, inset: Pixels) {
2003 self.client_inset = Some(inset);
2004 self.platform_window.set_client_inset(inset);
2005 }
2006
2007 /// Returns the client_inset value by [`Self::set_client_inset`].
2008 pub fn client_inset(&self) -> Option<Pixels> {
2009 self.client_inset
2010 }
2011
2012 /// Returns whether the title bar window controls need to be rendered by the application (Wayland and X11)
2013 pub fn window_decorations(&self) -> Decorations {
2014 self.platform_window.window_decorations()
2015 }
2016
2017 /// Returns which window controls are currently visible (Wayland)
2018 pub fn window_controls(&self) -> WindowControls {
2019 self.platform_window.window_controls()
2020 }
2021
2022 /// Updates the window's title at the platform level.
2023 pub fn set_window_title(&mut self, title: &str) {
2024 self.platform_window.set_title(title);
2025 }
2026
2027 /// Sets the application identifier.
2028 pub fn set_app_id(&mut self, app_id: &str) {
2029 self.platform_window.set_app_id(app_id);
2030 }
2031
2032 /// Sets the window background appearance.
2033 pub fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance) {
2034 self.platform_window
2035 .set_background_appearance(background_appearance);
2036 }
2037
2038 /// Mark the window as dirty at the platform level.
2039 pub fn set_window_edited(&mut self, edited: bool) {
2040 self.platform_window.set_edited(edited);
2041 }
2042
2043 /// Determine the display on which the window is visible.
2044 pub fn display(&self, cx: &App) -> Option<Rc<dyn PlatformDisplay>> {
2045 cx.platform
2046 .displays()
2047 .into_iter()
2048 .find(|display| Some(display.id()) == self.display_id)
2049 }
2050
2051 /// Show the platform character palette.
2052 pub fn show_character_palette(&self) {
2053 self.platform_window.show_character_palette();
2054 }
2055
2056 /// The scale factor of the display associated with the window. For example, it could
2057 /// return 2.0 for a "retina" display, indicating that each logical pixel should actually
2058 /// be rendered as two pixels on screen.
2059 pub fn scale_factor(&self) -> f32 {
2060 self.scale_factor
2061 }
2062
2063 /// The size of an em for the base font of the application. Adjusting this value allows the
2064 /// UI to scale, just like zooming a web page.
2065 pub fn rem_size(&self) -> Pixels {
2066 self.rem_size_override_stack
2067 .last()
2068 .copied()
2069 .unwrap_or(self.rem_size)
2070 }
2071
2072 /// Sets the size of an em for the base font of the application. Adjusting this value allows the
2073 /// UI to scale, just like zooming a web page.
2074 pub fn set_rem_size(&mut self, rem_size: impl Into<Pixels>) {
2075 self.rem_size = rem_size.into();
2076 }
2077
2078 /// Acquire a globally unique identifier for the given ElementId.
2079 /// Only valid for the duration of the provided closure.
2080 pub fn with_global_id<R>(
2081 &mut self,
2082 element_id: ElementId,
2083 f: impl FnOnce(&GlobalElementId, &mut Self) -> R,
2084 ) -> R {
2085 self.with_id(element_id, |this| {
2086 let global_id = GlobalElementId(Arc::from(&*this.element_id_stack));
2087
2088 f(&global_id, this)
2089 })
2090 }
2091
2092 /// Calls the provided closure with the element ID pushed on the stack.
2093 #[inline]
2094 pub fn with_id<R>(
2095 &mut self,
2096 element_id: impl Into<ElementId>,
2097 f: impl FnOnce(&mut Self) -> R,
2098 ) -> R {
2099 self.element_id_stack.push(element_id.into());
2100 let result = f(self);
2101 self.element_id_stack.pop();
2102 result
2103 }
2104
2105 /// Executes the provided function with the specified rem size.
2106 ///
2107 /// This method must only be called as part of element drawing.
2108 // This function is called in a highly recursive manner in editor
2109 // prepainting, make sure its inlined to reduce the stack burden
2110 #[inline]
2111 pub fn with_rem_size<F, R>(&mut self, rem_size: Option<impl Into<Pixels>>, f: F) -> R
2112 where
2113 F: FnOnce(&mut Self) -> R,
2114 {
2115 self.invalidator.debug_assert_paint_or_prepaint();
2116
2117 if let Some(rem_size) = rem_size {
2118 self.rem_size_override_stack.push(rem_size.into());
2119 let result = f(self);
2120 self.rem_size_override_stack.pop();
2121 result
2122 } else {
2123 f(self)
2124 }
2125 }
2126
2127 /// The line height associated with the current text style.
2128 pub fn line_height(&self) -> Pixels {
2129 self.text_style().line_height_in_pixels(self.rem_size())
2130 }
2131
2132 /// Call to prevent the default action of an event. Currently only used to prevent
2133 /// parent elements from becoming focused on mouse down.
2134 pub fn prevent_default(&mut self) {
2135 self.default_prevented = true;
2136 }
2137
2138 /// Obtain whether default has been prevented for the event currently being dispatched.
2139 pub fn default_prevented(&self) -> bool {
2140 self.default_prevented
2141 }
2142
2143 /// Determine whether the given action is available along the dispatch path to the currently focused element.
2144 pub fn is_action_available(&self, action: &dyn Action, cx: &App) -> bool {
2145 let node_id =
2146 self.focus_node_id_in_rendered_frame(self.focused(cx).map(|handle| handle.id));
2147 self.rendered_frame
2148 .dispatch_tree
2149 .is_action_available(action, node_id)
2150 }
2151
2152 /// Determine whether the given action is available along the dispatch path to the given focus_handle.
2153 pub fn is_action_available_in(&self, action: &dyn Action, focus_handle: &FocusHandle) -> bool {
2154 let node_id = self.focus_node_id_in_rendered_frame(Some(focus_handle.id));
2155 self.rendered_frame
2156 .dispatch_tree
2157 .is_action_available(action, node_id)
2158 }
2159
2160 /// The position of the mouse relative to the window.
2161 pub fn mouse_position(&self) -> Point<Pixels> {
2162 self.mouse_position
2163 }
2164
2165 /// Captures the pointer for the given hitbox. While captured, all mouse move and mouse up
2166 /// events will be routed to listeners that check this hitbox's `is_hovered` status,
2167 /// regardless of actual hit testing. This enables drag operations that continue
2168 /// even when the pointer moves outside the element's bounds.
2169 ///
2170 /// The capture is automatically released on mouse up.
2171 pub fn capture_pointer(&mut self, hitbox_id: HitboxId) {
2172 self.captured_hitbox = Some(hitbox_id);
2173 }
2174
2175 /// Releases any active pointer capture.
2176 pub fn release_pointer(&mut self) {
2177 self.captured_hitbox = None;
2178 }
2179
2180 /// Returns the hitbox that has captured the pointer, if any.
2181 pub fn captured_hitbox(&self) -> Option<HitboxId> {
2182 self.captured_hitbox
2183 }
2184
2185 /// The current state of the keyboard's modifiers
2186 pub fn modifiers(&self) -> Modifiers {
2187 self.modifiers
2188 }
2189
2190 /// Returns true if the last input event was keyboard-based (key press, tab navigation, etc.)
2191 /// This is used for focus-visible styling to show focus indicators only for keyboard navigation.
2192 pub fn last_input_was_keyboard(&self) -> bool {
2193 self.last_input_modality == InputModality::Keyboard
2194 }
2195
2196 /// The current state of the keyboard's capslock
2197 pub fn capslock(&self) -> Capslock {
2198 self.capslock
2199 }
2200
2201 fn complete_frame(&self) {
2202 self.platform_window.completed_frame();
2203 }
2204
2205 /// Produces a new frame and assigns it to `rendered_frame`. To actually show
2206 /// the contents of the new [`Scene`], use [`Self::present`].
2207 #[profiling::function]
2208 pub fn draw(&mut self, cx: &mut App) -> ArenaClearNeeded {
2209 // Set up the per-App arena for element allocation during this draw.
2210 // This ensures that multiple test Apps have isolated arenas.
2211 let _arena_scope = ElementArenaScope::enter(&cx.element_arena);
2212
2213 self.invalidate_entities();
2214 cx.entities.clear_accessed();
2215 debug_assert!(self.rendered_entity_stack.is_empty());
2216 self.invalidator.set_dirty(false);
2217 self.requested_autoscroll = None;
2218
2219 // Restore the previously-used input handler.
2220 if let Some(input_handler) = self.platform_window.take_input_handler() {
2221 self.rendered_frame.input_handlers.push(Some(input_handler));
2222 }
2223 if !cx.mode.skip_drawing() {
2224 self.draw_roots(cx);
2225 }
2226 self.dirty_views.clear();
2227 self.next_frame.window_active = self.active.get();
2228
2229 // Register requested input handler with the platform window.
2230 if let Some(input_handler) = self.next_frame.input_handlers.pop() {
2231 self.platform_window
2232 .set_input_handler(input_handler.unwrap());
2233 }
2234
2235 self.layout_engine.as_mut().unwrap().clear();
2236 self.text_system().finish_frame();
2237 self.next_frame.finish(&mut self.rendered_frame);
2238
2239 self.invalidator.set_phase(DrawPhase::Focus);
2240 let previous_focus_path = self.rendered_frame.focus_path();
2241 let previous_window_active = self.rendered_frame.window_active;
2242 mem::swap(&mut self.rendered_frame, &mut self.next_frame);
2243 self.next_frame.clear();
2244 let current_focus_path = self.rendered_frame.focus_path();
2245 let current_window_active = self.rendered_frame.window_active;
2246
2247 if previous_focus_path != current_focus_path
2248 || previous_window_active != current_window_active
2249 {
2250 if !previous_focus_path.is_empty() && current_focus_path.is_empty() {
2251 self.focus_lost_listeners
2252 .clone()
2253 .retain(&(), |listener| listener(self, cx));
2254 }
2255
2256 let event = WindowFocusEvent {
2257 previous_focus_path: if previous_window_active {
2258 previous_focus_path
2259 } else {
2260 Default::default()
2261 },
2262 current_focus_path: if current_window_active {
2263 current_focus_path
2264 } else {
2265 Default::default()
2266 },
2267 };
2268 self.focus_listeners
2269 .clone()
2270 .retain(&(), |listener| listener(&event, self, cx));
2271 }
2272
2273 debug_assert!(self.rendered_entity_stack.is_empty());
2274 self.record_entities_accessed(cx);
2275 self.reset_cursor_style(cx);
2276 self.refreshing = false;
2277 self.invalidator.set_phase(DrawPhase::None);
2278 self.needs_present.set(true);
2279
2280 ArenaClearNeeded::new(&cx.element_arena)
2281 }
2282
2283 fn record_entities_accessed(&mut self, cx: &mut App) {
2284 let mut entities_ref = cx.entities.accessed_entities.get_mut();
2285 let mut entities = mem::take(entities_ref.deref_mut());
2286 let handle = self.handle;
2287 cx.record_entities_accessed(
2288 handle,
2289 // Try moving window invalidator into the Window
2290 self.invalidator.clone(),
2291 &entities,
2292 );
2293 let mut entities_ref = cx.entities.accessed_entities.get_mut();
2294 mem::swap(&mut entities, entities_ref.deref_mut());
2295 }
2296
2297 fn invalidate_entities(&mut self) {
2298 let mut views = self.invalidator.take_views();
2299 for entity in views.drain() {
2300 self.mark_view_dirty(entity);
2301 }
2302 self.invalidator.replace_views(views);
2303 }
2304
2305 #[profiling::function]
2306 fn present(&self) {
2307 self.platform_window.draw(&self.rendered_frame.scene);
2308 self.needs_present.set(false);
2309 profiling::finish_frame!();
2310 }
2311
2312 fn draw_roots(&mut self, cx: &mut App) {
2313 self.invalidator.set_phase(DrawPhase::Prepaint);
2314 self.tooltip_bounds.take();
2315
2316 let _inspector_width: Pixels = rems(30.0).to_pixels(self.rem_size());
2317 let root_size = {
2318 #[cfg(any(feature = "inspector", debug_assertions))]
2319 {
2320 if self.inspector.is_some() {
2321 let mut size = self.viewport_size;
2322 size.width = (size.width - _inspector_width).max(px(0.0));
2323 size
2324 } else {
2325 self.viewport_size
2326 }
2327 }
2328 #[cfg(not(any(feature = "inspector", debug_assertions)))]
2329 {
2330 self.viewport_size
2331 }
2332 };
2333
2334 // Layout all root elements.
2335 let mut root_element = self.root.as_ref().unwrap().clone().into_any();
2336 root_element.prepaint_as_root(Point::default(), root_size.into(), self, cx);
2337
2338 #[cfg(any(feature = "inspector", debug_assertions))]
2339 let inspector_element = self.prepaint_inspector(_inspector_width, cx);
2340
2341 let mut sorted_deferred_draws =
2342 (0..self.next_frame.deferred_draws.len()).collect::<SmallVec<[_; 8]>>();
2343 sorted_deferred_draws.sort_by_key(|ix| self.next_frame.deferred_draws[*ix].priority);
2344 self.prepaint_deferred_draws(&sorted_deferred_draws, cx);
2345
2346 let mut prompt_element = None;
2347 let mut active_drag_element = None;
2348 let mut tooltip_element = None;
2349 if let Some(prompt) = self.prompt.take() {
2350 let mut element = prompt.view.any_view().into_any();
2351 element.prepaint_as_root(Point::default(), root_size.into(), self, cx);
2352 prompt_element = Some(element);
2353 self.prompt = Some(prompt);
2354 } else if let Some(active_drag) = cx.active_drag.take() {
2355 let mut element = active_drag.view.clone().into_any();
2356 let offset = self.mouse_position() - active_drag.cursor_offset;
2357 element.prepaint_as_root(offset, AvailableSpace::min_size(), self, cx);
2358 active_drag_element = Some(element);
2359 cx.active_drag = Some(active_drag);
2360 } else {
2361 tooltip_element = self.prepaint_tooltip(cx);
2362 }
2363
2364 self.mouse_hit_test = self.next_frame.hit_test(self.mouse_position);
2365
2366 // Now actually paint the elements.
2367 self.invalidator.set_phase(DrawPhase::Paint);
2368 root_element.paint(self, cx);
2369
2370 #[cfg(any(feature = "inspector", debug_assertions))]
2371 self.paint_inspector(inspector_element, cx);
2372
2373 self.paint_deferred_draws(&sorted_deferred_draws, cx);
2374
2375 if let Some(mut prompt_element) = prompt_element {
2376 prompt_element.paint(self, cx);
2377 } else if let Some(mut drag_element) = active_drag_element {
2378 drag_element.paint(self, cx);
2379 } else if let Some(mut tooltip_element) = tooltip_element {
2380 tooltip_element.paint(self, cx);
2381 }
2382
2383 #[cfg(any(feature = "inspector", debug_assertions))]
2384 self.paint_inspector_hitbox(cx);
2385 }
2386
2387 fn prepaint_tooltip(&mut self, cx: &mut App) -> Option<AnyElement> {
2388 // Use indexing instead of iteration to avoid borrowing self for the duration of the loop.
2389 for tooltip_request_index in (0..self.next_frame.tooltip_requests.len()).rev() {
2390 let Some(Some(tooltip_request)) = self
2391 .next_frame
2392 .tooltip_requests
2393 .get(tooltip_request_index)
2394 .cloned()
2395 else {
2396 log::error!("Unexpectedly absent TooltipRequest");
2397 continue;
2398 };
2399 let mut element = tooltip_request.tooltip.view.clone().into_any();
2400 let mouse_position = tooltip_request.tooltip.mouse_position;
2401 let tooltip_size = element.layout_as_root(AvailableSpace::min_size(), self, cx);
2402
2403 let mut tooltip_bounds =
2404 Bounds::new(mouse_position + point(px(1.), px(1.)), tooltip_size);
2405 let window_bounds = Bounds {
2406 origin: Point::default(),
2407 size: self.viewport_size(),
2408 };
2409
2410 if tooltip_bounds.right() > window_bounds.right() {
2411 let new_x = mouse_position.x - tooltip_bounds.size.width - px(1.);
2412 if new_x >= Pixels::ZERO {
2413 tooltip_bounds.origin.x = new_x;
2414 } else {
2415 tooltip_bounds.origin.x = cmp::max(
2416 Pixels::ZERO,
2417 tooltip_bounds.origin.x - tooltip_bounds.right() - window_bounds.right(),
2418 );
2419 }
2420 }
2421
2422 if tooltip_bounds.bottom() > window_bounds.bottom() {
2423 let new_y = mouse_position.y - tooltip_bounds.size.height - px(1.);
2424 if new_y >= Pixels::ZERO {
2425 tooltip_bounds.origin.y = new_y;
2426 } else {
2427 tooltip_bounds.origin.y = cmp::max(
2428 Pixels::ZERO,
2429 tooltip_bounds.origin.y - tooltip_bounds.bottom() - window_bounds.bottom(),
2430 );
2431 }
2432 }
2433
2434 // It's possible for an element to have an active tooltip while not being painted (e.g.
2435 // via the `visible_on_hover` method). Since mouse listeners are not active in this
2436 // case, instead update the tooltip's visibility here.
2437 let is_visible =
2438 (tooltip_request.tooltip.check_visible_and_update)(tooltip_bounds, self, cx);
2439 if !is_visible {
2440 continue;
2441 }
2442
2443 self.with_absolute_element_offset(tooltip_bounds.origin, |window| {
2444 element.prepaint(window, cx)
2445 });
2446
2447 self.tooltip_bounds = Some(TooltipBounds {
2448 id: tooltip_request.id,
2449 bounds: tooltip_bounds,
2450 });
2451 return Some(element);
2452 }
2453 None
2454 }
2455
2456 fn prepaint_deferred_draws(&mut self, deferred_draw_indices: &[usize], cx: &mut App) {
2457 assert_eq!(self.element_id_stack.len(), 0);
2458
2459 let mut deferred_draws = mem::take(&mut self.next_frame.deferred_draws);
2460 for deferred_draw_ix in deferred_draw_indices {
2461 let deferred_draw = &mut deferred_draws[*deferred_draw_ix];
2462 self.element_id_stack
2463 .clone_from(&deferred_draw.element_id_stack);
2464 self.text_style_stack
2465 .clone_from(&deferred_draw.text_style_stack);
2466 self.next_frame
2467 .dispatch_tree
2468 .set_active_node(deferred_draw.parent_node);
2469
2470 let prepaint_start = self.prepaint_index();
2471 let content_mask = deferred_draw.content_mask.clone();
2472 if let Some(element) = deferred_draw.element.as_mut() {
2473 self.with_rendered_view(deferred_draw.current_view, |window| {
2474 window.with_content_mask(content_mask, |window| {
2475 window.with_rem_size(Some(deferred_draw.rem_size), |window| {
2476 window.with_absolute_element_offset(
2477 deferred_draw.absolute_offset,
2478 |window| {
2479 element.prepaint(window, cx);
2480 },
2481 );
2482 });
2483 });
2484 })
2485 } else {
2486 self.reuse_prepaint(deferred_draw.prepaint_range.clone());
2487 }
2488 let prepaint_end = self.prepaint_index();
2489 deferred_draw.prepaint_range = prepaint_start..prepaint_end;
2490 }
2491 assert_eq!(
2492 self.next_frame.deferred_draws.len(),
2493 0,
2494 "cannot call defer_draw during deferred drawing"
2495 );
2496 self.next_frame.deferred_draws = deferred_draws;
2497 self.element_id_stack.clear();
2498 self.text_style_stack.clear();
2499 }
2500
2501 fn paint_deferred_draws(&mut self, deferred_draw_indices: &[usize], cx: &mut App) {
2502 assert_eq!(self.element_id_stack.len(), 0);
2503
2504 let mut deferred_draws = mem::take(&mut self.next_frame.deferred_draws);
2505 for deferred_draw_ix in deferred_draw_indices {
2506 let mut deferred_draw = &mut deferred_draws[*deferred_draw_ix];
2507 self.element_id_stack
2508 .clone_from(&deferred_draw.element_id_stack);
2509 self.next_frame
2510 .dispatch_tree
2511 .set_active_node(deferred_draw.parent_node);
2512
2513 let paint_start = self.paint_index();
2514 let content_mask = deferred_draw.content_mask.clone();
2515 if let Some(element) = deferred_draw.element.as_mut() {
2516 self.with_rendered_view(deferred_draw.current_view, |window| {
2517 window.with_content_mask(content_mask, |window| {
2518 window.with_rem_size(Some(deferred_draw.rem_size), |window| {
2519 element.paint(window, cx);
2520 });
2521 })
2522 })
2523 } else {
2524 self.reuse_paint(deferred_draw.paint_range.clone());
2525 }
2526 let paint_end = self.paint_index();
2527 deferred_draw.paint_range = paint_start..paint_end;
2528 }
2529 self.next_frame.deferred_draws = deferred_draws;
2530 self.element_id_stack.clear();
2531 }
2532
2533 pub(crate) fn prepaint_index(&self) -> PrepaintStateIndex {
2534 PrepaintStateIndex {
2535 hitboxes_index: self.next_frame.hitboxes.len(),
2536 tooltips_index: self.next_frame.tooltip_requests.len(),
2537 deferred_draws_index: self.next_frame.deferred_draws.len(),
2538 dispatch_tree_index: self.next_frame.dispatch_tree.len(),
2539 accessed_element_states_index: self.next_frame.accessed_element_states.len(),
2540 line_layout_index: self.text_system.layout_index(),
2541 }
2542 }
2543
2544 pub(crate) fn reuse_prepaint(&mut self, range: Range<PrepaintStateIndex>) {
2545 self.next_frame.hitboxes.extend(
2546 self.rendered_frame.hitboxes[range.start.hitboxes_index..range.end.hitboxes_index]
2547 .iter()
2548 .cloned(),
2549 );
2550 self.next_frame.tooltip_requests.extend(
2551 self.rendered_frame.tooltip_requests
2552 [range.start.tooltips_index..range.end.tooltips_index]
2553 .iter_mut()
2554 .map(|request| request.take()),
2555 );
2556 self.next_frame.accessed_element_states.extend(
2557 self.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
2558 ..range.end.accessed_element_states_index]
2559 .iter()
2560 .map(|(id, type_id)| (id.clone(), *type_id)),
2561 );
2562 self.text_system
2563 .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
2564
2565 let reused_subtree = self.next_frame.dispatch_tree.reuse_subtree(
2566 range.start.dispatch_tree_index..range.end.dispatch_tree_index,
2567 &mut self.rendered_frame.dispatch_tree,
2568 self.focus,
2569 );
2570
2571 if reused_subtree.contains_focus() {
2572 self.next_frame.focus = self.focus;
2573 }
2574
2575 self.next_frame.deferred_draws.extend(
2576 self.rendered_frame.deferred_draws
2577 [range.start.deferred_draws_index..range.end.deferred_draws_index]
2578 .iter()
2579 .map(|deferred_draw| DeferredDraw {
2580 current_view: deferred_draw.current_view,
2581 parent_node: reused_subtree.refresh_node_id(deferred_draw.parent_node),
2582 element_id_stack: deferred_draw.element_id_stack.clone(),
2583 text_style_stack: deferred_draw.text_style_stack.clone(),
2584 content_mask: deferred_draw.content_mask.clone(),
2585 rem_size: deferred_draw.rem_size,
2586 priority: deferred_draw.priority,
2587 element: None,
2588 absolute_offset: deferred_draw.absolute_offset,
2589 prepaint_range: deferred_draw.prepaint_range.clone(),
2590 paint_range: deferred_draw.paint_range.clone(),
2591 }),
2592 );
2593 }
2594
2595 pub(crate) fn paint_index(&self) -> PaintIndex {
2596 PaintIndex {
2597 scene_index: self.next_frame.scene.len(),
2598 mouse_listeners_index: self.next_frame.mouse_listeners.len(),
2599 input_handlers_index: self.next_frame.input_handlers.len(),
2600 cursor_styles_index: self.next_frame.cursor_styles.len(),
2601 accessed_element_states_index: self.next_frame.accessed_element_states.len(),
2602 tab_handle_index: self.next_frame.tab_stops.paint_index(),
2603 line_layout_index: self.text_system.layout_index(),
2604 }
2605 }
2606
2607 pub(crate) fn reuse_paint(&mut self, range: Range<PaintIndex>) {
2608 self.next_frame.cursor_styles.extend(
2609 self.rendered_frame.cursor_styles
2610 [range.start.cursor_styles_index..range.end.cursor_styles_index]
2611 .iter()
2612 .cloned(),
2613 );
2614 self.next_frame.input_handlers.extend(
2615 self.rendered_frame.input_handlers
2616 [range.start.input_handlers_index..range.end.input_handlers_index]
2617 .iter_mut()
2618 .map(|handler| handler.take()),
2619 );
2620 self.next_frame.mouse_listeners.extend(
2621 self.rendered_frame.mouse_listeners
2622 [range.start.mouse_listeners_index..range.end.mouse_listeners_index]
2623 .iter_mut()
2624 .map(|listener| listener.take()),
2625 );
2626 self.next_frame.accessed_element_states.extend(
2627 self.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
2628 ..range.end.accessed_element_states_index]
2629 .iter()
2630 .map(|(id, type_id)| (id.clone(), *type_id)),
2631 );
2632 self.next_frame.tab_stops.replay(
2633 &self.rendered_frame.tab_stops.insertion_history
2634 [range.start.tab_handle_index..range.end.tab_handle_index],
2635 );
2636
2637 self.text_system
2638 .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
2639 self.next_frame.scene.replay(
2640 range.start.scene_index..range.end.scene_index,
2641 &self.rendered_frame.scene,
2642 );
2643 }
2644
2645 /// Push a text style onto the stack, and call a function with that style active.
2646 /// Use [`Window::text_style`] to get the current, combined text style. This method
2647 /// should only be called as part of element drawing.
2648 // This function is called in a highly recursive manner in editor
2649 // prepainting, make sure its inlined to reduce the stack burden
2650 #[inline]
2651 pub fn with_text_style<F, R>(&mut self, style: Option<TextStyleRefinement>, f: F) -> R
2652 where
2653 F: FnOnce(&mut Self) -> R,
2654 {
2655 self.invalidator.debug_assert_paint_or_prepaint();
2656 if let Some(style) = style {
2657 self.text_style_stack.push(style);
2658 let result = f(self);
2659 self.text_style_stack.pop();
2660 result
2661 } else {
2662 f(self)
2663 }
2664 }
2665
2666 /// Updates the cursor style at the platform level. This method should only be called
2667 /// during the paint phase of element drawing.
2668 pub fn set_cursor_style(&mut self, style: CursorStyle, hitbox: &Hitbox) {
2669 self.invalidator.debug_assert_paint();
2670 self.next_frame.cursor_styles.push(CursorStyleRequest {
2671 hitbox_id: Some(hitbox.id),
2672 style,
2673 });
2674 }
2675
2676 /// Updates the cursor style for the entire window at the platform level. A cursor
2677 /// style using this method will have precedence over any cursor style set using
2678 /// `set_cursor_style`. This method should only be called during the paint
2679 /// phase of element drawing.
2680 pub fn set_window_cursor_style(&mut self, style: CursorStyle) {
2681 self.invalidator.debug_assert_paint();
2682 self.next_frame.cursor_styles.push(CursorStyleRequest {
2683 hitbox_id: None,
2684 style,
2685 })
2686 }
2687
2688 /// Sets a tooltip to be rendered for the upcoming frame. This method should only be called
2689 /// during the paint phase of element drawing.
2690 pub fn set_tooltip(&mut self, tooltip: AnyTooltip) -> TooltipId {
2691 self.invalidator.debug_assert_prepaint();
2692 let id = TooltipId(post_inc(&mut self.next_tooltip_id.0));
2693 self.next_frame
2694 .tooltip_requests
2695 .push(Some(TooltipRequest { id, tooltip }));
2696 id
2697 }
2698
2699 /// Invoke the given function with the given content mask after intersecting it
2700 /// with the current mask. This method should only be called during element drawing.
2701 // This function is called in a highly recursive manner in editor
2702 // prepainting, make sure its inlined to reduce the stack burden
2703 #[inline]
2704 pub fn with_content_mask<R>(
2705 &mut self,
2706 mask: Option<ContentMask<Pixels>>,
2707 f: impl FnOnce(&mut Self) -> R,
2708 ) -> R {
2709 self.invalidator.debug_assert_paint_or_prepaint();
2710 if let Some(mask) = mask {
2711 let mask = mask.intersect(&self.content_mask());
2712 self.content_mask_stack.push(mask);
2713 let result = f(self);
2714 self.content_mask_stack.pop();
2715 result
2716 } else {
2717 f(self)
2718 }
2719 }
2720
2721 /// Updates the global element offset relative to the current offset. This is used to implement
2722 /// scrolling. This method should only be called during the prepaint phase of element drawing.
2723 pub fn with_element_offset<R>(
2724 &mut self,
2725 offset: Point<Pixels>,
2726 f: impl FnOnce(&mut Self) -> R,
2727 ) -> R {
2728 self.invalidator.debug_assert_prepaint();
2729
2730 if offset.is_zero() {
2731 return f(self);
2732 };
2733
2734 let abs_offset = self.element_offset() + offset;
2735 self.with_absolute_element_offset(abs_offset, f)
2736 }
2737
2738 /// Updates the global element offset based on the given offset. This is used to implement
2739 /// drag handles and other manual painting of elements. This method should only be called during
2740 /// the prepaint phase of element drawing.
2741 pub fn with_absolute_element_offset<R>(
2742 &mut self,
2743 offset: Point<Pixels>,
2744 f: impl FnOnce(&mut Self) -> R,
2745 ) -> R {
2746 self.invalidator.debug_assert_prepaint();
2747 self.element_offset_stack.push(offset);
2748 let result = f(self);
2749 self.element_offset_stack.pop();
2750 result
2751 }
2752
2753 pub(crate) fn with_element_opacity<R>(
2754 &mut self,
2755 opacity: Option<f32>,
2756 f: impl FnOnce(&mut Self) -> R,
2757 ) -> R {
2758 self.invalidator.debug_assert_paint_or_prepaint();
2759
2760 let Some(opacity) = opacity else {
2761 return f(self);
2762 };
2763
2764 let previous_opacity = self.element_opacity;
2765 self.element_opacity = previous_opacity * opacity;
2766 let result = f(self);
2767 self.element_opacity = previous_opacity;
2768 result
2769 }
2770
2771 /// Perform prepaint on child elements in a "retryable" manner, so that any side effects
2772 /// of prepaints can be discarded before prepainting again. This is used to support autoscroll
2773 /// where we need to prepaint children to detect the autoscroll bounds, then adjust the
2774 /// element offset and prepaint again. See [`crate::List`] for an example. This method should only be
2775 /// called during the prepaint phase of element drawing.
2776 pub fn transact<T, U>(&mut self, f: impl FnOnce(&mut Self) -> Result<T, U>) -> Result<T, U> {
2777 self.invalidator.debug_assert_prepaint();
2778 let index = self.prepaint_index();
2779 let result = f(self);
2780 if result.is_err() {
2781 self.next_frame.hitboxes.truncate(index.hitboxes_index);
2782 self.next_frame
2783 .tooltip_requests
2784 .truncate(index.tooltips_index);
2785 self.next_frame
2786 .deferred_draws
2787 .truncate(index.deferred_draws_index);
2788 self.next_frame
2789 .dispatch_tree
2790 .truncate(index.dispatch_tree_index);
2791 self.next_frame
2792 .accessed_element_states
2793 .truncate(index.accessed_element_states_index);
2794 self.text_system.truncate_layouts(index.line_layout_index);
2795 }
2796 result
2797 }
2798
2799 /// When you call this method during [`Element::prepaint`], containing elements will attempt to
2800 /// scroll to cause the specified bounds to become visible. When they decide to autoscroll, they will call
2801 /// [`Element::prepaint`] again with a new set of bounds. See [`crate::List`] for an example of an element
2802 /// that supports this method being called on the elements it contains. This method should only be
2803 /// called during the prepaint phase of element drawing.
2804 pub fn request_autoscroll(&mut self, bounds: Bounds<Pixels>) {
2805 self.invalidator.debug_assert_prepaint();
2806 self.requested_autoscroll = Some(bounds);
2807 }
2808
2809 /// This method can be called from a containing element such as [`crate::List`] to support the autoscroll behavior
2810 /// described in [`Self::request_autoscroll`].
2811 pub fn take_autoscroll(&mut self) -> Option<Bounds<Pixels>> {
2812 self.invalidator.debug_assert_prepaint();
2813 self.requested_autoscroll.take()
2814 }
2815
2816 /// Asynchronously load an asset, if the asset hasn't finished loading this will return None.
2817 /// Your view will be re-drawn once the asset has finished loading.
2818 ///
2819 /// Note that the multiple calls to this method will only result in one `Asset::load` call at a
2820 /// time.
2821 pub fn use_asset<A: Asset>(&mut self, source: &A::Source, cx: &mut App) -> Option<A::Output> {
2822 let (task, is_first) = cx.fetch_asset::<A>(source);
2823 task.clone().now_or_never().or_else(|| {
2824 if is_first {
2825 let entity_id = self.current_view();
2826 self.spawn(cx, {
2827 let task = task.clone();
2828 async move |cx| {
2829 task.await;
2830
2831 cx.on_next_frame(move |_, cx| {
2832 cx.notify(entity_id);
2833 });
2834 }
2835 })
2836 .detach();
2837 }
2838
2839 None
2840 })
2841 }
2842
2843 /// Asynchronously load an asset, if the asset hasn't finished loading or doesn't exist this will return None.
2844 /// Your view will not be re-drawn once the asset has finished loading.
2845 ///
2846 /// Note that the multiple calls to this method will only result in one `Asset::load` call at a
2847 /// time.
2848 pub fn get_asset<A: Asset>(&mut self, source: &A::Source, cx: &mut App) -> Option<A::Output> {
2849 let (task, _) = cx.fetch_asset::<A>(source);
2850 task.now_or_never()
2851 }
2852 /// Obtain the current element offset. This method should only be called during the
2853 /// prepaint phase of element drawing.
2854 pub fn element_offset(&self) -> Point<Pixels> {
2855 self.invalidator.debug_assert_prepaint();
2856 self.element_offset_stack
2857 .last()
2858 .copied()
2859 .unwrap_or_default()
2860 }
2861
2862 /// Obtain the current element opacity. This method should only be called during the
2863 /// prepaint phase of element drawing.
2864 #[inline]
2865 pub(crate) fn element_opacity(&self) -> f32 {
2866 self.invalidator.debug_assert_paint_or_prepaint();
2867 self.element_opacity
2868 }
2869
2870 /// Obtain the current content mask. This method should only be called during element drawing.
2871 pub fn content_mask(&self) -> ContentMask<Pixels> {
2872 self.invalidator.debug_assert_paint_or_prepaint();
2873 self.content_mask_stack
2874 .last()
2875 .cloned()
2876 .unwrap_or_else(|| ContentMask {
2877 bounds: Bounds {
2878 origin: Point::default(),
2879 size: self.viewport_size,
2880 },
2881 })
2882 }
2883
2884 /// Provide elements in the called function with a new namespace in which their identifiers must be unique.
2885 /// This can be used within a custom element to distinguish multiple sets of child elements.
2886 pub fn with_element_namespace<R>(
2887 &mut self,
2888 element_id: impl Into<ElementId>,
2889 f: impl FnOnce(&mut Self) -> R,
2890 ) -> R {
2891 self.element_id_stack.push(element_id.into());
2892 let result = f(self);
2893 self.element_id_stack.pop();
2894 result
2895 }
2896
2897 /// Use a piece of state that exists as long this element is being rendered in consecutive frames.
2898 pub fn use_keyed_state<S: 'static>(
2899 &mut self,
2900 key: impl Into<ElementId>,
2901 cx: &mut App,
2902 init: impl FnOnce(&mut Self, &mut Context<S>) -> S,
2903 ) -> Entity<S> {
2904 let current_view = self.current_view();
2905 self.with_global_id(key.into(), |global_id, window| {
2906 window.with_element_state(global_id, |state: Option<Entity<S>>, window| {
2907 if let Some(state) = state {
2908 (state.clone(), state)
2909 } else {
2910 let new_state = cx.new(|cx| init(window, cx));
2911 cx.observe(&new_state, move |_, cx| {
2912 cx.notify(current_view);
2913 })
2914 .detach();
2915 (new_state.clone(), new_state)
2916 }
2917 })
2918 })
2919 }
2920
2921 /// Use a piece of state that exists as long this element is being rendered in consecutive frames, without needing to specify a key
2922 ///
2923 /// NOTE: This method uses the location of the caller to generate an ID for this state.
2924 /// If this is not sufficient to identify your state (e.g. you're rendering a list item),
2925 /// you can provide a custom ElementID using the `use_keyed_state` method.
2926 #[track_caller]
2927 pub fn use_state<S: 'static>(
2928 &mut self,
2929 cx: &mut App,
2930 init: impl FnOnce(&mut Self, &mut Context<S>) -> S,
2931 ) -> Entity<S> {
2932 self.use_keyed_state(
2933 ElementId::CodeLocation(*core::panic::Location::caller()),
2934 cx,
2935 init,
2936 )
2937 }
2938
2939 /// Updates or initializes state for an element with the given id that lives across multiple
2940 /// frames. If an element with this ID existed in the rendered frame, its state will be passed
2941 /// to the given closure. The state returned by the closure will be stored so it can be referenced
2942 /// when drawing the next frame. This method should only be called as part of element drawing.
2943 pub fn with_element_state<S, R>(
2944 &mut self,
2945 global_id: &GlobalElementId,
2946 f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
2947 ) -> R
2948 where
2949 S: 'static,
2950 {
2951 self.invalidator.debug_assert_paint_or_prepaint();
2952
2953 let key = (global_id.clone(), TypeId::of::<S>());
2954 self.next_frame.accessed_element_states.push(key.clone());
2955
2956 if let Some(any) = self
2957 .next_frame
2958 .element_states
2959 .remove(&key)
2960 .or_else(|| self.rendered_frame.element_states.remove(&key))
2961 {
2962 let ElementStateBox {
2963 inner,
2964 #[cfg(debug_assertions)]
2965 type_name,
2966 } = any;
2967 // Using the extra inner option to avoid needing to reallocate a new box.
2968 let mut state_box = inner
2969 .downcast::<Option<S>>()
2970 .map_err(|_| {
2971 #[cfg(debug_assertions)]
2972 {
2973 anyhow::anyhow!(
2974 "invalid element state type for id, requested {:?}, actual: {:?}",
2975 std::any::type_name::<S>(),
2976 type_name
2977 )
2978 }
2979
2980 #[cfg(not(debug_assertions))]
2981 {
2982 anyhow::anyhow!(
2983 "invalid element state type for id, requested {:?}",
2984 std::any::type_name::<S>(),
2985 )
2986 }
2987 })
2988 .unwrap();
2989
2990 let state = state_box.take().expect(
2991 "reentrant call to with_element_state for the same state type and element id",
2992 );
2993 let (result, state) = f(Some(state), self);
2994 state_box.replace(state);
2995 self.next_frame.element_states.insert(
2996 key,
2997 ElementStateBox {
2998 inner: state_box,
2999 #[cfg(debug_assertions)]
3000 type_name,
3001 },
3002 );
3003 result
3004 } else {
3005 let (result, state) = f(None, self);
3006 self.next_frame.element_states.insert(
3007 key,
3008 ElementStateBox {
3009 inner: Box::new(Some(state)),
3010 #[cfg(debug_assertions)]
3011 type_name: std::any::type_name::<S>(),
3012 },
3013 );
3014 result
3015 }
3016 }
3017
3018 /// A variant of `with_element_state` that allows the element's id to be optional. This is a convenience
3019 /// method for elements where the element id may or may not be assigned. Prefer using `with_element_state`
3020 /// when the element is guaranteed to have an id.
3021 ///
3022 /// The first option means 'no ID provided'
3023 /// The second option means 'not yet initialized'
3024 pub fn with_optional_element_state<S, R>(
3025 &mut self,
3026 global_id: Option<&GlobalElementId>,
3027 f: impl FnOnce(Option<Option<S>>, &mut Self) -> (R, Option<S>),
3028 ) -> R
3029 where
3030 S: 'static,
3031 {
3032 self.invalidator.debug_assert_paint_or_prepaint();
3033
3034 if let Some(global_id) = global_id {
3035 self.with_element_state(global_id, |state, cx| {
3036 let (result, state) = f(Some(state), cx);
3037 let state =
3038 state.expect("you must return some state when you pass some element id");
3039 (result, state)
3040 })
3041 } else {
3042 let (result, state) = f(None, self);
3043 debug_assert!(
3044 state.is_none(),
3045 "you must not return an element state when passing None for the global id"
3046 );
3047 result
3048 }
3049 }
3050
3051 /// Executes the given closure within the context of a tab group.
3052 #[inline]
3053 pub fn with_tab_group<R>(&mut self, index: Option<isize>, f: impl FnOnce(&mut Self) -> R) -> R {
3054 if let Some(index) = index {
3055 self.next_frame.tab_stops.begin_group(index);
3056 let result = f(self);
3057 self.next_frame.tab_stops.end_group();
3058 result
3059 } else {
3060 f(self)
3061 }
3062 }
3063
3064 /// Defers the drawing of the given element, scheduling it to be painted on top of the currently-drawn tree
3065 /// at a later time. The `priority` parameter determines the drawing order relative to other deferred elements,
3066 /// with higher values being drawn on top.
3067 ///
3068 /// When `content_mask` is provided, the deferred element will be clipped to that region during
3069 /// both prepaint and paint. When `None`, no additional clipping is applied.
3070 ///
3071 /// This method should only be called as part of the prepaint phase of element drawing.
3072 pub fn defer_draw(
3073 &mut self,
3074 element: AnyElement,
3075 absolute_offset: Point<Pixels>,
3076 priority: usize,
3077 content_mask: Option<ContentMask<Pixels>>,
3078 ) {
3079 self.invalidator.debug_assert_prepaint();
3080 let parent_node = self.next_frame.dispatch_tree.active_node_id().unwrap();
3081 self.next_frame.deferred_draws.push(DeferredDraw {
3082 current_view: self.current_view(),
3083 parent_node,
3084 element_id_stack: self.element_id_stack.clone(),
3085 text_style_stack: self.text_style_stack.clone(),
3086 content_mask,
3087 rem_size: self.rem_size(),
3088 priority,
3089 element: Some(element),
3090 absolute_offset,
3091 prepaint_range: PrepaintStateIndex::default()..PrepaintStateIndex::default(),
3092 paint_range: PaintIndex::default()..PaintIndex::default(),
3093 });
3094 }
3095
3096 /// Creates a new painting layer for the specified bounds. A "layer" is a batch
3097 /// of geometry that are non-overlapping and have the same draw order. This is typically used
3098 /// for performance reasons.
3099 ///
3100 /// This method should only be called as part of the paint phase of element drawing.
3101 pub fn paint_layer<R>(&mut self, bounds: Bounds<Pixels>, f: impl FnOnce(&mut Self) -> R) -> R {
3102 self.invalidator.debug_assert_paint();
3103
3104 let scale_factor = self.scale_factor();
3105 let content_mask = self.content_mask();
3106 let clipped_bounds = bounds.intersect(&content_mask.bounds);
3107 if !clipped_bounds.is_empty() {
3108 self.next_frame
3109 .scene
3110 .push_layer(clipped_bounds.scale(scale_factor));
3111 }
3112
3113 let result = f(self);
3114
3115 if !clipped_bounds.is_empty() {
3116 self.next_frame.scene.pop_layer();
3117 }
3118
3119 result
3120 }
3121
3122 /// Paint one or more drop shadows into the scene for the next frame at the current z-index.
3123 ///
3124 /// This method should only be called as part of the paint phase of element drawing.
3125 pub fn paint_shadows(
3126 &mut self,
3127 bounds: Bounds<Pixels>,
3128 corner_radii: Corners<Pixels>,
3129 shadows: &[BoxShadow],
3130 ) {
3131 self.invalidator.debug_assert_paint();
3132
3133 let scale_factor = self.scale_factor();
3134 let content_mask = self.content_mask();
3135 let opacity = self.element_opacity();
3136 for shadow in shadows {
3137 let shadow_bounds = (bounds + shadow.offset).dilate(shadow.spread_radius);
3138 self.next_frame.scene.insert_primitive(Shadow {
3139 order: 0,
3140 blur_radius: shadow.blur_radius.scale(scale_factor),
3141 bounds: shadow_bounds.scale(scale_factor),
3142 content_mask: content_mask.scale(scale_factor),
3143 corner_radii: corner_radii.scale(scale_factor),
3144 color: shadow.color.opacity(opacity),
3145 });
3146 }
3147 }
3148
3149 /// Paint one or more quads into the scene for the next frame at the current stacking context.
3150 /// Quads are colored rectangular regions with an optional background, border, and corner radius.
3151 /// see [`fill`], [`outline`], and [`quad`] to construct this type.
3152 ///
3153 /// This method should only be called as part of the paint phase of element drawing.
3154 ///
3155 /// Note that the `quad.corner_radii` are allowed to exceed the bounds, creating sharp corners
3156 /// where the circular arcs meet. This will not display well when combined with dashed borders.
3157 /// Use `Corners::clamp_radii_for_quad_size` if the radii should fit within the bounds.
3158 pub fn paint_quad(&mut self, quad: PaintQuad) {
3159 self.invalidator.debug_assert_paint();
3160
3161 let scale_factor = self.scale_factor();
3162 let content_mask = self.content_mask();
3163 let opacity = self.element_opacity();
3164 self.next_frame.scene.insert_primitive(Quad {
3165 order: 0,
3166 bounds: quad.bounds.scale(scale_factor),
3167 content_mask: content_mask.scale(scale_factor),
3168 background: quad.background.opacity(opacity),
3169 border_color: quad.border_color.opacity(opacity),
3170 corner_radii: quad.corner_radii.scale(scale_factor),
3171 border_widths: quad.border_widths.scale(scale_factor),
3172 border_style: quad.border_style,
3173 });
3174 }
3175
3176 /// Paint the given `Path` into the scene for the next frame at the current z-index.
3177 ///
3178 /// This method should only be called as part of the paint phase of element drawing.
3179 pub fn paint_path(&mut self, mut path: Path<Pixels>, color: impl Into<Background>) {
3180 self.invalidator.debug_assert_paint();
3181
3182 let scale_factor = self.scale_factor();
3183 let content_mask = self.content_mask();
3184 let opacity = self.element_opacity();
3185 path.content_mask = content_mask;
3186 let color: Background = color.into();
3187 path.color = color.opacity(opacity);
3188 self.next_frame
3189 .scene
3190 .insert_primitive(path.scale(scale_factor));
3191 }
3192
3193 /// Paint an underline into the scene for the next frame at the current z-index.
3194 ///
3195 /// This method should only be called as part of the paint phase of element drawing.
3196 pub fn paint_underline(
3197 &mut self,
3198 origin: Point<Pixels>,
3199 width: Pixels,
3200 style: &UnderlineStyle,
3201 ) {
3202 self.invalidator.debug_assert_paint();
3203
3204 let scale_factor = self.scale_factor();
3205 let height = if style.wavy {
3206 style.thickness * 3.
3207 } else {
3208 style.thickness
3209 };
3210 let bounds = Bounds {
3211 origin,
3212 size: size(width, height),
3213 };
3214 let content_mask = self.content_mask();
3215 let element_opacity = self.element_opacity();
3216
3217 self.next_frame.scene.insert_primitive(Underline {
3218 order: 0,
3219 pad: 0,
3220 bounds: bounds.scale(scale_factor),
3221 content_mask: content_mask.scale(scale_factor),
3222 color: style.color.unwrap_or_default().opacity(element_opacity),
3223 thickness: style.thickness.scale(scale_factor),
3224 wavy: if style.wavy { 1 } else { 0 },
3225 });
3226 }
3227
3228 /// Paint a strikethrough into the scene for the next frame at the current z-index.
3229 ///
3230 /// This method should only be called as part of the paint phase of element drawing.
3231 pub fn paint_strikethrough(
3232 &mut self,
3233 origin: Point<Pixels>,
3234 width: Pixels,
3235 style: &StrikethroughStyle,
3236 ) {
3237 self.invalidator.debug_assert_paint();
3238
3239 let scale_factor = self.scale_factor();
3240 let height = style.thickness;
3241 let bounds = Bounds {
3242 origin,
3243 size: size(width, height),
3244 };
3245 let content_mask = self.content_mask();
3246 let opacity = self.element_opacity();
3247
3248 self.next_frame.scene.insert_primitive(Underline {
3249 order: 0,
3250 pad: 0,
3251 bounds: bounds.scale(scale_factor),
3252 content_mask: content_mask.scale(scale_factor),
3253 thickness: style.thickness.scale(scale_factor),
3254 color: style.color.unwrap_or_default().opacity(opacity),
3255 wavy: 0,
3256 });
3257 }
3258
3259 /// Paints a monochrome (non-emoji) glyph into the scene for the next frame at the current z-index.
3260 ///
3261 /// The y component of the origin is the baseline of the glyph.
3262 /// You should generally prefer to use the [`ShapedLine::paint`](crate::ShapedLine::paint) or
3263 /// [`WrappedLine::paint`](crate::WrappedLine::paint) methods in the [`TextSystem`](crate::TextSystem).
3264 /// This method is only useful if you need to paint a single glyph that has already been shaped.
3265 ///
3266 /// This method should only be called as part of the paint phase of element drawing.
3267 pub fn paint_glyph(
3268 &mut self,
3269 origin: Point<Pixels>,
3270 font_id: FontId,
3271 glyph_id: GlyphId,
3272 font_size: Pixels,
3273 color: Hsla,
3274 ) -> Result<()> {
3275 self.invalidator.debug_assert_paint();
3276
3277 let element_opacity = self.element_opacity();
3278 let scale_factor = self.scale_factor();
3279 let glyph_origin = origin.scale(scale_factor);
3280
3281 let subpixel_variant = Point {
3282 x: (glyph_origin.x.0.fract() * SUBPIXEL_VARIANTS_X as f32).floor() as u8,
3283 y: (glyph_origin.y.0.fract() * SUBPIXEL_VARIANTS_Y as f32).floor() as u8,
3284 };
3285 let subpixel_rendering = self.should_use_subpixel_rendering(font_id, font_size);
3286 let params = RenderGlyphParams {
3287 font_id,
3288 glyph_id,
3289 font_size,
3290 subpixel_variant,
3291 scale_factor,
3292 is_emoji: false,
3293 subpixel_rendering,
3294 };
3295
3296 let raster_bounds = self.text_system().raster_bounds(¶ms)?;
3297 if !raster_bounds.is_zero() {
3298 let tile = self
3299 .sprite_atlas
3300 .get_or_insert_with(¶ms.clone().into(), &mut || {
3301 let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?;
3302 Ok(Some((size, Cow::Owned(bytes))))
3303 })?
3304 .expect("Callback above only errors or returns Some");
3305 let bounds = Bounds {
3306 origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
3307 size: tile.bounds.size.map(Into::into),
3308 };
3309 let content_mask = self.content_mask().scale(scale_factor);
3310
3311 if subpixel_rendering {
3312 self.next_frame.scene.insert_primitive(SubpixelSprite {
3313 order: 0,
3314 pad: 0,
3315 bounds,
3316 content_mask,
3317 color: color.opacity(element_opacity),
3318 tile,
3319 transformation: TransformationMatrix::unit(),
3320 });
3321 } else {
3322 self.next_frame.scene.insert_primitive(MonochromeSprite {
3323 order: 0,
3324 pad: 0,
3325 bounds,
3326 content_mask,
3327 color: color.opacity(element_opacity),
3328 tile,
3329 transformation: TransformationMatrix::unit(),
3330 });
3331 }
3332 }
3333 Ok(())
3334 }
3335
3336 /// Paints a monochrome glyph with pre-computed raster bounds.
3337 ///
3338 /// This is faster than `paint_glyph` because it skips the per-glyph cache lookup.
3339 /// Use `ShapedLine::compute_glyph_raster_data` to batch-compute raster bounds during prepaint.
3340 pub fn paint_glyph_with_raster_bounds(
3341 &mut self,
3342 origin: Point<Pixels>,
3343 _font_id: FontId,
3344 _glyph_id: GlyphId,
3345 _font_size: Pixels,
3346 color: Hsla,
3347 raster_bounds: Bounds<DevicePixels>,
3348 params: &RenderGlyphParams,
3349 ) -> Result<()> {
3350 self.invalidator.debug_assert_paint();
3351
3352 let element_opacity = self.element_opacity();
3353 let scale_factor = self.scale_factor();
3354 let glyph_origin = origin.scale(scale_factor);
3355
3356 if !raster_bounds.is_zero() {
3357 let tile = self
3358 .sprite_atlas
3359 .get_or_insert_with(¶ms.clone().into(), &mut || {
3360 let (size, bytes) = self.text_system().rasterize_glyph(params)?;
3361 Ok(Some((size, Cow::Owned(bytes))))
3362 })?
3363 .expect("Callback above only errors or returns Some");
3364 let bounds = Bounds {
3365 origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
3366 size: tile.bounds.size.map(Into::into),
3367 };
3368 let content_mask = self.content_mask().scale(scale_factor);
3369 self.next_frame.scene.insert_primitive(MonochromeSprite {
3370 order: 0,
3371 pad: 0,
3372 bounds,
3373 content_mask,
3374 color: color.opacity(element_opacity),
3375 tile,
3376 transformation: TransformationMatrix::unit(),
3377 });
3378 }
3379 Ok(())
3380 }
3381
3382 /// Paints an emoji glyph with pre-computed raster bounds.
3383 ///
3384 /// This is faster than `paint_emoji` because it skips the per-glyph cache lookup.
3385 /// Use `ShapedLine::compute_glyph_raster_data` to batch-compute raster bounds during prepaint.
3386 pub fn paint_emoji_with_raster_bounds(
3387 &mut self,
3388 origin: Point<Pixels>,
3389 _font_id: FontId,
3390 _glyph_id: GlyphId,
3391 _font_size: Pixels,
3392 raster_bounds: Bounds<DevicePixels>,
3393 params: &RenderGlyphParams,
3394 ) -> Result<()> {
3395 self.invalidator.debug_assert_paint();
3396
3397 let scale_factor = self.scale_factor();
3398 let glyph_origin = origin.scale(scale_factor);
3399
3400 if !raster_bounds.is_zero() {
3401 let tile = self
3402 .sprite_atlas
3403 .get_or_insert_with(¶ms.clone().into(), &mut || {
3404 let (size, bytes) = self.text_system().rasterize_glyph(params)?;
3405 Ok(Some((size, Cow::Owned(bytes))))
3406 })?
3407 .expect("Callback above only errors or returns Some");
3408
3409 let bounds = Bounds {
3410 origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
3411 size: tile.bounds.size.map(Into::into),
3412 };
3413 let content_mask = self.content_mask().scale(scale_factor);
3414 let opacity = self.element_opacity();
3415
3416 self.next_frame.scene.insert_primitive(PolychromeSprite {
3417 order: 0,
3418 pad: 0,
3419 grayscale: false,
3420 bounds,
3421 corner_radii: Default::default(),
3422 content_mask,
3423 tile,
3424 opacity,
3425 });
3426 }
3427 Ok(())
3428 }
3429
3430 fn should_use_subpixel_rendering(&self, font_id: FontId, font_size: Pixels) -> bool {
3431 if self.platform_window.background_appearance() != WindowBackgroundAppearance::Opaque {
3432 return false;
3433 }
3434
3435 if !self.platform_window.is_subpixel_rendering_supported() {
3436 return false;
3437 }
3438
3439 let mode = match self.text_rendering_mode.get() {
3440 TextRenderingMode::PlatformDefault => self
3441 .text_system()
3442 .recommended_rendering_mode(font_id, font_size),
3443 mode => mode,
3444 };
3445
3446 mode == TextRenderingMode::Subpixel
3447 }
3448
3449 /// Paints an emoji glyph into the scene for the next frame at the current z-index.
3450 ///
3451 /// The y component of the origin is the baseline of the glyph.
3452 /// You should generally prefer to use the [`ShapedLine::paint`](crate::ShapedLine::paint) or
3453 /// [`WrappedLine::paint`](crate::WrappedLine::paint) methods in the [`TextSystem`](crate::TextSystem).
3454 /// This method is only useful if you need to paint a single emoji that has already been shaped.
3455 ///
3456 /// This method should only be called as part of the paint phase of element drawing.
3457 pub fn paint_emoji(
3458 &mut self,
3459 origin: Point<Pixels>,
3460 font_id: FontId,
3461 glyph_id: GlyphId,
3462 font_size: Pixels,
3463 ) -> Result<()> {
3464 self.invalidator.debug_assert_paint();
3465
3466 let scale_factor = self.scale_factor();
3467 let glyph_origin = origin.scale(scale_factor);
3468 let params = RenderGlyphParams {
3469 font_id,
3470 glyph_id,
3471 font_size,
3472 // We don't render emojis with subpixel variants.
3473 subpixel_variant: Default::default(),
3474 scale_factor,
3475 is_emoji: true,
3476 subpixel_rendering: false,
3477 };
3478
3479 let raster_bounds = self.text_system().raster_bounds(¶ms)?;
3480 if !raster_bounds.is_zero() {
3481 let tile = self
3482 .sprite_atlas
3483 .get_or_insert_with(¶ms.clone().into(), &mut || {
3484 let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?;
3485 Ok(Some((size, Cow::Owned(bytes))))
3486 })?
3487 .expect("Callback above only errors or returns Some");
3488
3489 let bounds = Bounds {
3490 origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
3491 size: tile.bounds.size.map(Into::into),
3492 };
3493 let content_mask = self.content_mask().scale(scale_factor);
3494 let opacity = self.element_opacity();
3495
3496 self.next_frame.scene.insert_primitive(PolychromeSprite {
3497 order: 0,
3498 pad: 0,
3499 grayscale: false,
3500 bounds,
3501 corner_radii: Default::default(),
3502 content_mask,
3503 tile,
3504 opacity,
3505 });
3506 }
3507 Ok(())
3508 }
3509
3510 /// Paint a monochrome SVG into the scene for the next frame at the current stacking context.
3511 ///
3512 /// This method should only be called as part of the paint phase of element drawing.
3513 pub fn paint_svg(
3514 &mut self,
3515 bounds: Bounds<Pixels>,
3516 path: SharedString,
3517 mut data: Option<&[u8]>,
3518 transformation: TransformationMatrix,
3519 color: Hsla,
3520 cx: &App,
3521 ) -> Result<()> {
3522 self.invalidator.debug_assert_paint();
3523
3524 let element_opacity = self.element_opacity();
3525 let scale_factor = self.scale_factor();
3526
3527 let bounds = bounds.scale(scale_factor);
3528 let params = RenderSvgParams {
3529 path,
3530 size: bounds.size.map(|pixels| {
3531 DevicePixels::from((pixels.0 * SMOOTH_SVG_SCALE_FACTOR).ceil() as i32)
3532 }),
3533 };
3534
3535 let Some(tile) =
3536 self.sprite_atlas
3537 .get_or_insert_with(¶ms.clone().into(), &mut || {
3538 let Some((size, bytes)) = cx.svg_renderer.render_alpha_mask(¶ms, data)?
3539 else {
3540 return Ok(None);
3541 };
3542 Ok(Some((size, Cow::Owned(bytes))))
3543 })?
3544 else {
3545 return Ok(());
3546 };
3547 let content_mask = self.content_mask().scale(scale_factor);
3548 let svg_bounds = Bounds {
3549 origin: bounds.center()
3550 - Point::new(
3551 ScaledPixels(tile.bounds.size.width.0 as f32 / SMOOTH_SVG_SCALE_FACTOR / 2.),
3552 ScaledPixels(tile.bounds.size.height.0 as f32 / SMOOTH_SVG_SCALE_FACTOR / 2.),
3553 ),
3554 size: tile
3555 .bounds
3556 .size
3557 .map(|value| ScaledPixels(value.0 as f32 / SMOOTH_SVG_SCALE_FACTOR)),
3558 };
3559
3560 self.next_frame.scene.insert_primitive(MonochromeSprite {
3561 order: 0,
3562 pad: 0,
3563 bounds: svg_bounds
3564 .map_origin(|origin| origin.round())
3565 .map_size(|size| size.ceil()),
3566 content_mask,
3567 color: color.opacity(element_opacity),
3568 tile,
3569 transformation,
3570 });
3571
3572 Ok(())
3573 }
3574
3575 /// Paint an image into the scene for the next frame at the current z-index.
3576 /// This method will panic if the frame_index is not valid
3577 ///
3578 /// This method should only be called as part of the paint phase of element drawing.
3579 pub fn paint_image(
3580 &mut self,
3581 bounds: Bounds<Pixels>,
3582 corner_radii: Corners<Pixels>,
3583 data: Arc<RenderImage>,
3584 frame_index: usize,
3585 grayscale: bool,
3586 ) -> Result<()> {
3587 self.invalidator.debug_assert_paint();
3588
3589 let scale_factor = self.scale_factor();
3590 let bounds = bounds.scale(scale_factor);
3591 let params = RenderImageParams {
3592 image_id: data.id,
3593 frame_index,
3594 };
3595
3596 let tile = self
3597 .sprite_atlas
3598 .get_or_insert_with(¶ms.into(), &mut || {
3599 Ok(Some((
3600 data.size(frame_index),
3601 Cow::Borrowed(
3602 data.as_bytes(frame_index)
3603 .expect("It's the caller's job to pass a valid frame index"),
3604 ),
3605 )))
3606 })?
3607 .expect("Callback above only returns Some");
3608 let content_mask = self.content_mask().scale(scale_factor);
3609 let corner_radii = corner_radii.scale(scale_factor);
3610 let opacity = self.element_opacity();
3611
3612 self.next_frame.scene.insert_primitive(PolychromeSprite {
3613 order: 0,
3614 pad: 0,
3615 grayscale,
3616 bounds: bounds
3617 .map_origin(|origin| origin.floor())
3618 .map_size(|size| size.ceil()),
3619 content_mask,
3620 corner_radii,
3621 tile,
3622 opacity,
3623 });
3624 Ok(())
3625 }
3626
3627 /// Paint a surface into the scene for the next frame at the current z-index.
3628 ///
3629 /// This method should only be called as part of the paint phase of element drawing.
3630 #[cfg(target_os = "macos")]
3631 pub fn paint_surface(&mut self, bounds: Bounds<Pixels>, image_buffer: CVPixelBuffer) {
3632 use crate::PaintSurface;
3633
3634 self.invalidator.debug_assert_paint();
3635
3636 let scale_factor = self.scale_factor();
3637 let bounds = bounds.scale(scale_factor);
3638 let content_mask = self.content_mask().scale(scale_factor);
3639 self.next_frame.scene.insert_primitive(PaintSurface {
3640 order: 0,
3641 bounds,
3642 content_mask,
3643 image_buffer,
3644 });
3645 }
3646
3647 /// Removes an image from the sprite atlas.
3648 pub fn drop_image(&mut self, data: Arc<RenderImage>) -> Result<()> {
3649 for frame_index in 0..data.frame_count() {
3650 let params = RenderImageParams {
3651 image_id: data.id,
3652 frame_index,
3653 };
3654
3655 self.sprite_atlas.remove(¶ms.clone().into());
3656 }
3657
3658 Ok(())
3659 }
3660
3661 /// Add a node to the layout tree for the current frame. Takes the `Style` of the element for which
3662 /// layout is being requested, along with the layout ids of any children. This method is called during
3663 /// calls to the [`Element::request_layout`] trait method and enables any element to participate in layout.
3664 ///
3665 /// This method should only be called as part of the request_layout or prepaint phase of element drawing.
3666 #[must_use]
3667 pub fn request_layout(
3668 &mut self,
3669 style: Style,
3670 children: impl IntoIterator<Item = LayoutId>,
3671 cx: &mut App,
3672 ) -> LayoutId {
3673 self.invalidator.debug_assert_prepaint();
3674
3675 cx.layout_id_buffer.clear();
3676 cx.layout_id_buffer.extend(children);
3677 let rem_size = self.rem_size();
3678 let scale_factor = self.scale_factor();
3679
3680 self.layout_engine.as_mut().unwrap().request_layout(
3681 style,
3682 rem_size,
3683 scale_factor,
3684 &cx.layout_id_buffer,
3685 )
3686 }
3687
3688 /// Add a node to the layout tree for the current frame. Instead of taking a `Style` and children,
3689 /// this variant takes a function that is invoked during layout so you can use arbitrary logic to
3690 /// determine the element's size. One place this is used internally is when measuring text.
3691 ///
3692 /// The given closure is invoked at layout time with the known dimensions and available space and
3693 /// returns a `Size`.
3694 ///
3695 /// This method should only be called as part of the request_layout or prepaint phase of element drawing.
3696 pub fn request_measured_layout<F>(&mut self, style: Style, measure: F) -> LayoutId
3697 where
3698 F: Fn(Size<Option<Pixels>>, Size<AvailableSpace>, &mut Window, &mut App) -> Size<Pixels>
3699 + 'static,
3700 {
3701 self.invalidator.debug_assert_prepaint();
3702
3703 let rem_size = self.rem_size();
3704 let scale_factor = self.scale_factor();
3705 self.layout_engine
3706 .as_mut()
3707 .unwrap()
3708 .request_measured_layout(style, rem_size, scale_factor, measure)
3709 }
3710
3711 /// Compute the layout for the given id within the given available space.
3712 /// This method is called for its side effect, typically by the framework prior to painting.
3713 /// After calling it, you can request the bounds of the given layout node id or any descendant.
3714 ///
3715 /// This method should only be called as part of the prepaint phase of element drawing.
3716 pub fn compute_layout(
3717 &mut self,
3718 layout_id: LayoutId,
3719 available_space: Size<AvailableSpace>,
3720 cx: &mut App,
3721 ) {
3722 self.invalidator.debug_assert_prepaint();
3723
3724 let mut layout_engine = self.layout_engine.take().unwrap();
3725 layout_engine.compute_layout(layout_id, available_space, self, cx);
3726 self.layout_engine = Some(layout_engine);
3727 }
3728
3729 /// Obtain the bounds computed for the given LayoutId relative to the window. This method will usually be invoked by
3730 /// GPUI itself automatically in order to pass your element its `Bounds` automatically.
3731 ///
3732 /// This method should only be called as part of element drawing.
3733 pub fn layout_bounds(&mut self, layout_id: LayoutId) -> Bounds<Pixels> {
3734 self.invalidator.debug_assert_prepaint();
3735
3736 let scale_factor = self.scale_factor();
3737 let mut bounds = self
3738 .layout_engine
3739 .as_mut()
3740 .unwrap()
3741 .layout_bounds(layout_id, scale_factor)
3742 .map(Into::into);
3743 bounds.origin += self.element_offset();
3744 bounds
3745 }
3746
3747 /// This method should be called during `prepaint`. You can use
3748 /// the returned [Hitbox] during `paint` or in an event handler
3749 /// to determine whether the inserted hitbox was the topmost.
3750 ///
3751 /// This method should only be called as part of the prepaint phase of element drawing.
3752 pub fn insert_hitbox(&mut self, bounds: Bounds<Pixels>, behavior: HitboxBehavior) -> Hitbox {
3753 self.invalidator.debug_assert_prepaint();
3754
3755 let content_mask = self.content_mask();
3756 let mut id = self.next_hitbox_id;
3757 self.next_hitbox_id = self.next_hitbox_id.next();
3758 let hitbox = Hitbox {
3759 id,
3760 bounds,
3761 content_mask,
3762 behavior,
3763 };
3764 self.next_frame.hitboxes.push(hitbox.clone());
3765 hitbox
3766 }
3767
3768 /// Set a hitbox which will act as a control area of the platform window.
3769 ///
3770 /// This method should only be called as part of the paint phase of element drawing.
3771 pub fn insert_window_control_hitbox(&mut self, area: WindowControlArea, hitbox: Hitbox) {
3772 self.invalidator.debug_assert_paint();
3773 self.next_frame.window_control_hitboxes.push((area, hitbox));
3774 }
3775
3776 /// Sets the key context for the current element. This context will be used to translate
3777 /// keybindings into actions.
3778 ///
3779 /// This method should only be called as part of the paint phase of element drawing.
3780 pub fn set_key_context(&mut self, context: KeyContext) {
3781 self.invalidator.debug_assert_paint();
3782 self.next_frame.dispatch_tree.set_key_context(context);
3783 }
3784
3785 /// Sets the focus handle for the current element. This handle will be used to manage focus state
3786 /// and keyboard event dispatch for the element.
3787 ///
3788 /// This method should only be called as part of the prepaint phase of element drawing.
3789 pub fn set_focus_handle(&mut self, focus_handle: &FocusHandle, _: &App) {
3790 self.invalidator.debug_assert_prepaint();
3791 if focus_handle.is_focused(self) {
3792 self.next_frame.focus = Some(focus_handle.id);
3793 }
3794 self.next_frame.dispatch_tree.set_focus_id(focus_handle.id);
3795 }
3796
3797 /// Sets the view id for the current element, which will be used to manage view caching.
3798 ///
3799 /// This method should only be called as part of element prepaint. We plan on removing this
3800 /// method eventually when we solve some issues that require us to construct editor elements
3801 /// directly instead of always using editors via views.
3802 pub fn set_view_id(&mut self, view_id: EntityId) {
3803 self.invalidator.debug_assert_prepaint();
3804 self.next_frame.dispatch_tree.set_view_id(view_id);
3805 }
3806
3807 /// Get the entity ID for the currently rendering view
3808 pub fn current_view(&self) -> EntityId {
3809 self.invalidator.debug_assert_paint_or_prepaint();
3810 self.rendered_entity_stack.last().copied().unwrap()
3811 }
3812
3813 #[inline]
3814 pub(crate) fn with_rendered_view<R>(
3815 &mut self,
3816 id: EntityId,
3817 f: impl FnOnce(&mut Self) -> R,
3818 ) -> R {
3819 self.rendered_entity_stack.push(id);
3820 let result = f(self);
3821 self.rendered_entity_stack.pop();
3822 result
3823 }
3824
3825 /// Executes the provided function with the specified image cache.
3826 pub fn with_image_cache<F, R>(&mut self, image_cache: Option<AnyImageCache>, f: F) -> R
3827 where
3828 F: FnOnce(&mut Self) -> R,
3829 {
3830 if let Some(image_cache) = image_cache {
3831 self.image_cache_stack.push(image_cache);
3832 let result = f(self);
3833 self.image_cache_stack.pop();
3834 result
3835 } else {
3836 f(self)
3837 }
3838 }
3839
3840 /// Sets an input handler, such as [`ElementInputHandler`][element_input_handler], which interfaces with the
3841 /// platform to receive textual input with proper integration with concerns such
3842 /// as IME interactions. This handler will be active for the upcoming frame until the following frame is
3843 /// rendered.
3844 ///
3845 /// This method should only be called as part of the paint phase of element drawing.
3846 ///
3847 /// [element_input_handler]: crate::ElementInputHandler
3848 pub fn handle_input(
3849 &mut self,
3850 focus_handle: &FocusHandle,
3851 input_handler: impl InputHandler,
3852 cx: &App,
3853 ) {
3854 self.invalidator.debug_assert_paint();
3855
3856 if focus_handle.is_focused(self) {
3857 let cx = self.to_async(cx);
3858 self.next_frame
3859 .input_handlers
3860 .push(Some(PlatformInputHandler::new(cx, Box::new(input_handler))));
3861 }
3862 }
3863
3864 /// Register a mouse event listener on the window for the next frame. The type of event
3865 /// is determined by the first parameter of the given listener. When the next frame is rendered
3866 /// the listener will be cleared.
3867 ///
3868 /// This method should only be called as part of the paint phase of element drawing.
3869 pub fn on_mouse_event<Event: MouseEvent>(
3870 &mut self,
3871 mut listener: impl FnMut(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
3872 ) {
3873 self.invalidator.debug_assert_paint();
3874
3875 self.next_frame.mouse_listeners.push(Some(Box::new(
3876 move |event: &dyn Any, phase: DispatchPhase, window: &mut Window, cx: &mut App| {
3877 if let Some(event) = event.downcast_ref() {
3878 listener(event, phase, window, cx)
3879 }
3880 },
3881 )));
3882 }
3883
3884 /// Register a key event listener on this node for the next frame. The type of event
3885 /// is determined by the first parameter of the given listener. When the next frame is rendered
3886 /// the listener will be cleared.
3887 ///
3888 /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
3889 /// a specific need to register a listener yourself.
3890 ///
3891 /// This method should only be called as part of the paint phase of element drawing.
3892 pub fn on_key_event<Event: KeyEvent>(
3893 &mut self,
3894 listener: impl Fn(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
3895 ) {
3896 self.invalidator.debug_assert_paint();
3897
3898 self.next_frame.dispatch_tree.on_key_event(Rc::new(
3899 move |event: &dyn Any, phase, window: &mut Window, cx: &mut App| {
3900 if let Some(event) = event.downcast_ref::<Event>() {
3901 listener(event, phase, window, cx)
3902 }
3903 },
3904 ));
3905 }
3906
3907 /// Register a modifiers changed event listener on the window for the next frame.
3908 ///
3909 /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
3910 /// a specific need to register a global listener.
3911 ///
3912 /// This method should only be called as part of the paint phase of element drawing.
3913 pub fn on_modifiers_changed(
3914 &mut self,
3915 listener: impl Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static,
3916 ) {
3917 self.invalidator.debug_assert_paint();
3918
3919 self.next_frame.dispatch_tree.on_modifiers_changed(Rc::new(
3920 move |event: &ModifiersChangedEvent, window: &mut Window, cx: &mut App| {
3921 listener(event, window, cx)
3922 },
3923 ));
3924 }
3925
3926 /// Register a listener to be called when the given focus handle or one of its descendants receives focus.
3927 /// This does not fire if the given focus handle - or one of its descendants - was previously focused.
3928 /// Returns a subscription and persists until the subscription is dropped.
3929 pub fn on_focus_in(
3930 &mut self,
3931 handle: &FocusHandle,
3932 cx: &mut App,
3933 mut listener: impl FnMut(&mut Window, &mut App) + 'static,
3934 ) -> Subscription {
3935 let focus_id = handle.id;
3936 let (subscription, activate) =
3937 self.new_focus_listener(Box::new(move |event, window, cx| {
3938 if event.is_focus_in(focus_id) {
3939 listener(window, cx);
3940 }
3941 true
3942 }));
3943 cx.defer(move |_| activate());
3944 subscription
3945 }
3946
3947 /// Register a listener to be called when the given focus handle or one of its descendants loses focus.
3948 /// Returns a subscription and persists until the subscription is dropped.
3949 pub fn on_focus_out(
3950 &mut self,
3951 handle: &FocusHandle,
3952 cx: &mut App,
3953 mut listener: impl FnMut(FocusOutEvent, &mut Window, &mut App) + 'static,
3954 ) -> Subscription {
3955 let focus_id = handle.id;
3956 let (subscription, activate) =
3957 self.new_focus_listener(Box::new(move |event, window, cx| {
3958 if let Some(blurred_id) = event.previous_focus_path.last().copied()
3959 && event.is_focus_out(focus_id)
3960 {
3961 let event = FocusOutEvent {
3962 blurred: WeakFocusHandle {
3963 id: blurred_id,
3964 handles: Arc::downgrade(&cx.focus_handles),
3965 },
3966 };
3967 listener(event, window, cx)
3968 }
3969 true
3970 }));
3971 cx.defer(move |_| activate());
3972 subscription
3973 }
3974
3975 fn reset_cursor_style(&self, cx: &mut App) {
3976 // Set the cursor only if we're the active window.
3977 if self.is_window_hovered() {
3978 let style = self
3979 .rendered_frame
3980 .cursor_style(self)
3981 .unwrap_or(CursorStyle::Arrow);
3982 cx.platform.set_cursor_style(style);
3983 }
3984 }
3985
3986 /// Dispatch a given keystroke as though the user had typed it.
3987 /// You can create a keystroke with Keystroke::parse("").
3988 pub fn dispatch_keystroke(&mut self, keystroke: Keystroke, cx: &mut App) -> bool {
3989 let keystroke = keystroke.with_simulated_ime();
3990 let result = self.dispatch_event(
3991 PlatformInput::KeyDown(KeyDownEvent {
3992 keystroke: keystroke.clone(),
3993 is_held: false,
3994 prefer_character_input: false,
3995 }),
3996 cx,
3997 );
3998 if !result.propagate {
3999 return true;
4000 }
4001
4002 if let Some(input) = keystroke.key_char
4003 && let Some(mut input_handler) = self.platform_window.take_input_handler()
4004 {
4005 input_handler.dispatch_input(&input, self, cx);
4006 self.platform_window.set_input_handler(input_handler);
4007 return true;
4008 }
4009
4010 false
4011 }
4012
4013 /// Return a key binding string for an action, to display in the UI. Uses the highest precedence
4014 /// binding for the action (last binding added to the keymap).
4015 pub fn keystroke_text_for(&self, action: &dyn Action) -> String {
4016 self.highest_precedence_binding_for_action(action)
4017 .map(|binding| {
4018 binding
4019 .keystrokes()
4020 .iter()
4021 .map(ToString::to_string)
4022 .collect::<Vec<_>>()
4023 .join(" ")
4024 })
4025 .unwrap_or_else(|| action.name().to_string())
4026 }
4027
4028 /// Dispatch a mouse or keyboard event on the window.
4029 #[profiling::function]
4030 pub fn dispatch_event(&mut self, event: PlatformInput, cx: &mut App) -> DispatchEventResult {
4031 // Track whether this input was keyboard-based for focus-visible styling
4032 self.last_input_modality = match &event {
4033 PlatformInput::KeyDown(_) | PlatformInput::ModifiersChanged(_) => {
4034 InputModality::Keyboard
4035 }
4036 PlatformInput::MouseDown(e) if e.is_focusing() => InputModality::Mouse,
4037 _ => self.last_input_modality,
4038 };
4039
4040 // Handlers may set this to false by calling `stop_propagation`.
4041 cx.propagate_event = true;
4042 // Handlers may set this to true by calling `prevent_default`.
4043 self.default_prevented = false;
4044
4045 let event = match event {
4046 // Track the mouse position with our own state, since accessing the platform
4047 // API for the mouse position can only occur on the main thread.
4048 PlatformInput::MouseMove(mouse_move) => {
4049 self.mouse_position = mouse_move.position;
4050 self.modifiers = mouse_move.modifiers;
4051 PlatformInput::MouseMove(mouse_move)
4052 }
4053 PlatformInput::MouseDown(mouse_down) => {
4054 self.mouse_position = mouse_down.position;
4055 self.modifiers = mouse_down.modifiers;
4056 PlatformInput::MouseDown(mouse_down)
4057 }
4058 PlatformInput::MouseUp(mouse_up) => {
4059 self.mouse_position = mouse_up.position;
4060 self.modifiers = mouse_up.modifiers;
4061 PlatformInput::MouseUp(mouse_up)
4062 }
4063 PlatformInput::MousePressure(mouse_pressure) => {
4064 PlatformInput::MousePressure(mouse_pressure)
4065 }
4066 PlatformInput::MouseExited(mouse_exited) => {
4067 self.modifiers = mouse_exited.modifiers;
4068 PlatformInput::MouseExited(mouse_exited)
4069 }
4070 PlatformInput::ModifiersChanged(modifiers_changed) => {
4071 self.modifiers = modifiers_changed.modifiers;
4072 self.capslock = modifiers_changed.capslock;
4073 PlatformInput::ModifiersChanged(modifiers_changed)
4074 }
4075 PlatformInput::ScrollWheel(scroll_wheel) => {
4076 self.mouse_position = scroll_wheel.position;
4077 self.modifiers = scroll_wheel.modifiers;
4078 PlatformInput::ScrollWheel(scroll_wheel)
4079 }
4080 #[cfg(any(target_os = "linux", target_os = "macos"))]
4081 PlatformInput::Pinch(pinch) => {
4082 self.mouse_position = pinch.position;
4083 self.modifiers = pinch.modifiers;
4084 PlatformInput::Pinch(pinch)
4085 }
4086 // Translate dragging and dropping of external files from the operating system
4087 // to internal drag and drop events.
4088 PlatformInput::FileDrop(file_drop) => match file_drop {
4089 FileDropEvent::Entered { position, paths } => {
4090 self.mouse_position = position;
4091 if cx.active_drag.is_none() {
4092 cx.active_drag = Some(AnyDrag {
4093 value: Arc::new(paths.clone()),
4094 view: cx.new(|_| paths).into(),
4095 cursor_offset: position,
4096 cursor_style: None,
4097 });
4098 }
4099 PlatformInput::MouseMove(MouseMoveEvent {
4100 position,
4101 pressed_button: Some(MouseButton::Left),
4102 modifiers: Modifiers::default(),
4103 })
4104 }
4105 FileDropEvent::Pending { position } => {
4106 self.mouse_position = position;
4107 PlatformInput::MouseMove(MouseMoveEvent {
4108 position,
4109 pressed_button: Some(MouseButton::Left),
4110 modifiers: Modifiers::default(),
4111 })
4112 }
4113 FileDropEvent::Submit { position } => {
4114 cx.activate(true);
4115 self.mouse_position = position;
4116 PlatformInput::MouseUp(MouseUpEvent {
4117 button: MouseButton::Left,
4118 position,
4119 modifiers: Modifiers::default(),
4120 click_count: 1,
4121 })
4122 }
4123 FileDropEvent::Exited => {
4124 cx.active_drag.take();
4125 PlatformInput::FileDrop(FileDropEvent::Exited)
4126 }
4127 },
4128 PlatformInput::KeyDown(_) | PlatformInput::KeyUp(_) => event,
4129 };
4130
4131 if let Some(any_mouse_event) = event.mouse_event() {
4132 self.dispatch_mouse_event(any_mouse_event, cx);
4133 } else if let Some(any_key_event) = event.keyboard_event() {
4134 self.dispatch_key_event(any_key_event, cx);
4135 }
4136
4137 if self.invalidator.is_dirty() {
4138 self.input_rate_tracker.borrow_mut().record_input();
4139 }
4140
4141 DispatchEventResult {
4142 propagate: cx.propagate_event,
4143 default_prevented: self.default_prevented,
4144 }
4145 }
4146
4147 fn dispatch_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
4148 let hit_test = self.rendered_frame.hit_test(self.mouse_position());
4149 if hit_test != self.mouse_hit_test {
4150 self.mouse_hit_test = hit_test;
4151 self.reset_cursor_style(cx);
4152 }
4153
4154 #[cfg(any(feature = "inspector", debug_assertions))]
4155 if self.is_inspector_picking(cx) {
4156 self.handle_inspector_mouse_event(event, cx);
4157 // When inspector is picking, all other mouse handling is skipped.
4158 return;
4159 }
4160
4161 let mut mouse_listeners = mem::take(&mut self.rendered_frame.mouse_listeners);
4162
4163 // Capture phase, events bubble from back to front. Handlers for this phase are used for
4164 // special purposes, such as detecting events outside of a given Bounds.
4165 for listener in &mut mouse_listeners {
4166 let listener = listener.as_mut().unwrap();
4167 listener(event, DispatchPhase::Capture, self, cx);
4168 if !cx.propagate_event {
4169 break;
4170 }
4171 }
4172
4173 // Bubble phase, where most normal handlers do their work.
4174 if cx.propagate_event {
4175 for listener in mouse_listeners.iter_mut().rev() {
4176 let listener = listener.as_mut().unwrap();
4177 listener(event, DispatchPhase::Bubble, self, cx);
4178 if !cx.propagate_event {
4179 break;
4180 }
4181 }
4182 }
4183
4184 self.rendered_frame.mouse_listeners = mouse_listeners;
4185
4186 if cx.has_active_drag() {
4187 if event.is::<MouseMoveEvent>() {
4188 // If this was a mouse move event, redraw the window so that the
4189 // active drag can follow the mouse cursor.
4190 self.refresh();
4191 } else if event.is::<MouseUpEvent>() {
4192 // If this was a mouse up event, cancel the active drag and redraw
4193 // the window.
4194 cx.active_drag = None;
4195 self.refresh();
4196 }
4197 }
4198
4199 // Auto-release pointer capture on mouse up
4200 if event.is::<MouseUpEvent>() && self.captured_hitbox.is_some() {
4201 self.captured_hitbox = None;
4202 }
4203 }
4204
4205 fn dispatch_key_event(&mut self, event: &dyn Any, cx: &mut App) {
4206 if self.invalidator.is_dirty() {
4207 self.draw(cx).clear();
4208 }
4209
4210 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
4211 let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
4212
4213 let mut keystroke: Option<Keystroke> = None;
4214
4215 if let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() {
4216 if event.modifiers.number_of_modifiers() == 0
4217 && self.pending_modifier.modifiers.number_of_modifiers() == 1
4218 && !self.pending_modifier.saw_keystroke
4219 {
4220 let key = match self.pending_modifier.modifiers {
4221 modifiers if modifiers.shift => Some("shift"),
4222 modifiers if modifiers.control => Some("control"),
4223 modifiers if modifiers.alt => Some("alt"),
4224 modifiers if modifiers.platform => Some("platform"),
4225 modifiers if modifiers.function => Some("function"),
4226 _ => None,
4227 };
4228 if let Some(key) = key {
4229 keystroke = Some(Keystroke {
4230 key: key.to_string(),
4231 key_char: None,
4232 modifiers: Modifiers::default(),
4233 });
4234 }
4235 }
4236
4237 if self.pending_modifier.modifiers.number_of_modifiers() == 0
4238 && event.modifiers.number_of_modifiers() == 1
4239 {
4240 self.pending_modifier.saw_keystroke = false
4241 }
4242 self.pending_modifier.modifiers = event.modifiers
4243 } else if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
4244 self.pending_modifier.saw_keystroke = true;
4245 keystroke = Some(key_down_event.keystroke.clone());
4246 }
4247
4248 let Some(keystroke) = keystroke else {
4249 self.finish_dispatch_key_event(event, dispatch_path, self.context_stack(), cx);
4250 return;
4251 };
4252
4253 cx.propagate_event = true;
4254 self.dispatch_keystroke_interceptors(event, self.context_stack(), cx);
4255 if !cx.propagate_event {
4256 self.finish_dispatch_key_event(event, dispatch_path, self.context_stack(), cx);
4257 return;
4258 }
4259
4260 let mut currently_pending = self.pending_input.take().unwrap_or_default();
4261 if currently_pending.focus.is_some() && currently_pending.focus != self.focus {
4262 currently_pending = PendingInput::default();
4263 }
4264
4265 let match_result = self.rendered_frame.dispatch_tree.dispatch_key(
4266 currently_pending.keystrokes,
4267 keystroke,
4268 &dispatch_path,
4269 );
4270
4271 if !match_result.to_replay.is_empty() {
4272 self.replay_pending_input(match_result.to_replay, cx);
4273 cx.propagate_event = true;
4274 }
4275
4276 if !match_result.pending.is_empty() {
4277 currently_pending.timer.take();
4278 currently_pending.keystrokes = match_result.pending;
4279 currently_pending.focus = self.focus;
4280
4281 let text_input_requires_timeout = event
4282 .downcast_ref::<KeyDownEvent>()
4283 .filter(|key_down| key_down.keystroke.key_char.is_some())
4284 .and_then(|_| self.platform_window.take_input_handler())
4285 .map_or(false, |mut input_handler| {
4286 let accepts = input_handler.accepts_text_input(self, cx);
4287 self.platform_window.set_input_handler(input_handler);
4288 accepts
4289 });
4290
4291 currently_pending.needs_timeout |=
4292 match_result.pending_has_binding || text_input_requires_timeout;
4293
4294 if currently_pending.needs_timeout {
4295 currently_pending.timer = Some(self.spawn(cx, async move |cx| {
4296 cx.background_executor.timer(Duration::from_secs(1)).await;
4297 cx.update(move |window, cx| {
4298 let Some(currently_pending) = window
4299 .pending_input
4300 .take()
4301 .filter(|pending| pending.focus == window.focus)
4302 else {
4303 return;
4304 };
4305
4306 let node_id = window.focus_node_id_in_rendered_frame(window.focus);
4307 let dispatch_path =
4308 window.rendered_frame.dispatch_tree.dispatch_path(node_id);
4309
4310 let to_replay = window
4311 .rendered_frame
4312 .dispatch_tree
4313 .flush_dispatch(currently_pending.keystrokes, &dispatch_path);
4314
4315 window.pending_input_changed(cx);
4316 window.replay_pending_input(to_replay, cx)
4317 })
4318 .log_err();
4319 }));
4320 } else {
4321 currently_pending.timer = None;
4322 }
4323 self.pending_input = Some(currently_pending);
4324 self.pending_input_changed(cx);
4325 cx.propagate_event = false;
4326 return;
4327 }
4328
4329 let skip_bindings = event
4330 .downcast_ref::<KeyDownEvent>()
4331 .filter(|key_down_event| key_down_event.prefer_character_input)
4332 .map(|_| {
4333 self.platform_window
4334 .take_input_handler()
4335 .map_or(false, |mut input_handler| {
4336 let accepts = input_handler.accepts_text_input(self, cx);
4337 self.platform_window.set_input_handler(input_handler);
4338 // If modifiers are not excessive (e.g. AltGr), and the input handler is accepting text input,
4339 // we prefer the text input over bindings.
4340 accepts
4341 })
4342 })
4343 .unwrap_or(false);
4344
4345 if !skip_bindings {
4346 for binding in match_result.bindings {
4347 self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
4348 if !cx.propagate_event {
4349 self.dispatch_keystroke_observers(
4350 event,
4351 Some(binding.action),
4352 match_result.context_stack,
4353 cx,
4354 );
4355 self.pending_input_changed(cx);
4356 return;
4357 }
4358 }
4359 }
4360
4361 self.finish_dispatch_key_event(event, dispatch_path, match_result.context_stack, cx);
4362 self.pending_input_changed(cx);
4363 }
4364
4365 fn finish_dispatch_key_event(
4366 &mut self,
4367 event: &dyn Any,
4368 dispatch_path: SmallVec<[DispatchNodeId; 32]>,
4369 context_stack: Vec<KeyContext>,
4370 cx: &mut App,
4371 ) {
4372 self.dispatch_key_down_up_event(event, &dispatch_path, cx);
4373 if !cx.propagate_event {
4374 return;
4375 }
4376
4377 self.dispatch_modifiers_changed_event(event, &dispatch_path, cx);
4378 if !cx.propagate_event {
4379 return;
4380 }
4381
4382 self.dispatch_keystroke_observers(event, None, context_stack, cx);
4383 }
4384
4385 pub(crate) fn pending_input_changed(&mut self, cx: &mut App) {
4386 self.pending_input_observers
4387 .clone()
4388 .retain(&(), |callback| callback(self, cx));
4389 }
4390
4391 fn dispatch_key_down_up_event(
4392 &mut self,
4393 event: &dyn Any,
4394 dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
4395 cx: &mut App,
4396 ) {
4397 // Capture phase
4398 for node_id in dispatch_path {
4399 let node = self.rendered_frame.dispatch_tree.node(*node_id);
4400
4401 for key_listener in node.key_listeners.clone() {
4402 key_listener(event, DispatchPhase::Capture, self, cx);
4403 if !cx.propagate_event {
4404 return;
4405 }
4406 }
4407 }
4408
4409 // Bubble phase
4410 for node_id in dispatch_path.iter().rev() {
4411 // Handle low level key events
4412 let node = self.rendered_frame.dispatch_tree.node(*node_id);
4413 for key_listener in node.key_listeners.clone() {
4414 key_listener(event, DispatchPhase::Bubble, self, cx);
4415 if !cx.propagate_event {
4416 return;
4417 }
4418 }
4419 }
4420 }
4421
4422 fn dispatch_modifiers_changed_event(
4423 &mut self,
4424 event: &dyn Any,
4425 dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
4426 cx: &mut App,
4427 ) {
4428 let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() else {
4429 return;
4430 };
4431 for node_id in dispatch_path.iter().rev() {
4432 let node = self.rendered_frame.dispatch_tree.node(*node_id);
4433 for listener in node.modifiers_changed_listeners.clone() {
4434 listener(event, self, cx);
4435 if !cx.propagate_event {
4436 return;
4437 }
4438 }
4439 }
4440 }
4441
4442 /// Determine whether a potential multi-stroke key binding is in progress on this window.
4443 pub fn has_pending_keystrokes(&self) -> bool {
4444 self.pending_input.is_some()
4445 }
4446
4447 pub(crate) fn clear_pending_keystrokes(&mut self) {
4448 self.pending_input.take();
4449 }
4450
4451 /// Returns the currently pending input keystrokes that might result in a multi-stroke key binding.
4452 pub fn pending_input_keystrokes(&self) -> Option<&[Keystroke]> {
4453 self.pending_input
4454 .as_ref()
4455 .map(|pending_input| pending_input.keystrokes.as_slice())
4456 }
4457
4458 fn replay_pending_input(&mut self, replays: SmallVec<[Replay; 1]>, cx: &mut App) {
4459 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
4460 let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
4461
4462 'replay: for replay in replays {
4463 let event = KeyDownEvent {
4464 keystroke: replay.keystroke.clone(),
4465 is_held: false,
4466 prefer_character_input: true,
4467 };
4468
4469 cx.propagate_event = true;
4470 for binding in replay.bindings {
4471 self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
4472 if !cx.propagate_event {
4473 self.dispatch_keystroke_observers(
4474 &event,
4475 Some(binding.action),
4476 Vec::default(),
4477 cx,
4478 );
4479 continue 'replay;
4480 }
4481 }
4482
4483 self.dispatch_key_down_up_event(&event, &dispatch_path, cx);
4484 if !cx.propagate_event {
4485 continue 'replay;
4486 }
4487 if let Some(input) = replay.keystroke.key_char.as_ref().cloned()
4488 && let Some(mut input_handler) = self.platform_window.take_input_handler()
4489 {
4490 input_handler.dispatch_input(&input, self, cx);
4491 self.platform_window.set_input_handler(input_handler)
4492 }
4493 }
4494 }
4495
4496 fn focus_node_id_in_rendered_frame(&self, focus_id: Option<FocusId>) -> DispatchNodeId {
4497 focus_id
4498 .and_then(|focus_id| {
4499 self.rendered_frame
4500 .dispatch_tree
4501 .focusable_node_id(focus_id)
4502 })
4503 .unwrap_or_else(|| self.rendered_frame.dispatch_tree.root_node_id())
4504 }
4505
4506 fn dispatch_action_on_node(
4507 &mut self,
4508 node_id: DispatchNodeId,
4509 action: &dyn Action,
4510 cx: &mut App,
4511 ) {
4512 let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
4513
4514 // Capture phase for global actions.
4515 cx.propagate_event = true;
4516 if let Some(mut global_listeners) = cx
4517 .global_action_listeners
4518 .remove(&action.as_any().type_id())
4519 {
4520 for listener in &global_listeners {
4521 listener(action.as_any(), DispatchPhase::Capture, cx);
4522 if !cx.propagate_event {
4523 break;
4524 }
4525 }
4526
4527 global_listeners.extend(
4528 cx.global_action_listeners
4529 .remove(&action.as_any().type_id())
4530 .unwrap_or_default(),
4531 );
4532
4533 cx.global_action_listeners
4534 .insert(action.as_any().type_id(), global_listeners);
4535 }
4536
4537 if !cx.propagate_event {
4538 return;
4539 }
4540
4541 // Capture phase for window actions.
4542 for node_id in &dispatch_path {
4543 let node = self.rendered_frame.dispatch_tree.node(*node_id);
4544 for DispatchActionListener {
4545 action_type,
4546 listener,
4547 } in node.action_listeners.clone()
4548 {
4549 let any_action = action.as_any();
4550 if action_type == any_action.type_id() {
4551 listener(any_action, DispatchPhase::Capture, self, cx);
4552
4553 if !cx.propagate_event {
4554 return;
4555 }
4556 }
4557 }
4558 }
4559
4560 // Bubble phase for window actions.
4561 for node_id in dispatch_path.iter().rev() {
4562 let node = self.rendered_frame.dispatch_tree.node(*node_id);
4563 for DispatchActionListener {
4564 action_type,
4565 listener,
4566 } in node.action_listeners.clone()
4567 {
4568 let any_action = action.as_any();
4569 if action_type == any_action.type_id() {
4570 cx.propagate_event = false; // Actions stop propagation by default during the bubble phase
4571 listener(any_action, DispatchPhase::Bubble, self, cx);
4572
4573 if !cx.propagate_event {
4574 return;
4575 }
4576 }
4577 }
4578 }
4579
4580 // Bubble phase for global actions.
4581 if let Some(mut global_listeners) = cx
4582 .global_action_listeners
4583 .remove(&action.as_any().type_id())
4584 {
4585 for listener in global_listeners.iter().rev() {
4586 cx.propagate_event = false; // Actions stop propagation by default during the bubble phase
4587
4588 listener(action.as_any(), DispatchPhase::Bubble, cx);
4589 if !cx.propagate_event {
4590 break;
4591 }
4592 }
4593
4594 global_listeners.extend(
4595 cx.global_action_listeners
4596 .remove(&action.as_any().type_id())
4597 .unwrap_or_default(),
4598 );
4599
4600 cx.global_action_listeners
4601 .insert(action.as_any().type_id(), global_listeners);
4602 }
4603 }
4604
4605 /// Register the given handler to be invoked whenever the global of the given type
4606 /// is updated.
4607 pub fn observe_global<G: Global>(
4608 &mut self,
4609 cx: &mut App,
4610 f: impl Fn(&mut Window, &mut App) + 'static,
4611 ) -> Subscription {
4612 let window_handle = self.handle;
4613 let (subscription, activate) = cx.global_observers.insert(
4614 TypeId::of::<G>(),
4615 Box::new(move |cx| {
4616 window_handle
4617 .update(cx, |_, window, cx| f(window, cx))
4618 .is_ok()
4619 }),
4620 );
4621 cx.defer(move |_| activate());
4622 subscription
4623 }
4624
4625 /// Focus the current window and bring it to the foreground at the platform level.
4626 pub fn activate_window(&self) {
4627 self.platform_window.activate();
4628 }
4629
4630 /// Minimize the current window at the platform level.
4631 pub fn minimize_window(&self) {
4632 self.platform_window.minimize();
4633 }
4634
4635 /// Toggle full screen status on the current window at the platform level.
4636 pub fn toggle_fullscreen(&self) {
4637 self.platform_window.toggle_fullscreen();
4638 }
4639
4640 /// Updates the IME panel position suggestions for languages like japanese, chinese.
4641 pub fn invalidate_character_coordinates(&self) {
4642 self.on_next_frame(|window, cx| {
4643 if let Some(mut input_handler) = window.platform_window.take_input_handler() {
4644 if let Some(bounds) = input_handler.selected_bounds(window, cx) {
4645 window.platform_window.update_ime_position(bounds);
4646 }
4647 window.platform_window.set_input_handler(input_handler);
4648 }
4649 });
4650 }
4651
4652 /// Present a platform dialog.
4653 /// The provided message will be presented, along with buttons for each answer.
4654 /// When a button is clicked, the returned Receiver will receive the index of the clicked button.
4655 pub fn prompt<T>(
4656 &mut self,
4657 level: PromptLevel,
4658 message: &str,
4659 detail: Option<&str>,
4660 answers: &[T],
4661 cx: &mut App,
4662 ) -> oneshot::Receiver<usize>
4663 where
4664 T: Clone + Into<PromptButton>,
4665 {
4666 let prompt_builder = cx.prompt_builder.take();
4667 let Some(prompt_builder) = prompt_builder else {
4668 unreachable!("Re-entrant window prompting is not supported by GPUI");
4669 };
4670
4671 let answers = answers
4672 .iter()
4673 .map(|answer| answer.clone().into())
4674 .collect::<Vec<_>>();
4675
4676 let receiver = match &prompt_builder {
4677 PromptBuilder::Default => self
4678 .platform_window
4679 .prompt(level, message, detail, &answers)
4680 .unwrap_or_else(|| {
4681 self.build_custom_prompt(&prompt_builder, level, message, detail, &answers, cx)
4682 }),
4683 PromptBuilder::Custom(_) => {
4684 self.build_custom_prompt(&prompt_builder, level, message, detail, &answers, cx)
4685 }
4686 };
4687
4688 cx.prompt_builder = Some(prompt_builder);
4689
4690 receiver
4691 }
4692
4693 fn build_custom_prompt(
4694 &mut self,
4695 prompt_builder: &PromptBuilder,
4696 level: PromptLevel,
4697 message: &str,
4698 detail: Option<&str>,
4699 answers: &[PromptButton],
4700 cx: &mut App,
4701 ) -> oneshot::Receiver<usize> {
4702 let (sender, receiver) = oneshot::channel();
4703 let handle = PromptHandle::new(sender);
4704 let handle = (prompt_builder)(level, message, detail, answers, handle, self, cx);
4705 self.prompt = Some(handle);
4706 receiver
4707 }
4708
4709 /// Returns the current context stack.
4710 pub fn context_stack(&self) -> Vec<KeyContext> {
4711 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
4712 let dispatch_tree = &self.rendered_frame.dispatch_tree;
4713 dispatch_tree
4714 .dispatch_path(node_id)
4715 .iter()
4716 .filter_map(move |&node_id| dispatch_tree.node(node_id).context.clone())
4717 .collect()
4718 }
4719
4720 /// Returns all available actions for the focused element.
4721 pub fn available_actions(&self, cx: &App) -> Vec<Box<dyn Action>> {
4722 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
4723 let mut actions = self.rendered_frame.dispatch_tree.available_actions(node_id);
4724 for action_type in cx.global_action_listeners.keys() {
4725 if let Err(ix) = actions.binary_search_by_key(action_type, |a| a.as_any().type_id()) {
4726 let action = cx.actions.build_action_type(action_type).ok();
4727 if let Some(action) = action {
4728 actions.insert(ix, action);
4729 }
4730 }
4731 }
4732 actions
4733 }
4734
4735 /// Returns key bindings that invoke an action on the currently focused element. Bindings are
4736 /// returned in the order they were added. For display, the last binding should take precedence.
4737 pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
4738 self.rendered_frame
4739 .dispatch_tree
4740 .bindings_for_action(action, &self.rendered_frame.dispatch_tree.context_stack)
4741 }
4742
4743 /// Returns the highest precedence key binding that invokes an action on the currently focused
4744 /// element. This is more efficient than getting the last result of `bindings_for_action`.
4745 pub fn highest_precedence_binding_for_action(&self, action: &dyn Action) -> Option<KeyBinding> {
4746 self.rendered_frame
4747 .dispatch_tree
4748 .highest_precedence_binding_for_action(
4749 action,
4750 &self.rendered_frame.dispatch_tree.context_stack,
4751 )
4752 }
4753
4754 /// Returns the key bindings for an action in a context.
4755 pub fn bindings_for_action_in_context(
4756 &self,
4757 action: &dyn Action,
4758 context: KeyContext,
4759 ) -> Vec<KeyBinding> {
4760 let dispatch_tree = &self.rendered_frame.dispatch_tree;
4761 dispatch_tree.bindings_for_action(action, &[context])
4762 }
4763
4764 /// Returns the highest precedence key binding for an action in a context. This is more
4765 /// efficient than getting the last result of `bindings_for_action_in_context`.
4766 pub fn highest_precedence_binding_for_action_in_context(
4767 &self,
4768 action: &dyn Action,
4769 context: KeyContext,
4770 ) -> Option<KeyBinding> {
4771 let dispatch_tree = &self.rendered_frame.dispatch_tree;
4772 dispatch_tree.highest_precedence_binding_for_action(action, &[context])
4773 }
4774
4775 /// Returns any bindings that would invoke an action on the given focus handle if it were
4776 /// focused. Bindings are returned in the order they were added. For display, the last binding
4777 /// should take precedence.
4778 pub fn bindings_for_action_in(
4779 &self,
4780 action: &dyn Action,
4781 focus_handle: &FocusHandle,
4782 ) -> Vec<KeyBinding> {
4783 let dispatch_tree = &self.rendered_frame.dispatch_tree;
4784 let Some(context_stack) = self.context_stack_for_focus_handle(focus_handle) else {
4785 return vec![];
4786 };
4787 dispatch_tree.bindings_for_action(action, &context_stack)
4788 }
4789
4790 /// Returns the highest precedence key binding that would invoke an action on the given focus
4791 /// handle if it were focused. This is more efficient than getting the last result of
4792 /// `bindings_for_action_in`.
4793 pub fn highest_precedence_binding_for_action_in(
4794 &self,
4795 action: &dyn Action,
4796 focus_handle: &FocusHandle,
4797 ) -> Option<KeyBinding> {
4798 let dispatch_tree = &self.rendered_frame.dispatch_tree;
4799 let context_stack = self.context_stack_for_focus_handle(focus_handle)?;
4800 dispatch_tree.highest_precedence_binding_for_action(action, &context_stack)
4801 }
4802
4803 /// Find the bindings that can follow the current input sequence for the current context stack.
4804 pub fn possible_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
4805 self.rendered_frame
4806 .dispatch_tree
4807 .possible_next_bindings_for_input(input, &self.context_stack())
4808 }
4809
4810 fn context_stack_for_focus_handle(
4811 &self,
4812 focus_handle: &FocusHandle,
4813 ) -> Option<Vec<KeyContext>> {
4814 let dispatch_tree = &self.rendered_frame.dispatch_tree;
4815 let node_id = dispatch_tree.focusable_node_id(focus_handle.id)?;
4816 let context_stack: Vec<_> = dispatch_tree
4817 .dispatch_path(node_id)
4818 .into_iter()
4819 .filter_map(|node_id| dispatch_tree.node(node_id).context.clone())
4820 .collect();
4821 Some(context_stack)
4822 }
4823
4824 /// Returns a generic event listener that invokes the given listener with the view and context associated with the given view handle.
4825 pub fn listener_for<T: 'static, E>(
4826 &self,
4827 view: &Entity<T>,
4828 f: impl Fn(&mut T, &E, &mut Window, &mut Context<T>) + 'static,
4829 ) -> impl Fn(&E, &mut Window, &mut App) + 'static {
4830 let view = view.downgrade();
4831 move |e: &E, window: &mut Window, cx: &mut App| {
4832 view.update(cx, |view, cx| f(view, e, window, cx)).ok();
4833 }
4834 }
4835
4836 /// Returns a generic handler that invokes the given handler with the view and context associated with the given view handle.
4837 pub fn handler_for<E: 'static, Callback: Fn(&mut E, &mut Window, &mut Context<E>) + 'static>(
4838 &self,
4839 entity: &Entity<E>,
4840 f: Callback,
4841 ) -> impl Fn(&mut Window, &mut App) + 'static {
4842 let entity = entity.downgrade();
4843 move |window: &mut Window, cx: &mut App| {
4844 entity.update(cx, |entity, cx| f(entity, window, cx)).ok();
4845 }
4846 }
4847
4848 /// Register a callback that can interrupt the closing of the current window based the returned boolean.
4849 /// If the callback returns false, the window won't be closed.
4850 pub fn on_window_should_close(
4851 &self,
4852 cx: &App,
4853 f: impl Fn(&mut Window, &mut App) -> bool + 'static,
4854 ) {
4855 let mut cx = self.to_async(cx);
4856 self.platform_window.on_should_close(Box::new(move || {
4857 cx.update(|window, cx| f(window, cx)).unwrap_or(true)
4858 }))
4859 }
4860
4861 /// Register an action listener on this node for the next frame. The type of action
4862 /// is determined by the first parameter of the given listener. When the next frame is rendered
4863 /// the listener will be cleared.
4864 ///
4865 /// This is a fairly low-level method, so prefer using action handlers on elements unless you have
4866 /// a specific need to register a listener yourself.
4867 ///
4868 /// This method should only be called as part of the paint phase of element drawing.
4869 pub fn on_action(
4870 &mut self,
4871 action_type: TypeId,
4872 listener: impl Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static,
4873 ) {
4874 self.invalidator.debug_assert_paint();
4875
4876 self.next_frame
4877 .dispatch_tree
4878 .on_action(action_type, Rc::new(listener));
4879 }
4880
4881 /// Register a capturing action listener on this node for the next frame if the condition is true.
4882 /// The type of action is determined by the first parameter of the given listener. When the next
4883 /// frame is rendered the listener will be cleared.
4884 ///
4885 /// This is a fairly low-level method, so prefer using action handlers on elements unless you have
4886 /// a specific need to register a listener yourself.
4887 ///
4888 /// This method should only be called as part of the paint phase of element drawing.
4889 pub fn on_action_when(
4890 &mut self,
4891 condition: bool,
4892 action_type: TypeId,
4893 listener: impl Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static,
4894 ) {
4895 self.invalidator.debug_assert_paint();
4896
4897 if condition {
4898 self.next_frame
4899 .dispatch_tree
4900 .on_action(action_type, Rc::new(listener));
4901 }
4902 }
4903
4904 /// Read information about the GPU backing this window.
4905 /// Currently returns None on Mac and Windows.
4906 pub fn gpu_specs(&self) -> Option<GpuSpecs> {
4907 self.platform_window.gpu_specs()
4908 }
4909
4910 /// Perform titlebar double-click action.
4911 /// This is macOS specific.
4912 pub fn titlebar_double_click(&self) {
4913 self.platform_window.titlebar_double_click();
4914 }
4915
4916 /// Gets the window's title at the platform level.
4917 /// This is macOS specific.
4918 pub fn window_title(&self) -> String {
4919 self.platform_window.get_title()
4920 }
4921
4922 /// Returns a list of all tabbed windows and their titles.
4923 /// This is macOS specific.
4924 pub fn tabbed_windows(&self) -> Option<Vec<SystemWindowTab>> {
4925 self.platform_window.tabbed_windows()
4926 }
4927
4928 /// Returns the tab bar visibility.
4929 /// This is macOS specific.
4930 pub fn tab_bar_visible(&self) -> bool {
4931 self.platform_window.tab_bar_visible()
4932 }
4933
4934 /// Merges all open windows into a single tabbed window.
4935 /// This is macOS specific.
4936 pub fn merge_all_windows(&self) {
4937 self.platform_window.merge_all_windows()
4938 }
4939
4940 /// Moves the tab to a new containing window.
4941 /// This is macOS specific.
4942 pub fn move_tab_to_new_window(&self) {
4943 self.platform_window.move_tab_to_new_window()
4944 }
4945
4946 /// Shows or hides the window tab overview.
4947 /// This is macOS specific.
4948 pub fn toggle_window_tab_overview(&self) {
4949 self.platform_window.toggle_window_tab_overview()
4950 }
4951
4952 /// Sets the tabbing identifier for the window.
4953 /// This is macOS specific.
4954 pub fn set_tabbing_identifier(&self, tabbing_identifier: Option<String>) {
4955 self.platform_window
4956 .set_tabbing_identifier(tabbing_identifier)
4957 }
4958
4959 /// Toggles the inspector mode on this window.
4960 #[cfg(any(feature = "inspector", debug_assertions))]
4961 pub fn toggle_inspector(&mut self, cx: &mut App) {
4962 self.inspector = match self.inspector {
4963 None => Some(cx.new(|_| Inspector::new())),
4964 Some(_) => None,
4965 };
4966 self.refresh();
4967 }
4968
4969 /// Returns true if the window is in inspector mode.
4970 pub fn is_inspector_picking(&self, _cx: &App) -> bool {
4971 #[cfg(any(feature = "inspector", debug_assertions))]
4972 {
4973 if let Some(inspector) = &self.inspector {
4974 return inspector.read(_cx).is_picking();
4975 }
4976 }
4977 false
4978 }
4979
4980 /// Executes the provided function with mutable access to an inspector state.
4981 #[cfg(any(feature = "inspector", debug_assertions))]
4982 pub fn with_inspector_state<T: 'static, R>(
4983 &mut self,
4984 _inspector_id: Option<&crate::InspectorElementId>,
4985 cx: &mut App,
4986 f: impl FnOnce(&mut Option<T>, &mut Self) -> R,
4987 ) -> R {
4988 if let Some(inspector_id) = _inspector_id
4989 && let Some(inspector) = &self.inspector
4990 {
4991 let inspector = inspector.clone();
4992 let active_element_id = inspector.read(cx).active_element_id();
4993 if Some(inspector_id) == active_element_id {
4994 return inspector.update(cx, |inspector, _cx| {
4995 inspector.with_active_element_state(self, f)
4996 });
4997 }
4998 }
4999 f(&mut None, self)
5000 }
5001
5002 #[cfg(any(feature = "inspector", debug_assertions))]
5003 pub(crate) fn build_inspector_element_id(
5004 &mut self,
5005 path: crate::InspectorElementPath,
5006 ) -> crate::InspectorElementId {
5007 self.invalidator.debug_assert_paint_or_prepaint();
5008 let path = Rc::new(path);
5009 let next_instance_id = self
5010 .next_frame
5011 .next_inspector_instance_ids
5012 .entry(path.clone())
5013 .or_insert(0);
5014 let instance_id = *next_instance_id;
5015 *next_instance_id += 1;
5016 crate::InspectorElementId { path, instance_id }
5017 }
5018
5019 #[cfg(any(feature = "inspector", debug_assertions))]
5020 fn prepaint_inspector(&mut self, inspector_width: Pixels, cx: &mut App) -> Option<AnyElement> {
5021 if let Some(inspector) = self.inspector.take() {
5022 let mut inspector_element = AnyView::from(inspector.clone()).into_any_element();
5023 inspector_element.prepaint_as_root(
5024 point(self.viewport_size.width - inspector_width, px(0.0)),
5025 size(inspector_width, self.viewport_size.height).into(),
5026 self,
5027 cx,
5028 );
5029 self.inspector = Some(inspector);
5030 Some(inspector_element)
5031 } else {
5032 None
5033 }
5034 }
5035
5036 #[cfg(any(feature = "inspector", debug_assertions))]
5037 fn paint_inspector(&mut self, mut inspector_element: Option<AnyElement>, cx: &mut App) {
5038 if let Some(mut inspector_element) = inspector_element {
5039 inspector_element.paint(self, cx);
5040 };
5041 }
5042
5043 /// Registers a hitbox that can be used for inspector picking mode, allowing users to select and
5044 /// inspect UI elements by clicking on them.
5045 #[cfg(any(feature = "inspector", debug_assertions))]
5046 pub fn insert_inspector_hitbox(
5047 &mut self,
5048 hitbox_id: HitboxId,
5049 inspector_id: Option<&crate::InspectorElementId>,
5050 cx: &App,
5051 ) {
5052 self.invalidator.debug_assert_paint_or_prepaint();
5053 if !self.is_inspector_picking(cx) {
5054 return;
5055 }
5056 if let Some(inspector_id) = inspector_id {
5057 self.next_frame
5058 .inspector_hitboxes
5059 .insert(hitbox_id, inspector_id.clone());
5060 }
5061 }
5062
5063 #[cfg(any(feature = "inspector", debug_assertions))]
5064 fn paint_inspector_hitbox(&mut self, cx: &App) {
5065 if let Some(inspector) = self.inspector.as_ref() {
5066 let inspector = inspector.read(cx);
5067 if let Some((hitbox_id, _)) = self.hovered_inspector_hitbox(inspector, &self.next_frame)
5068 && let Some(hitbox) = self
5069 .next_frame
5070 .hitboxes
5071 .iter()
5072 .find(|hitbox| hitbox.id == hitbox_id)
5073 {
5074 self.paint_quad(crate::fill(hitbox.bounds, crate::rgba(0x61afef4d)));
5075 }
5076 }
5077 }
5078
5079 #[cfg(any(feature = "inspector", debug_assertions))]
5080 fn handle_inspector_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
5081 let Some(inspector) = self.inspector.clone() else {
5082 return;
5083 };
5084 if event.downcast_ref::<MouseMoveEvent>().is_some() {
5085 inspector.update(cx, |inspector, _cx| {
5086 if let Some((_, inspector_id)) =
5087 self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
5088 {
5089 inspector.hover(inspector_id, self);
5090 }
5091 });
5092 } else if event.downcast_ref::<crate::MouseDownEvent>().is_some() {
5093 inspector.update(cx, |inspector, _cx| {
5094 if let Some((_, inspector_id)) =
5095 self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
5096 {
5097 inspector.select(inspector_id, self);
5098 }
5099 });
5100 } else if let Some(event) = event.downcast_ref::<crate::ScrollWheelEvent>() {
5101 // This should be kept in sync with SCROLL_LINES in x11 platform.
5102 const SCROLL_LINES: f32 = 3.0;
5103 const SCROLL_PIXELS_PER_LAYER: f32 = 36.0;
5104 let delta_y = event
5105 .delta
5106 .pixel_delta(px(SCROLL_PIXELS_PER_LAYER / SCROLL_LINES))
5107 .y;
5108 if let Some(inspector) = self.inspector.clone() {
5109 inspector.update(cx, |inspector, _cx| {
5110 if let Some(depth) = inspector.pick_depth.as_mut() {
5111 *depth += f32::from(delta_y) / SCROLL_PIXELS_PER_LAYER;
5112 let max_depth = self.mouse_hit_test.ids.len() as f32 - 0.5;
5113 if *depth < 0.0 {
5114 *depth = 0.0;
5115 } else if *depth > max_depth {
5116 *depth = max_depth;
5117 }
5118 if let Some((_, inspector_id)) =
5119 self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
5120 {
5121 inspector.set_active_element_id(inspector_id, self);
5122 }
5123 }
5124 });
5125 }
5126 }
5127 }
5128
5129 #[cfg(any(feature = "inspector", debug_assertions))]
5130 fn hovered_inspector_hitbox(
5131 &self,
5132 inspector: &Inspector,
5133 frame: &Frame,
5134 ) -> Option<(HitboxId, crate::InspectorElementId)> {
5135 if let Some(pick_depth) = inspector.pick_depth {
5136 let depth = (pick_depth as i64).try_into().unwrap_or(0);
5137 let max_skipped = self.mouse_hit_test.ids.len().saturating_sub(1);
5138 let skip_count = (depth as usize).min(max_skipped);
5139 for hitbox_id in self.mouse_hit_test.ids.iter().skip(skip_count) {
5140 if let Some(inspector_id) = frame.inspector_hitboxes.get(hitbox_id) {
5141 return Some((*hitbox_id, inspector_id.clone()));
5142 }
5143 }
5144 }
5145 None
5146 }
5147
5148 /// For testing: set the current modifier keys state.
5149 /// This does not generate any events.
5150 #[cfg(any(test, feature = "test-support"))]
5151 pub fn set_modifiers(&mut self, modifiers: Modifiers) {
5152 self.modifiers = modifiers;
5153 }
5154
5155 /// For testing: simulate a mouse move event to the given position.
5156 /// This dispatches the event through the normal event handling path,
5157 /// which will trigger hover states and tooltips.
5158 #[cfg(any(test, feature = "test-support"))]
5159 pub fn simulate_mouse_move(&mut self, position: Point<Pixels>, cx: &mut App) {
5160 let event = PlatformInput::MouseMove(MouseMoveEvent {
5161 position,
5162 modifiers: self.modifiers,
5163 pressed_button: None,
5164 });
5165 let _ = self.dispatch_event(event, cx);
5166 }
5167}
5168
5169// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
5170slotmap::new_key_type! {
5171 /// A unique identifier for a window.
5172 pub struct WindowId;
5173}
5174
5175impl WindowId {
5176 /// Converts this window ID to a `u64`.
5177 pub fn as_u64(&self) -> u64 {
5178 self.0.as_ffi()
5179 }
5180}
5181
5182impl From<u64> for WindowId {
5183 fn from(value: u64) -> Self {
5184 WindowId(slotmap::KeyData::from_ffi(value))
5185 }
5186}
5187
5188/// A handle to a window with a specific root view type.
5189/// Note that this does not keep the window alive on its own.
5190#[derive(Deref, DerefMut)]
5191pub struct WindowHandle<V> {
5192 #[deref]
5193 #[deref_mut]
5194 pub(crate) any_handle: AnyWindowHandle,
5195 state_type: PhantomData<fn(V) -> V>,
5196}
5197
5198impl<V> Debug for WindowHandle<V> {
5199 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
5200 f.debug_struct("WindowHandle")
5201 .field("any_handle", &self.any_handle.id.as_u64())
5202 .finish()
5203 }
5204}
5205
5206impl<V: 'static + Render> WindowHandle<V> {
5207 /// Creates a new handle from a window ID.
5208 /// This does not check if the root type of the window is `V`.
5209 pub fn new(id: WindowId) -> Self {
5210 WindowHandle {
5211 any_handle: AnyWindowHandle {
5212 id,
5213 state_type: TypeId::of::<V>(),
5214 },
5215 state_type: PhantomData,
5216 }
5217 }
5218
5219 /// Get the root view out of this window.
5220 ///
5221 /// This will fail if the window is closed or if the root view's type does not match `V`.
5222 #[cfg(any(test, feature = "test-support"))]
5223 pub fn root<C>(&self, cx: &mut C) -> Result<Entity<V>>
5224 where
5225 C: AppContext,
5226 {
5227 cx.update_window(self.any_handle, |root_view, _, _| {
5228 root_view
5229 .downcast::<V>()
5230 .map_err(|_| anyhow!("the type of the window's root view has changed"))
5231 })?
5232 }
5233
5234 /// Updates the root view of this window.
5235 ///
5236 /// This will fail if the window has been closed or if the root view's type does not match
5237 pub fn update<C, R>(
5238 &self,
5239 cx: &mut C,
5240 update: impl FnOnce(&mut V, &mut Window, &mut Context<V>) -> R,
5241 ) -> Result<R>
5242 where
5243 C: AppContext,
5244 {
5245 cx.update_window(self.any_handle, |root_view, window, cx| {
5246 let view = root_view
5247 .downcast::<V>()
5248 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
5249
5250 Ok(view.update(cx, |view, cx| update(view, window, cx)))
5251 })?
5252 }
5253
5254 /// Read the root view out of this window.
5255 ///
5256 /// This will fail if the window is closed or if the root view's type does not match `V`.
5257 pub fn read<'a>(&self, cx: &'a App) -> Result<&'a V> {
5258 let x = cx
5259 .windows
5260 .get(self.id)
5261 .and_then(|window| {
5262 window
5263 .as_deref()
5264 .and_then(|window| window.root.clone())
5265 .map(|root_view| root_view.downcast::<V>())
5266 })
5267 .context("window not found")?
5268 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
5269
5270 Ok(x.read(cx))
5271 }
5272
5273 /// Read the root view out of this window, with a callback
5274 ///
5275 /// This will fail if the window is closed or if the root view's type does not match `V`.
5276 pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &App) -> R) -> Result<R>
5277 where
5278 C: AppContext,
5279 {
5280 cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
5281 }
5282
5283 /// Read the root view pointer off of this window.
5284 ///
5285 /// This will fail if the window is closed or if the root view's type does not match `V`.
5286 pub fn entity<C>(&self, cx: &C) -> Result<Entity<V>>
5287 where
5288 C: AppContext,
5289 {
5290 cx.read_window(self, |root_view, _cx| root_view)
5291 }
5292
5293 /// Check if this window is 'active'.
5294 ///
5295 /// Will return `None` if the window is closed or currently
5296 /// borrowed.
5297 pub fn is_active(&self, cx: &mut App) -> Option<bool> {
5298 cx.update_window(self.any_handle, |_, window, _| window.is_window_active())
5299 .ok()
5300 }
5301}
5302
5303impl<V> Copy for WindowHandle<V> {}
5304
5305impl<V> Clone for WindowHandle<V> {
5306 fn clone(&self) -> Self {
5307 *self
5308 }
5309}
5310
5311impl<V> PartialEq for WindowHandle<V> {
5312 fn eq(&self, other: &Self) -> bool {
5313 self.any_handle == other.any_handle
5314 }
5315}
5316
5317impl<V> Eq for WindowHandle<V> {}
5318
5319impl<V> Hash for WindowHandle<V> {
5320 fn hash<H: Hasher>(&self, state: &mut H) {
5321 self.any_handle.hash(state);
5322 }
5323}
5324
5325impl<V: 'static> From<WindowHandle<V>> for AnyWindowHandle {
5326 fn from(val: WindowHandle<V>) -> Self {
5327 val.any_handle
5328 }
5329}
5330
5331/// A handle to a window with any root view type, which can be downcast to a window with a specific root view type.
5332#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
5333pub struct AnyWindowHandle {
5334 pub(crate) id: WindowId,
5335 state_type: TypeId,
5336}
5337
5338impl AnyWindowHandle {
5339 /// Get the ID of this window.
5340 pub fn window_id(&self) -> WindowId {
5341 self.id
5342 }
5343
5344 /// Attempt to convert this handle to a window handle with a specific root view type.
5345 /// If the types do not match, this will return `None`.
5346 pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
5347 if TypeId::of::<T>() == self.state_type {
5348 Some(WindowHandle {
5349 any_handle: *self,
5350 state_type: PhantomData,
5351 })
5352 } else {
5353 None
5354 }
5355 }
5356
5357 /// Updates the state of the root view of this window.
5358 ///
5359 /// This will fail if the window has been closed.
5360 pub fn update<C, R>(
5361 self,
5362 cx: &mut C,
5363 update: impl FnOnce(AnyView, &mut Window, &mut App) -> R,
5364 ) -> Result<R>
5365 where
5366 C: AppContext,
5367 {
5368 cx.update_window(self, update)
5369 }
5370
5371 /// Read the state of the root view of this window.
5372 ///
5373 /// This will fail if the window has been closed.
5374 pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(Entity<T>, &App) -> R) -> Result<R>
5375 where
5376 C: AppContext,
5377 T: 'static,
5378 {
5379 let view = self
5380 .downcast::<T>()
5381 .context("the type of the window's root view has changed")?;
5382
5383 cx.read_window(&view, read)
5384 }
5385}
5386
5387impl HasWindowHandle for Window {
5388 fn window_handle(&self) -> Result<raw_window_handle::WindowHandle<'_>, HandleError> {
5389 self.platform_window.window_handle()
5390 }
5391}
5392
5393impl HasDisplayHandle for Window {
5394 fn display_handle(
5395 &self,
5396 ) -> std::result::Result<raw_window_handle::DisplayHandle<'_>, HandleError> {
5397 self.platform_window.display_handle()
5398 }
5399}
5400
5401/// An identifier for an [`Element`].
5402///
5403/// Can be constructed with a string, a number, or both, as well
5404/// as other internal representations.
5405#[derive(Clone, Debug, Eq, PartialEq, Hash)]
5406pub enum ElementId {
5407 /// The ID of a View element
5408 View(EntityId),
5409 /// An integer ID.
5410 Integer(u64),
5411 /// A string based ID.
5412 Name(SharedString),
5413 /// A UUID.
5414 Uuid(Uuid),
5415 /// An ID that's equated with a focus handle.
5416 FocusHandle(FocusId),
5417 /// A combination of a name and an integer.
5418 NamedInteger(SharedString, u64),
5419 /// A path.
5420 Path(Arc<std::path::Path>),
5421 /// A code location.
5422 CodeLocation(core::panic::Location<'static>),
5423 /// A labeled child of an element.
5424 NamedChild(Arc<ElementId>, SharedString),
5425}
5426
5427impl ElementId {
5428 /// Constructs an `ElementId::NamedInteger` from a name and `usize`.
5429 pub fn named_usize(name: impl Into<SharedString>, integer: usize) -> ElementId {
5430 Self::NamedInteger(name.into(), integer as u64)
5431 }
5432}
5433
5434impl Display for ElementId {
5435 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
5436 match self {
5437 ElementId::View(entity_id) => write!(f, "view-{}", entity_id)?,
5438 ElementId::Integer(ix) => write!(f, "{}", ix)?,
5439 ElementId::Name(name) => write!(f, "{}", name)?,
5440 ElementId::FocusHandle(_) => write!(f, "FocusHandle")?,
5441 ElementId::NamedInteger(s, i) => write!(f, "{}-{}", s, i)?,
5442 ElementId::Uuid(uuid) => write!(f, "{}", uuid)?,
5443 ElementId::Path(path) => write!(f, "{}", path.display())?,
5444 ElementId::CodeLocation(location) => write!(f, "{}", location)?,
5445 ElementId::NamedChild(id, name) => write!(f, "{}-{}", id, name)?,
5446 }
5447
5448 Ok(())
5449 }
5450}
5451
5452impl TryInto<SharedString> for ElementId {
5453 type Error = anyhow::Error;
5454
5455 fn try_into(self) -> anyhow::Result<SharedString> {
5456 if let ElementId::Name(name) = self {
5457 Ok(name)
5458 } else {
5459 anyhow::bail!("element id is not string")
5460 }
5461 }
5462}
5463
5464impl From<usize> for ElementId {
5465 fn from(id: usize) -> Self {
5466 ElementId::Integer(id as u64)
5467 }
5468}
5469
5470impl From<i32> for ElementId {
5471 fn from(id: i32) -> Self {
5472 Self::Integer(id as u64)
5473 }
5474}
5475
5476impl From<SharedString> for ElementId {
5477 fn from(name: SharedString) -> Self {
5478 ElementId::Name(name)
5479 }
5480}
5481
5482impl From<String> for ElementId {
5483 fn from(name: String) -> Self {
5484 ElementId::Name(name.into())
5485 }
5486}
5487
5488impl From<Arc<str>> for ElementId {
5489 fn from(name: Arc<str>) -> Self {
5490 ElementId::Name(name.into())
5491 }
5492}
5493
5494impl From<Arc<std::path::Path>> for ElementId {
5495 fn from(path: Arc<std::path::Path>) -> Self {
5496 ElementId::Path(path)
5497 }
5498}
5499
5500impl From<&'static str> for ElementId {
5501 fn from(name: &'static str) -> Self {
5502 ElementId::Name(name.into())
5503 }
5504}
5505
5506impl<'a> From<&'a FocusHandle> for ElementId {
5507 fn from(handle: &'a FocusHandle) -> Self {
5508 ElementId::FocusHandle(handle.id)
5509 }
5510}
5511
5512impl From<(&'static str, EntityId)> for ElementId {
5513 fn from((name, id): (&'static str, EntityId)) -> Self {
5514 ElementId::NamedInteger(name.into(), id.as_u64())
5515 }
5516}
5517
5518impl From<(&'static str, usize)> for ElementId {
5519 fn from((name, id): (&'static str, usize)) -> Self {
5520 ElementId::NamedInteger(name.into(), id as u64)
5521 }
5522}
5523
5524impl From<(SharedString, usize)> for ElementId {
5525 fn from((name, id): (SharedString, usize)) -> Self {
5526 ElementId::NamedInteger(name, id as u64)
5527 }
5528}
5529
5530impl From<(&'static str, u64)> for ElementId {
5531 fn from((name, id): (&'static str, u64)) -> Self {
5532 ElementId::NamedInteger(name.into(), id)
5533 }
5534}
5535
5536impl From<Uuid> for ElementId {
5537 fn from(value: Uuid) -> Self {
5538 Self::Uuid(value)
5539 }
5540}
5541
5542impl From<(&'static str, u32)> for ElementId {
5543 fn from((name, id): (&'static str, u32)) -> Self {
5544 ElementId::NamedInteger(name.into(), id.into())
5545 }
5546}
5547
5548impl<T: Into<SharedString>> From<(ElementId, T)> for ElementId {
5549 fn from((id, name): (ElementId, T)) -> Self {
5550 ElementId::NamedChild(Arc::new(id), name.into())
5551 }
5552}
5553
5554impl From<&'static core::panic::Location<'static>> for ElementId {
5555 fn from(location: &'static core::panic::Location<'static>) -> Self {
5556 ElementId::CodeLocation(*location)
5557 }
5558}
5559
5560/// A rectangle to be rendered in the window at the given position and size.
5561/// Passed as an argument [`Window::paint_quad`].
5562#[derive(Clone)]
5563pub struct PaintQuad {
5564 /// The bounds of the quad within the window.
5565 pub bounds: Bounds<Pixels>,
5566 /// The radii of the quad's corners.
5567 pub corner_radii: Corners<Pixels>,
5568 /// The background color of the quad.
5569 pub background: Background,
5570 /// The widths of the quad's borders.
5571 pub border_widths: Edges<Pixels>,
5572 /// The color of the quad's borders.
5573 pub border_color: Hsla,
5574 /// The style of the quad's borders.
5575 pub border_style: BorderStyle,
5576}
5577
5578impl PaintQuad {
5579 /// Sets the corner radii of the quad.
5580 pub fn corner_radii(self, corner_radii: impl Into<Corners<Pixels>>) -> Self {
5581 PaintQuad {
5582 corner_radii: corner_radii.into(),
5583 ..self
5584 }
5585 }
5586
5587 /// Sets the border widths of the quad.
5588 pub fn border_widths(self, border_widths: impl Into<Edges<Pixels>>) -> Self {
5589 PaintQuad {
5590 border_widths: border_widths.into(),
5591 ..self
5592 }
5593 }
5594
5595 /// Sets the border color of the quad.
5596 pub fn border_color(self, border_color: impl Into<Hsla>) -> Self {
5597 PaintQuad {
5598 border_color: border_color.into(),
5599 ..self
5600 }
5601 }
5602
5603 /// Sets the background color of the quad.
5604 pub fn background(self, background: impl Into<Background>) -> Self {
5605 PaintQuad {
5606 background: background.into(),
5607 ..self
5608 }
5609 }
5610}
5611
5612/// Creates a quad with the given parameters.
5613pub fn quad(
5614 bounds: Bounds<Pixels>,
5615 corner_radii: impl Into<Corners<Pixels>>,
5616 background: impl Into<Background>,
5617 border_widths: impl Into<Edges<Pixels>>,
5618 border_color: impl Into<Hsla>,
5619 border_style: BorderStyle,
5620) -> PaintQuad {
5621 PaintQuad {
5622 bounds,
5623 corner_radii: corner_radii.into(),
5624 background: background.into(),
5625 border_widths: border_widths.into(),
5626 border_color: border_color.into(),
5627 border_style,
5628 }
5629}
5630
5631/// Creates a filled quad with the given bounds and background color.
5632pub fn fill(bounds: impl Into<Bounds<Pixels>>, background: impl Into<Background>) -> PaintQuad {
5633 PaintQuad {
5634 bounds: bounds.into(),
5635 corner_radii: (0.).into(),
5636 background: background.into(),
5637 border_widths: (0.).into(),
5638 border_color: transparent_black(),
5639 border_style: BorderStyle::default(),
5640 }
5641}
5642
5643/// Creates a rectangle outline with the given bounds, border color, and a 1px border width
5644pub fn outline(
5645 bounds: impl Into<Bounds<Pixels>>,
5646 border_color: impl Into<Hsla>,
5647 border_style: BorderStyle,
5648) -> PaintQuad {
5649 PaintQuad {
5650 bounds: bounds.into(),
5651 corner_radii: (0.).into(),
5652 background: transparent_black().into(),
5653 border_widths: (1.).into(),
5654 border_color: border_color.into(),
5655 border_style,
5656 }
5657}