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