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