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