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