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