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