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