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