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