1use crate::{
2 point, prelude::*, px, size, transparent_black, Action, AnyDrag, AnyElement, AnyTooltip,
3 AnyView, App, AppContext, Arena, Asset, AsyncWindowContext, AvailableSpace, Background, Bounds,
4 BoxShadow, Context, Corners, CursorStyle, Decorations, DevicePixels, DispatchActionListener,
5 DispatchNodeId, DispatchTree, DisplayId, Edges, Effect, Entity, EntityId, EventEmitter,
6 FileDropEvent, FontId, Global, GlobalElementId, GlyphId, GpuSpecs, Hsla, InputHandler, IsZero,
7 KeyBinding, KeyContext, KeyDownEvent, KeyEvent, Keystroke, KeystrokeEvent, LayoutId,
8 LineLayoutIndex, Modifiers, ModifiersChangedEvent, MonochromeSprite, MouseButton, MouseEvent,
9 MouseMoveEvent, MouseUpEvent, Path, Pixels, PlatformAtlas, PlatformDisplay, PlatformInput,
10 PlatformInputHandler, PlatformWindow, Point, PolychromeSprite, PromptLevel, Quad, Render,
11 RenderGlyphParams, RenderImage, RenderImageParams, RenderSvgParams, Replay, ResizeEdge,
12 ScaledPixels, Scene, Shadow, SharedString, Size, StrikethroughStyle, Style, SubscriberSet,
13 Subscription, TaffyLayoutEngine, Task, TextStyle, TextStyleRefinement, TransformationMatrix,
14 Underline, UnderlineStyle, WindowAppearance, WindowBackgroundAppearance, WindowBounds,
15 WindowControls, WindowDecorations, WindowOptions, WindowParams, WindowTextSystem,
16 SMOOTH_SVG_SCALE_FACTOR, SUBPIXEL_VARIANTS,
17};
18use anyhow::{anyhow, Context as _, Result};
19use collections::{FxHashMap, FxHashSet};
20use derive_more::{Deref, DerefMut};
21use futures::channel::oneshot;
22use futures::FutureExt;
23#[cfg(target_os = "macos")]
24use media::core_video::CVImageBuffer;
25use parking_lot::RwLock;
26use refineable::Refineable;
27use slotmap::SlotMap;
28use smallvec::SmallVec;
29use std::{
30 any::{Any, TypeId},
31 borrow::Cow,
32 cell::{Cell, RefCell},
33 cmp,
34 fmt::{Debug, Display},
35 future::Future,
36 hash::{Hash, Hasher},
37 marker::PhantomData,
38 mem,
39 ops::{DerefMut, Range},
40 rc::Rc,
41 sync::{
42 atomic::{AtomicUsize, Ordering::SeqCst},
43 Arc, Weak,
44 },
45 time::{Duration, Instant},
46};
47use util::post_inc;
48use util::{measure, ResultExt};
49use uuid::Uuid;
50
51mod prompts;
52
53pub use prompts::*;
54
55pub(crate) const DEFAULT_WINDOW_SIZE: Size<Pixels> = size(px(1024.), px(700.));
56
57/// Represents the two different phases when dispatching events.
58#[derive(Default, Copy, Clone, Debug, Eq, PartialEq)]
59pub enum DispatchPhase {
60 /// After the capture phase comes the bubble phase, in which mouse event listeners are
61 /// invoked front to back and keyboard event listeners are invoked from the focused element
62 /// to the root of the element tree. This is the phase you'll most commonly want to use when
63 /// registering event listeners.
64 #[default]
65 Bubble,
66 /// During the initial capture phase, mouse event listeners are invoked back to front, and keyboard
67 /// listeners are invoked from the root of the tree downward toward the focused element. This phase
68 /// is used for special purposes such as clearing the "pressed" state for click events. If
69 /// you stop event propagation during this phase, you need to know what you're doing. Handlers
70 /// outside of the immediate region may rely on detecting non-local events during this phase.
71 Capture,
72}
73
74impl DispatchPhase {
75 /// Returns true if this represents the "bubble" phase.
76 pub fn bubble(self) -> bool {
77 self == DispatchPhase::Bubble
78 }
79
80 /// Returns true if this represents the "capture" phase.
81 pub fn capture(self) -> bool {
82 self == DispatchPhase::Capture
83 }
84}
85
86struct WindowInvalidatorInner {
87 pub dirty: bool,
88 pub draw_phase: DrawPhase,
89 pub dirty_views: FxHashSet<EntityId>,
90}
91
92#[derive(Clone)]
93pub(crate) struct WindowInvalidator {
94 inner: Rc<RefCell<WindowInvalidatorInner>>,
95}
96
97impl WindowInvalidator {
98 pub fn new() -> Self {
99 WindowInvalidator {
100 inner: Rc::new(RefCell::new(WindowInvalidatorInner {
101 dirty: true,
102 draw_phase: DrawPhase::None,
103 dirty_views: FxHashSet::default(),
104 })),
105 }
106 }
107
108 pub fn invalidate_view(&self, entity: EntityId, cx: &mut App) -> bool {
109 let mut inner = self.inner.borrow_mut();
110 inner.dirty_views.insert(entity);
111 if inner.draw_phase == DrawPhase::None {
112 inner.dirty = true;
113 cx.push_effect(Effect::Notify { emitter: entity });
114 true
115 } else {
116 false
117 }
118 }
119
120 pub fn is_dirty(&self) -> bool {
121 self.inner.borrow().dirty
122 }
123
124 pub fn set_dirty(&self, dirty: bool) {
125 self.inner.borrow_mut().dirty = dirty
126 }
127
128 pub fn set_phase(&self, phase: DrawPhase) {
129 self.inner.borrow_mut().draw_phase = phase
130 }
131
132 pub fn take_views(&self) -> FxHashSet<EntityId> {
133 mem::take(&mut self.inner.borrow_mut().dirty_views)
134 }
135
136 pub fn replace_views(&self, views: FxHashSet<EntityId>) {
137 self.inner.borrow_mut().dirty_views = views;
138 }
139
140 pub fn not_painting(&self) -> bool {
141 self.inner.borrow().draw_phase == DrawPhase::None
142 }
143
144 #[track_caller]
145 pub fn debug_assert_paint(&self) {
146 debug_assert!(
147 matches!(self.inner.borrow().draw_phase, DrawPhase::Paint),
148 "this method can only be called during paint"
149 );
150 }
151
152 #[track_caller]
153 pub fn debug_assert_prepaint(&self) {
154 debug_assert!(
155 matches!(self.inner.borrow().draw_phase, DrawPhase::Prepaint),
156 "this method can only be called during request_layout, or prepaint"
157 );
158 }
159
160 #[track_caller]
161 pub fn debug_assert_paint_or_prepaint(&self) {
162 debug_assert!(
163 matches!(
164 self.inner.borrow().draw_phase,
165 DrawPhase::Paint | DrawPhase::Prepaint
166 ),
167 "this method can only be called during request_layout, prepaint, or paint"
168 );
169 }
170}
171
172type AnyObserver = Box<dyn FnMut(&mut Window, &mut App) -> bool + 'static>;
173
174pub(crate) type AnyWindowFocusListener =
175 Box<dyn FnMut(&WindowFocusEvent, &mut Window, &mut App) -> bool + 'static>;
176
177pub(crate) struct WindowFocusEvent {
178 pub(crate) previous_focus_path: SmallVec<[FocusId; 8]>,
179 pub(crate) current_focus_path: SmallVec<[FocusId; 8]>,
180}
181
182impl WindowFocusEvent {
183 pub fn is_focus_in(&self, focus_id: FocusId) -> bool {
184 !self.previous_focus_path.contains(&focus_id) && self.current_focus_path.contains(&focus_id)
185 }
186
187 pub fn is_focus_out(&self, focus_id: FocusId) -> bool {
188 self.previous_focus_path.contains(&focus_id) && !self.current_focus_path.contains(&focus_id)
189 }
190}
191
192/// This is provided when subscribing for `Context::on_focus_out` events.
193pub struct FocusOutEvent {
194 /// A weak focus handle representing what was blurred.
195 pub blurred: WeakFocusHandle,
196}
197
198slotmap::new_key_type! {
199 /// A globally unique identifier for a focusable element.
200 pub struct FocusId;
201}
202
203thread_local! {
204 /// 8MB wasn't quite enough...
205 pub(crate) static ELEMENT_ARENA: RefCell<Arena> = RefCell::new(Arena::new(32 * 1024 * 1024));
206}
207
208pub(crate) type FocusMap = RwLock<SlotMap<FocusId, AtomicUsize>>;
209
210impl FocusId {
211 /// Obtains whether the element associated with this handle is currently focused.
212 pub fn is_focused(&self, window: &Window) -> bool {
213 window.focus == Some(*self)
214 }
215
216 /// Obtains whether the element associated with this handle contains the focused
217 /// element or is itself focused.
218 pub fn contains_focused(&self, window: &Window, cx: &App) -> bool {
219 window
220 .focused(cx)
221 .map_or(false, |focused| self.contains(focused.id, window))
222 }
223
224 /// Obtains whether the element associated with this handle is contained within the
225 /// focused element or is itself focused.
226 pub fn within_focused(&self, window: &Window, cx: &App) -> bool {
227 let focused = window.focused(cx);
228 focused.map_or(false, |focused| focused.id.contains(*self, window))
229 }
230
231 /// Obtains whether this handle contains the given handle in the most recently rendered frame.
232 pub(crate) fn contains(&self, other: Self, window: &Window) -> bool {
233 window
234 .rendered_frame
235 .dispatch_tree
236 .focus_contains(*self, other)
237 }
238}
239
240/// A handle which can be used to track and manipulate the focused element in a window.
241pub struct FocusHandle {
242 pub(crate) id: FocusId,
243 handles: Arc<FocusMap>,
244}
245
246impl std::fmt::Debug for FocusHandle {
247 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
248 f.write_fmt(format_args!("FocusHandle({:?})", self.id))
249 }
250}
251
252impl FocusHandle {
253 pub(crate) fn new(handles: &Arc<FocusMap>) -> Self {
254 let id = handles.write().insert(AtomicUsize::new(1));
255 Self {
256 id,
257 handles: handles.clone(),
258 }
259 }
260
261 pub(crate) fn for_id(id: FocusId, handles: &Arc<FocusMap>) -> Option<Self> {
262 let lock = handles.read();
263 let ref_count = lock.get(id)?;
264 if ref_count.load(SeqCst) == 0 {
265 None
266 } else {
267 ref_count.fetch_add(1, SeqCst);
268 Some(Self {
269 id,
270 handles: handles.clone(),
271 })
272 }
273 }
274
275 /// Converts this focus handle into a weak variant, which does not prevent it from being released.
276 pub fn downgrade(&self) -> WeakFocusHandle {
277 WeakFocusHandle {
278 id: self.id,
279 handles: Arc::downgrade(&self.handles),
280 }
281 }
282
283 /// Moves the focus to the element associated with this handle.
284 pub fn focus(&self, window: &mut Window) {
285 window.focus(self)
286 }
287
288 /// Obtains whether the element associated with this handle is currently focused.
289 pub fn is_focused(&self, window: &Window) -> bool {
290 self.id.is_focused(window)
291 }
292
293 /// Obtains whether the element associated with this handle contains the focused
294 /// element or is itself focused.
295 pub fn contains_focused(&self, window: &Window, cx: &App) -> bool {
296 self.id.contains_focused(window, cx)
297 }
298
299 /// Obtains whether the element associated with this handle is contained within the
300 /// focused element or is itself focused.
301 pub fn within_focused(&self, window: &Window, cx: &mut App) -> bool {
302 self.id.within_focused(window, cx)
303 }
304
305 /// Obtains whether this handle contains the given handle in the most recently rendered frame.
306 pub fn contains(&self, other: &Self, window: &Window) -> bool {
307 self.id.contains(other.id, window)
308 }
309
310 /// Dispatch an action on the element that rendered this focus handle
311 pub fn dispatch_action(&self, action: &dyn Action, window: &mut Window, cx: &mut App) {
312 if let Some(node_id) = window
313 .rendered_frame
314 .dispatch_tree
315 .focusable_node_id(self.id)
316 {
317 window.dispatch_action_on_node(node_id, action, cx)
318 }
319 }
320}
321
322impl Clone for FocusHandle {
323 fn clone(&self) -> Self {
324 Self::for_id(self.id, &self.handles).unwrap()
325 }
326}
327
328impl PartialEq for FocusHandle {
329 fn eq(&self, other: &Self) -> bool {
330 self.id == other.id
331 }
332}
333
334impl Eq for FocusHandle {}
335
336impl Drop for FocusHandle {
337 fn drop(&mut self) {
338 self.handles
339 .read()
340 .get(self.id)
341 .unwrap()
342 .fetch_sub(1, SeqCst);
343 }
344}
345
346/// A weak reference to a focus handle.
347#[derive(Clone, Debug)]
348pub struct WeakFocusHandle {
349 pub(crate) id: FocusId,
350 pub(crate) handles: Weak<FocusMap>,
351}
352
353impl WeakFocusHandle {
354 /// Attempts to upgrade the [WeakFocusHandle] to a [FocusHandle].
355 pub fn upgrade(&self) -> Option<FocusHandle> {
356 let handles = self.handles.upgrade()?;
357 FocusHandle::for_id(self.id, &handles)
358 }
359}
360
361impl PartialEq for WeakFocusHandle {
362 fn eq(&self, other: &WeakFocusHandle) -> bool {
363 self.id == other.id
364 }
365}
366
367impl Eq for WeakFocusHandle {}
368
369impl PartialEq<FocusHandle> for WeakFocusHandle {
370 fn eq(&self, other: &FocusHandle) -> bool {
371 self.id == other.id
372 }
373}
374
375impl PartialEq<WeakFocusHandle> for FocusHandle {
376 fn eq(&self, other: &WeakFocusHandle) -> bool {
377 self.id == other.id
378 }
379}
380
381/// Focusable allows users of your view to easily
382/// focus it (using window.focus_view(cx, view))
383pub trait Focusable: 'static {
384 /// Returns the focus handle associated with this view.
385 fn focus_handle(&self, cx: &App) -> FocusHandle;
386}
387
388impl<V: Focusable> Focusable for Entity<V> {
389 fn focus_handle(&self, cx: &App) -> FocusHandle {
390 self.read(cx).focus_handle(cx)
391 }
392}
393
394/// ManagedView is a view (like a Modal, Popover, Menu, etc.)
395/// where the lifecycle of the view is handled by another view.
396pub trait ManagedView: Focusable + EventEmitter<DismissEvent> + Render {}
397
398impl<M: Focusable + EventEmitter<DismissEvent> + Render> ManagedView for M {}
399
400/// Emitted by implementers of [`ManagedView`] to indicate the view should be dismissed, such as when a view is presented as a modal.
401pub struct DismissEvent;
402
403type FrameCallback = Box<dyn FnOnce(&mut Window, &mut App)>;
404
405pub(crate) type AnyMouseListener =
406 Box<dyn FnMut(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static>;
407
408#[derive(Clone)]
409pub(crate) struct CursorStyleRequest {
410 pub(crate) hitbox_id: HitboxId,
411 pub(crate) style: CursorStyle,
412}
413
414/// An identifier for a [Hitbox].
415#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
416pub struct HitboxId(usize);
417
418impl HitboxId {
419 /// Checks if the hitbox with this id is currently hovered.
420 pub fn is_hovered(&self, window: &Window) -> bool {
421 window.mouse_hit_test.0.contains(self)
422 }
423}
424
425/// A rectangular region that potentially blocks hitboxes inserted prior.
426/// See [Window::insert_hitbox] for more details.
427#[derive(Clone, Debug, Deref)]
428pub struct Hitbox {
429 /// A unique identifier for the hitbox.
430 pub id: HitboxId,
431 /// The bounds of the hitbox.
432 #[deref]
433 pub bounds: Bounds<Pixels>,
434 /// The content mask when the hitbox was inserted.
435 pub content_mask: ContentMask<Pixels>,
436 /// Whether the hitbox occludes other hitboxes inserted prior.
437 pub opaque: bool,
438}
439
440impl Hitbox {
441 /// Checks if the hitbox is currently hovered.
442 pub fn is_hovered(&self, window: &Window) -> bool {
443 self.id.is_hovered(window)
444 }
445}
446
447#[derive(Default, Eq, PartialEq)]
448pub(crate) struct HitTest(SmallVec<[HitboxId; 8]>);
449
450/// An identifier for a tooltip.
451#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
452pub struct TooltipId(usize);
453
454impl TooltipId {
455 /// Checks if the tooltip is currently hovered.
456 pub fn is_hovered(&self, window: &Window) -> bool {
457 window
458 .tooltip_bounds
459 .as_ref()
460 .map_or(false, |tooltip_bounds| {
461 tooltip_bounds.id == *self
462 && tooltip_bounds.bounds.contains(&window.mouse_position())
463 })
464 }
465}
466
467pub(crate) struct TooltipBounds {
468 id: TooltipId,
469 bounds: Bounds<Pixels>,
470}
471
472#[derive(Clone)]
473pub(crate) struct TooltipRequest {
474 id: TooltipId,
475 tooltip: AnyTooltip,
476}
477
478pub(crate) struct DeferredDraw {
479 priority: usize,
480 parent_node: DispatchNodeId,
481 element_id_stack: SmallVec<[ElementId; 32]>,
482 text_style_stack: Vec<TextStyleRefinement>,
483 element: Option<AnyElement>,
484 absolute_offset: Point<Pixels>,
485 prepaint_range: Range<PrepaintStateIndex>,
486 paint_range: Range<PaintIndex>,
487}
488
489pub(crate) struct Frame {
490 pub(crate) focus: Option<FocusId>,
491 pub(crate) window_active: bool,
492 pub(crate) element_states: FxHashMap<(GlobalElementId, TypeId), ElementStateBox>,
493 accessed_element_states: Vec<(GlobalElementId, TypeId)>,
494 pub(crate) mouse_listeners: Vec<Option<AnyMouseListener>>,
495 pub(crate) dispatch_tree: DispatchTree,
496 pub(crate) scene: Scene,
497 pub(crate) hitboxes: Vec<Hitbox>,
498 pub(crate) deferred_draws: Vec<DeferredDraw>,
499 pub(crate) input_handlers: Vec<Option<PlatformInputHandler>>,
500 pub(crate) tooltip_requests: Vec<Option<TooltipRequest>>,
501 pub(crate) cursor_styles: Vec<CursorStyleRequest>,
502 #[cfg(any(test, feature = "test-support"))]
503 pub(crate) debug_bounds: FxHashMap<String, Bounds<Pixels>>,
504}
505
506#[derive(Clone, Default)]
507pub(crate) struct PrepaintStateIndex {
508 hitboxes_index: usize,
509 tooltips_index: usize,
510 deferred_draws_index: usize,
511 dispatch_tree_index: usize,
512 accessed_element_states_index: usize,
513 line_layout_index: LineLayoutIndex,
514}
515
516#[derive(Clone, Default)]
517pub(crate) struct PaintIndex {
518 scene_index: usize,
519 mouse_listeners_index: usize,
520 input_handlers_index: usize,
521 cursor_styles_index: usize,
522 accessed_element_states_index: usize,
523 line_layout_index: LineLayoutIndex,
524}
525
526impl Frame {
527 pub(crate) fn new(dispatch_tree: DispatchTree) -> Self {
528 Frame {
529 focus: None,
530 window_active: false,
531 element_states: FxHashMap::default(),
532 accessed_element_states: Vec::new(),
533 mouse_listeners: Vec::new(),
534 dispatch_tree,
535 scene: Scene::default(),
536 hitboxes: Vec::new(),
537 deferred_draws: Vec::new(),
538 input_handlers: Vec::new(),
539 tooltip_requests: Vec::new(),
540 cursor_styles: Vec::new(),
541
542 #[cfg(any(test, feature = "test-support"))]
543 debug_bounds: FxHashMap::default(),
544 }
545 }
546
547 pub(crate) fn clear(&mut self) {
548 self.element_states.clear();
549 self.accessed_element_states.clear();
550 self.mouse_listeners.clear();
551 self.dispatch_tree.clear();
552 self.scene.clear();
553 self.input_handlers.clear();
554 self.tooltip_requests.clear();
555 self.cursor_styles.clear();
556 self.hitboxes.clear();
557 self.deferred_draws.clear();
558 self.focus = None;
559 }
560
561 pub(crate) fn hit_test(&self, position: Point<Pixels>) -> HitTest {
562 let mut hit_test = HitTest::default();
563 for hitbox in self.hitboxes.iter().rev() {
564 let bounds = hitbox.bounds.intersect(&hitbox.content_mask.bounds);
565 if bounds.contains(&position) {
566 hit_test.0.push(hitbox.id);
567 if hitbox.opaque {
568 break;
569 }
570 }
571 }
572 hit_test
573 }
574
575 pub(crate) fn focus_path(&self) -> SmallVec<[FocusId; 8]> {
576 self.focus
577 .map(|focus_id| self.dispatch_tree.focus_path(focus_id))
578 .unwrap_or_default()
579 }
580
581 pub(crate) fn finish(&mut self, prev_frame: &mut Self) {
582 for element_state_key in &self.accessed_element_states {
583 if let Some((element_state_key, element_state)) =
584 prev_frame.element_states.remove_entry(element_state_key)
585 {
586 self.element_states.insert(element_state_key, element_state);
587 }
588 }
589
590 self.scene.finish();
591 }
592}
593
594// Holds the state for a specific window.
595#[doc(hidden)]
596pub struct Window {
597 pub(crate) handle: AnyWindowHandle,
598 pub(crate) invalidator: WindowInvalidator,
599 pub(crate) removed: bool,
600 pub(crate) platform_window: Box<dyn PlatformWindow>,
601 display_id: Option<DisplayId>,
602 sprite_atlas: Arc<dyn PlatformAtlas>,
603 text_system: Arc<WindowTextSystem>,
604 rem_size: Pixels,
605 /// The stack of override values for the window's rem size.
606 ///
607 /// This is used by `with_rem_size` to allow rendering an element tree with
608 /// a given rem size.
609 rem_size_override_stack: SmallVec<[Pixels; 8]>,
610 pub(crate) viewport_size: Size<Pixels>,
611 layout_engine: Option<TaffyLayoutEngine>,
612 pub(crate) root: Option<AnyView>,
613 pub(crate) element_id_stack: SmallVec<[ElementId; 32]>,
614 pub(crate) text_style_stack: Vec<TextStyleRefinement>,
615 pub(crate) rendered_entity_stack: Vec<EntityId>,
616 pub(crate) element_offset_stack: Vec<Point<Pixels>>,
617 pub(crate) element_opacity: Option<f32>,
618 pub(crate) content_mask_stack: Vec<ContentMask<Pixels>>,
619 pub(crate) requested_autoscroll: Option<Bounds<Pixels>>,
620 pub(crate) rendered_frame: Frame,
621 pub(crate) next_frame: Frame,
622 pub(crate) next_hitbox_id: HitboxId,
623 pub(crate) next_tooltip_id: TooltipId,
624 pub(crate) tooltip_bounds: Option<TooltipBounds>,
625 next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>>,
626 pub(crate) dirty_views: FxHashSet<EntityId>,
627 focus_listeners: SubscriberSet<(), AnyWindowFocusListener>,
628 pub(crate) focus_lost_listeners: SubscriberSet<(), AnyObserver>,
629 default_prevented: bool,
630 mouse_position: Point<Pixels>,
631 mouse_hit_test: HitTest,
632 modifiers: Modifiers,
633 scale_factor: f32,
634 pub(crate) bounds_observers: SubscriberSet<(), AnyObserver>,
635 appearance: WindowAppearance,
636 pub(crate) appearance_observers: SubscriberSet<(), AnyObserver>,
637 active: Rc<Cell<bool>>,
638 hovered: Rc<Cell<bool>>,
639 pub(crate) needs_present: Rc<Cell<bool>>,
640 pub(crate) last_input_timestamp: Rc<Cell<Instant>>,
641 pub(crate) refreshing: bool,
642 pub(crate) activation_observers: SubscriberSet<(), AnyObserver>,
643 pub(crate) focus: Option<FocusId>,
644 focus_enabled: bool,
645 pending_input: Option<PendingInput>,
646 pending_modifier: ModifierState,
647 pub(crate) pending_input_observers: SubscriberSet<(), AnyObserver>,
648 prompt: Option<RenderablePromptHandle>,
649}
650
651#[derive(Clone, Debug, Default)]
652struct ModifierState {
653 modifiers: Modifiers,
654 saw_keystroke: bool,
655}
656
657#[derive(Clone, Copy, Debug, Eq, PartialEq)]
658pub(crate) enum DrawPhase {
659 None,
660 Prepaint,
661 Paint,
662 Focus,
663}
664
665#[derive(Default, Debug)]
666struct PendingInput {
667 keystrokes: SmallVec<[Keystroke; 1]>,
668 focus: Option<FocusId>,
669 timer: Option<Task<()>>,
670}
671
672pub(crate) struct ElementStateBox {
673 pub(crate) inner: Box<dyn Any>,
674 #[cfg(debug_assertions)]
675 pub(crate) type_name: &'static str,
676}
677
678fn default_bounds(display_id: Option<DisplayId>, cx: &mut App) -> Bounds<Pixels> {
679 const DEFAULT_WINDOW_OFFSET: Point<Pixels> = point(px(0.), px(35.));
680
681 // TODO, BUG: if you open a window with the currently active window
682 // on the stack, this will erroneously select the 'unwrap_or_else'
683 // code path
684 cx.active_window()
685 .and_then(|w| w.update(cx, |_, window, _| window.bounds()).ok())
686 .map(|mut bounds| {
687 bounds.origin += DEFAULT_WINDOW_OFFSET;
688 bounds
689 })
690 .unwrap_or_else(|| {
691 let display = display_id
692 .map(|id| cx.find_display(id))
693 .unwrap_or_else(|| cx.primary_display());
694
695 display
696 .map(|display| display.default_bounds())
697 .unwrap_or_else(|| Bounds::new(point(px(0.), px(0.)), DEFAULT_WINDOW_SIZE))
698 })
699}
700
701impl Window {
702 pub(crate) fn new(
703 handle: AnyWindowHandle,
704 options: WindowOptions,
705 cx: &mut App,
706 ) -> Result<Self> {
707 let WindowOptions {
708 window_bounds,
709 titlebar,
710 focus,
711 show,
712 kind,
713 is_movable,
714 display_id,
715 window_background,
716 app_id,
717 window_min_size,
718 window_decorations,
719 } = options;
720
721 let bounds = window_bounds
722 .map(|bounds| bounds.get_bounds())
723 .unwrap_or_else(|| default_bounds(display_id, cx));
724 let mut platform_window = cx.platform.open_window(
725 handle,
726 WindowParams {
727 bounds,
728 titlebar,
729 kind,
730 is_movable,
731 focus,
732 show,
733 display_id,
734 window_min_size,
735 },
736 )?;
737 let display_id = platform_window.display().map(|display| display.id());
738 let sprite_atlas = platform_window.sprite_atlas();
739 let mouse_position = platform_window.mouse_position();
740 let modifiers = platform_window.modifiers();
741 let content_size = platform_window.content_size();
742 let scale_factor = platform_window.scale_factor();
743 let appearance = platform_window.appearance();
744 let text_system = Arc::new(WindowTextSystem::new(cx.text_system().clone()));
745 let invalidator = WindowInvalidator::new();
746 let active = Rc::new(Cell::new(platform_window.is_active()));
747 let hovered = Rc::new(Cell::new(platform_window.is_hovered()));
748 let needs_present = Rc::new(Cell::new(false));
749 let next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>> = Default::default();
750 let last_input_timestamp = Rc::new(Cell::new(Instant::now()));
751
752 platform_window
753 .request_decorations(window_decorations.unwrap_or(WindowDecorations::Server));
754 platform_window.set_background_appearance(window_background);
755
756 if let Some(ref window_open_state) = window_bounds {
757 match window_open_state {
758 WindowBounds::Fullscreen(_) => platform_window.toggle_fullscreen(),
759 WindowBounds::Maximized(_) => platform_window.zoom(),
760 WindowBounds::Windowed(_) => {}
761 }
762 }
763
764 platform_window.on_close(Box::new({
765 let mut cx = cx.to_async();
766 move || {
767 let _ = handle.update(&mut cx, |_, window, _| window.remove_window());
768 }
769 }));
770 platform_window.on_request_frame(Box::new({
771 let mut cx = cx.to_async();
772 let invalidator = invalidator.clone();
773 let active = active.clone();
774 let needs_present = needs_present.clone();
775 let next_frame_callbacks = next_frame_callbacks.clone();
776 let last_input_timestamp = last_input_timestamp.clone();
777 move |request_frame_options| {
778 let next_frame_callbacks = next_frame_callbacks.take();
779 if !next_frame_callbacks.is_empty() {
780 handle
781 .update(&mut cx, |_, window, cx| {
782 for callback in next_frame_callbacks {
783 callback(window, cx);
784 }
785 })
786 .log_err();
787 }
788
789 // Keep presenting the current scene for 1 extra second since the
790 // last input to prevent the display from underclocking the refresh rate.
791 let needs_present = request_frame_options.require_presentation
792 || needs_present.get()
793 || (active.get()
794 && last_input_timestamp.get().elapsed() < Duration::from_secs(1));
795
796 if invalidator.is_dirty() {
797 measure("frame duration", || {
798 handle
799 .update(&mut cx, |_, window, cx| {
800 window.draw(cx);
801 window.present();
802 })
803 .log_err();
804 })
805 } else if needs_present {
806 handle
807 .update(&mut cx, |_, window, _| window.present())
808 .log_err();
809 }
810
811 handle
812 .update(&mut cx, |_, window, _| {
813 window.complete_frame();
814 })
815 .log_err();
816 }
817 }));
818 platform_window.on_resize(Box::new({
819 let mut cx = cx.to_async();
820 move |_, _| {
821 handle
822 .update(&mut cx, |_, window, cx| window.bounds_changed(cx))
823 .log_err();
824 }
825 }));
826 platform_window.on_moved(Box::new({
827 let mut cx = cx.to_async();
828 move || {
829 handle
830 .update(&mut cx, |_, window, cx| window.bounds_changed(cx))
831 .log_err();
832 }
833 }));
834 platform_window.on_appearance_changed(Box::new({
835 let mut cx = cx.to_async();
836 move || {
837 handle
838 .update(&mut cx, |_, window, cx| window.appearance_changed(cx))
839 .log_err();
840 }
841 }));
842 platform_window.on_active_status_change(Box::new({
843 let mut cx = cx.to_async();
844 move |active| {
845 handle
846 .update(&mut cx, |_, window, cx| {
847 window.active.set(active);
848 window
849 .activation_observers
850 .clone()
851 .retain(&(), |callback| callback(window, cx));
852 window.refresh();
853 })
854 .log_err();
855 }
856 }));
857 platform_window.on_hover_status_change(Box::new({
858 let mut cx = cx.to_async();
859 move |active| {
860 handle
861 .update(&mut cx, |_, window, _| {
862 window.hovered.set(active);
863 window.refresh();
864 })
865 .log_err();
866 }
867 }));
868 platform_window.on_input({
869 let mut cx = cx.to_async();
870 Box::new(move |event| {
871 handle
872 .update(&mut cx, |_, window, cx| window.dispatch_event(event, cx))
873 .log_err()
874 .unwrap_or(DispatchEventResult::default())
875 })
876 });
877
878 if let Some(app_id) = app_id {
879 platform_window.set_app_id(&app_id);
880 }
881
882 platform_window.map_window().unwrap();
883
884 Ok(Window {
885 handle,
886 invalidator,
887 removed: false,
888 platform_window,
889 display_id,
890 sprite_atlas,
891 text_system,
892 rem_size: px(16.),
893 rem_size_override_stack: SmallVec::new(),
894 viewport_size: content_size,
895 layout_engine: Some(TaffyLayoutEngine::new()),
896 root: None,
897 element_id_stack: SmallVec::default(),
898 text_style_stack: Vec::new(),
899 rendered_entity_stack: Vec::new(),
900 element_offset_stack: Vec::new(),
901 content_mask_stack: Vec::new(),
902 element_opacity: None,
903 requested_autoscroll: None,
904 rendered_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
905 next_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
906 next_frame_callbacks,
907 next_hitbox_id: HitboxId::default(),
908 next_tooltip_id: TooltipId::default(),
909 tooltip_bounds: None,
910 dirty_views: FxHashSet::default(),
911 focus_listeners: SubscriberSet::new(),
912 focus_lost_listeners: SubscriberSet::new(),
913 default_prevented: true,
914 mouse_position,
915 mouse_hit_test: HitTest::default(),
916 modifiers,
917 scale_factor,
918 bounds_observers: SubscriberSet::new(),
919 appearance,
920 appearance_observers: SubscriberSet::new(),
921 active,
922 hovered,
923 needs_present,
924 last_input_timestamp,
925 refreshing: false,
926 activation_observers: SubscriberSet::new(),
927 focus: None,
928 focus_enabled: true,
929 pending_input: None,
930 pending_modifier: ModifierState::default(),
931 pending_input_observers: SubscriberSet::new(),
932 prompt: None,
933 })
934 }
935
936 pub(crate) fn new_focus_listener(
937 &self,
938 value: AnyWindowFocusListener,
939 ) -> (Subscription, impl FnOnce()) {
940 self.focus_listeners.insert((), value)
941 }
942}
943
944#[derive(Clone, Debug, Default, PartialEq, Eq)]
945pub(crate) struct DispatchEventResult {
946 pub propagate: bool,
947 pub default_prevented: bool,
948}
949
950/// Indicates which region of the window is visible. Content falling outside of this mask will not be
951/// rendered. Currently, only rectangular content masks are supported, but we give the mask its own type
952/// to leave room to support more complex shapes in the future.
953#[derive(Clone, Debug, Default, PartialEq, Eq)]
954#[repr(C)]
955pub struct ContentMask<P: Clone + Default + Debug> {
956 /// The bounds
957 pub bounds: Bounds<P>,
958}
959
960impl ContentMask<Pixels> {
961 /// Scale the content mask's pixel units by the given scaling factor.
962 pub fn scale(&self, factor: f32) -> ContentMask<ScaledPixels> {
963 ContentMask {
964 bounds: self.bounds.scale(factor),
965 }
966 }
967
968 /// Intersect the content mask with the given content mask.
969 pub fn intersect(&self, other: &Self) -> Self {
970 let bounds = self.bounds.intersect(&other.bounds);
971 ContentMask { bounds }
972 }
973}
974
975impl Window {
976 fn mark_view_dirty(&mut self, view_id: EntityId) {
977 // Mark ancestor views as dirty. If already in the `dirty_views` set, then all its ancestors
978 // should already be dirty.
979 for view_id in self
980 .rendered_frame
981 .dispatch_tree
982 .view_path(view_id)
983 .into_iter()
984 .rev()
985 {
986 if !self.dirty_views.insert(view_id) {
987 break;
988 }
989 }
990 }
991
992 /// Registers a callback to be invoked when the window appearance changes.
993 pub fn observe_window_appearance(
994 &self,
995 mut callback: impl FnMut(&mut Window, &mut App) + 'static,
996 ) -> Subscription {
997 let (subscription, activate) = self.appearance_observers.insert(
998 (),
999 Box::new(move |window, cx| {
1000 callback(window, cx);
1001 true
1002 }),
1003 );
1004 activate();
1005 subscription
1006 }
1007
1008 pub fn replace_root<E>(
1009 &mut self,
1010 cx: &mut App,
1011 build_view: impl FnOnce(&mut Window, &mut Context<'_, E>) -> E,
1012 ) -> Entity<E>
1013 where
1014 E: 'static + Render,
1015 {
1016 let view = cx.new(|cx| build_view(self, cx));
1017 self.root = Some(view.clone().into());
1018 self.refresh();
1019 view
1020 }
1021
1022 pub fn root<E>(&self) -> Option<Option<Entity<E>>>
1023 where
1024 E: 'static + Render,
1025 {
1026 self.root
1027 .as_ref()
1028 .map(|view| view.clone().downcast::<E>().ok())
1029 }
1030
1031 /// Obtain a handle to the window that belongs to this context.
1032 pub fn window_handle(&self) -> AnyWindowHandle {
1033 self.handle
1034 }
1035
1036 /// Mark the window as dirty, scheduling it to be redrawn on the next frame.
1037 pub fn refresh(&mut self) {
1038 if self.invalidator.not_painting() {
1039 self.refreshing = true;
1040 self.invalidator.set_dirty(true);
1041 }
1042 }
1043
1044 /// Close this window.
1045 pub fn remove_window(&mut self) {
1046 self.removed = true;
1047 }
1048
1049 /// Obtain the currently focused [`FocusHandle`]. If no elements are focused, returns `None`.
1050 pub fn focused(&self, cx: &App) -> Option<FocusHandle> {
1051 self.focus
1052 .and_then(|id| FocusHandle::for_id(id, &cx.focus_handles))
1053 }
1054
1055 /// Move focus to the element associated with the given [`FocusHandle`].
1056 pub fn focus(&mut self, handle: &FocusHandle) {
1057 if !self.focus_enabled || self.focus == Some(handle.id) {
1058 return;
1059 }
1060
1061 self.focus = Some(handle.id);
1062 self.clear_pending_keystrokes();
1063 self.refresh();
1064 }
1065
1066 /// Remove focus from all elements within this context's window.
1067 pub fn blur(&mut self) {
1068 if !self.focus_enabled {
1069 return;
1070 }
1071
1072 self.focus = None;
1073 self.refresh();
1074 }
1075
1076 /// Blur the window and don't allow anything in it to be focused again.
1077 pub fn disable_focus(&mut self) {
1078 self.blur();
1079 self.focus_enabled = false;
1080 }
1081
1082 /// Accessor for the text system.
1083 pub fn text_system(&self) -> &Arc<WindowTextSystem> {
1084 &self.text_system
1085 }
1086
1087 /// The current text style. Which is composed of all the style refinements provided to `with_text_style`.
1088 pub fn text_style(&self) -> TextStyle {
1089 let mut style = TextStyle::default();
1090 for refinement in &self.text_style_stack {
1091 style.refine(refinement);
1092 }
1093 style
1094 }
1095
1096 /// Check if the platform window is maximized
1097 /// On some platforms (namely Windows) this is different than the bounds being the size of the display
1098 pub fn is_maximized(&self) -> bool {
1099 self.platform_window.is_maximized()
1100 }
1101
1102 /// request a certain window decoration (Wayland)
1103 pub fn request_decorations(&self, decorations: WindowDecorations) {
1104 self.platform_window.request_decorations(decorations);
1105 }
1106
1107 /// Start a window resize operation (Wayland)
1108 pub fn start_window_resize(&self, edge: ResizeEdge) {
1109 self.platform_window.start_window_resize(edge);
1110 }
1111
1112 /// Return the `WindowBounds` to indicate that how a window should be opened
1113 /// after it has been closed
1114 pub fn window_bounds(&self) -> WindowBounds {
1115 self.platform_window.window_bounds()
1116 }
1117
1118 /// Return the `WindowBounds` excluding insets (Wayland and X11)
1119 pub fn inner_window_bounds(&self) -> WindowBounds {
1120 self.platform_window.inner_window_bounds()
1121 }
1122
1123 /// Dispatch the given action on the currently focused element.
1124 pub fn dispatch_action(&mut self, action: Box<dyn Action>, cx: &mut App) {
1125 let focus_handle = self.focused(cx);
1126
1127 let window = self.handle;
1128 cx.defer(move |cx| {
1129 window
1130 .update(cx, |_, window, cx| {
1131 let node_id = focus_handle
1132 .and_then(|handle| {
1133 window
1134 .rendered_frame
1135 .dispatch_tree
1136 .focusable_node_id(handle.id)
1137 })
1138 .unwrap_or_else(|| window.rendered_frame.dispatch_tree.root_node_id());
1139
1140 window.dispatch_action_on_node(node_id, action.as_ref(), cx);
1141 })
1142 .log_err();
1143 })
1144 }
1145
1146 pub(crate) fn dispatch_keystroke_observers(
1147 &mut self,
1148 event: &dyn Any,
1149 action: Option<Box<dyn Action>>,
1150 cx: &mut App,
1151 ) {
1152 let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() else {
1153 return;
1154 };
1155
1156 cx.keystroke_observers.clone().retain(&(), move |callback| {
1157 (callback)(
1158 &KeystrokeEvent {
1159 keystroke: key_down_event.keystroke.clone(),
1160 action: action.as_ref().map(|action| action.boxed_clone()),
1161 },
1162 self,
1163 cx,
1164 )
1165 });
1166 }
1167
1168 /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
1169 /// that are currently on the stack to be returned to the app.
1170 pub fn defer(&self, cx: &mut App, f: impl FnOnce(&mut Window, &mut App) + 'static) {
1171 let handle = self.handle;
1172 cx.defer(move |cx| {
1173 handle.update(cx, |_, window, cx| f(window, cx)).ok();
1174 });
1175 }
1176
1177 /// Subscribe to events emitted by a entity.
1178 /// The entity to which you're subscribing must implement the [`EventEmitter`] trait.
1179 /// The callback will be invoked a handle to the emitting entity, the event, and a window context for the current window.
1180 pub fn observe<T: 'static>(
1181 &mut self,
1182 observed: &Entity<T>,
1183 cx: &mut App,
1184 mut on_notify: impl FnMut(Entity<T>, &mut Window, &mut App) + 'static,
1185 ) -> Subscription {
1186 let entity_id = observed.entity_id();
1187 let observed = observed.downgrade();
1188 let window_handle = self.handle;
1189 cx.new_observer(
1190 entity_id,
1191 Box::new(move |cx| {
1192 window_handle
1193 .update(cx, |_, window, cx| {
1194 if let Some(handle) = observed.upgrade() {
1195 on_notify(handle, window, cx);
1196 true
1197 } else {
1198 false
1199 }
1200 })
1201 .unwrap_or(false)
1202 }),
1203 )
1204 }
1205
1206 /// Subscribe to events emitted by a entity.
1207 /// The entity to which you're subscribing must implement the [`EventEmitter`] trait.
1208 /// The callback will be invoked a handle to the emitting entity, the event, and a window context for the current window.
1209 pub fn subscribe<Emitter, Evt>(
1210 &mut self,
1211 entity: &Entity<Emitter>,
1212 cx: &mut App,
1213 mut on_event: impl FnMut(Entity<Emitter>, &Evt, &mut Window, &mut App) + 'static,
1214 ) -> Subscription
1215 where
1216 Emitter: EventEmitter<Evt>,
1217 Evt: 'static,
1218 {
1219 let entity_id = entity.entity_id();
1220 let entity = entity.downgrade();
1221 let window_handle = self.handle;
1222 cx.new_subscription(
1223 entity_id,
1224 (
1225 TypeId::of::<Evt>(),
1226 Box::new(move |event, cx| {
1227 window_handle
1228 .update(cx, |_, window, cx| {
1229 if let Some(handle) = Entity::<Emitter>::upgrade_from(&entity) {
1230 let event = event.downcast_ref().expect("invalid event type");
1231 on_event(handle, event, window, cx);
1232 true
1233 } else {
1234 false
1235 }
1236 })
1237 .unwrap_or(false)
1238 }),
1239 ),
1240 )
1241 }
1242
1243 /// Register a callback to be invoked when the given `Entity` is released.
1244 pub fn observe_release<T>(
1245 &self,
1246 entity: &Entity<T>,
1247 cx: &mut App,
1248 mut on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,
1249 ) -> Subscription
1250 where
1251 T: 'static,
1252 {
1253 let entity_id = entity.entity_id();
1254 let window_handle = self.handle;
1255 let (subscription, activate) = cx.release_listeners.insert(
1256 entity_id,
1257 Box::new(move |entity, cx| {
1258 let entity = entity.downcast_mut().expect("invalid entity type");
1259 let _ = window_handle.update(cx, |_, window, cx| on_release(entity, window, cx));
1260 }),
1261 );
1262 activate();
1263 subscription
1264 }
1265
1266 /// Creates an [`AsyncWindowContext`], which has a static lifetime and can be held across
1267 /// await points in async code.
1268 pub fn to_async(&self, cx: &App) -> AsyncWindowContext {
1269 AsyncWindowContext::new_context(cx.to_async(), self.handle)
1270 }
1271
1272 /// Schedule the given closure to be run directly after the current frame is rendered.
1273 pub fn on_next_frame(&self, callback: impl FnOnce(&mut Window, &mut App) + 'static) {
1274 RefCell::borrow_mut(&self.next_frame_callbacks).push(Box::new(callback));
1275 }
1276
1277 /// Schedule a frame to be drawn on the next animation frame.
1278 ///
1279 /// This is useful for elements that need to animate continuously, such as a video player or an animated GIF.
1280 /// It will cause the window to redraw on the next frame, even if no other changes have occurred.
1281 ///
1282 /// If called from within a view, it will notify that view on the next frame. Otherwise, it will refresh the entire window.
1283 pub fn request_animation_frame(&self) {
1284 let entity = self.current_view();
1285 self.on_next_frame(move |_, cx| cx.notify(entity));
1286 }
1287
1288 /// Spawn the future returned by the given closure on the application thread pool.
1289 /// The closure is provided a handle to the current window and an `AsyncWindowContext` for
1290 /// use within your future.
1291 #[track_caller]
1292 pub fn spawn<Fut, R>(&self, cx: &App, f: impl FnOnce(AsyncWindowContext) -> Fut) -> Task<R>
1293 where
1294 R: 'static,
1295 Fut: Future<Output = R> + 'static,
1296 {
1297 cx.spawn(|app| f(AsyncWindowContext::new_context(app, self.handle)))
1298 }
1299
1300 fn bounds_changed(&mut self, cx: &mut App) {
1301 self.scale_factor = self.platform_window.scale_factor();
1302 self.viewport_size = self.platform_window.content_size();
1303 self.display_id = self.platform_window.display().map(|display| display.id());
1304
1305 self.refresh();
1306
1307 self.bounds_observers
1308 .clone()
1309 .retain(&(), |callback| callback(self, cx));
1310 }
1311
1312 /// Returns the bounds of the current window in the global coordinate space, which could span across multiple displays.
1313 pub fn bounds(&self) -> Bounds<Pixels> {
1314 self.platform_window.bounds()
1315 }
1316
1317 /// Returns whether or not the window is currently fullscreen
1318 pub fn is_fullscreen(&self) -> bool {
1319 self.platform_window.is_fullscreen()
1320 }
1321
1322 pub(crate) fn appearance_changed(&mut self, cx: &mut App) {
1323 self.appearance = self.platform_window.appearance();
1324
1325 self.appearance_observers
1326 .clone()
1327 .retain(&(), |callback| callback(self, cx));
1328 }
1329
1330 /// Returns the appearance of the current window.
1331 pub fn appearance(&self) -> WindowAppearance {
1332 self.appearance
1333 }
1334
1335 /// Returns the size of the drawable area within the window.
1336 pub fn viewport_size(&self) -> Size<Pixels> {
1337 self.viewport_size
1338 }
1339
1340 /// Returns whether this window is focused by the operating system (receiving key events).
1341 pub fn is_window_active(&self) -> bool {
1342 self.active.get()
1343 }
1344
1345 /// Returns whether this window is considered to be the window
1346 /// that currently owns the mouse cursor.
1347 /// On mac, this is equivalent to `is_window_active`.
1348 pub fn is_window_hovered(&self) -> bool {
1349 if cfg!(any(
1350 target_os = "windows",
1351 target_os = "linux",
1352 target_os = "freebsd"
1353 )) {
1354 self.hovered.get()
1355 } else {
1356 self.is_window_active()
1357 }
1358 }
1359
1360 /// Toggle zoom on the window.
1361 pub fn zoom_window(&self) {
1362 self.platform_window.zoom();
1363 }
1364
1365 /// Opens the native title bar context menu, useful when implementing client side decorations (Wayland and X11)
1366 pub fn show_window_menu(&self, position: Point<Pixels>) {
1367 self.platform_window.show_window_menu(position)
1368 }
1369
1370 /// Tells the compositor to take control of window movement (Wayland and X11)
1371 ///
1372 /// Events may not be received during a move operation.
1373 pub fn start_window_move(&self) {
1374 self.platform_window.start_window_move()
1375 }
1376
1377 /// When using client side decorations, set this to the width of the invisible decorations (Wayland and X11)
1378 pub fn set_client_inset(&self, inset: Pixels) {
1379 self.platform_window.set_client_inset(inset);
1380 }
1381
1382 /// Returns whether the title bar window controls need to be rendered by the application (Wayland and X11)
1383 pub fn window_decorations(&self) -> Decorations {
1384 self.platform_window.window_decorations()
1385 }
1386
1387 /// Returns which window controls are currently visible (Wayland)
1388 pub fn window_controls(&self) -> WindowControls {
1389 self.platform_window.window_controls()
1390 }
1391
1392 /// Updates the window's title at the platform level.
1393 pub fn set_window_title(&mut self, title: &str) {
1394 self.platform_window.set_title(title);
1395 }
1396
1397 /// Sets the application identifier.
1398 pub fn set_app_id(&mut self, app_id: &str) {
1399 self.platform_window.set_app_id(app_id);
1400 }
1401
1402 /// Sets the window background appearance.
1403 pub fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance) {
1404 self.platform_window
1405 .set_background_appearance(background_appearance);
1406 }
1407
1408 /// Mark the window as dirty at the platform level.
1409 pub fn set_window_edited(&mut self, edited: bool) {
1410 self.platform_window.set_edited(edited);
1411 }
1412
1413 /// Determine the display on which the window is visible.
1414 pub fn display(&self, cx: &App) -> Option<Rc<dyn PlatformDisplay>> {
1415 cx.platform
1416 .displays()
1417 .into_iter()
1418 .find(|display| Some(display.id()) == self.display_id)
1419 }
1420
1421 /// Show the platform character palette.
1422 pub fn show_character_palette(&self) {
1423 self.platform_window.show_character_palette();
1424 }
1425
1426 /// The scale factor of the display associated with the window. For example, it could
1427 /// return 2.0 for a "retina" display, indicating that each logical pixel should actually
1428 /// be rendered as two pixels on screen.
1429 pub fn scale_factor(&self) -> f32 {
1430 self.scale_factor
1431 }
1432
1433 /// The size of an em for the base font of the application. Adjusting this value allows the
1434 /// UI to scale, just like zooming a web page.
1435 pub fn rem_size(&self) -> Pixels {
1436 self.rem_size_override_stack
1437 .last()
1438 .copied()
1439 .unwrap_or(self.rem_size)
1440 }
1441
1442 /// Sets the size of an em for the base font of the application. Adjusting this value allows the
1443 /// UI to scale, just like zooming a web page.
1444 pub fn set_rem_size(&mut self, rem_size: impl Into<Pixels>) {
1445 self.rem_size = rem_size.into();
1446 }
1447
1448 /// Executes the provided function with the specified rem size.
1449 ///
1450 /// This method must only be called as part of element drawing.
1451 pub fn with_rem_size<F, R>(&mut self, rem_size: Option<impl Into<Pixels>>, f: F) -> R
1452 where
1453 F: FnOnce(&mut Self) -> R,
1454 {
1455 self.invalidator.debug_assert_paint_or_prepaint();
1456
1457 if let Some(rem_size) = rem_size {
1458 self.rem_size_override_stack.push(rem_size.into());
1459 let result = f(self);
1460 self.rem_size_override_stack.pop();
1461 result
1462 } else {
1463 f(self)
1464 }
1465 }
1466
1467 /// The line height associated with the current text style.
1468 pub fn line_height(&self) -> Pixels {
1469 self.text_style().line_height_in_pixels(self.rem_size())
1470 }
1471
1472 /// Call to prevent the default action of an event. Currently only used to prevent
1473 /// parent elements from becoming focused on mouse down.
1474 pub fn prevent_default(&mut self) {
1475 self.default_prevented = true;
1476 }
1477
1478 /// Obtain whether default has been prevented for the event currently being dispatched.
1479 pub fn default_prevented(&self) -> bool {
1480 self.default_prevented
1481 }
1482
1483 /// Determine whether the given action is available along the dispatch path to the currently focused element.
1484 pub fn is_action_available(&self, action: &dyn Action, cx: &mut App) -> bool {
1485 let target = self
1486 .focused(cx)
1487 .and_then(|focused_handle| {
1488 self.rendered_frame
1489 .dispatch_tree
1490 .focusable_node_id(focused_handle.id)
1491 })
1492 .unwrap_or_else(|| self.rendered_frame.dispatch_tree.root_node_id());
1493 self.rendered_frame
1494 .dispatch_tree
1495 .is_action_available(action, target)
1496 }
1497
1498 /// The position of the mouse relative to the window.
1499 pub fn mouse_position(&self) -> Point<Pixels> {
1500 self.mouse_position
1501 }
1502
1503 /// The current state of the keyboard's modifiers
1504 pub fn modifiers(&self) -> Modifiers {
1505 self.modifiers
1506 }
1507
1508 fn complete_frame(&self) {
1509 self.platform_window.completed_frame();
1510 }
1511
1512 /// Produces a new frame and assigns it to `rendered_frame`. To actually show
1513 /// the contents of the new [Scene], use [present].
1514 #[profiling::function]
1515 pub fn draw(&mut self, cx: &mut App) {
1516 self.invalidate_entities();
1517 cx.entities.clear_accessed();
1518 debug_assert!(self.rendered_entity_stack.is_empty());
1519 self.invalidator.set_dirty(false);
1520 self.requested_autoscroll = None;
1521
1522 // Restore the previously-used input handler.
1523 if let Some(input_handler) = self.platform_window.take_input_handler() {
1524 self.rendered_frame.input_handlers.push(Some(input_handler));
1525 }
1526 self.draw_roots(cx);
1527 self.dirty_views.clear();
1528 self.next_frame.window_active = self.active.get();
1529
1530 // Register requested input handler with the platform window.
1531 if let Some(input_handler) = self.next_frame.input_handlers.pop() {
1532 self.platform_window
1533 .set_input_handler(input_handler.unwrap());
1534 }
1535
1536 self.layout_engine.as_mut().unwrap().clear();
1537 self.text_system().finish_frame();
1538 self.next_frame.finish(&mut self.rendered_frame);
1539 ELEMENT_ARENA.with_borrow_mut(|element_arena| {
1540 let percentage = (element_arena.len() as f32 / element_arena.capacity() as f32) * 100.;
1541 if percentage >= 80. {
1542 log::warn!("elevated element arena occupation: {}.", percentage);
1543 }
1544 element_arena.clear();
1545 });
1546
1547 self.invalidator.set_phase(DrawPhase::Focus);
1548 let previous_focus_path = self.rendered_frame.focus_path();
1549 let previous_window_active = self.rendered_frame.window_active;
1550 mem::swap(&mut self.rendered_frame, &mut self.next_frame);
1551 self.next_frame.clear();
1552 let current_focus_path = self.rendered_frame.focus_path();
1553 let current_window_active = self.rendered_frame.window_active;
1554
1555 if previous_focus_path != current_focus_path
1556 || previous_window_active != current_window_active
1557 {
1558 if !previous_focus_path.is_empty() && current_focus_path.is_empty() {
1559 self.focus_lost_listeners
1560 .clone()
1561 .retain(&(), |listener| listener(self, cx));
1562 }
1563
1564 let event = WindowFocusEvent {
1565 previous_focus_path: if previous_window_active {
1566 previous_focus_path
1567 } else {
1568 Default::default()
1569 },
1570 current_focus_path: if current_window_active {
1571 current_focus_path
1572 } else {
1573 Default::default()
1574 },
1575 };
1576 self.focus_listeners
1577 .clone()
1578 .retain(&(), |listener| listener(&event, self, cx));
1579 }
1580
1581 debug_assert!(self.rendered_entity_stack.is_empty());
1582 self.record_entities_accessed(cx);
1583 self.reset_cursor_style(cx);
1584 self.refreshing = false;
1585 self.invalidator.set_phase(DrawPhase::None);
1586 self.needs_present.set(true);
1587 }
1588
1589 fn record_entities_accessed(&mut self, cx: &mut App) {
1590 let mut entities_ref = cx.entities.accessed_entities.borrow_mut();
1591 let mut entities = mem::take(entities_ref.deref_mut());
1592 drop(entities_ref);
1593 let handle = self.handle;
1594 cx.record_entities_accessed(
1595 handle,
1596 // Try moving window invalidator into the Window
1597 self.invalidator.clone(),
1598 &entities,
1599 );
1600 let mut entities_ref = cx.entities.accessed_entities.borrow_mut();
1601 mem::swap(&mut entities, entities_ref.deref_mut());
1602 }
1603
1604 fn invalidate_entities(&mut self) {
1605 let mut views = self.invalidator.take_views();
1606 for entity in views.drain() {
1607 self.mark_view_dirty(entity);
1608 }
1609 self.invalidator.replace_views(views);
1610 }
1611
1612 #[profiling::function]
1613 fn present(&self) {
1614 self.platform_window.draw(&self.rendered_frame.scene);
1615 self.needs_present.set(false);
1616 profiling::finish_frame!();
1617 }
1618
1619 fn draw_roots(&mut self, cx: &mut App) {
1620 self.invalidator.set_phase(DrawPhase::Prepaint);
1621 self.tooltip_bounds.take();
1622
1623 // Layout all root elements.
1624 let mut root_element = self.root.as_ref().unwrap().clone().into_any();
1625 root_element.prepaint_as_root(Point::default(), self.viewport_size.into(), self, cx);
1626
1627 let mut sorted_deferred_draws =
1628 (0..self.next_frame.deferred_draws.len()).collect::<SmallVec<[_; 8]>>();
1629 sorted_deferred_draws.sort_by_key(|ix| self.next_frame.deferred_draws[*ix].priority);
1630 self.prepaint_deferred_draws(&sorted_deferred_draws, cx);
1631
1632 let mut prompt_element = None;
1633 let mut active_drag_element = None;
1634 let mut tooltip_element = None;
1635 if let Some(prompt) = self.prompt.take() {
1636 let mut element = prompt.view.any_view().into_any();
1637 element.prepaint_as_root(Point::default(), self.viewport_size.into(), self, cx);
1638 prompt_element = Some(element);
1639 self.prompt = Some(prompt);
1640 } else if let Some(active_drag) = cx.active_drag.take() {
1641 let mut element = active_drag.view.clone().into_any();
1642 let offset = self.mouse_position() - active_drag.cursor_offset;
1643 element.prepaint_as_root(offset, AvailableSpace::min_size(), self, cx);
1644 active_drag_element = Some(element);
1645 cx.active_drag = Some(active_drag);
1646 } else {
1647 tooltip_element = self.prepaint_tooltip(cx);
1648 }
1649
1650 self.mouse_hit_test = self.next_frame.hit_test(self.mouse_position);
1651
1652 // Now actually paint the elements.
1653 self.invalidator.set_phase(DrawPhase::Paint);
1654 root_element.paint(self, cx);
1655
1656 self.paint_deferred_draws(&sorted_deferred_draws, cx);
1657
1658 if let Some(mut prompt_element) = prompt_element {
1659 prompt_element.paint(self, cx);
1660 } else if let Some(mut drag_element) = active_drag_element {
1661 drag_element.paint(self, cx);
1662 } else if let Some(mut tooltip_element) = tooltip_element {
1663 tooltip_element.paint(self, cx);
1664 }
1665 }
1666
1667 fn prepaint_tooltip(&mut self, cx: &mut App) -> Option<AnyElement> {
1668 // Use indexing instead of iteration to avoid borrowing self for the duration of the loop.
1669 for tooltip_request_index in (0..self.next_frame.tooltip_requests.len()).rev() {
1670 let Some(Some(tooltip_request)) = self
1671 .next_frame
1672 .tooltip_requests
1673 .get(tooltip_request_index)
1674 .cloned()
1675 else {
1676 log::error!("Unexpectedly absent TooltipRequest");
1677 continue;
1678 };
1679 let mut element = tooltip_request.tooltip.view.clone().into_any();
1680 let mouse_position = tooltip_request.tooltip.mouse_position;
1681 let tooltip_size = element.layout_as_root(AvailableSpace::min_size(), self, cx);
1682
1683 let mut tooltip_bounds =
1684 Bounds::new(mouse_position + point(px(1.), px(1.)), tooltip_size);
1685 let window_bounds = Bounds {
1686 origin: Point::default(),
1687 size: self.viewport_size(),
1688 };
1689
1690 if tooltip_bounds.right() > window_bounds.right() {
1691 let new_x = mouse_position.x - tooltip_bounds.size.width - px(1.);
1692 if new_x >= Pixels::ZERO {
1693 tooltip_bounds.origin.x = new_x;
1694 } else {
1695 tooltip_bounds.origin.x = cmp::max(
1696 Pixels::ZERO,
1697 tooltip_bounds.origin.x - tooltip_bounds.right() - window_bounds.right(),
1698 );
1699 }
1700 }
1701
1702 if tooltip_bounds.bottom() > window_bounds.bottom() {
1703 let new_y = mouse_position.y - tooltip_bounds.size.height - px(1.);
1704 if new_y >= Pixels::ZERO {
1705 tooltip_bounds.origin.y = new_y;
1706 } else {
1707 tooltip_bounds.origin.y = cmp::max(
1708 Pixels::ZERO,
1709 tooltip_bounds.origin.y - tooltip_bounds.bottom() - window_bounds.bottom(),
1710 );
1711 }
1712 }
1713
1714 // It's possible for an element to have an active tooltip while not being painted (e.g.
1715 // via the `visible_on_hover` method). Since mouse listeners are not active in this
1716 // case, instead update the tooltip's visibility here.
1717 let is_visible =
1718 (tooltip_request.tooltip.check_visible_and_update)(tooltip_bounds, self, cx);
1719 if !is_visible {
1720 continue;
1721 }
1722
1723 self.with_absolute_element_offset(tooltip_bounds.origin, |window| {
1724 element.prepaint(window, cx)
1725 });
1726
1727 self.tooltip_bounds = Some(TooltipBounds {
1728 id: tooltip_request.id,
1729 bounds: tooltip_bounds,
1730 });
1731 return Some(element);
1732 }
1733 None
1734 }
1735
1736 fn prepaint_deferred_draws(&mut self, deferred_draw_indices: &[usize], cx: &mut App) {
1737 assert_eq!(self.element_id_stack.len(), 0);
1738
1739 let mut deferred_draws = mem::take(&mut self.next_frame.deferred_draws);
1740 for deferred_draw_ix in deferred_draw_indices {
1741 let deferred_draw = &mut deferred_draws[*deferred_draw_ix];
1742 self.element_id_stack
1743 .clone_from(&deferred_draw.element_id_stack);
1744 self.text_style_stack
1745 .clone_from(&deferred_draw.text_style_stack);
1746 self.next_frame
1747 .dispatch_tree
1748 .set_active_node(deferred_draw.parent_node);
1749
1750 let prepaint_start = self.prepaint_index();
1751 if let Some(element) = deferred_draw.element.as_mut() {
1752 self.with_absolute_element_offset(deferred_draw.absolute_offset, |window| {
1753 element.prepaint(window, cx)
1754 });
1755 } else {
1756 self.reuse_prepaint(deferred_draw.prepaint_range.clone());
1757 }
1758 let prepaint_end = self.prepaint_index();
1759 deferred_draw.prepaint_range = prepaint_start..prepaint_end;
1760 }
1761 assert_eq!(
1762 self.next_frame.deferred_draws.len(),
1763 0,
1764 "cannot call defer_draw during deferred drawing"
1765 );
1766 self.next_frame.deferred_draws = deferred_draws;
1767 self.element_id_stack.clear();
1768 self.text_style_stack.clear();
1769 }
1770
1771 fn paint_deferred_draws(&mut self, deferred_draw_indices: &[usize], cx: &mut App) {
1772 assert_eq!(self.element_id_stack.len(), 0);
1773
1774 let mut deferred_draws = mem::take(&mut self.next_frame.deferred_draws);
1775 for deferred_draw_ix in deferred_draw_indices {
1776 let mut deferred_draw = &mut deferred_draws[*deferred_draw_ix];
1777 self.element_id_stack
1778 .clone_from(&deferred_draw.element_id_stack);
1779 self.next_frame
1780 .dispatch_tree
1781 .set_active_node(deferred_draw.parent_node);
1782
1783 let paint_start = self.paint_index();
1784 if let Some(element) = deferred_draw.element.as_mut() {
1785 element.paint(self, cx);
1786 } else {
1787 self.reuse_paint(deferred_draw.paint_range.clone());
1788 }
1789 let paint_end = self.paint_index();
1790 deferred_draw.paint_range = paint_start..paint_end;
1791 }
1792 self.next_frame.deferred_draws = deferred_draws;
1793 self.element_id_stack.clear();
1794 }
1795
1796 pub(crate) fn prepaint_index(&self) -> PrepaintStateIndex {
1797 PrepaintStateIndex {
1798 hitboxes_index: self.next_frame.hitboxes.len(),
1799 tooltips_index: self.next_frame.tooltip_requests.len(),
1800 deferred_draws_index: self.next_frame.deferred_draws.len(),
1801 dispatch_tree_index: self.next_frame.dispatch_tree.len(),
1802 accessed_element_states_index: self.next_frame.accessed_element_states.len(),
1803 line_layout_index: self.text_system.layout_index(),
1804 }
1805 }
1806
1807 pub(crate) fn reuse_prepaint(&mut self, range: Range<PrepaintStateIndex>) {
1808 self.next_frame.hitboxes.extend(
1809 self.rendered_frame.hitboxes[range.start.hitboxes_index..range.end.hitboxes_index]
1810 .iter()
1811 .cloned(),
1812 );
1813 self.next_frame.tooltip_requests.extend(
1814 self.rendered_frame.tooltip_requests
1815 [range.start.tooltips_index..range.end.tooltips_index]
1816 .iter_mut()
1817 .map(|request| request.take()),
1818 );
1819 self.next_frame.accessed_element_states.extend(
1820 self.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
1821 ..range.end.accessed_element_states_index]
1822 .iter()
1823 .map(|(id, type_id)| (GlobalElementId(id.0.clone()), *type_id)),
1824 );
1825 self.text_system
1826 .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
1827
1828 let reused_subtree = self.next_frame.dispatch_tree.reuse_subtree(
1829 range.start.dispatch_tree_index..range.end.dispatch_tree_index,
1830 &mut self.rendered_frame.dispatch_tree,
1831 self.focus,
1832 );
1833
1834 if reused_subtree.contains_focus() {
1835 self.next_frame.focus = self.focus;
1836 }
1837
1838 self.next_frame.deferred_draws.extend(
1839 self.rendered_frame.deferred_draws
1840 [range.start.deferred_draws_index..range.end.deferred_draws_index]
1841 .iter()
1842 .map(|deferred_draw| DeferredDraw {
1843 parent_node: reused_subtree.refresh_node_id(deferred_draw.parent_node),
1844 element_id_stack: deferred_draw.element_id_stack.clone(),
1845 text_style_stack: deferred_draw.text_style_stack.clone(),
1846 priority: deferred_draw.priority,
1847 element: None,
1848 absolute_offset: deferred_draw.absolute_offset,
1849 prepaint_range: deferred_draw.prepaint_range.clone(),
1850 paint_range: deferred_draw.paint_range.clone(),
1851 }),
1852 );
1853 }
1854
1855 pub(crate) fn paint_index(&self) -> PaintIndex {
1856 PaintIndex {
1857 scene_index: self.next_frame.scene.len(),
1858 mouse_listeners_index: self.next_frame.mouse_listeners.len(),
1859 input_handlers_index: self.next_frame.input_handlers.len(),
1860 cursor_styles_index: self.next_frame.cursor_styles.len(),
1861 accessed_element_states_index: self.next_frame.accessed_element_states.len(),
1862 line_layout_index: self.text_system.layout_index(),
1863 }
1864 }
1865
1866 pub(crate) fn reuse_paint(&mut self, range: Range<PaintIndex>) {
1867 self.next_frame.cursor_styles.extend(
1868 self.rendered_frame.cursor_styles
1869 [range.start.cursor_styles_index..range.end.cursor_styles_index]
1870 .iter()
1871 .cloned(),
1872 );
1873 self.next_frame.input_handlers.extend(
1874 self.rendered_frame.input_handlers
1875 [range.start.input_handlers_index..range.end.input_handlers_index]
1876 .iter_mut()
1877 .map(|handler| handler.take()),
1878 );
1879 self.next_frame.mouse_listeners.extend(
1880 self.rendered_frame.mouse_listeners
1881 [range.start.mouse_listeners_index..range.end.mouse_listeners_index]
1882 .iter_mut()
1883 .map(|listener| listener.take()),
1884 );
1885 self.next_frame.accessed_element_states.extend(
1886 self.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
1887 ..range.end.accessed_element_states_index]
1888 .iter()
1889 .map(|(id, type_id)| (GlobalElementId(id.0.clone()), *type_id)),
1890 );
1891
1892 self.text_system
1893 .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
1894 self.next_frame.scene.replay(
1895 range.start.scene_index..range.end.scene_index,
1896 &self.rendered_frame.scene,
1897 );
1898 }
1899
1900 /// Push a text style onto the stack, and call a function with that style active.
1901 /// Use [`Window::text_style`] to get the current, combined text style. This method
1902 /// should only be called as part of element drawing.
1903 pub fn with_text_style<F, R>(&mut self, style: Option<TextStyleRefinement>, f: F) -> R
1904 where
1905 F: FnOnce(&mut Self) -> R,
1906 {
1907 self.invalidator.debug_assert_paint_or_prepaint();
1908 if let Some(style) = style {
1909 self.text_style_stack.push(style);
1910 let result = f(self);
1911 self.text_style_stack.pop();
1912 result
1913 } else {
1914 f(self)
1915 }
1916 }
1917
1918 /// Updates the cursor style at the platform level. This method should only be called
1919 /// during the prepaint phase of element drawing.
1920 pub fn set_cursor_style(&mut self, style: CursorStyle, hitbox: &Hitbox) {
1921 self.invalidator.debug_assert_paint();
1922 self.next_frame.cursor_styles.push(CursorStyleRequest {
1923 hitbox_id: hitbox.id,
1924 style,
1925 });
1926 }
1927
1928 /// Sets a tooltip to be rendered for the upcoming frame. This method should only be called
1929 /// during the paint phase of element drawing.
1930 pub fn set_tooltip(&mut self, tooltip: AnyTooltip) -> TooltipId {
1931 self.invalidator.debug_assert_prepaint();
1932 let id = TooltipId(post_inc(&mut self.next_tooltip_id.0));
1933 self.next_frame
1934 .tooltip_requests
1935 .push(Some(TooltipRequest { id, tooltip }));
1936 id
1937 }
1938
1939 /// Invoke the given function with the given content mask after intersecting it
1940 /// with the current mask. This method should only be called during element drawing.
1941 pub fn with_content_mask<R>(
1942 &mut self,
1943 mask: Option<ContentMask<Pixels>>,
1944 f: impl FnOnce(&mut Self) -> R,
1945 ) -> R {
1946 self.invalidator.debug_assert_paint_or_prepaint();
1947 if let Some(mask) = mask {
1948 let mask = mask.intersect(&self.content_mask());
1949 self.content_mask_stack.push(mask);
1950 let result = f(self);
1951 self.content_mask_stack.pop();
1952 result
1953 } else {
1954 f(self)
1955 }
1956 }
1957
1958 /// Updates the global element offset relative to the current offset. This is used to implement
1959 /// scrolling. This method should only be called during the prepaint phase of element drawing.
1960 pub fn with_element_offset<R>(
1961 &mut self,
1962 offset: Point<Pixels>,
1963 f: impl FnOnce(&mut Self) -> R,
1964 ) -> R {
1965 self.invalidator.debug_assert_prepaint();
1966
1967 if offset.is_zero() {
1968 return f(self);
1969 };
1970
1971 let abs_offset = self.element_offset() + offset;
1972 self.with_absolute_element_offset(abs_offset, f)
1973 }
1974
1975 /// Updates the global element offset based on the given offset. This is used to implement
1976 /// drag handles and other manual painting of elements. This method should only be called during
1977 /// the prepaint phase of element drawing.
1978 pub fn with_absolute_element_offset<R>(
1979 &mut self,
1980 offset: Point<Pixels>,
1981 f: impl FnOnce(&mut Self) -> R,
1982 ) -> R {
1983 self.invalidator.debug_assert_prepaint();
1984 self.element_offset_stack.push(offset);
1985 let result = f(self);
1986 self.element_offset_stack.pop();
1987 result
1988 }
1989
1990 pub(crate) fn with_element_opacity<R>(
1991 &mut self,
1992 opacity: Option<f32>,
1993 f: impl FnOnce(&mut Self) -> R,
1994 ) -> R {
1995 if opacity.is_none() {
1996 return f(self);
1997 }
1998
1999 self.invalidator.debug_assert_paint_or_prepaint();
2000 self.element_opacity = opacity;
2001 let result = f(self);
2002 self.element_opacity = None;
2003 result
2004 }
2005
2006 /// Perform prepaint on child elements in a "retryable" manner, so that any side effects
2007 /// of prepaints can be discarded before prepainting again. This is used to support autoscroll
2008 /// where we need to prepaint children to detect the autoscroll bounds, then adjust the
2009 /// element offset and prepaint again. See [`List`] for an example. This method should only be
2010 /// called during the prepaint phase of element drawing.
2011 pub fn transact<T, U>(&mut self, f: impl FnOnce(&mut Self) -> Result<T, U>) -> Result<T, U> {
2012 self.invalidator.debug_assert_prepaint();
2013 let index = self.prepaint_index();
2014 let result = f(self);
2015 if result.is_err() {
2016 self.next_frame.hitboxes.truncate(index.hitboxes_index);
2017 self.next_frame
2018 .tooltip_requests
2019 .truncate(index.tooltips_index);
2020 self.next_frame
2021 .deferred_draws
2022 .truncate(index.deferred_draws_index);
2023 self.next_frame
2024 .dispatch_tree
2025 .truncate(index.dispatch_tree_index);
2026 self.next_frame
2027 .accessed_element_states
2028 .truncate(index.accessed_element_states_index);
2029 self.text_system.truncate_layouts(index.line_layout_index);
2030 }
2031 result
2032 }
2033
2034 /// When you call this method during [`prepaint`], containing elements will attempt to
2035 /// scroll to cause the specified bounds to become visible. When they decide to autoscroll, they will call
2036 /// [`prepaint`] again with a new set of bounds. See [`List`] for an example of an element
2037 /// that supports this method being called on the elements it contains. This method should only be
2038 /// called during the prepaint phase of element drawing.
2039 pub fn request_autoscroll(&mut self, bounds: Bounds<Pixels>) {
2040 self.invalidator.debug_assert_prepaint();
2041 self.requested_autoscroll = Some(bounds);
2042 }
2043
2044 /// This method can be called from a containing element such as [`List`] to support the autoscroll behavior
2045 /// described in [`request_autoscroll`].
2046 pub fn take_autoscroll(&mut self) -> Option<Bounds<Pixels>> {
2047 self.invalidator.debug_assert_prepaint();
2048 self.requested_autoscroll.take()
2049 }
2050
2051 /// Asynchronously load an asset, if the asset hasn't finished loading this will return None.
2052 /// Your view will be re-drawn once the asset has finished loading.
2053 ///
2054 /// Note that the multiple calls to this method will only result in one `Asset::load` call at a
2055 /// time.
2056 pub fn use_asset<A: Asset>(&mut self, source: &A::Source, cx: &mut App) -> Option<A::Output> {
2057 let (task, is_first) = cx.fetch_asset::<A>(source);
2058 task.clone().now_or_never().or_else(|| {
2059 if is_first {
2060 let entity = self.current_view();
2061 self.spawn(cx, {
2062 let task = task.clone();
2063 |mut cx| async move {
2064 task.await;
2065
2066 cx.on_next_frame(move |_, cx| {
2067 cx.notify(entity);
2068 });
2069 }
2070 })
2071 .detach();
2072 }
2073
2074 None
2075 })
2076 }
2077 /// Obtain the current element offset. This method should only be called during the
2078 /// prepaint phase of element drawing.
2079 pub fn element_offset(&self) -> Point<Pixels> {
2080 self.invalidator.debug_assert_prepaint();
2081 self.element_offset_stack
2082 .last()
2083 .copied()
2084 .unwrap_or_default()
2085 }
2086
2087 /// Obtain the current element opacity. This method should only be called during the
2088 /// prepaint phase of element drawing.
2089 pub(crate) fn element_opacity(&self) -> f32 {
2090 self.invalidator.debug_assert_paint_or_prepaint();
2091 self.element_opacity.unwrap_or(1.0)
2092 }
2093
2094 /// Obtain the current content mask. This method should only be called during element drawing.
2095 pub fn content_mask(&self) -> ContentMask<Pixels> {
2096 self.invalidator.debug_assert_paint_or_prepaint();
2097 self.content_mask_stack
2098 .last()
2099 .cloned()
2100 .unwrap_or_else(|| ContentMask {
2101 bounds: Bounds {
2102 origin: Point::default(),
2103 size: self.viewport_size,
2104 },
2105 })
2106 }
2107
2108 /// Provide elements in the called function with a new namespace in which their identifiers must be unique.
2109 /// This can be used within a custom element to distinguish multiple sets of child elements.
2110 pub fn with_element_namespace<R>(
2111 &mut self,
2112 element_id: impl Into<ElementId>,
2113 f: impl FnOnce(&mut Self) -> R,
2114 ) -> R {
2115 self.element_id_stack.push(element_id.into());
2116 let result = f(self);
2117 self.element_id_stack.pop();
2118 result
2119 }
2120
2121 /// Updates or initializes state for an element with the given id that lives across multiple
2122 /// frames. If an element with this ID existed in the rendered frame, its state will be passed
2123 /// to the given closure. The state returned by the closure will be stored so it can be referenced
2124 /// when drawing the next frame. This method should only be called as part of element drawing.
2125 pub fn with_element_state<S, R>(
2126 &mut self,
2127 global_id: &GlobalElementId,
2128 f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
2129 ) -> R
2130 where
2131 S: 'static,
2132 {
2133 self.invalidator.debug_assert_paint_or_prepaint();
2134
2135 let key = (GlobalElementId(global_id.0.clone()), TypeId::of::<S>());
2136 self.next_frame
2137 .accessed_element_states
2138 .push((GlobalElementId(key.0.clone()), TypeId::of::<S>()));
2139
2140 if let Some(any) = self
2141 .next_frame
2142 .element_states
2143 .remove(&key)
2144 .or_else(|| self.rendered_frame.element_states.remove(&key))
2145 {
2146 let ElementStateBox {
2147 inner,
2148 #[cfg(debug_assertions)]
2149 type_name,
2150 } = any;
2151 // Using the extra inner option to avoid needing to reallocate a new box.
2152 let mut state_box = inner
2153 .downcast::<Option<S>>()
2154 .map_err(|_| {
2155 #[cfg(debug_assertions)]
2156 {
2157 anyhow::anyhow!(
2158 "invalid element state type for id, requested {:?}, actual: {:?}",
2159 std::any::type_name::<S>(),
2160 type_name
2161 )
2162 }
2163
2164 #[cfg(not(debug_assertions))]
2165 {
2166 anyhow::anyhow!(
2167 "invalid element state type for id, requested {:?}",
2168 std::any::type_name::<S>(),
2169 )
2170 }
2171 })
2172 .unwrap();
2173
2174 let state = state_box.take().expect(
2175 "reentrant call to with_element_state for the same state type and element id",
2176 );
2177 let (result, state) = f(Some(state), self);
2178 state_box.replace(state);
2179 self.next_frame.element_states.insert(
2180 key,
2181 ElementStateBox {
2182 inner: state_box,
2183 #[cfg(debug_assertions)]
2184 type_name,
2185 },
2186 );
2187 result
2188 } else {
2189 let (result, state) = f(None, self);
2190 self.next_frame.element_states.insert(
2191 key,
2192 ElementStateBox {
2193 inner: Box::new(Some(state)),
2194 #[cfg(debug_assertions)]
2195 type_name: std::any::type_name::<S>(),
2196 },
2197 );
2198 result
2199 }
2200 }
2201
2202 /// A variant of `with_element_state` that allows the element's id to be optional. This is a convenience
2203 /// method for elements where the element id may or may not be assigned. Prefer using `with_element_state`
2204 /// when the element is guaranteed to have an id.
2205 ///
2206 /// The first option means 'no ID provided'
2207 /// The second option means 'not yet initialized'
2208 pub fn with_optional_element_state<S, R>(
2209 &mut self,
2210 global_id: Option<&GlobalElementId>,
2211 f: impl FnOnce(Option<Option<S>>, &mut Self) -> (R, Option<S>),
2212 ) -> R
2213 where
2214 S: 'static,
2215 {
2216 self.invalidator.debug_assert_paint_or_prepaint();
2217
2218 if let Some(global_id) = global_id {
2219 self.with_element_state(global_id, |state, cx| {
2220 let (result, state) = f(Some(state), cx);
2221 let state =
2222 state.expect("you must return some state when you pass some element id");
2223 (result, state)
2224 })
2225 } else {
2226 let (result, state) = f(None, self);
2227 debug_assert!(
2228 state.is_none(),
2229 "you must not return an element state when passing None for the global id"
2230 );
2231 result
2232 }
2233 }
2234
2235 /// Defers the drawing of the given element, scheduling it to be painted on top of the currently-drawn tree
2236 /// at a later time. The `priority` parameter determines the drawing order relative to other deferred elements,
2237 /// with higher values being drawn on top.
2238 ///
2239 /// This method should only be called as part of the prepaint phase of element drawing.
2240 pub fn defer_draw(
2241 &mut self,
2242 element: AnyElement,
2243 absolute_offset: Point<Pixels>,
2244 priority: usize,
2245 ) {
2246 self.invalidator.debug_assert_prepaint();
2247 let parent_node = self.next_frame.dispatch_tree.active_node_id().unwrap();
2248 self.next_frame.deferred_draws.push(DeferredDraw {
2249 parent_node,
2250 element_id_stack: self.element_id_stack.clone(),
2251 text_style_stack: self.text_style_stack.clone(),
2252 priority,
2253 element: Some(element),
2254 absolute_offset,
2255 prepaint_range: PrepaintStateIndex::default()..PrepaintStateIndex::default(),
2256 paint_range: PaintIndex::default()..PaintIndex::default(),
2257 });
2258 }
2259
2260 /// Creates a new painting layer for the specified bounds. A "layer" is a batch
2261 /// of geometry that are non-overlapping and have the same draw order. This is typically used
2262 /// for performance reasons.
2263 ///
2264 /// This method should only be called as part of the paint phase of element drawing.
2265 pub fn paint_layer<R>(&mut self, bounds: Bounds<Pixels>, f: impl FnOnce(&mut Self) -> R) -> R {
2266 self.invalidator.debug_assert_paint();
2267
2268 let scale_factor = self.scale_factor();
2269 let content_mask = self.content_mask();
2270 let clipped_bounds = bounds.intersect(&content_mask.bounds);
2271 if !clipped_bounds.is_empty() {
2272 self.next_frame
2273 .scene
2274 .push_layer(clipped_bounds.scale(scale_factor));
2275 }
2276
2277 let result = f(self);
2278
2279 if !clipped_bounds.is_empty() {
2280 self.next_frame.scene.pop_layer();
2281 }
2282
2283 result
2284 }
2285
2286 /// Paint one or more drop shadows into the scene for the next frame at the current z-index.
2287 ///
2288 /// This method should only be called as part of the paint phase of element drawing.
2289 pub fn paint_shadows(
2290 &mut self,
2291 bounds: Bounds<Pixels>,
2292 corner_radii: Corners<Pixels>,
2293 shadows: &[BoxShadow],
2294 ) {
2295 self.invalidator.debug_assert_paint();
2296
2297 let scale_factor = self.scale_factor();
2298 let content_mask = self.content_mask();
2299 let opacity = self.element_opacity();
2300 for shadow in shadows {
2301 let shadow_bounds = (bounds + shadow.offset).dilate(shadow.spread_radius);
2302 self.next_frame.scene.insert_primitive(Shadow {
2303 order: 0,
2304 blur_radius: shadow.blur_radius.scale(scale_factor),
2305 bounds: shadow_bounds.scale(scale_factor),
2306 content_mask: content_mask.scale(scale_factor),
2307 corner_radii: corner_radii.scale(scale_factor),
2308 color: shadow.color.opacity(opacity),
2309 });
2310 }
2311 }
2312
2313 /// Paint one or more quads into the scene for the next frame at the current stacking context.
2314 /// Quads are colored rectangular regions with an optional background, border, and corner radius.
2315 /// see [`fill`](crate::fill), [`outline`](crate::outline), and [`quad`](crate::quad) to construct this type.
2316 ///
2317 /// This method should only be called as part of the paint phase of element drawing.
2318 pub fn paint_quad(&mut self, quad: PaintQuad) {
2319 self.invalidator.debug_assert_paint();
2320
2321 let scale_factor = self.scale_factor();
2322 let content_mask = self.content_mask();
2323 let opacity = self.element_opacity();
2324 self.next_frame.scene.insert_primitive(Quad {
2325 order: 0,
2326 pad: 0,
2327 bounds: quad.bounds.scale(scale_factor),
2328 content_mask: content_mask.scale(scale_factor),
2329 background: quad.background.opacity(opacity),
2330 border_color: quad.border_color.opacity(opacity),
2331 corner_radii: quad.corner_radii.scale(scale_factor),
2332 border_widths: quad.border_widths.scale(scale_factor),
2333 });
2334 }
2335
2336 /// Paint the given `Path` into the scene for the next frame at the current z-index.
2337 ///
2338 /// This method should only be called as part of the paint phase of element drawing.
2339 pub fn paint_path(&mut self, mut path: Path<Pixels>, color: impl Into<Background>) {
2340 self.invalidator.debug_assert_paint();
2341
2342 let scale_factor = self.scale_factor();
2343 let content_mask = self.content_mask();
2344 let opacity = self.element_opacity();
2345 path.content_mask = content_mask;
2346 let color: Background = color.into();
2347 path.color = color.opacity(opacity);
2348 self.next_frame
2349 .scene
2350 .insert_primitive(path.scale(scale_factor));
2351 }
2352
2353 /// Paint an underline into the scene for the next frame at the current z-index.
2354 ///
2355 /// This method should only be called as part of the paint phase of element drawing.
2356 pub fn paint_underline(
2357 &mut self,
2358 origin: Point<Pixels>,
2359 width: Pixels,
2360 style: &UnderlineStyle,
2361 ) {
2362 self.invalidator.debug_assert_paint();
2363
2364 let scale_factor = self.scale_factor();
2365 let height = if style.wavy {
2366 style.thickness * 3.
2367 } else {
2368 style.thickness
2369 };
2370 let bounds = Bounds {
2371 origin,
2372 size: size(width, height),
2373 };
2374 let content_mask = self.content_mask();
2375 let element_opacity = self.element_opacity();
2376
2377 self.next_frame.scene.insert_primitive(Underline {
2378 order: 0,
2379 pad: 0,
2380 bounds: bounds.scale(scale_factor),
2381 content_mask: content_mask.scale(scale_factor),
2382 color: style.color.unwrap_or_default().opacity(element_opacity),
2383 thickness: style.thickness.scale(scale_factor),
2384 wavy: style.wavy,
2385 });
2386 }
2387
2388 /// Paint a strikethrough into the scene for the next frame at the current z-index.
2389 ///
2390 /// This method should only be called as part of the paint phase of element drawing.
2391 pub fn paint_strikethrough(
2392 &mut self,
2393 origin: Point<Pixels>,
2394 width: Pixels,
2395 style: &StrikethroughStyle,
2396 ) {
2397 self.invalidator.debug_assert_paint();
2398
2399 let scale_factor = self.scale_factor();
2400 let height = style.thickness;
2401 let bounds = Bounds {
2402 origin,
2403 size: size(width, height),
2404 };
2405 let content_mask = self.content_mask();
2406 let opacity = self.element_opacity();
2407
2408 self.next_frame.scene.insert_primitive(Underline {
2409 order: 0,
2410 pad: 0,
2411 bounds: bounds.scale(scale_factor),
2412 content_mask: content_mask.scale(scale_factor),
2413 thickness: style.thickness.scale(scale_factor),
2414 color: style.color.unwrap_or_default().opacity(opacity),
2415 wavy: false,
2416 });
2417 }
2418
2419 /// Paints a monochrome (non-emoji) glyph into the scene for the next frame at the current z-index.
2420 ///
2421 /// The y component of the origin is the baseline of the glyph.
2422 /// You should generally prefer to use the [`ShapedLine::paint`](crate::ShapedLine::paint) or
2423 /// [`WrappedLine::paint`](crate::WrappedLine::paint) methods in the [`TextSystem`](crate::TextSystem).
2424 /// This method is only useful if you need to paint a single glyph that has already been shaped.
2425 ///
2426 /// This method should only be called as part of the paint phase of element drawing.
2427 pub fn paint_glyph(
2428 &mut self,
2429 origin: Point<Pixels>,
2430 font_id: FontId,
2431 glyph_id: GlyphId,
2432 font_size: Pixels,
2433 color: Hsla,
2434 ) -> Result<()> {
2435 self.invalidator.debug_assert_paint();
2436
2437 let element_opacity = self.element_opacity();
2438 let scale_factor = self.scale_factor();
2439 let glyph_origin = origin.scale(scale_factor);
2440 let subpixel_variant = Point {
2441 x: (glyph_origin.x.0.fract() * SUBPIXEL_VARIANTS as f32).floor() as u8,
2442 y: (glyph_origin.y.0.fract() * SUBPIXEL_VARIANTS as f32).floor() as u8,
2443 };
2444 let params = RenderGlyphParams {
2445 font_id,
2446 glyph_id,
2447 font_size,
2448 subpixel_variant,
2449 scale_factor,
2450 is_emoji: false,
2451 };
2452
2453 let raster_bounds = self.text_system().raster_bounds(¶ms)?;
2454 if !raster_bounds.is_zero() {
2455 let tile = self
2456 .sprite_atlas
2457 .get_or_insert_with(¶ms.clone().into(), &mut || {
2458 let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?;
2459 Ok(Some((size, Cow::Owned(bytes))))
2460 })?
2461 .expect("Callback above only errors or returns Some");
2462 let bounds = Bounds {
2463 origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
2464 size: tile.bounds.size.map(Into::into),
2465 };
2466 let content_mask = self.content_mask().scale(scale_factor);
2467 self.next_frame.scene.insert_primitive(MonochromeSprite {
2468 order: 0,
2469 pad: 0,
2470 bounds,
2471 content_mask,
2472 color: color.opacity(element_opacity),
2473 tile,
2474 transformation: TransformationMatrix::unit(),
2475 });
2476 }
2477 Ok(())
2478 }
2479
2480 /// Paints an emoji glyph into the scene for the next frame at the current z-index.
2481 ///
2482 /// The y component of the origin is the baseline of the glyph.
2483 /// You should generally prefer to use the [`ShapedLine::paint`](crate::ShapedLine::paint) or
2484 /// [`WrappedLine::paint`](crate::WrappedLine::paint) methods in the [`TextSystem`](crate::TextSystem).
2485 /// This method is only useful if you need to paint a single emoji that has already been shaped.
2486 ///
2487 /// This method should only be called as part of the paint phase of element drawing.
2488 pub fn paint_emoji(
2489 &mut self,
2490 origin: Point<Pixels>,
2491 font_id: FontId,
2492 glyph_id: GlyphId,
2493 font_size: Pixels,
2494 ) -> Result<()> {
2495 self.invalidator.debug_assert_paint();
2496
2497 let scale_factor = self.scale_factor();
2498 let glyph_origin = origin.scale(scale_factor);
2499 let params = RenderGlyphParams {
2500 font_id,
2501 glyph_id,
2502 font_size,
2503 // We don't render emojis with subpixel variants.
2504 subpixel_variant: Default::default(),
2505 scale_factor,
2506 is_emoji: true,
2507 };
2508
2509 let raster_bounds = self.text_system().raster_bounds(¶ms)?;
2510 if !raster_bounds.is_zero() {
2511 let tile = self
2512 .sprite_atlas
2513 .get_or_insert_with(¶ms.clone().into(), &mut || {
2514 let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?;
2515 Ok(Some((size, Cow::Owned(bytes))))
2516 })?
2517 .expect("Callback above only errors or returns Some");
2518
2519 let bounds = Bounds {
2520 origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
2521 size: tile.bounds.size.map(Into::into),
2522 };
2523 let content_mask = self.content_mask().scale(scale_factor);
2524 let opacity = self.element_opacity();
2525
2526 self.next_frame.scene.insert_primitive(PolychromeSprite {
2527 order: 0,
2528 pad: 0,
2529 grayscale: false,
2530 bounds,
2531 corner_radii: Default::default(),
2532 content_mask,
2533 tile,
2534 opacity,
2535 });
2536 }
2537 Ok(())
2538 }
2539
2540 /// Paint a monochrome SVG into the scene for the next frame at the current stacking context.
2541 ///
2542 /// This method should only be called as part of the paint phase of element drawing.
2543 pub fn paint_svg(
2544 &mut self,
2545 bounds: Bounds<Pixels>,
2546 path: SharedString,
2547 transformation: TransformationMatrix,
2548 color: Hsla,
2549 cx: &App,
2550 ) -> Result<()> {
2551 self.invalidator.debug_assert_paint();
2552
2553 let element_opacity = self.element_opacity();
2554 let scale_factor = self.scale_factor();
2555 let bounds = bounds.scale(scale_factor);
2556 let params = RenderSvgParams {
2557 path,
2558 size: bounds.size.map(|pixels| {
2559 DevicePixels::from((pixels.0 * SMOOTH_SVG_SCALE_FACTOR).ceil() as i32)
2560 }),
2561 };
2562
2563 let Some(tile) =
2564 self.sprite_atlas
2565 .get_or_insert_with(¶ms.clone().into(), &mut || {
2566 let Some(bytes) = cx.svg_renderer.render(¶ms)? else {
2567 return Ok(None);
2568 };
2569 Ok(Some((params.size, Cow::Owned(bytes))))
2570 })?
2571 else {
2572 return Ok(());
2573 };
2574 let content_mask = self.content_mask().scale(scale_factor);
2575
2576 self.next_frame.scene.insert_primitive(MonochromeSprite {
2577 order: 0,
2578 pad: 0,
2579 bounds: bounds
2580 .map_origin(|origin| origin.floor())
2581 .map_size(|size| size.ceil()),
2582 content_mask,
2583 color: color.opacity(element_opacity),
2584 tile,
2585 transformation,
2586 });
2587
2588 Ok(())
2589 }
2590
2591 /// Paint an image into the scene for the next frame at the current z-index.
2592 /// This method will panic if the frame_index is not valid
2593 ///
2594 /// This method should only be called as part of the paint phase of element drawing.
2595 pub fn paint_image(
2596 &mut self,
2597 bounds: Bounds<Pixels>,
2598 corner_radii: Corners<Pixels>,
2599 data: Arc<RenderImage>,
2600 frame_index: usize,
2601 grayscale: bool,
2602 ) -> Result<()> {
2603 self.invalidator.debug_assert_paint();
2604
2605 let scale_factor = self.scale_factor();
2606 let bounds = bounds.scale(scale_factor);
2607 let params = RenderImageParams {
2608 image_id: data.id,
2609 frame_index,
2610 };
2611
2612 let tile = self
2613 .sprite_atlas
2614 .get_or_insert_with(¶ms.clone().into(), &mut || {
2615 Ok(Some((
2616 data.size(frame_index),
2617 Cow::Borrowed(
2618 data.as_bytes(frame_index)
2619 .expect("It's the caller's job to pass a valid frame index"),
2620 ),
2621 )))
2622 })?
2623 .expect("Callback above only returns Some");
2624 let content_mask = self.content_mask().scale(scale_factor);
2625 let corner_radii = corner_radii.scale(scale_factor);
2626 let opacity = self.element_opacity();
2627
2628 self.next_frame.scene.insert_primitive(PolychromeSprite {
2629 order: 0,
2630 pad: 0,
2631 grayscale,
2632 bounds,
2633 content_mask,
2634 corner_radii,
2635 tile,
2636 opacity,
2637 });
2638 Ok(())
2639 }
2640
2641 /// Paint a surface into the scene for the next frame at the current z-index.
2642 ///
2643 /// This method should only be called as part of the paint phase of element drawing.
2644 #[cfg(target_os = "macos")]
2645 pub fn paint_surface(&mut self, bounds: Bounds<Pixels>, image_buffer: CVImageBuffer) {
2646 use crate::PaintSurface;
2647
2648 self.invalidator.debug_assert_paint();
2649
2650 let scale_factor = self.scale_factor();
2651 let bounds = bounds.scale(scale_factor);
2652 let content_mask = self.content_mask().scale(scale_factor);
2653 self.next_frame.scene.insert_primitive(PaintSurface {
2654 order: 0,
2655 bounds,
2656 content_mask,
2657 image_buffer,
2658 });
2659 }
2660
2661 /// Removes an image from the sprite atlas.
2662 pub fn drop_image(&mut self, data: Arc<RenderImage>) -> Result<()> {
2663 for frame_index in 0..data.frame_count() {
2664 let params = RenderImageParams {
2665 image_id: data.id,
2666 frame_index,
2667 };
2668
2669 self.sprite_atlas.remove(¶ms.clone().into());
2670 }
2671
2672 Ok(())
2673 }
2674
2675 /// Add a node to the layout tree for the current frame. Takes the `Style` of the element for which
2676 /// layout is being requested, along with the layout ids of any children. This method is called during
2677 /// calls to the [`Element::request_layout`] trait method and enables any element to participate in layout.
2678 ///
2679 /// This method should only be called as part of the request_layout or prepaint phase of element drawing.
2680 #[must_use]
2681 pub fn request_layout(
2682 &mut self,
2683 style: Style,
2684 children: impl IntoIterator<Item = LayoutId>,
2685 cx: &mut App,
2686 ) -> LayoutId {
2687 self.invalidator.debug_assert_prepaint();
2688
2689 cx.layout_id_buffer.clear();
2690 cx.layout_id_buffer.extend(children);
2691 let rem_size = self.rem_size();
2692
2693 self.layout_engine
2694 .as_mut()
2695 .unwrap()
2696 .request_layout(style, rem_size, &cx.layout_id_buffer)
2697 }
2698
2699 /// Add a node to the layout tree for the current frame. Instead of taking a `Style` and children,
2700 /// this variant takes a function that is invoked during layout so you can use arbitrary logic to
2701 /// determine the element's size. One place this is used internally is when measuring text.
2702 ///
2703 /// The given closure is invoked at layout time with the known dimensions and available space and
2704 /// returns a `Size`.
2705 ///
2706 /// This method should only be called as part of the request_layout or prepaint phase of element drawing.
2707 pub fn request_measured_layout<
2708 F: FnMut(Size<Option<Pixels>>, Size<AvailableSpace>, &mut Window, &mut App) -> Size<Pixels>
2709 + 'static,
2710 >(
2711 &mut self,
2712 style: Style,
2713 measure: F,
2714 ) -> LayoutId {
2715 self.invalidator.debug_assert_prepaint();
2716
2717 let rem_size = self.rem_size();
2718 self.layout_engine
2719 .as_mut()
2720 .unwrap()
2721 .request_measured_layout(style, rem_size, measure)
2722 }
2723
2724 /// Compute the layout for the given id within the given available space.
2725 /// This method is called for its side effect, typically by the framework prior to painting.
2726 /// After calling it, you can request the bounds of the given layout node id or any descendant.
2727 ///
2728 /// This method should only be called as part of the prepaint phase of element drawing.
2729 pub fn compute_layout(
2730 &mut self,
2731 layout_id: LayoutId,
2732 available_space: Size<AvailableSpace>,
2733 cx: &mut App,
2734 ) {
2735 self.invalidator.debug_assert_prepaint();
2736
2737 let mut layout_engine = self.layout_engine.take().unwrap();
2738 layout_engine.compute_layout(layout_id, available_space, self, cx);
2739 self.layout_engine = Some(layout_engine);
2740 }
2741
2742 /// Obtain the bounds computed for the given LayoutId relative to the window. This method will usually be invoked by
2743 /// GPUI itself automatically in order to pass your element its `Bounds` automatically.
2744 ///
2745 /// This method should only be called as part of element drawing.
2746 pub fn layout_bounds(&mut self, layout_id: LayoutId) -> Bounds<Pixels> {
2747 self.invalidator.debug_assert_prepaint();
2748
2749 let mut bounds = self
2750 .layout_engine
2751 .as_mut()
2752 .unwrap()
2753 .layout_bounds(layout_id)
2754 .map(Into::into);
2755 bounds.origin += self.element_offset();
2756 bounds
2757 }
2758
2759 /// This method should be called during `prepaint`. You can use
2760 /// the returned [Hitbox] during `paint` or in an event handler
2761 /// to determine whether the inserted hitbox was the topmost.
2762 ///
2763 /// This method should only be called as part of the prepaint phase of element drawing.
2764 pub fn insert_hitbox(&mut self, bounds: Bounds<Pixels>, opaque: bool) -> Hitbox {
2765 self.invalidator.debug_assert_prepaint();
2766
2767 let content_mask = self.content_mask();
2768 let id = self.next_hitbox_id;
2769 self.next_hitbox_id.0 += 1;
2770 let hitbox = Hitbox {
2771 id,
2772 bounds,
2773 content_mask,
2774 opaque,
2775 };
2776 self.next_frame.hitboxes.push(hitbox.clone());
2777 hitbox
2778 }
2779
2780 /// Sets the key context for the current element. This context will be used to translate
2781 /// keybindings into actions.
2782 ///
2783 /// This method should only be called as part of the paint phase of element drawing.
2784 pub fn set_key_context(&mut self, context: KeyContext) {
2785 self.invalidator.debug_assert_paint();
2786 self.next_frame.dispatch_tree.set_key_context(context);
2787 }
2788
2789 /// Sets the focus handle for the current element. This handle will be used to manage focus state
2790 /// and keyboard event dispatch for the element.
2791 ///
2792 /// This method should only be called as part of the prepaint phase of element drawing.
2793 pub fn set_focus_handle(&mut self, focus_handle: &FocusHandle, _: &App) {
2794 self.invalidator.debug_assert_prepaint();
2795 if focus_handle.is_focused(self) {
2796 self.next_frame.focus = Some(focus_handle.id);
2797 }
2798 self.next_frame.dispatch_tree.set_focus_id(focus_handle.id);
2799 }
2800
2801 /// Sets the view id for the current element, which will be used to manage view caching.
2802 ///
2803 /// This method should only be called as part of element prepaint. We plan on removing this
2804 /// method eventually when we solve some issues that require us to construct editor elements
2805 /// directly instead of always using editors via views.
2806 pub fn set_view_id(&mut self, view_id: EntityId) {
2807 self.invalidator.debug_assert_prepaint();
2808 self.next_frame.dispatch_tree.set_view_id(view_id);
2809 }
2810
2811 /// Get the entity ID for the currently rendering view
2812 pub fn current_view(&self) -> EntityId {
2813 self.invalidator.debug_assert_paint_or_prepaint();
2814 self.rendered_entity_stack.last().copied().unwrap()
2815 }
2816
2817 pub(crate) fn with_rendered_view<R>(
2818 &mut self,
2819 id: EntityId,
2820 f: impl FnOnce(&mut Self) -> R,
2821 ) -> R {
2822 self.rendered_entity_stack.push(id);
2823 let result = f(self);
2824 self.rendered_entity_stack.pop();
2825 result
2826 }
2827
2828 /// Sets an input handler, such as [`ElementInputHandler`][element_input_handler], which interfaces with the
2829 /// platform to receive textual input with proper integration with concerns such
2830 /// as IME interactions. This handler will be active for the upcoming frame until the following frame is
2831 /// rendered.
2832 ///
2833 /// This method should only be called as part of the paint phase of element drawing.
2834 ///
2835 /// [element_input_handler]: crate::ElementInputHandler
2836 pub fn handle_input(
2837 &mut self,
2838 focus_handle: &FocusHandle,
2839 input_handler: impl InputHandler,
2840 cx: &App,
2841 ) {
2842 self.invalidator.debug_assert_paint();
2843
2844 if focus_handle.is_focused(self) {
2845 let cx = self.to_async(cx);
2846 self.next_frame
2847 .input_handlers
2848 .push(Some(PlatformInputHandler::new(cx, Box::new(input_handler))));
2849 }
2850 }
2851
2852 /// Register a mouse event listener on the window for the next frame. The type of event
2853 /// is determined by the first parameter of the given listener. When the next frame is rendered
2854 /// the listener will be cleared.
2855 ///
2856 /// This method should only be called as part of the paint phase of element drawing.
2857 pub fn on_mouse_event<Event: MouseEvent>(
2858 &mut self,
2859 mut handler: impl FnMut(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
2860 ) {
2861 self.invalidator.debug_assert_paint();
2862
2863 self.next_frame.mouse_listeners.push(Some(Box::new(
2864 move |event: &dyn Any, phase: DispatchPhase, window: &mut Window, cx: &mut App| {
2865 if let Some(event) = event.downcast_ref() {
2866 handler(event, phase, window, cx)
2867 }
2868 },
2869 )));
2870 }
2871
2872 /// Register a key event listener on the window for the next frame. The type of event
2873 /// is determined by the first parameter of the given listener. When the next frame is rendered
2874 /// the listener will be cleared.
2875 ///
2876 /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
2877 /// a specific need to register a global listener.
2878 ///
2879 /// This method should only be called as part of the paint phase of element drawing.
2880 pub fn on_key_event<Event: KeyEvent>(
2881 &mut self,
2882 listener: impl Fn(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
2883 ) {
2884 self.invalidator.debug_assert_paint();
2885
2886 self.next_frame.dispatch_tree.on_key_event(Rc::new(
2887 move |event: &dyn Any, phase, window: &mut Window, cx: &mut App| {
2888 if let Some(event) = event.downcast_ref::<Event>() {
2889 listener(event, phase, window, cx)
2890 }
2891 },
2892 ));
2893 }
2894
2895 /// Register a modifiers changed event listener on the window for the next frame.
2896 ///
2897 /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
2898 /// a specific need to register a global listener.
2899 ///
2900 /// This method should only be called as part of the paint phase of element drawing.
2901 pub fn on_modifiers_changed(
2902 &mut self,
2903 listener: impl Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static,
2904 ) {
2905 self.invalidator.debug_assert_paint();
2906
2907 self.next_frame.dispatch_tree.on_modifiers_changed(Rc::new(
2908 move |event: &ModifiersChangedEvent, window: &mut Window, cx: &mut App| {
2909 listener(event, window, cx)
2910 },
2911 ));
2912 }
2913
2914 /// Register a listener to be called when the given focus handle or one of its descendants receives focus.
2915 /// This does not fire if the given focus handle - or one of its descendants - was previously focused.
2916 /// Returns a subscription and persists until the subscription is dropped.
2917 pub fn on_focus_in(
2918 &mut self,
2919 handle: &FocusHandle,
2920 cx: &mut App,
2921 mut listener: impl FnMut(&mut Window, &mut App) + 'static,
2922 ) -> Subscription {
2923 let focus_id = handle.id;
2924 let (subscription, activate) =
2925 self.new_focus_listener(Box::new(move |event, window, cx| {
2926 if event.is_focus_in(focus_id) {
2927 listener(window, cx);
2928 }
2929 true
2930 }));
2931 cx.defer(move |_| activate());
2932 subscription
2933 }
2934
2935 /// Register a listener to be called when the given focus handle or one of its descendants loses focus.
2936 /// Returns a subscription and persists until the subscription is dropped.
2937 pub fn on_focus_out(
2938 &mut self,
2939 handle: &FocusHandle,
2940 cx: &mut App,
2941 mut listener: impl FnMut(FocusOutEvent, &mut Window, &mut App) + 'static,
2942 ) -> Subscription {
2943 let focus_id = handle.id;
2944 let (subscription, activate) =
2945 self.new_focus_listener(Box::new(move |event, window, cx| {
2946 if let Some(blurred_id) = event.previous_focus_path.last().copied() {
2947 if event.is_focus_out(focus_id) {
2948 let event = FocusOutEvent {
2949 blurred: WeakFocusHandle {
2950 id: blurred_id,
2951 handles: Arc::downgrade(&cx.focus_handles),
2952 },
2953 };
2954 listener(event, window, cx)
2955 }
2956 }
2957 true
2958 }));
2959 cx.defer(move |_| activate());
2960 subscription
2961 }
2962
2963 fn reset_cursor_style(&self, cx: &mut App) {
2964 // Set the cursor only if we're the active window.
2965 if self.is_window_hovered() {
2966 let style = self
2967 .rendered_frame
2968 .cursor_styles
2969 .iter()
2970 .rev()
2971 .find(|request| request.hitbox_id.is_hovered(self))
2972 .map(|request| request.style)
2973 .unwrap_or(CursorStyle::Arrow);
2974 cx.platform.set_cursor_style(style);
2975 }
2976 }
2977
2978 /// Dispatch a given keystroke as though the user had typed it.
2979 /// You can create a keystroke with Keystroke::parse("").
2980 pub fn dispatch_keystroke(&mut self, keystroke: Keystroke, cx: &mut App) -> bool {
2981 let keystroke = keystroke.with_simulated_ime();
2982 let result = self.dispatch_event(
2983 PlatformInput::KeyDown(KeyDownEvent {
2984 keystroke: keystroke.clone(),
2985 is_held: false,
2986 }),
2987 cx,
2988 );
2989 if !result.propagate {
2990 return true;
2991 }
2992
2993 if let Some(input) = keystroke.key_char {
2994 if let Some(mut input_handler) = self.platform_window.take_input_handler() {
2995 input_handler.dispatch_input(&input, self, cx);
2996 self.platform_window.set_input_handler(input_handler);
2997 return true;
2998 }
2999 }
3000
3001 false
3002 }
3003
3004 /// Return a key binding string for an action, to display in the UI. Uses the highest precedence
3005 /// binding for the action (last binding added to the keymap).
3006 pub fn keystroke_text_for(&self, action: &dyn Action) -> String {
3007 self.bindings_for_action(action)
3008 .last()
3009 .map(|binding| {
3010 binding
3011 .keystrokes()
3012 .iter()
3013 .map(ToString::to_string)
3014 .collect::<Vec<_>>()
3015 .join(" ")
3016 })
3017 .unwrap_or_else(|| action.name().to_string())
3018 }
3019
3020 /// Dispatch a mouse or keyboard event on the window.
3021 #[profiling::function]
3022 pub fn dispatch_event(&mut self, event: PlatformInput, cx: &mut App) -> DispatchEventResult {
3023 self.last_input_timestamp.set(Instant::now());
3024 // Handlers may set this to false by calling `stop_propagation`.
3025 cx.propagate_event = true;
3026 // Handlers may set this to true by calling `prevent_default`.
3027 self.default_prevented = false;
3028
3029 let event = match event {
3030 // Track the mouse position with our own state, since accessing the platform
3031 // API for the mouse position can only occur on the main thread.
3032 PlatformInput::MouseMove(mouse_move) => {
3033 self.mouse_position = mouse_move.position;
3034 self.modifiers = mouse_move.modifiers;
3035 PlatformInput::MouseMove(mouse_move)
3036 }
3037 PlatformInput::MouseDown(mouse_down) => {
3038 self.mouse_position = mouse_down.position;
3039 self.modifiers = mouse_down.modifiers;
3040 PlatformInput::MouseDown(mouse_down)
3041 }
3042 PlatformInput::MouseUp(mouse_up) => {
3043 self.mouse_position = mouse_up.position;
3044 self.modifiers = mouse_up.modifiers;
3045 PlatformInput::MouseUp(mouse_up)
3046 }
3047 PlatformInput::MouseExited(mouse_exited) => {
3048 self.modifiers = mouse_exited.modifiers;
3049 PlatformInput::MouseExited(mouse_exited)
3050 }
3051 PlatformInput::ModifiersChanged(modifiers_changed) => {
3052 self.modifiers = modifiers_changed.modifiers;
3053 PlatformInput::ModifiersChanged(modifiers_changed)
3054 }
3055 PlatformInput::ScrollWheel(scroll_wheel) => {
3056 self.mouse_position = scroll_wheel.position;
3057 self.modifiers = scroll_wheel.modifiers;
3058 PlatformInput::ScrollWheel(scroll_wheel)
3059 }
3060 // Translate dragging and dropping of external files from the operating system
3061 // to internal drag and drop events.
3062 PlatformInput::FileDrop(file_drop) => match file_drop {
3063 FileDropEvent::Entered { position, paths } => {
3064 self.mouse_position = position;
3065 if cx.active_drag.is_none() {
3066 cx.active_drag = Some(AnyDrag {
3067 value: Arc::new(paths.clone()),
3068 view: cx.new(|_| paths).into(),
3069 cursor_offset: position,
3070 });
3071 }
3072 PlatformInput::MouseMove(MouseMoveEvent {
3073 position,
3074 pressed_button: Some(MouseButton::Left),
3075 modifiers: Modifiers::default(),
3076 })
3077 }
3078 FileDropEvent::Pending { position } => {
3079 self.mouse_position = position;
3080 PlatformInput::MouseMove(MouseMoveEvent {
3081 position,
3082 pressed_button: Some(MouseButton::Left),
3083 modifiers: Modifiers::default(),
3084 })
3085 }
3086 FileDropEvent::Submit { position } => {
3087 cx.activate(true);
3088 self.mouse_position = position;
3089 PlatformInput::MouseUp(MouseUpEvent {
3090 button: MouseButton::Left,
3091 position,
3092 modifiers: Modifiers::default(),
3093 click_count: 1,
3094 })
3095 }
3096 FileDropEvent::Exited => {
3097 cx.active_drag.take();
3098 PlatformInput::FileDrop(FileDropEvent::Exited)
3099 }
3100 },
3101 PlatformInput::KeyDown(_) | PlatformInput::KeyUp(_) => event,
3102 };
3103
3104 if let Some(any_mouse_event) = event.mouse_event() {
3105 self.dispatch_mouse_event(any_mouse_event, cx);
3106 } else if let Some(any_key_event) = event.keyboard_event() {
3107 self.dispatch_key_event(any_key_event, cx);
3108 }
3109
3110 DispatchEventResult {
3111 propagate: cx.propagate_event,
3112 default_prevented: self.default_prevented,
3113 }
3114 }
3115
3116 fn dispatch_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
3117 let hit_test = self.rendered_frame.hit_test(self.mouse_position());
3118 if hit_test != self.mouse_hit_test {
3119 self.mouse_hit_test = hit_test;
3120 self.reset_cursor_style(cx);
3121 }
3122
3123 let mut mouse_listeners = mem::take(&mut self.rendered_frame.mouse_listeners);
3124
3125 // Capture phase, events bubble from back to front. Handlers for this phase are used for
3126 // special purposes, such as detecting events outside of a given Bounds.
3127 for listener in &mut mouse_listeners {
3128 let listener = listener.as_mut().unwrap();
3129 listener(event, DispatchPhase::Capture, self, cx);
3130 if !cx.propagate_event {
3131 break;
3132 }
3133 }
3134
3135 // Bubble phase, where most normal handlers do their work.
3136 if cx.propagate_event {
3137 for listener in mouse_listeners.iter_mut().rev() {
3138 let listener = listener.as_mut().unwrap();
3139 listener(event, DispatchPhase::Bubble, self, cx);
3140 if !cx.propagate_event {
3141 break;
3142 }
3143 }
3144 }
3145
3146 self.rendered_frame.mouse_listeners = mouse_listeners;
3147
3148 if cx.has_active_drag() {
3149 if event.is::<MouseMoveEvent>() {
3150 // If this was a mouse move event, redraw the window so that the
3151 // active drag can follow the mouse cursor.
3152 self.refresh();
3153 } else if event.is::<MouseUpEvent>() {
3154 // If this was a mouse up event, cancel the active drag and redraw
3155 // the window.
3156 cx.active_drag = None;
3157 self.refresh();
3158 }
3159 }
3160 }
3161
3162 fn dispatch_key_event(&mut self, event: &dyn Any, cx: &mut App) {
3163 if self.invalidator.is_dirty() {
3164 self.draw(cx);
3165 }
3166
3167 let node_id = self
3168 .focus
3169 .and_then(|focus_id| {
3170 self.rendered_frame
3171 .dispatch_tree
3172 .focusable_node_id(focus_id)
3173 })
3174 .unwrap_or_else(|| self.rendered_frame.dispatch_tree.root_node_id());
3175
3176 let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
3177
3178 let mut keystroke: Option<Keystroke> = None;
3179
3180 if let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() {
3181 if event.modifiers.number_of_modifiers() == 0
3182 && self.pending_modifier.modifiers.number_of_modifiers() == 1
3183 && !self.pending_modifier.saw_keystroke
3184 {
3185 let key = match self.pending_modifier.modifiers {
3186 modifiers if modifiers.shift => Some("shift"),
3187 modifiers if modifiers.control => Some("control"),
3188 modifiers if modifiers.alt => Some("alt"),
3189 modifiers if modifiers.platform => Some("platform"),
3190 modifiers if modifiers.function => Some("function"),
3191 _ => None,
3192 };
3193 if let Some(key) = key {
3194 keystroke = Some(Keystroke {
3195 key: key.to_string(),
3196 key_char: None,
3197 modifiers: Modifiers::default(),
3198 });
3199 }
3200 }
3201
3202 if self.pending_modifier.modifiers.number_of_modifiers() == 0
3203 && event.modifiers.number_of_modifiers() == 1
3204 {
3205 self.pending_modifier.saw_keystroke = false
3206 }
3207 self.pending_modifier.modifiers = event.modifiers
3208 } else if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
3209 self.pending_modifier.saw_keystroke = true;
3210 keystroke = Some(key_down_event.keystroke.clone());
3211 }
3212
3213 let Some(keystroke) = keystroke else {
3214 self.finish_dispatch_key_event(event, dispatch_path, cx);
3215 return;
3216 };
3217
3218 let mut currently_pending = self.pending_input.take().unwrap_or_default();
3219 if currently_pending.focus.is_some() && currently_pending.focus != self.focus {
3220 currently_pending = PendingInput::default();
3221 }
3222
3223 let match_result = self.rendered_frame.dispatch_tree.dispatch_key(
3224 currently_pending.keystrokes,
3225 keystroke,
3226 &dispatch_path,
3227 );
3228 if !match_result.to_replay.is_empty() {
3229 self.replay_pending_input(match_result.to_replay, cx)
3230 }
3231
3232 if !match_result.pending.is_empty() {
3233 currently_pending.keystrokes = match_result.pending;
3234 currently_pending.focus = self.focus;
3235 currently_pending.timer = Some(self.spawn(cx, |mut cx| async move {
3236 cx.background_executor.timer(Duration::from_secs(1)).await;
3237 cx.update(move |window, cx| {
3238 let Some(currently_pending) = window
3239 .pending_input
3240 .take()
3241 .filter(|pending| pending.focus == window.focus)
3242 else {
3243 return;
3244 };
3245
3246 let dispatch_path = window.rendered_frame.dispatch_tree.dispatch_path(node_id);
3247
3248 let to_replay = window
3249 .rendered_frame
3250 .dispatch_tree
3251 .flush_dispatch(currently_pending.keystrokes, &dispatch_path);
3252
3253 window.replay_pending_input(to_replay, cx)
3254 })
3255 .log_err();
3256 }));
3257 self.pending_input = Some(currently_pending);
3258 self.pending_input_changed(cx);
3259 cx.propagate_event = false;
3260 return;
3261 }
3262
3263 cx.propagate_event = true;
3264 for binding in match_result.bindings {
3265 self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
3266 if !cx.propagate_event {
3267 self.dispatch_keystroke_observers(event, Some(binding.action), cx);
3268 self.pending_input_changed(cx);
3269 return;
3270 }
3271 }
3272
3273 self.finish_dispatch_key_event(event, dispatch_path, cx);
3274 self.pending_input_changed(cx);
3275 }
3276
3277 fn finish_dispatch_key_event(
3278 &mut self,
3279 event: &dyn Any,
3280 dispatch_path: SmallVec<[DispatchNodeId; 32]>,
3281 cx: &mut App,
3282 ) {
3283 self.dispatch_key_down_up_event(event, &dispatch_path, cx);
3284 if !cx.propagate_event {
3285 return;
3286 }
3287
3288 self.dispatch_modifiers_changed_event(event, &dispatch_path, cx);
3289 if !cx.propagate_event {
3290 return;
3291 }
3292
3293 self.dispatch_keystroke_observers(event, None, cx);
3294 }
3295
3296 fn pending_input_changed(&mut self, cx: &mut App) {
3297 self.pending_input_observers
3298 .clone()
3299 .retain(&(), |callback| callback(self, cx));
3300 }
3301
3302 fn dispatch_key_down_up_event(
3303 &mut self,
3304 event: &dyn Any,
3305 dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
3306 cx: &mut App,
3307 ) {
3308 // Capture phase
3309 for node_id in dispatch_path {
3310 let node = self.rendered_frame.dispatch_tree.node(*node_id);
3311
3312 for key_listener in node.key_listeners.clone() {
3313 key_listener(event, DispatchPhase::Capture, self, cx);
3314 if !cx.propagate_event {
3315 return;
3316 }
3317 }
3318 }
3319
3320 // Bubble phase
3321 for node_id in dispatch_path.iter().rev() {
3322 // Handle low level key events
3323 let node = self.rendered_frame.dispatch_tree.node(*node_id);
3324 for key_listener in node.key_listeners.clone() {
3325 key_listener(event, DispatchPhase::Bubble, self, cx);
3326 if !cx.propagate_event {
3327 return;
3328 }
3329 }
3330 }
3331 }
3332
3333 fn dispatch_modifiers_changed_event(
3334 &mut self,
3335 event: &dyn Any,
3336 dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
3337 cx: &mut App,
3338 ) {
3339 let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() else {
3340 return;
3341 };
3342 for node_id in dispatch_path.iter().rev() {
3343 let node = self.rendered_frame.dispatch_tree.node(*node_id);
3344 for listener in node.modifiers_changed_listeners.clone() {
3345 listener(event, self, cx);
3346 if !cx.propagate_event {
3347 return;
3348 }
3349 }
3350 }
3351 }
3352
3353 /// Determine whether a potential multi-stroke key binding is in progress on this window.
3354 pub fn has_pending_keystrokes(&self) -> bool {
3355 self.pending_input.is_some()
3356 }
3357
3358 pub(crate) fn clear_pending_keystrokes(&mut self) {
3359 self.pending_input.take();
3360 }
3361
3362 /// Returns the currently pending input keystrokes that might result in a multi-stroke key binding.
3363 pub fn pending_input_keystrokes(&self) -> Option<&[Keystroke]> {
3364 self.pending_input
3365 .as_ref()
3366 .map(|pending_input| pending_input.keystrokes.as_slice())
3367 }
3368
3369 fn replay_pending_input(&mut self, replays: SmallVec<[Replay; 1]>, cx: &mut App) {
3370 let node_id = self
3371 .focus
3372 .and_then(|focus_id| {
3373 self.rendered_frame
3374 .dispatch_tree
3375 .focusable_node_id(focus_id)
3376 })
3377 .unwrap_or_else(|| self.rendered_frame.dispatch_tree.root_node_id());
3378
3379 let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
3380
3381 'replay: for replay in replays {
3382 let event = KeyDownEvent {
3383 keystroke: replay.keystroke.clone(),
3384 is_held: false,
3385 };
3386
3387 cx.propagate_event = true;
3388 for binding in replay.bindings {
3389 self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
3390 if !cx.propagate_event {
3391 self.dispatch_keystroke_observers(&event, Some(binding.action), cx);
3392 continue 'replay;
3393 }
3394 }
3395
3396 self.dispatch_key_down_up_event(&event, &dispatch_path, cx);
3397 if !cx.propagate_event {
3398 continue 'replay;
3399 }
3400 if let Some(input) = replay.keystroke.key_char.as_ref().cloned() {
3401 if let Some(mut input_handler) = self.platform_window.take_input_handler() {
3402 input_handler.dispatch_input(&input, self, cx);
3403 self.platform_window.set_input_handler(input_handler)
3404 }
3405 }
3406 }
3407 }
3408
3409 fn dispatch_action_on_node(
3410 &mut self,
3411 node_id: DispatchNodeId,
3412 action: &dyn Action,
3413 cx: &mut App,
3414 ) {
3415 let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
3416
3417 // Capture phase for global actions.
3418 cx.propagate_event = true;
3419 if let Some(mut global_listeners) = cx
3420 .global_action_listeners
3421 .remove(&action.as_any().type_id())
3422 {
3423 for listener in &global_listeners {
3424 listener(action.as_any(), DispatchPhase::Capture, cx);
3425 if !cx.propagate_event {
3426 break;
3427 }
3428 }
3429
3430 global_listeners.extend(
3431 cx.global_action_listeners
3432 .remove(&action.as_any().type_id())
3433 .unwrap_or_default(),
3434 );
3435
3436 cx.global_action_listeners
3437 .insert(action.as_any().type_id(), global_listeners);
3438 }
3439
3440 if !cx.propagate_event {
3441 return;
3442 }
3443
3444 // Capture phase for window actions.
3445 for node_id in &dispatch_path {
3446 let node = self.rendered_frame.dispatch_tree.node(*node_id);
3447 for DispatchActionListener {
3448 action_type,
3449 listener,
3450 } in node.action_listeners.clone()
3451 {
3452 let any_action = action.as_any();
3453 if action_type == any_action.type_id() {
3454 listener(any_action, DispatchPhase::Capture, self, cx);
3455
3456 if !cx.propagate_event {
3457 return;
3458 }
3459 }
3460 }
3461 }
3462
3463 // Bubble phase for window actions.
3464 for node_id in dispatch_path.iter().rev() {
3465 let node = self.rendered_frame.dispatch_tree.node(*node_id);
3466 for DispatchActionListener {
3467 action_type,
3468 listener,
3469 } in node.action_listeners.clone()
3470 {
3471 let any_action = action.as_any();
3472 if action_type == any_action.type_id() {
3473 cx.propagate_event = false; // Actions stop propagation by default during the bubble phase
3474 listener(any_action, DispatchPhase::Bubble, self, cx);
3475
3476 if !cx.propagate_event {
3477 return;
3478 }
3479 }
3480 }
3481 }
3482
3483 // Bubble phase for global actions.
3484 if let Some(mut global_listeners) = cx
3485 .global_action_listeners
3486 .remove(&action.as_any().type_id())
3487 {
3488 for listener in global_listeners.iter().rev() {
3489 cx.propagate_event = false; // Actions stop propagation by default during the bubble phase
3490
3491 listener(action.as_any(), DispatchPhase::Bubble, cx);
3492 if !cx.propagate_event {
3493 break;
3494 }
3495 }
3496
3497 global_listeners.extend(
3498 cx.global_action_listeners
3499 .remove(&action.as_any().type_id())
3500 .unwrap_or_default(),
3501 );
3502
3503 cx.global_action_listeners
3504 .insert(action.as_any().type_id(), global_listeners);
3505 }
3506 }
3507
3508 /// Register the given handler to be invoked whenever the global of the given type
3509 /// is updated.
3510 pub fn observe_global<G: Global>(
3511 &mut self,
3512 cx: &mut App,
3513 f: impl Fn(&mut Window, &mut App) + 'static,
3514 ) -> Subscription {
3515 let window_handle = self.handle;
3516 let (subscription, activate) = cx.global_observers.insert(
3517 TypeId::of::<G>(),
3518 Box::new(move |cx| {
3519 window_handle
3520 .update(cx, |_, window, cx| f(window, cx))
3521 .is_ok()
3522 }),
3523 );
3524 cx.defer(move |_| activate());
3525 subscription
3526 }
3527
3528 /// Focus the current window and bring it to the foreground at the platform level.
3529 pub fn activate_window(&self) {
3530 self.platform_window.activate();
3531 }
3532
3533 /// Minimize the current window at the platform level.
3534 pub fn minimize_window(&self) {
3535 self.platform_window.minimize();
3536 }
3537
3538 /// Toggle full screen status on the current window at the platform level.
3539 pub fn toggle_fullscreen(&self) {
3540 self.platform_window.toggle_fullscreen();
3541 }
3542
3543 /// Updates the IME panel position suggestions for languages like japanese, chinese.
3544 pub fn invalidate_character_coordinates(&self) {
3545 self.on_next_frame(|window, cx| {
3546 if let Some(mut input_handler) = window.platform_window.take_input_handler() {
3547 if let Some(bounds) = input_handler.selected_bounds(window, cx) {
3548 window
3549 .platform_window
3550 .update_ime_position(bounds.scale(window.scale_factor()));
3551 }
3552 window.platform_window.set_input_handler(input_handler);
3553 }
3554 });
3555 }
3556
3557 /// Present a platform dialog.
3558 /// The provided message will be presented, along with buttons for each answer.
3559 /// When a button is clicked, the returned Receiver will receive the index of the clicked button.
3560 pub fn prompt(
3561 &mut self,
3562 level: PromptLevel,
3563 message: &str,
3564 detail: Option<&str>,
3565 answers: &[&str],
3566 cx: &mut App,
3567 ) -> oneshot::Receiver<usize> {
3568 let prompt_builder = cx.prompt_builder.take();
3569 let Some(prompt_builder) = prompt_builder else {
3570 unreachable!("Re-entrant window prompting is not supported by GPUI");
3571 };
3572
3573 let receiver = match &prompt_builder {
3574 PromptBuilder::Default => self
3575 .platform_window
3576 .prompt(level, message, detail, answers)
3577 .unwrap_or_else(|| {
3578 self.build_custom_prompt(&prompt_builder, level, message, detail, answers, cx)
3579 }),
3580 PromptBuilder::Custom(_) => {
3581 self.build_custom_prompt(&prompt_builder, level, message, detail, answers, cx)
3582 }
3583 };
3584
3585 cx.prompt_builder = Some(prompt_builder);
3586
3587 receiver
3588 }
3589
3590 fn build_custom_prompt(
3591 &mut self,
3592 prompt_builder: &PromptBuilder,
3593 level: PromptLevel,
3594 message: &str,
3595 detail: Option<&str>,
3596 answers: &[&str],
3597 cx: &mut App,
3598 ) -> oneshot::Receiver<usize> {
3599 let (sender, receiver) = oneshot::channel();
3600 let handle = PromptHandle::new(sender);
3601 let handle = (prompt_builder)(level, message, detail, answers, handle, self, cx);
3602 self.prompt = Some(handle);
3603 receiver
3604 }
3605
3606 /// Returns the current context stack.
3607 pub fn context_stack(&self) -> Vec<KeyContext> {
3608 let dispatch_tree = &self.rendered_frame.dispatch_tree;
3609 let node_id = self
3610 .focus
3611 .and_then(|focus_id| dispatch_tree.focusable_node_id(focus_id))
3612 .unwrap_or_else(|| dispatch_tree.root_node_id());
3613
3614 dispatch_tree
3615 .dispatch_path(node_id)
3616 .iter()
3617 .filter_map(move |&node_id| dispatch_tree.node(node_id).context.clone())
3618 .collect()
3619 }
3620
3621 /// Returns all available actions for the focused element.
3622 pub fn available_actions(&self, cx: &App) -> Vec<Box<dyn Action>> {
3623 let node_id = self
3624 .focus
3625 .and_then(|focus_id| {
3626 self.rendered_frame
3627 .dispatch_tree
3628 .focusable_node_id(focus_id)
3629 })
3630 .unwrap_or_else(|| self.rendered_frame.dispatch_tree.root_node_id());
3631
3632 let mut actions = self.rendered_frame.dispatch_tree.available_actions(node_id);
3633 for action_type in cx.global_action_listeners.keys() {
3634 if let Err(ix) = actions.binary_search_by_key(action_type, |a| a.as_any().type_id()) {
3635 let action = cx.actions.build_action_type(action_type).ok();
3636 if let Some(action) = action {
3637 actions.insert(ix, action);
3638 }
3639 }
3640 }
3641 actions
3642 }
3643
3644 /// Returns key bindings that invoke an action on the currently focused element. Bindings are
3645 /// returned in the order they were added. For display, the last binding should take precedence.
3646 pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
3647 self.rendered_frame
3648 .dispatch_tree
3649 .bindings_for_action(action, &self.rendered_frame.dispatch_tree.context_stack)
3650 }
3651
3652 /// Returns any bindings that would invoke an action on the given focus handle if it were
3653 /// focused. Bindings are returned in the order they were added. For display, the last binding
3654 /// should take precedence.
3655 pub fn bindings_for_action_in(
3656 &self,
3657 action: &dyn Action,
3658 focus_handle: &FocusHandle,
3659 ) -> Vec<KeyBinding> {
3660 let dispatch_tree = &self.rendered_frame.dispatch_tree;
3661
3662 let Some(node_id) = dispatch_tree.focusable_node_id(focus_handle.id) else {
3663 return vec![];
3664 };
3665 let context_stack: Vec<_> = dispatch_tree
3666 .dispatch_path(node_id)
3667 .into_iter()
3668 .filter_map(|node_id| dispatch_tree.node(node_id).context.clone())
3669 .collect();
3670 dispatch_tree.bindings_for_action(action, &context_stack)
3671 }
3672
3673 /// Returns a generic event listener that invokes the given listener with the view and context associated with the given view handle.
3674 pub fn listener_for<V: Render, E>(
3675 &self,
3676 view: &Entity<V>,
3677 f: impl Fn(&mut V, &E, &mut Window, &mut Context<V>) + 'static,
3678 ) -> impl Fn(&E, &mut Window, &mut App) + 'static {
3679 let view = view.downgrade();
3680 move |e: &E, window: &mut Window, cx: &mut App| {
3681 view.update(cx, |view, cx| f(view, e, window, cx)).ok();
3682 }
3683 }
3684
3685 /// Returns a generic handler that invokes the given handler with the view and context associated with the given view handle.
3686 pub fn handler_for<V: Render>(
3687 &self,
3688 view: &Entity<V>,
3689 f: impl Fn(&mut V, &mut Window, &mut Context<V>) + 'static,
3690 ) -> impl Fn(&mut Window, &mut App) {
3691 let view = view.downgrade();
3692 move |window: &mut Window, cx: &mut App| {
3693 view.update(cx, |view, cx| f(view, window, cx)).ok();
3694 }
3695 }
3696
3697 /// Register a callback that can interrupt the closing of the current window based the returned boolean.
3698 /// If the callback returns false, the window won't be closed.
3699 pub fn on_window_should_close(
3700 &self,
3701 cx: &App,
3702 f: impl Fn(&mut Window, &mut App) -> bool + 'static,
3703 ) {
3704 let mut cx = self.to_async(cx);
3705 self.platform_window.on_should_close(Box::new(move || {
3706 cx.update(|window, cx| f(window, cx)).unwrap_or(true)
3707 }))
3708 }
3709
3710 /// Register an action listener on the window for the next frame. The type of action
3711 /// is determined by the first parameter of the given listener. When the next frame is rendered
3712 /// the listener will be cleared.
3713 ///
3714 /// This is a fairly low-level method, so prefer using action handlers on elements unless you have
3715 /// a specific need to register a global listener.
3716 pub fn on_action(
3717 &mut self,
3718 action_type: TypeId,
3719 listener: impl Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static,
3720 ) {
3721 self.next_frame
3722 .dispatch_tree
3723 .on_action(action_type, Rc::new(listener));
3724 }
3725
3726 /// Read information about the GPU backing this window.
3727 /// Currently returns None on Mac and Windows.
3728 pub fn gpu_specs(&self) -> Option<GpuSpecs> {
3729 self.platform_window.gpu_specs()
3730 }
3731}
3732
3733// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
3734slotmap::new_key_type! {
3735 /// A unique identifier for a window.
3736 pub struct WindowId;
3737}
3738
3739impl WindowId {
3740 /// Converts this window ID to a `u64`.
3741 pub fn as_u64(&self) -> u64 {
3742 self.0.as_ffi()
3743 }
3744}
3745
3746impl From<u64> for WindowId {
3747 fn from(value: u64) -> Self {
3748 WindowId(slotmap::KeyData::from_ffi(value))
3749 }
3750}
3751
3752/// A handle to a window with a specific root view type.
3753/// Note that this does not keep the window alive on its own.
3754#[derive(Deref, DerefMut)]
3755pub struct WindowHandle<V> {
3756 #[deref]
3757 #[deref_mut]
3758 pub(crate) any_handle: AnyWindowHandle,
3759 state_type: PhantomData<V>,
3760}
3761
3762impl<V: 'static + Render> WindowHandle<V> {
3763 /// Creates a new handle from a window ID.
3764 /// This does not check if the root type of the window is `V`.
3765 pub fn new(id: WindowId) -> Self {
3766 WindowHandle {
3767 any_handle: AnyWindowHandle {
3768 id,
3769 state_type: TypeId::of::<V>(),
3770 },
3771 state_type: PhantomData,
3772 }
3773 }
3774
3775 /// Get the root view out of this window.
3776 ///
3777 /// This will fail if the window is closed or if the root view's type does not match `V`.
3778 #[cfg(any(test, feature = "test-support"))]
3779 pub fn root<C>(&self, cx: &mut C) -> Result<Entity<V>>
3780 where
3781 C: AppContext,
3782 {
3783 crate::Flatten::flatten(cx.update_window(self.any_handle, |root_view, _, _| {
3784 root_view
3785 .downcast::<V>()
3786 .map_err(|_| anyhow!("the type of the window's root view has changed"))
3787 }))
3788 }
3789
3790 /// Updates the root view of this window.
3791 ///
3792 /// This will fail if the window has been closed or if the root view's type does not match
3793 pub fn update<C, R>(
3794 &self,
3795 cx: &mut C,
3796 update: impl FnOnce(&mut V, &mut Window, &mut Context<'_, V>) -> R,
3797 ) -> Result<R>
3798 where
3799 C: AppContext,
3800 {
3801 cx.update_window(self.any_handle, |root_view, window, cx| {
3802 let view = root_view
3803 .downcast::<V>()
3804 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
3805
3806 Ok(view.update(cx, |view, cx| update(view, window, cx)))
3807 })?
3808 }
3809
3810 /// Read the root view out of this window.
3811 ///
3812 /// This will fail if the window is closed or if the root view's type does not match `V`.
3813 pub fn read<'a>(&self, cx: &'a App) -> Result<&'a V> {
3814 let x = cx
3815 .windows
3816 .get(self.id)
3817 .and_then(|window| {
3818 window
3819 .as_ref()
3820 .and_then(|window| window.root.clone())
3821 .map(|root_view| root_view.downcast::<V>())
3822 })
3823 .ok_or_else(|| anyhow!("window not found"))?
3824 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
3825
3826 Ok(x.read(cx))
3827 }
3828
3829 /// Read the root view out of this window, with a callback
3830 ///
3831 /// This will fail if the window is closed or if the root view's type does not match `V`.
3832 pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &App) -> R) -> Result<R>
3833 where
3834 C: AppContext,
3835 {
3836 cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
3837 }
3838
3839 /// Read the root view pointer off of this window.
3840 ///
3841 /// This will fail if the window is closed or if the root view's type does not match `V`.
3842 pub fn entity<C>(&self, cx: &C) -> Result<Entity<V>>
3843 where
3844 C: AppContext,
3845 {
3846 cx.read_window(self, |root_view, _cx| root_view.clone())
3847 }
3848
3849 /// Check if this window is 'active'.
3850 ///
3851 /// Will return `None` if the window is closed or currently
3852 /// borrowed.
3853 pub fn is_active(&self, cx: &mut App) -> Option<bool> {
3854 cx.update_window(self.any_handle, |_, window, _| window.is_window_active())
3855 .ok()
3856 }
3857}
3858
3859impl<V> Copy for WindowHandle<V> {}
3860
3861impl<V> Clone for WindowHandle<V> {
3862 fn clone(&self) -> Self {
3863 *self
3864 }
3865}
3866
3867impl<V> PartialEq for WindowHandle<V> {
3868 fn eq(&self, other: &Self) -> bool {
3869 self.any_handle == other.any_handle
3870 }
3871}
3872
3873impl<V> Eq for WindowHandle<V> {}
3874
3875impl<V> Hash for WindowHandle<V> {
3876 fn hash<H: Hasher>(&self, state: &mut H) {
3877 self.any_handle.hash(state);
3878 }
3879}
3880
3881impl<V: 'static> From<WindowHandle<V>> for AnyWindowHandle {
3882 fn from(val: WindowHandle<V>) -> Self {
3883 val.any_handle
3884 }
3885}
3886
3887unsafe impl<V> Send for WindowHandle<V> {}
3888unsafe impl<V> Sync for WindowHandle<V> {}
3889
3890/// A handle to a window with any root view type, which can be downcast to a window with a specific root view type.
3891#[derive(Copy, Clone, PartialEq, Eq, Hash)]
3892pub struct AnyWindowHandle {
3893 pub(crate) id: WindowId,
3894 state_type: TypeId,
3895}
3896
3897impl AnyWindowHandle {
3898 /// Get the ID of this window.
3899 pub fn window_id(&self) -> WindowId {
3900 self.id
3901 }
3902
3903 /// Attempt to convert this handle to a window handle with a specific root view type.
3904 /// If the types do not match, this will return `None`.
3905 pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
3906 if TypeId::of::<T>() == self.state_type {
3907 Some(WindowHandle {
3908 any_handle: *self,
3909 state_type: PhantomData,
3910 })
3911 } else {
3912 None
3913 }
3914 }
3915
3916 /// Updates the state of the root view of this window.
3917 ///
3918 /// This will fail if the window has been closed.
3919 pub fn update<C, R>(
3920 self,
3921 cx: &mut C,
3922 update: impl FnOnce(AnyView, &mut Window, &mut App) -> R,
3923 ) -> Result<R>
3924 where
3925 C: AppContext,
3926 {
3927 cx.update_window(self, update)
3928 }
3929
3930 /// Read the state of the root view of this window.
3931 ///
3932 /// This will fail if the window has been closed.
3933 pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(Entity<T>, &App) -> R) -> Result<R>
3934 where
3935 C: AppContext,
3936 T: 'static,
3937 {
3938 let view = self
3939 .downcast::<T>()
3940 .context("the type of the window's root view has changed")?;
3941
3942 cx.read_window(&view, read)
3943 }
3944}
3945
3946/// An identifier for an [`Element`](crate::Element).
3947///
3948/// Can be constructed with a string, a number, or both, as well
3949/// as other internal representations.
3950#[derive(Clone, Debug, Eq, PartialEq, Hash)]
3951pub enum ElementId {
3952 /// The ID of a View element
3953 View(EntityId),
3954 /// An integer ID.
3955 Integer(usize),
3956 /// A string based ID.
3957 Name(SharedString),
3958 /// A UUID.
3959 Uuid(Uuid),
3960 /// An ID that's equated with a focus handle.
3961 FocusHandle(FocusId),
3962 /// A combination of a name and an integer.
3963 NamedInteger(SharedString, usize),
3964 /// A path
3965 Path(Arc<std::path::Path>),
3966}
3967
3968impl Display for ElementId {
3969 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3970 match self {
3971 ElementId::View(entity_id) => write!(f, "view-{}", entity_id)?,
3972 ElementId::Integer(ix) => write!(f, "{}", ix)?,
3973 ElementId::Name(name) => write!(f, "{}", name)?,
3974 ElementId::FocusHandle(_) => write!(f, "FocusHandle")?,
3975 ElementId::NamedInteger(s, i) => write!(f, "{}-{}", s, i)?,
3976 ElementId::Uuid(uuid) => write!(f, "{}", uuid)?,
3977 ElementId::Path(path) => write!(f, "{}", path.display())?,
3978 }
3979
3980 Ok(())
3981 }
3982}
3983
3984impl TryInto<SharedString> for ElementId {
3985 type Error = anyhow::Error;
3986
3987 fn try_into(self) -> anyhow::Result<SharedString> {
3988 if let ElementId::Name(name) = self {
3989 Ok(name)
3990 } else {
3991 Err(anyhow!("element id is not string"))
3992 }
3993 }
3994}
3995
3996impl From<usize> for ElementId {
3997 fn from(id: usize) -> Self {
3998 ElementId::Integer(id)
3999 }
4000}
4001
4002impl From<i32> for ElementId {
4003 fn from(id: i32) -> Self {
4004 Self::Integer(id as usize)
4005 }
4006}
4007
4008impl From<SharedString> for ElementId {
4009 fn from(name: SharedString) -> Self {
4010 ElementId::Name(name)
4011 }
4012}
4013
4014impl From<Arc<std::path::Path>> for ElementId {
4015 fn from(path: Arc<std::path::Path>) -> Self {
4016 ElementId::Path(path)
4017 }
4018}
4019
4020impl From<&'static str> for ElementId {
4021 fn from(name: &'static str) -> Self {
4022 ElementId::Name(name.into())
4023 }
4024}
4025
4026impl<'a> From<&'a FocusHandle> for ElementId {
4027 fn from(handle: &'a FocusHandle) -> Self {
4028 ElementId::FocusHandle(handle.id)
4029 }
4030}
4031
4032impl From<(&'static str, EntityId)> for ElementId {
4033 fn from((name, id): (&'static str, EntityId)) -> Self {
4034 ElementId::NamedInteger(name.into(), id.as_u64() as usize)
4035 }
4036}
4037
4038impl From<(&'static str, usize)> for ElementId {
4039 fn from((name, id): (&'static str, usize)) -> Self {
4040 ElementId::NamedInteger(name.into(), id)
4041 }
4042}
4043
4044impl From<(SharedString, usize)> for ElementId {
4045 fn from((name, id): (SharedString, usize)) -> Self {
4046 ElementId::NamedInteger(name, id)
4047 }
4048}
4049
4050impl From<(&'static str, u64)> for ElementId {
4051 fn from((name, id): (&'static str, u64)) -> Self {
4052 ElementId::NamedInteger(name.into(), id as usize)
4053 }
4054}
4055
4056impl From<Uuid> for ElementId {
4057 fn from(value: Uuid) -> Self {
4058 Self::Uuid(value)
4059 }
4060}
4061
4062impl From<(&'static str, u32)> for ElementId {
4063 fn from((name, id): (&'static str, u32)) -> Self {
4064 ElementId::NamedInteger(name.into(), id as usize)
4065 }
4066}
4067
4068/// A rectangle to be rendered in the window at the given position and size.
4069/// Passed as an argument [`Window::paint_quad`].
4070#[derive(Clone)]
4071pub struct PaintQuad {
4072 /// The bounds of the quad within the window.
4073 pub bounds: Bounds<Pixels>,
4074 /// The radii of the quad's corners.
4075 pub corner_radii: Corners<Pixels>,
4076 /// The background color of the quad.
4077 pub background: Background,
4078 /// The widths of the quad's borders.
4079 pub border_widths: Edges<Pixels>,
4080 /// The color of the quad's borders.
4081 pub border_color: Hsla,
4082}
4083
4084impl PaintQuad {
4085 /// Sets the corner radii of the quad.
4086 pub fn corner_radii(self, corner_radii: impl Into<Corners<Pixels>>) -> Self {
4087 PaintQuad {
4088 corner_radii: corner_radii.into(),
4089 ..self
4090 }
4091 }
4092
4093 /// Sets the border widths of the quad.
4094 pub fn border_widths(self, border_widths: impl Into<Edges<Pixels>>) -> Self {
4095 PaintQuad {
4096 border_widths: border_widths.into(),
4097 ..self
4098 }
4099 }
4100
4101 /// Sets the border color of the quad.
4102 pub fn border_color(self, border_color: impl Into<Hsla>) -> Self {
4103 PaintQuad {
4104 border_color: border_color.into(),
4105 ..self
4106 }
4107 }
4108
4109 /// Sets the background color of the quad.
4110 pub fn background(self, background: impl Into<Background>) -> Self {
4111 PaintQuad {
4112 background: background.into(),
4113 ..self
4114 }
4115 }
4116}
4117
4118/// Creates a quad with the given parameters.
4119pub fn quad(
4120 bounds: Bounds<Pixels>,
4121 corner_radii: impl Into<Corners<Pixels>>,
4122 background: impl Into<Background>,
4123 border_widths: impl Into<Edges<Pixels>>,
4124 border_color: impl Into<Hsla>,
4125) -> PaintQuad {
4126 PaintQuad {
4127 bounds,
4128 corner_radii: corner_radii.into(),
4129 background: background.into(),
4130 border_widths: border_widths.into(),
4131 border_color: border_color.into(),
4132 }
4133}
4134
4135/// Creates a filled quad with the given bounds and background color.
4136pub fn fill(bounds: impl Into<Bounds<Pixels>>, background: impl Into<Background>) -> PaintQuad {
4137 PaintQuad {
4138 bounds: bounds.into(),
4139 corner_radii: (0.).into(),
4140 background: background.into(),
4141 border_widths: (0.).into(),
4142 border_color: transparent_black(),
4143 }
4144}
4145
4146/// Creates a rectangle outline with the given bounds, border color, and a 1px border width
4147pub fn outline(bounds: impl Into<Bounds<Pixels>>, border_color: impl Into<Hsla>) -> PaintQuad {
4148 PaintQuad {
4149 bounds: bounds.into(),
4150 corner_radii: (0.).into(),
4151 background: transparent_black().into(),
4152 border_widths: (1.).into(),
4153 border_color: border_color.into(),
4154 }
4155}