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