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