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 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_drawing(&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_drawing() {
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 // Render the SVG at twice the size to get a higher quality result.
2557 let params = RenderSvgParams {
2558 path,
2559 size: bounds
2560 .size
2561 .map(|pixels| DevicePixels::from((pixels.0 * 2.).ceil() as i32)),
2562 };
2563
2564 let Some(tile) =
2565 self.sprite_atlas
2566 .get_or_insert_with(¶ms.clone().into(), &mut || {
2567 let Some(bytes) = cx.svg_renderer.render(¶ms)? else {
2568 return Ok(None);
2569 };
2570 Ok(Some((params.size, Cow::Owned(bytes))))
2571 })?
2572 else {
2573 return Ok(());
2574 };
2575 let content_mask = self.content_mask().scale(scale_factor);
2576
2577 self.next_frame.scene.insert_primitive(MonochromeSprite {
2578 order: 0,
2579 pad: 0,
2580 bounds: bounds
2581 .map_origin(|origin| origin.floor())
2582 .map_size(|size| size.ceil()),
2583 content_mask,
2584 color: color.opacity(element_opacity),
2585 tile,
2586 transformation,
2587 });
2588
2589 Ok(())
2590 }
2591
2592 /// Paint an image into the scene for the next frame at the current z-index.
2593 /// This method will panic if the frame_index is not valid
2594 ///
2595 /// This method should only be called as part of the paint phase of element drawing.
2596 pub fn paint_image(
2597 &mut self,
2598 bounds: Bounds<Pixels>,
2599 corner_radii: Corners<Pixels>,
2600 data: Arc<RenderImage>,
2601 frame_index: usize,
2602 grayscale: bool,
2603 ) -> Result<()> {
2604 self.invalidator.debug_assert_paint();
2605
2606 let scale_factor = self.scale_factor();
2607 let bounds = bounds.scale(scale_factor);
2608 let params = RenderImageParams {
2609 image_id: data.id,
2610 frame_index,
2611 };
2612
2613 let tile = self
2614 .sprite_atlas
2615 .get_or_insert_with(¶ms.clone().into(), &mut || {
2616 Ok(Some((
2617 data.size(frame_index),
2618 Cow::Borrowed(
2619 data.as_bytes(frame_index)
2620 .expect("It's the caller's job to pass a valid frame index"),
2621 ),
2622 )))
2623 })?
2624 .expect("Callback above only returns Some");
2625 let content_mask = self.content_mask().scale(scale_factor);
2626 let corner_radii = corner_radii.scale(scale_factor);
2627 let opacity = self.element_opacity();
2628
2629 self.next_frame.scene.insert_primitive(PolychromeSprite {
2630 order: 0,
2631 pad: 0,
2632 grayscale,
2633 bounds,
2634 content_mask,
2635 corner_radii,
2636 tile,
2637 opacity,
2638 });
2639 Ok(())
2640 }
2641
2642 /// Paint a surface into the scene for the next frame at the current z-index.
2643 ///
2644 /// This method should only be called as part of the paint phase of element drawing.
2645 #[cfg(target_os = "macos")]
2646 pub fn paint_surface(&mut self, bounds: Bounds<Pixels>, image_buffer: CVImageBuffer) {
2647 use crate::PaintSurface;
2648
2649 self.invalidator.debug_assert_paint();
2650
2651 let scale_factor = self.scale_factor();
2652 let bounds = bounds.scale(scale_factor);
2653 let content_mask = self.content_mask().scale(scale_factor);
2654 self.next_frame.scene.insert_primitive(PaintSurface {
2655 order: 0,
2656 bounds,
2657 content_mask,
2658 image_buffer,
2659 });
2660 }
2661
2662 /// Removes an image from the sprite atlas.
2663 pub fn drop_image(&mut self, data: Arc<RenderImage>) -> Result<()> {
2664 for frame_index in 0..data.frame_count() {
2665 let params = RenderImageParams {
2666 image_id: data.id,
2667 frame_index,
2668 };
2669
2670 self.sprite_atlas.remove(¶ms.clone().into());
2671 }
2672
2673 Ok(())
2674 }
2675
2676 /// Add a node to the layout tree for the current frame. Takes the `Style` of the element for which
2677 /// layout is being requested, along with the layout ids of any children. This method is called during
2678 /// calls to the [`Element::request_layout`] trait method and enables any element to participate in layout.
2679 ///
2680 /// This method should only be called as part of the request_layout or prepaint phase of element drawing.
2681 #[must_use]
2682 pub fn request_layout(
2683 &mut self,
2684 style: Style,
2685 children: impl IntoIterator<Item = LayoutId>,
2686 cx: &mut App,
2687 ) -> LayoutId {
2688 self.invalidator.debug_assert_prepaint();
2689
2690 cx.layout_id_buffer.clear();
2691 cx.layout_id_buffer.extend(children);
2692 let rem_size = self.rem_size();
2693
2694 self.layout_engine
2695 .as_mut()
2696 .unwrap()
2697 .request_layout(style, rem_size, &cx.layout_id_buffer)
2698 }
2699
2700 /// Add a node to the layout tree for the current frame. Instead of taking a `Style` and children,
2701 /// this variant takes a function that is invoked during layout so you can use arbitrary logic to
2702 /// determine the element's size. One place this is used internally is when measuring text.
2703 ///
2704 /// The given closure is invoked at layout time with the known dimensions and available space and
2705 /// returns a `Size`.
2706 ///
2707 /// This method should only be called as part of the request_layout or prepaint phase of element drawing.
2708 pub fn request_measured_layout<
2709 F: FnMut(Size<Option<Pixels>>, Size<AvailableSpace>, &mut Window, &mut App) -> Size<Pixels>
2710 + 'static,
2711 >(
2712 &mut self,
2713 style: Style,
2714 measure: F,
2715 ) -> LayoutId {
2716 self.invalidator.debug_assert_prepaint();
2717
2718 let rem_size = self.rem_size();
2719 self.layout_engine
2720 .as_mut()
2721 .unwrap()
2722 .request_measured_layout(style, rem_size, measure)
2723 }
2724
2725 /// Compute the layout for the given id within the given available space.
2726 /// This method is called for its side effect, typically by the framework prior to painting.
2727 /// After calling it, you can request the bounds of the given layout node id or any descendant.
2728 ///
2729 /// This method should only be called as part of the prepaint phase of element drawing.
2730 pub fn compute_layout(
2731 &mut self,
2732 layout_id: LayoutId,
2733 available_space: Size<AvailableSpace>,
2734 cx: &mut App,
2735 ) {
2736 self.invalidator.debug_assert_prepaint();
2737
2738 let mut layout_engine = self.layout_engine.take().unwrap();
2739 layout_engine.compute_layout(layout_id, available_space, self, cx);
2740 self.layout_engine = Some(layout_engine);
2741 }
2742
2743 /// Obtain the bounds computed for the given LayoutId relative to the window. This method will usually be invoked by
2744 /// GPUI itself automatically in order to pass your element its `Bounds` automatically.
2745 ///
2746 /// This method should only be called as part of element drawing.
2747 pub fn layout_bounds(&mut self, layout_id: LayoutId) -> Bounds<Pixels> {
2748 self.invalidator.debug_assert_prepaint();
2749
2750 let mut bounds = self
2751 .layout_engine
2752 .as_mut()
2753 .unwrap()
2754 .layout_bounds(layout_id)
2755 .map(Into::into);
2756 bounds.origin += self.element_offset();
2757 bounds
2758 }
2759
2760 /// This method should be called during `prepaint`. You can use
2761 /// the returned [Hitbox] during `paint` or in an event handler
2762 /// to determine whether the inserted hitbox was the topmost.
2763 ///
2764 /// This method should only be called as part of the prepaint phase of element drawing.
2765 pub fn insert_hitbox(&mut self, bounds: Bounds<Pixels>, opaque: bool) -> Hitbox {
2766 self.invalidator.debug_assert_prepaint();
2767
2768 let content_mask = self.content_mask();
2769 let id = self.next_hitbox_id;
2770 self.next_hitbox_id.0 += 1;
2771 let hitbox = Hitbox {
2772 id,
2773 bounds,
2774 content_mask,
2775 opaque,
2776 };
2777 self.next_frame.hitboxes.push(hitbox.clone());
2778 hitbox
2779 }
2780
2781 /// Sets the key context for the current element. This context will be used to translate
2782 /// keybindings into actions.
2783 ///
2784 /// This method should only be called as part of the paint phase of element drawing.
2785 pub fn set_key_context(&mut self, context: KeyContext) {
2786 self.invalidator.debug_assert_paint();
2787 self.next_frame.dispatch_tree.set_key_context(context);
2788 }
2789
2790 /// Sets the focus handle for the current element. This handle will be used to manage focus state
2791 /// and keyboard event dispatch for the element.
2792 ///
2793 /// This method should only be called as part of the prepaint phase of element drawing.
2794 pub fn set_focus_handle(&mut self, focus_handle: &FocusHandle, _: &App) {
2795 self.invalidator.debug_assert_prepaint();
2796 if focus_handle.is_focused(self) {
2797 self.next_frame.focus = Some(focus_handle.id);
2798 }
2799 self.next_frame.dispatch_tree.set_focus_id(focus_handle.id);
2800 }
2801
2802 /// Sets the view id for the current element, which will be used to manage view caching.
2803 ///
2804 /// This method should only be called as part of element prepaint. We plan on removing this
2805 /// method eventually when we solve some issues that require us to construct editor elements
2806 /// directly instead of always using editors via views.
2807 pub fn set_view_id(&mut self, view_id: EntityId) {
2808 self.invalidator.debug_assert_prepaint();
2809 self.next_frame.dispatch_tree.set_view_id(view_id);
2810 }
2811
2812 /// Get the entity ID for the currently rendering view
2813 pub fn current_view(&self) -> EntityId {
2814 self.invalidator.debug_assert_paint_or_prepaint();
2815 self.rendered_entity_stack.last().copied().unwrap()
2816 }
2817
2818 pub(crate) fn with_rendered_view<R>(
2819 &mut self,
2820 id: EntityId,
2821 f: impl FnOnce(&mut Self) -> R,
2822 ) -> R {
2823 self.rendered_entity_stack.push(id);
2824 let result = f(self);
2825 self.rendered_entity_stack.pop();
2826 result
2827 }
2828
2829 /// Sets an input handler, such as [`ElementInputHandler`][element_input_handler], which interfaces with the
2830 /// platform to receive textual input with proper integration with concerns such
2831 /// as IME interactions. This handler will be active for the upcoming frame until the following frame is
2832 /// rendered.
2833 ///
2834 /// This method should only be called as part of the paint phase of element drawing.
2835 ///
2836 /// [element_input_handler]: crate::ElementInputHandler
2837 pub fn handle_input(
2838 &mut self,
2839 focus_handle: &FocusHandle,
2840 input_handler: impl InputHandler,
2841 cx: &App,
2842 ) {
2843 self.invalidator.debug_assert_paint();
2844
2845 if focus_handle.is_focused(self) {
2846 let cx = self.to_async(cx);
2847 self.next_frame
2848 .input_handlers
2849 .push(Some(PlatformInputHandler::new(cx, Box::new(input_handler))));
2850 }
2851 }
2852
2853 /// Register a mouse event listener on the window for the next frame. The type of event
2854 /// is determined by the first parameter of the given listener. When the next frame is rendered
2855 /// the listener will be cleared.
2856 ///
2857 /// This method should only be called as part of the paint phase of element drawing.
2858 pub fn on_mouse_event<Event: MouseEvent>(
2859 &mut self,
2860 mut handler: impl FnMut(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
2861 ) {
2862 self.invalidator.debug_assert_paint();
2863
2864 self.next_frame.mouse_listeners.push(Some(Box::new(
2865 move |event: &dyn Any, phase: DispatchPhase, window: &mut Window, cx: &mut App| {
2866 if let Some(event) = event.downcast_ref() {
2867 handler(event, phase, window, cx)
2868 }
2869 },
2870 )));
2871 }
2872
2873 /// Register a key event listener on the window for the next frame. The type of event
2874 /// is determined by the first parameter of the given listener. When the next frame is rendered
2875 /// the listener will be cleared.
2876 ///
2877 /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
2878 /// a specific need to register a global listener.
2879 ///
2880 /// This method should only be called as part of the paint phase of element drawing.
2881 pub fn on_key_event<Event: KeyEvent>(
2882 &mut self,
2883 listener: impl Fn(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
2884 ) {
2885 self.invalidator.debug_assert_paint();
2886
2887 self.next_frame.dispatch_tree.on_key_event(Rc::new(
2888 move |event: &dyn Any, phase, window: &mut Window, cx: &mut App| {
2889 if let Some(event) = event.downcast_ref::<Event>() {
2890 listener(event, phase, window, cx)
2891 }
2892 },
2893 ));
2894 }
2895
2896 /// Register a modifiers changed event listener on the window for the next frame.
2897 ///
2898 /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
2899 /// a specific need to register a global listener.
2900 ///
2901 /// This method should only be called as part of the paint phase of element drawing.
2902 pub fn on_modifiers_changed(
2903 &mut self,
2904 listener: impl Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static,
2905 ) {
2906 self.invalidator.debug_assert_paint();
2907
2908 self.next_frame.dispatch_tree.on_modifiers_changed(Rc::new(
2909 move |event: &ModifiersChangedEvent, window: &mut Window, cx: &mut App| {
2910 listener(event, window, cx)
2911 },
2912 ));
2913 }
2914
2915 /// Register a listener to be called when the given focus handle or one of its descendants receives focus.
2916 /// This does not fire if the given focus handle - or one of its descendants - was previously focused.
2917 /// Returns a subscription and persists until the subscription is dropped.
2918 pub fn on_focus_in(
2919 &mut self,
2920 handle: &FocusHandle,
2921 cx: &mut App,
2922 mut listener: impl FnMut(&mut Window, &mut App) + 'static,
2923 ) -> Subscription {
2924 let focus_id = handle.id;
2925 let (subscription, activate) =
2926 self.new_focus_listener(Box::new(move |event, window, cx| {
2927 if event.is_focus_in(focus_id) {
2928 listener(window, cx);
2929 }
2930 true
2931 }));
2932 cx.defer(move |_| activate());
2933 subscription
2934 }
2935
2936 /// Register a listener to be called when the given focus handle or one of its descendants loses focus.
2937 /// Returns a subscription and persists until the subscription is dropped.
2938 pub fn on_focus_out(
2939 &mut self,
2940 handle: &FocusHandle,
2941 cx: &mut App,
2942 mut listener: impl FnMut(FocusOutEvent, &mut Window, &mut App) + 'static,
2943 ) -> Subscription {
2944 let focus_id = handle.id;
2945 let (subscription, activate) =
2946 self.new_focus_listener(Box::new(move |event, window, cx| {
2947 if let Some(blurred_id) = event.previous_focus_path.last().copied() {
2948 if event.is_focus_out(focus_id) {
2949 let event = FocusOutEvent {
2950 blurred: WeakFocusHandle {
2951 id: blurred_id,
2952 handles: Arc::downgrade(&cx.focus_handles),
2953 },
2954 };
2955 listener(event, window, cx)
2956 }
2957 }
2958 true
2959 }));
2960 cx.defer(move |_| activate());
2961 subscription
2962 }
2963
2964 fn reset_cursor_style(&self, cx: &mut App) {
2965 // Set the cursor only if we're the active window.
2966 if self.is_window_hovered() {
2967 let style = self
2968 .rendered_frame
2969 .cursor_styles
2970 .iter()
2971 .rev()
2972 .find(|request| request.hitbox_id.is_hovered(self))
2973 .map(|request| request.style)
2974 .unwrap_or(CursorStyle::Arrow);
2975 cx.platform.set_cursor_style(style);
2976 }
2977 }
2978
2979 /// Dispatch a given keystroke as though the user had typed it.
2980 /// You can create a keystroke with Keystroke::parse("").
2981 pub fn dispatch_keystroke(&mut self, keystroke: Keystroke, cx: &mut App) -> bool {
2982 let keystroke = keystroke.with_simulated_ime();
2983 let result = self.dispatch_event(
2984 PlatformInput::KeyDown(KeyDownEvent {
2985 keystroke: keystroke.clone(),
2986 is_held: false,
2987 }),
2988 cx,
2989 );
2990 if !result.propagate {
2991 return true;
2992 }
2993
2994 if let Some(input) = keystroke.key_char {
2995 if let Some(mut input_handler) = self.platform_window.take_input_handler() {
2996 input_handler.dispatch_input(&input, self, cx);
2997 self.platform_window.set_input_handler(input_handler);
2998 return true;
2999 }
3000 }
3001
3002 false
3003 }
3004
3005 /// Return a key binding string for an action, to display in the UI. Uses the highest precedence
3006 /// binding for the action (last binding added to the keymap).
3007 pub fn keystroke_text_for(&self, action: &dyn Action) -> String {
3008 self.bindings_for_action(action)
3009 .last()
3010 .map(|binding| {
3011 binding
3012 .keystrokes()
3013 .iter()
3014 .map(ToString::to_string)
3015 .collect::<Vec<_>>()
3016 .join(" ")
3017 })
3018 .unwrap_or_else(|| action.name().to_string())
3019 }
3020
3021 /// Dispatch a mouse or keyboard event on the window.
3022 #[profiling::function]
3023 pub fn dispatch_event(&mut self, event: PlatformInput, cx: &mut App) -> DispatchEventResult {
3024 self.last_input_timestamp.set(Instant::now());
3025 // Handlers may set this to false by calling `stop_propagation`.
3026 cx.propagate_event = true;
3027 // Handlers may set this to true by calling `prevent_default`.
3028 self.default_prevented = false;
3029
3030 let event = match event {
3031 // Track the mouse position with our own state, since accessing the platform
3032 // API for the mouse position can only occur on the main thread.
3033 PlatformInput::MouseMove(mouse_move) => {
3034 self.mouse_position = mouse_move.position;
3035 self.modifiers = mouse_move.modifiers;
3036 PlatformInput::MouseMove(mouse_move)
3037 }
3038 PlatformInput::MouseDown(mouse_down) => {
3039 self.mouse_position = mouse_down.position;
3040 self.modifiers = mouse_down.modifiers;
3041 PlatformInput::MouseDown(mouse_down)
3042 }
3043 PlatformInput::MouseUp(mouse_up) => {
3044 self.mouse_position = mouse_up.position;
3045 self.modifiers = mouse_up.modifiers;
3046 PlatformInput::MouseUp(mouse_up)
3047 }
3048 PlatformInput::MouseExited(mouse_exited) => {
3049 self.modifiers = mouse_exited.modifiers;
3050 PlatformInput::MouseExited(mouse_exited)
3051 }
3052 PlatformInput::ModifiersChanged(modifiers_changed) => {
3053 self.modifiers = modifiers_changed.modifiers;
3054 PlatformInput::ModifiersChanged(modifiers_changed)
3055 }
3056 PlatformInput::ScrollWheel(scroll_wheel) => {
3057 self.mouse_position = scroll_wheel.position;
3058 self.modifiers = scroll_wheel.modifiers;
3059 PlatformInput::ScrollWheel(scroll_wheel)
3060 }
3061 // Translate dragging and dropping of external files from the operating system
3062 // to internal drag and drop events.
3063 PlatformInput::FileDrop(file_drop) => match file_drop {
3064 FileDropEvent::Entered { position, paths } => {
3065 self.mouse_position = position;
3066 if cx.active_drag.is_none() {
3067 cx.active_drag = Some(AnyDrag {
3068 value: Arc::new(paths.clone()),
3069 view: cx.new(|_| paths).into(),
3070 cursor_offset: position,
3071 });
3072 }
3073 PlatformInput::MouseMove(MouseMoveEvent {
3074 position,
3075 pressed_button: Some(MouseButton::Left),
3076 modifiers: Modifiers::default(),
3077 })
3078 }
3079 FileDropEvent::Pending { position } => {
3080 self.mouse_position = position;
3081 PlatformInput::MouseMove(MouseMoveEvent {
3082 position,
3083 pressed_button: Some(MouseButton::Left),
3084 modifiers: Modifiers::default(),
3085 })
3086 }
3087 FileDropEvent::Submit { position } => {
3088 cx.activate(true);
3089 self.mouse_position = position;
3090 PlatformInput::MouseUp(MouseUpEvent {
3091 button: MouseButton::Left,
3092 position,
3093 modifiers: Modifiers::default(),
3094 click_count: 1,
3095 })
3096 }
3097 FileDropEvent::Exited => {
3098 cx.active_drag.take();
3099 PlatformInput::FileDrop(FileDropEvent::Exited)
3100 }
3101 },
3102 PlatformInput::KeyDown(_) | PlatformInput::KeyUp(_) => event,
3103 };
3104
3105 if let Some(any_mouse_event) = event.mouse_event() {
3106 self.dispatch_mouse_event(any_mouse_event, cx);
3107 } else if let Some(any_key_event) = event.keyboard_event() {
3108 self.dispatch_key_event(any_key_event, cx);
3109 }
3110
3111 DispatchEventResult {
3112 propagate: cx.propagate_event,
3113 default_prevented: self.default_prevented,
3114 }
3115 }
3116
3117 fn dispatch_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
3118 let hit_test = self.rendered_frame.hit_test(self.mouse_position());
3119 if hit_test != self.mouse_hit_test {
3120 self.mouse_hit_test = hit_test;
3121 self.reset_cursor_style(cx);
3122 }
3123
3124 let mut mouse_listeners = mem::take(&mut self.rendered_frame.mouse_listeners);
3125
3126 // Capture phase, events bubble from back to front. Handlers for this phase are used for
3127 // special purposes, such as detecting events outside of a given Bounds.
3128 for listener in &mut mouse_listeners {
3129 let listener = listener.as_mut().unwrap();
3130 listener(event, DispatchPhase::Capture, self, cx);
3131 if !cx.propagate_event {
3132 break;
3133 }
3134 }
3135
3136 // Bubble phase, where most normal handlers do their work.
3137 if cx.propagate_event {
3138 for listener in mouse_listeners.iter_mut().rev() {
3139 let listener = listener.as_mut().unwrap();
3140 listener(event, DispatchPhase::Bubble, self, cx);
3141 if !cx.propagate_event {
3142 break;
3143 }
3144 }
3145 }
3146
3147 self.rendered_frame.mouse_listeners = mouse_listeners;
3148
3149 if cx.has_active_drag() {
3150 if event.is::<MouseMoveEvent>() {
3151 // If this was a mouse move event, redraw the window so that the
3152 // active drag can follow the mouse cursor.
3153 self.refresh();
3154 } else if event.is::<MouseUpEvent>() {
3155 // If this was a mouse up event, cancel the active drag and redraw
3156 // the window.
3157 cx.active_drag = None;
3158 self.refresh();
3159 }
3160 }
3161 }
3162
3163 fn dispatch_key_event(&mut self, event: &dyn Any, cx: &mut App) {
3164 if self.invalidator.is_dirty() {
3165 self.draw(cx);
3166 }
3167
3168 let node_id = self
3169 .focus
3170 .and_then(|focus_id| {
3171 self.rendered_frame
3172 .dispatch_tree
3173 .focusable_node_id(focus_id)
3174 })
3175 .unwrap_or_else(|| self.rendered_frame.dispatch_tree.root_node_id());
3176
3177 let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
3178
3179 let mut keystroke: Option<Keystroke> = None;
3180
3181 if let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() {
3182 if event.modifiers.number_of_modifiers() == 0
3183 && self.pending_modifier.modifiers.number_of_modifiers() == 1
3184 && !self.pending_modifier.saw_keystroke
3185 {
3186 let key = match self.pending_modifier.modifiers {
3187 modifiers if modifiers.shift => Some("shift"),
3188 modifiers if modifiers.control => Some("control"),
3189 modifiers if modifiers.alt => Some("alt"),
3190 modifiers if modifiers.platform => Some("platform"),
3191 modifiers if modifiers.function => Some("function"),
3192 _ => None,
3193 };
3194 if let Some(key) = key {
3195 keystroke = Some(Keystroke {
3196 key: key.to_string(),
3197 key_char: None,
3198 modifiers: Modifiers::default(),
3199 });
3200 }
3201 }
3202
3203 if self.pending_modifier.modifiers.number_of_modifiers() == 0
3204 && event.modifiers.number_of_modifiers() == 1
3205 {
3206 self.pending_modifier.saw_keystroke = false
3207 }
3208 self.pending_modifier.modifiers = event.modifiers
3209 } else if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
3210 self.pending_modifier.saw_keystroke = true;
3211 keystroke = Some(key_down_event.keystroke.clone());
3212 }
3213
3214 let Some(keystroke) = keystroke else {
3215 self.finish_dispatch_key_event(event, dispatch_path, cx);
3216 return;
3217 };
3218
3219 let mut currently_pending = self.pending_input.take().unwrap_or_default();
3220 if currently_pending.focus.is_some() && currently_pending.focus != self.focus {
3221 currently_pending = PendingInput::default();
3222 }
3223
3224 let match_result = self.rendered_frame.dispatch_tree.dispatch_key(
3225 currently_pending.keystrokes,
3226 keystroke,
3227 &dispatch_path,
3228 );
3229 if !match_result.to_replay.is_empty() {
3230 self.replay_pending_input(match_result.to_replay, cx)
3231 }
3232
3233 if !match_result.pending.is_empty() {
3234 currently_pending.keystrokes = match_result.pending;
3235 currently_pending.focus = self.focus;
3236 currently_pending.timer = Some(self.spawn(cx, |mut cx| async move {
3237 cx.background_executor.timer(Duration::from_secs(1)).await;
3238 cx.update(move |window, cx| {
3239 let Some(currently_pending) = window
3240 .pending_input
3241 .take()
3242 .filter(|pending| pending.focus == window.focus)
3243 else {
3244 return;
3245 };
3246
3247 let dispatch_path = window.rendered_frame.dispatch_tree.dispatch_path(node_id);
3248
3249 let to_replay = window
3250 .rendered_frame
3251 .dispatch_tree
3252 .flush_dispatch(currently_pending.keystrokes, &dispatch_path);
3253
3254 window.replay_pending_input(to_replay, cx)
3255 })
3256 .log_err();
3257 }));
3258 self.pending_input = Some(currently_pending);
3259 self.pending_input_changed(cx);
3260 cx.propagate_event = false;
3261 return;
3262 }
3263
3264 cx.propagate_event = true;
3265 for binding in match_result.bindings {
3266 self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
3267 if !cx.propagate_event {
3268 self.dispatch_keystroke_observers(event, Some(binding.action), cx);
3269 self.pending_input_changed(cx);
3270 return;
3271 }
3272 }
3273
3274 self.finish_dispatch_key_event(event, dispatch_path, cx);
3275 self.pending_input_changed(cx);
3276 }
3277
3278 fn finish_dispatch_key_event(
3279 &mut self,
3280 event: &dyn Any,
3281 dispatch_path: SmallVec<[DispatchNodeId; 32]>,
3282 cx: &mut App,
3283 ) {
3284 self.dispatch_key_down_up_event(event, &dispatch_path, cx);
3285 if !cx.propagate_event {
3286 return;
3287 }
3288
3289 self.dispatch_modifiers_changed_event(event, &dispatch_path, cx);
3290 if !cx.propagate_event {
3291 return;
3292 }
3293
3294 self.dispatch_keystroke_observers(event, None, cx);
3295 }
3296
3297 fn pending_input_changed(&mut self, cx: &mut App) {
3298 self.pending_input_observers
3299 .clone()
3300 .retain(&(), |callback| callback(self, cx));
3301 }
3302
3303 fn dispatch_key_down_up_event(
3304 &mut self,
3305 event: &dyn Any,
3306 dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
3307 cx: &mut App,
3308 ) {
3309 // Capture phase
3310 for node_id in dispatch_path {
3311 let node = self.rendered_frame.dispatch_tree.node(*node_id);
3312
3313 for key_listener in node.key_listeners.clone() {
3314 key_listener(event, DispatchPhase::Capture, self, cx);
3315 if !cx.propagate_event {
3316 return;
3317 }
3318 }
3319 }
3320
3321 // Bubble phase
3322 for node_id in dispatch_path.iter().rev() {
3323 // Handle low level key events
3324 let node = self.rendered_frame.dispatch_tree.node(*node_id);
3325 for key_listener in node.key_listeners.clone() {
3326 key_listener(event, DispatchPhase::Bubble, self, cx);
3327 if !cx.propagate_event {
3328 return;
3329 }
3330 }
3331 }
3332 }
3333
3334 fn dispatch_modifiers_changed_event(
3335 &mut self,
3336 event: &dyn Any,
3337 dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
3338 cx: &mut App,
3339 ) {
3340 let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() else {
3341 return;
3342 };
3343 for node_id in dispatch_path.iter().rev() {
3344 let node = self.rendered_frame.dispatch_tree.node(*node_id);
3345 for listener in node.modifiers_changed_listeners.clone() {
3346 listener(event, self, cx);
3347 if !cx.propagate_event {
3348 return;
3349 }
3350 }
3351 }
3352 }
3353
3354 /// Determine whether a potential multi-stroke key binding is in progress on this window.
3355 pub fn has_pending_keystrokes(&self) -> bool {
3356 self.pending_input.is_some()
3357 }
3358
3359 pub(crate) fn clear_pending_keystrokes(&mut self) {
3360 self.pending_input.take();
3361 }
3362
3363 /// Returns the currently pending input keystrokes that might result in a multi-stroke key binding.
3364 pub fn pending_input_keystrokes(&self) -> Option<&[Keystroke]> {
3365 self.pending_input
3366 .as_ref()
3367 .map(|pending_input| pending_input.keystrokes.as_slice())
3368 }
3369
3370 fn replay_pending_input(&mut self, replays: SmallVec<[Replay; 1]>, cx: &mut App) {
3371 let node_id = self
3372 .focus
3373 .and_then(|focus_id| {
3374 self.rendered_frame
3375 .dispatch_tree
3376 .focusable_node_id(focus_id)
3377 })
3378 .unwrap_or_else(|| self.rendered_frame.dispatch_tree.root_node_id());
3379
3380 let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
3381
3382 'replay: for replay in replays {
3383 let event = KeyDownEvent {
3384 keystroke: replay.keystroke.clone(),
3385 is_held: false,
3386 };
3387
3388 cx.propagate_event = true;
3389 for binding in replay.bindings {
3390 self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
3391 if !cx.propagate_event {
3392 self.dispatch_keystroke_observers(&event, Some(binding.action), cx);
3393 continue 'replay;
3394 }
3395 }
3396
3397 self.dispatch_key_down_up_event(&event, &dispatch_path, cx);
3398 if !cx.propagate_event {
3399 continue 'replay;
3400 }
3401 if let Some(input) = replay.keystroke.key_char.as_ref().cloned() {
3402 if let Some(mut input_handler) = self.platform_window.take_input_handler() {
3403 input_handler.dispatch_input(&input, self, cx);
3404 self.platform_window.set_input_handler(input_handler)
3405 }
3406 }
3407 }
3408 }
3409
3410 fn dispatch_action_on_node(
3411 &mut self,
3412 node_id: DispatchNodeId,
3413 action: &dyn Action,
3414 cx: &mut App,
3415 ) {
3416 let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
3417
3418 // Capture phase for global actions.
3419 cx.propagate_event = true;
3420 if let Some(mut global_listeners) = cx
3421 .global_action_listeners
3422 .remove(&action.as_any().type_id())
3423 {
3424 for listener in &global_listeners {
3425 listener(action.as_any(), DispatchPhase::Capture, cx);
3426 if !cx.propagate_event {
3427 break;
3428 }
3429 }
3430
3431 global_listeners.extend(
3432 cx.global_action_listeners
3433 .remove(&action.as_any().type_id())
3434 .unwrap_or_default(),
3435 );
3436
3437 cx.global_action_listeners
3438 .insert(action.as_any().type_id(), global_listeners);
3439 }
3440
3441 if !cx.propagate_event {
3442 return;
3443 }
3444
3445 // Capture phase for window actions.
3446 for node_id in &dispatch_path {
3447 let node = self.rendered_frame.dispatch_tree.node(*node_id);
3448 for DispatchActionListener {
3449 action_type,
3450 listener,
3451 } in node.action_listeners.clone()
3452 {
3453 let any_action = action.as_any();
3454 if action_type == any_action.type_id() {
3455 listener(any_action, DispatchPhase::Capture, self, cx);
3456
3457 if !cx.propagate_event {
3458 return;
3459 }
3460 }
3461 }
3462 }
3463
3464 // Bubble phase for window actions.
3465 for node_id in dispatch_path.iter().rev() {
3466 let node = self.rendered_frame.dispatch_tree.node(*node_id);
3467 for DispatchActionListener {
3468 action_type,
3469 listener,
3470 } in node.action_listeners.clone()
3471 {
3472 let any_action = action.as_any();
3473 if action_type == any_action.type_id() {
3474 cx.propagate_event = false; // Actions stop propagation by default during the bubble phase
3475 listener(any_action, DispatchPhase::Bubble, self, cx);
3476
3477 if !cx.propagate_event {
3478 return;
3479 }
3480 }
3481 }
3482 }
3483
3484 // Bubble phase for global actions.
3485 if let Some(mut global_listeners) = cx
3486 .global_action_listeners
3487 .remove(&action.as_any().type_id())
3488 {
3489 for listener in global_listeners.iter().rev() {
3490 cx.propagate_event = false; // Actions stop propagation by default during the bubble phase
3491
3492 listener(action.as_any(), DispatchPhase::Bubble, cx);
3493 if !cx.propagate_event {
3494 break;
3495 }
3496 }
3497
3498 global_listeners.extend(
3499 cx.global_action_listeners
3500 .remove(&action.as_any().type_id())
3501 .unwrap_or_default(),
3502 );
3503
3504 cx.global_action_listeners
3505 .insert(action.as_any().type_id(), global_listeners);
3506 }
3507 }
3508
3509 /// Register the given handler to be invoked whenever the global of the given type
3510 /// is updated.
3511 pub fn observe_global<G: Global>(
3512 &mut self,
3513 cx: &mut App,
3514 f: impl Fn(&mut Window, &mut App) + 'static,
3515 ) -> Subscription {
3516 let window_handle = self.handle;
3517 let (subscription, activate) = cx.global_observers.insert(
3518 TypeId::of::<G>(),
3519 Box::new(move |cx| {
3520 window_handle
3521 .update(cx, |_, window, cx| f(window, cx))
3522 .is_ok()
3523 }),
3524 );
3525 cx.defer(move |_| activate());
3526 subscription
3527 }
3528
3529 /// Focus the current window and bring it to the foreground at the platform level.
3530 pub fn activate_window(&self) {
3531 self.platform_window.activate();
3532 }
3533
3534 /// Minimize the current window at the platform level.
3535 pub fn minimize_window(&self) {
3536 self.platform_window.minimize();
3537 }
3538
3539 /// Toggle full screen status on the current window at the platform level.
3540 pub fn toggle_fullscreen(&self) {
3541 self.platform_window.toggle_fullscreen();
3542 }
3543
3544 /// Updates the IME panel position suggestions for languages like japanese, chinese.
3545 pub fn invalidate_character_coordinates(&self) {
3546 self.on_next_frame(|window, cx| {
3547 if let Some(mut input_handler) = window.platform_window.take_input_handler() {
3548 if let Some(bounds) = input_handler.selected_bounds(window, cx) {
3549 window
3550 .platform_window
3551 .update_ime_position(bounds.scale(window.scale_factor()));
3552 }
3553 window.platform_window.set_input_handler(input_handler);
3554 }
3555 });
3556 }
3557
3558 /// Present a platform dialog.
3559 /// The provided message will be presented, along with buttons for each answer.
3560 /// When a button is clicked, the returned Receiver will receive the index of the clicked button.
3561 pub fn prompt(
3562 &mut self,
3563 level: PromptLevel,
3564 message: &str,
3565 detail: Option<&str>,
3566 answers: &[&str],
3567 cx: &mut App,
3568 ) -> oneshot::Receiver<usize> {
3569 let prompt_builder = cx.prompt_builder.take();
3570 let Some(prompt_builder) = prompt_builder else {
3571 unreachable!("Re-entrant window prompting is not supported by GPUI");
3572 };
3573
3574 let receiver = match &prompt_builder {
3575 PromptBuilder::Default => self
3576 .platform_window
3577 .prompt(level, message, detail, answers)
3578 .unwrap_or_else(|| {
3579 self.build_custom_prompt(&prompt_builder, level, message, detail, answers, cx)
3580 }),
3581 PromptBuilder::Custom(_) => {
3582 self.build_custom_prompt(&prompt_builder, level, message, detail, answers, cx)
3583 }
3584 };
3585
3586 cx.prompt_builder = Some(prompt_builder);
3587
3588 receiver
3589 }
3590
3591 fn build_custom_prompt(
3592 &mut self,
3593 prompt_builder: &PromptBuilder,
3594 level: PromptLevel,
3595 message: &str,
3596 detail: Option<&str>,
3597 answers: &[&str],
3598 cx: &mut App,
3599 ) -> oneshot::Receiver<usize> {
3600 let (sender, receiver) = oneshot::channel();
3601 let handle = PromptHandle::new(sender);
3602 let handle = (prompt_builder)(level, message, detail, answers, handle, self, cx);
3603 self.prompt = Some(handle);
3604 receiver
3605 }
3606
3607 /// Returns the current context stack.
3608 pub fn context_stack(&self) -> Vec<KeyContext> {
3609 let dispatch_tree = &self.rendered_frame.dispatch_tree;
3610 let node_id = self
3611 .focus
3612 .and_then(|focus_id| dispatch_tree.focusable_node_id(focus_id))
3613 .unwrap_or_else(|| dispatch_tree.root_node_id());
3614
3615 dispatch_tree
3616 .dispatch_path(node_id)
3617 .iter()
3618 .filter_map(move |&node_id| dispatch_tree.node(node_id).context.clone())
3619 .collect()
3620 }
3621
3622 /// Returns all available actions for the focused element.
3623 pub fn available_actions(&self, cx: &App) -> Vec<Box<dyn Action>> {
3624 let node_id = self
3625 .focus
3626 .and_then(|focus_id| {
3627 self.rendered_frame
3628 .dispatch_tree
3629 .focusable_node_id(focus_id)
3630 })
3631 .unwrap_or_else(|| self.rendered_frame.dispatch_tree.root_node_id());
3632
3633 let mut actions = self.rendered_frame.dispatch_tree.available_actions(node_id);
3634 for action_type in cx.global_action_listeners.keys() {
3635 if let Err(ix) = actions.binary_search_by_key(action_type, |a| a.as_any().type_id()) {
3636 let action = cx.actions.build_action_type(action_type).ok();
3637 if let Some(action) = action {
3638 actions.insert(ix, action);
3639 }
3640 }
3641 }
3642 actions
3643 }
3644
3645 /// Returns key bindings that invoke an action on the currently focused element. Bindings are
3646 /// returned in the order they were added. For display, the last binding should take precedence.
3647 pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
3648 self.rendered_frame
3649 .dispatch_tree
3650 .bindings_for_action(action, &self.rendered_frame.dispatch_tree.context_stack)
3651 }
3652
3653 /// Returns any bindings that would invoke an action on the given focus handle if it were
3654 /// focused. Bindings are returned in the order they were added. For display, the last binding
3655 /// should take precedence.
3656 pub fn bindings_for_action_in(
3657 &self,
3658 action: &dyn Action,
3659 focus_handle: &FocusHandle,
3660 ) -> Vec<KeyBinding> {
3661 let dispatch_tree = &self.rendered_frame.dispatch_tree;
3662
3663 let Some(node_id) = dispatch_tree.focusable_node_id(focus_handle.id) else {
3664 return vec![];
3665 };
3666 let context_stack: Vec<_> = dispatch_tree
3667 .dispatch_path(node_id)
3668 .into_iter()
3669 .filter_map(|node_id| dispatch_tree.node(node_id).context.clone())
3670 .collect();
3671 dispatch_tree.bindings_for_action(action, &context_stack)
3672 }
3673
3674 /// Returns a generic event listener that invokes the given listener with the view and context associated with the given view handle.
3675 pub fn listener_for<V: Render, E>(
3676 &self,
3677 view: &Entity<V>,
3678 f: impl Fn(&mut V, &E, &mut Window, &mut Context<V>) + 'static,
3679 ) -> impl Fn(&E, &mut Window, &mut App) + 'static {
3680 let view = view.downgrade();
3681 move |e: &E, window: &mut Window, cx: &mut App| {
3682 view.update(cx, |view, cx| f(view, e, window, cx)).ok();
3683 }
3684 }
3685
3686 /// Returns a generic handler that invokes the given handler with the view and context associated with the given view handle.
3687 pub fn handler_for<V: Render>(
3688 &self,
3689 view: &Entity<V>,
3690 f: impl Fn(&mut V, &mut Window, &mut Context<V>) + 'static,
3691 ) -> impl Fn(&mut Window, &mut App) {
3692 let view = view.downgrade();
3693 move |window: &mut Window, cx: &mut App| {
3694 view.update(cx, |view, cx| f(view, window, cx)).ok();
3695 }
3696 }
3697
3698 /// Register a callback that can interrupt the closing of the current window based the returned boolean.
3699 /// If the callback returns false, the window won't be closed.
3700 pub fn on_window_should_close(
3701 &self,
3702 cx: &App,
3703 f: impl Fn(&mut Window, &mut App) -> bool + 'static,
3704 ) {
3705 let mut cx = self.to_async(cx);
3706 self.platform_window.on_should_close(Box::new(move || {
3707 cx.update(|window, cx| f(window, cx)).unwrap_or(true)
3708 }))
3709 }
3710
3711 /// Register an action listener on the window for the next frame. The type of action
3712 /// is determined by the first parameter of the given listener. When the next frame is rendered
3713 /// the listener will be cleared.
3714 ///
3715 /// This is a fairly low-level method, so prefer using action handlers on elements unless you have
3716 /// a specific need to register a global listener.
3717 pub fn on_action(
3718 &mut self,
3719 action_type: TypeId,
3720 listener: impl Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static,
3721 ) {
3722 self.next_frame
3723 .dispatch_tree
3724 .on_action(action_type, Rc::new(listener));
3725 }
3726
3727 /// Read information about the GPU backing this window.
3728 /// Currently returns None on Mac and Windows.
3729 pub fn gpu_specs(&self) -> Option<GpuSpecs> {
3730 self.platform_window.gpu_specs()
3731 }
3732}
3733
3734// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
3735slotmap::new_key_type! {
3736 /// A unique identifier for a window.
3737 pub struct WindowId;
3738}
3739
3740impl WindowId {
3741 /// Converts this window ID to a `u64`.
3742 pub fn as_u64(&self) -> u64 {
3743 self.0.as_ffi()
3744 }
3745}
3746
3747impl From<u64> for WindowId {
3748 fn from(value: u64) -> Self {
3749 WindowId(slotmap::KeyData::from_ffi(value))
3750 }
3751}
3752
3753/// A handle to a window with a specific root view type.
3754/// Note that this does not keep the window alive on its own.
3755#[derive(Deref, DerefMut)]
3756pub struct WindowHandle<V> {
3757 #[deref]
3758 #[deref_mut]
3759 pub(crate) any_handle: AnyWindowHandle,
3760 state_type: PhantomData<V>,
3761}
3762
3763impl<V: 'static + Render> WindowHandle<V> {
3764 /// Creates a new handle from a window ID.
3765 /// This does not check if the root type of the window is `V`.
3766 pub fn new(id: WindowId) -> Self {
3767 WindowHandle {
3768 any_handle: AnyWindowHandle {
3769 id,
3770 state_type: TypeId::of::<V>(),
3771 },
3772 state_type: PhantomData,
3773 }
3774 }
3775
3776 /// Get the root view out of this window.
3777 ///
3778 /// This will fail if the window is closed or if the root view's type does not match `V`.
3779 #[cfg(any(test, feature = "test-support"))]
3780 pub fn root<C>(&self, cx: &mut C) -> Result<Entity<V>>
3781 where
3782 C: AppContext,
3783 {
3784 crate::Flatten::flatten(cx.update_window(self.any_handle, |root_view, _, _| {
3785 root_view
3786 .downcast::<V>()
3787 .map_err(|_| anyhow!("the type of the window's root view has changed"))
3788 }))
3789 }
3790
3791 /// Updates the root view of this window.
3792 ///
3793 /// This will fail if the window has been closed or if the root view's type does not match
3794 pub fn update<C, R>(
3795 &self,
3796 cx: &mut C,
3797 update: impl FnOnce(&mut V, &mut Window, &mut Context<'_, V>) -> R,
3798 ) -> Result<R>
3799 where
3800 C: AppContext,
3801 {
3802 cx.update_window(self.any_handle, |root_view, window, cx| {
3803 let view = root_view
3804 .downcast::<V>()
3805 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
3806
3807 Ok(view.update(cx, |view, cx| update(view, window, cx)))
3808 })?
3809 }
3810
3811 /// Read the root view out of this window.
3812 ///
3813 /// This will fail if the window is closed or if the root view's type does not match `V`.
3814 pub fn read<'a>(&self, cx: &'a App) -> Result<&'a V> {
3815 let x = cx
3816 .windows
3817 .get(self.id)
3818 .and_then(|window| {
3819 window
3820 .as_ref()
3821 .and_then(|window| window.root.clone())
3822 .map(|root_view| root_view.downcast::<V>())
3823 })
3824 .ok_or_else(|| anyhow!("window not found"))?
3825 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
3826
3827 Ok(x.read(cx))
3828 }
3829
3830 /// Read the root view out of this window, with a callback
3831 ///
3832 /// This will fail if the window is closed or if the root view's type does not match `V`.
3833 pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &App) -> R) -> Result<R>
3834 where
3835 C: AppContext,
3836 {
3837 cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
3838 }
3839
3840 /// Read the root view pointer off of this window.
3841 ///
3842 /// This will fail if the window is closed or if the root view's type does not match `V`.
3843 pub fn entity<C>(&self, cx: &C) -> Result<Entity<V>>
3844 where
3845 C: AppContext,
3846 {
3847 cx.read_window(self, |root_view, _cx| root_view.clone())
3848 }
3849
3850 /// Check if this window is 'active'.
3851 ///
3852 /// Will return `None` if the window is closed or currently
3853 /// borrowed.
3854 pub fn is_active(&self, cx: &mut App) -> Option<bool> {
3855 cx.update_window(self.any_handle, |_, window, _| window.is_window_active())
3856 .ok()
3857 }
3858}
3859
3860impl<V> Copy for WindowHandle<V> {}
3861
3862impl<V> Clone for WindowHandle<V> {
3863 fn clone(&self) -> Self {
3864 *self
3865 }
3866}
3867
3868impl<V> PartialEq for WindowHandle<V> {
3869 fn eq(&self, other: &Self) -> bool {
3870 self.any_handle == other.any_handle
3871 }
3872}
3873
3874impl<V> Eq for WindowHandle<V> {}
3875
3876impl<V> Hash for WindowHandle<V> {
3877 fn hash<H: Hasher>(&self, state: &mut H) {
3878 self.any_handle.hash(state);
3879 }
3880}
3881
3882impl<V: 'static> From<WindowHandle<V>> for AnyWindowHandle {
3883 fn from(val: WindowHandle<V>) -> Self {
3884 val.any_handle
3885 }
3886}
3887
3888unsafe impl<V> Send for WindowHandle<V> {}
3889unsafe impl<V> Sync for WindowHandle<V> {}
3890
3891/// A handle to a window with any root view type, which can be downcast to a window with a specific root view type.
3892#[derive(Copy, Clone, PartialEq, Eq, Hash)]
3893pub struct AnyWindowHandle {
3894 pub(crate) id: WindowId,
3895 state_type: TypeId,
3896}
3897
3898impl AnyWindowHandle {
3899 /// Get the ID of this window.
3900 pub fn window_id(&self) -> WindowId {
3901 self.id
3902 }
3903
3904 /// Attempt to convert this handle to a window handle with a specific root view type.
3905 /// If the types do not match, this will return `None`.
3906 pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
3907 if TypeId::of::<T>() == self.state_type {
3908 Some(WindowHandle {
3909 any_handle: *self,
3910 state_type: PhantomData,
3911 })
3912 } else {
3913 None
3914 }
3915 }
3916
3917 /// Updates the state of the root view of this window.
3918 ///
3919 /// This will fail if the window has been closed.
3920 pub fn update<C, R>(
3921 self,
3922 cx: &mut C,
3923 update: impl FnOnce(AnyView, &mut Window, &mut App) -> R,
3924 ) -> Result<R>
3925 where
3926 C: AppContext,
3927 {
3928 cx.update_window(self, update)
3929 }
3930
3931 /// Read the state of the root view of this window.
3932 ///
3933 /// This will fail if the window has been closed.
3934 pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(Entity<T>, &App) -> R) -> Result<R>
3935 where
3936 C: AppContext,
3937 T: 'static,
3938 {
3939 let view = self
3940 .downcast::<T>()
3941 .context("the type of the window's root view has changed")?;
3942
3943 cx.read_window(&view, read)
3944 }
3945}
3946
3947/// An identifier for an [`Element`](crate::Element).
3948///
3949/// Can be constructed with a string, a number, or both, as well
3950/// as other internal representations.
3951#[derive(Clone, Debug, Eq, PartialEq, Hash)]
3952pub enum ElementId {
3953 /// The ID of a View element
3954 View(EntityId),
3955 /// An integer ID.
3956 Integer(usize),
3957 /// A string based ID.
3958 Name(SharedString),
3959 /// A UUID.
3960 Uuid(Uuid),
3961 /// An ID that's equated with a focus handle.
3962 FocusHandle(FocusId),
3963 /// A combination of a name and an integer.
3964 NamedInteger(SharedString, usize),
3965 /// A path
3966 Path(Arc<std::path::Path>),
3967}
3968
3969impl Display for ElementId {
3970 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3971 match self {
3972 ElementId::View(entity_id) => write!(f, "view-{}", entity_id)?,
3973 ElementId::Integer(ix) => write!(f, "{}", ix)?,
3974 ElementId::Name(name) => write!(f, "{}", name)?,
3975 ElementId::FocusHandle(_) => write!(f, "FocusHandle")?,
3976 ElementId::NamedInteger(s, i) => write!(f, "{}-{}", s, i)?,
3977 ElementId::Uuid(uuid) => write!(f, "{}", uuid)?,
3978 ElementId::Path(path) => write!(f, "{}", path.display())?,
3979 }
3980
3981 Ok(())
3982 }
3983}
3984
3985impl TryInto<SharedString> for ElementId {
3986 type Error = anyhow::Error;
3987
3988 fn try_into(self) -> anyhow::Result<SharedString> {
3989 if let ElementId::Name(name) = self {
3990 Ok(name)
3991 } else {
3992 Err(anyhow!("element id is not string"))
3993 }
3994 }
3995}
3996
3997impl From<usize> for ElementId {
3998 fn from(id: usize) -> Self {
3999 ElementId::Integer(id)
4000 }
4001}
4002
4003impl From<i32> for ElementId {
4004 fn from(id: i32) -> Self {
4005 Self::Integer(id as usize)
4006 }
4007}
4008
4009impl From<SharedString> for ElementId {
4010 fn from(name: SharedString) -> Self {
4011 ElementId::Name(name)
4012 }
4013}
4014
4015impl From<Arc<std::path::Path>> for ElementId {
4016 fn from(path: Arc<std::path::Path>) -> Self {
4017 ElementId::Path(path)
4018 }
4019}
4020
4021impl From<&'static str> for ElementId {
4022 fn from(name: &'static str) -> Self {
4023 ElementId::Name(name.into())
4024 }
4025}
4026
4027impl<'a> From<&'a FocusHandle> for ElementId {
4028 fn from(handle: &'a FocusHandle) -> Self {
4029 ElementId::FocusHandle(handle.id)
4030 }
4031}
4032
4033impl From<(&'static str, EntityId)> for ElementId {
4034 fn from((name, id): (&'static str, EntityId)) -> Self {
4035 ElementId::NamedInteger(name.into(), id.as_u64() as usize)
4036 }
4037}
4038
4039impl From<(&'static str, usize)> for ElementId {
4040 fn from((name, id): (&'static str, usize)) -> Self {
4041 ElementId::NamedInteger(name.into(), id)
4042 }
4043}
4044
4045impl From<(SharedString, usize)> for ElementId {
4046 fn from((name, id): (SharedString, usize)) -> Self {
4047 ElementId::NamedInteger(name, id)
4048 }
4049}
4050
4051impl From<(&'static str, u64)> for ElementId {
4052 fn from((name, id): (&'static str, u64)) -> Self {
4053 ElementId::NamedInteger(name.into(), id as usize)
4054 }
4055}
4056
4057impl From<Uuid> for ElementId {
4058 fn from(value: Uuid) -> Self {
4059 Self::Uuid(value)
4060 }
4061}
4062
4063impl From<(&'static str, u32)> for ElementId {
4064 fn from((name, id): (&'static str, u32)) -> Self {
4065 ElementId::NamedInteger(name.into(), id as usize)
4066 }
4067}
4068
4069/// A rectangle to be rendered in the window at the given position and size.
4070/// Passed as an argument [`Window::paint_quad`].
4071#[derive(Clone)]
4072pub struct PaintQuad {
4073 /// The bounds of the quad within the window.
4074 pub bounds: Bounds<Pixels>,
4075 /// The radii of the quad's corners.
4076 pub corner_radii: Corners<Pixels>,
4077 /// The background color of the quad.
4078 pub background: Background,
4079 /// The widths of the quad's borders.
4080 pub border_widths: Edges<Pixels>,
4081 /// The color of the quad's borders.
4082 pub border_color: Hsla,
4083}
4084
4085impl PaintQuad {
4086 /// Sets the corner radii of the quad.
4087 pub fn corner_radii(self, corner_radii: impl Into<Corners<Pixels>>) -> Self {
4088 PaintQuad {
4089 corner_radii: corner_radii.into(),
4090 ..self
4091 }
4092 }
4093
4094 /// Sets the border widths of the quad.
4095 pub fn border_widths(self, border_widths: impl Into<Edges<Pixels>>) -> Self {
4096 PaintQuad {
4097 border_widths: border_widths.into(),
4098 ..self
4099 }
4100 }
4101
4102 /// Sets the border color of the quad.
4103 pub fn border_color(self, border_color: impl Into<Hsla>) -> Self {
4104 PaintQuad {
4105 border_color: border_color.into(),
4106 ..self
4107 }
4108 }
4109
4110 /// Sets the background color of the quad.
4111 pub fn background(self, background: impl Into<Background>) -> Self {
4112 PaintQuad {
4113 background: background.into(),
4114 ..self
4115 }
4116 }
4117}
4118
4119/// Creates a quad with the given parameters.
4120pub fn quad(
4121 bounds: Bounds<Pixels>,
4122 corner_radii: impl Into<Corners<Pixels>>,
4123 background: impl Into<Background>,
4124 border_widths: impl Into<Edges<Pixels>>,
4125 border_color: impl Into<Hsla>,
4126) -> PaintQuad {
4127 PaintQuad {
4128 bounds,
4129 corner_radii: corner_radii.into(),
4130 background: background.into(),
4131 border_widths: border_widths.into(),
4132 border_color: border_color.into(),
4133 }
4134}
4135
4136/// Creates a filled quad with the given bounds and background color.
4137pub fn fill(bounds: impl Into<Bounds<Pixels>>, background: impl Into<Background>) -> PaintQuad {
4138 PaintQuad {
4139 bounds: bounds.into(),
4140 corner_radii: (0.).into(),
4141 background: background.into(),
4142 border_widths: (0.).into(),
4143 border_color: transparent_black(),
4144 }
4145}
4146
4147/// Creates a rectangle outline with the given bounds, border color, and a 1px border width
4148pub fn outline(bounds: impl Into<Bounds<Pixels>>, border_color: impl Into<Hsla>) -> PaintQuad {
4149 PaintQuad {
4150 bounds: bounds.into(),
4151 corner_radii: (0.).into(),
4152 background: transparent_black().into(),
4153 border_widths: (1.).into(),
4154 border_color: border_color.into(),
4155 }
4156}