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 println!("clearing focus 1");
709
710 #[cfg(any(feature = "inspector", debug_assertions))]
711 {
712 self.next_inspector_instance_ids.clear();
713 self.inspector_hitboxes.clear();
714 }
715 }
716
717 pub(crate) fn cursor_style(&self, window: &Window) -> Option<CursorStyle> {
718 self.cursor_styles
719 .iter()
720 .rev()
721 .fold_while(None, |style, request| match request.hitbox_id {
722 None => Done(Some(request.style)),
723 Some(hitbox_id) => Continue(
724 style.or_else(|| hitbox_id.is_hovered(window).then_some(request.style)),
725 ),
726 })
727 .into_inner()
728 }
729
730 pub(crate) fn hit_test(&self, position: Point<Pixels>) -> HitTest {
731 let mut set_hover_hitbox_count = false;
732 let mut hit_test = HitTest::default();
733 for hitbox in self.hitboxes.iter().rev() {
734 let bounds = hitbox.bounds.intersect(&hitbox.content_mask.bounds);
735 if bounds.contains(&position) {
736 hit_test.ids.push(hitbox.id);
737 if !set_hover_hitbox_count
738 && hitbox.behavior == HitboxBehavior::BlockMouseExceptScroll
739 {
740 hit_test.hover_hitbox_count = hit_test.ids.len();
741 set_hover_hitbox_count = true;
742 }
743 if hitbox.behavior == HitboxBehavior::BlockMouse {
744 break;
745 }
746 }
747 }
748 if !set_hover_hitbox_count {
749 hit_test.hover_hitbox_count = hit_test.ids.len();
750 }
751 hit_test
752 }
753
754 pub(crate) fn focus_path(&self) -> SmallVec<[FocusId; 8]> {
755 dbg!("focus path");
756 dbg!(self.focus.is_some());
757 self.focus
758 .map(|focus_id| self.dispatch_tree.focus_path(focus_id))
759 .unwrap_or_default()
760 }
761
762 pub(crate) fn finish(&mut self, prev_frame: &mut Self) {
763 for element_state_key in &self.accessed_element_states {
764 if let Some((element_state_key, element_state)) =
765 prev_frame.element_states.remove_entry(element_state_key)
766 {
767 self.element_states.insert(element_state_key, element_state);
768 }
769 }
770
771 self.scene.finish();
772 }
773}
774
775/// Holds the state for a specific window.
776pub struct Window {
777 pub(crate) handle: AnyWindowHandle,
778 pub(crate) invalidator: WindowInvalidator,
779 pub(crate) removed: bool,
780 pub(crate) platform_window: Box<dyn PlatformWindow>,
781 display_id: Option<DisplayId>,
782 sprite_atlas: Arc<dyn PlatformAtlas>,
783 text_system: Arc<WindowTextSystem>,
784 rem_size: Pixels,
785 /// The stack of override values for the window's rem size.
786 ///
787 /// This is used by `with_rem_size` to allow rendering an element tree with
788 /// a given rem size.
789 rem_size_override_stack: SmallVec<[Pixels; 8]>,
790 pub(crate) viewport_size: Size<Pixels>,
791 layout_engine: Option<TaffyLayoutEngine>,
792 pub(crate) root: Option<AnyView>,
793 pub(crate) element_id_stack: SmallVec<[ElementId; 32]>,
794 pub(crate) text_style_stack: Vec<TextStyleRefinement>,
795 pub(crate) rendered_entity_stack: Vec<EntityId>,
796 pub(crate) element_offset_stack: Vec<Point<Pixels>>,
797 pub(crate) element_opacity: Option<f32>,
798 pub(crate) content_mask_stack: Vec<ContentMask<Pixels>>,
799 pub(crate) requested_autoscroll: Option<Bounds<Pixels>>,
800 pub(crate) image_cache_stack: Vec<AnyImageCache>,
801 pub(crate) rendered_frame: Frame,
802 pub(crate) next_frame: Frame,
803 next_hitbox_id: HitboxId,
804 pub(crate) next_tooltip_id: TooltipId,
805 pub(crate) tooltip_bounds: Option<TooltipBounds>,
806 next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>>,
807 pub(crate) dirty_views: FxHashSet<EntityId>,
808 focus_listeners: SubscriberSet<(), AnyWindowFocusListener>,
809 pub(crate) focus_lost_listeners: SubscriberSet<(), AnyObserver>,
810 default_prevented: bool,
811 mouse_position: Point<Pixels>,
812 mouse_hit_test: HitTest,
813 modifiers: Modifiers,
814 capslock: Capslock,
815 scale_factor: f32,
816 pub(crate) bounds_observers: SubscriberSet<(), AnyObserver>,
817 appearance: WindowAppearance,
818 pub(crate) appearance_observers: SubscriberSet<(), AnyObserver>,
819 active: Rc<Cell<bool>>,
820 hovered: Rc<Cell<bool>>,
821 pub(crate) needs_present: Rc<Cell<bool>>,
822 pub(crate) last_input_timestamp: Rc<Cell<Instant>>,
823 pub(crate) refreshing: bool,
824 pub(crate) activation_observers: SubscriberSet<(), AnyObserver>,
825 pub(crate) focus: Option<FocusId>,
826 focus_enabled: bool,
827 pending_input: Option<PendingInput>,
828 pending_modifier: ModifierState,
829 pub(crate) pending_input_observers: SubscriberSet<(), AnyObserver>,
830 prompt: Option<RenderablePromptHandle>,
831 pub(crate) client_inset: Option<Pixels>,
832 #[cfg(any(feature = "inspector", debug_assertions))]
833 inspector: Option<Entity<Inspector>>,
834}
835
836#[derive(Clone, Debug, Default)]
837struct ModifierState {
838 modifiers: Modifiers,
839 saw_keystroke: bool,
840}
841
842#[derive(Clone, Copy, Debug, Eq, PartialEq)]
843pub(crate) enum DrawPhase {
844 None,
845 Prepaint,
846 Paint,
847 Focus,
848}
849
850#[derive(Default, Debug)]
851struct PendingInput {
852 keystrokes: SmallVec<[Keystroke; 1]>,
853 focus: Option<FocusId>,
854 timer: Option<Task<()>>,
855}
856
857pub(crate) struct ElementStateBox {
858 pub(crate) inner: Box<dyn Any>,
859 #[cfg(debug_assertions)]
860 pub(crate) type_name: &'static str,
861}
862
863fn default_bounds(display_id: Option<DisplayId>, cx: &mut App) -> Bounds<Pixels> {
864 const DEFAULT_WINDOW_OFFSET: Point<Pixels> = point(px(0.), px(35.));
865
866 // TODO, BUG: if you open a window with the currently active window
867 // on the stack, this will erroneously select the 'unwrap_or_else'
868 // code path
869 cx.active_window()
870 .and_then(|w| w.update(cx, |_, window, _| window.bounds()).ok())
871 .map(|mut bounds| {
872 bounds.origin += DEFAULT_WINDOW_OFFSET;
873 bounds
874 })
875 .unwrap_or_else(|| {
876 let display = display_id
877 .map(|id| cx.find_display(id))
878 .unwrap_or_else(|| cx.primary_display());
879
880 display
881 .map(|display| display.default_bounds())
882 .unwrap_or_else(|| Bounds::new(point(px(0.), px(0.)), DEFAULT_WINDOW_SIZE))
883 })
884}
885
886impl Window {
887 pub(crate) fn new(
888 handle: AnyWindowHandle,
889 options: WindowOptions,
890 cx: &mut App,
891 ) -> Result<Self> {
892 let WindowOptions {
893 window_bounds,
894 titlebar,
895 focus,
896 show,
897 kind,
898 is_movable,
899 display_id,
900 window_background,
901 app_id,
902 window_min_size,
903 window_decorations,
904 } = options;
905
906 let bounds = window_bounds
907 .map(|bounds| bounds.get_bounds())
908 .unwrap_or_else(|| default_bounds(display_id, cx));
909 let mut platform_window = cx.platform.open_window(
910 handle,
911 WindowParams {
912 bounds,
913 titlebar,
914 kind,
915 is_movable,
916 focus,
917 show,
918 display_id,
919 window_min_size,
920 },
921 )?;
922 let display_id = platform_window.display().map(|display| display.id());
923 let sprite_atlas = platform_window.sprite_atlas();
924 let mouse_position = platform_window.mouse_position();
925 let modifiers = platform_window.modifiers();
926 let capslock = platform_window.capslock();
927 let content_size = platform_window.content_size();
928 let scale_factor = platform_window.scale_factor();
929 let appearance = platform_window.appearance();
930 let text_system = Arc::new(WindowTextSystem::new(cx.text_system().clone()));
931 let invalidator = WindowInvalidator::new();
932 let active = Rc::new(Cell::new(platform_window.is_active()));
933 let hovered = Rc::new(Cell::new(platform_window.is_hovered()));
934 let needs_present = Rc::new(Cell::new(false));
935 let next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>> = Default::default();
936 let last_input_timestamp = Rc::new(Cell::new(Instant::now()));
937
938 platform_window
939 .request_decorations(window_decorations.unwrap_or(WindowDecorations::Server));
940 platform_window.set_background_appearance(window_background);
941
942 if let Some(ref window_open_state) = window_bounds {
943 match window_open_state {
944 WindowBounds::Fullscreen(_) => platform_window.toggle_fullscreen(),
945 WindowBounds::Maximized(_) => platform_window.zoom(),
946 WindowBounds::Windowed(_) => {}
947 }
948 }
949
950 platform_window.on_close(Box::new({
951 let mut cx = cx.to_async();
952 move || {
953 let _ = handle.update(&mut cx, |_, window, _| window.remove_window());
954 }
955 }));
956 platform_window.on_request_frame(Box::new({
957 let mut cx = cx.to_async();
958 let invalidator = invalidator.clone();
959 let active = active.clone();
960 let needs_present = needs_present.clone();
961 let next_frame_callbacks = next_frame_callbacks.clone();
962 let last_input_timestamp = last_input_timestamp.clone();
963 move |request_frame_options| {
964 let next_frame_callbacks = next_frame_callbacks.take();
965 if !next_frame_callbacks.is_empty() {
966 handle
967 .update(&mut cx, |_, window, cx| {
968 for callback in next_frame_callbacks {
969 callback(window, cx);
970 }
971 })
972 .log_err();
973 }
974
975 // Keep presenting the current scene for 1 extra second since the
976 // last input to prevent the display from underclocking the refresh rate.
977 let needs_present = request_frame_options.require_presentation
978 || needs_present.get()
979 || (active.get()
980 && last_input_timestamp.get().elapsed() < Duration::from_secs(1));
981
982 if invalidator.is_dirty() {
983 measure("frame duration", || {
984 handle
985 .update(&mut cx, |_, window, cx| {
986 let arena_clear_needed = window.draw(cx);
987 window.present();
988 // drop the arena elements after present to reduce latency
989 arena_clear_needed.clear();
990 })
991 .log_err();
992 })
993 } else if needs_present {
994 handle
995 .update(&mut cx, |_, window, _| window.present())
996 .log_err();
997 }
998
999 handle
1000 .update(&mut cx, |_, window, _| {
1001 window.complete_frame();
1002 })
1003 .log_err();
1004 }
1005 }));
1006 platform_window.on_resize(Box::new({
1007 let mut cx = cx.to_async();
1008 move |_, _| {
1009 handle
1010 .update(&mut cx, |_, window, cx| window.bounds_changed(cx))
1011 .log_err();
1012 }
1013 }));
1014 platform_window.on_moved(Box::new({
1015 let mut cx = cx.to_async();
1016 move || {
1017 handle
1018 .update(&mut cx, |_, window, cx| window.bounds_changed(cx))
1019 .log_err();
1020 }
1021 }));
1022 platform_window.on_appearance_changed(Box::new({
1023 let mut cx = cx.to_async();
1024 move || {
1025 handle
1026 .update(&mut cx, |_, window, cx| window.appearance_changed(cx))
1027 .log_err();
1028 }
1029 }));
1030 platform_window.on_active_status_change(Box::new({
1031 let mut cx = cx.to_async();
1032 move |active| {
1033 handle
1034 .update(&mut cx, |_, window, cx| {
1035 window.active.set(active);
1036 window.modifiers = window.platform_window.modifiers();
1037 window.capslock = window.platform_window.capslock();
1038 window
1039 .activation_observers
1040 .clone()
1041 .retain(&(), |callback| callback(window, cx));
1042 window.refresh();
1043 })
1044 .log_err();
1045 }
1046 }));
1047 platform_window.on_hover_status_change(Box::new({
1048 let mut cx = cx.to_async();
1049 move |active| {
1050 handle
1051 .update(&mut cx, |_, window, _| {
1052 window.hovered.set(active);
1053 window.refresh();
1054 })
1055 .log_err();
1056 }
1057 }));
1058 platform_window.on_input({
1059 let mut cx = cx.to_async();
1060 Box::new(move |event| {
1061 handle
1062 .update(&mut cx, |_, window, cx| window.dispatch_event(event, cx))
1063 .log_err()
1064 .unwrap_or(DispatchEventResult::default())
1065 })
1066 });
1067 platform_window.on_hit_test_window_control({
1068 let mut cx = cx.to_async();
1069 Box::new(move || {
1070 handle
1071 .update(&mut cx, |_, window, _cx| {
1072 for (area, hitbox) in &window.rendered_frame.window_control_hitboxes {
1073 if window.mouse_hit_test.ids.contains(&hitbox.id) {
1074 return Some(*area);
1075 }
1076 }
1077 None
1078 })
1079 .log_err()
1080 .unwrap_or(None)
1081 })
1082 });
1083
1084 if let Some(app_id) = app_id {
1085 platform_window.set_app_id(&app_id);
1086 }
1087
1088 platform_window.map_window().unwrap();
1089
1090 Ok(Window {
1091 handle,
1092 invalidator,
1093 removed: false,
1094 platform_window,
1095 display_id,
1096 sprite_atlas,
1097 text_system,
1098 rem_size: px(16.),
1099 rem_size_override_stack: SmallVec::new(),
1100 viewport_size: content_size,
1101 layout_engine: Some(TaffyLayoutEngine::new()),
1102 root: None,
1103 element_id_stack: SmallVec::default(),
1104 text_style_stack: Vec::new(),
1105 rendered_entity_stack: Vec::new(),
1106 element_offset_stack: Vec::new(),
1107 content_mask_stack: Vec::new(),
1108 element_opacity: None,
1109 requested_autoscroll: None,
1110 rendered_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
1111 next_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
1112 next_frame_callbacks,
1113 next_hitbox_id: HitboxId(0),
1114 next_tooltip_id: TooltipId::default(),
1115 tooltip_bounds: None,
1116 dirty_views: FxHashSet::default(),
1117 focus_listeners: SubscriberSet::new(),
1118 focus_lost_listeners: SubscriberSet::new(),
1119 default_prevented: true,
1120 mouse_position,
1121 mouse_hit_test: HitTest::default(),
1122 modifiers,
1123 capslock,
1124 scale_factor,
1125 bounds_observers: SubscriberSet::new(),
1126 appearance,
1127 appearance_observers: SubscriberSet::new(),
1128 active,
1129 hovered,
1130 needs_present,
1131 last_input_timestamp,
1132 refreshing: false,
1133 activation_observers: SubscriberSet::new(),
1134 focus: None,
1135 focus_enabled: true,
1136 pending_input: None,
1137 pending_modifier: ModifierState::default(),
1138 pending_input_observers: SubscriberSet::new(),
1139 prompt: None,
1140 client_inset: None,
1141 image_cache_stack: Vec::new(),
1142 #[cfg(any(feature = "inspector", debug_assertions))]
1143 inspector: None,
1144 })
1145 }
1146
1147 pub(crate) fn new_focus_listener(
1148 &self,
1149 value: AnyWindowFocusListener,
1150 ) -> (Subscription, impl FnOnce() + use<>) {
1151 self.focus_listeners.insert((), value)
1152 }
1153}
1154
1155#[derive(Clone, Debug, Default, PartialEq, Eq)]
1156pub(crate) struct DispatchEventResult {
1157 pub propagate: bool,
1158 pub default_prevented: bool,
1159}
1160
1161/// Indicates which region of the window is visible. Content falling outside of this mask will not be
1162/// rendered. Currently, only rectangular content masks are supported, but we give the mask its own type
1163/// to leave room to support more complex shapes in the future.
1164#[derive(Clone, Debug, Default, PartialEq, Eq)]
1165#[repr(C)]
1166pub struct ContentMask<P: Clone + Debug + Default + PartialEq> {
1167 /// The bounds
1168 pub bounds: Bounds<P>,
1169}
1170
1171impl ContentMask<Pixels> {
1172 /// Scale the content mask's pixel units by the given scaling factor.
1173 pub fn scale(&self, factor: f32) -> ContentMask<ScaledPixels> {
1174 ContentMask {
1175 bounds: self.bounds.scale(factor),
1176 }
1177 }
1178
1179 /// Intersect the content mask with the given content mask.
1180 pub fn intersect(&self, other: &Self) -> Self {
1181 let bounds = self.bounds.intersect(&other.bounds);
1182 ContentMask { bounds }
1183 }
1184}
1185
1186impl Window {
1187 fn mark_view_dirty(&mut self, view_id: EntityId) {
1188 // Mark ancestor views as dirty. If already in the `dirty_views` set, then all its ancestors
1189 // should already be dirty.
1190 for view_id in self
1191 .rendered_frame
1192 .dispatch_tree
1193 .view_path(view_id)
1194 .into_iter()
1195 .rev()
1196 {
1197 if !self.dirty_views.insert(view_id) {
1198 break;
1199 }
1200 }
1201 }
1202
1203 /// Registers a callback to be invoked when the window appearance changes.
1204 pub fn observe_window_appearance(
1205 &self,
1206 mut callback: impl FnMut(&mut Window, &mut App) + 'static,
1207 ) -> Subscription {
1208 let (subscription, activate) = self.appearance_observers.insert(
1209 (),
1210 Box::new(move |window, cx| {
1211 callback(window, cx);
1212 true
1213 }),
1214 );
1215 activate();
1216 subscription
1217 }
1218
1219 /// Replaces the root entity of the window with a new one.
1220 pub fn replace_root<E>(
1221 &mut self,
1222 cx: &mut App,
1223 build_view: impl FnOnce(&mut Window, &mut Context<E>) -> E,
1224 ) -> Entity<E>
1225 where
1226 E: 'static + Render,
1227 {
1228 let view = cx.new(|cx| build_view(self, cx));
1229 self.root = Some(view.clone().into());
1230 self.refresh();
1231 view
1232 }
1233
1234 /// Returns the root entity of the window, if it has one.
1235 pub fn root<E>(&self) -> Option<Option<Entity<E>>>
1236 where
1237 E: 'static + Render,
1238 {
1239 self.root
1240 .as_ref()
1241 .map(|view| view.clone().downcast::<E>().ok())
1242 }
1243
1244 /// Obtain a handle to the window that belongs to this context.
1245 pub fn window_handle(&self) -> AnyWindowHandle {
1246 self.handle
1247 }
1248
1249 /// Mark the window as dirty, scheduling it to be redrawn on the next frame.
1250 pub fn refresh(&mut self) {
1251 if self.invalidator.not_drawing() {
1252 self.refreshing = true;
1253 self.invalidator.set_dirty(true);
1254 }
1255 }
1256
1257 /// Close this window.
1258 pub fn remove_window(&mut self) {
1259 self.removed = true;
1260 }
1261
1262 /// Obtain the currently focused [`FocusHandle`]. If no elements are focused, returns `None`.
1263 pub fn focused(&self, cx: &App) -> Option<FocusHandle> {
1264 self.focus
1265 .and_then(|id| FocusHandle::for_id(id, &cx.focus_handles))
1266 }
1267
1268 /// Move focus to the element associated with the given [`FocusHandle`].
1269 pub fn focus(&mut self, handle: &FocusHandle) {
1270 println!(
1271 "Setting focus to {:?} on platform {:?}",
1272 handle.id,
1273 std::env::consts::OS
1274 );
1275
1276 if !self.focus_enabled || self.focus == Some(handle.id) {
1277 return;
1278 }
1279 println!("actually setting focus");
1280 self.focus = Some(handle.id);
1281 self.clear_pending_keystrokes();
1282 self.refresh();
1283 }
1284
1285 /// Remove focus from all elements within this context's window.
1286 pub fn blur(&mut self) {
1287 if !self.focus_enabled {
1288 return;
1289 }
1290
1291 self.focus = None;
1292 println!("clearing focus 2");
1293 self.refresh();
1294 }
1295
1296 /// Blur the window and don't allow anything in it to be focused again.
1297 pub fn disable_focus(&mut self) {
1298 self.blur();
1299 self.focus_enabled = false;
1300 }
1301
1302 /// Accessor for the text system.
1303 pub fn text_system(&self) -> &Arc<WindowTextSystem> {
1304 &self.text_system
1305 }
1306
1307 /// The current text style. Which is composed of all the style refinements provided to `with_text_style`.
1308 pub fn text_style(&self) -> TextStyle {
1309 let mut style = TextStyle::default();
1310 for refinement in &self.text_style_stack {
1311 style.refine(refinement);
1312 }
1313 style
1314 }
1315
1316 /// Check if the platform window is maximized
1317 /// On some platforms (namely Windows) this is different than the bounds being the size of the display
1318 pub fn is_maximized(&self) -> bool {
1319 self.platform_window.is_maximized()
1320 }
1321
1322 /// request a certain window decoration (Wayland)
1323 pub fn request_decorations(&self, decorations: WindowDecorations) {
1324 self.platform_window.request_decorations(decorations);
1325 }
1326
1327 /// Start a window resize operation (Wayland)
1328 pub fn start_window_resize(&self, edge: ResizeEdge) {
1329 self.platform_window.start_window_resize(edge);
1330 }
1331
1332 /// Return the `WindowBounds` to indicate that how a window should be opened
1333 /// after it has been closed
1334 pub fn window_bounds(&self) -> WindowBounds {
1335 self.platform_window.window_bounds()
1336 }
1337
1338 /// Return the `WindowBounds` excluding insets (Wayland and X11)
1339 pub fn inner_window_bounds(&self) -> WindowBounds {
1340 self.platform_window.inner_window_bounds()
1341 }
1342
1343 /// Dispatch the given action on the currently focused element.
1344 pub fn dispatch_action(&mut self, action: Box<dyn Action>, cx: &mut App) {
1345 let focus_id = self.focused(cx).map(|handle| handle.id);
1346 dbg!(&focus_id);
1347 let window = self.handle;
1348 cx.defer(move |cx| {
1349 window
1350 .update(cx, |_, window, cx| {
1351 let node_id = window.focus_node_id_in_rendered_frame(focus_id);
1352 dbg!(&node_id);
1353 window.dispatch_action_on_node(node_id, action.as_ref(), cx);
1354 })
1355 .log_err();
1356 })
1357 }
1358
1359 pub(crate) fn dispatch_keystroke_observers(
1360 &mut self,
1361 event: &dyn Any,
1362 action: Option<Box<dyn Action>>,
1363 context_stack: Vec<KeyContext>,
1364 cx: &mut App,
1365 ) {
1366 let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() else {
1367 return;
1368 };
1369
1370 cx.keystroke_observers.clone().retain(&(), move |callback| {
1371 (callback)(
1372 &KeystrokeEvent {
1373 keystroke: key_down_event.keystroke.clone(),
1374 action: action.as_ref().map(|action| action.boxed_clone()),
1375 context_stack: context_stack.clone(),
1376 },
1377 self,
1378 cx,
1379 )
1380 });
1381 }
1382
1383 pub(crate) fn dispatch_keystroke_interceptors(
1384 &mut self,
1385 event: &dyn Any,
1386 context_stack: Vec<KeyContext>,
1387 cx: &mut App,
1388 ) {
1389 let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() else {
1390 return;
1391 };
1392
1393 cx.keystroke_interceptors
1394 .clone()
1395 .retain(&(), move |callback| {
1396 (callback)(
1397 &KeystrokeEvent {
1398 keystroke: key_down_event.keystroke.clone(),
1399 action: None,
1400 context_stack: context_stack.clone(),
1401 },
1402 self,
1403 cx,
1404 )
1405 });
1406 }
1407
1408 /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
1409 /// that are currently on the stack to be returned to the app.
1410 pub fn defer(&self, cx: &mut App, f: impl FnOnce(&mut Window, &mut App) + 'static) {
1411 let handle = self.handle;
1412 cx.defer(move |cx| {
1413 handle.update(cx, |_, window, cx| f(window, cx)).ok();
1414 });
1415 }
1416
1417 /// Subscribe to events emitted by a entity.
1418 /// The entity to which you're subscribing must implement the [`EventEmitter`] trait.
1419 /// The callback will be invoked a handle to the emitting entity, the event, and a window context for the current window.
1420 pub fn observe<T: 'static>(
1421 &mut self,
1422 observed: &Entity<T>,
1423 cx: &mut App,
1424 mut on_notify: impl FnMut(Entity<T>, &mut Window, &mut App) + 'static,
1425 ) -> Subscription {
1426 let entity_id = observed.entity_id();
1427 let observed = observed.downgrade();
1428 let window_handle = self.handle;
1429 cx.new_observer(
1430 entity_id,
1431 Box::new(move |cx| {
1432 window_handle
1433 .update(cx, |_, window, cx| {
1434 if let Some(handle) = observed.upgrade() {
1435 on_notify(handle, window, cx);
1436 true
1437 } else {
1438 false
1439 }
1440 })
1441 .unwrap_or(false)
1442 }),
1443 )
1444 }
1445
1446 /// Subscribe to events emitted by a entity.
1447 /// The entity to which you're subscribing must implement the [`EventEmitter`] trait.
1448 /// The callback will be invoked a handle to the emitting entity, the event, and a window context for the current window.
1449 pub fn subscribe<Emitter, Evt>(
1450 &mut self,
1451 entity: &Entity<Emitter>,
1452 cx: &mut App,
1453 mut on_event: impl FnMut(Entity<Emitter>, &Evt, &mut Window, &mut App) + 'static,
1454 ) -> Subscription
1455 where
1456 Emitter: EventEmitter<Evt>,
1457 Evt: 'static,
1458 {
1459 let entity_id = entity.entity_id();
1460 let handle = entity.downgrade();
1461 let window_handle = self.handle;
1462 cx.new_subscription(
1463 entity_id,
1464 (
1465 TypeId::of::<Evt>(),
1466 Box::new(move |event, cx| {
1467 window_handle
1468 .update(cx, |_, window, cx| {
1469 if let Some(entity) = handle.upgrade() {
1470 let event = event.downcast_ref().expect("invalid event type");
1471 on_event(entity, event, window, cx);
1472 true
1473 } else {
1474 false
1475 }
1476 })
1477 .unwrap_or(false)
1478 }),
1479 ),
1480 )
1481 }
1482
1483 /// Register a callback to be invoked when the given `Entity` is released.
1484 pub fn observe_release<T>(
1485 &self,
1486 entity: &Entity<T>,
1487 cx: &mut App,
1488 mut on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,
1489 ) -> Subscription
1490 where
1491 T: 'static,
1492 {
1493 let entity_id = entity.entity_id();
1494 let window_handle = self.handle;
1495 let (subscription, activate) = cx.release_listeners.insert(
1496 entity_id,
1497 Box::new(move |entity, cx| {
1498 let entity = entity.downcast_mut().expect("invalid entity type");
1499 let _ = window_handle.update(cx, |_, window, cx| on_release(entity, window, cx));
1500 }),
1501 );
1502 activate();
1503 subscription
1504 }
1505
1506 /// Creates an [`AsyncWindowContext`], which has a static lifetime and can be held across
1507 /// await points in async code.
1508 pub fn to_async(&self, cx: &App) -> AsyncWindowContext {
1509 AsyncWindowContext::new_context(cx.to_async(), self.handle)
1510 }
1511
1512 /// Schedule the given closure to be run directly after the current frame is rendered.
1513 pub fn on_next_frame(&self, callback: impl FnOnce(&mut Window, &mut App) + 'static) {
1514 RefCell::borrow_mut(&self.next_frame_callbacks).push(Box::new(callback));
1515 }
1516
1517 /// Schedule a frame to be drawn on the next animation frame.
1518 ///
1519 /// This is useful for elements that need to animate continuously, such as a video player or an animated GIF.
1520 /// It will cause the window to redraw on the next frame, even if no other changes have occurred.
1521 ///
1522 /// If called from within a view, it will notify that view on the next frame. Otherwise, it will refresh the entire window.
1523 pub fn request_animation_frame(&self) {
1524 let entity = self.current_view();
1525 self.on_next_frame(move |_, cx| cx.notify(entity));
1526 }
1527
1528 /// Spawn the future returned by the given closure on the application thread pool.
1529 /// The closure is provided a handle to the current window and an `AsyncWindowContext` for
1530 /// use within your future.
1531 #[track_caller]
1532 pub fn spawn<AsyncFn, R>(&self, cx: &App, f: AsyncFn) -> Task<R>
1533 where
1534 R: 'static,
1535 AsyncFn: AsyncFnOnce(&mut AsyncWindowContext) -> R + 'static,
1536 {
1537 let handle = self.handle;
1538 cx.spawn(async move |app| {
1539 let mut async_window_cx = AsyncWindowContext::new_context(app.clone(), handle);
1540 f(&mut async_window_cx).await
1541 })
1542 }
1543
1544 fn bounds_changed(&mut self, cx: &mut App) {
1545 self.scale_factor = self.platform_window.scale_factor();
1546 self.viewport_size = self.platform_window.content_size();
1547 self.display_id = self.platform_window.display().map(|display| display.id());
1548
1549 self.refresh();
1550
1551 self.bounds_observers
1552 .clone()
1553 .retain(&(), |callback| callback(self, cx));
1554 }
1555
1556 /// Returns the bounds of the current window in the global coordinate space, which could span across multiple displays.
1557 pub fn bounds(&self) -> Bounds<Pixels> {
1558 self.platform_window.bounds()
1559 }
1560
1561 /// Set the content size of the window.
1562 pub fn resize(&mut self, size: Size<Pixels>) {
1563 self.platform_window.resize(size);
1564 }
1565
1566 /// Returns whether or not the window is currently fullscreen
1567 pub fn is_fullscreen(&self) -> bool {
1568 self.platform_window.is_fullscreen()
1569 }
1570
1571 pub(crate) fn appearance_changed(&mut self, cx: &mut App) {
1572 self.appearance = self.platform_window.appearance();
1573
1574 self.appearance_observers
1575 .clone()
1576 .retain(&(), |callback| callback(self, cx));
1577 }
1578
1579 /// Returns the appearance of the current window.
1580 pub fn appearance(&self) -> WindowAppearance {
1581 self.appearance
1582 }
1583
1584 /// Returns the size of the drawable area within the window.
1585 pub fn viewport_size(&self) -> Size<Pixels> {
1586 self.viewport_size
1587 }
1588
1589 /// Returns whether this window is focused by the operating system (receiving key events).
1590 pub fn is_window_active(&self) -> bool {
1591 self.active.get()
1592 }
1593
1594 /// Returns whether this window is considered to be the window
1595 /// that currently owns the mouse cursor.
1596 /// On mac, this is equivalent to `is_window_active`.
1597 pub fn is_window_hovered(&self) -> bool {
1598 if cfg!(any(
1599 target_os = "windows",
1600 target_os = "linux",
1601 target_os = "freebsd"
1602 )) {
1603 self.hovered.get()
1604 } else {
1605 self.is_window_active()
1606 }
1607 }
1608
1609 /// Toggle zoom on the window.
1610 pub fn zoom_window(&self) {
1611 self.platform_window.zoom();
1612 }
1613
1614 /// Opens the native title bar context menu, useful when implementing client side decorations (Wayland and X11)
1615 pub fn show_window_menu(&self, position: Point<Pixels>) {
1616 self.platform_window.show_window_menu(position)
1617 }
1618
1619 /// Tells the compositor to take control of window movement (Wayland and X11)
1620 ///
1621 /// Events may not be received during a move operation.
1622 pub fn start_window_move(&self) {
1623 self.platform_window.start_window_move()
1624 }
1625
1626 /// When using client side decorations, set this to the width of the invisible decorations (Wayland and X11)
1627 pub fn set_client_inset(&mut self, inset: Pixels) {
1628 self.client_inset = Some(inset);
1629 self.platform_window.set_client_inset(inset);
1630 }
1631
1632 /// Returns the client_inset value by [`Self::set_client_inset`].
1633 pub fn client_inset(&self) -> Option<Pixels> {
1634 self.client_inset
1635 }
1636
1637 /// Returns whether the title bar window controls need to be rendered by the application (Wayland and X11)
1638 pub fn window_decorations(&self) -> Decorations {
1639 self.platform_window.window_decorations()
1640 }
1641
1642 /// Returns which window controls are currently visible (Wayland)
1643 pub fn window_controls(&self) -> WindowControls {
1644 self.platform_window.window_controls()
1645 }
1646
1647 /// Updates the window's title at the platform level.
1648 pub fn set_window_title(&mut self, title: &str) {
1649 self.platform_window.set_title(title);
1650 }
1651
1652 /// Sets the application identifier.
1653 pub fn set_app_id(&mut self, app_id: &str) {
1654 self.platform_window.set_app_id(app_id);
1655 }
1656
1657 /// Sets the window background appearance.
1658 pub fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance) {
1659 self.platform_window
1660 .set_background_appearance(background_appearance);
1661 }
1662
1663 /// Mark the window as dirty at the platform level.
1664 pub fn set_window_edited(&mut self, edited: bool) {
1665 self.platform_window.set_edited(edited);
1666 }
1667
1668 /// Determine the display on which the window is visible.
1669 pub fn display(&self, cx: &App) -> Option<Rc<dyn PlatformDisplay>> {
1670 cx.platform
1671 .displays()
1672 .into_iter()
1673 .find(|display| Some(display.id()) == self.display_id)
1674 }
1675
1676 /// Show the platform character palette.
1677 pub fn show_character_palette(&self) {
1678 self.platform_window.show_character_palette();
1679 }
1680
1681 /// The scale factor of the display associated with the window. For example, it could
1682 /// return 2.0 for a "retina" display, indicating that each logical pixel should actually
1683 /// be rendered as two pixels on screen.
1684 pub fn scale_factor(&self) -> f32 {
1685 self.scale_factor
1686 }
1687
1688 /// The size of an em for the base font of the application. Adjusting this value allows the
1689 /// UI to scale, just like zooming a web page.
1690 pub fn rem_size(&self) -> Pixels {
1691 self.rem_size_override_stack
1692 .last()
1693 .copied()
1694 .unwrap_or(self.rem_size)
1695 }
1696
1697 /// Sets the size of an em for the base font of the application. Adjusting this value allows the
1698 /// UI to scale, just like zooming a web page.
1699 pub fn set_rem_size(&mut self, rem_size: impl Into<Pixels>) {
1700 self.rem_size = rem_size.into();
1701 }
1702
1703 /// Acquire a globally unique identifier for the given ElementId.
1704 /// Only valid for the duration of the provided closure.
1705 pub fn with_global_id<R>(
1706 &mut self,
1707 element_id: ElementId,
1708 f: impl FnOnce(&GlobalElementId, &mut Self) -> R,
1709 ) -> R {
1710 self.element_id_stack.push(element_id);
1711 let global_id = GlobalElementId(self.element_id_stack.clone());
1712 let result = f(&global_id, self);
1713 self.element_id_stack.pop();
1714 result
1715 }
1716
1717 /// Executes the provided function with the specified rem size.
1718 ///
1719 /// This method must only be called as part of element drawing.
1720 pub fn with_rem_size<F, R>(&mut self, rem_size: Option<impl Into<Pixels>>, f: F) -> R
1721 where
1722 F: FnOnce(&mut Self) -> R,
1723 {
1724 self.invalidator.debug_assert_paint_or_prepaint();
1725
1726 if let Some(rem_size) = rem_size {
1727 self.rem_size_override_stack.push(rem_size.into());
1728 let result = f(self);
1729 self.rem_size_override_stack.pop();
1730 result
1731 } else {
1732 f(self)
1733 }
1734 }
1735
1736 /// The line height associated with the current text style.
1737 pub fn line_height(&self) -> Pixels {
1738 self.text_style().line_height_in_pixels(self.rem_size())
1739 }
1740
1741 /// Call to prevent the default action of an event. Currently only used to prevent
1742 /// parent elements from becoming focused on mouse down.
1743 pub fn prevent_default(&mut self) {
1744 self.default_prevented = true;
1745 }
1746
1747 /// Obtain whether default has been prevented for the event currently being dispatched.
1748 pub fn default_prevented(&self) -> bool {
1749 self.default_prevented
1750 }
1751
1752 /// Determine whether the given action is available along the dispatch path to the currently focused element.
1753 pub fn is_action_available(&self, action: &dyn Action, cx: &mut App) -> bool {
1754 let node_id =
1755 self.focus_node_id_in_rendered_frame(self.focused(cx).map(|handle| handle.id));
1756 self.rendered_frame
1757 .dispatch_tree
1758 .is_action_available(action, node_id)
1759 }
1760
1761 /// The position of the mouse relative to the window.
1762 pub fn mouse_position(&self) -> Point<Pixels> {
1763 self.mouse_position
1764 }
1765
1766 /// The current state of the keyboard's modifiers
1767 pub fn modifiers(&self) -> Modifiers {
1768 self.modifiers
1769 }
1770
1771 /// The current state of the keyboard's capslock
1772 pub fn capslock(&self) -> Capslock {
1773 self.capslock
1774 }
1775
1776 fn complete_frame(&self) {
1777 self.platform_window.completed_frame();
1778 }
1779
1780 /// Produces a new frame and assigns it to `rendered_frame`. To actually show
1781 /// the contents of the new [Scene], use [present].
1782 #[profiling::function]
1783 pub fn draw(&mut self, cx: &mut App) -> ArenaClearNeeded {
1784 self.invalidate_entities();
1785 cx.entities.clear_accessed();
1786 debug_assert!(self.rendered_entity_stack.is_empty());
1787 self.invalidator.set_dirty(false);
1788 self.requested_autoscroll = None;
1789
1790 // Restore the previously-used input handler.
1791 if let Some(input_handler) = self.platform_window.take_input_handler() {
1792 self.rendered_frame.input_handlers.push(Some(input_handler));
1793 }
1794 self.draw_roots(cx);
1795 self.dirty_views.clear();
1796 self.next_frame.window_active = self.active.get();
1797
1798 // Register requested input handler with the platform window.
1799 if let Some(input_handler) = self.next_frame.input_handlers.pop() {
1800 self.platform_window
1801 .set_input_handler(input_handler.unwrap());
1802 }
1803
1804 self.layout_engine.as_mut().unwrap().clear();
1805 self.text_system().finish_frame();
1806 self.next_frame.finish(&mut self.rendered_frame);
1807
1808 self.invalidator.set_phase(DrawPhase::Focus);
1809 let previous_focus_path = self.rendered_frame.focus_path();
1810 let previous_window_active = self.rendered_frame.window_active;
1811 println!(
1812 "dbg! Window::draw - pre-swap: rendered_frame.focus = {:?}, next_frame.focus = {:?}",
1813 self.rendered_frame.focus, self.next_frame.focus
1814 );
1815 mem::swap(&mut self.rendered_frame, &mut self.next_frame);
1816 self.next_frame.clear();
1817 println!(
1818 "dbg! Window::draw - post-swap: rendered_frame.focus = {:?}, next_frame.focus = {:?}",
1819 self.rendered_frame.focus, self.next_frame.focus
1820 );
1821 let current_focus_path = self.rendered_frame.focus_path();
1822 let current_window_active = self.rendered_frame.window_active;
1823
1824 if previous_focus_path != current_focus_path
1825 || previous_window_active != current_window_active
1826 {
1827 if !previous_focus_path.is_empty() && current_focus_path.is_empty() {
1828 self.focus_lost_listeners
1829 .clone()
1830 .retain(&(), |listener| listener(self, cx));
1831 }
1832
1833 let event = WindowFocusEvent {
1834 previous_focus_path: if previous_window_active {
1835 previous_focus_path
1836 } else {
1837 Default::default()
1838 },
1839 current_focus_path: if current_window_active {
1840 current_focus_path
1841 } else {
1842 Default::default()
1843 },
1844 };
1845 self.focus_listeners
1846 .clone()
1847 .retain(&(), |listener| listener(&event, self, cx));
1848 }
1849
1850 debug_assert!(self.rendered_entity_stack.is_empty());
1851 self.record_entities_accessed(cx);
1852 self.reset_cursor_style(cx);
1853 self.refreshing = false;
1854 self.invalidator.set_phase(DrawPhase::None);
1855 self.needs_present.set(true);
1856
1857 ArenaClearNeeded
1858 }
1859
1860 fn record_entities_accessed(&mut self, cx: &mut App) {
1861 let mut entities_ref = cx.entities.accessed_entities.borrow_mut();
1862 let mut entities = mem::take(entities_ref.deref_mut());
1863 drop(entities_ref);
1864 let handle = self.handle;
1865 cx.record_entities_accessed(
1866 handle,
1867 // Try moving window invalidator into the Window
1868 self.invalidator.clone(),
1869 &entities,
1870 );
1871 let mut entities_ref = cx.entities.accessed_entities.borrow_mut();
1872 mem::swap(&mut entities, entities_ref.deref_mut());
1873 }
1874
1875 fn invalidate_entities(&mut self) {
1876 let mut views = self.invalidator.take_views();
1877 for entity in views.drain() {
1878 self.mark_view_dirty(entity);
1879 }
1880 self.invalidator.replace_views(views);
1881 }
1882
1883 #[profiling::function]
1884 fn present(&self) {
1885 self.platform_window.draw(&self.rendered_frame.scene);
1886 self.needs_present.set(false);
1887 profiling::finish_frame!();
1888 }
1889
1890 fn draw_roots(&mut self, cx: &mut App) {
1891 self.invalidator.set_phase(DrawPhase::Prepaint);
1892 self.tooltip_bounds.take();
1893
1894 let _inspector_width: Pixels = rems(30.0).to_pixels(self.rem_size());
1895 let root_size = {
1896 #[cfg(any(feature = "inspector", debug_assertions))]
1897 {
1898 if self.inspector.is_some() {
1899 let mut size = self.viewport_size;
1900 size.width = (size.width - _inspector_width).max(px(0.0));
1901 size
1902 } else {
1903 self.viewport_size
1904 }
1905 }
1906 #[cfg(not(any(feature = "inspector", debug_assertions)))]
1907 {
1908 self.viewport_size
1909 }
1910 };
1911
1912 // Layout all root elements.
1913 let mut root_element = self.root.as_ref().unwrap().clone().into_any();
1914 root_element.prepaint_as_root(Point::default(), root_size.into(), self, cx);
1915
1916 #[cfg(any(feature = "inspector", debug_assertions))]
1917 let inspector_element = self.prepaint_inspector(_inspector_width, cx);
1918
1919 let mut sorted_deferred_draws =
1920 (0..self.next_frame.deferred_draws.len()).collect::<SmallVec<[_; 8]>>();
1921 sorted_deferred_draws.sort_by_key(|ix| self.next_frame.deferred_draws[*ix].priority);
1922 self.prepaint_deferred_draws(&sorted_deferred_draws, cx);
1923
1924 let mut prompt_element = None;
1925 let mut active_drag_element = None;
1926 let mut tooltip_element = None;
1927 if let Some(prompt) = self.prompt.take() {
1928 let mut element = prompt.view.any_view().into_any();
1929 element.prepaint_as_root(Point::default(), root_size.into(), self, cx);
1930 prompt_element = Some(element);
1931 self.prompt = Some(prompt);
1932 } else if let Some(active_drag) = cx.active_drag.take() {
1933 let mut element = active_drag.view.clone().into_any();
1934 let offset = self.mouse_position() - active_drag.cursor_offset;
1935 element.prepaint_as_root(offset, AvailableSpace::min_size(), self, cx);
1936 active_drag_element = Some(element);
1937 cx.active_drag = Some(active_drag);
1938 } else {
1939 tooltip_element = self.prepaint_tooltip(cx);
1940 }
1941
1942 self.mouse_hit_test = self.next_frame.hit_test(self.mouse_position);
1943
1944 // Now actually paint the elements.
1945 self.invalidator.set_phase(DrawPhase::Paint);
1946 root_element.paint(self, cx);
1947
1948 #[cfg(any(feature = "inspector", debug_assertions))]
1949 self.paint_inspector(inspector_element, cx);
1950
1951 self.paint_deferred_draws(&sorted_deferred_draws, cx);
1952
1953 if let Some(mut prompt_element) = prompt_element {
1954 prompt_element.paint(self, cx);
1955 } else if let Some(mut drag_element) = active_drag_element {
1956 drag_element.paint(self, cx);
1957 } else if let Some(mut tooltip_element) = tooltip_element {
1958 tooltip_element.paint(self, cx);
1959 }
1960
1961 #[cfg(any(feature = "inspector", debug_assertions))]
1962 self.paint_inspector_hitbox(cx);
1963 }
1964
1965 fn prepaint_tooltip(&mut self, cx: &mut App) -> Option<AnyElement> {
1966 // Use indexing instead of iteration to avoid borrowing self for the duration of the loop.
1967 for tooltip_request_index in (0..self.next_frame.tooltip_requests.len()).rev() {
1968 let Some(Some(tooltip_request)) = self
1969 .next_frame
1970 .tooltip_requests
1971 .get(tooltip_request_index)
1972 .cloned()
1973 else {
1974 log::error!("Unexpectedly absent TooltipRequest");
1975 continue;
1976 };
1977 let mut element = tooltip_request.tooltip.view.clone().into_any();
1978 let mouse_position = tooltip_request.tooltip.mouse_position;
1979 let tooltip_size = element.layout_as_root(AvailableSpace::min_size(), self, cx);
1980
1981 let mut tooltip_bounds =
1982 Bounds::new(mouse_position + point(px(1.), px(1.)), tooltip_size);
1983 let window_bounds = Bounds {
1984 origin: Point::default(),
1985 size: self.viewport_size(),
1986 };
1987
1988 if tooltip_bounds.right() > window_bounds.right() {
1989 let new_x = mouse_position.x - tooltip_bounds.size.width - px(1.);
1990 if new_x >= Pixels::ZERO {
1991 tooltip_bounds.origin.x = new_x;
1992 } else {
1993 tooltip_bounds.origin.x = cmp::max(
1994 Pixels::ZERO,
1995 tooltip_bounds.origin.x - tooltip_bounds.right() - window_bounds.right(),
1996 );
1997 }
1998 }
1999
2000 if tooltip_bounds.bottom() > window_bounds.bottom() {
2001 let new_y = mouse_position.y - tooltip_bounds.size.height - px(1.);
2002 if new_y >= Pixels::ZERO {
2003 tooltip_bounds.origin.y = new_y;
2004 } else {
2005 tooltip_bounds.origin.y = cmp::max(
2006 Pixels::ZERO,
2007 tooltip_bounds.origin.y - tooltip_bounds.bottom() - window_bounds.bottom(),
2008 );
2009 }
2010 }
2011
2012 // It's possible for an element to have an active tooltip while not being painted (e.g.
2013 // via the `visible_on_hover` method). Since mouse listeners are not active in this
2014 // case, instead update the tooltip's visibility here.
2015 let is_visible =
2016 (tooltip_request.tooltip.check_visible_and_update)(tooltip_bounds, self, cx);
2017 if !is_visible {
2018 continue;
2019 }
2020
2021 self.with_absolute_element_offset(tooltip_bounds.origin, |window| {
2022 element.prepaint(window, cx)
2023 });
2024
2025 self.tooltip_bounds = Some(TooltipBounds {
2026 id: tooltip_request.id,
2027 bounds: tooltip_bounds,
2028 });
2029 return Some(element);
2030 }
2031 None
2032 }
2033
2034 fn prepaint_deferred_draws(&mut self, deferred_draw_indices: &[usize], cx: &mut App) {
2035 assert_eq!(self.element_id_stack.len(), 0);
2036
2037 let mut deferred_draws = mem::take(&mut self.next_frame.deferred_draws);
2038 for deferred_draw_ix in deferred_draw_indices {
2039 let deferred_draw = &mut deferred_draws[*deferred_draw_ix];
2040 self.element_id_stack
2041 .clone_from(&deferred_draw.element_id_stack);
2042 self.text_style_stack
2043 .clone_from(&deferred_draw.text_style_stack);
2044 self.next_frame
2045 .dispatch_tree
2046 .set_active_node(deferred_draw.parent_node);
2047
2048 let prepaint_start = self.prepaint_index();
2049 if let Some(element) = deferred_draw.element.as_mut() {
2050 self.with_rendered_view(deferred_draw.current_view, |window| {
2051 window.with_absolute_element_offset(deferred_draw.absolute_offset, |window| {
2052 element.prepaint(window, cx)
2053 });
2054 })
2055 } else {
2056 self.reuse_prepaint(deferred_draw.prepaint_range.clone());
2057 }
2058 let prepaint_end = self.prepaint_index();
2059 deferred_draw.prepaint_range = prepaint_start..prepaint_end;
2060 }
2061 assert_eq!(
2062 self.next_frame.deferred_draws.len(),
2063 0,
2064 "cannot call defer_draw during deferred drawing"
2065 );
2066 self.next_frame.deferred_draws = deferred_draws;
2067 self.element_id_stack.clear();
2068 self.text_style_stack.clear();
2069 }
2070
2071 fn paint_deferred_draws(&mut self, deferred_draw_indices: &[usize], cx: &mut App) {
2072 assert_eq!(self.element_id_stack.len(), 0);
2073
2074 let mut deferred_draws = mem::take(&mut self.next_frame.deferred_draws);
2075 for deferred_draw_ix in deferred_draw_indices {
2076 let mut deferred_draw = &mut deferred_draws[*deferred_draw_ix];
2077 self.element_id_stack
2078 .clone_from(&deferred_draw.element_id_stack);
2079 self.next_frame
2080 .dispatch_tree
2081 .set_active_node(deferred_draw.parent_node);
2082
2083 let paint_start = self.paint_index();
2084 if let Some(element) = deferred_draw.element.as_mut() {
2085 self.with_rendered_view(deferred_draw.current_view, |window| {
2086 element.paint(window, cx);
2087 })
2088 } else {
2089 self.reuse_paint(deferred_draw.paint_range.clone());
2090 }
2091 let paint_end = self.paint_index();
2092 deferred_draw.paint_range = paint_start..paint_end;
2093 }
2094 self.next_frame.deferred_draws = deferred_draws;
2095 self.element_id_stack.clear();
2096 }
2097
2098 pub(crate) fn prepaint_index(&self) -> PrepaintStateIndex {
2099 PrepaintStateIndex {
2100 hitboxes_index: self.next_frame.hitboxes.len(),
2101 tooltips_index: self.next_frame.tooltip_requests.len(),
2102 deferred_draws_index: self.next_frame.deferred_draws.len(),
2103 dispatch_tree_index: self.next_frame.dispatch_tree.len(),
2104 accessed_element_states_index: self.next_frame.accessed_element_states.len(),
2105 line_layout_index: self.text_system.layout_index(),
2106 }
2107 }
2108
2109 pub(crate) fn reuse_prepaint(&mut self, range: Range<PrepaintStateIndex>) {
2110 self.next_frame.hitboxes.extend(
2111 self.rendered_frame.hitboxes[range.start.hitboxes_index..range.end.hitboxes_index]
2112 .iter()
2113 .cloned(),
2114 );
2115 self.next_frame.tooltip_requests.extend(
2116 self.rendered_frame.tooltip_requests
2117 [range.start.tooltips_index..range.end.tooltips_index]
2118 .iter_mut()
2119 .map(|request| request.take()),
2120 );
2121 self.next_frame.accessed_element_states.extend(
2122 self.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
2123 ..range.end.accessed_element_states_index]
2124 .iter()
2125 .map(|(id, type_id)| (GlobalElementId(id.0.clone()), *type_id)),
2126 );
2127 self.text_system
2128 .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
2129
2130 let reused_subtree = self.next_frame.dispatch_tree.reuse_subtree(
2131 range.start.dispatch_tree_index..range.end.dispatch_tree_index,
2132 &mut self.rendered_frame.dispatch_tree,
2133 self.focus,
2134 );
2135
2136 if reused_subtree.contains_focus() {
2137 println!("setting focus for next frame");
2138 self.next_frame.focus = self.focus;
2139 }
2140
2141 self.next_frame.deferred_draws.extend(
2142 self.rendered_frame.deferred_draws
2143 [range.start.deferred_draws_index..range.end.deferred_draws_index]
2144 .iter()
2145 .map(|deferred_draw| DeferredDraw {
2146 current_view: deferred_draw.current_view,
2147 parent_node: reused_subtree.refresh_node_id(deferred_draw.parent_node),
2148 element_id_stack: deferred_draw.element_id_stack.clone(),
2149 text_style_stack: deferred_draw.text_style_stack.clone(),
2150 priority: deferred_draw.priority,
2151 element: None,
2152 absolute_offset: deferred_draw.absolute_offset,
2153 prepaint_range: deferred_draw.prepaint_range.clone(),
2154 paint_range: deferred_draw.paint_range.clone(),
2155 }),
2156 );
2157 }
2158
2159 pub(crate) fn paint_index(&self) -> PaintIndex {
2160 PaintIndex {
2161 scene_index: self.next_frame.scene.len(),
2162 mouse_listeners_index: self.next_frame.mouse_listeners.len(),
2163 input_handlers_index: self.next_frame.input_handlers.len(),
2164 cursor_styles_index: self.next_frame.cursor_styles.len(),
2165 accessed_element_states_index: self.next_frame.accessed_element_states.len(),
2166 line_layout_index: self.text_system.layout_index(),
2167 }
2168 }
2169
2170 pub(crate) fn reuse_paint(&mut self, range: Range<PaintIndex>) {
2171 self.next_frame.cursor_styles.extend(
2172 self.rendered_frame.cursor_styles
2173 [range.start.cursor_styles_index..range.end.cursor_styles_index]
2174 .iter()
2175 .cloned(),
2176 );
2177 self.next_frame.input_handlers.extend(
2178 self.rendered_frame.input_handlers
2179 [range.start.input_handlers_index..range.end.input_handlers_index]
2180 .iter_mut()
2181 .map(|handler| handler.take()),
2182 );
2183 self.next_frame.mouse_listeners.extend(
2184 self.rendered_frame.mouse_listeners
2185 [range.start.mouse_listeners_index..range.end.mouse_listeners_index]
2186 .iter_mut()
2187 .map(|listener| listener.take()),
2188 );
2189 self.next_frame.accessed_element_states.extend(
2190 self.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
2191 ..range.end.accessed_element_states_index]
2192 .iter()
2193 .map(|(id, type_id)| (GlobalElementId(id.0.clone()), *type_id)),
2194 );
2195
2196 self.text_system
2197 .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
2198 self.next_frame.scene.replay(
2199 range.start.scene_index..range.end.scene_index,
2200 &self.rendered_frame.scene,
2201 );
2202 }
2203
2204 /// Push a text style onto the stack, and call a function with that style active.
2205 /// Use [`Window::text_style`] to get the current, combined text style. This method
2206 /// should only be called as part of element drawing.
2207 pub fn with_text_style<F, R>(&mut self, style: Option<TextStyleRefinement>, f: F) -> R
2208 where
2209 F: FnOnce(&mut Self) -> R,
2210 {
2211 self.invalidator.debug_assert_paint_or_prepaint();
2212 if let Some(style) = style {
2213 self.text_style_stack.push(style);
2214 let result = f(self);
2215 self.text_style_stack.pop();
2216 result
2217 } else {
2218 f(self)
2219 }
2220 }
2221
2222 /// Updates the cursor style at the platform level. This method should only be called
2223 /// during the prepaint phase of element drawing.
2224 pub fn set_cursor_style(&mut self, style: CursorStyle, hitbox: &Hitbox) {
2225 self.invalidator.debug_assert_paint();
2226 self.next_frame.cursor_styles.push(CursorStyleRequest {
2227 hitbox_id: Some(hitbox.id),
2228 style,
2229 });
2230 }
2231
2232 /// Updates the cursor style for the entire window at the platform level. A cursor
2233 /// style using this method will have precedence over any cursor style set using
2234 /// `set_cursor_style`. This method should only be called during the prepaint
2235 /// phase of element drawing.
2236 pub fn set_window_cursor_style(&mut self, style: CursorStyle) {
2237 self.invalidator.debug_assert_paint();
2238 self.next_frame.cursor_styles.push(CursorStyleRequest {
2239 hitbox_id: None,
2240 style,
2241 })
2242 }
2243
2244 /// Sets a tooltip to be rendered for the upcoming frame. This method should only be called
2245 /// during the paint phase of element drawing.
2246 pub fn set_tooltip(&mut self, tooltip: AnyTooltip) -> TooltipId {
2247 self.invalidator.debug_assert_prepaint();
2248 let id = TooltipId(post_inc(&mut self.next_tooltip_id.0));
2249 self.next_frame
2250 .tooltip_requests
2251 .push(Some(TooltipRequest { id, tooltip }));
2252 id
2253 }
2254
2255 /// Invoke the given function with the given content mask after intersecting it
2256 /// with the current mask. This method should only be called during element drawing.
2257 pub fn with_content_mask<R>(
2258 &mut self,
2259 mask: Option<ContentMask<Pixels>>,
2260 f: impl FnOnce(&mut Self) -> R,
2261 ) -> R {
2262 self.invalidator.debug_assert_paint_or_prepaint();
2263 if let Some(mask) = mask {
2264 let mask = mask.intersect(&self.content_mask());
2265 self.content_mask_stack.push(mask);
2266 let result = f(self);
2267 self.content_mask_stack.pop();
2268 result
2269 } else {
2270 f(self)
2271 }
2272 }
2273
2274 /// Updates the global element offset relative to the current offset. This is used to implement
2275 /// scrolling. This method should only be called during the prepaint phase of element drawing.
2276 pub fn with_element_offset<R>(
2277 &mut self,
2278 offset: Point<Pixels>,
2279 f: impl FnOnce(&mut Self) -> R,
2280 ) -> R {
2281 self.invalidator.debug_assert_prepaint();
2282
2283 if offset.is_zero() {
2284 return f(self);
2285 };
2286
2287 let abs_offset = self.element_offset() + offset;
2288 self.with_absolute_element_offset(abs_offset, f)
2289 }
2290
2291 /// Updates the global element offset based on the given offset. This is used to implement
2292 /// drag handles and other manual painting of elements. This method should only be called during
2293 /// the prepaint phase of element drawing.
2294 pub fn with_absolute_element_offset<R>(
2295 &mut self,
2296 offset: Point<Pixels>,
2297 f: impl FnOnce(&mut Self) -> R,
2298 ) -> R {
2299 self.invalidator.debug_assert_prepaint();
2300 self.element_offset_stack.push(offset);
2301 let result = f(self);
2302 self.element_offset_stack.pop();
2303 result
2304 }
2305
2306 pub(crate) fn with_element_opacity<R>(
2307 &mut self,
2308 opacity: Option<f32>,
2309 f: impl FnOnce(&mut Self) -> R,
2310 ) -> R {
2311 if opacity.is_none() {
2312 return f(self);
2313 }
2314
2315 self.invalidator.debug_assert_paint_or_prepaint();
2316 self.element_opacity = opacity;
2317 let result = f(self);
2318 self.element_opacity = None;
2319 result
2320 }
2321
2322 /// Perform prepaint on child elements in a "retryable" manner, so that any side effects
2323 /// of prepaints can be discarded before prepainting again. This is used to support autoscroll
2324 /// where we need to prepaint children to detect the autoscroll bounds, then adjust the
2325 /// element offset and prepaint again. See [`List`] for an example. This method should only be
2326 /// called during the prepaint phase of element drawing.
2327 pub fn transact<T, U>(&mut self, f: impl FnOnce(&mut Self) -> Result<T, U>) -> Result<T, U> {
2328 self.invalidator.debug_assert_prepaint();
2329 let index = self.prepaint_index();
2330 let result = f(self);
2331 if result.is_err() {
2332 self.next_frame.hitboxes.truncate(index.hitboxes_index);
2333 self.next_frame
2334 .tooltip_requests
2335 .truncate(index.tooltips_index);
2336 self.next_frame
2337 .deferred_draws
2338 .truncate(index.deferred_draws_index);
2339 self.next_frame
2340 .dispatch_tree
2341 .truncate(index.dispatch_tree_index);
2342 self.next_frame
2343 .accessed_element_states
2344 .truncate(index.accessed_element_states_index);
2345 self.text_system.truncate_layouts(index.line_layout_index);
2346 }
2347 result
2348 }
2349
2350 /// When you call this method during [`prepaint`], containing elements will attempt to
2351 /// scroll to cause the specified bounds to become visible. When they decide to autoscroll, they will call
2352 /// [`prepaint`] again with a new set of bounds. See [`List`] for an example of an element
2353 /// that supports this method being called on the elements it contains. This method should only be
2354 /// called during the prepaint phase of element drawing.
2355 pub fn request_autoscroll(&mut self, bounds: Bounds<Pixels>) {
2356 self.invalidator.debug_assert_prepaint();
2357 self.requested_autoscroll = Some(bounds);
2358 }
2359
2360 /// This method can be called from a containing element such as [`List`] to support the autoscroll behavior
2361 /// described in [`request_autoscroll`].
2362 pub fn take_autoscroll(&mut self) -> Option<Bounds<Pixels>> {
2363 self.invalidator.debug_assert_prepaint();
2364 self.requested_autoscroll.take()
2365 }
2366
2367 /// Asynchronously load an asset, if the asset hasn't finished loading this will return None.
2368 /// Your view will be re-drawn once the asset has finished loading.
2369 ///
2370 /// Note that the multiple calls to this method will only result in one `Asset::load` call at a
2371 /// time.
2372 pub fn use_asset<A: Asset>(&mut self, source: &A::Source, cx: &mut App) -> Option<A::Output> {
2373 let (task, is_first) = cx.fetch_asset::<A>(source);
2374 task.clone().now_or_never().or_else(|| {
2375 if is_first {
2376 let entity_id = self.current_view();
2377 self.spawn(cx, {
2378 let task = task.clone();
2379 async move |cx| {
2380 task.await;
2381
2382 cx.on_next_frame(move |_, cx| {
2383 cx.notify(entity_id);
2384 });
2385 }
2386 })
2387 .detach();
2388 }
2389
2390 None
2391 })
2392 }
2393
2394 /// Asynchronously load an asset, if the asset hasn't finished loading or doesn't exist this will return None.
2395 /// Your view will not be re-drawn once the asset has finished loading.
2396 ///
2397 /// Note that the multiple calls to this method will only result in one `Asset::load` call at a
2398 /// time.
2399 pub fn get_asset<A: Asset>(&mut self, source: &A::Source, cx: &mut App) -> Option<A::Output> {
2400 let (task, _) = cx.fetch_asset::<A>(source);
2401 task.clone().now_or_never()
2402 }
2403 /// Obtain the current element offset. This method should only be called during the
2404 /// prepaint phase of element drawing.
2405 pub fn element_offset(&self) -> Point<Pixels> {
2406 self.invalidator.debug_assert_prepaint();
2407 self.element_offset_stack
2408 .last()
2409 .copied()
2410 .unwrap_or_default()
2411 }
2412
2413 /// Obtain the current element opacity. This method should only be called during the
2414 /// prepaint phase of element drawing.
2415 pub(crate) fn element_opacity(&self) -> f32 {
2416 self.invalidator.debug_assert_paint_or_prepaint();
2417 self.element_opacity.unwrap_or(1.0)
2418 }
2419
2420 /// Obtain the current content mask. This method should only be called during element drawing.
2421 pub fn content_mask(&self) -> ContentMask<Pixels> {
2422 self.invalidator.debug_assert_paint_or_prepaint();
2423 self.content_mask_stack
2424 .last()
2425 .cloned()
2426 .unwrap_or_else(|| ContentMask {
2427 bounds: Bounds {
2428 origin: Point::default(),
2429 size: self.viewport_size,
2430 },
2431 })
2432 }
2433
2434 /// Provide elements in the called function with a new namespace in which their identifiers must be unique.
2435 /// This can be used within a custom element to distinguish multiple sets of child elements.
2436 pub fn with_element_namespace<R>(
2437 &mut self,
2438 element_id: impl Into<ElementId>,
2439 f: impl FnOnce(&mut Self) -> R,
2440 ) -> R {
2441 self.element_id_stack.push(element_id.into());
2442 let result = f(self);
2443 self.element_id_stack.pop();
2444 result
2445 }
2446
2447 /// Updates or initializes state for an element with the given id that lives across multiple
2448 /// frames. If an element with this ID existed in the rendered frame, its state will be passed
2449 /// to the given closure. The state returned by the closure will be stored so it can be referenced
2450 /// when drawing the next frame. This method should only be called as part of element drawing.
2451 pub fn with_element_state<S, R>(
2452 &mut self,
2453 global_id: &GlobalElementId,
2454 f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
2455 ) -> R
2456 where
2457 S: 'static,
2458 {
2459 self.invalidator.debug_assert_paint_or_prepaint();
2460
2461 let key = (GlobalElementId(global_id.0.clone()), TypeId::of::<S>());
2462 self.next_frame
2463 .accessed_element_states
2464 .push((GlobalElementId(key.0.clone()), TypeId::of::<S>()));
2465
2466 if let Some(any) = self
2467 .next_frame
2468 .element_states
2469 .remove(&key)
2470 .or_else(|| self.rendered_frame.element_states.remove(&key))
2471 {
2472 let ElementStateBox {
2473 inner,
2474 #[cfg(debug_assertions)]
2475 type_name,
2476 } = any;
2477 // Using the extra inner option to avoid needing to reallocate a new box.
2478 let mut state_box = inner
2479 .downcast::<Option<S>>()
2480 .map_err(|_| {
2481 #[cfg(debug_assertions)]
2482 {
2483 anyhow::anyhow!(
2484 "invalid element state type for id, requested {:?}, actual: {:?}",
2485 std::any::type_name::<S>(),
2486 type_name
2487 )
2488 }
2489
2490 #[cfg(not(debug_assertions))]
2491 {
2492 anyhow::anyhow!(
2493 "invalid element state type for id, requested {:?}",
2494 std::any::type_name::<S>(),
2495 )
2496 }
2497 })
2498 .unwrap();
2499
2500 let state = state_box.take().expect(
2501 "reentrant call to with_element_state for the same state type and element id",
2502 );
2503 let (result, state) = f(Some(state), self);
2504 state_box.replace(state);
2505 self.next_frame.element_states.insert(
2506 key,
2507 ElementStateBox {
2508 inner: state_box,
2509 #[cfg(debug_assertions)]
2510 type_name,
2511 },
2512 );
2513 result
2514 } else {
2515 let (result, state) = f(None, self);
2516 self.next_frame.element_states.insert(
2517 key,
2518 ElementStateBox {
2519 inner: Box::new(Some(state)),
2520 #[cfg(debug_assertions)]
2521 type_name: std::any::type_name::<S>(),
2522 },
2523 );
2524 result
2525 }
2526 }
2527
2528 /// A variant of `with_element_state` that allows the element's id to be optional. This is a convenience
2529 /// method for elements where the element id may or may not be assigned. Prefer using `with_element_state`
2530 /// when the element is guaranteed to have an id.
2531 ///
2532 /// The first option means 'no ID provided'
2533 /// The second option means 'not yet initialized'
2534 pub fn with_optional_element_state<S, R>(
2535 &mut self,
2536 global_id: Option<&GlobalElementId>,
2537 f: impl FnOnce(Option<Option<S>>, &mut Self) -> (R, Option<S>),
2538 ) -> R
2539 where
2540 S: 'static,
2541 {
2542 self.invalidator.debug_assert_paint_or_prepaint();
2543
2544 if let Some(global_id) = global_id {
2545 self.with_element_state(global_id, |state, cx| {
2546 let (result, state) = f(Some(state), cx);
2547 let state =
2548 state.expect("you must return some state when you pass some element id");
2549 (result, state)
2550 })
2551 } else {
2552 let (result, state) = f(None, self);
2553 debug_assert!(
2554 state.is_none(),
2555 "you must not return an element state when passing None for the global id"
2556 );
2557 result
2558 }
2559 }
2560
2561 /// Defers the drawing of the given element, scheduling it to be painted on top of the currently-drawn tree
2562 /// at a later time. The `priority` parameter determines the drawing order relative to other deferred elements,
2563 /// with higher values being drawn on top.
2564 ///
2565 /// This method should only be called as part of the prepaint phase of element drawing.
2566 pub fn defer_draw(
2567 &mut self,
2568 element: AnyElement,
2569 absolute_offset: Point<Pixels>,
2570 priority: usize,
2571 ) {
2572 self.invalidator.debug_assert_prepaint();
2573 let parent_node = self.next_frame.dispatch_tree.active_node_id().unwrap();
2574 self.next_frame.deferred_draws.push(DeferredDraw {
2575 current_view: self.current_view(),
2576 parent_node,
2577 element_id_stack: self.element_id_stack.clone(),
2578 text_style_stack: self.text_style_stack.clone(),
2579 priority,
2580 element: Some(element),
2581 absolute_offset,
2582 prepaint_range: PrepaintStateIndex::default()..PrepaintStateIndex::default(),
2583 paint_range: PaintIndex::default()..PaintIndex::default(),
2584 });
2585 }
2586
2587 /// Creates a new painting layer for the specified bounds. A "layer" is a batch
2588 /// of geometry that are non-overlapping and have the same draw order. This is typically used
2589 /// for performance reasons.
2590 ///
2591 /// This method should only be called as part of the paint phase of element drawing.
2592 pub fn paint_layer<R>(&mut self, bounds: Bounds<Pixels>, f: impl FnOnce(&mut Self) -> R) -> R {
2593 self.invalidator.debug_assert_paint();
2594
2595 let scale_factor = self.scale_factor();
2596 let content_mask = self.content_mask();
2597 let clipped_bounds = bounds.intersect(&content_mask.bounds);
2598 if !clipped_bounds.is_empty() {
2599 self.next_frame
2600 .scene
2601 .push_layer(clipped_bounds.scale(scale_factor));
2602 }
2603
2604 let result = f(self);
2605
2606 if !clipped_bounds.is_empty() {
2607 self.next_frame.scene.pop_layer();
2608 }
2609
2610 result
2611 }
2612
2613 /// Paint one or more drop shadows into the scene for the next frame at the current z-index.
2614 ///
2615 /// This method should only be called as part of the paint phase of element drawing.
2616 pub fn paint_shadows(
2617 &mut self,
2618 bounds: Bounds<Pixels>,
2619 corner_radii: Corners<Pixels>,
2620 shadows: &[BoxShadow],
2621 ) {
2622 self.invalidator.debug_assert_paint();
2623
2624 let scale_factor = self.scale_factor();
2625 let content_mask = self.content_mask();
2626 let opacity = self.element_opacity();
2627 for shadow in shadows {
2628 let shadow_bounds = (bounds + shadow.offset).dilate(shadow.spread_radius);
2629 self.next_frame.scene.insert_primitive(Shadow {
2630 order: 0,
2631 blur_radius: shadow.blur_radius.scale(scale_factor),
2632 bounds: shadow_bounds.scale(scale_factor),
2633 content_mask: content_mask.scale(scale_factor),
2634 corner_radii: corner_radii.scale(scale_factor),
2635 color: shadow.color.opacity(opacity),
2636 });
2637 }
2638 }
2639
2640 /// Paint one or more quads into the scene for the next frame at the current stacking context.
2641 /// Quads are colored rectangular regions with an optional background, border, and corner radius.
2642 /// see [`fill`](crate::fill), [`outline`](crate::outline), and [`quad`](crate::quad) to construct this type.
2643 ///
2644 /// This method should only be called as part of the paint phase of element drawing.
2645 ///
2646 /// Note that the `quad.corner_radii` are allowed to exceed the bounds, creating sharp corners
2647 /// where the circular arcs meet. This will not display well when combined with dashed borders.
2648 /// Use `Corners::clamp_radii_for_quad_size` if the radii should fit within the bounds.
2649 pub fn paint_quad(&mut self, quad: PaintQuad) {
2650 self.invalidator.debug_assert_paint();
2651
2652 let scale_factor = self.scale_factor();
2653 let content_mask = self.content_mask();
2654 let opacity = self.element_opacity();
2655 self.next_frame.scene.insert_primitive(Quad {
2656 order: 0,
2657 bounds: quad.bounds.scale(scale_factor),
2658 content_mask: content_mask.scale(scale_factor),
2659 background: quad.background.opacity(opacity),
2660 border_color: quad.border_color.opacity(opacity),
2661 corner_radii: quad.corner_radii.scale(scale_factor),
2662 border_widths: quad.border_widths.scale(scale_factor),
2663 border_style: quad.border_style,
2664 });
2665 }
2666
2667 /// Paint the given `Path` into the scene for the next frame at the current z-index.
2668 ///
2669 /// This method should only be called as part of the paint phase of element drawing.
2670 pub fn paint_path(&mut self, mut path: Path<Pixels>, color: impl Into<Background>) {
2671 self.invalidator.debug_assert_paint();
2672
2673 let scale_factor = self.scale_factor();
2674 let content_mask = self.content_mask();
2675 let opacity = self.element_opacity();
2676 path.content_mask = content_mask;
2677 let color: Background = color.into();
2678 path.color = color.opacity(opacity);
2679 self.next_frame
2680 .scene
2681 .insert_primitive(path.apply_scale(scale_factor));
2682 }
2683
2684 /// Paint an underline into the scene for the next frame at the current z-index.
2685 ///
2686 /// This method should only be called as part of the paint phase of element drawing.
2687 pub fn paint_underline(
2688 &mut self,
2689 origin: Point<Pixels>,
2690 width: Pixels,
2691 style: &UnderlineStyle,
2692 ) {
2693 self.invalidator.debug_assert_paint();
2694
2695 let scale_factor = self.scale_factor();
2696 let height = if style.wavy {
2697 style.thickness * 3.
2698 } else {
2699 style.thickness
2700 };
2701 let bounds = Bounds {
2702 origin,
2703 size: size(width, height),
2704 };
2705 let content_mask = self.content_mask();
2706 let element_opacity = self.element_opacity();
2707
2708 self.next_frame.scene.insert_primitive(Underline {
2709 order: 0,
2710 pad: 0,
2711 bounds: bounds.scale(scale_factor),
2712 content_mask: content_mask.scale(scale_factor),
2713 color: style.color.unwrap_or_default().opacity(element_opacity),
2714 thickness: style.thickness.scale(scale_factor),
2715 wavy: style.wavy,
2716 });
2717 }
2718
2719 /// Paint a strikethrough into the scene for the next frame at the current z-index.
2720 ///
2721 /// This method should only be called as part of the paint phase of element drawing.
2722 pub fn paint_strikethrough(
2723 &mut self,
2724 origin: Point<Pixels>,
2725 width: Pixels,
2726 style: &StrikethroughStyle,
2727 ) {
2728 self.invalidator.debug_assert_paint();
2729
2730 let scale_factor = self.scale_factor();
2731 let height = style.thickness;
2732 let bounds = Bounds {
2733 origin,
2734 size: size(width, height),
2735 };
2736 let content_mask = self.content_mask();
2737 let opacity = self.element_opacity();
2738
2739 self.next_frame.scene.insert_primitive(Underline {
2740 order: 0,
2741 pad: 0,
2742 bounds: bounds.scale(scale_factor),
2743 content_mask: content_mask.scale(scale_factor),
2744 thickness: style.thickness.scale(scale_factor),
2745 color: style.color.unwrap_or_default().opacity(opacity),
2746 wavy: false,
2747 });
2748 }
2749
2750 /// Paints a monochrome (non-emoji) glyph into the scene for the next frame at the current z-index.
2751 ///
2752 /// The y component of the origin is the baseline of the glyph.
2753 /// You should generally prefer to use the [`ShapedLine::paint`](crate::ShapedLine::paint) or
2754 /// [`WrappedLine::paint`](crate::WrappedLine::paint) methods in the [`TextSystem`](crate::TextSystem).
2755 /// This method is only useful if you need to paint a single glyph that has already been shaped.
2756 ///
2757 /// This method should only be called as part of the paint phase of element drawing.
2758 pub fn paint_glyph(
2759 &mut self,
2760 origin: Point<Pixels>,
2761 font_id: FontId,
2762 glyph_id: GlyphId,
2763 font_size: Pixels,
2764 color: Hsla,
2765 ) -> Result<()> {
2766 self.invalidator.debug_assert_paint();
2767
2768 let element_opacity = self.element_opacity();
2769 let scale_factor = self.scale_factor();
2770 let glyph_origin = origin.scale(scale_factor);
2771 let subpixel_variant = Point {
2772 x: (glyph_origin.x.0.fract() * SUBPIXEL_VARIANTS as f32).floor() as u8,
2773 y: (glyph_origin.y.0.fract() * SUBPIXEL_VARIANTS as f32).floor() as u8,
2774 };
2775 let params = RenderGlyphParams {
2776 font_id,
2777 glyph_id,
2778 font_size,
2779 subpixel_variant,
2780 scale_factor,
2781 is_emoji: false,
2782 };
2783
2784 let raster_bounds = self.text_system().raster_bounds(¶ms)?;
2785 if !raster_bounds.is_zero() {
2786 let tile = self
2787 .sprite_atlas
2788 .get_or_insert_with(¶ms.clone().into(), &mut || {
2789 let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?;
2790 Ok(Some((size, Cow::Owned(bytes))))
2791 })?
2792 .expect("Callback above only errors or returns Some");
2793 let bounds = Bounds {
2794 origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
2795 size: tile.bounds.size.map(Into::into),
2796 };
2797 let content_mask = self.content_mask().scale(scale_factor);
2798 self.next_frame.scene.insert_primitive(MonochromeSprite {
2799 order: 0,
2800 pad: 0,
2801 bounds,
2802 content_mask,
2803 color: color.opacity(element_opacity),
2804 tile,
2805 transformation: TransformationMatrix::unit(),
2806 });
2807 }
2808 Ok(())
2809 }
2810
2811 /// Paints an emoji glyph into the scene for the next frame at the current z-index.
2812 ///
2813 /// The y component of the origin is the baseline of the glyph.
2814 /// You should generally prefer to use the [`ShapedLine::paint`](crate::ShapedLine::paint) or
2815 /// [`WrappedLine::paint`](crate::WrappedLine::paint) methods in the [`TextSystem`](crate::TextSystem).
2816 /// This method is only useful if you need to paint a single emoji that has already been shaped.
2817 ///
2818 /// This method should only be called as part of the paint phase of element drawing.
2819 pub fn paint_emoji(
2820 &mut self,
2821 origin: Point<Pixels>,
2822 font_id: FontId,
2823 glyph_id: GlyphId,
2824 font_size: Pixels,
2825 ) -> Result<()> {
2826 self.invalidator.debug_assert_paint();
2827
2828 let scale_factor = self.scale_factor();
2829 let glyph_origin = origin.scale(scale_factor);
2830 let params = RenderGlyphParams {
2831 font_id,
2832 glyph_id,
2833 font_size,
2834 // We don't render emojis with subpixel variants.
2835 subpixel_variant: Default::default(),
2836 scale_factor,
2837 is_emoji: true,
2838 };
2839
2840 let raster_bounds = self.text_system().raster_bounds(¶ms)?;
2841 if !raster_bounds.is_zero() {
2842 let tile = self
2843 .sprite_atlas
2844 .get_or_insert_with(¶ms.clone().into(), &mut || {
2845 let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?;
2846 Ok(Some((size, Cow::Owned(bytes))))
2847 })?
2848 .expect("Callback above only errors or returns Some");
2849
2850 let bounds = Bounds {
2851 origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
2852 size: tile.bounds.size.map(Into::into),
2853 };
2854 let content_mask = self.content_mask().scale(scale_factor);
2855 let opacity = self.element_opacity();
2856
2857 self.next_frame.scene.insert_primitive(PolychromeSprite {
2858 order: 0,
2859 pad: 0,
2860 grayscale: false,
2861 bounds,
2862 corner_radii: Default::default(),
2863 content_mask,
2864 tile,
2865 opacity,
2866 });
2867 }
2868 Ok(())
2869 }
2870
2871 /// Paint a monochrome SVG into the scene for the next frame at the current stacking context.
2872 ///
2873 /// This method should only be called as part of the paint phase of element drawing.
2874 pub fn paint_svg(
2875 &mut self,
2876 bounds: Bounds<Pixels>,
2877 path: SharedString,
2878 transformation: TransformationMatrix,
2879 color: Hsla,
2880 cx: &App,
2881 ) -> Result<()> {
2882 self.invalidator.debug_assert_paint();
2883
2884 let element_opacity = self.element_opacity();
2885 let scale_factor = self.scale_factor();
2886 let bounds = bounds.scale(scale_factor);
2887 let params = RenderSvgParams {
2888 path,
2889 size: bounds.size.map(|pixels| {
2890 DevicePixels::from((pixels.0 * SMOOTH_SVG_SCALE_FACTOR).ceil() as i32)
2891 }),
2892 };
2893
2894 let Some(tile) =
2895 self.sprite_atlas
2896 .get_or_insert_with(¶ms.clone().into(), &mut || {
2897 let Some(bytes) = cx.svg_renderer.render(¶ms)? else {
2898 return Ok(None);
2899 };
2900 Ok(Some((params.size, Cow::Owned(bytes))))
2901 })?
2902 else {
2903 return Ok(());
2904 };
2905 let content_mask = self.content_mask().scale(scale_factor);
2906
2907 self.next_frame.scene.insert_primitive(MonochromeSprite {
2908 order: 0,
2909 pad: 0,
2910 bounds: bounds
2911 .map_origin(|origin| origin.floor())
2912 .map_size(|size| size.ceil()),
2913 content_mask,
2914 color: color.opacity(element_opacity),
2915 tile,
2916 transformation,
2917 });
2918
2919 Ok(())
2920 }
2921
2922 /// Paint an image into the scene for the next frame at the current z-index.
2923 /// This method will panic if the frame_index is not valid
2924 ///
2925 /// This method should only be called as part of the paint phase of element drawing.
2926 pub fn paint_image(
2927 &mut self,
2928 bounds: Bounds<Pixels>,
2929 corner_radii: Corners<Pixels>,
2930 data: Arc<RenderImage>,
2931 frame_index: usize,
2932 grayscale: bool,
2933 ) -> Result<()> {
2934 self.invalidator.debug_assert_paint();
2935
2936 let scale_factor = self.scale_factor();
2937 let bounds = bounds.scale(scale_factor);
2938 let params = RenderImageParams {
2939 image_id: data.id,
2940 frame_index,
2941 };
2942
2943 let tile = self
2944 .sprite_atlas
2945 .get_or_insert_with(¶ms.clone().into(), &mut || {
2946 Ok(Some((
2947 data.size(frame_index),
2948 Cow::Borrowed(
2949 data.as_bytes(frame_index)
2950 .expect("It's the caller's job to pass a valid frame index"),
2951 ),
2952 )))
2953 })?
2954 .expect("Callback above only returns Some");
2955 let content_mask = self.content_mask().scale(scale_factor);
2956 let corner_radii = corner_radii.scale(scale_factor);
2957 let opacity = self.element_opacity();
2958
2959 self.next_frame.scene.insert_primitive(PolychromeSprite {
2960 order: 0,
2961 pad: 0,
2962 grayscale,
2963 bounds: bounds
2964 .map_origin(|origin| origin.floor())
2965 .map_size(|size| size.ceil()),
2966 content_mask,
2967 corner_radii,
2968 tile,
2969 opacity,
2970 });
2971 Ok(())
2972 }
2973
2974 /// Paint a surface into the scene for the next frame at the current z-index.
2975 ///
2976 /// This method should only be called as part of the paint phase of element drawing.
2977 #[cfg(target_os = "macos")]
2978 pub fn paint_surface(&mut self, bounds: Bounds<Pixels>, image_buffer: CVPixelBuffer) {
2979 use crate::PaintSurface;
2980
2981 self.invalidator.debug_assert_paint();
2982
2983 let scale_factor = self.scale_factor();
2984 let bounds = bounds.scale(scale_factor);
2985 let content_mask = self.content_mask().scale(scale_factor);
2986 self.next_frame.scene.insert_primitive(PaintSurface {
2987 order: 0,
2988 bounds,
2989 content_mask,
2990 image_buffer,
2991 });
2992 }
2993
2994 /// Removes an image from the sprite atlas.
2995 pub fn drop_image(&mut self, data: Arc<RenderImage>) -> Result<()> {
2996 for frame_index in 0..data.frame_count() {
2997 let params = RenderImageParams {
2998 image_id: data.id,
2999 frame_index,
3000 };
3001
3002 self.sprite_atlas.remove(¶ms.clone().into());
3003 }
3004
3005 Ok(())
3006 }
3007
3008 /// Add a node to the layout tree for the current frame. Takes the `Style` of the element for which
3009 /// layout is being requested, along with the layout ids of any children. This method is called during
3010 /// calls to the [`Element::request_layout`] trait method and enables any element to participate in layout.
3011 ///
3012 /// This method should only be called as part of the request_layout or prepaint phase of element drawing.
3013 #[must_use]
3014 pub fn request_layout(
3015 &mut self,
3016 style: Style,
3017 children: impl IntoIterator<Item = LayoutId>,
3018 cx: &mut App,
3019 ) -> LayoutId {
3020 self.invalidator.debug_assert_prepaint();
3021
3022 cx.layout_id_buffer.clear();
3023 cx.layout_id_buffer.extend(children);
3024 let rem_size = self.rem_size();
3025
3026 self.layout_engine
3027 .as_mut()
3028 .unwrap()
3029 .request_layout(style, rem_size, &cx.layout_id_buffer)
3030 }
3031
3032 /// Add a node to the layout tree for the current frame. Instead of taking a `Style` and children,
3033 /// this variant takes a function that is invoked during layout so you can use arbitrary logic to
3034 /// determine the element's size. One place this is used internally is when measuring text.
3035 ///
3036 /// The given closure is invoked at layout time with the known dimensions and available space and
3037 /// returns a `Size`.
3038 ///
3039 /// This method should only be called as part of the request_layout or prepaint phase of element drawing.
3040 pub fn request_measured_layout<
3041 F: FnMut(Size<Option<Pixels>>, Size<AvailableSpace>, &mut Window, &mut App) -> Size<Pixels>
3042 + 'static,
3043 >(
3044 &mut self,
3045 style: Style,
3046 measure: F,
3047 ) -> LayoutId {
3048 self.invalidator.debug_assert_prepaint();
3049
3050 let rem_size = self.rem_size();
3051 self.layout_engine
3052 .as_mut()
3053 .unwrap()
3054 .request_measured_layout(style, rem_size, measure)
3055 }
3056
3057 /// Compute the layout for the given id within the given available space.
3058 /// This method is called for its side effect, typically by the framework prior to painting.
3059 /// After calling it, you can request the bounds of the given layout node id or any descendant.
3060 ///
3061 /// This method should only be called as part of the prepaint phase of element drawing.
3062 pub fn compute_layout(
3063 &mut self,
3064 layout_id: LayoutId,
3065 available_space: Size<AvailableSpace>,
3066 cx: &mut App,
3067 ) {
3068 self.invalidator.debug_assert_prepaint();
3069
3070 let mut layout_engine = self.layout_engine.take().unwrap();
3071 layout_engine.compute_layout(layout_id, available_space, self, cx);
3072 self.layout_engine = Some(layout_engine);
3073 }
3074
3075 /// Obtain the bounds computed for the given LayoutId relative to the window. This method will usually be invoked by
3076 /// GPUI itself automatically in order to pass your element its `Bounds` automatically.
3077 ///
3078 /// This method should only be called as part of element drawing.
3079 pub fn layout_bounds(&mut self, layout_id: LayoutId) -> Bounds<Pixels> {
3080 self.invalidator.debug_assert_prepaint();
3081
3082 let mut bounds = self
3083 .layout_engine
3084 .as_mut()
3085 .unwrap()
3086 .layout_bounds(layout_id)
3087 .map(Into::into);
3088 bounds.origin += self.element_offset();
3089 bounds
3090 }
3091
3092 /// This method should be called during `prepaint`. You can use
3093 /// the returned [Hitbox] during `paint` or in an event handler
3094 /// to determine whether the inserted hitbox was the topmost.
3095 ///
3096 /// This method should only be called as part of the prepaint phase of element drawing.
3097 pub fn insert_hitbox(&mut self, bounds: Bounds<Pixels>, behavior: HitboxBehavior) -> Hitbox {
3098 self.invalidator.debug_assert_prepaint();
3099
3100 let content_mask = self.content_mask();
3101 let mut id = self.next_hitbox_id;
3102 self.next_hitbox_id = self.next_hitbox_id.next();
3103 let hitbox = Hitbox {
3104 id,
3105 bounds,
3106 content_mask,
3107 behavior,
3108 };
3109 self.next_frame.hitboxes.push(hitbox.clone());
3110 hitbox
3111 }
3112
3113 /// Set a hitbox which will act as a control area of the platform window.
3114 ///
3115 /// This method should only be called as part of the paint phase of element drawing.
3116 pub fn insert_window_control_hitbox(&mut self, area: WindowControlArea, hitbox: Hitbox) {
3117 self.invalidator.debug_assert_paint();
3118 self.next_frame.window_control_hitboxes.push((area, hitbox));
3119 }
3120
3121 /// Sets the key context for the current element. This context will be used to translate
3122 /// keybindings into actions.
3123 ///
3124 /// This method should only be called as part of the paint phase of element drawing.
3125 pub fn set_key_context(&mut self, context: KeyContext) {
3126 self.invalidator.debug_assert_paint();
3127 self.next_frame.dispatch_tree.set_key_context(context);
3128 }
3129
3130 /// Sets the focus handle for the current element. This handle will be used to manage focus state
3131 /// and keyboard event dispatch for the element.
3132 ///
3133 /// This method should only be called as part of the prepaint phase of element drawing.
3134 pub fn set_focus_handle(&mut self, focus_handle: &FocusHandle, _: &App) {
3135 self.invalidator.debug_assert_prepaint();
3136 if focus_handle.is_focused(self) {
3137 println!("setting focus for next frame");
3138 self.next_frame.focus = Some(focus_handle.id);
3139 }
3140 self.next_frame.dispatch_tree.set_focus_id(focus_handle.id);
3141 }
3142
3143 /// Sets the view id for the current element, which will be used to manage view caching.
3144 ///
3145 /// This method should only be called as part of element prepaint. We plan on removing this
3146 /// method eventually when we solve some issues that require us to construct editor elements
3147 /// directly instead of always using editors via views.
3148 pub fn set_view_id(&mut self, view_id: EntityId) {
3149 self.invalidator.debug_assert_prepaint();
3150 self.next_frame.dispatch_tree.set_view_id(view_id);
3151 }
3152
3153 /// Get the entity ID for the currently rendering view
3154 pub fn current_view(&self) -> EntityId {
3155 self.invalidator.debug_assert_paint_or_prepaint();
3156 self.rendered_entity_stack.last().copied().unwrap()
3157 }
3158
3159 pub(crate) fn with_rendered_view<R>(
3160 &mut self,
3161 id: EntityId,
3162 f: impl FnOnce(&mut Self) -> R,
3163 ) -> R {
3164 self.rendered_entity_stack.push(id);
3165 let result = f(self);
3166 self.rendered_entity_stack.pop();
3167 result
3168 }
3169
3170 /// Executes the provided function with the specified image cache.
3171 pub fn with_image_cache<F, R>(&mut self, image_cache: Option<AnyImageCache>, f: F) -> R
3172 where
3173 F: FnOnce(&mut Self) -> R,
3174 {
3175 if let Some(image_cache) = image_cache {
3176 self.image_cache_stack.push(image_cache);
3177 let result = f(self);
3178 self.image_cache_stack.pop();
3179 result
3180 } else {
3181 f(self)
3182 }
3183 }
3184
3185 /// Sets an input handler, such as [`ElementInputHandler`][element_input_handler], which interfaces with the
3186 /// platform to receive textual input with proper integration with concerns such
3187 /// as IME interactions. This handler will be active for the upcoming frame until the following frame is
3188 /// rendered.
3189 ///
3190 /// This method should only be called as part of the paint phase of element drawing.
3191 ///
3192 /// [element_input_handler]: crate::ElementInputHandler
3193 pub fn handle_input(
3194 &mut self,
3195 focus_handle: &FocusHandle,
3196 input_handler: impl InputHandler,
3197 cx: &App,
3198 ) {
3199 self.invalidator.debug_assert_paint();
3200
3201 if focus_handle.is_focused(self) {
3202 let cx = self.to_async(cx);
3203 self.next_frame
3204 .input_handlers
3205 .push(Some(PlatformInputHandler::new(cx, Box::new(input_handler))));
3206 }
3207 }
3208
3209 /// Register a mouse 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 method should only be called as part of the paint phase of element drawing.
3214 pub fn on_mouse_event<Event: MouseEvent>(
3215 &mut self,
3216 mut handler: impl FnMut(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
3217 ) {
3218 self.invalidator.debug_assert_paint();
3219
3220 self.next_frame.mouse_listeners.push(Some(Box::new(
3221 move |event: &dyn Any, phase: DispatchPhase, window: &mut Window, cx: &mut App| {
3222 if let Some(event) = event.downcast_ref() {
3223 handler(event, phase, window, cx)
3224 }
3225 },
3226 )));
3227 }
3228
3229 /// Register a key event listener on the window for the next frame. The type of event
3230 /// is determined by the first parameter of the given listener. When the next frame is rendered
3231 /// the listener will be cleared.
3232 ///
3233 /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
3234 /// a specific need to register a global listener.
3235 ///
3236 /// This method should only be called as part of the paint phase of element drawing.
3237 pub fn on_key_event<Event: KeyEvent>(
3238 &mut self,
3239 listener: impl Fn(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
3240 ) {
3241 self.invalidator.debug_assert_paint();
3242
3243 self.next_frame.dispatch_tree.on_key_event(Rc::new(
3244 move |event: &dyn Any, phase, window: &mut Window, cx: &mut App| {
3245 if let Some(event) = event.downcast_ref::<Event>() {
3246 listener(event, phase, window, cx)
3247 }
3248 },
3249 ));
3250 }
3251
3252 /// Register a modifiers changed event listener on the window for the next frame.
3253 ///
3254 /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
3255 /// a specific need to register a global listener.
3256 ///
3257 /// This method should only be called as part of the paint phase of element drawing.
3258 pub fn on_modifiers_changed(
3259 &mut self,
3260 listener: impl Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static,
3261 ) {
3262 self.invalidator.debug_assert_paint();
3263
3264 self.next_frame.dispatch_tree.on_modifiers_changed(Rc::new(
3265 move |event: &ModifiersChangedEvent, window: &mut Window, cx: &mut App| {
3266 listener(event, window, cx)
3267 },
3268 ));
3269 }
3270
3271 /// Register a listener to be called when the given focus handle or one of its descendants receives focus.
3272 /// This does not fire if the given focus handle - or one of its descendants - was previously focused.
3273 /// Returns a subscription and persists until the subscription is dropped.
3274 pub fn on_focus_in(
3275 &mut self,
3276 handle: &FocusHandle,
3277 cx: &mut App,
3278 mut listener: impl FnMut(&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 event.is_focus_in(focus_id) {
3284 listener(window, cx);
3285 }
3286 true
3287 }));
3288 cx.defer(move |_| activate());
3289 subscription
3290 }
3291
3292 /// Register a listener to be called when the given focus handle or one of its descendants loses focus.
3293 /// Returns a subscription and persists until the subscription is dropped.
3294 pub fn on_focus_out(
3295 &mut self,
3296 handle: &FocusHandle,
3297 cx: &mut App,
3298 mut listener: impl FnMut(FocusOutEvent, &mut Window, &mut App) + 'static,
3299 ) -> Subscription {
3300 let focus_id = handle.id;
3301 let (subscription, activate) =
3302 self.new_focus_listener(Box::new(move |event, window, cx| {
3303 if let Some(blurred_id) = event.previous_focus_path.last().copied() {
3304 if event.is_focus_out(focus_id) {
3305 let event = FocusOutEvent {
3306 blurred: WeakFocusHandle {
3307 id: blurred_id,
3308 handles: Arc::downgrade(&cx.focus_handles),
3309 },
3310 };
3311 listener(event, window, cx)
3312 }
3313 }
3314 true
3315 }));
3316 cx.defer(move |_| activate());
3317 subscription
3318 }
3319
3320 fn reset_cursor_style(&self, cx: &mut App) {
3321 // Set the cursor only if we're the active window.
3322 if self.is_window_hovered() {
3323 let style = self
3324 .rendered_frame
3325 .cursor_style(self)
3326 .unwrap_or(CursorStyle::Arrow);
3327 cx.platform.set_cursor_style(style);
3328 }
3329 }
3330
3331 /// Dispatch a given keystroke as though the user had typed it.
3332 /// You can create a keystroke with Keystroke::parse("").
3333 pub fn dispatch_keystroke(&mut self, keystroke: Keystroke, cx: &mut App) -> bool {
3334 let keystroke = keystroke.with_simulated_ime();
3335 let result = self.dispatch_event(
3336 PlatformInput::KeyDown(KeyDownEvent {
3337 keystroke: keystroke.clone(),
3338 is_held: false,
3339 }),
3340 cx,
3341 );
3342 if !result.propagate {
3343 return true;
3344 }
3345
3346 if let Some(input) = keystroke.key_char {
3347 if let Some(mut input_handler) = self.platform_window.take_input_handler() {
3348 input_handler.dispatch_input(&input, self, cx);
3349 self.platform_window.set_input_handler(input_handler);
3350 return true;
3351 }
3352 }
3353
3354 false
3355 }
3356
3357 /// Return a key binding string for an action, to display in the UI. Uses the highest precedence
3358 /// binding for the action (last binding added to the keymap).
3359 pub fn keystroke_text_for(&self, action: &dyn Action) -> String {
3360 self.highest_precedence_binding_for_action(action)
3361 .map(|binding| {
3362 binding
3363 .keystrokes()
3364 .iter()
3365 .map(ToString::to_string)
3366 .collect::<Vec<_>>()
3367 .join(" ")
3368 })
3369 .unwrap_or_else(|| action.name().to_string())
3370 }
3371
3372 /// Dispatch a mouse or keyboard event on the window.
3373 #[profiling::function]
3374 pub fn dispatch_event(&mut self, event: PlatformInput, cx: &mut App) -> DispatchEventResult {
3375 self.last_input_timestamp.set(Instant::now());
3376 // Handlers may set this to false by calling `stop_propagation`.
3377 cx.propagate_event = true;
3378 // Handlers may set this to true by calling `prevent_default`.
3379 self.default_prevented = false;
3380
3381 let event = match event {
3382 // Track the mouse position with our own state, since accessing the platform
3383 // API for the mouse position can only occur on the main thread.
3384 PlatformInput::MouseMove(mouse_move) => {
3385 self.mouse_position = mouse_move.position;
3386 self.modifiers = mouse_move.modifiers;
3387 PlatformInput::MouseMove(mouse_move)
3388 }
3389 PlatformInput::MouseDown(mouse_down) => {
3390 self.mouse_position = mouse_down.position;
3391 self.modifiers = mouse_down.modifiers;
3392 PlatformInput::MouseDown(mouse_down)
3393 }
3394 PlatformInput::MouseUp(mouse_up) => {
3395 self.mouse_position = mouse_up.position;
3396 self.modifiers = mouse_up.modifiers;
3397 PlatformInput::MouseUp(mouse_up)
3398 }
3399 PlatformInput::MouseExited(mouse_exited) => {
3400 self.modifiers = mouse_exited.modifiers;
3401 PlatformInput::MouseExited(mouse_exited)
3402 }
3403 PlatformInput::ModifiersChanged(modifiers_changed) => {
3404 self.modifiers = modifiers_changed.modifiers;
3405 self.capslock = modifiers_changed.capslock;
3406 PlatformInput::ModifiersChanged(modifiers_changed)
3407 }
3408 PlatformInput::ScrollWheel(scroll_wheel) => {
3409 self.mouse_position = scroll_wheel.position;
3410 self.modifiers = scroll_wheel.modifiers;
3411 PlatformInput::ScrollWheel(scroll_wheel)
3412 }
3413 // Translate dragging and dropping of external files from the operating system
3414 // to internal drag and drop events.
3415 PlatformInput::FileDrop(file_drop) => match file_drop {
3416 FileDropEvent::Entered { position, paths } => {
3417 self.mouse_position = position;
3418 if cx.active_drag.is_none() {
3419 cx.active_drag = Some(AnyDrag {
3420 value: Arc::new(paths.clone()),
3421 view: cx.new(|_| paths).into(),
3422 cursor_offset: position,
3423 cursor_style: None,
3424 });
3425 }
3426 PlatformInput::MouseMove(MouseMoveEvent {
3427 position,
3428 pressed_button: Some(MouseButton::Left),
3429 modifiers: Modifiers::default(),
3430 })
3431 }
3432 FileDropEvent::Pending { position } => {
3433 self.mouse_position = position;
3434 PlatformInput::MouseMove(MouseMoveEvent {
3435 position,
3436 pressed_button: Some(MouseButton::Left),
3437 modifiers: Modifiers::default(),
3438 })
3439 }
3440 FileDropEvent::Submit { position } => {
3441 cx.activate(true);
3442 self.mouse_position = position;
3443 PlatformInput::MouseUp(MouseUpEvent {
3444 button: MouseButton::Left,
3445 position,
3446 modifiers: Modifiers::default(),
3447 click_count: 1,
3448 })
3449 }
3450 FileDropEvent::Exited => {
3451 cx.active_drag.take();
3452 PlatformInput::FileDrop(FileDropEvent::Exited)
3453 }
3454 },
3455 PlatformInput::KeyDown(_) | PlatformInput::KeyUp(_) => event,
3456 };
3457
3458 if let Some(any_mouse_event) = event.mouse_event() {
3459 self.dispatch_mouse_event(any_mouse_event, cx);
3460 } else if let Some(any_key_event) = event.keyboard_event() {
3461 self.dispatch_key_event(any_key_event, cx);
3462 }
3463
3464 DispatchEventResult {
3465 propagate: cx.propagate_event,
3466 default_prevented: self.default_prevented,
3467 }
3468 }
3469
3470 fn dispatch_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
3471 let hit_test = self.rendered_frame.hit_test(self.mouse_position());
3472 if hit_test != self.mouse_hit_test {
3473 self.mouse_hit_test = hit_test;
3474 self.reset_cursor_style(cx);
3475 }
3476
3477 #[cfg(any(feature = "inspector", debug_assertions))]
3478 if self.is_inspector_picking(cx) {
3479 self.handle_inspector_mouse_event(event, cx);
3480 // When inspector is picking, all other mouse handling is skipped.
3481 return;
3482 }
3483
3484 let mut mouse_listeners = mem::take(&mut self.rendered_frame.mouse_listeners);
3485
3486 // Capture phase, events bubble from back to front. Handlers for this phase are used for
3487 // special purposes, such as detecting events outside of a given Bounds.
3488 for listener in &mut mouse_listeners {
3489 let listener = listener.as_mut().unwrap();
3490 listener(event, DispatchPhase::Capture, self, cx);
3491 if !cx.propagate_event {
3492 break;
3493 }
3494 }
3495
3496 // Bubble phase, where most normal handlers do their work.
3497 if cx.propagate_event {
3498 for listener in mouse_listeners.iter_mut().rev() {
3499 let listener = listener.as_mut().unwrap();
3500 listener(event, DispatchPhase::Bubble, self, cx);
3501 if !cx.propagate_event {
3502 break;
3503 }
3504 }
3505 }
3506
3507 self.rendered_frame.mouse_listeners = mouse_listeners;
3508
3509 if cx.has_active_drag() {
3510 if event.is::<MouseMoveEvent>() {
3511 // If this was a mouse move event, redraw the window so that the
3512 // active drag can follow the mouse cursor.
3513 self.refresh();
3514 } else if event.is::<MouseUpEvent>() {
3515 // If this was a mouse up event, cancel the active drag and redraw
3516 // the window.
3517 cx.active_drag = None;
3518 self.refresh();
3519 }
3520 }
3521 }
3522
3523 fn dispatch_key_event(&mut self, event: &dyn Any, cx: &mut App) {
3524 if self.invalidator.is_dirty() {
3525 self.draw(cx).clear();
3526 }
3527
3528 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
3529 let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
3530
3531 let mut keystroke: Option<Keystroke> = None;
3532
3533 if let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() {
3534 if event.modifiers.number_of_modifiers() == 0
3535 && self.pending_modifier.modifiers.number_of_modifiers() == 1
3536 && !self.pending_modifier.saw_keystroke
3537 {
3538 let key = match self.pending_modifier.modifiers {
3539 modifiers if modifiers.shift => Some("shift"),
3540 modifiers if modifiers.control => Some("control"),
3541 modifiers if modifiers.alt => Some("alt"),
3542 modifiers if modifiers.platform => Some("platform"),
3543 modifiers if modifiers.function => Some("function"),
3544 _ => None,
3545 };
3546 if let Some(key) = key {
3547 keystroke = Some(Keystroke {
3548 key: key.to_string(),
3549 key_char: None,
3550 modifiers: Modifiers::default(),
3551 });
3552 }
3553 }
3554
3555 if self.pending_modifier.modifiers.number_of_modifiers() == 0
3556 && event.modifiers.number_of_modifiers() == 1
3557 {
3558 self.pending_modifier.saw_keystroke = false
3559 }
3560 self.pending_modifier.modifiers = event.modifiers
3561 } else if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
3562 self.pending_modifier.saw_keystroke = true;
3563 keystroke = Some(key_down_event.keystroke.clone());
3564 }
3565
3566 let Some(keystroke) = keystroke else {
3567 self.finish_dispatch_key_event(event, dispatch_path, self.context_stack(), cx);
3568 return;
3569 };
3570
3571 cx.propagate_event = true;
3572 self.dispatch_keystroke_interceptors(event, self.context_stack(), cx);
3573 if !cx.propagate_event {
3574 self.finish_dispatch_key_event(event, dispatch_path, self.context_stack(), cx);
3575 return;
3576 }
3577
3578 let mut currently_pending = self.pending_input.take().unwrap_or_default();
3579 if currently_pending.focus.is_some() && currently_pending.focus != self.focus {
3580 currently_pending = PendingInput::default();
3581 }
3582
3583 let match_result = self.rendered_frame.dispatch_tree.dispatch_key(
3584 currently_pending.keystrokes,
3585 keystroke,
3586 &dispatch_path,
3587 );
3588
3589 if !match_result.to_replay.is_empty() {
3590 self.replay_pending_input(match_result.to_replay, cx)
3591 }
3592
3593 if !match_result.pending.is_empty() {
3594 currently_pending.keystrokes = match_result.pending;
3595 currently_pending.focus = self.focus;
3596 currently_pending.timer = Some(self.spawn(cx, async move |cx| {
3597 cx.background_executor.timer(Duration::from_secs(1)).await;
3598 cx.update(move |window, cx| {
3599 let Some(currently_pending) = window
3600 .pending_input
3601 .take()
3602 .filter(|pending| pending.focus == window.focus)
3603 else {
3604 return;
3605 };
3606
3607 let node_id = window.focus_node_id_in_rendered_frame(window.focus);
3608 let dispatch_path = window.rendered_frame.dispatch_tree.dispatch_path(node_id);
3609
3610 let to_replay = window
3611 .rendered_frame
3612 .dispatch_tree
3613 .flush_dispatch(currently_pending.keystrokes, &dispatch_path);
3614
3615 window.pending_input_changed(cx);
3616 window.replay_pending_input(to_replay, cx)
3617 })
3618 .log_err();
3619 }));
3620 self.pending_input = Some(currently_pending);
3621 self.pending_input_changed(cx);
3622 cx.propagate_event = false;
3623 return;
3624 }
3625
3626 for binding in match_result.bindings {
3627 self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
3628 if !cx.propagate_event {
3629 self.dispatch_keystroke_observers(
3630 event,
3631 Some(binding.action),
3632 match_result.context_stack.clone(),
3633 cx,
3634 );
3635 self.pending_input_changed(cx);
3636 return;
3637 }
3638 }
3639
3640 self.finish_dispatch_key_event(event, dispatch_path, match_result.context_stack, cx);
3641 self.pending_input_changed(cx);
3642 }
3643
3644 fn finish_dispatch_key_event(
3645 &mut self,
3646 event: &dyn Any,
3647 dispatch_path: SmallVec<[DispatchNodeId; 32]>,
3648 context_stack: Vec<KeyContext>,
3649 cx: &mut App,
3650 ) {
3651 self.dispatch_key_down_up_event(event, &dispatch_path, cx);
3652 if !cx.propagate_event {
3653 return;
3654 }
3655
3656 self.dispatch_modifiers_changed_event(event, &dispatch_path, cx);
3657 if !cx.propagate_event {
3658 return;
3659 }
3660
3661 self.dispatch_keystroke_observers(event, None, context_stack, cx);
3662 }
3663
3664 fn pending_input_changed(&mut self, cx: &mut App) {
3665 self.pending_input_observers
3666 .clone()
3667 .retain(&(), |callback| callback(self, cx));
3668 }
3669
3670 fn dispatch_key_down_up_event(
3671 &mut self,
3672 event: &dyn Any,
3673 dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
3674 cx: &mut App,
3675 ) {
3676 // Capture phase
3677 for node_id in dispatch_path {
3678 let node = self.rendered_frame.dispatch_tree.node(*node_id);
3679
3680 for key_listener in node.key_listeners.clone() {
3681 key_listener(event, DispatchPhase::Capture, self, cx);
3682 if !cx.propagate_event {
3683 return;
3684 }
3685 }
3686 }
3687
3688 // Bubble phase
3689 for node_id in dispatch_path.iter().rev() {
3690 // Handle low level key events
3691 let node = self.rendered_frame.dispatch_tree.node(*node_id);
3692 for key_listener in node.key_listeners.clone() {
3693 key_listener(event, DispatchPhase::Bubble, self, cx);
3694 if !cx.propagate_event {
3695 return;
3696 }
3697 }
3698 }
3699 }
3700
3701 fn dispatch_modifiers_changed_event(
3702 &mut self,
3703 event: &dyn Any,
3704 dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
3705 cx: &mut App,
3706 ) {
3707 let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() else {
3708 return;
3709 };
3710 for node_id in dispatch_path.iter().rev() {
3711 let node = self.rendered_frame.dispatch_tree.node(*node_id);
3712 for listener in node.modifiers_changed_listeners.clone() {
3713 listener(event, self, cx);
3714 if !cx.propagate_event {
3715 return;
3716 }
3717 }
3718 }
3719 }
3720
3721 /// Determine whether a potential multi-stroke key binding is in progress on this window.
3722 pub fn has_pending_keystrokes(&self) -> bool {
3723 self.pending_input.is_some()
3724 }
3725
3726 pub(crate) fn clear_pending_keystrokes(&mut self) {
3727 self.pending_input.take();
3728 }
3729
3730 /// Returns the currently pending input keystrokes that might result in a multi-stroke key binding.
3731 pub fn pending_input_keystrokes(&self) -> Option<&[Keystroke]> {
3732 self.pending_input
3733 .as_ref()
3734 .map(|pending_input| pending_input.keystrokes.as_slice())
3735 }
3736
3737 fn replay_pending_input(&mut self, replays: SmallVec<[Replay; 1]>, cx: &mut App) {
3738 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
3739 let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
3740
3741 'replay: for replay in replays {
3742 let event = KeyDownEvent {
3743 keystroke: replay.keystroke.clone(),
3744 is_held: false,
3745 };
3746
3747 cx.propagate_event = true;
3748 for binding in replay.bindings {
3749 self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
3750 if !cx.propagate_event {
3751 self.dispatch_keystroke_observers(
3752 &event,
3753 Some(binding.action),
3754 Vec::default(),
3755 cx,
3756 );
3757 continue 'replay;
3758 }
3759 }
3760
3761 self.dispatch_key_down_up_event(&event, &dispatch_path, cx);
3762 if !cx.propagate_event {
3763 continue 'replay;
3764 }
3765 if let Some(input) = replay.keystroke.key_char.as_ref().cloned() {
3766 if let Some(mut input_handler) = self.platform_window.take_input_handler() {
3767 input_handler.dispatch_input(&input, self, cx);
3768 self.platform_window.set_input_handler(input_handler)
3769 }
3770 }
3771 }
3772 }
3773
3774 fn focus_node_id_in_rendered_frame(&self, focus_id: Option<FocusId>) -> DispatchNodeId {
3775 focus_id
3776 .and_then(|focus_id| {
3777 self.rendered_frame
3778 .dispatch_tree
3779 .focusable_node_id(focus_id)
3780 })
3781 .unwrap_or_else(|| {
3782 println!("root node id");
3783 self.rendered_frame.dispatch_tree.root_node_id()
3784 })
3785 }
3786
3787 fn dispatch_action_on_node(
3788 &mut self,
3789 node_id: DispatchNodeId,
3790 action: &dyn Action,
3791 cx: &mut App,
3792 ) {
3793 let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
3794
3795 // Capture phase for global actions.
3796 cx.propagate_event = true;
3797 if let Some(mut global_listeners) = cx
3798 .global_action_listeners
3799 .remove(&action.as_any().type_id())
3800 {
3801 for listener in &global_listeners {
3802 listener(action.as_any(), DispatchPhase::Capture, cx);
3803 if !cx.propagate_event {
3804 break;
3805 }
3806 }
3807
3808 global_listeners.extend(
3809 cx.global_action_listeners
3810 .remove(&action.as_any().type_id())
3811 .unwrap_or_default(),
3812 );
3813
3814 cx.global_action_listeners
3815 .insert(action.as_any().type_id(), global_listeners);
3816 }
3817
3818 if !cx.propagate_event {
3819 return;
3820 }
3821
3822 // Capture phase for window actions.
3823 for node_id in &dispatch_path {
3824 let node = self.rendered_frame.dispatch_tree.node(*node_id);
3825 for DispatchActionListener {
3826 action_type,
3827 listener,
3828 } in node.action_listeners.clone()
3829 {
3830 let any_action = action.as_any();
3831 if action_type == any_action.type_id() {
3832 listener(any_action, DispatchPhase::Capture, self, cx);
3833
3834 if !cx.propagate_event {
3835 return;
3836 }
3837 }
3838 }
3839 }
3840
3841 // Bubble phase for window actions.
3842 for node_id in dispatch_path.iter().rev() {
3843 let node = self.rendered_frame.dispatch_tree.node(*node_id);
3844 for DispatchActionListener {
3845 action_type,
3846 listener,
3847 } in node.action_listeners.clone()
3848 {
3849 let any_action = action.as_any();
3850 if action_type == any_action.type_id() {
3851 cx.propagate_event = false; // Actions stop propagation by default during the bubble phase
3852 listener(any_action, DispatchPhase::Bubble, self, cx);
3853
3854 if !cx.propagate_event {
3855 return;
3856 }
3857 }
3858 }
3859 }
3860
3861 // Bubble phase for global actions.
3862 if let Some(mut global_listeners) = cx
3863 .global_action_listeners
3864 .remove(&action.as_any().type_id())
3865 {
3866 for listener in global_listeners.iter().rev() {
3867 cx.propagate_event = false; // Actions stop propagation by default during the bubble phase
3868
3869 listener(action.as_any(), DispatchPhase::Bubble, cx);
3870 if !cx.propagate_event {
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}