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