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