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