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