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