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