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