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