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