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