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