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