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