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