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