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