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