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