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