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