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