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 let mut sorted_deferred_draws =
2348 (0..self.next_frame.deferred_draws.len()).collect::<SmallVec<[_; 8]>>();
2349 sorted_deferred_draws.sort_by_key(|ix| self.next_frame.deferred_draws[*ix].priority);
2350 self.prepaint_deferred_draws(&sorted_deferred_draws, cx);
2351
2352 let mut prompt_element = None;
2353 let mut active_drag_element = None;
2354 let mut tooltip_element = None;
2355 if let Some(prompt) = self.prompt.take() {
2356 let mut element = prompt.view.any_view().into_any();
2357 element.prepaint_as_root(Point::default(), root_size.into(), self, cx);
2358 prompt_element = Some(element);
2359 self.prompt = Some(prompt);
2360 } else if let Some(active_drag) = cx.active_drag.take() {
2361 let mut element = active_drag.view.clone().into_any();
2362 let offset = self.mouse_position() - active_drag.cursor_offset;
2363 element.prepaint_as_root(offset, AvailableSpace::min_size(), self, cx);
2364 active_drag_element = Some(element);
2365 cx.active_drag = Some(active_drag);
2366 } else {
2367 tooltip_element = self.prepaint_tooltip(cx);
2368 }
2369
2370 self.mouse_hit_test = self.next_frame.hit_test(self.mouse_position);
2371
2372 // Now actually paint the elements.
2373 self.invalidator.set_phase(DrawPhase::Paint);
2374 root_element.paint(self, cx);
2375
2376 #[cfg(any(feature = "inspector", debug_assertions))]
2377 self.paint_inspector(inspector_element, cx);
2378
2379 self.paint_deferred_draws(&sorted_deferred_draws, cx);
2380
2381 if let Some(mut prompt_element) = prompt_element {
2382 prompt_element.paint(self, cx);
2383 } else if let Some(mut drag_element) = active_drag_element {
2384 drag_element.paint(self, cx);
2385 } else if let Some(mut tooltip_element) = tooltip_element {
2386 tooltip_element.paint(self, cx);
2387 }
2388
2389 #[cfg(any(feature = "inspector", debug_assertions))]
2390 self.paint_inspector_hitbox(cx);
2391 }
2392
2393 fn prepaint_tooltip(&mut self, cx: &mut App) -> Option<AnyElement> {
2394 // Use indexing instead of iteration to avoid borrowing self for the duration of the loop.
2395 for tooltip_request_index in (0..self.next_frame.tooltip_requests.len()).rev() {
2396 let Some(Some(tooltip_request)) = self
2397 .next_frame
2398 .tooltip_requests
2399 .get(tooltip_request_index)
2400 .cloned()
2401 else {
2402 log::error!("Unexpectedly absent TooltipRequest");
2403 continue;
2404 };
2405 let mut element = tooltip_request.tooltip.view.clone().into_any();
2406 let mouse_position = tooltip_request.tooltip.mouse_position;
2407 let tooltip_size = element.layout_as_root(AvailableSpace::min_size(), self, cx);
2408
2409 let mut tooltip_bounds =
2410 Bounds::new(mouse_position + point(px(1.), px(1.)), tooltip_size);
2411 let window_bounds = Bounds {
2412 origin: Point::default(),
2413 size: self.viewport_size(),
2414 };
2415
2416 if tooltip_bounds.right() > window_bounds.right() {
2417 let new_x = mouse_position.x - tooltip_bounds.size.width - px(1.);
2418 if new_x >= Pixels::ZERO {
2419 tooltip_bounds.origin.x = new_x;
2420 } else {
2421 tooltip_bounds.origin.x = cmp::max(
2422 Pixels::ZERO,
2423 tooltip_bounds.origin.x - tooltip_bounds.right() - window_bounds.right(),
2424 );
2425 }
2426 }
2427
2428 if tooltip_bounds.bottom() > window_bounds.bottom() {
2429 let new_y = mouse_position.y - tooltip_bounds.size.height - px(1.);
2430 if new_y >= Pixels::ZERO {
2431 tooltip_bounds.origin.y = new_y;
2432 } else {
2433 tooltip_bounds.origin.y = cmp::max(
2434 Pixels::ZERO,
2435 tooltip_bounds.origin.y - tooltip_bounds.bottom() - window_bounds.bottom(),
2436 );
2437 }
2438 }
2439
2440 // It's possible for an element to have an active tooltip while not being painted (e.g.
2441 // via the `visible_on_hover` method). Since mouse listeners are not active in this
2442 // case, instead update the tooltip's visibility here.
2443 let is_visible =
2444 (tooltip_request.tooltip.check_visible_and_update)(tooltip_bounds, self, cx);
2445 if !is_visible {
2446 continue;
2447 }
2448
2449 self.with_absolute_element_offset(tooltip_bounds.origin, |window| {
2450 element.prepaint(window, cx)
2451 });
2452
2453 self.tooltip_bounds = Some(TooltipBounds {
2454 id: tooltip_request.id,
2455 bounds: tooltip_bounds,
2456 });
2457 return Some(element);
2458 }
2459 None
2460 }
2461
2462 fn prepaint_deferred_draws(&mut self, deferred_draw_indices: &[usize], cx: &mut App) {
2463 assert_eq!(self.element_id_stack.len(), 0);
2464
2465 let mut deferred_draws = mem::take(&mut self.next_frame.deferred_draws);
2466 for deferred_draw_ix in deferred_draw_indices {
2467 let deferred_draw = &mut deferred_draws[*deferred_draw_ix];
2468 self.element_id_stack
2469 .clone_from(&deferred_draw.element_id_stack);
2470 self.text_style_stack
2471 .clone_from(&deferred_draw.text_style_stack);
2472 self.next_frame
2473 .dispatch_tree
2474 .set_active_node(deferred_draw.parent_node);
2475
2476 let prepaint_start = self.prepaint_index();
2477 let content_mask = deferred_draw.content_mask.clone();
2478 if let Some(element) = deferred_draw.element.as_mut() {
2479 self.with_rendered_view(deferred_draw.current_view, |window| {
2480 window.with_content_mask(content_mask, |window| {
2481 window.with_rem_size(Some(deferred_draw.rem_size), |window| {
2482 window.with_absolute_element_offset(
2483 deferred_draw.absolute_offset,
2484 |window| {
2485 element.prepaint(window, cx);
2486 },
2487 );
2488 });
2489 });
2490 })
2491 } else {
2492 self.reuse_prepaint(deferred_draw.prepaint_range.clone());
2493 }
2494 let prepaint_end = self.prepaint_index();
2495 deferred_draw.prepaint_range = prepaint_start..prepaint_end;
2496 }
2497 assert_eq!(
2498 self.next_frame.deferred_draws.len(),
2499 0,
2500 "cannot call defer_draw during deferred drawing"
2501 );
2502 self.next_frame.deferred_draws = deferred_draws;
2503 self.element_id_stack.clear();
2504 self.text_style_stack.clear();
2505 }
2506
2507 fn paint_deferred_draws(&mut self, deferred_draw_indices: &[usize], cx: &mut App) {
2508 assert_eq!(self.element_id_stack.len(), 0);
2509
2510 let mut deferred_draws = mem::take(&mut self.next_frame.deferred_draws);
2511 for deferred_draw_ix in deferred_draw_indices {
2512 let mut deferred_draw = &mut deferred_draws[*deferred_draw_ix];
2513 self.element_id_stack
2514 .clone_from(&deferred_draw.element_id_stack);
2515 self.next_frame
2516 .dispatch_tree
2517 .set_active_node(deferred_draw.parent_node);
2518
2519 let paint_start = self.paint_index();
2520 let content_mask = deferred_draw.content_mask.clone();
2521 if let Some(element) = deferred_draw.element.as_mut() {
2522 self.with_rendered_view(deferred_draw.current_view, |window| {
2523 window.with_content_mask(content_mask, |window| {
2524 window.with_rem_size(Some(deferred_draw.rem_size), |window| {
2525 element.paint(window, cx);
2526 });
2527 })
2528 })
2529 } else {
2530 self.reuse_paint(deferred_draw.paint_range.clone());
2531 }
2532 let paint_end = self.paint_index();
2533 deferred_draw.paint_range = paint_start..paint_end;
2534 }
2535 self.next_frame.deferred_draws = deferred_draws;
2536 self.element_id_stack.clear();
2537 }
2538
2539 pub(crate) fn prepaint_index(&self) -> PrepaintStateIndex {
2540 PrepaintStateIndex {
2541 hitboxes_index: self.next_frame.hitboxes.len(),
2542 tooltips_index: self.next_frame.tooltip_requests.len(),
2543 deferred_draws_index: self.next_frame.deferred_draws.len(),
2544 dispatch_tree_index: self.next_frame.dispatch_tree.len(),
2545 accessed_element_states_index: self.next_frame.accessed_element_states.len(),
2546 line_layout_index: self.text_system.layout_index(),
2547 }
2548 }
2549
2550 pub(crate) fn reuse_prepaint(&mut self, range: Range<PrepaintStateIndex>) {
2551 self.next_frame.hitboxes.extend(
2552 self.rendered_frame.hitboxes[range.start.hitboxes_index..range.end.hitboxes_index]
2553 .iter()
2554 .cloned(),
2555 );
2556 self.next_frame.tooltip_requests.extend(
2557 self.rendered_frame.tooltip_requests
2558 [range.start.tooltips_index..range.end.tooltips_index]
2559 .iter_mut()
2560 .map(|request| request.take()),
2561 );
2562 self.next_frame.accessed_element_states.extend(
2563 self.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
2564 ..range.end.accessed_element_states_index]
2565 .iter()
2566 .map(|(id, type_id)| (id.clone(), *type_id)),
2567 );
2568 self.text_system
2569 .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
2570
2571 let reused_subtree = self.next_frame.dispatch_tree.reuse_subtree(
2572 range.start.dispatch_tree_index..range.end.dispatch_tree_index,
2573 &mut self.rendered_frame.dispatch_tree,
2574 self.focus,
2575 );
2576
2577 if reused_subtree.contains_focus() {
2578 self.next_frame.focus = self.focus;
2579 }
2580
2581 self.next_frame.deferred_draws.extend(
2582 self.rendered_frame.deferred_draws
2583 [range.start.deferred_draws_index..range.end.deferred_draws_index]
2584 .iter()
2585 .map(|deferred_draw| DeferredDraw {
2586 current_view: deferred_draw.current_view,
2587 parent_node: reused_subtree.refresh_node_id(deferred_draw.parent_node),
2588 element_id_stack: deferred_draw.element_id_stack.clone(),
2589 text_style_stack: deferred_draw.text_style_stack.clone(),
2590 content_mask: deferred_draw.content_mask.clone(),
2591 rem_size: deferred_draw.rem_size,
2592 priority: deferred_draw.priority,
2593 element: None,
2594 absolute_offset: deferred_draw.absolute_offset,
2595 prepaint_range: deferred_draw.prepaint_range.clone(),
2596 paint_range: deferred_draw.paint_range.clone(),
2597 }),
2598 );
2599 }
2600
2601 pub(crate) fn paint_index(&self) -> PaintIndex {
2602 PaintIndex {
2603 scene_index: self.next_frame.scene.len(),
2604 mouse_listeners_index: self.next_frame.mouse_listeners.len(),
2605 input_handlers_index: self.next_frame.input_handlers.len(),
2606 cursor_styles_index: self.next_frame.cursor_styles.len(),
2607 accessed_element_states_index: self.next_frame.accessed_element_states.len(),
2608 tab_handle_index: self.next_frame.tab_stops.paint_index(),
2609 line_layout_index: self.text_system.layout_index(),
2610 }
2611 }
2612
2613 pub(crate) fn reuse_paint(&mut self, range: Range<PaintIndex>) {
2614 self.next_frame.cursor_styles.extend(
2615 self.rendered_frame.cursor_styles
2616 [range.start.cursor_styles_index..range.end.cursor_styles_index]
2617 .iter()
2618 .cloned(),
2619 );
2620 self.next_frame.input_handlers.extend(
2621 self.rendered_frame.input_handlers
2622 [range.start.input_handlers_index..range.end.input_handlers_index]
2623 .iter_mut()
2624 .map(|handler| handler.take()),
2625 );
2626 self.next_frame.mouse_listeners.extend(
2627 self.rendered_frame.mouse_listeners
2628 [range.start.mouse_listeners_index..range.end.mouse_listeners_index]
2629 .iter_mut()
2630 .map(|listener| listener.take()),
2631 );
2632 self.next_frame.accessed_element_states.extend(
2633 self.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
2634 ..range.end.accessed_element_states_index]
2635 .iter()
2636 .map(|(id, type_id)| (id.clone(), *type_id)),
2637 );
2638 self.next_frame.tab_stops.replay(
2639 &self.rendered_frame.tab_stops.insertion_history
2640 [range.start.tab_handle_index..range.end.tab_handle_index],
2641 );
2642
2643 self.text_system
2644 .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
2645 self.next_frame.scene.replay(
2646 range.start.scene_index..range.end.scene_index,
2647 &self.rendered_frame.scene,
2648 );
2649 }
2650
2651 /// Push a text style onto the stack, and call a function with that style active.
2652 /// Use [`Window::text_style`] to get the current, combined text style. This method
2653 /// should only be called as part of element drawing.
2654 // This function is called in a highly recursive manner in editor
2655 // prepainting, make sure its inlined to reduce the stack burden
2656 #[inline]
2657 pub fn with_text_style<F, R>(&mut self, style: Option<TextStyleRefinement>, f: F) -> R
2658 where
2659 F: FnOnce(&mut Self) -> R,
2660 {
2661 self.invalidator.debug_assert_paint_or_prepaint();
2662 if let Some(style) = style {
2663 self.text_style_stack.push(style);
2664 let result = f(self);
2665 self.text_style_stack.pop();
2666 result
2667 } else {
2668 f(self)
2669 }
2670 }
2671
2672 /// Updates the cursor style at the platform level. This method should only be called
2673 /// during the paint phase of element drawing.
2674 pub fn set_cursor_style(&mut self, style: CursorStyle, hitbox: &Hitbox) {
2675 self.invalidator.debug_assert_paint();
2676 self.next_frame.cursor_styles.push(CursorStyleRequest {
2677 hitbox_id: Some(hitbox.id),
2678 style,
2679 });
2680 }
2681
2682 /// Updates the cursor style for the entire window at the platform level. A cursor
2683 /// style using this method will have precedence over any cursor style set using
2684 /// `set_cursor_style`. This method should only be called during the paint
2685 /// phase of element drawing.
2686 pub fn set_window_cursor_style(&mut self, style: CursorStyle) {
2687 self.invalidator.debug_assert_paint();
2688 self.next_frame.cursor_styles.push(CursorStyleRequest {
2689 hitbox_id: None,
2690 style,
2691 })
2692 }
2693
2694 /// Sets a tooltip to be rendered for the upcoming frame. This method should only be called
2695 /// during the paint phase of element drawing.
2696 pub fn set_tooltip(&mut self, tooltip: AnyTooltip) -> TooltipId {
2697 self.invalidator.debug_assert_prepaint();
2698 let id = TooltipId(post_inc(&mut self.next_tooltip_id.0));
2699 self.next_frame
2700 .tooltip_requests
2701 .push(Some(TooltipRequest { id, tooltip }));
2702 id
2703 }
2704
2705 /// Invoke the given function with the given content mask after intersecting it
2706 /// with the current mask. This method should only be called during element drawing.
2707 // This function is called in a highly recursive manner in editor
2708 // prepainting, make sure its inlined to reduce the stack burden
2709 #[inline]
2710 pub fn with_content_mask<R>(
2711 &mut self,
2712 mask: Option<ContentMask<Pixels>>,
2713 f: impl FnOnce(&mut Self) -> R,
2714 ) -> R {
2715 self.invalidator.debug_assert_paint_or_prepaint();
2716 if let Some(mask) = mask {
2717 let mask = mask.intersect(&self.content_mask());
2718 self.content_mask_stack.push(mask);
2719 let result = f(self);
2720 self.content_mask_stack.pop();
2721 result
2722 } else {
2723 f(self)
2724 }
2725 }
2726
2727 /// Updates the global element offset relative to the current offset. This is used to implement
2728 /// scrolling. This method should only be called during the prepaint phase of element drawing.
2729 pub fn with_element_offset<R>(
2730 &mut self,
2731 offset: Point<Pixels>,
2732 f: impl FnOnce(&mut Self) -> R,
2733 ) -> R {
2734 self.invalidator.debug_assert_prepaint();
2735
2736 if offset.is_zero() {
2737 return f(self);
2738 };
2739
2740 let abs_offset = self.element_offset() + offset;
2741 self.with_absolute_element_offset(abs_offset, f)
2742 }
2743
2744 /// Updates the global element offset based on the given offset. This is used to implement
2745 /// drag handles and other manual painting of elements. This method should only be called during
2746 /// the prepaint phase of element drawing.
2747 pub fn with_absolute_element_offset<R>(
2748 &mut self,
2749 offset: Point<Pixels>,
2750 f: impl FnOnce(&mut Self) -> R,
2751 ) -> R {
2752 self.invalidator.debug_assert_prepaint();
2753 self.element_offset_stack.push(offset);
2754 let result = f(self);
2755 self.element_offset_stack.pop();
2756 result
2757 }
2758
2759 pub(crate) fn with_element_opacity<R>(
2760 &mut self,
2761 opacity: Option<f32>,
2762 f: impl FnOnce(&mut Self) -> R,
2763 ) -> R {
2764 self.invalidator.debug_assert_paint_or_prepaint();
2765
2766 let Some(opacity) = opacity else {
2767 return f(self);
2768 };
2769
2770 let previous_opacity = self.element_opacity;
2771 self.element_opacity = previous_opacity * opacity;
2772 let result = f(self);
2773 self.element_opacity = previous_opacity;
2774 result
2775 }
2776
2777 /// Perform prepaint on child elements in a "retryable" manner, so that any side effects
2778 /// of prepaints can be discarded before prepainting again. This is used to support autoscroll
2779 /// where we need to prepaint children to detect the autoscroll bounds, then adjust the
2780 /// element offset and prepaint again. See [`crate::List`] for an example. This method should only be
2781 /// called during the prepaint phase of element drawing.
2782 pub fn transact<T, U>(&mut self, f: impl FnOnce(&mut Self) -> Result<T, U>) -> Result<T, U> {
2783 self.invalidator.debug_assert_prepaint();
2784 let index = self.prepaint_index();
2785 let result = f(self);
2786 if result.is_err() {
2787 self.next_frame.hitboxes.truncate(index.hitboxes_index);
2788 self.next_frame
2789 .tooltip_requests
2790 .truncate(index.tooltips_index);
2791 self.next_frame
2792 .deferred_draws
2793 .truncate(index.deferred_draws_index);
2794 self.next_frame
2795 .dispatch_tree
2796 .truncate(index.dispatch_tree_index);
2797 self.next_frame
2798 .accessed_element_states
2799 .truncate(index.accessed_element_states_index);
2800 self.text_system.truncate_layouts(index.line_layout_index);
2801 }
2802 result
2803 }
2804
2805 /// When you call this method during [`Element::prepaint`], containing elements will attempt to
2806 /// scroll to cause the specified bounds to become visible. When they decide to autoscroll, they will call
2807 /// [`Element::prepaint`] again with a new set of bounds. See [`crate::List`] for an example of an element
2808 /// that supports this method being called on the elements it contains. This method should only be
2809 /// called during the prepaint phase of element drawing.
2810 pub fn request_autoscroll(&mut self, bounds: Bounds<Pixels>) {
2811 self.invalidator.debug_assert_prepaint();
2812 self.requested_autoscroll = Some(bounds);
2813 }
2814
2815 /// This method can be called from a containing element such as [`crate::List`] to support the autoscroll behavior
2816 /// described in [`Self::request_autoscroll`].
2817 pub fn take_autoscroll(&mut self) -> Option<Bounds<Pixels>> {
2818 self.invalidator.debug_assert_prepaint();
2819 self.requested_autoscroll.take()
2820 }
2821
2822 /// Asynchronously load an asset, if the asset hasn't finished loading this will return None.
2823 /// Your view will be re-drawn once the asset has finished loading.
2824 ///
2825 /// Note that the multiple calls to this method will only result in one `Asset::load` call at a
2826 /// time.
2827 pub fn use_asset<A: Asset>(&mut self, source: &A::Source, cx: &mut App) -> Option<A::Output> {
2828 let (task, is_first) = cx.fetch_asset::<A>(source);
2829 task.clone().now_or_never().or_else(|| {
2830 if is_first {
2831 let entity_id = self.current_view();
2832 self.spawn(cx, {
2833 let task = task.clone();
2834 async move |cx| {
2835 task.await;
2836
2837 cx.on_next_frame(move |_, cx| {
2838 cx.notify(entity_id);
2839 });
2840 }
2841 })
2842 .detach();
2843 }
2844
2845 None
2846 })
2847 }
2848
2849 /// Asynchronously load an asset, if the asset hasn't finished loading or doesn't exist this will return None.
2850 /// Your view will not 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 get_asset<A: Asset>(&mut self, source: &A::Source, cx: &mut App) -> Option<A::Output> {
2855 let (task, _) = cx.fetch_asset::<A>(source);
2856 task.now_or_never()
2857 }
2858 /// Obtain the current element offset. This method should only be called during the
2859 /// prepaint phase of element drawing.
2860 pub fn element_offset(&self) -> Point<Pixels> {
2861 self.invalidator.debug_assert_prepaint();
2862 self.element_offset_stack
2863 .last()
2864 .copied()
2865 .unwrap_or_default()
2866 }
2867
2868 /// Obtain the current element opacity. This method should only be called during the
2869 /// prepaint phase of element drawing.
2870 #[inline]
2871 pub(crate) fn element_opacity(&self) -> f32 {
2872 self.invalidator.debug_assert_paint_or_prepaint();
2873 self.element_opacity
2874 }
2875
2876 /// Obtain the current content mask. This method should only be called during element drawing.
2877 pub fn content_mask(&self) -> ContentMask<Pixels> {
2878 self.invalidator.debug_assert_paint_or_prepaint();
2879 self.content_mask_stack
2880 .last()
2881 .cloned()
2882 .unwrap_or_else(|| ContentMask {
2883 bounds: Bounds {
2884 origin: Point::default(),
2885 size: self.viewport_size,
2886 },
2887 })
2888 }
2889
2890 /// Provide elements in the called function with a new namespace in which their identifiers must be unique.
2891 /// This can be used within a custom element to distinguish multiple sets of child elements.
2892 pub fn with_element_namespace<R>(
2893 &mut self,
2894 element_id: impl Into<ElementId>,
2895 f: impl FnOnce(&mut Self) -> R,
2896 ) -> R {
2897 self.element_id_stack.push(element_id.into());
2898 let result = f(self);
2899 self.element_id_stack.pop();
2900 result
2901 }
2902
2903 /// Use a piece of state that exists as long this element is being rendered in consecutive frames.
2904 pub fn use_keyed_state<S: 'static>(
2905 &mut self,
2906 key: impl Into<ElementId>,
2907 cx: &mut App,
2908 init: impl FnOnce(&mut Self, &mut Context<S>) -> S,
2909 ) -> Entity<S> {
2910 let current_view = self.current_view();
2911 self.with_global_id(key.into(), |global_id, window| {
2912 window.with_element_state(global_id, |state: Option<Entity<S>>, window| {
2913 if let Some(state) = state {
2914 (state.clone(), state)
2915 } else {
2916 let new_state = cx.new(|cx| init(window, cx));
2917 cx.observe(&new_state, move |_, cx| {
2918 cx.notify(current_view);
2919 })
2920 .detach();
2921 (new_state.clone(), new_state)
2922 }
2923 })
2924 })
2925 }
2926
2927 /// Use a piece of state that exists as long this element is being rendered in consecutive frames, without needing to specify a key
2928 ///
2929 /// NOTE: This method uses the location of the caller to generate an ID for this state.
2930 /// If this is not sufficient to identify your state (e.g. you're rendering a list item),
2931 /// you can provide a custom ElementID using the `use_keyed_state` method.
2932 #[track_caller]
2933 pub fn use_state<S: 'static>(
2934 &mut self,
2935 cx: &mut App,
2936 init: impl FnOnce(&mut Self, &mut Context<S>) -> S,
2937 ) -> Entity<S> {
2938 self.use_keyed_state(
2939 ElementId::CodeLocation(*core::panic::Location::caller()),
2940 cx,
2941 init,
2942 )
2943 }
2944
2945 /// Updates or initializes state for an element with the given id that lives across multiple
2946 /// frames. If an element with this ID existed in the rendered frame, its state will be passed
2947 /// to the given closure. The state returned by the closure will be stored so it can be referenced
2948 /// when drawing the next frame. This method should only be called as part of element drawing.
2949 pub fn with_element_state<S, R>(
2950 &mut self,
2951 global_id: &GlobalElementId,
2952 f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
2953 ) -> R
2954 where
2955 S: 'static,
2956 {
2957 self.invalidator.debug_assert_paint_or_prepaint();
2958
2959 let key = (global_id.clone(), TypeId::of::<S>());
2960 self.next_frame.accessed_element_states.push(key.clone());
2961
2962 if let Some(any) = self
2963 .next_frame
2964 .element_states
2965 .remove(&key)
2966 .or_else(|| self.rendered_frame.element_states.remove(&key))
2967 {
2968 let ElementStateBox {
2969 inner,
2970 #[cfg(debug_assertions)]
2971 type_name,
2972 } = any;
2973 // Using the extra inner option to avoid needing to reallocate a new box.
2974 let mut state_box = inner
2975 .downcast::<Option<S>>()
2976 .map_err(|_| {
2977 #[cfg(debug_assertions)]
2978 {
2979 anyhow::anyhow!(
2980 "invalid element state type for id, requested {:?}, actual: {:?}",
2981 std::any::type_name::<S>(),
2982 type_name
2983 )
2984 }
2985
2986 #[cfg(not(debug_assertions))]
2987 {
2988 anyhow::anyhow!(
2989 "invalid element state type for id, requested {:?}",
2990 std::any::type_name::<S>(),
2991 )
2992 }
2993 })
2994 .unwrap();
2995
2996 let state = state_box.take().expect(
2997 "reentrant call to with_element_state for the same state type and element id",
2998 );
2999 let (result, state) = f(Some(state), self);
3000 state_box.replace(state);
3001 self.next_frame.element_states.insert(
3002 key,
3003 ElementStateBox {
3004 inner: state_box,
3005 #[cfg(debug_assertions)]
3006 type_name,
3007 },
3008 );
3009 result
3010 } else {
3011 let (result, state) = f(None, self);
3012 self.next_frame.element_states.insert(
3013 key,
3014 ElementStateBox {
3015 inner: Box::new(Some(state)),
3016 #[cfg(debug_assertions)]
3017 type_name: std::any::type_name::<S>(),
3018 },
3019 );
3020 result
3021 }
3022 }
3023
3024 /// A variant of `with_element_state` that allows the element's id to be optional. This is a convenience
3025 /// method for elements where the element id may or may not be assigned. Prefer using `with_element_state`
3026 /// when the element is guaranteed to have an id.
3027 ///
3028 /// The first option means 'no ID provided'
3029 /// The second option means 'not yet initialized'
3030 pub fn with_optional_element_state<S, R>(
3031 &mut self,
3032 global_id: Option<&GlobalElementId>,
3033 f: impl FnOnce(Option<Option<S>>, &mut Self) -> (R, Option<S>),
3034 ) -> R
3035 where
3036 S: 'static,
3037 {
3038 self.invalidator.debug_assert_paint_or_prepaint();
3039
3040 if let Some(global_id) = global_id {
3041 self.with_element_state(global_id, |state, cx| {
3042 let (result, state) = f(Some(state), cx);
3043 let state =
3044 state.expect("you must return some state when you pass some element id");
3045 (result, state)
3046 })
3047 } else {
3048 let (result, state) = f(None, self);
3049 debug_assert!(
3050 state.is_none(),
3051 "you must not return an element state when passing None for the global id"
3052 );
3053 result
3054 }
3055 }
3056
3057 /// Executes the given closure within the context of a tab group.
3058 #[inline]
3059 pub fn with_tab_group<R>(&mut self, index: Option<isize>, f: impl FnOnce(&mut Self) -> R) -> R {
3060 if let Some(index) = index {
3061 self.next_frame.tab_stops.begin_group(index);
3062 let result = f(self);
3063 self.next_frame.tab_stops.end_group();
3064 result
3065 } else {
3066 f(self)
3067 }
3068 }
3069
3070 /// Defers the drawing of the given element, scheduling it to be painted on top of the currently-drawn tree
3071 /// at a later time. The `priority` parameter determines the drawing order relative to other deferred elements,
3072 /// with higher values being drawn on top.
3073 ///
3074 /// When `content_mask` is provided, the deferred element will be clipped to that region during
3075 /// both prepaint and paint. When `None`, no additional clipping is applied.
3076 ///
3077 /// This method should only be called as part of the prepaint phase of element drawing.
3078 pub fn defer_draw(
3079 &mut self,
3080 element: AnyElement,
3081 absolute_offset: Point<Pixels>,
3082 priority: usize,
3083 content_mask: Option<ContentMask<Pixels>>,
3084 ) {
3085 self.invalidator.debug_assert_prepaint();
3086 let parent_node = self.next_frame.dispatch_tree.active_node_id().unwrap();
3087 self.next_frame.deferred_draws.push(DeferredDraw {
3088 current_view: self.current_view(),
3089 parent_node,
3090 element_id_stack: self.element_id_stack.clone(),
3091 text_style_stack: self.text_style_stack.clone(),
3092 content_mask,
3093 rem_size: self.rem_size(),
3094 priority,
3095 element: Some(element),
3096 absolute_offset,
3097 prepaint_range: PrepaintStateIndex::default()..PrepaintStateIndex::default(),
3098 paint_range: PaintIndex::default()..PaintIndex::default(),
3099 });
3100 }
3101
3102 /// Creates a new painting layer for the specified bounds. A "layer" is a batch
3103 /// of geometry that are non-overlapping and have the same draw order. This is typically used
3104 /// for performance reasons.
3105 ///
3106 /// This method should only be called as part of the paint phase of element drawing.
3107 pub fn paint_layer<R>(&mut self, bounds: Bounds<Pixels>, f: impl FnOnce(&mut Self) -> R) -> R {
3108 self.invalidator.debug_assert_paint();
3109
3110 let scale_factor = self.scale_factor();
3111 let content_mask = self.content_mask();
3112 let clipped_bounds = bounds.intersect(&content_mask.bounds);
3113 if !clipped_bounds.is_empty() {
3114 self.next_frame
3115 .scene
3116 .push_layer(clipped_bounds.scale(scale_factor));
3117 }
3118
3119 let result = f(self);
3120
3121 if !clipped_bounds.is_empty() {
3122 self.next_frame.scene.pop_layer();
3123 }
3124
3125 result
3126 }
3127
3128 /// Paint one or more drop shadows into the scene for the next frame at the current z-index.
3129 ///
3130 /// This method should only be called as part of the paint phase of element drawing.
3131 pub fn paint_shadows(
3132 &mut self,
3133 bounds: Bounds<Pixels>,
3134 corner_radii: Corners<Pixels>,
3135 shadows: &[BoxShadow],
3136 ) {
3137 self.invalidator.debug_assert_paint();
3138
3139 let scale_factor = self.scale_factor();
3140 let content_mask = self.content_mask();
3141 let opacity = self.element_opacity();
3142 for shadow in shadows {
3143 let shadow_bounds = (bounds + shadow.offset).dilate(shadow.spread_radius);
3144 self.next_frame.scene.insert_primitive(Shadow {
3145 order: 0,
3146 blur_radius: shadow.blur_radius.scale(scale_factor),
3147 bounds: shadow_bounds.scale(scale_factor),
3148 content_mask: content_mask.scale(scale_factor),
3149 corner_radii: corner_radii.scale(scale_factor),
3150 color: shadow.color.opacity(opacity),
3151 });
3152 }
3153 }
3154
3155 /// Paint one or more quads into the scene for the next frame at the current stacking context.
3156 /// Quads are colored rectangular regions with an optional background, border, and corner radius.
3157 /// see [`fill`], [`outline`], and [`quad`] to construct this type.
3158 ///
3159 /// This method should only be called as part of the paint phase of element drawing.
3160 ///
3161 /// Note that the `quad.corner_radii` are allowed to exceed the bounds, creating sharp corners
3162 /// where the circular arcs meet. This will not display well when combined with dashed borders.
3163 /// Use `Corners::clamp_radii_for_quad_size` if the radii should fit within the bounds.
3164 pub fn paint_quad(&mut self, quad: PaintQuad) {
3165 self.invalidator.debug_assert_paint();
3166
3167 let scale_factor = self.scale_factor();
3168 let content_mask = self.content_mask();
3169 let opacity = self.element_opacity();
3170 self.next_frame.scene.insert_primitive(Quad {
3171 order: 0,
3172 bounds: quad.bounds.scale(scale_factor),
3173 content_mask: content_mask.scale(scale_factor),
3174 background: quad.background.opacity(opacity),
3175 border_color: quad.border_color.opacity(opacity),
3176 corner_radii: quad.corner_radii.scale(scale_factor),
3177 border_widths: quad.border_widths.scale(scale_factor),
3178 border_style: quad.border_style,
3179 });
3180 }
3181
3182 /// Paint the given `Path` into the scene for the next frame at the current z-index.
3183 ///
3184 /// This method should only be called as part of the paint phase of element drawing.
3185 pub fn paint_path(&mut self, mut path: Path<Pixels>, color: impl Into<Background>) {
3186 self.invalidator.debug_assert_paint();
3187
3188 let scale_factor = self.scale_factor();
3189 let content_mask = self.content_mask();
3190 let opacity = self.element_opacity();
3191 path.content_mask = content_mask;
3192 let color: Background = color.into();
3193 path.color = color.opacity(opacity);
3194 self.next_frame
3195 .scene
3196 .insert_primitive(path.scale(scale_factor));
3197 }
3198
3199 /// Paint an underline into the scene for the next frame at the current z-index.
3200 ///
3201 /// This method should only be called as part of the paint phase of element drawing.
3202 pub fn paint_underline(
3203 &mut self,
3204 origin: Point<Pixels>,
3205 width: Pixels,
3206 style: &UnderlineStyle,
3207 ) {
3208 self.invalidator.debug_assert_paint();
3209
3210 let scale_factor = self.scale_factor();
3211 let height = if style.wavy {
3212 style.thickness * 3.
3213 } else {
3214 style.thickness
3215 };
3216 let bounds = Bounds {
3217 origin,
3218 size: size(width, height),
3219 };
3220 let content_mask = self.content_mask();
3221 let element_opacity = self.element_opacity();
3222
3223 self.next_frame.scene.insert_primitive(Underline {
3224 order: 0,
3225 pad: 0,
3226 bounds: bounds.scale(scale_factor),
3227 content_mask: content_mask.scale(scale_factor),
3228 color: style.color.unwrap_or_default().opacity(element_opacity),
3229 thickness: style.thickness.scale(scale_factor),
3230 wavy: if style.wavy { 1 } else { 0 },
3231 });
3232 }
3233
3234 /// Paint a strikethrough into the scene for the next frame at the current z-index.
3235 ///
3236 /// This method should only be called as part of the paint phase of element drawing.
3237 pub fn paint_strikethrough(
3238 &mut self,
3239 origin: Point<Pixels>,
3240 width: Pixels,
3241 style: &StrikethroughStyle,
3242 ) {
3243 self.invalidator.debug_assert_paint();
3244
3245 let scale_factor = self.scale_factor();
3246 let height = style.thickness;
3247 let bounds = Bounds {
3248 origin,
3249 size: size(width, height),
3250 };
3251 let content_mask = self.content_mask();
3252 let opacity = self.element_opacity();
3253
3254 self.next_frame.scene.insert_primitive(Underline {
3255 order: 0,
3256 pad: 0,
3257 bounds: bounds.scale(scale_factor),
3258 content_mask: content_mask.scale(scale_factor),
3259 thickness: style.thickness.scale(scale_factor),
3260 color: style.color.unwrap_or_default().opacity(opacity),
3261 wavy: 0,
3262 });
3263 }
3264
3265 /// Paints a monochrome (non-emoji) glyph into the scene for the next frame at the current z-index.
3266 ///
3267 /// The y component of the origin is the baseline of the glyph.
3268 /// You should generally prefer to use the [`ShapedLine::paint`](crate::ShapedLine::paint) or
3269 /// [`WrappedLine::paint`](crate::WrappedLine::paint) methods in the [`TextSystem`](crate::TextSystem).
3270 /// This method is only useful if you need to paint a single glyph that has already been shaped.
3271 ///
3272 /// This method should only be called as part of the paint phase of element drawing.
3273 pub fn paint_glyph(
3274 &mut self,
3275 origin: Point<Pixels>,
3276 font_id: FontId,
3277 glyph_id: GlyphId,
3278 font_size: Pixels,
3279 color: Hsla,
3280 ) -> Result<()> {
3281 self.invalidator.debug_assert_paint();
3282
3283 let element_opacity = self.element_opacity();
3284 let scale_factor = self.scale_factor();
3285 let glyph_origin = origin.scale(scale_factor);
3286
3287 let subpixel_variant = Point {
3288 x: (glyph_origin.x.0.fract() * SUBPIXEL_VARIANTS_X as f32).floor() as u8,
3289 y: (glyph_origin.y.0.fract() * SUBPIXEL_VARIANTS_Y as f32).floor() as u8,
3290 };
3291 let subpixel_rendering = self.should_use_subpixel_rendering(font_id, font_size);
3292 let params = RenderGlyphParams {
3293 font_id,
3294 glyph_id,
3295 font_size,
3296 subpixel_variant,
3297 scale_factor,
3298 is_emoji: false,
3299 subpixel_rendering,
3300 };
3301
3302 let raster_bounds = self.text_system().raster_bounds(¶ms)?;
3303 if !raster_bounds.is_zero() {
3304 let tile = self
3305 .sprite_atlas
3306 .get_or_insert_with(¶ms.clone().into(), &mut || {
3307 let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?;
3308 Ok(Some((size, Cow::Owned(bytes))))
3309 })?
3310 .expect("Callback above only errors or returns Some");
3311 let bounds = Bounds {
3312 origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
3313 size: tile.bounds.size.map(Into::into),
3314 };
3315 let content_mask = self.content_mask().scale(scale_factor);
3316
3317 if subpixel_rendering {
3318 self.next_frame.scene.insert_primitive(SubpixelSprite {
3319 order: 0,
3320 pad: 0,
3321 bounds,
3322 content_mask,
3323 color: color.opacity(element_opacity),
3324 tile,
3325 transformation: TransformationMatrix::unit(),
3326 });
3327 } else {
3328 self.next_frame.scene.insert_primitive(MonochromeSprite {
3329 order: 0,
3330 pad: 0,
3331 bounds,
3332 content_mask,
3333 color: color.opacity(element_opacity),
3334 tile,
3335 transformation: TransformationMatrix::unit(),
3336 });
3337 }
3338 }
3339 Ok(())
3340 }
3341
3342 /// Paints a monochrome glyph with pre-computed raster bounds.
3343 ///
3344 /// This is faster than `paint_glyph` because it skips the per-glyph cache lookup.
3345 /// Use `ShapedLine::compute_glyph_raster_data` to batch-compute raster bounds during prepaint.
3346 pub fn paint_glyph_with_raster_bounds(
3347 &mut self,
3348 origin: Point<Pixels>,
3349 _font_id: FontId,
3350 _glyph_id: GlyphId,
3351 _font_size: Pixels,
3352 color: Hsla,
3353 raster_bounds: Bounds<DevicePixels>,
3354 params: &RenderGlyphParams,
3355 ) -> Result<()> {
3356 self.invalidator.debug_assert_paint();
3357
3358 let element_opacity = self.element_opacity();
3359 let scale_factor = self.scale_factor();
3360 let glyph_origin = origin.scale(scale_factor);
3361
3362 if !raster_bounds.is_zero() {
3363 let tile = self
3364 .sprite_atlas
3365 .get_or_insert_with(¶ms.clone().into(), &mut || {
3366 let (size, bytes) = self.text_system().rasterize_glyph(params)?;
3367 Ok(Some((size, Cow::Owned(bytes))))
3368 })?
3369 .expect("Callback above only errors or returns Some");
3370 let bounds = Bounds {
3371 origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
3372 size: tile.bounds.size.map(Into::into),
3373 };
3374 let content_mask = self.content_mask().scale(scale_factor);
3375 self.next_frame.scene.insert_primitive(MonochromeSprite {
3376 order: 0,
3377 pad: 0,
3378 bounds,
3379 content_mask,
3380 color: color.opacity(element_opacity),
3381 tile,
3382 transformation: TransformationMatrix::unit(),
3383 });
3384 }
3385 Ok(())
3386 }
3387
3388 /// Paints an emoji glyph with pre-computed raster bounds.
3389 ///
3390 /// This is faster than `paint_emoji` because it skips the per-glyph cache lookup.
3391 /// Use `ShapedLine::compute_glyph_raster_data` to batch-compute raster bounds during prepaint.
3392 pub fn paint_emoji_with_raster_bounds(
3393 &mut self,
3394 origin: Point<Pixels>,
3395 _font_id: FontId,
3396 _glyph_id: GlyphId,
3397 _font_size: Pixels,
3398 raster_bounds: Bounds<DevicePixels>,
3399 params: &RenderGlyphParams,
3400 ) -> Result<()> {
3401 self.invalidator.debug_assert_paint();
3402
3403 let scale_factor = self.scale_factor();
3404 let glyph_origin = origin.scale(scale_factor);
3405
3406 if !raster_bounds.is_zero() {
3407 let tile = self
3408 .sprite_atlas
3409 .get_or_insert_with(¶ms.clone().into(), &mut || {
3410 let (size, bytes) = self.text_system().rasterize_glyph(params)?;
3411 Ok(Some((size, Cow::Owned(bytes))))
3412 })?
3413 .expect("Callback above only errors or returns Some");
3414
3415 let bounds = Bounds {
3416 origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
3417 size: tile.bounds.size.map(Into::into),
3418 };
3419 let content_mask = self.content_mask().scale(scale_factor);
3420 let opacity = self.element_opacity();
3421
3422 self.next_frame.scene.insert_primitive(PolychromeSprite {
3423 order: 0,
3424 pad: 0,
3425 grayscale: false,
3426 bounds,
3427 corner_radii: Default::default(),
3428 content_mask,
3429 tile,
3430 opacity,
3431 });
3432 }
3433 Ok(())
3434 }
3435
3436 fn should_use_subpixel_rendering(&self, font_id: FontId, font_size: Pixels) -> bool {
3437 if self.platform_window.background_appearance() != WindowBackgroundAppearance::Opaque {
3438 return false;
3439 }
3440
3441 if !self.platform_window.is_subpixel_rendering_supported() {
3442 return false;
3443 }
3444
3445 let mode = match self.text_rendering_mode.get() {
3446 TextRenderingMode::PlatformDefault => self
3447 .text_system()
3448 .recommended_rendering_mode(font_id, font_size),
3449 mode => mode,
3450 };
3451
3452 mode == TextRenderingMode::Subpixel
3453 }
3454
3455 /// Paints an emoji glyph into the scene for the next frame at the current z-index.
3456 ///
3457 /// The y component of the origin is the baseline of the glyph.
3458 /// You should generally prefer to use the [`ShapedLine::paint`](crate::ShapedLine::paint) or
3459 /// [`WrappedLine::paint`](crate::WrappedLine::paint) methods in the [`TextSystem`](crate::TextSystem).
3460 /// This method is only useful if you need to paint a single emoji that has already been shaped.
3461 ///
3462 /// This method should only be called as part of the paint phase of element drawing.
3463 pub fn paint_emoji(
3464 &mut self,
3465 origin: Point<Pixels>,
3466 font_id: FontId,
3467 glyph_id: GlyphId,
3468 font_size: Pixels,
3469 ) -> Result<()> {
3470 self.invalidator.debug_assert_paint();
3471
3472 let scale_factor = self.scale_factor();
3473 let glyph_origin = origin.scale(scale_factor);
3474 let params = RenderGlyphParams {
3475 font_id,
3476 glyph_id,
3477 font_size,
3478 // We don't render emojis with subpixel variants.
3479 subpixel_variant: Default::default(),
3480 scale_factor,
3481 is_emoji: true,
3482 subpixel_rendering: false,
3483 };
3484
3485 let raster_bounds = self.text_system().raster_bounds(¶ms)?;
3486 if !raster_bounds.is_zero() {
3487 let tile = self
3488 .sprite_atlas
3489 .get_or_insert_with(¶ms.clone().into(), &mut || {
3490 let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?;
3491 Ok(Some((size, Cow::Owned(bytes))))
3492 })?
3493 .expect("Callback above only errors or returns Some");
3494
3495 let bounds = Bounds {
3496 origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
3497 size: tile.bounds.size.map(Into::into),
3498 };
3499 let content_mask = self.content_mask().scale(scale_factor);
3500 let opacity = self.element_opacity();
3501
3502 self.next_frame.scene.insert_primitive(PolychromeSprite {
3503 order: 0,
3504 pad: 0,
3505 grayscale: false,
3506 bounds,
3507 corner_radii: Default::default(),
3508 content_mask,
3509 tile,
3510 opacity,
3511 });
3512 }
3513 Ok(())
3514 }
3515
3516 /// Paint a monochrome SVG into the scene for the next frame at the current stacking context.
3517 ///
3518 /// This method should only be called as part of the paint phase of element drawing.
3519 pub fn paint_svg(
3520 &mut self,
3521 bounds: Bounds<Pixels>,
3522 path: SharedString,
3523 mut data: Option<&[u8]>,
3524 transformation: TransformationMatrix,
3525 color: Hsla,
3526 cx: &App,
3527 ) -> Result<()> {
3528 self.invalidator.debug_assert_paint();
3529
3530 let element_opacity = self.element_opacity();
3531 let scale_factor = self.scale_factor();
3532
3533 let bounds = bounds.scale(scale_factor);
3534 let params = RenderSvgParams {
3535 path,
3536 size: bounds.size.map(|pixels| {
3537 DevicePixels::from((pixels.0 * SMOOTH_SVG_SCALE_FACTOR).ceil() as i32)
3538 }),
3539 };
3540
3541 let Some(tile) =
3542 self.sprite_atlas
3543 .get_or_insert_with(¶ms.clone().into(), &mut || {
3544 let Some((size, bytes)) = cx.svg_renderer.render_alpha_mask(¶ms, data)?
3545 else {
3546 return Ok(None);
3547 };
3548 Ok(Some((size, Cow::Owned(bytes))))
3549 })?
3550 else {
3551 return Ok(());
3552 };
3553 let content_mask = self.content_mask().scale(scale_factor);
3554 let svg_bounds = Bounds {
3555 origin: bounds.center()
3556 - Point::new(
3557 ScaledPixels(tile.bounds.size.width.0 as f32 / SMOOTH_SVG_SCALE_FACTOR / 2.),
3558 ScaledPixels(tile.bounds.size.height.0 as f32 / SMOOTH_SVG_SCALE_FACTOR / 2.),
3559 ),
3560 size: tile
3561 .bounds
3562 .size
3563 .map(|value| ScaledPixels(value.0 as f32 / SMOOTH_SVG_SCALE_FACTOR)),
3564 };
3565
3566 self.next_frame.scene.insert_primitive(MonochromeSprite {
3567 order: 0,
3568 pad: 0,
3569 bounds: svg_bounds
3570 .map_origin(|origin| origin.round())
3571 .map_size(|size| size.ceil()),
3572 content_mask,
3573 color: color.opacity(element_opacity),
3574 tile,
3575 transformation,
3576 });
3577
3578 Ok(())
3579 }
3580
3581 /// Paint an image into the scene for the next frame at the current z-index.
3582 /// This method will panic if the frame_index is not valid
3583 ///
3584 /// This method should only be called as part of the paint phase of element drawing.
3585 pub fn paint_image(
3586 &mut self,
3587 bounds: Bounds<Pixels>,
3588 corner_radii: Corners<Pixels>,
3589 data: Arc<RenderImage>,
3590 frame_index: usize,
3591 grayscale: bool,
3592 ) -> Result<()> {
3593 self.invalidator.debug_assert_paint();
3594
3595 let scale_factor = self.scale_factor();
3596 let bounds = bounds.scale(scale_factor);
3597 let params = RenderImageParams {
3598 image_id: data.id,
3599 frame_index,
3600 };
3601
3602 let tile = self
3603 .sprite_atlas
3604 .get_or_insert_with(¶ms.into(), &mut || {
3605 Ok(Some((
3606 data.size(frame_index),
3607 Cow::Borrowed(
3608 data.as_bytes(frame_index)
3609 .expect("It's the caller's job to pass a valid frame index"),
3610 ),
3611 )))
3612 })?
3613 .expect("Callback above only returns Some");
3614 let content_mask = self.content_mask().scale(scale_factor);
3615 let corner_radii = corner_radii.scale(scale_factor);
3616 let opacity = self.element_opacity();
3617
3618 self.next_frame.scene.insert_primitive(PolychromeSprite {
3619 order: 0,
3620 pad: 0,
3621 grayscale,
3622 bounds: bounds
3623 .map_origin(|origin| origin.floor())
3624 .map_size(|size| size.ceil()),
3625 content_mask,
3626 corner_radii,
3627 tile,
3628 opacity,
3629 });
3630 Ok(())
3631 }
3632
3633 /// Paint a surface into the scene for the next frame at the current z-index.
3634 ///
3635 /// This method should only be called as part of the paint phase of element drawing.
3636 #[cfg(target_os = "macos")]
3637 pub fn paint_surface(&mut self, bounds: Bounds<Pixels>, image_buffer: CVPixelBuffer) {
3638 use crate::PaintSurface;
3639
3640 self.invalidator.debug_assert_paint();
3641
3642 let scale_factor = self.scale_factor();
3643 let bounds = bounds.scale(scale_factor);
3644 let content_mask = self.content_mask().scale(scale_factor);
3645 self.next_frame.scene.insert_primitive(PaintSurface {
3646 order: 0,
3647 bounds,
3648 content_mask,
3649 image_buffer,
3650 });
3651 }
3652
3653 /// Removes an image from the sprite atlas.
3654 pub fn drop_image(&mut self, data: Arc<RenderImage>) -> Result<()> {
3655 for frame_index in 0..data.frame_count() {
3656 let params = RenderImageParams {
3657 image_id: data.id,
3658 frame_index,
3659 };
3660
3661 self.sprite_atlas.remove(¶ms.clone().into());
3662 }
3663
3664 Ok(())
3665 }
3666
3667 /// Add a node to the layout tree for the current frame. Takes the `Style` of the element for which
3668 /// layout is being requested, along with the layout ids of any children. This method is called during
3669 /// calls to the [`Element::request_layout`] trait method and enables any element to participate in layout.
3670 ///
3671 /// This method should only be called as part of the request_layout or prepaint phase of element drawing.
3672 #[must_use]
3673 pub fn request_layout(
3674 &mut self,
3675 style: Style,
3676 children: impl IntoIterator<Item = LayoutId>,
3677 cx: &mut App,
3678 ) -> LayoutId {
3679 self.invalidator.debug_assert_prepaint();
3680
3681 cx.layout_id_buffer.clear();
3682 cx.layout_id_buffer.extend(children);
3683 let rem_size = self.rem_size();
3684 let scale_factor = self.scale_factor();
3685
3686 self.layout_engine.as_mut().unwrap().request_layout(
3687 style,
3688 rem_size,
3689 scale_factor,
3690 &cx.layout_id_buffer,
3691 )
3692 }
3693
3694 /// Add a node to the layout tree for the current frame. Instead of taking a `Style` and children,
3695 /// this variant takes a function that is invoked during layout so you can use arbitrary logic to
3696 /// determine the element's size. One place this is used internally is when measuring text.
3697 ///
3698 /// The given closure is invoked at layout time with the known dimensions and available space and
3699 /// returns a `Size`.
3700 ///
3701 /// This method should only be called as part of the request_layout or prepaint phase of element drawing.
3702 pub fn request_measured_layout<F>(&mut self, style: Style, measure: F) -> LayoutId
3703 where
3704 F: Fn(Size<Option<Pixels>>, Size<AvailableSpace>, &mut Window, &mut App) -> Size<Pixels>
3705 + 'static,
3706 {
3707 self.invalidator.debug_assert_prepaint();
3708
3709 let rem_size = self.rem_size();
3710 let scale_factor = self.scale_factor();
3711 self.layout_engine
3712 .as_mut()
3713 .unwrap()
3714 .request_measured_layout(style, rem_size, scale_factor, measure)
3715 }
3716
3717 /// Compute the layout for the given id within the given available space.
3718 /// This method is called for its side effect, typically by the framework prior to painting.
3719 /// After calling it, you can request the bounds of the given layout node id or any descendant.
3720 ///
3721 /// This method should only be called as part of the prepaint phase of element drawing.
3722 pub fn compute_layout(
3723 &mut self,
3724 layout_id: LayoutId,
3725 available_space: Size<AvailableSpace>,
3726 cx: &mut App,
3727 ) {
3728 self.invalidator.debug_assert_prepaint();
3729
3730 let mut layout_engine = self.layout_engine.take().unwrap();
3731 layout_engine.compute_layout(layout_id, available_space, self, cx);
3732 self.layout_engine = Some(layout_engine);
3733 }
3734
3735 /// Obtain the bounds computed for the given LayoutId relative to the window. This method will usually be invoked by
3736 /// GPUI itself automatically in order to pass your element its `Bounds` automatically.
3737 ///
3738 /// This method should only be called as part of element drawing.
3739 pub fn layout_bounds(&mut self, layout_id: LayoutId) -> Bounds<Pixels> {
3740 self.invalidator.debug_assert_prepaint();
3741
3742 let scale_factor = self.scale_factor();
3743 let mut bounds = self
3744 .layout_engine
3745 .as_mut()
3746 .unwrap()
3747 .layout_bounds(layout_id, scale_factor)
3748 .map(Into::into);
3749 bounds.origin += self.element_offset();
3750 bounds
3751 }
3752
3753 /// This method should be called during `prepaint`. You can use
3754 /// the returned [Hitbox] during `paint` or in an event handler
3755 /// to determine whether the inserted hitbox was the topmost.
3756 ///
3757 /// This method should only be called as part of the prepaint phase of element drawing.
3758 pub fn insert_hitbox(&mut self, bounds: Bounds<Pixels>, behavior: HitboxBehavior) -> Hitbox {
3759 self.invalidator.debug_assert_prepaint();
3760
3761 let content_mask = self.content_mask();
3762 let mut id = self.next_hitbox_id;
3763 self.next_hitbox_id = self.next_hitbox_id.next();
3764 let hitbox = Hitbox {
3765 id,
3766 bounds,
3767 content_mask,
3768 behavior,
3769 };
3770 self.next_frame.hitboxes.push(hitbox.clone());
3771 hitbox
3772 }
3773
3774 /// Set a hitbox which will act as a control area of the platform window.
3775 ///
3776 /// This method should only be called as part of the paint phase of element drawing.
3777 pub fn insert_window_control_hitbox(&mut self, area: WindowControlArea, hitbox: Hitbox) {
3778 self.invalidator.debug_assert_paint();
3779 self.next_frame.window_control_hitboxes.push((area, hitbox));
3780 }
3781
3782 /// Sets the key context for the current element. This context will be used to translate
3783 /// keybindings into actions.
3784 ///
3785 /// This method should only be called as part of the paint phase of element drawing.
3786 pub fn set_key_context(&mut self, context: KeyContext) {
3787 self.invalidator.debug_assert_paint();
3788 self.next_frame.dispatch_tree.set_key_context(context);
3789 }
3790
3791 /// Sets the focus handle for the current element. This handle will be used to manage focus state
3792 /// and keyboard event dispatch for the element.
3793 ///
3794 /// This method should only be called as part of the prepaint phase of element drawing.
3795 pub fn set_focus_handle(&mut self, focus_handle: &FocusHandle, _: &App) {
3796 self.invalidator.debug_assert_prepaint();
3797 if focus_handle.is_focused(self) {
3798 self.next_frame.focus = Some(focus_handle.id);
3799 }
3800 self.next_frame.dispatch_tree.set_focus_id(focus_handle.id);
3801 }
3802
3803 /// Sets the view id for the current element, which will be used to manage view caching.
3804 ///
3805 /// This method should only be called as part of element prepaint. We plan on removing this
3806 /// method eventually when we solve some issues that require us to construct editor elements
3807 /// directly instead of always using editors via views.
3808 pub fn set_view_id(&mut self, view_id: EntityId) {
3809 self.invalidator.debug_assert_prepaint();
3810 self.next_frame.dispatch_tree.set_view_id(view_id);
3811 }
3812
3813 /// Get the entity ID for the currently rendering view
3814 pub fn current_view(&self) -> EntityId {
3815 self.invalidator.debug_assert_paint_or_prepaint();
3816 self.rendered_entity_stack.last().copied().unwrap()
3817 }
3818
3819 #[inline]
3820 pub(crate) fn with_rendered_view<R>(
3821 &mut self,
3822 id: EntityId,
3823 f: impl FnOnce(&mut Self) -> R,
3824 ) -> R {
3825 self.rendered_entity_stack.push(id);
3826 let result = f(self);
3827 self.rendered_entity_stack.pop();
3828 result
3829 }
3830
3831 /// Executes the provided function with the specified image cache.
3832 pub fn with_image_cache<F, R>(&mut self, image_cache: Option<AnyImageCache>, f: F) -> R
3833 where
3834 F: FnOnce(&mut Self) -> R,
3835 {
3836 if let Some(image_cache) = image_cache {
3837 self.image_cache_stack.push(image_cache);
3838 let result = f(self);
3839 self.image_cache_stack.pop();
3840 result
3841 } else {
3842 f(self)
3843 }
3844 }
3845
3846 /// Sets an input handler, such as [`ElementInputHandler`][element_input_handler], which interfaces with the
3847 /// platform to receive textual input with proper integration with concerns such
3848 /// as IME interactions. This handler will be active for the upcoming frame until the following frame is
3849 /// rendered.
3850 ///
3851 /// This method should only be called as part of the paint phase of element drawing.
3852 ///
3853 /// [element_input_handler]: crate::ElementInputHandler
3854 pub fn handle_input(
3855 &mut self,
3856 focus_handle: &FocusHandle,
3857 input_handler: impl InputHandler,
3858 cx: &App,
3859 ) {
3860 self.invalidator.debug_assert_paint();
3861
3862 if focus_handle.is_focused(self) {
3863 let cx = self.to_async(cx);
3864 self.next_frame
3865 .input_handlers
3866 .push(Some(PlatformInputHandler::new(cx, Box::new(input_handler))));
3867 }
3868 }
3869
3870 /// Register a mouse event listener on the window for the next frame. The type of event
3871 /// is determined by the first parameter of the given listener. When the next frame is rendered
3872 /// the listener will be cleared.
3873 ///
3874 /// This method should only be called as part of the paint phase of element drawing.
3875 pub fn on_mouse_event<Event: MouseEvent>(
3876 &mut self,
3877 mut listener: impl FnMut(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
3878 ) {
3879 self.invalidator.debug_assert_paint();
3880
3881 self.next_frame.mouse_listeners.push(Some(Box::new(
3882 move |event: &dyn Any, phase: DispatchPhase, window: &mut Window, cx: &mut App| {
3883 if let Some(event) = event.downcast_ref() {
3884 listener(event, phase, window, cx)
3885 }
3886 },
3887 )));
3888 }
3889
3890 /// Register a key event listener on this node for the next frame. The type of event
3891 /// is determined by the first parameter of the given listener. When the next frame is rendered
3892 /// the listener will be cleared.
3893 ///
3894 /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
3895 /// a specific need to register a listener yourself.
3896 ///
3897 /// This method should only be called as part of the paint phase of element drawing.
3898 pub fn on_key_event<Event: KeyEvent>(
3899 &mut self,
3900 listener: impl Fn(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
3901 ) {
3902 self.invalidator.debug_assert_paint();
3903
3904 self.next_frame.dispatch_tree.on_key_event(Rc::new(
3905 move |event: &dyn Any, phase, window: &mut Window, cx: &mut App| {
3906 if let Some(event) = event.downcast_ref::<Event>() {
3907 listener(event, phase, window, cx)
3908 }
3909 },
3910 ));
3911 }
3912
3913 /// Register a modifiers changed event listener on the window for the next frame.
3914 ///
3915 /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
3916 /// a specific need to register a global listener.
3917 ///
3918 /// This method should only be called as part of the paint phase of element drawing.
3919 pub fn on_modifiers_changed(
3920 &mut self,
3921 listener: impl Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static,
3922 ) {
3923 self.invalidator.debug_assert_paint();
3924
3925 self.next_frame.dispatch_tree.on_modifiers_changed(Rc::new(
3926 move |event: &ModifiersChangedEvent, window: &mut Window, cx: &mut App| {
3927 listener(event, window, cx)
3928 },
3929 ));
3930 }
3931
3932 /// Register a listener to be called when the given focus handle or one of its descendants receives focus.
3933 /// This does not fire if the given focus handle - or one of its descendants - was previously focused.
3934 /// Returns a subscription and persists until the subscription is dropped.
3935 pub fn on_focus_in(
3936 &mut self,
3937 handle: &FocusHandle,
3938 cx: &mut App,
3939 mut listener: impl FnMut(&mut Window, &mut App) + 'static,
3940 ) -> Subscription {
3941 let focus_id = handle.id;
3942 let (subscription, activate) =
3943 self.new_focus_listener(Box::new(move |event, window, cx| {
3944 if event.is_focus_in(focus_id) {
3945 listener(window, cx);
3946 }
3947 true
3948 }));
3949 cx.defer(move |_| activate());
3950 subscription
3951 }
3952
3953 /// Register a listener to be called when the given focus handle or one of its descendants loses focus.
3954 /// Returns a subscription and persists until the subscription is dropped.
3955 pub fn on_focus_out(
3956 &mut self,
3957 handle: &FocusHandle,
3958 cx: &mut App,
3959 mut listener: impl FnMut(FocusOutEvent, &mut Window, &mut App) + 'static,
3960 ) -> Subscription {
3961 let focus_id = handle.id;
3962 let (subscription, activate) =
3963 self.new_focus_listener(Box::new(move |event, window, cx| {
3964 if let Some(blurred_id) = event.previous_focus_path.last().copied()
3965 && event.is_focus_out(focus_id)
3966 {
3967 let event = FocusOutEvent {
3968 blurred: WeakFocusHandle {
3969 id: blurred_id,
3970 handles: Arc::downgrade(&cx.focus_handles),
3971 },
3972 };
3973 listener(event, window, cx)
3974 }
3975 true
3976 }));
3977 cx.defer(move |_| activate());
3978 subscription
3979 }
3980
3981 fn reset_cursor_style(&self, cx: &mut App) {
3982 // Set the cursor only if we're the active window.
3983 if self.is_window_hovered() {
3984 let style = self
3985 .rendered_frame
3986 .cursor_style(self)
3987 .unwrap_or(CursorStyle::Arrow);
3988 cx.platform.set_cursor_style(style);
3989 }
3990 }
3991
3992 /// Dispatch a given keystroke as though the user had typed it.
3993 /// You can create a keystroke with Keystroke::parse("").
3994 pub fn dispatch_keystroke(&mut self, keystroke: Keystroke, cx: &mut App) -> bool {
3995 let keystroke = keystroke.with_simulated_ime();
3996 let result = self.dispatch_event(
3997 PlatformInput::KeyDown(KeyDownEvent {
3998 keystroke: keystroke.clone(),
3999 is_held: false,
4000 prefer_character_input: false,
4001 }),
4002 cx,
4003 );
4004 if !result.propagate {
4005 return true;
4006 }
4007
4008 if let Some(input) = keystroke.key_char
4009 && let Some(mut input_handler) = self.platform_window.take_input_handler()
4010 {
4011 input_handler.dispatch_input(&input, self, cx);
4012 self.platform_window.set_input_handler(input_handler);
4013 return true;
4014 }
4015
4016 false
4017 }
4018
4019 /// Return a key binding string for an action, to display in the UI. Uses the highest precedence
4020 /// binding for the action (last binding added to the keymap).
4021 pub fn keystroke_text_for(&self, action: &dyn Action) -> String {
4022 self.highest_precedence_binding_for_action(action)
4023 .map(|binding| {
4024 binding
4025 .keystrokes()
4026 .iter()
4027 .map(ToString::to_string)
4028 .collect::<Vec<_>>()
4029 .join(" ")
4030 })
4031 .unwrap_or_else(|| action.name().to_string())
4032 }
4033
4034 /// Dispatch a mouse or keyboard event on the window.
4035 #[profiling::function]
4036 pub fn dispatch_event(&mut self, event: PlatformInput, cx: &mut App) -> DispatchEventResult {
4037 // Track input modality for focus-visible styling and hover suppression.
4038 // Hover is suppressed during keyboard modality so that keyboard navigation
4039 // doesn't show hover highlights on the item under the mouse cursor.
4040 let old_modality = self.last_input_modality;
4041 self.last_input_modality = match &event {
4042 PlatformInput::KeyDown(_) => InputModality::Keyboard,
4043 PlatformInput::MouseMove(_) | PlatformInput::MouseDown(_) => InputModality::Mouse,
4044 _ => self.last_input_modality,
4045 };
4046 if self.last_input_modality != old_modality {
4047 self.refresh();
4048 }
4049
4050 // Handlers may set this to false by calling `stop_propagation`.
4051 cx.propagate_event = true;
4052 // Handlers may set this to true by calling `prevent_default`.
4053 self.default_prevented = false;
4054
4055 let event = match event {
4056 // Track the mouse position with our own state, since accessing the platform
4057 // API for the mouse position can only occur on the main thread.
4058 PlatformInput::MouseMove(mouse_move) => {
4059 self.mouse_position = mouse_move.position;
4060 self.modifiers = mouse_move.modifiers;
4061 PlatformInput::MouseMove(mouse_move)
4062 }
4063 PlatformInput::MouseDown(mouse_down) => {
4064 self.mouse_position = mouse_down.position;
4065 self.modifiers = mouse_down.modifiers;
4066 PlatformInput::MouseDown(mouse_down)
4067 }
4068 PlatformInput::MouseUp(mouse_up) => {
4069 self.mouse_position = mouse_up.position;
4070 self.modifiers = mouse_up.modifiers;
4071 PlatformInput::MouseUp(mouse_up)
4072 }
4073 PlatformInput::MousePressure(mouse_pressure) => {
4074 PlatformInput::MousePressure(mouse_pressure)
4075 }
4076 PlatformInput::MouseExited(mouse_exited) => {
4077 self.modifiers = mouse_exited.modifiers;
4078 PlatformInput::MouseExited(mouse_exited)
4079 }
4080 PlatformInput::ModifiersChanged(modifiers_changed) => {
4081 self.modifiers = modifiers_changed.modifiers;
4082 self.capslock = modifiers_changed.capslock;
4083 PlatformInput::ModifiersChanged(modifiers_changed)
4084 }
4085 PlatformInput::ScrollWheel(scroll_wheel) => {
4086 self.mouse_position = scroll_wheel.position;
4087 self.modifiers = scroll_wheel.modifiers;
4088 PlatformInput::ScrollWheel(scroll_wheel)
4089 }
4090 #[cfg(any(target_os = "linux", target_os = "macos"))]
4091 PlatformInput::Pinch(pinch) => {
4092 self.mouse_position = pinch.position;
4093 self.modifiers = pinch.modifiers;
4094 PlatformInput::Pinch(pinch)
4095 }
4096 // Translate dragging and dropping of external files from the operating system
4097 // to internal drag and drop events.
4098 PlatformInput::FileDrop(file_drop) => match file_drop {
4099 FileDropEvent::Entered { position, paths } => {
4100 self.mouse_position = position;
4101 if cx.active_drag.is_none() {
4102 cx.active_drag = Some(AnyDrag {
4103 value: Arc::new(paths.clone()),
4104 view: cx.new(|_| paths).into(),
4105 cursor_offset: position,
4106 cursor_style: None,
4107 });
4108 }
4109 PlatformInput::MouseMove(MouseMoveEvent {
4110 position,
4111 pressed_button: Some(MouseButton::Left),
4112 modifiers: Modifiers::default(),
4113 })
4114 }
4115 FileDropEvent::Pending { position } => {
4116 self.mouse_position = position;
4117 PlatformInput::MouseMove(MouseMoveEvent {
4118 position,
4119 pressed_button: Some(MouseButton::Left),
4120 modifiers: Modifiers::default(),
4121 })
4122 }
4123 FileDropEvent::Submit { position } => {
4124 cx.activate(true);
4125 self.mouse_position = position;
4126 PlatformInput::MouseUp(MouseUpEvent {
4127 button: MouseButton::Left,
4128 position,
4129 modifiers: Modifiers::default(),
4130 click_count: 1,
4131 })
4132 }
4133 FileDropEvent::Exited => {
4134 cx.active_drag.take();
4135 PlatformInput::FileDrop(FileDropEvent::Exited)
4136 }
4137 },
4138 PlatformInput::KeyDown(_) | PlatformInput::KeyUp(_) => event,
4139 };
4140
4141 if let Some(any_mouse_event) = event.mouse_event() {
4142 self.dispatch_mouse_event(any_mouse_event, cx);
4143 } else if let Some(any_key_event) = event.keyboard_event() {
4144 self.dispatch_key_event(any_key_event, cx);
4145 }
4146
4147 if self.invalidator.is_dirty() {
4148 self.input_rate_tracker.borrow_mut().record_input();
4149 }
4150
4151 DispatchEventResult {
4152 propagate: cx.propagate_event,
4153 default_prevented: self.default_prevented,
4154 }
4155 }
4156
4157 fn dispatch_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
4158 let hit_test = self.rendered_frame.hit_test(self.mouse_position());
4159 if hit_test != self.mouse_hit_test {
4160 self.mouse_hit_test = hit_test;
4161 self.reset_cursor_style(cx);
4162 }
4163
4164 #[cfg(any(feature = "inspector", debug_assertions))]
4165 if self.is_inspector_picking(cx) {
4166 self.handle_inspector_mouse_event(event, cx);
4167 // When inspector is picking, all other mouse handling is skipped.
4168 return;
4169 }
4170
4171 let mut mouse_listeners = mem::take(&mut self.rendered_frame.mouse_listeners);
4172
4173 // Capture phase, events bubble from back to front. Handlers for this phase are used for
4174 // special purposes, such as detecting events outside of a given Bounds.
4175 for listener in &mut mouse_listeners {
4176 let listener = listener.as_mut().unwrap();
4177 listener(event, DispatchPhase::Capture, self, cx);
4178 if !cx.propagate_event {
4179 break;
4180 }
4181 }
4182
4183 // Bubble phase, where most normal handlers do their work.
4184 if cx.propagate_event {
4185 for listener in mouse_listeners.iter_mut().rev() {
4186 let listener = listener.as_mut().unwrap();
4187 listener(event, DispatchPhase::Bubble, self, cx);
4188 if !cx.propagate_event {
4189 break;
4190 }
4191 }
4192 }
4193
4194 self.rendered_frame.mouse_listeners = mouse_listeners;
4195
4196 if cx.has_active_drag() {
4197 if event.is::<MouseMoveEvent>() {
4198 // If this was a mouse move event, redraw the window so that the
4199 // active drag can follow the mouse cursor.
4200 self.refresh();
4201 } else if event.is::<MouseUpEvent>() {
4202 // If this was a mouse up event, cancel the active drag and redraw
4203 // the window.
4204 cx.active_drag = None;
4205 self.refresh();
4206 }
4207 }
4208
4209 // Auto-release pointer capture on mouse up
4210 if event.is::<MouseUpEvent>() && self.captured_hitbox.is_some() {
4211 self.captured_hitbox = None;
4212 }
4213 }
4214
4215 fn dispatch_key_event(&mut self, event: &dyn Any, cx: &mut App) {
4216 if self.invalidator.is_dirty() {
4217 self.draw(cx).clear();
4218 }
4219
4220 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
4221 let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
4222
4223 let mut keystroke: Option<Keystroke> = None;
4224
4225 if let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() {
4226 if event.modifiers.number_of_modifiers() == 0
4227 && self.pending_modifier.modifiers.number_of_modifiers() == 1
4228 && !self.pending_modifier.saw_keystroke
4229 {
4230 let key = match self.pending_modifier.modifiers {
4231 modifiers if modifiers.shift => Some("shift"),
4232 modifiers if modifiers.control => Some("control"),
4233 modifiers if modifiers.alt => Some("alt"),
4234 modifiers if modifiers.platform => Some("platform"),
4235 modifiers if modifiers.function => Some("function"),
4236 _ => None,
4237 };
4238 if let Some(key) = key {
4239 keystroke = Some(Keystroke {
4240 key: key.to_string(),
4241 key_char: None,
4242 modifiers: Modifiers::default(),
4243 });
4244 }
4245 }
4246
4247 if self.pending_modifier.modifiers.number_of_modifiers() == 0
4248 && event.modifiers.number_of_modifiers() == 1
4249 {
4250 self.pending_modifier.saw_keystroke = false
4251 }
4252 self.pending_modifier.modifiers = event.modifiers
4253 } else if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
4254 self.pending_modifier.saw_keystroke = true;
4255 keystroke = Some(key_down_event.keystroke.clone());
4256 }
4257
4258 let Some(keystroke) = keystroke else {
4259 self.finish_dispatch_key_event(event, dispatch_path, self.context_stack(), cx);
4260 return;
4261 };
4262
4263 cx.propagate_event = true;
4264 self.dispatch_keystroke_interceptors(event, self.context_stack(), cx);
4265 if !cx.propagate_event {
4266 self.finish_dispatch_key_event(event, dispatch_path, self.context_stack(), cx);
4267 return;
4268 }
4269
4270 let mut currently_pending = self.pending_input.take().unwrap_or_default();
4271 if currently_pending.focus.is_some() && currently_pending.focus != self.focus {
4272 currently_pending = PendingInput::default();
4273 }
4274
4275 let match_result = self.rendered_frame.dispatch_tree.dispatch_key(
4276 currently_pending.keystrokes,
4277 keystroke,
4278 &dispatch_path,
4279 );
4280
4281 if !match_result.to_replay.is_empty() {
4282 self.replay_pending_input(match_result.to_replay, cx);
4283 cx.propagate_event = true;
4284 }
4285
4286 if !match_result.pending.is_empty() {
4287 currently_pending.timer.take();
4288 currently_pending.keystrokes = match_result.pending;
4289 currently_pending.focus = self.focus;
4290
4291 let text_input_requires_timeout = event
4292 .downcast_ref::<KeyDownEvent>()
4293 .filter(|key_down| key_down.keystroke.key_char.is_some())
4294 .and_then(|_| self.platform_window.take_input_handler())
4295 .map_or(false, |mut input_handler| {
4296 let accepts = input_handler.accepts_text_input(self, cx);
4297 self.platform_window.set_input_handler(input_handler);
4298 accepts
4299 });
4300
4301 currently_pending.needs_timeout |=
4302 match_result.pending_has_binding || text_input_requires_timeout;
4303
4304 if currently_pending.needs_timeout {
4305 currently_pending.timer = Some(self.spawn(cx, async move |cx| {
4306 cx.background_executor.timer(Duration::from_secs(1)).await;
4307 cx.update(move |window, cx| {
4308 let Some(currently_pending) = window
4309 .pending_input
4310 .take()
4311 .filter(|pending| pending.focus == window.focus)
4312 else {
4313 return;
4314 };
4315
4316 let node_id = window.focus_node_id_in_rendered_frame(window.focus);
4317 let dispatch_path =
4318 window.rendered_frame.dispatch_tree.dispatch_path(node_id);
4319
4320 let to_replay = window
4321 .rendered_frame
4322 .dispatch_tree
4323 .flush_dispatch(currently_pending.keystrokes, &dispatch_path);
4324
4325 window.pending_input_changed(cx);
4326 window.replay_pending_input(to_replay, cx)
4327 })
4328 .log_err();
4329 }));
4330 } else {
4331 currently_pending.timer = None;
4332 }
4333 self.pending_input = Some(currently_pending);
4334 self.pending_input_changed(cx);
4335 cx.propagate_event = false;
4336 return;
4337 }
4338
4339 let skip_bindings = event
4340 .downcast_ref::<KeyDownEvent>()
4341 .filter(|key_down_event| key_down_event.prefer_character_input)
4342 .map(|_| {
4343 self.platform_window
4344 .take_input_handler()
4345 .map_or(false, |mut input_handler| {
4346 let accepts = input_handler.accepts_text_input(self, cx);
4347 self.platform_window.set_input_handler(input_handler);
4348 // If modifiers are not excessive (e.g. AltGr), and the input handler is accepting text input,
4349 // we prefer the text input over bindings.
4350 accepts
4351 })
4352 })
4353 .unwrap_or(false);
4354
4355 if !skip_bindings {
4356 for binding in match_result.bindings {
4357 self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
4358 if !cx.propagate_event {
4359 self.dispatch_keystroke_observers(
4360 event,
4361 Some(binding.action),
4362 match_result.context_stack,
4363 cx,
4364 );
4365 self.pending_input_changed(cx);
4366 return;
4367 }
4368 }
4369 }
4370
4371 self.finish_dispatch_key_event(event, dispatch_path, match_result.context_stack, cx);
4372 self.pending_input_changed(cx);
4373 }
4374
4375 fn finish_dispatch_key_event(
4376 &mut self,
4377 event: &dyn Any,
4378 dispatch_path: SmallVec<[DispatchNodeId; 32]>,
4379 context_stack: Vec<KeyContext>,
4380 cx: &mut App,
4381 ) {
4382 self.dispatch_key_down_up_event(event, &dispatch_path, cx);
4383 if !cx.propagate_event {
4384 return;
4385 }
4386
4387 self.dispatch_modifiers_changed_event(event, &dispatch_path, cx);
4388 if !cx.propagate_event {
4389 return;
4390 }
4391
4392 self.dispatch_keystroke_observers(event, None, context_stack, cx);
4393 }
4394
4395 pub(crate) fn pending_input_changed(&mut self, cx: &mut App) {
4396 self.pending_input_observers
4397 .clone()
4398 .retain(&(), |callback| callback(self, cx));
4399 }
4400
4401 fn dispatch_key_down_up_event(
4402 &mut self,
4403 event: &dyn Any,
4404 dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
4405 cx: &mut App,
4406 ) {
4407 // Capture phase
4408 for node_id in dispatch_path {
4409 let node = self.rendered_frame.dispatch_tree.node(*node_id);
4410
4411 for key_listener in node.key_listeners.clone() {
4412 key_listener(event, DispatchPhase::Capture, self, cx);
4413 if !cx.propagate_event {
4414 return;
4415 }
4416 }
4417 }
4418
4419 // Bubble phase
4420 for node_id in dispatch_path.iter().rev() {
4421 // Handle low level key events
4422 let node = self.rendered_frame.dispatch_tree.node(*node_id);
4423 for key_listener in node.key_listeners.clone() {
4424 key_listener(event, DispatchPhase::Bubble, self, cx);
4425 if !cx.propagate_event {
4426 return;
4427 }
4428 }
4429 }
4430 }
4431
4432 fn dispatch_modifiers_changed_event(
4433 &mut self,
4434 event: &dyn Any,
4435 dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
4436 cx: &mut App,
4437 ) {
4438 let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() else {
4439 return;
4440 };
4441 for node_id in dispatch_path.iter().rev() {
4442 let node = self.rendered_frame.dispatch_tree.node(*node_id);
4443 for listener in node.modifiers_changed_listeners.clone() {
4444 listener(event, self, cx);
4445 if !cx.propagate_event {
4446 return;
4447 }
4448 }
4449 }
4450 }
4451
4452 /// Determine whether a potential multi-stroke key binding is in progress on this window.
4453 pub fn has_pending_keystrokes(&self) -> bool {
4454 self.pending_input.is_some()
4455 }
4456
4457 pub(crate) fn clear_pending_keystrokes(&mut self) {
4458 self.pending_input.take();
4459 }
4460
4461 /// Returns the currently pending input keystrokes that might result in a multi-stroke key binding.
4462 pub fn pending_input_keystrokes(&self) -> Option<&[Keystroke]> {
4463 self.pending_input
4464 .as_ref()
4465 .map(|pending_input| pending_input.keystrokes.as_slice())
4466 }
4467
4468 fn replay_pending_input(&mut self, replays: SmallVec<[Replay; 1]>, cx: &mut App) {
4469 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
4470 let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
4471
4472 'replay: for replay in replays {
4473 let event = KeyDownEvent {
4474 keystroke: replay.keystroke.clone(),
4475 is_held: false,
4476 prefer_character_input: true,
4477 };
4478
4479 cx.propagate_event = true;
4480 for binding in replay.bindings {
4481 self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
4482 if !cx.propagate_event {
4483 self.dispatch_keystroke_observers(
4484 &event,
4485 Some(binding.action),
4486 Vec::default(),
4487 cx,
4488 );
4489 continue 'replay;
4490 }
4491 }
4492
4493 self.dispatch_key_down_up_event(&event, &dispatch_path, cx);
4494 if !cx.propagate_event {
4495 continue 'replay;
4496 }
4497 if let Some(input) = replay.keystroke.key_char.as_ref().cloned()
4498 && let Some(mut input_handler) = self.platform_window.take_input_handler()
4499 {
4500 input_handler.dispatch_input(&input, self, cx);
4501 self.platform_window.set_input_handler(input_handler)
4502 }
4503 }
4504 }
4505
4506 fn focus_node_id_in_rendered_frame(&self, focus_id: Option<FocusId>) -> DispatchNodeId {
4507 focus_id
4508 .and_then(|focus_id| {
4509 self.rendered_frame
4510 .dispatch_tree
4511 .focusable_node_id(focus_id)
4512 })
4513 .unwrap_or_else(|| self.rendered_frame.dispatch_tree.root_node_id())
4514 }
4515
4516 fn dispatch_action_on_node(
4517 &mut self,
4518 node_id: DispatchNodeId,
4519 action: &dyn Action,
4520 cx: &mut App,
4521 ) {
4522 let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
4523
4524 // Capture phase for global actions.
4525 cx.propagate_event = true;
4526 if let Some(mut global_listeners) = cx
4527 .global_action_listeners
4528 .remove(&action.as_any().type_id())
4529 {
4530 for listener in &global_listeners {
4531 listener(action.as_any(), DispatchPhase::Capture, cx);
4532 if !cx.propagate_event {
4533 break;
4534 }
4535 }
4536
4537 global_listeners.extend(
4538 cx.global_action_listeners
4539 .remove(&action.as_any().type_id())
4540 .unwrap_or_default(),
4541 );
4542
4543 cx.global_action_listeners
4544 .insert(action.as_any().type_id(), global_listeners);
4545 }
4546
4547 if !cx.propagate_event {
4548 return;
4549 }
4550
4551 // Capture phase for window actions.
4552 for node_id in &dispatch_path {
4553 let node = self.rendered_frame.dispatch_tree.node(*node_id);
4554 for DispatchActionListener {
4555 action_type,
4556 listener,
4557 } in node.action_listeners.clone()
4558 {
4559 let any_action = action.as_any();
4560 if action_type == any_action.type_id() {
4561 listener(any_action, DispatchPhase::Capture, self, cx);
4562
4563 if !cx.propagate_event {
4564 return;
4565 }
4566 }
4567 }
4568 }
4569
4570 // Bubble phase for window actions.
4571 for node_id in dispatch_path.iter().rev() {
4572 let node = self.rendered_frame.dispatch_tree.node(*node_id);
4573 for DispatchActionListener {
4574 action_type,
4575 listener,
4576 } in node.action_listeners.clone()
4577 {
4578 let any_action = action.as_any();
4579 if action_type == any_action.type_id() {
4580 cx.propagate_event = false; // Actions stop propagation by default during the bubble phase
4581 listener(any_action, DispatchPhase::Bubble, self, cx);
4582
4583 if !cx.propagate_event {
4584 return;
4585 }
4586 }
4587 }
4588 }
4589
4590 // Bubble phase for global actions.
4591 if let Some(mut global_listeners) = cx
4592 .global_action_listeners
4593 .remove(&action.as_any().type_id())
4594 {
4595 for listener in global_listeners.iter().rev() {
4596 cx.propagate_event = false; // Actions stop propagation by default during the bubble phase
4597
4598 listener(action.as_any(), DispatchPhase::Bubble, cx);
4599 if !cx.propagate_event {
4600 break;
4601 }
4602 }
4603
4604 global_listeners.extend(
4605 cx.global_action_listeners
4606 .remove(&action.as_any().type_id())
4607 .unwrap_or_default(),
4608 );
4609
4610 cx.global_action_listeners
4611 .insert(action.as_any().type_id(), global_listeners);
4612 }
4613 }
4614
4615 /// Register the given handler to be invoked whenever the global of the given type
4616 /// is updated.
4617 pub fn observe_global<G: Global>(
4618 &mut self,
4619 cx: &mut App,
4620 f: impl Fn(&mut Window, &mut App) + 'static,
4621 ) -> Subscription {
4622 let window_handle = self.handle;
4623 let (subscription, activate) = cx.global_observers.insert(
4624 TypeId::of::<G>(),
4625 Box::new(move |cx| {
4626 window_handle
4627 .update(cx, |_, window, cx| f(window, cx))
4628 .is_ok()
4629 }),
4630 );
4631 cx.defer(move |_| activate());
4632 subscription
4633 }
4634
4635 /// Focus the current window and bring it to the foreground at the platform level.
4636 pub fn activate_window(&self) {
4637 self.platform_window.activate();
4638 }
4639
4640 /// Minimize the current window at the platform level.
4641 pub fn minimize_window(&self) {
4642 self.platform_window.minimize();
4643 }
4644
4645 /// Toggle full screen status on the current window at the platform level.
4646 pub fn toggle_fullscreen(&self) {
4647 self.platform_window.toggle_fullscreen();
4648 }
4649
4650 /// Updates the IME panel position suggestions for languages like japanese, chinese.
4651 pub fn invalidate_character_coordinates(&self) {
4652 self.on_next_frame(|window, cx| {
4653 if let Some(mut input_handler) = window.platform_window.take_input_handler() {
4654 if let Some(bounds) = input_handler.selected_bounds(window, cx) {
4655 window.platform_window.update_ime_position(bounds);
4656 }
4657 window.platform_window.set_input_handler(input_handler);
4658 }
4659 });
4660 }
4661
4662 /// Present a platform dialog.
4663 /// The provided message will be presented, along with buttons for each answer.
4664 /// When a button is clicked, the returned Receiver will receive the index of the clicked button.
4665 pub fn prompt<T>(
4666 &mut self,
4667 level: PromptLevel,
4668 message: &str,
4669 detail: Option<&str>,
4670 answers: &[T],
4671 cx: &mut App,
4672 ) -> oneshot::Receiver<usize>
4673 where
4674 T: Clone + Into<PromptButton>,
4675 {
4676 let prompt_builder = cx.prompt_builder.take();
4677 let Some(prompt_builder) = prompt_builder else {
4678 unreachable!("Re-entrant window prompting is not supported by GPUI");
4679 };
4680
4681 let answers = answers
4682 .iter()
4683 .map(|answer| answer.clone().into())
4684 .collect::<Vec<_>>();
4685
4686 let receiver = match &prompt_builder {
4687 PromptBuilder::Default => self
4688 .platform_window
4689 .prompt(level, message, detail, &answers)
4690 .unwrap_or_else(|| {
4691 self.build_custom_prompt(&prompt_builder, level, message, detail, &answers, cx)
4692 }),
4693 PromptBuilder::Custom(_) => {
4694 self.build_custom_prompt(&prompt_builder, level, message, detail, &answers, cx)
4695 }
4696 };
4697
4698 cx.prompt_builder = Some(prompt_builder);
4699
4700 receiver
4701 }
4702
4703 fn build_custom_prompt(
4704 &mut self,
4705 prompt_builder: &PromptBuilder,
4706 level: PromptLevel,
4707 message: &str,
4708 detail: Option<&str>,
4709 answers: &[PromptButton],
4710 cx: &mut App,
4711 ) -> oneshot::Receiver<usize> {
4712 let (sender, receiver) = oneshot::channel();
4713 let handle = PromptHandle::new(sender);
4714 let handle = (prompt_builder)(level, message, detail, answers, handle, self, cx);
4715 self.prompt = Some(handle);
4716 receiver
4717 }
4718
4719 /// Returns the current context stack.
4720 pub fn context_stack(&self) -> Vec<KeyContext> {
4721 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
4722 let dispatch_tree = &self.rendered_frame.dispatch_tree;
4723 dispatch_tree
4724 .dispatch_path(node_id)
4725 .iter()
4726 .filter_map(move |&node_id| dispatch_tree.node(node_id).context.clone())
4727 .collect()
4728 }
4729
4730 /// Returns all available actions for the focused element.
4731 pub fn available_actions(&self, cx: &App) -> Vec<Box<dyn Action>> {
4732 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
4733 let mut actions = self.rendered_frame.dispatch_tree.available_actions(node_id);
4734 for action_type in cx.global_action_listeners.keys() {
4735 if let Err(ix) = actions.binary_search_by_key(action_type, |a| a.as_any().type_id()) {
4736 let action = cx.actions.build_action_type(action_type).ok();
4737 if let Some(action) = action {
4738 actions.insert(ix, action);
4739 }
4740 }
4741 }
4742 actions
4743 }
4744
4745 /// Returns key bindings that invoke an action on the currently focused element. Bindings are
4746 /// returned in the order they were added. For display, the last binding should take precedence.
4747 pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
4748 self.rendered_frame
4749 .dispatch_tree
4750 .bindings_for_action(action, &self.rendered_frame.dispatch_tree.context_stack)
4751 }
4752
4753 /// Returns the highest precedence key binding that invokes an action on the currently focused
4754 /// element. This is more efficient than getting the last result of `bindings_for_action`.
4755 pub fn highest_precedence_binding_for_action(&self, action: &dyn Action) -> Option<KeyBinding> {
4756 self.rendered_frame
4757 .dispatch_tree
4758 .highest_precedence_binding_for_action(
4759 action,
4760 &self.rendered_frame.dispatch_tree.context_stack,
4761 )
4762 }
4763
4764 /// Returns the key bindings for an action in a context.
4765 pub fn bindings_for_action_in_context(
4766 &self,
4767 action: &dyn Action,
4768 context: KeyContext,
4769 ) -> Vec<KeyBinding> {
4770 let dispatch_tree = &self.rendered_frame.dispatch_tree;
4771 dispatch_tree.bindings_for_action(action, &[context])
4772 }
4773
4774 /// Returns the highest precedence key binding for an action in a context. This is more
4775 /// efficient than getting the last result of `bindings_for_action_in_context`.
4776 pub fn highest_precedence_binding_for_action_in_context(
4777 &self,
4778 action: &dyn Action,
4779 context: KeyContext,
4780 ) -> Option<KeyBinding> {
4781 let dispatch_tree = &self.rendered_frame.dispatch_tree;
4782 dispatch_tree.highest_precedence_binding_for_action(action, &[context])
4783 }
4784
4785 /// Returns any bindings that would invoke an action on the given focus handle if it were
4786 /// focused. Bindings are returned in the order they were added. For display, the last binding
4787 /// should take precedence.
4788 pub fn bindings_for_action_in(
4789 &self,
4790 action: &dyn Action,
4791 focus_handle: &FocusHandle,
4792 ) -> Vec<KeyBinding> {
4793 let dispatch_tree = &self.rendered_frame.dispatch_tree;
4794 let Some(context_stack) = self.context_stack_for_focus_handle(focus_handle) else {
4795 return vec![];
4796 };
4797 dispatch_tree.bindings_for_action(action, &context_stack)
4798 }
4799
4800 /// Returns the highest precedence key binding that would invoke an action on the given focus
4801 /// handle if it were focused. This is more efficient than getting the last result of
4802 /// `bindings_for_action_in`.
4803 pub fn highest_precedence_binding_for_action_in(
4804 &self,
4805 action: &dyn Action,
4806 focus_handle: &FocusHandle,
4807 ) -> Option<KeyBinding> {
4808 let dispatch_tree = &self.rendered_frame.dispatch_tree;
4809 let context_stack = self.context_stack_for_focus_handle(focus_handle)?;
4810 dispatch_tree.highest_precedence_binding_for_action(action, &context_stack)
4811 }
4812
4813 /// Find the bindings that can follow the current input sequence for the current context stack.
4814 pub fn possible_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
4815 self.rendered_frame
4816 .dispatch_tree
4817 .possible_next_bindings_for_input(input, &self.context_stack())
4818 }
4819
4820 fn context_stack_for_focus_handle(
4821 &self,
4822 focus_handle: &FocusHandle,
4823 ) -> Option<Vec<KeyContext>> {
4824 let dispatch_tree = &self.rendered_frame.dispatch_tree;
4825 let node_id = dispatch_tree.focusable_node_id(focus_handle.id)?;
4826 let context_stack: Vec<_> = dispatch_tree
4827 .dispatch_path(node_id)
4828 .into_iter()
4829 .filter_map(|node_id| dispatch_tree.node(node_id).context.clone())
4830 .collect();
4831 Some(context_stack)
4832 }
4833
4834 /// Returns a generic event listener that invokes the given listener with the view and context associated with the given view handle.
4835 pub fn listener_for<T: 'static, E>(
4836 &self,
4837 view: &Entity<T>,
4838 f: impl Fn(&mut T, &E, &mut Window, &mut Context<T>) + 'static,
4839 ) -> impl Fn(&E, &mut Window, &mut App) + 'static {
4840 let view = view.downgrade();
4841 move |e: &E, window: &mut Window, cx: &mut App| {
4842 view.update(cx, |view, cx| f(view, e, window, cx)).ok();
4843 }
4844 }
4845
4846 /// Returns a generic handler that invokes the given handler with the view and context associated with the given view handle.
4847 pub fn handler_for<E: 'static, Callback: Fn(&mut E, &mut Window, &mut Context<E>) + 'static>(
4848 &self,
4849 entity: &Entity<E>,
4850 f: Callback,
4851 ) -> impl Fn(&mut Window, &mut App) + 'static {
4852 let entity = entity.downgrade();
4853 move |window: &mut Window, cx: &mut App| {
4854 entity.update(cx, |entity, cx| f(entity, window, cx)).ok();
4855 }
4856 }
4857
4858 /// Register a callback that can interrupt the closing of the current window based the returned boolean.
4859 /// If the callback returns false, the window won't be closed.
4860 pub fn on_window_should_close(
4861 &self,
4862 cx: &App,
4863 f: impl Fn(&mut Window, &mut App) -> bool + 'static,
4864 ) {
4865 let mut cx = self.to_async(cx);
4866 self.platform_window.on_should_close(Box::new(move || {
4867 cx.update(|window, cx| f(window, cx)).unwrap_or(true)
4868 }))
4869 }
4870
4871 /// Register an action listener on this node for the next frame. The type of action
4872 /// is determined by the first parameter of the given listener. When the next frame is rendered
4873 /// the listener will be cleared.
4874 ///
4875 /// This is a fairly low-level method, so prefer using action handlers on elements unless you have
4876 /// a specific need to register a listener yourself.
4877 ///
4878 /// This method should only be called as part of the paint phase of element drawing.
4879 pub fn on_action(
4880 &mut self,
4881 action_type: TypeId,
4882 listener: impl Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static,
4883 ) {
4884 self.invalidator.debug_assert_paint();
4885
4886 self.next_frame
4887 .dispatch_tree
4888 .on_action(action_type, Rc::new(listener));
4889 }
4890
4891 /// Register a capturing action listener on this node for the next frame if the condition is true.
4892 /// The type of action is determined by the first parameter of the given listener. When the next
4893 /// frame is rendered the listener will be cleared.
4894 ///
4895 /// This is a fairly low-level method, so prefer using action handlers on elements unless you have
4896 /// a specific need to register a listener yourself.
4897 ///
4898 /// This method should only be called as part of the paint phase of element drawing.
4899 pub fn on_action_when(
4900 &mut self,
4901 condition: bool,
4902 action_type: TypeId,
4903 listener: impl Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static,
4904 ) {
4905 self.invalidator.debug_assert_paint();
4906
4907 if condition {
4908 self.next_frame
4909 .dispatch_tree
4910 .on_action(action_type, Rc::new(listener));
4911 }
4912 }
4913
4914 /// Read information about the GPU backing this window.
4915 /// Currently returns None on Mac and Windows.
4916 pub fn gpu_specs(&self) -> Option<GpuSpecs> {
4917 self.platform_window.gpu_specs()
4918 }
4919
4920 /// Perform titlebar double-click action.
4921 /// This is macOS specific.
4922 pub fn titlebar_double_click(&self) {
4923 self.platform_window.titlebar_double_click();
4924 }
4925
4926 /// Gets the window's title at the platform level.
4927 /// This is macOS specific.
4928 pub fn window_title(&self) -> String {
4929 self.platform_window.get_title()
4930 }
4931
4932 /// Returns a list of all tabbed windows and their titles.
4933 /// This is macOS specific.
4934 pub fn tabbed_windows(&self) -> Option<Vec<SystemWindowTab>> {
4935 self.platform_window.tabbed_windows()
4936 }
4937
4938 /// Returns the tab bar visibility.
4939 /// This is macOS specific.
4940 pub fn tab_bar_visible(&self) -> bool {
4941 self.platform_window.tab_bar_visible()
4942 }
4943
4944 /// Merges all open windows into a single tabbed window.
4945 /// This is macOS specific.
4946 pub fn merge_all_windows(&self) {
4947 self.platform_window.merge_all_windows()
4948 }
4949
4950 /// Moves the tab to a new containing window.
4951 /// This is macOS specific.
4952 pub fn move_tab_to_new_window(&self) {
4953 self.platform_window.move_tab_to_new_window()
4954 }
4955
4956 /// Shows or hides the window tab overview.
4957 /// This is macOS specific.
4958 pub fn toggle_window_tab_overview(&self) {
4959 self.platform_window.toggle_window_tab_overview()
4960 }
4961
4962 /// Sets the tabbing identifier for the window.
4963 /// This is macOS specific.
4964 pub fn set_tabbing_identifier(&self, tabbing_identifier: Option<String>) {
4965 self.platform_window
4966 .set_tabbing_identifier(tabbing_identifier)
4967 }
4968
4969 /// Toggles the inspector mode on this window.
4970 #[cfg(any(feature = "inspector", debug_assertions))]
4971 pub fn toggle_inspector(&mut self, cx: &mut App) {
4972 self.inspector = match self.inspector {
4973 None => Some(cx.new(|_| Inspector::new())),
4974 Some(_) => None,
4975 };
4976 self.refresh();
4977 }
4978
4979 /// Returns true if the window is in inspector mode.
4980 pub fn is_inspector_picking(&self, _cx: &App) -> bool {
4981 #[cfg(any(feature = "inspector", debug_assertions))]
4982 {
4983 if let Some(inspector) = &self.inspector {
4984 return inspector.read(_cx).is_picking();
4985 }
4986 }
4987 false
4988 }
4989
4990 /// Executes the provided function with mutable access to an inspector state.
4991 #[cfg(any(feature = "inspector", debug_assertions))]
4992 pub fn with_inspector_state<T: 'static, R>(
4993 &mut self,
4994 _inspector_id: Option<&crate::InspectorElementId>,
4995 cx: &mut App,
4996 f: impl FnOnce(&mut Option<T>, &mut Self) -> R,
4997 ) -> R {
4998 if let Some(inspector_id) = _inspector_id
4999 && let Some(inspector) = &self.inspector
5000 {
5001 let inspector = inspector.clone();
5002 let active_element_id = inspector.read(cx).active_element_id();
5003 if Some(inspector_id) == active_element_id {
5004 return inspector.update(cx, |inspector, _cx| {
5005 inspector.with_active_element_state(self, f)
5006 });
5007 }
5008 }
5009 f(&mut None, self)
5010 }
5011
5012 #[cfg(any(feature = "inspector", debug_assertions))]
5013 pub(crate) fn build_inspector_element_id(
5014 &mut self,
5015 path: crate::InspectorElementPath,
5016 ) -> crate::InspectorElementId {
5017 self.invalidator.debug_assert_paint_or_prepaint();
5018 let path = Rc::new(path);
5019 let next_instance_id = self
5020 .next_frame
5021 .next_inspector_instance_ids
5022 .entry(path.clone())
5023 .or_insert(0);
5024 let instance_id = *next_instance_id;
5025 *next_instance_id += 1;
5026 crate::InspectorElementId { path, instance_id }
5027 }
5028
5029 #[cfg(any(feature = "inspector", debug_assertions))]
5030 fn prepaint_inspector(&mut self, inspector_width: Pixels, cx: &mut App) -> Option<AnyElement> {
5031 if let Some(inspector) = self.inspector.take() {
5032 let mut inspector_element = AnyView::from(inspector.clone()).into_any_element();
5033 inspector_element.prepaint_as_root(
5034 point(self.viewport_size.width - inspector_width, px(0.0)),
5035 size(inspector_width, self.viewport_size.height).into(),
5036 self,
5037 cx,
5038 );
5039 self.inspector = Some(inspector);
5040 Some(inspector_element)
5041 } else {
5042 None
5043 }
5044 }
5045
5046 #[cfg(any(feature = "inspector", debug_assertions))]
5047 fn paint_inspector(&mut self, mut inspector_element: Option<AnyElement>, cx: &mut App) {
5048 if let Some(mut inspector_element) = inspector_element {
5049 inspector_element.paint(self, cx);
5050 };
5051 }
5052
5053 /// Registers a hitbox that can be used for inspector picking mode, allowing users to select and
5054 /// inspect UI elements by clicking on them.
5055 #[cfg(any(feature = "inspector", debug_assertions))]
5056 pub fn insert_inspector_hitbox(
5057 &mut self,
5058 hitbox_id: HitboxId,
5059 inspector_id: Option<&crate::InspectorElementId>,
5060 cx: &App,
5061 ) {
5062 self.invalidator.debug_assert_paint_or_prepaint();
5063 if !self.is_inspector_picking(cx) {
5064 return;
5065 }
5066 if let Some(inspector_id) = inspector_id {
5067 self.next_frame
5068 .inspector_hitboxes
5069 .insert(hitbox_id, inspector_id.clone());
5070 }
5071 }
5072
5073 #[cfg(any(feature = "inspector", debug_assertions))]
5074 fn paint_inspector_hitbox(&mut self, cx: &App) {
5075 if let Some(inspector) = self.inspector.as_ref() {
5076 let inspector = inspector.read(cx);
5077 if let Some((hitbox_id, _)) = self.hovered_inspector_hitbox(inspector, &self.next_frame)
5078 && let Some(hitbox) = self
5079 .next_frame
5080 .hitboxes
5081 .iter()
5082 .find(|hitbox| hitbox.id == hitbox_id)
5083 {
5084 self.paint_quad(crate::fill(hitbox.bounds, crate::rgba(0x61afef4d)));
5085 }
5086 }
5087 }
5088
5089 #[cfg(any(feature = "inspector", debug_assertions))]
5090 fn handle_inspector_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
5091 let Some(inspector) = self.inspector.clone() else {
5092 return;
5093 };
5094 if event.downcast_ref::<MouseMoveEvent>().is_some() {
5095 inspector.update(cx, |inspector, _cx| {
5096 if let Some((_, inspector_id)) =
5097 self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
5098 {
5099 inspector.hover(inspector_id, self);
5100 }
5101 });
5102 } else if event.downcast_ref::<crate::MouseDownEvent>().is_some() {
5103 inspector.update(cx, |inspector, _cx| {
5104 if let Some((_, inspector_id)) =
5105 self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
5106 {
5107 inspector.select(inspector_id, self);
5108 }
5109 });
5110 } else if let Some(event) = event.downcast_ref::<crate::ScrollWheelEvent>() {
5111 // This should be kept in sync with SCROLL_LINES in x11 platform.
5112 const SCROLL_LINES: f32 = 3.0;
5113 const SCROLL_PIXELS_PER_LAYER: f32 = 36.0;
5114 let delta_y = event
5115 .delta
5116 .pixel_delta(px(SCROLL_PIXELS_PER_LAYER / SCROLL_LINES))
5117 .y;
5118 if let Some(inspector) = self.inspector.clone() {
5119 inspector.update(cx, |inspector, _cx| {
5120 if let Some(depth) = inspector.pick_depth.as_mut() {
5121 *depth += f32::from(delta_y) / SCROLL_PIXELS_PER_LAYER;
5122 let max_depth = self.mouse_hit_test.ids.len() as f32 - 0.5;
5123 if *depth < 0.0 {
5124 *depth = 0.0;
5125 } else if *depth > max_depth {
5126 *depth = max_depth;
5127 }
5128 if let Some((_, inspector_id)) =
5129 self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
5130 {
5131 inspector.set_active_element_id(inspector_id, self);
5132 }
5133 }
5134 });
5135 }
5136 }
5137 }
5138
5139 #[cfg(any(feature = "inspector", debug_assertions))]
5140 fn hovered_inspector_hitbox(
5141 &self,
5142 inspector: &Inspector,
5143 frame: &Frame,
5144 ) -> Option<(HitboxId, crate::InspectorElementId)> {
5145 if let Some(pick_depth) = inspector.pick_depth {
5146 let depth = (pick_depth as i64).try_into().unwrap_or(0);
5147 let max_skipped = self.mouse_hit_test.ids.len().saturating_sub(1);
5148 let skip_count = (depth as usize).min(max_skipped);
5149 for hitbox_id in self.mouse_hit_test.ids.iter().skip(skip_count) {
5150 if let Some(inspector_id) = frame.inspector_hitboxes.get(hitbox_id) {
5151 return Some((*hitbox_id, inspector_id.clone()));
5152 }
5153 }
5154 }
5155 None
5156 }
5157
5158 /// For testing: set the current modifier keys state.
5159 /// This does not generate any events.
5160 #[cfg(any(test, feature = "test-support"))]
5161 pub fn set_modifiers(&mut self, modifiers: Modifiers) {
5162 self.modifiers = modifiers;
5163 }
5164
5165 /// For testing: simulate a mouse move event to the given position.
5166 /// This dispatches the event through the normal event handling path,
5167 /// which will trigger hover states and tooltips.
5168 #[cfg(any(test, feature = "test-support"))]
5169 pub fn simulate_mouse_move(&mut self, position: Point<Pixels>, cx: &mut App) {
5170 let event = PlatformInput::MouseMove(MouseMoveEvent {
5171 position,
5172 modifiers: self.modifiers,
5173 pressed_button: None,
5174 });
5175 let _ = self.dispatch_event(event, cx);
5176 }
5177}
5178
5179// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
5180slotmap::new_key_type! {
5181 /// A unique identifier for a window.
5182 pub struct WindowId;
5183}
5184
5185impl WindowId {
5186 /// Converts this window ID to a `u64`.
5187 pub fn as_u64(&self) -> u64 {
5188 self.0.as_ffi()
5189 }
5190}
5191
5192impl From<u64> for WindowId {
5193 fn from(value: u64) -> Self {
5194 WindowId(slotmap::KeyData::from_ffi(value))
5195 }
5196}
5197
5198/// A handle to a window with a specific root view type.
5199/// Note that this does not keep the window alive on its own.
5200#[derive(Deref, DerefMut)]
5201pub struct WindowHandle<V> {
5202 #[deref]
5203 #[deref_mut]
5204 pub(crate) any_handle: AnyWindowHandle,
5205 state_type: PhantomData<fn(V) -> V>,
5206}
5207
5208impl<V> Debug for WindowHandle<V> {
5209 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
5210 f.debug_struct("WindowHandle")
5211 .field("any_handle", &self.any_handle.id.as_u64())
5212 .finish()
5213 }
5214}
5215
5216impl<V: 'static + Render> WindowHandle<V> {
5217 /// Creates a new handle from a window ID.
5218 /// This does not check if the root type of the window is `V`.
5219 pub fn new(id: WindowId) -> Self {
5220 WindowHandle {
5221 any_handle: AnyWindowHandle {
5222 id,
5223 state_type: TypeId::of::<V>(),
5224 },
5225 state_type: PhantomData,
5226 }
5227 }
5228
5229 /// Get the root view out of this window.
5230 ///
5231 /// This will fail if the window is closed or if the root view's type does not match `V`.
5232 #[cfg(any(test, feature = "test-support"))]
5233 pub fn root<C>(&self, cx: &mut C) -> Result<Entity<V>>
5234 where
5235 C: AppContext,
5236 {
5237 cx.update_window(self.any_handle, |root_view, _, _| {
5238 root_view
5239 .downcast::<V>()
5240 .map_err(|_| anyhow!("the type of the window's root view has changed"))
5241 })?
5242 }
5243
5244 /// Updates the root view of this window.
5245 ///
5246 /// This will fail if the window has been closed or if the root view's type does not match
5247 pub fn update<C, R>(
5248 &self,
5249 cx: &mut C,
5250 update: impl FnOnce(&mut V, &mut Window, &mut Context<V>) -> R,
5251 ) -> Result<R>
5252 where
5253 C: AppContext,
5254 {
5255 cx.update_window(self.any_handle, |root_view, window, cx| {
5256 let view = root_view
5257 .downcast::<V>()
5258 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
5259
5260 Ok(view.update(cx, |view, cx| update(view, window, cx)))
5261 })?
5262 }
5263
5264 /// Read the root view out of this window.
5265 ///
5266 /// This will fail if the window is closed or if the root view's type does not match `V`.
5267 pub fn read<'a>(&self, cx: &'a App) -> Result<&'a V> {
5268 let x = cx
5269 .windows
5270 .get(self.id)
5271 .and_then(|window| {
5272 window
5273 .as_deref()
5274 .and_then(|window| window.root.clone())
5275 .map(|root_view| root_view.downcast::<V>())
5276 })
5277 .context("window not found")?
5278 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
5279
5280 Ok(x.read(cx))
5281 }
5282
5283 /// Read the root view out of this window, with a callback
5284 ///
5285 /// This will fail if the window is closed or if the root view's type does not match `V`.
5286 pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &App) -> R) -> Result<R>
5287 where
5288 C: AppContext,
5289 {
5290 cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
5291 }
5292
5293 /// Read the root view pointer off of this window.
5294 ///
5295 /// This will fail if the window is closed or if the root view's type does not match `V`.
5296 pub fn entity<C>(&self, cx: &C) -> Result<Entity<V>>
5297 where
5298 C: AppContext,
5299 {
5300 cx.read_window(self, |root_view, _cx| root_view)
5301 }
5302
5303 /// Check if this window is 'active'.
5304 ///
5305 /// Will return `None` if the window is closed or currently
5306 /// borrowed.
5307 pub fn is_active(&self, cx: &mut App) -> Option<bool> {
5308 cx.update_window(self.any_handle, |_, window, _| window.is_window_active())
5309 .ok()
5310 }
5311}
5312
5313impl<V> Copy for WindowHandle<V> {}
5314
5315impl<V> Clone for WindowHandle<V> {
5316 fn clone(&self) -> Self {
5317 *self
5318 }
5319}
5320
5321impl<V> PartialEq for WindowHandle<V> {
5322 fn eq(&self, other: &Self) -> bool {
5323 self.any_handle == other.any_handle
5324 }
5325}
5326
5327impl<V> Eq for WindowHandle<V> {}
5328
5329impl<V> Hash for WindowHandle<V> {
5330 fn hash<H: Hasher>(&self, state: &mut H) {
5331 self.any_handle.hash(state);
5332 }
5333}
5334
5335impl<V: 'static> From<WindowHandle<V>> for AnyWindowHandle {
5336 fn from(val: WindowHandle<V>) -> Self {
5337 val.any_handle
5338 }
5339}
5340
5341/// A handle to a window with any root view type, which can be downcast to a window with a specific root view type.
5342#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
5343pub struct AnyWindowHandle {
5344 pub(crate) id: WindowId,
5345 state_type: TypeId,
5346}
5347
5348impl AnyWindowHandle {
5349 /// Get the ID of this window.
5350 pub fn window_id(&self) -> WindowId {
5351 self.id
5352 }
5353
5354 /// Attempt to convert this handle to a window handle with a specific root view type.
5355 /// If the types do not match, this will return `None`.
5356 pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
5357 if TypeId::of::<T>() == self.state_type {
5358 Some(WindowHandle {
5359 any_handle: *self,
5360 state_type: PhantomData,
5361 })
5362 } else {
5363 None
5364 }
5365 }
5366
5367 /// Updates the state of the root view of this window.
5368 ///
5369 /// This will fail if the window has been closed.
5370 pub fn update<C, R>(
5371 self,
5372 cx: &mut C,
5373 update: impl FnOnce(AnyView, &mut Window, &mut App) -> R,
5374 ) -> Result<R>
5375 where
5376 C: AppContext,
5377 {
5378 cx.update_window(self, update)
5379 }
5380
5381 /// Read the state of the root view of this window.
5382 ///
5383 /// This will fail if the window has been closed.
5384 pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(Entity<T>, &App) -> R) -> Result<R>
5385 where
5386 C: AppContext,
5387 T: 'static,
5388 {
5389 let view = self
5390 .downcast::<T>()
5391 .context("the type of the window's root view has changed")?;
5392
5393 cx.read_window(&view, read)
5394 }
5395}
5396
5397impl HasWindowHandle for Window {
5398 fn window_handle(&self) -> Result<raw_window_handle::WindowHandle<'_>, HandleError> {
5399 self.platform_window.window_handle()
5400 }
5401}
5402
5403impl HasDisplayHandle for Window {
5404 fn display_handle(
5405 &self,
5406 ) -> std::result::Result<raw_window_handle::DisplayHandle<'_>, HandleError> {
5407 self.platform_window.display_handle()
5408 }
5409}
5410
5411/// An identifier for an [`Element`].
5412///
5413/// Can be constructed with a string, a number, or both, as well
5414/// as other internal representations.
5415#[derive(Clone, Debug, Eq, PartialEq, Hash)]
5416pub enum ElementId {
5417 /// The ID of a View element
5418 View(EntityId),
5419 /// An integer ID.
5420 Integer(u64),
5421 /// A string based ID.
5422 Name(SharedString),
5423 /// A UUID.
5424 Uuid(Uuid),
5425 /// An ID that's equated with a focus handle.
5426 FocusHandle(FocusId),
5427 /// A combination of a name and an integer.
5428 NamedInteger(SharedString, u64),
5429 /// A path.
5430 Path(Arc<std::path::Path>),
5431 /// A code location.
5432 CodeLocation(core::panic::Location<'static>),
5433 /// A labeled child of an element.
5434 NamedChild(Arc<ElementId>, SharedString),
5435}
5436
5437impl ElementId {
5438 /// Constructs an `ElementId::NamedInteger` from a name and `usize`.
5439 pub fn named_usize(name: impl Into<SharedString>, integer: usize) -> ElementId {
5440 Self::NamedInteger(name.into(), integer as u64)
5441 }
5442}
5443
5444impl Display for ElementId {
5445 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
5446 match self {
5447 ElementId::View(entity_id) => write!(f, "view-{}", entity_id)?,
5448 ElementId::Integer(ix) => write!(f, "{}", ix)?,
5449 ElementId::Name(name) => write!(f, "{}", name)?,
5450 ElementId::FocusHandle(_) => write!(f, "FocusHandle")?,
5451 ElementId::NamedInteger(s, i) => write!(f, "{}-{}", s, i)?,
5452 ElementId::Uuid(uuid) => write!(f, "{}", uuid)?,
5453 ElementId::Path(path) => write!(f, "{}", path.display())?,
5454 ElementId::CodeLocation(location) => write!(f, "{}", location)?,
5455 ElementId::NamedChild(id, name) => write!(f, "{}-{}", id, name)?,
5456 }
5457
5458 Ok(())
5459 }
5460}
5461
5462impl TryInto<SharedString> for ElementId {
5463 type Error = anyhow::Error;
5464
5465 fn try_into(self) -> anyhow::Result<SharedString> {
5466 if let ElementId::Name(name) = self {
5467 Ok(name)
5468 } else {
5469 anyhow::bail!("element id is not string")
5470 }
5471 }
5472}
5473
5474impl From<usize> for ElementId {
5475 fn from(id: usize) -> Self {
5476 ElementId::Integer(id as u64)
5477 }
5478}
5479
5480impl From<i32> for ElementId {
5481 fn from(id: i32) -> Self {
5482 Self::Integer(id as u64)
5483 }
5484}
5485
5486impl From<SharedString> for ElementId {
5487 fn from(name: SharedString) -> Self {
5488 ElementId::Name(name)
5489 }
5490}
5491
5492impl From<String> for ElementId {
5493 fn from(name: String) -> Self {
5494 ElementId::Name(name.into())
5495 }
5496}
5497
5498impl From<Arc<str>> for ElementId {
5499 fn from(name: Arc<str>) -> Self {
5500 ElementId::Name(name.into())
5501 }
5502}
5503
5504impl From<Arc<std::path::Path>> for ElementId {
5505 fn from(path: Arc<std::path::Path>) -> Self {
5506 ElementId::Path(path)
5507 }
5508}
5509
5510impl From<&'static str> for ElementId {
5511 fn from(name: &'static str) -> Self {
5512 ElementId::Name(name.into())
5513 }
5514}
5515
5516impl<'a> From<&'a FocusHandle> for ElementId {
5517 fn from(handle: &'a FocusHandle) -> Self {
5518 ElementId::FocusHandle(handle.id)
5519 }
5520}
5521
5522impl From<(&'static str, EntityId)> for ElementId {
5523 fn from((name, id): (&'static str, EntityId)) -> Self {
5524 ElementId::NamedInteger(name.into(), id.as_u64())
5525 }
5526}
5527
5528impl From<(&'static str, usize)> for ElementId {
5529 fn from((name, id): (&'static str, usize)) -> Self {
5530 ElementId::NamedInteger(name.into(), id as u64)
5531 }
5532}
5533
5534impl From<(SharedString, usize)> for ElementId {
5535 fn from((name, id): (SharedString, usize)) -> Self {
5536 ElementId::NamedInteger(name, id as u64)
5537 }
5538}
5539
5540impl From<(&'static str, u64)> for ElementId {
5541 fn from((name, id): (&'static str, u64)) -> Self {
5542 ElementId::NamedInteger(name.into(), id)
5543 }
5544}
5545
5546impl From<Uuid> for ElementId {
5547 fn from(value: Uuid) -> Self {
5548 Self::Uuid(value)
5549 }
5550}
5551
5552impl From<(&'static str, u32)> for ElementId {
5553 fn from((name, id): (&'static str, u32)) -> Self {
5554 ElementId::NamedInteger(name.into(), id.into())
5555 }
5556}
5557
5558impl<T: Into<SharedString>> From<(ElementId, T)> for ElementId {
5559 fn from((id, name): (ElementId, T)) -> Self {
5560 ElementId::NamedChild(Arc::new(id), name.into())
5561 }
5562}
5563
5564impl From<&'static core::panic::Location<'static>> for ElementId {
5565 fn from(location: &'static core::panic::Location<'static>) -> Self {
5566 ElementId::CodeLocation(*location)
5567 }
5568}
5569
5570/// A rectangle to be rendered in the window at the given position and size.
5571/// Passed as an argument [`Window::paint_quad`].
5572#[derive(Clone)]
5573pub struct PaintQuad {
5574 /// The bounds of the quad within the window.
5575 pub bounds: Bounds<Pixels>,
5576 /// The radii of the quad's corners.
5577 pub corner_radii: Corners<Pixels>,
5578 /// The background color of the quad.
5579 pub background: Background,
5580 /// The widths of the quad's borders.
5581 pub border_widths: Edges<Pixels>,
5582 /// The color of the quad's borders.
5583 pub border_color: Hsla,
5584 /// The style of the quad's borders.
5585 pub border_style: BorderStyle,
5586}
5587
5588impl PaintQuad {
5589 /// Sets the corner radii of the quad.
5590 pub fn corner_radii(self, corner_radii: impl Into<Corners<Pixels>>) -> Self {
5591 PaintQuad {
5592 corner_radii: corner_radii.into(),
5593 ..self
5594 }
5595 }
5596
5597 /// Sets the border widths of the quad.
5598 pub fn border_widths(self, border_widths: impl Into<Edges<Pixels>>) -> Self {
5599 PaintQuad {
5600 border_widths: border_widths.into(),
5601 ..self
5602 }
5603 }
5604
5605 /// Sets the border color of the quad.
5606 pub fn border_color(self, border_color: impl Into<Hsla>) -> Self {
5607 PaintQuad {
5608 border_color: border_color.into(),
5609 ..self
5610 }
5611 }
5612
5613 /// Sets the background color of the quad.
5614 pub fn background(self, background: impl Into<Background>) -> Self {
5615 PaintQuad {
5616 background: background.into(),
5617 ..self
5618 }
5619 }
5620}
5621
5622/// Creates a quad with the given parameters.
5623pub fn quad(
5624 bounds: Bounds<Pixels>,
5625 corner_radii: impl Into<Corners<Pixels>>,
5626 background: impl Into<Background>,
5627 border_widths: impl Into<Edges<Pixels>>,
5628 border_color: impl Into<Hsla>,
5629 border_style: BorderStyle,
5630) -> PaintQuad {
5631 PaintQuad {
5632 bounds,
5633 corner_radii: corner_radii.into(),
5634 background: background.into(),
5635 border_widths: border_widths.into(),
5636 border_color: border_color.into(),
5637 border_style,
5638 }
5639}
5640
5641/// Creates a filled quad with the given bounds and background color.
5642pub fn fill(bounds: impl Into<Bounds<Pixels>>, background: impl Into<Background>) -> PaintQuad {
5643 PaintQuad {
5644 bounds: bounds.into(),
5645 corner_radii: (0.).into(),
5646 background: background.into(),
5647 border_widths: (0.).into(),
5648 border_color: transparent_black(),
5649 border_style: BorderStyle::default(),
5650 }
5651}
5652
5653/// Creates a rectangle outline with the given bounds, border color, and a 1px border width
5654pub fn outline(
5655 bounds: impl Into<Bounds<Pixels>>,
5656 border_color: impl Into<Hsla>,
5657 border_style: BorderStyle,
5658) -> PaintQuad {
5659 PaintQuad {
5660 bounds: bounds.into(),
5661 corner_radii: (0.).into(),
5662 background: transparent_black().into(),
5663 border_widths: (1.).into(),
5664 border_color: border_color.into(),
5665 border_style,
5666 }
5667}