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