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