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