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::MouseExited(mouse_exited) => {
3709 self.modifiers = mouse_exited.modifiers;
3710 PlatformInput::MouseExited(mouse_exited)
3711 }
3712 PlatformInput::ModifiersChanged(modifiers_changed) => {
3713 self.modifiers = modifiers_changed.modifiers;
3714 self.capslock = modifiers_changed.capslock;
3715 PlatformInput::ModifiersChanged(modifiers_changed)
3716 }
3717 PlatformInput::ScrollWheel(scroll_wheel) => {
3718 self.mouse_position = scroll_wheel.position;
3719 self.modifiers = scroll_wheel.modifiers;
3720 PlatformInput::ScrollWheel(scroll_wheel)
3721 }
3722 // Translate dragging and dropping of external files from the operating system
3723 // to internal drag and drop events.
3724 PlatformInput::FileDrop(file_drop) => match file_drop {
3725 FileDropEvent::Entered { position, paths } => {
3726 self.mouse_position = position;
3727 if cx.active_drag.is_none() {
3728 cx.active_drag = Some(AnyDrag {
3729 value: Arc::new(paths.clone()),
3730 view: cx.new(|_| paths).into(),
3731 cursor_offset: position,
3732 cursor_style: None,
3733 });
3734 }
3735 PlatformInput::MouseMove(MouseMoveEvent {
3736 position,
3737 pressed_button: Some(MouseButton::Left),
3738 modifiers: Modifiers::default(),
3739 })
3740 }
3741 FileDropEvent::Pending { position } => {
3742 self.mouse_position = position;
3743 PlatformInput::MouseMove(MouseMoveEvent {
3744 position,
3745 pressed_button: Some(MouseButton::Left),
3746 modifiers: Modifiers::default(),
3747 })
3748 }
3749 FileDropEvent::Submit { position } => {
3750 cx.activate(true);
3751 self.mouse_position = position;
3752 PlatformInput::MouseUp(MouseUpEvent {
3753 button: MouseButton::Left,
3754 position,
3755 modifiers: Modifiers::default(),
3756 click_count: 1,
3757 })
3758 }
3759 FileDropEvent::Exited => {
3760 cx.active_drag.take();
3761 PlatformInput::FileDrop(FileDropEvent::Exited)
3762 }
3763 },
3764 PlatformInput::KeyDown(_) | PlatformInput::KeyUp(_) => event,
3765 };
3766
3767 if let Some(any_mouse_event) = event.mouse_event() {
3768 self.dispatch_mouse_event(any_mouse_event, cx);
3769 } else if let Some(any_key_event) = event.keyboard_event() {
3770 self.dispatch_key_event(any_key_event, cx);
3771 }
3772
3773 DispatchEventResult {
3774 propagate: cx.propagate_event,
3775 default_prevented: self.default_prevented,
3776 }
3777 }
3778
3779 fn dispatch_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
3780 let hit_test = self.rendered_frame.hit_test(self.mouse_position());
3781 if hit_test != self.mouse_hit_test {
3782 self.mouse_hit_test = hit_test;
3783 self.reset_cursor_style(cx);
3784 }
3785
3786 #[cfg(any(feature = "inspector", debug_assertions))]
3787 if self.is_inspector_picking(cx) {
3788 self.handle_inspector_mouse_event(event, cx);
3789 // When inspector is picking, all other mouse handling is skipped.
3790 return;
3791 }
3792
3793 let mut mouse_listeners = mem::take(&mut self.rendered_frame.mouse_listeners);
3794
3795 // Capture phase, events bubble from back to front. Handlers for this phase are used for
3796 // special purposes, such as detecting events outside of a given Bounds.
3797 for listener in &mut mouse_listeners {
3798 let listener = listener.as_mut().unwrap();
3799 listener(event, DispatchPhase::Capture, self, cx);
3800 if !cx.propagate_event {
3801 break;
3802 }
3803 }
3804
3805 // Bubble phase, where most normal handlers do their work.
3806 if cx.propagate_event {
3807 for listener in mouse_listeners.iter_mut().rev() {
3808 let listener = listener.as_mut().unwrap();
3809 listener(event, DispatchPhase::Bubble, self, cx);
3810 if !cx.propagate_event {
3811 break;
3812 }
3813 }
3814 }
3815
3816 self.rendered_frame.mouse_listeners = mouse_listeners;
3817
3818 if cx.has_active_drag() {
3819 if event.is::<MouseMoveEvent>() {
3820 // If this was a mouse move event, redraw the window so that the
3821 // active drag can follow the mouse cursor.
3822 self.refresh();
3823 } else if event.is::<MouseUpEvent>() {
3824 // If this was a mouse up event, cancel the active drag and redraw
3825 // the window.
3826 cx.active_drag = None;
3827 self.refresh();
3828 }
3829 }
3830 }
3831
3832 fn dispatch_key_event(&mut self, event: &dyn Any, cx: &mut App) {
3833 if self.invalidator.is_dirty() {
3834 self.draw(cx).clear();
3835 }
3836
3837 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
3838 let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
3839
3840 let mut keystroke: Option<Keystroke> = None;
3841
3842 if let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() {
3843 if event.modifiers.number_of_modifiers() == 0
3844 && self.pending_modifier.modifiers.number_of_modifiers() == 1
3845 && !self.pending_modifier.saw_keystroke
3846 {
3847 let key = match self.pending_modifier.modifiers {
3848 modifiers if modifiers.shift => Some("shift"),
3849 modifiers if modifiers.control => Some("control"),
3850 modifiers if modifiers.alt => Some("alt"),
3851 modifiers if modifiers.platform => Some("platform"),
3852 modifiers if modifiers.function => Some("function"),
3853 _ => None,
3854 };
3855 if let Some(key) = key {
3856 keystroke = Some(Keystroke {
3857 key: key.to_string(),
3858 key_char: None,
3859 modifiers: Modifiers::default(),
3860 });
3861 }
3862 }
3863
3864 if self.pending_modifier.modifiers.number_of_modifiers() == 0
3865 && event.modifiers.number_of_modifiers() == 1
3866 {
3867 self.pending_modifier.saw_keystroke = false
3868 }
3869 self.pending_modifier.modifiers = event.modifiers
3870 } else if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
3871 self.pending_modifier.saw_keystroke = true;
3872 keystroke = Some(key_down_event.keystroke.clone());
3873 }
3874
3875 let Some(keystroke) = keystroke else {
3876 self.finish_dispatch_key_event(event, dispatch_path, self.context_stack(), cx);
3877 return;
3878 };
3879
3880 cx.propagate_event = true;
3881 self.dispatch_keystroke_interceptors(event, self.context_stack(), cx);
3882 if !cx.propagate_event {
3883 self.finish_dispatch_key_event(event, dispatch_path, self.context_stack(), cx);
3884 return;
3885 }
3886
3887 let mut currently_pending = self.pending_input.take().unwrap_or_default();
3888 if currently_pending.focus.is_some() && currently_pending.focus != self.focus {
3889 currently_pending = PendingInput::default();
3890 }
3891
3892 let match_result = self.rendered_frame.dispatch_tree.dispatch_key(
3893 currently_pending.keystrokes,
3894 keystroke,
3895 &dispatch_path,
3896 );
3897
3898 if !match_result.to_replay.is_empty() {
3899 self.replay_pending_input(match_result.to_replay, cx);
3900 cx.propagate_event = true;
3901 }
3902
3903 if !match_result.pending.is_empty() {
3904 currently_pending.timer.take();
3905 currently_pending.keystrokes = match_result.pending;
3906 currently_pending.focus = self.focus;
3907
3908 let text_input_requires_timeout = event
3909 .downcast_ref::<KeyDownEvent>()
3910 .filter(|key_down| key_down.keystroke.key_char.is_some())
3911 .and_then(|_| self.platform_window.take_input_handler())
3912 .map_or(false, |mut input_handler| {
3913 let accepts = input_handler.accepts_text_input(self, cx);
3914 self.platform_window.set_input_handler(input_handler);
3915 accepts
3916 });
3917
3918 currently_pending.needs_timeout |=
3919 match_result.pending_has_binding || text_input_requires_timeout;
3920
3921 if currently_pending.needs_timeout {
3922 currently_pending.timer = Some(self.spawn(cx, async move |cx| {
3923 cx.background_executor.timer(Duration::from_secs(1)).await;
3924 cx.update(move |window, cx| {
3925 let Some(currently_pending) = window
3926 .pending_input
3927 .take()
3928 .filter(|pending| pending.focus == window.focus)
3929 else {
3930 return;
3931 };
3932
3933 let node_id = window.focus_node_id_in_rendered_frame(window.focus);
3934 let dispatch_path =
3935 window.rendered_frame.dispatch_tree.dispatch_path(node_id);
3936
3937 let to_replay = window
3938 .rendered_frame
3939 .dispatch_tree
3940 .flush_dispatch(currently_pending.keystrokes, &dispatch_path);
3941
3942 window.pending_input_changed(cx);
3943 window.replay_pending_input(to_replay, cx)
3944 })
3945 .log_err();
3946 }));
3947 } else {
3948 currently_pending.timer = None;
3949 }
3950 self.pending_input = Some(currently_pending);
3951 self.pending_input_changed(cx);
3952 cx.propagate_event = false;
3953 return;
3954 }
3955
3956 let skip_bindings = event
3957 .downcast_ref::<KeyDownEvent>()
3958 .filter(|key_down_event| key_down_event.prefer_character_input)
3959 .map(|_| {
3960 self.platform_window
3961 .take_input_handler()
3962 .map_or(false, |mut input_handler| {
3963 let accepts = input_handler.accepts_text_input(self, cx);
3964 self.platform_window.set_input_handler(input_handler);
3965 // If modifiers are not excessive (e.g. AltGr), and the input handler is accepting text input,
3966 // we prefer the text input over bindings.
3967 accepts
3968 })
3969 })
3970 .unwrap_or(false);
3971
3972 if !skip_bindings {
3973 for binding in match_result.bindings {
3974 self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
3975 if !cx.propagate_event {
3976 self.dispatch_keystroke_observers(
3977 event,
3978 Some(binding.action),
3979 match_result.context_stack,
3980 cx,
3981 );
3982 self.pending_input_changed(cx);
3983 return;
3984 }
3985 }
3986 }
3987
3988 self.finish_dispatch_key_event(event, dispatch_path, match_result.context_stack, cx);
3989 self.pending_input_changed(cx);
3990 }
3991
3992 fn finish_dispatch_key_event(
3993 &mut self,
3994 event: &dyn Any,
3995 dispatch_path: SmallVec<[DispatchNodeId; 32]>,
3996 context_stack: Vec<KeyContext>,
3997 cx: &mut App,
3998 ) {
3999 self.dispatch_key_down_up_event(event, &dispatch_path, cx);
4000 if !cx.propagate_event {
4001 return;
4002 }
4003
4004 self.dispatch_modifiers_changed_event(event, &dispatch_path, cx);
4005 if !cx.propagate_event {
4006 return;
4007 }
4008
4009 self.dispatch_keystroke_observers(event, None, context_stack, cx);
4010 }
4011
4012 fn pending_input_changed(&mut self, cx: &mut App) {
4013 self.pending_input_observers
4014 .clone()
4015 .retain(&(), |callback| callback(self, cx));
4016 }
4017
4018 fn dispatch_key_down_up_event(
4019 &mut self,
4020 event: &dyn Any,
4021 dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
4022 cx: &mut App,
4023 ) {
4024 // Capture phase
4025 for node_id in dispatch_path {
4026 let node = self.rendered_frame.dispatch_tree.node(*node_id);
4027
4028 for key_listener in node.key_listeners.clone() {
4029 key_listener(event, DispatchPhase::Capture, self, cx);
4030 if !cx.propagate_event {
4031 return;
4032 }
4033 }
4034 }
4035
4036 // Bubble phase
4037 for node_id in dispatch_path.iter().rev() {
4038 // Handle low level key events
4039 let node = self.rendered_frame.dispatch_tree.node(*node_id);
4040 for key_listener in node.key_listeners.clone() {
4041 key_listener(event, DispatchPhase::Bubble, self, cx);
4042 if !cx.propagate_event {
4043 return;
4044 }
4045 }
4046 }
4047 }
4048
4049 fn dispatch_modifiers_changed_event(
4050 &mut self,
4051 event: &dyn Any,
4052 dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
4053 cx: &mut App,
4054 ) {
4055 let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() else {
4056 return;
4057 };
4058 for node_id in dispatch_path.iter().rev() {
4059 let node = self.rendered_frame.dispatch_tree.node(*node_id);
4060 for listener in node.modifiers_changed_listeners.clone() {
4061 listener(event, self, cx);
4062 if !cx.propagate_event {
4063 return;
4064 }
4065 }
4066 }
4067 }
4068
4069 /// Determine whether a potential multi-stroke key binding is in progress on this window.
4070 pub fn has_pending_keystrokes(&self) -> bool {
4071 self.pending_input.is_some()
4072 }
4073
4074 pub(crate) fn clear_pending_keystrokes(&mut self) {
4075 self.pending_input.take();
4076 }
4077
4078 /// Returns the currently pending input keystrokes that might result in a multi-stroke key binding.
4079 pub fn pending_input_keystrokes(&self) -> Option<&[Keystroke]> {
4080 self.pending_input
4081 .as_ref()
4082 .map(|pending_input| pending_input.keystrokes.as_slice())
4083 }
4084
4085 fn replay_pending_input(&mut self, replays: SmallVec<[Replay; 1]>, cx: &mut App) {
4086 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
4087 let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
4088
4089 'replay: for replay in replays {
4090 let event = KeyDownEvent {
4091 keystroke: replay.keystroke.clone(),
4092 is_held: false,
4093 prefer_character_input: true,
4094 };
4095
4096 cx.propagate_event = true;
4097 for binding in replay.bindings {
4098 self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
4099 if !cx.propagate_event {
4100 self.dispatch_keystroke_observers(
4101 &event,
4102 Some(binding.action),
4103 Vec::default(),
4104 cx,
4105 );
4106 continue 'replay;
4107 }
4108 }
4109
4110 self.dispatch_key_down_up_event(&event, &dispatch_path, cx);
4111 if !cx.propagate_event {
4112 continue 'replay;
4113 }
4114 if let Some(input) = replay.keystroke.key_char.as_ref().cloned()
4115 && let Some(mut input_handler) = self.platform_window.take_input_handler()
4116 {
4117 input_handler.dispatch_input(&input, self, cx);
4118 self.platform_window.set_input_handler(input_handler)
4119 }
4120 }
4121 }
4122
4123 fn focus_node_id_in_rendered_frame(&self, focus_id: Option<FocusId>) -> DispatchNodeId {
4124 focus_id
4125 .and_then(|focus_id| {
4126 self.rendered_frame
4127 .dispatch_tree
4128 .focusable_node_id(focus_id)
4129 })
4130 .unwrap_or_else(|| self.rendered_frame.dispatch_tree.root_node_id())
4131 }
4132
4133 fn dispatch_action_on_node(
4134 &mut self,
4135 node_id: DispatchNodeId,
4136 action: &dyn Action,
4137 cx: &mut App,
4138 ) {
4139 let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
4140
4141 // Capture phase for global actions.
4142 cx.propagate_event = true;
4143 if let Some(mut global_listeners) = cx
4144 .global_action_listeners
4145 .remove(&action.as_any().type_id())
4146 {
4147 for listener in &global_listeners {
4148 listener(action.as_any(), DispatchPhase::Capture, cx);
4149 if !cx.propagate_event {
4150 break;
4151 }
4152 }
4153
4154 global_listeners.extend(
4155 cx.global_action_listeners
4156 .remove(&action.as_any().type_id())
4157 .unwrap_or_default(),
4158 );
4159
4160 cx.global_action_listeners
4161 .insert(action.as_any().type_id(), global_listeners);
4162 }
4163
4164 if !cx.propagate_event {
4165 return;
4166 }
4167
4168 // Capture phase for window actions.
4169 for node_id in &dispatch_path {
4170 let node = self.rendered_frame.dispatch_tree.node(*node_id);
4171 for DispatchActionListener {
4172 action_type,
4173 listener,
4174 } in node.action_listeners.clone()
4175 {
4176 let any_action = action.as_any();
4177 if action_type == any_action.type_id() {
4178 listener(any_action, DispatchPhase::Capture, self, cx);
4179
4180 if !cx.propagate_event {
4181 return;
4182 }
4183 }
4184 }
4185 }
4186
4187 // Bubble phase for window actions.
4188 for node_id in dispatch_path.iter().rev() {
4189 let node = self.rendered_frame.dispatch_tree.node(*node_id);
4190 for DispatchActionListener {
4191 action_type,
4192 listener,
4193 } in node.action_listeners.clone()
4194 {
4195 let any_action = action.as_any();
4196 if action_type == any_action.type_id() {
4197 cx.propagate_event = false; // Actions stop propagation by default during the bubble phase
4198 listener(any_action, DispatchPhase::Bubble, self, cx);
4199
4200 if !cx.propagate_event {
4201 return;
4202 }
4203 }
4204 }
4205 }
4206
4207 // Bubble phase for global actions.
4208 if let Some(mut global_listeners) = cx
4209 .global_action_listeners
4210 .remove(&action.as_any().type_id())
4211 {
4212 for listener in global_listeners.iter().rev() {
4213 cx.propagate_event = false; // Actions stop propagation by default during the bubble phase
4214
4215 listener(action.as_any(), DispatchPhase::Bubble, cx);
4216 if !cx.propagate_event {
4217 break;
4218 }
4219 }
4220
4221 global_listeners.extend(
4222 cx.global_action_listeners
4223 .remove(&action.as_any().type_id())
4224 .unwrap_or_default(),
4225 );
4226
4227 cx.global_action_listeners
4228 .insert(action.as_any().type_id(), global_listeners);
4229 }
4230 }
4231
4232 /// Register the given handler to be invoked whenever the global of the given type
4233 /// is updated.
4234 pub fn observe_global<G: Global>(
4235 &mut self,
4236 cx: &mut App,
4237 f: impl Fn(&mut Window, &mut App) + 'static,
4238 ) -> Subscription {
4239 let window_handle = self.handle;
4240 let (subscription, activate) = cx.global_observers.insert(
4241 TypeId::of::<G>(),
4242 Box::new(move |cx| {
4243 window_handle
4244 .update(cx, |_, window, cx| f(window, cx))
4245 .is_ok()
4246 }),
4247 );
4248 cx.defer(move |_| activate());
4249 subscription
4250 }
4251
4252 /// Focus the current window and bring it to the foreground at the platform level.
4253 pub fn activate_window(&self) {
4254 self.platform_window.activate();
4255 }
4256
4257 /// Minimize the current window at the platform level.
4258 pub fn minimize_window(&self) {
4259 self.platform_window.minimize();
4260 }
4261
4262 /// Toggle full screen status on the current window at the platform level.
4263 pub fn toggle_fullscreen(&self) {
4264 self.platform_window.toggle_fullscreen();
4265 }
4266
4267 /// Updates the IME panel position suggestions for languages like japanese, chinese.
4268 pub fn invalidate_character_coordinates(&self) {
4269 self.on_next_frame(|window, cx| {
4270 if let Some(mut input_handler) = window.platform_window.take_input_handler() {
4271 if let Some(bounds) = input_handler.selected_bounds(window, cx) {
4272 window.platform_window.update_ime_position(bounds);
4273 }
4274 window.platform_window.set_input_handler(input_handler);
4275 }
4276 });
4277 }
4278
4279 /// Present a platform dialog.
4280 /// The provided message will be presented, along with buttons for each answer.
4281 /// When a button is clicked, the returned Receiver will receive the index of the clicked button.
4282 pub fn prompt<T>(
4283 &mut self,
4284 level: PromptLevel,
4285 message: &str,
4286 detail: Option<&str>,
4287 answers: &[T],
4288 cx: &mut App,
4289 ) -> oneshot::Receiver<usize>
4290 where
4291 T: Clone + Into<PromptButton>,
4292 {
4293 let prompt_builder = cx.prompt_builder.take();
4294 let Some(prompt_builder) = prompt_builder else {
4295 unreachable!("Re-entrant window prompting is not supported by GPUI");
4296 };
4297
4298 let answers = answers
4299 .iter()
4300 .map(|answer| answer.clone().into())
4301 .collect::<Vec<_>>();
4302
4303 let receiver = match &prompt_builder {
4304 PromptBuilder::Default => self
4305 .platform_window
4306 .prompt(level, message, detail, &answers)
4307 .unwrap_or_else(|| {
4308 self.build_custom_prompt(&prompt_builder, level, message, detail, &answers, cx)
4309 }),
4310 PromptBuilder::Custom(_) => {
4311 self.build_custom_prompt(&prompt_builder, level, message, detail, &answers, cx)
4312 }
4313 };
4314
4315 cx.prompt_builder = Some(prompt_builder);
4316
4317 receiver
4318 }
4319
4320 fn build_custom_prompt(
4321 &mut self,
4322 prompt_builder: &PromptBuilder,
4323 level: PromptLevel,
4324 message: &str,
4325 detail: Option<&str>,
4326 answers: &[PromptButton],
4327 cx: &mut App,
4328 ) -> oneshot::Receiver<usize> {
4329 let (sender, receiver) = oneshot::channel();
4330 let handle = PromptHandle::new(sender);
4331 let handle = (prompt_builder)(level, message, detail, answers, handle, self, cx);
4332 self.prompt = Some(handle);
4333 receiver
4334 }
4335
4336 /// Returns the current context stack.
4337 pub fn context_stack(&self) -> Vec<KeyContext> {
4338 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
4339 let dispatch_tree = &self.rendered_frame.dispatch_tree;
4340 dispatch_tree
4341 .dispatch_path(node_id)
4342 .iter()
4343 .filter_map(move |&node_id| dispatch_tree.node(node_id).context.clone())
4344 .collect()
4345 }
4346
4347 /// Returns all available actions for the focused element.
4348 pub fn available_actions(&self, cx: &App) -> Vec<Box<dyn Action>> {
4349 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
4350 let mut actions = self.rendered_frame.dispatch_tree.available_actions(node_id);
4351 for action_type in cx.global_action_listeners.keys() {
4352 if let Err(ix) = actions.binary_search_by_key(action_type, |a| a.as_any().type_id()) {
4353 let action = cx.actions.build_action_type(action_type).ok();
4354 if let Some(action) = action {
4355 actions.insert(ix, action);
4356 }
4357 }
4358 }
4359 actions
4360 }
4361
4362 /// Returns key bindings that invoke an action on the currently focused element. Bindings are
4363 /// returned in the order they were added. For display, the last binding should take precedence.
4364 pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
4365 self.rendered_frame
4366 .dispatch_tree
4367 .bindings_for_action(action, &self.rendered_frame.dispatch_tree.context_stack)
4368 }
4369
4370 /// Returns the highest precedence key binding that invokes an action on the currently focused
4371 /// element. This is more efficient than getting the last result of `bindings_for_action`.
4372 pub fn highest_precedence_binding_for_action(&self, action: &dyn Action) -> Option<KeyBinding> {
4373 self.rendered_frame
4374 .dispatch_tree
4375 .highest_precedence_binding_for_action(
4376 action,
4377 &self.rendered_frame.dispatch_tree.context_stack,
4378 )
4379 }
4380
4381 /// Returns the key bindings for an action in a context.
4382 pub fn bindings_for_action_in_context(
4383 &self,
4384 action: &dyn Action,
4385 context: KeyContext,
4386 ) -> Vec<KeyBinding> {
4387 let dispatch_tree = &self.rendered_frame.dispatch_tree;
4388 dispatch_tree.bindings_for_action(action, &[context])
4389 }
4390
4391 /// Returns the highest precedence key binding for an action in a context. This is more
4392 /// efficient than getting the last result of `bindings_for_action_in_context`.
4393 pub fn highest_precedence_binding_for_action_in_context(
4394 &self,
4395 action: &dyn Action,
4396 context: KeyContext,
4397 ) -> Option<KeyBinding> {
4398 let dispatch_tree = &self.rendered_frame.dispatch_tree;
4399 dispatch_tree.highest_precedence_binding_for_action(action, &[context])
4400 }
4401
4402 /// Returns any bindings that would invoke an action on the given focus handle if it were
4403 /// focused. Bindings are returned in the order they were added. For display, the last binding
4404 /// should take precedence.
4405 pub fn bindings_for_action_in(
4406 &self,
4407 action: &dyn Action,
4408 focus_handle: &FocusHandle,
4409 ) -> Vec<KeyBinding> {
4410 let dispatch_tree = &self.rendered_frame.dispatch_tree;
4411 let Some(context_stack) = self.context_stack_for_focus_handle(focus_handle) else {
4412 return vec![];
4413 };
4414 dispatch_tree.bindings_for_action(action, &context_stack)
4415 }
4416
4417 /// Returns the highest precedence key binding that would invoke an action on the given focus
4418 /// handle if it were focused. This is more efficient than getting the last result of
4419 /// `bindings_for_action_in`.
4420 pub fn highest_precedence_binding_for_action_in(
4421 &self,
4422 action: &dyn Action,
4423 focus_handle: &FocusHandle,
4424 ) -> Option<KeyBinding> {
4425 let dispatch_tree = &self.rendered_frame.dispatch_tree;
4426 let context_stack = self.context_stack_for_focus_handle(focus_handle)?;
4427 dispatch_tree.highest_precedence_binding_for_action(action, &context_stack)
4428 }
4429
4430 fn context_stack_for_focus_handle(
4431 &self,
4432 focus_handle: &FocusHandle,
4433 ) -> Option<Vec<KeyContext>> {
4434 let dispatch_tree = &self.rendered_frame.dispatch_tree;
4435 let node_id = dispatch_tree.focusable_node_id(focus_handle.id)?;
4436 let context_stack: Vec<_> = dispatch_tree
4437 .dispatch_path(node_id)
4438 .into_iter()
4439 .filter_map(|node_id| dispatch_tree.node(node_id).context.clone())
4440 .collect();
4441 Some(context_stack)
4442 }
4443
4444 /// Returns a generic event listener that invokes the given listener with the view and context associated with the given view handle.
4445 pub fn listener_for<T: 'static, E>(
4446 &self,
4447 view: &Entity<T>,
4448 f: impl Fn(&mut T, &E, &mut Window, &mut Context<T>) + 'static,
4449 ) -> impl Fn(&E, &mut Window, &mut App) + 'static {
4450 let view = view.downgrade();
4451 move |e: &E, window: &mut Window, cx: &mut App| {
4452 view.update(cx, |view, cx| f(view, e, window, cx)).ok();
4453 }
4454 }
4455
4456 /// Returns a generic handler that invokes the given handler with the view and context associated with the given view handle.
4457 pub fn handler_for<E: 'static, Callback: Fn(&mut E, &mut Window, &mut Context<E>) + 'static>(
4458 &self,
4459 entity: &Entity<E>,
4460 f: Callback,
4461 ) -> impl Fn(&mut Window, &mut App) + 'static {
4462 let entity = entity.downgrade();
4463 move |window: &mut Window, cx: &mut App| {
4464 entity.update(cx, |entity, cx| f(entity, window, cx)).ok();
4465 }
4466 }
4467
4468 /// Register a callback that can interrupt the closing of the current window based the returned boolean.
4469 /// If the callback returns false, the window won't be closed.
4470 pub fn on_window_should_close(
4471 &self,
4472 cx: &App,
4473 f: impl Fn(&mut Window, &mut App) -> bool + 'static,
4474 ) {
4475 let mut cx = self.to_async(cx);
4476 self.platform_window.on_should_close(Box::new(move || {
4477 cx.update(|window, cx| f(window, cx)).unwrap_or(true)
4478 }))
4479 }
4480
4481 /// Register an action listener on this node for the next frame. The type of action
4482 /// is determined by the first parameter of the given listener. When the next frame is rendered
4483 /// the listener will be cleared.
4484 ///
4485 /// This is a fairly low-level method, so prefer using action handlers on elements unless you have
4486 /// a specific need to register a listener yourself.
4487 ///
4488 /// This method should only be called as part of the paint phase of element drawing.
4489 pub fn on_action(
4490 &mut self,
4491 action_type: TypeId,
4492 listener: impl Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static,
4493 ) {
4494 self.invalidator.debug_assert_paint();
4495
4496 self.next_frame
4497 .dispatch_tree
4498 .on_action(action_type, Rc::new(listener));
4499 }
4500
4501 /// Register a capturing action listener on this node for the next frame if the condition is true.
4502 /// The type of action is determined by the first parameter of the given listener. When the next
4503 /// frame is rendered the listener will be cleared.
4504 ///
4505 /// This is a fairly low-level method, so prefer using action handlers on elements unless you have
4506 /// a specific need to register a listener yourself.
4507 ///
4508 /// This method should only be called as part of the paint phase of element drawing.
4509 pub fn on_action_when(
4510 &mut self,
4511 condition: bool,
4512 action_type: TypeId,
4513 listener: impl Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static,
4514 ) {
4515 self.invalidator.debug_assert_paint();
4516
4517 if condition {
4518 self.next_frame
4519 .dispatch_tree
4520 .on_action(action_type, Rc::new(listener));
4521 }
4522 }
4523
4524 /// Read information about the GPU backing this window.
4525 /// Currently returns None on Mac and Windows.
4526 pub fn gpu_specs(&self) -> Option<GpuSpecs> {
4527 self.platform_window.gpu_specs()
4528 }
4529
4530 /// Perform titlebar double-click action.
4531 /// This is macOS specific.
4532 pub fn titlebar_double_click(&self) {
4533 self.platform_window.titlebar_double_click();
4534 }
4535
4536 /// Gets the window's title at the platform level.
4537 /// This is macOS specific.
4538 pub fn window_title(&self) -> String {
4539 self.platform_window.get_title()
4540 }
4541
4542 /// Returns a list of all tabbed windows and their titles.
4543 /// This is macOS specific.
4544 pub fn tabbed_windows(&self) -> Option<Vec<SystemWindowTab>> {
4545 self.platform_window.tabbed_windows()
4546 }
4547
4548 /// Returns the tab bar visibility.
4549 /// This is macOS specific.
4550 pub fn tab_bar_visible(&self) -> bool {
4551 self.platform_window.tab_bar_visible()
4552 }
4553
4554 /// Merges all open windows into a single tabbed window.
4555 /// This is macOS specific.
4556 pub fn merge_all_windows(&self) {
4557 self.platform_window.merge_all_windows()
4558 }
4559
4560 /// Moves the tab to a new containing window.
4561 /// This is macOS specific.
4562 pub fn move_tab_to_new_window(&self) {
4563 self.platform_window.move_tab_to_new_window()
4564 }
4565
4566 /// Shows or hides the window tab overview.
4567 /// This is macOS specific.
4568 pub fn toggle_window_tab_overview(&self) {
4569 self.platform_window.toggle_window_tab_overview()
4570 }
4571
4572 /// Sets the tabbing identifier for the window.
4573 /// This is macOS specific.
4574 pub fn set_tabbing_identifier(&self, tabbing_identifier: Option<String>) {
4575 self.platform_window
4576 .set_tabbing_identifier(tabbing_identifier)
4577 }
4578
4579 /// Toggles the inspector mode on this window.
4580 #[cfg(any(feature = "inspector", debug_assertions))]
4581 pub fn toggle_inspector(&mut self, cx: &mut App) {
4582 self.inspector = match self.inspector {
4583 None => Some(cx.new(|_| Inspector::new())),
4584 Some(_) => None,
4585 };
4586 self.refresh();
4587 }
4588
4589 /// Returns true if the window is in inspector mode.
4590 pub fn is_inspector_picking(&self, _cx: &App) -> bool {
4591 #[cfg(any(feature = "inspector", debug_assertions))]
4592 {
4593 if let Some(inspector) = &self.inspector {
4594 return inspector.read(_cx).is_picking();
4595 }
4596 }
4597 false
4598 }
4599
4600 /// Executes the provided function with mutable access to an inspector state.
4601 #[cfg(any(feature = "inspector", debug_assertions))]
4602 pub fn with_inspector_state<T: 'static, R>(
4603 &mut self,
4604 _inspector_id: Option<&crate::InspectorElementId>,
4605 cx: &mut App,
4606 f: impl FnOnce(&mut Option<T>, &mut Self) -> R,
4607 ) -> R {
4608 if let Some(inspector_id) = _inspector_id
4609 && let Some(inspector) = &self.inspector
4610 {
4611 let inspector = inspector.clone();
4612 let active_element_id = inspector.read(cx).active_element_id();
4613 if Some(inspector_id) == active_element_id {
4614 return inspector.update(cx, |inspector, _cx| {
4615 inspector.with_active_element_state(self, f)
4616 });
4617 }
4618 }
4619 f(&mut None, self)
4620 }
4621
4622 #[cfg(any(feature = "inspector", debug_assertions))]
4623 pub(crate) fn build_inspector_element_id(
4624 &mut self,
4625 path: crate::InspectorElementPath,
4626 ) -> crate::InspectorElementId {
4627 self.invalidator.debug_assert_paint_or_prepaint();
4628 let path = Rc::new(path);
4629 let next_instance_id = self
4630 .next_frame
4631 .next_inspector_instance_ids
4632 .entry(path.clone())
4633 .or_insert(0);
4634 let instance_id = *next_instance_id;
4635 *next_instance_id += 1;
4636 crate::InspectorElementId { path, instance_id }
4637 }
4638
4639 #[cfg(any(feature = "inspector", debug_assertions))]
4640 fn prepaint_inspector(&mut self, inspector_width: Pixels, cx: &mut App) -> Option<AnyElement> {
4641 if let Some(inspector) = self.inspector.take() {
4642 let mut inspector_element = AnyView::from(inspector.clone()).into_any_element();
4643 inspector_element.prepaint_as_root(
4644 point(self.viewport_size.width - inspector_width, px(0.0)),
4645 size(inspector_width, self.viewport_size.height).into(),
4646 self,
4647 cx,
4648 );
4649 self.inspector = Some(inspector);
4650 Some(inspector_element)
4651 } else {
4652 None
4653 }
4654 }
4655
4656 #[cfg(any(feature = "inspector", debug_assertions))]
4657 fn paint_inspector(&mut self, mut inspector_element: Option<AnyElement>, cx: &mut App) {
4658 if let Some(mut inspector_element) = inspector_element {
4659 inspector_element.paint(self, cx);
4660 };
4661 }
4662
4663 /// Registers a hitbox that can be used for inspector picking mode, allowing users to select and
4664 /// inspect UI elements by clicking on them.
4665 #[cfg(any(feature = "inspector", debug_assertions))]
4666 pub fn insert_inspector_hitbox(
4667 &mut self,
4668 hitbox_id: HitboxId,
4669 inspector_id: Option<&crate::InspectorElementId>,
4670 cx: &App,
4671 ) {
4672 self.invalidator.debug_assert_paint_or_prepaint();
4673 if !self.is_inspector_picking(cx) {
4674 return;
4675 }
4676 if let Some(inspector_id) = inspector_id {
4677 self.next_frame
4678 .inspector_hitboxes
4679 .insert(hitbox_id, inspector_id.clone());
4680 }
4681 }
4682
4683 #[cfg(any(feature = "inspector", debug_assertions))]
4684 fn paint_inspector_hitbox(&mut self, cx: &App) {
4685 if let Some(inspector) = self.inspector.as_ref() {
4686 let inspector = inspector.read(cx);
4687 if let Some((hitbox_id, _)) = self.hovered_inspector_hitbox(inspector, &self.next_frame)
4688 && let Some(hitbox) = self
4689 .next_frame
4690 .hitboxes
4691 .iter()
4692 .find(|hitbox| hitbox.id == hitbox_id)
4693 {
4694 self.paint_quad(crate::fill(hitbox.bounds, crate::rgba(0x61afef4d)));
4695 }
4696 }
4697 }
4698
4699 #[cfg(any(feature = "inspector", debug_assertions))]
4700 fn handle_inspector_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
4701 let Some(inspector) = self.inspector.clone() else {
4702 return;
4703 };
4704 if event.downcast_ref::<MouseMoveEvent>().is_some() {
4705 inspector.update(cx, |inspector, _cx| {
4706 if let Some((_, inspector_id)) =
4707 self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
4708 {
4709 inspector.hover(inspector_id, self);
4710 }
4711 });
4712 } else if event.downcast_ref::<crate::MouseDownEvent>().is_some() {
4713 inspector.update(cx, |inspector, _cx| {
4714 if let Some((_, inspector_id)) =
4715 self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
4716 {
4717 inspector.select(inspector_id, self);
4718 }
4719 });
4720 } else if let Some(event) = event.downcast_ref::<crate::ScrollWheelEvent>() {
4721 // This should be kept in sync with SCROLL_LINES in x11 platform.
4722 const SCROLL_LINES: f32 = 3.0;
4723 const SCROLL_PIXELS_PER_LAYER: f32 = 36.0;
4724 let delta_y = event
4725 .delta
4726 .pixel_delta(px(SCROLL_PIXELS_PER_LAYER / SCROLL_LINES))
4727 .y;
4728 if let Some(inspector) = self.inspector.clone() {
4729 inspector.update(cx, |inspector, _cx| {
4730 if let Some(depth) = inspector.pick_depth.as_mut() {
4731 *depth += f32::from(delta_y) / SCROLL_PIXELS_PER_LAYER;
4732 let max_depth = self.mouse_hit_test.ids.len() as f32 - 0.5;
4733 if *depth < 0.0 {
4734 *depth = 0.0;
4735 } else if *depth > max_depth {
4736 *depth = max_depth;
4737 }
4738 if let Some((_, inspector_id)) =
4739 self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
4740 {
4741 inspector.set_active_element_id(inspector_id, self);
4742 }
4743 }
4744 });
4745 }
4746 }
4747 }
4748
4749 #[cfg(any(feature = "inspector", debug_assertions))]
4750 fn hovered_inspector_hitbox(
4751 &self,
4752 inspector: &Inspector,
4753 frame: &Frame,
4754 ) -> Option<(HitboxId, crate::InspectorElementId)> {
4755 if let Some(pick_depth) = inspector.pick_depth {
4756 let depth = (pick_depth as i64).try_into().unwrap_or(0);
4757 let max_skipped = self.mouse_hit_test.ids.len().saturating_sub(1);
4758 let skip_count = (depth as usize).min(max_skipped);
4759 for hitbox_id in self.mouse_hit_test.ids.iter().skip(skip_count) {
4760 if let Some(inspector_id) = frame.inspector_hitboxes.get(hitbox_id) {
4761 return Some((*hitbox_id, inspector_id.clone()));
4762 }
4763 }
4764 }
4765 None
4766 }
4767
4768 /// For testing: set the current modifier keys state.
4769 /// This does not generate any events.
4770 #[cfg(any(test, feature = "test-support"))]
4771 pub fn set_modifiers(&mut self, modifiers: Modifiers) {
4772 self.modifiers = modifiers;
4773 }
4774}
4775
4776// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
4777slotmap::new_key_type! {
4778 /// A unique identifier for a window.
4779 pub struct WindowId;
4780}
4781
4782impl WindowId {
4783 /// Converts this window ID to a `u64`.
4784 pub fn as_u64(&self) -> u64 {
4785 self.0.as_ffi()
4786 }
4787}
4788
4789impl From<u64> for WindowId {
4790 fn from(value: u64) -> Self {
4791 WindowId(slotmap::KeyData::from_ffi(value))
4792 }
4793}
4794
4795/// A handle to a window with a specific root view type.
4796/// Note that this does not keep the window alive on its own.
4797#[derive(Deref, DerefMut)]
4798pub struct WindowHandle<V> {
4799 #[deref]
4800 #[deref_mut]
4801 pub(crate) any_handle: AnyWindowHandle,
4802 state_type: PhantomData<fn(V) -> V>,
4803}
4804
4805impl<V> Debug for WindowHandle<V> {
4806 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4807 f.debug_struct("WindowHandle")
4808 .field("any_handle", &self.any_handle.id.as_u64())
4809 .finish()
4810 }
4811}
4812
4813impl<V: 'static + Render> WindowHandle<V> {
4814 /// Creates a new handle from a window ID.
4815 /// This does not check if the root type of the window is `V`.
4816 pub fn new(id: WindowId) -> Self {
4817 WindowHandle {
4818 any_handle: AnyWindowHandle {
4819 id,
4820 state_type: TypeId::of::<V>(),
4821 },
4822 state_type: PhantomData,
4823 }
4824 }
4825
4826 /// Get the root view out of this window.
4827 ///
4828 /// This will fail if the window is closed or if the root view's type does not match `V`.
4829 #[cfg(any(test, feature = "test-support"))]
4830 pub fn root<C>(&self, cx: &mut C) -> Result<Entity<V>>
4831 where
4832 C: AppContext,
4833 {
4834 crate::Flatten::flatten(cx.update_window(self.any_handle, |root_view, _, _| {
4835 root_view
4836 .downcast::<V>()
4837 .map_err(|_| anyhow!("the type of the window's root view has changed"))
4838 }))
4839 }
4840
4841 /// Updates the root view of this window.
4842 ///
4843 /// This will fail if the window has been closed or if the root view's type does not match
4844 pub fn update<C, R>(
4845 &self,
4846 cx: &mut C,
4847 update: impl FnOnce(&mut V, &mut Window, &mut Context<V>) -> R,
4848 ) -> Result<R>
4849 where
4850 C: AppContext,
4851 {
4852 cx.update_window(self.any_handle, |root_view, window, cx| {
4853 let view = root_view
4854 .downcast::<V>()
4855 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
4856
4857 Ok(view.update(cx, |view, cx| update(view, window, cx)))
4858 })?
4859 }
4860
4861 /// Read the root view out of this window.
4862 ///
4863 /// This will fail if the window is closed or if the root view's type does not match `V`.
4864 pub fn read<'a>(&self, cx: &'a App) -> Result<&'a V> {
4865 let x = cx
4866 .windows
4867 .get(self.id)
4868 .and_then(|window| {
4869 window
4870 .as_deref()
4871 .and_then(|window| window.root.clone())
4872 .map(|root_view| root_view.downcast::<V>())
4873 })
4874 .context("window not found")?
4875 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
4876
4877 Ok(x.read(cx))
4878 }
4879
4880 /// Read the root view out of this window, with a callback
4881 ///
4882 /// This will fail if the window is closed or if the root view's type does not match `V`.
4883 pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &App) -> R) -> Result<R>
4884 where
4885 C: AppContext,
4886 {
4887 cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
4888 }
4889
4890 /// Read the root view pointer off of this window.
4891 ///
4892 /// This will fail if the window is closed or if the root view's type does not match `V`.
4893 pub fn entity<C>(&self, cx: &C) -> Result<Entity<V>>
4894 where
4895 C: AppContext,
4896 {
4897 cx.read_window(self, |root_view, _cx| root_view)
4898 }
4899
4900 /// Check if this window is 'active'.
4901 ///
4902 /// Will return `None` if the window is closed or currently
4903 /// borrowed.
4904 pub fn is_active(&self, cx: &mut App) -> Option<bool> {
4905 cx.update_window(self.any_handle, |_, window, _| window.is_window_active())
4906 .ok()
4907 }
4908}
4909
4910impl<V> Copy for WindowHandle<V> {}
4911
4912impl<V> Clone for WindowHandle<V> {
4913 fn clone(&self) -> Self {
4914 *self
4915 }
4916}
4917
4918impl<V> PartialEq for WindowHandle<V> {
4919 fn eq(&self, other: &Self) -> bool {
4920 self.any_handle == other.any_handle
4921 }
4922}
4923
4924impl<V> Eq for WindowHandle<V> {}
4925
4926impl<V> Hash for WindowHandle<V> {
4927 fn hash<H: Hasher>(&self, state: &mut H) {
4928 self.any_handle.hash(state);
4929 }
4930}
4931
4932impl<V: 'static> From<WindowHandle<V>> for AnyWindowHandle {
4933 fn from(val: WindowHandle<V>) -> Self {
4934 val.any_handle
4935 }
4936}
4937
4938/// A handle to a window with any root view type, which can be downcast to a window with a specific root view type.
4939#[derive(Copy, Clone, PartialEq, Eq, Hash)]
4940pub struct AnyWindowHandle {
4941 pub(crate) id: WindowId,
4942 state_type: TypeId,
4943}
4944
4945impl AnyWindowHandle {
4946 /// Get the ID of this window.
4947 pub fn window_id(&self) -> WindowId {
4948 self.id
4949 }
4950
4951 /// Attempt to convert this handle to a window handle with a specific root view type.
4952 /// If the types do not match, this will return `None`.
4953 pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
4954 if TypeId::of::<T>() == self.state_type {
4955 Some(WindowHandle {
4956 any_handle: *self,
4957 state_type: PhantomData,
4958 })
4959 } else {
4960 None
4961 }
4962 }
4963
4964 /// Updates the state of the root view of this window.
4965 ///
4966 /// This will fail if the window has been closed.
4967 pub fn update<C, R>(
4968 self,
4969 cx: &mut C,
4970 update: impl FnOnce(AnyView, &mut Window, &mut App) -> R,
4971 ) -> Result<R>
4972 where
4973 C: AppContext,
4974 {
4975 cx.update_window(self, update)
4976 }
4977
4978 /// Read the state of the root view of this window.
4979 ///
4980 /// This will fail if the window has been closed.
4981 pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(Entity<T>, &App) -> R) -> Result<R>
4982 where
4983 C: AppContext,
4984 T: 'static,
4985 {
4986 let view = self
4987 .downcast::<T>()
4988 .context("the type of the window's root view has changed")?;
4989
4990 cx.read_window(&view, read)
4991 }
4992}
4993
4994impl HasWindowHandle for Window {
4995 fn window_handle(&self) -> Result<raw_window_handle::WindowHandle<'_>, HandleError> {
4996 self.platform_window.window_handle()
4997 }
4998}
4999
5000impl HasDisplayHandle for Window {
5001 fn display_handle(
5002 &self,
5003 ) -> std::result::Result<raw_window_handle::DisplayHandle<'_>, HandleError> {
5004 self.platform_window.display_handle()
5005 }
5006}
5007
5008/// An identifier for an [`Element`].
5009///
5010/// Can be constructed with a string, a number, or both, as well
5011/// as other internal representations.
5012#[derive(Clone, Debug, Eq, PartialEq, Hash)]
5013pub enum ElementId {
5014 /// The ID of a View element
5015 View(EntityId),
5016 /// An integer ID.
5017 Integer(u64),
5018 /// A string based ID.
5019 Name(SharedString),
5020 /// A UUID.
5021 Uuid(Uuid),
5022 /// An ID that's equated with a focus handle.
5023 FocusHandle(FocusId),
5024 /// A combination of a name and an integer.
5025 NamedInteger(SharedString, u64),
5026 /// A path.
5027 Path(Arc<std::path::Path>),
5028 /// A code location.
5029 CodeLocation(core::panic::Location<'static>),
5030 /// A labeled child of an element.
5031 NamedChild(Arc<ElementId>, SharedString),
5032}
5033
5034impl ElementId {
5035 /// Constructs an `ElementId::NamedInteger` from a name and `usize`.
5036 pub fn named_usize(name: impl Into<SharedString>, integer: usize) -> ElementId {
5037 Self::NamedInteger(name.into(), integer as u64)
5038 }
5039}
5040
5041impl Display for ElementId {
5042 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
5043 match self {
5044 ElementId::View(entity_id) => write!(f, "view-{}", entity_id)?,
5045 ElementId::Integer(ix) => write!(f, "{}", ix)?,
5046 ElementId::Name(name) => write!(f, "{}", name)?,
5047 ElementId::FocusHandle(_) => write!(f, "FocusHandle")?,
5048 ElementId::NamedInteger(s, i) => write!(f, "{}-{}", s, i)?,
5049 ElementId::Uuid(uuid) => write!(f, "{}", uuid)?,
5050 ElementId::Path(path) => write!(f, "{}", path.display())?,
5051 ElementId::CodeLocation(location) => write!(f, "{}", location)?,
5052 ElementId::NamedChild(id, name) => write!(f, "{}-{}", id, name)?,
5053 }
5054
5055 Ok(())
5056 }
5057}
5058
5059impl TryInto<SharedString> for ElementId {
5060 type Error = anyhow::Error;
5061
5062 fn try_into(self) -> anyhow::Result<SharedString> {
5063 if let ElementId::Name(name) = self {
5064 Ok(name)
5065 } else {
5066 anyhow::bail!("element id is not string")
5067 }
5068 }
5069}
5070
5071impl From<usize> for ElementId {
5072 fn from(id: usize) -> Self {
5073 ElementId::Integer(id as u64)
5074 }
5075}
5076
5077impl From<i32> for ElementId {
5078 fn from(id: i32) -> Self {
5079 Self::Integer(id as u64)
5080 }
5081}
5082
5083impl From<SharedString> for ElementId {
5084 fn from(name: SharedString) -> Self {
5085 ElementId::Name(name)
5086 }
5087}
5088
5089impl From<String> for ElementId {
5090 fn from(name: String) -> Self {
5091 ElementId::Name(name.into())
5092 }
5093}
5094
5095impl From<Arc<str>> for ElementId {
5096 fn from(name: Arc<str>) -> Self {
5097 ElementId::Name(name.into())
5098 }
5099}
5100
5101impl From<Arc<std::path::Path>> for ElementId {
5102 fn from(path: Arc<std::path::Path>) -> Self {
5103 ElementId::Path(path)
5104 }
5105}
5106
5107impl From<&'static str> for ElementId {
5108 fn from(name: &'static str) -> Self {
5109 ElementId::Name(name.into())
5110 }
5111}
5112
5113impl<'a> From<&'a FocusHandle> for ElementId {
5114 fn from(handle: &'a FocusHandle) -> Self {
5115 ElementId::FocusHandle(handle.id)
5116 }
5117}
5118
5119impl From<(&'static str, EntityId)> for ElementId {
5120 fn from((name, id): (&'static str, EntityId)) -> Self {
5121 ElementId::NamedInteger(name.into(), id.as_u64())
5122 }
5123}
5124
5125impl From<(&'static str, usize)> for ElementId {
5126 fn from((name, id): (&'static str, usize)) -> Self {
5127 ElementId::NamedInteger(name.into(), id as u64)
5128 }
5129}
5130
5131impl From<(SharedString, usize)> for ElementId {
5132 fn from((name, id): (SharedString, usize)) -> Self {
5133 ElementId::NamedInteger(name, id as u64)
5134 }
5135}
5136
5137impl From<(&'static str, u64)> for ElementId {
5138 fn from((name, id): (&'static str, u64)) -> Self {
5139 ElementId::NamedInteger(name.into(), id)
5140 }
5141}
5142
5143impl From<Uuid> for ElementId {
5144 fn from(value: Uuid) -> Self {
5145 Self::Uuid(value)
5146 }
5147}
5148
5149impl From<(&'static str, u32)> for ElementId {
5150 fn from((name, id): (&'static str, u32)) -> Self {
5151 ElementId::NamedInteger(name.into(), id.into())
5152 }
5153}
5154
5155impl<T: Into<SharedString>> From<(ElementId, T)> for ElementId {
5156 fn from((id, name): (ElementId, T)) -> Self {
5157 ElementId::NamedChild(Arc::new(id), name.into())
5158 }
5159}
5160
5161impl From<&'static core::panic::Location<'static>> for ElementId {
5162 fn from(location: &'static core::panic::Location<'static>) -> Self {
5163 ElementId::CodeLocation(*location)
5164 }
5165}
5166
5167/// A rectangle to be rendered in the window at the given position and size.
5168/// Passed as an argument [`Window::paint_quad`].
5169#[derive(Clone)]
5170pub struct PaintQuad {
5171 /// The bounds of the quad within the window.
5172 pub bounds: Bounds<Pixels>,
5173 /// The radii of the quad's corners.
5174 pub corner_radii: Corners<Pixels>,
5175 /// The background color of the quad.
5176 pub background: Background,
5177 /// The widths of the quad's borders.
5178 pub border_widths: Edges<Pixels>,
5179 /// The color of the quad's borders.
5180 pub border_color: Hsla,
5181 /// The style of the quad's borders.
5182 pub border_style: BorderStyle,
5183}
5184
5185impl PaintQuad {
5186 /// Sets the corner radii of the quad.
5187 pub fn corner_radii(self, corner_radii: impl Into<Corners<Pixels>>) -> Self {
5188 PaintQuad {
5189 corner_radii: corner_radii.into(),
5190 ..self
5191 }
5192 }
5193
5194 /// Sets the border widths of the quad.
5195 pub fn border_widths(self, border_widths: impl Into<Edges<Pixels>>) -> Self {
5196 PaintQuad {
5197 border_widths: border_widths.into(),
5198 ..self
5199 }
5200 }
5201
5202 /// Sets the border color of the quad.
5203 pub fn border_color(self, border_color: impl Into<Hsla>) -> Self {
5204 PaintQuad {
5205 border_color: border_color.into(),
5206 ..self
5207 }
5208 }
5209
5210 /// Sets the background color of the quad.
5211 pub fn background(self, background: impl Into<Background>) -> Self {
5212 PaintQuad {
5213 background: background.into(),
5214 ..self
5215 }
5216 }
5217}
5218
5219/// Creates a quad with the given parameters.
5220pub fn quad(
5221 bounds: Bounds<Pixels>,
5222 corner_radii: impl Into<Corners<Pixels>>,
5223 background: impl Into<Background>,
5224 border_widths: impl Into<Edges<Pixels>>,
5225 border_color: impl Into<Hsla>,
5226 border_style: BorderStyle,
5227) -> PaintQuad {
5228 PaintQuad {
5229 bounds,
5230 corner_radii: corner_radii.into(),
5231 background: background.into(),
5232 border_widths: border_widths.into(),
5233 border_color: border_color.into(),
5234 border_style,
5235 }
5236}
5237
5238/// Creates a filled quad with the given bounds and background color.
5239pub fn fill(bounds: impl Into<Bounds<Pixels>>, background: impl Into<Background>) -> PaintQuad {
5240 PaintQuad {
5241 bounds: bounds.into(),
5242 corner_radii: (0.).into(),
5243 background: background.into(),
5244 border_widths: (0.).into(),
5245 border_color: transparent_black(),
5246 border_style: BorderStyle::default(),
5247 }
5248}
5249
5250/// Creates a rectangle outline with the given bounds, border color, and a 1px border width
5251pub fn outline(
5252 bounds: impl Into<Bounds<Pixels>>,
5253 border_color: impl Into<Hsla>,
5254 border_style: BorderStyle,
5255) -> PaintQuad {
5256 PaintQuad {
5257 bounds: bounds.into(),
5258 corner_radii: (0.).into(),
5259 background: transparent_black().into(),
5260 border_widths: (1.).into(),
5261 border_color: border_color.into(),
5262 border_style,
5263 }
5264}