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,
2663 content_mask,
2664 corner_radii,
2665 tile,
2666 opacity,
2667 });
2668 Ok(())
2669 }
2670
2671 /// Paint a surface into the scene for the next frame at the current z-index.
2672 ///
2673 /// This method should only be called as part of the paint phase of element drawing.
2674 #[cfg(target_os = "macos")]
2675 pub fn paint_surface(&mut self, bounds: Bounds<Pixels>, image_buffer: CVPixelBuffer) {
2676 use crate::PaintSurface;
2677
2678 self.invalidator.debug_assert_paint();
2679
2680 let scale_factor = self.scale_factor();
2681 let bounds = bounds.scale(scale_factor);
2682 let content_mask = self.content_mask().scale(scale_factor);
2683 self.next_frame.scene.insert_primitive(PaintSurface {
2684 order: 0,
2685 bounds,
2686 content_mask,
2687 image_buffer,
2688 });
2689 }
2690
2691 /// Removes an image from the sprite atlas.
2692 pub fn drop_image(&mut self, data: Arc<RenderImage>) -> Result<()> {
2693 for frame_index in 0..data.frame_count() {
2694 let params = RenderImageParams {
2695 image_id: data.id,
2696 frame_index,
2697 };
2698
2699 self.sprite_atlas.remove(¶ms.clone().into());
2700 }
2701
2702 Ok(())
2703 }
2704
2705 /// Add a node to the layout tree for the current frame. Takes the `Style` of the element for which
2706 /// layout is being requested, along with the layout ids of any children. This method is called during
2707 /// calls to the [`Element::request_layout`] trait method and enables any element to participate in layout.
2708 ///
2709 /// This method should only be called as part of the request_layout or prepaint phase of element drawing.
2710 #[must_use]
2711 pub fn request_layout(
2712 &mut self,
2713 style: Style,
2714 children: impl IntoIterator<Item = LayoutId>,
2715 cx: &mut App,
2716 ) -> LayoutId {
2717 self.invalidator.debug_assert_prepaint();
2718
2719 cx.layout_id_buffer.clear();
2720 cx.layout_id_buffer.extend(children);
2721 let rem_size = self.rem_size();
2722
2723 self.layout_engine
2724 .as_mut()
2725 .unwrap()
2726 .request_layout(style, rem_size, &cx.layout_id_buffer)
2727 }
2728
2729 /// Add a node to the layout tree for the current frame. Instead of taking a `Style` and children,
2730 /// this variant takes a function that is invoked during layout so you can use arbitrary logic to
2731 /// determine the element's size. One place this is used internally is when measuring text.
2732 ///
2733 /// The given closure is invoked at layout time with the known dimensions and available space and
2734 /// returns a `Size`.
2735 ///
2736 /// This method should only be called as part of the request_layout or prepaint phase of element drawing.
2737 pub fn request_measured_layout<
2738 F: FnMut(Size<Option<Pixels>>, Size<AvailableSpace>, &mut Window, &mut App) -> Size<Pixels>
2739 + 'static,
2740 >(
2741 &mut self,
2742 style: Style,
2743 measure: F,
2744 ) -> LayoutId {
2745 self.invalidator.debug_assert_prepaint();
2746
2747 let rem_size = self.rem_size();
2748 self.layout_engine
2749 .as_mut()
2750 .unwrap()
2751 .request_measured_layout(style, rem_size, measure)
2752 }
2753
2754 /// Compute the layout for the given id within the given available space.
2755 /// This method is called for its side effect, typically by the framework prior to painting.
2756 /// After calling it, you can request the bounds of the given layout node id or any descendant.
2757 ///
2758 /// This method should only be called as part of the prepaint phase of element drawing.
2759 pub fn compute_layout(
2760 &mut self,
2761 layout_id: LayoutId,
2762 available_space: Size<AvailableSpace>,
2763 cx: &mut App,
2764 ) {
2765 self.invalidator.debug_assert_prepaint();
2766
2767 let mut layout_engine = self.layout_engine.take().unwrap();
2768 layout_engine.compute_layout(layout_id, available_space, self, cx);
2769 self.layout_engine = Some(layout_engine);
2770 }
2771
2772 /// Obtain the bounds computed for the given LayoutId relative to the window. This method will usually be invoked by
2773 /// GPUI itself automatically in order to pass your element its `Bounds` automatically.
2774 ///
2775 /// This method should only be called as part of element drawing.
2776 pub fn layout_bounds(&mut self, layout_id: LayoutId) -> Bounds<Pixels> {
2777 self.invalidator.debug_assert_prepaint();
2778
2779 let mut bounds = self
2780 .layout_engine
2781 .as_mut()
2782 .unwrap()
2783 .layout_bounds(layout_id)
2784 .map(Into::into);
2785 bounds.origin += self.element_offset();
2786 bounds
2787 }
2788
2789 /// This method should be called during `prepaint`. You can use
2790 /// the returned [Hitbox] during `paint` or in an event handler
2791 /// to determine whether the inserted hitbox was the topmost.
2792 ///
2793 /// This method should only be called as part of the prepaint phase of element drawing.
2794 pub fn insert_hitbox(&mut self, bounds: Bounds<Pixels>, opaque: bool) -> Hitbox {
2795 self.invalidator.debug_assert_prepaint();
2796
2797 let content_mask = self.content_mask();
2798 let id = self.next_hitbox_id;
2799 self.next_hitbox_id.0 += 1;
2800 let hitbox = Hitbox {
2801 id,
2802 bounds,
2803 content_mask,
2804 opaque,
2805 };
2806 self.next_frame.hitboxes.push(hitbox.clone());
2807 hitbox
2808 }
2809
2810 /// Sets the key context for the current element. This context will be used to translate
2811 /// keybindings into actions.
2812 ///
2813 /// This method should only be called as part of the paint phase of element drawing.
2814 pub fn set_key_context(&mut self, context: KeyContext) {
2815 self.invalidator.debug_assert_paint();
2816 self.next_frame.dispatch_tree.set_key_context(context);
2817 }
2818
2819 /// Sets the focus handle for the current element. This handle will be used to manage focus state
2820 /// and keyboard event dispatch for the element.
2821 ///
2822 /// This method should only be called as part of the prepaint phase of element drawing.
2823 pub fn set_focus_handle(&mut self, focus_handle: &FocusHandle, _: &App) {
2824 self.invalidator.debug_assert_prepaint();
2825 if focus_handle.is_focused(self) {
2826 self.next_frame.focus = Some(focus_handle.id);
2827 }
2828 self.next_frame.dispatch_tree.set_focus_id(focus_handle.id);
2829 }
2830
2831 /// Sets the view id for the current element, which will be used to manage view caching.
2832 ///
2833 /// This method should only be called as part of element prepaint. We plan on removing this
2834 /// method eventually when we solve some issues that require us to construct editor elements
2835 /// directly instead of always using editors via views.
2836 pub fn set_view_id(&mut self, view_id: EntityId) {
2837 self.invalidator.debug_assert_prepaint();
2838 self.next_frame.dispatch_tree.set_view_id(view_id);
2839 }
2840
2841 /// Get the entity ID for the currently rendering view
2842 pub fn current_view(&self) -> EntityId {
2843 self.invalidator.debug_assert_paint_or_prepaint();
2844 self.rendered_entity_stack.last().copied().unwrap()
2845 }
2846
2847 pub(crate) fn with_rendered_view<R>(
2848 &mut self,
2849 id: EntityId,
2850 f: impl FnOnce(&mut Self) -> R,
2851 ) -> R {
2852 self.rendered_entity_stack.push(id);
2853 let result = f(self);
2854 self.rendered_entity_stack.pop();
2855 result
2856 }
2857
2858 /// Sets an input handler, such as [`ElementInputHandler`][element_input_handler], which interfaces with the
2859 /// platform to receive textual input with proper integration with concerns such
2860 /// as IME interactions. This handler will be active for the upcoming frame until the following frame is
2861 /// rendered.
2862 ///
2863 /// This method should only be called as part of the paint phase of element drawing.
2864 ///
2865 /// [element_input_handler]: crate::ElementInputHandler
2866 pub fn handle_input(
2867 &mut self,
2868 focus_handle: &FocusHandle,
2869 input_handler: impl InputHandler,
2870 cx: &App,
2871 ) {
2872 self.invalidator.debug_assert_paint();
2873
2874 if focus_handle.is_focused(self) {
2875 let cx = self.to_async(cx);
2876 self.next_frame
2877 .input_handlers
2878 .push(Some(PlatformInputHandler::new(cx, Box::new(input_handler))));
2879 }
2880 }
2881
2882 /// Register a mouse event listener on the window for the next frame. The type of event
2883 /// is determined by the first parameter of the given listener. When the next frame is rendered
2884 /// the listener will be cleared.
2885 ///
2886 /// This method should only be called as part of the paint phase of element drawing.
2887 pub fn on_mouse_event<Event: MouseEvent>(
2888 &mut self,
2889 mut handler: impl FnMut(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
2890 ) {
2891 self.invalidator.debug_assert_paint();
2892
2893 self.next_frame.mouse_listeners.push(Some(Box::new(
2894 move |event: &dyn Any, phase: DispatchPhase, window: &mut Window, cx: &mut App| {
2895 if let Some(event) = event.downcast_ref() {
2896 handler(event, phase, window, cx)
2897 }
2898 },
2899 )));
2900 }
2901
2902 /// Register a key event listener on the window for the next frame. The type of event
2903 /// is determined by the first parameter of the given listener. When the next frame is rendered
2904 /// the listener will be cleared.
2905 ///
2906 /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
2907 /// a specific need to register a global listener.
2908 ///
2909 /// This method should only be called as part of the paint phase of element drawing.
2910 pub fn on_key_event<Event: KeyEvent>(
2911 &mut self,
2912 listener: impl Fn(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
2913 ) {
2914 self.invalidator.debug_assert_paint();
2915
2916 self.next_frame.dispatch_tree.on_key_event(Rc::new(
2917 move |event: &dyn Any, phase, window: &mut Window, cx: &mut App| {
2918 if let Some(event) = event.downcast_ref::<Event>() {
2919 listener(event, phase, window, cx)
2920 }
2921 },
2922 ));
2923 }
2924
2925 /// Register a modifiers changed event listener on the window for the next frame.
2926 ///
2927 /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
2928 /// a specific need to register a global listener.
2929 ///
2930 /// This method should only be called as part of the paint phase of element drawing.
2931 pub fn on_modifiers_changed(
2932 &mut self,
2933 listener: impl Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static,
2934 ) {
2935 self.invalidator.debug_assert_paint();
2936
2937 self.next_frame.dispatch_tree.on_modifiers_changed(Rc::new(
2938 move |event: &ModifiersChangedEvent, window: &mut Window, cx: &mut App| {
2939 listener(event, window, cx)
2940 },
2941 ));
2942 }
2943
2944 /// Register a listener to be called when the given focus handle or one of its descendants receives focus.
2945 /// This does not fire if the given focus handle - or one of its descendants - was previously focused.
2946 /// Returns a subscription and persists until the subscription is dropped.
2947 pub fn on_focus_in(
2948 &mut self,
2949 handle: &FocusHandle,
2950 cx: &mut App,
2951 mut listener: impl FnMut(&mut Window, &mut App) + 'static,
2952 ) -> Subscription {
2953 let focus_id = handle.id;
2954 let (subscription, activate) =
2955 self.new_focus_listener(Box::new(move |event, window, cx| {
2956 if event.is_focus_in(focus_id) {
2957 listener(window, cx);
2958 }
2959 true
2960 }));
2961 cx.defer(move |_| activate());
2962 subscription
2963 }
2964
2965 /// Register a listener to be called when the given focus handle or one of its descendants loses focus.
2966 /// Returns a subscription and persists until the subscription is dropped.
2967 pub fn on_focus_out(
2968 &mut self,
2969 handle: &FocusHandle,
2970 cx: &mut App,
2971 mut listener: impl FnMut(FocusOutEvent, &mut Window, &mut App) + 'static,
2972 ) -> Subscription {
2973 let focus_id = handle.id;
2974 let (subscription, activate) =
2975 self.new_focus_listener(Box::new(move |event, window, cx| {
2976 if let Some(blurred_id) = event.previous_focus_path.last().copied() {
2977 if event.is_focus_out(focus_id) {
2978 let event = FocusOutEvent {
2979 blurred: WeakFocusHandle {
2980 id: blurred_id,
2981 handles: Arc::downgrade(&cx.focus_handles),
2982 },
2983 };
2984 listener(event, window, cx)
2985 }
2986 }
2987 true
2988 }));
2989 cx.defer(move |_| activate());
2990 subscription
2991 }
2992
2993 fn reset_cursor_style(&self, cx: &mut App) {
2994 // Set the cursor only if we're the active window.
2995 if self.is_window_hovered() {
2996 let style = self
2997 .rendered_frame
2998 .cursor_styles
2999 .iter()
3000 .rev()
3001 .find(|request| {
3002 request
3003 .hitbox_id
3004 .map_or(true, |hitbox_id| hitbox_id.is_hovered(self))
3005 })
3006 .map(|request| request.style)
3007 .unwrap_or(CursorStyle::Arrow);
3008 cx.platform.set_cursor_style(style);
3009 }
3010 }
3011
3012 /// Dispatch a given keystroke as though the user had typed it.
3013 /// You can create a keystroke with Keystroke::parse("").
3014 pub fn dispatch_keystroke(&mut self, keystroke: Keystroke, cx: &mut App) -> bool {
3015 let keystroke = keystroke.with_simulated_ime();
3016 let result = self.dispatch_event(
3017 PlatformInput::KeyDown(KeyDownEvent {
3018 keystroke: keystroke.clone(),
3019 is_held: false,
3020 }),
3021 cx,
3022 );
3023 if !result.propagate {
3024 return true;
3025 }
3026
3027 if let Some(input) = keystroke.key_char {
3028 if let Some(mut input_handler) = self.platform_window.take_input_handler() {
3029 input_handler.dispatch_input(&input, self, cx);
3030 self.platform_window.set_input_handler(input_handler);
3031 return true;
3032 }
3033 }
3034
3035 false
3036 }
3037
3038 /// Return a key binding string for an action, to display in the UI. Uses the highest precedence
3039 /// binding for the action (last binding added to the keymap).
3040 pub fn keystroke_text_for(&self, action: &dyn Action) -> String {
3041 self.bindings_for_action(action)
3042 .last()
3043 .map(|binding| {
3044 binding
3045 .keystrokes()
3046 .iter()
3047 .map(ToString::to_string)
3048 .collect::<Vec<_>>()
3049 .join(" ")
3050 })
3051 .unwrap_or_else(|| action.name().to_string())
3052 }
3053
3054 /// Dispatch a mouse or keyboard event on the window.
3055 #[profiling::function]
3056 pub fn dispatch_event(&mut self, event: PlatformInput, cx: &mut App) -> DispatchEventResult {
3057 self.last_input_timestamp.set(Instant::now());
3058 // Handlers may set this to false by calling `stop_propagation`.
3059 cx.propagate_event = true;
3060 // Handlers may set this to true by calling `prevent_default`.
3061 self.default_prevented = false;
3062
3063 let event = match event {
3064 // Track the mouse position with our own state, since accessing the platform
3065 // API for the mouse position can only occur on the main thread.
3066 PlatformInput::MouseMove(mouse_move) => {
3067 self.mouse_position = mouse_move.position;
3068 self.modifiers = mouse_move.modifiers;
3069 PlatformInput::MouseMove(mouse_move)
3070 }
3071 PlatformInput::MouseDown(mouse_down) => {
3072 self.mouse_position = mouse_down.position;
3073 self.modifiers = mouse_down.modifiers;
3074 PlatformInput::MouseDown(mouse_down)
3075 }
3076 PlatformInput::MouseUp(mouse_up) => {
3077 self.mouse_position = mouse_up.position;
3078 self.modifiers = mouse_up.modifiers;
3079 PlatformInput::MouseUp(mouse_up)
3080 }
3081 PlatformInput::MouseExited(mouse_exited) => {
3082 self.modifiers = mouse_exited.modifiers;
3083 PlatformInput::MouseExited(mouse_exited)
3084 }
3085 PlatformInput::ModifiersChanged(modifiers_changed) => {
3086 self.modifiers = modifiers_changed.modifiers;
3087 PlatformInput::ModifiersChanged(modifiers_changed)
3088 }
3089 PlatformInput::ScrollWheel(scroll_wheel) => {
3090 self.mouse_position = scroll_wheel.position;
3091 self.modifiers = scroll_wheel.modifiers;
3092 PlatformInput::ScrollWheel(scroll_wheel)
3093 }
3094 // Translate dragging and dropping of external files from the operating system
3095 // to internal drag and drop events.
3096 PlatformInput::FileDrop(file_drop) => match file_drop {
3097 FileDropEvent::Entered { position, paths } => {
3098 self.mouse_position = position;
3099 if cx.active_drag.is_none() {
3100 cx.active_drag = Some(AnyDrag {
3101 value: Arc::new(paths.clone()),
3102 view: cx.new(|_| paths).into(),
3103 cursor_offset: position,
3104 cursor_style: None,
3105 });
3106 }
3107 PlatformInput::MouseMove(MouseMoveEvent {
3108 position,
3109 pressed_button: Some(MouseButton::Left),
3110 modifiers: Modifiers::default(),
3111 })
3112 }
3113 FileDropEvent::Pending { position } => {
3114 self.mouse_position = position;
3115 PlatformInput::MouseMove(MouseMoveEvent {
3116 position,
3117 pressed_button: Some(MouseButton::Left),
3118 modifiers: Modifiers::default(),
3119 })
3120 }
3121 FileDropEvent::Submit { position } => {
3122 cx.activate(true);
3123 self.mouse_position = position;
3124 PlatformInput::MouseUp(MouseUpEvent {
3125 button: MouseButton::Left,
3126 position,
3127 modifiers: Modifiers::default(),
3128 click_count: 1,
3129 })
3130 }
3131 FileDropEvent::Exited => {
3132 cx.active_drag.take();
3133 PlatformInput::FileDrop(FileDropEvent::Exited)
3134 }
3135 },
3136 PlatformInput::KeyDown(_) | PlatformInput::KeyUp(_) => event,
3137 };
3138
3139 if let Some(any_mouse_event) = event.mouse_event() {
3140 self.dispatch_mouse_event(any_mouse_event, cx);
3141 } else if let Some(any_key_event) = event.keyboard_event() {
3142 self.dispatch_key_event(any_key_event, cx);
3143 }
3144
3145 DispatchEventResult {
3146 propagate: cx.propagate_event,
3147 default_prevented: self.default_prevented,
3148 }
3149 }
3150
3151 fn dispatch_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
3152 let hit_test = self.rendered_frame.hit_test(self.mouse_position());
3153 if hit_test != self.mouse_hit_test {
3154 self.mouse_hit_test = hit_test;
3155 self.reset_cursor_style(cx);
3156 }
3157
3158 let mut mouse_listeners = mem::take(&mut self.rendered_frame.mouse_listeners);
3159
3160 // Capture phase, events bubble from back to front. Handlers for this phase are used for
3161 // special purposes, such as detecting events outside of a given Bounds.
3162 for listener in &mut mouse_listeners {
3163 let listener = listener.as_mut().unwrap();
3164 listener(event, DispatchPhase::Capture, self, cx);
3165 if !cx.propagate_event {
3166 break;
3167 }
3168 }
3169
3170 // Bubble phase, where most normal handlers do their work.
3171 if cx.propagate_event {
3172 for listener in mouse_listeners.iter_mut().rev() {
3173 let listener = listener.as_mut().unwrap();
3174 listener(event, DispatchPhase::Bubble, self, cx);
3175 if !cx.propagate_event {
3176 break;
3177 }
3178 }
3179 }
3180
3181 self.rendered_frame.mouse_listeners = mouse_listeners;
3182
3183 if cx.has_active_drag() {
3184 if event.is::<MouseMoveEvent>() {
3185 // If this was a mouse move event, redraw the window so that the
3186 // active drag can follow the mouse cursor.
3187 self.refresh();
3188 } else if event.is::<MouseUpEvent>() {
3189 // If this was a mouse up event, cancel the active drag and redraw
3190 // the window.
3191 cx.active_drag = None;
3192 self.refresh();
3193 }
3194 }
3195 }
3196
3197 fn dispatch_key_event(&mut self, event: &dyn Any, cx: &mut App) {
3198 if self.invalidator.is_dirty() {
3199 self.draw(cx);
3200 }
3201
3202 let node_id = self
3203 .focus
3204 .and_then(|focus_id| {
3205 self.rendered_frame
3206 .dispatch_tree
3207 .focusable_node_id(focus_id)
3208 })
3209 .unwrap_or_else(|| self.rendered_frame.dispatch_tree.root_node_id());
3210
3211 let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
3212
3213 let mut keystroke: Option<Keystroke> = None;
3214
3215 if let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() {
3216 if event.modifiers.number_of_modifiers() == 0
3217 && self.pending_modifier.modifiers.number_of_modifiers() == 1
3218 && !self.pending_modifier.saw_keystroke
3219 {
3220 let key = match self.pending_modifier.modifiers {
3221 modifiers if modifiers.shift => Some("shift"),
3222 modifiers if modifiers.control => Some("control"),
3223 modifiers if modifiers.alt => Some("alt"),
3224 modifiers if modifiers.platform => Some("platform"),
3225 modifiers if modifiers.function => Some("function"),
3226 _ => None,
3227 };
3228 if let Some(key) = key {
3229 keystroke = Some(Keystroke {
3230 key: key.to_string(),
3231 key_char: None,
3232 modifiers: Modifiers::default(),
3233 });
3234 }
3235 }
3236
3237 if self.pending_modifier.modifiers.number_of_modifiers() == 0
3238 && event.modifiers.number_of_modifiers() == 1
3239 {
3240 self.pending_modifier.saw_keystroke = false
3241 }
3242 self.pending_modifier.modifiers = event.modifiers
3243 } else if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
3244 self.pending_modifier.saw_keystroke = true;
3245 keystroke = Some(key_down_event.keystroke.clone());
3246 }
3247
3248 let Some(keystroke) = keystroke else {
3249 self.finish_dispatch_key_event(event, dispatch_path, cx);
3250 return;
3251 };
3252
3253 let mut currently_pending = self.pending_input.take().unwrap_or_default();
3254 if currently_pending.focus.is_some() && currently_pending.focus != self.focus {
3255 currently_pending = PendingInput::default();
3256 }
3257
3258 let match_result = self.rendered_frame.dispatch_tree.dispatch_key(
3259 currently_pending.keystrokes,
3260 keystroke,
3261 &dispatch_path,
3262 );
3263
3264 if !match_result.to_replay.is_empty() {
3265 self.replay_pending_input(match_result.to_replay, cx)
3266 }
3267
3268 if !match_result.pending.is_empty() {
3269 currently_pending.keystrokes = match_result.pending;
3270 currently_pending.focus = self.focus;
3271 currently_pending.timer = Some(self.spawn(cx, async move |cx| {
3272 cx.background_executor.timer(Duration::from_secs(1)).await;
3273 cx.update(move |window, cx| {
3274 let Some(currently_pending) = window
3275 .pending_input
3276 .take()
3277 .filter(|pending| pending.focus == window.focus)
3278 else {
3279 return;
3280 };
3281
3282 let dispatch_path = window.rendered_frame.dispatch_tree.dispatch_path(node_id);
3283
3284 let to_replay = window
3285 .rendered_frame
3286 .dispatch_tree
3287 .flush_dispatch(currently_pending.keystrokes, &dispatch_path);
3288
3289 window.replay_pending_input(to_replay, cx)
3290 })
3291 .log_err();
3292 }));
3293 self.pending_input = Some(currently_pending);
3294 self.pending_input_changed(cx);
3295 cx.propagate_event = false;
3296 return;
3297 }
3298
3299 cx.propagate_event = true;
3300 for binding in match_result.bindings {
3301 self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
3302 if !cx.propagate_event {
3303 self.dispatch_keystroke_observers(event, Some(binding.action), cx);
3304 self.pending_input_changed(cx);
3305 return;
3306 }
3307 }
3308
3309 self.finish_dispatch_key_event(event, dispatch_path, cx);
3310 self.pending_input_changed(cx);
3311 }
3312
3313 fn finish_dispatch_key_event(
3314 &mut self,
3315 event: &dyn Any,
3316 dispatch_path: SmallVec<[DispatchNodeId; 32]>,
3317 cx: &mut App,
3318 ) {
3319 self.dispatch_key_down_up_event(event, &dispatch_path, cx);
3320 if !cx.propagate_event {
3321 return;
3322 }
3323
3324 self.dispatch_modifiers_changed_event(event, &dispatch_path, cx);
3325 if !cx.propagate_event {
3326 return;
3327 }
3328
3329 self.dispatch_keystroke_observers(event, None, cx);
3330 }
3331
3332 fn pending_input_changed(&mut self, cx: &mut App) {
3333 self.pending_input_observers
3334 .clone()
3335 .retain(&(), |callback| callback(self, cx));
3336 }
3337
3338 fn dispatch_key_down_up_event(
3339 &mut self,
3340 event: &dyn Any,
3341 dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
3342 cx: &mut App,
3343 ) {
3344 // Capture phase
3345 for node_id in dispatch_path {
3346 let node = self.rendered_frame.dispatch_tree.node(*node_id);
3347
3348 for key_listener in node.key_listeners.clone() {
3349 key_listener(event, DispatchPhase::Capture, self, cx);
3350 if !cx.propagate_event {
3351 return;
3352 }
3353 }
3354 }
3355
3356 // Bubble phase
3357 for node_id in dispatch_path.iter().rev() {
3358 // Handle low level key events
3359 let node = self.rendered_frame.dispatch_tree.node(*node_id);
3360 for key_listener in node.key_listeners.clone() {
3361 key_listener(event, DispatchPhase::Bubble, self, cx);
3362 if !cx.propagate_event {
3363 return;
3364 }
3365 }
3366 }
3367 }
3368
3369 fn dispatch_modifiers_changed_event(
3370 &mut self,
3371 event: &dyn Any,
3372 dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
3373 cx: &mut App,
3374 ) {
3375 let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() else {
3376 return;
3377 };
3378 for node_id in dispatch_path.iter().rev() {
3379 let node = self.rendered_frame.dispatch_tree.node(*node_id);
3380 for listener in node.modifiers_changed_listeners.clone() {
3381 listener(event, self, cx);
3382 if !cx.propagate_event {
3383 return;
3384 }
3385 }
3386 }
3387 }
3388
3389 /// Determine whether a potential multi-stroke key binding is in progress on this window.
3390 pub fn has_pending_keystrokes(&self) -> bool {
3391 self.pending_input.is_some()
3392 }
3393
3394 pub(crate) fn clear_pending_keystrokes(&mut self) {
3395 self.pending_input.take();
3396 }
3397
3398 /// Returns the currently pending input keystrokes that might result in a multi-stroke key binding.
3399 pub fn pending_input_keystrokes(&self) -> Option<&[Keystroke]> {
3400 self.pending_input
3401 .as_ref()
3402 .map(|pending_input| pending_input.keystrokes.as_slice())
3403 }
3404
3405 fn replay_pending_input(&mut self, replays: SmallVec<[Replay; 1]>, cx: &mut App) {
3406 let node_id = self
3407 .focus
3408 .and_then(|focus_id| {
3409 self.rendered_frame
3410 .dispatch_tree
3411 .focusable_node_id(focus_id)
3412 })
3413 .unwrap_or_else(|| self.rendered_frame.dispatch_tree.root_node_id());
3414
3415 let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
3416
3417 'replay: for replay in replays {
3418 let event = KeyDownEvent {
3419 keystroke: replay.keystroke.clone(),
3420 is_held: false,
3421 };
3422
3423 cx.propagate_event = true;
3424 for binding in replay.bindings {
3425 self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
3426 if !cx.propagate_event {
3427 self.dispatch_keystroke_observers(&event, Some(binding.action), cx);
3428 continue 'replay;
3429 }
3430 }
3431
3432 self.dispatch_key_down_up_event(&event, &dispatch_path, cx);
3433 if !cx.propagate_event {
3434 continue 'replay;
3435 }
3436 if let Some(input) = replay.keystroke.key_char.as_ref().cloned() {
3437 if let Some(mut input_handler) = self.platform_window.take_input_handler() {
3438 input_handler.dispatch_input(&input, self, cx);
3439 self.platform_window.set_input_handler(input_handler)
3440 }
3441 }
3442 }
3443 }
3444
3445 fn dispatch_action_on_node(
3446 &mut self,
3447 node_id: DispatchNodeId,
3448 action: &dyn Action,
3449 cx: &mut App,
3450 ) {
3451 let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
3452
3453 // Capture phase for global actions.
3454 cx.propagate_event = true;
3455 if let Some(mut global_listeners) = cx
3456 .global_action_listeners
3457 .remove(&action.as_any().type_id())
3458 {
3459 for listener in &global_listeners {
3460 listener(action.as_any(), DispatchPhase::Capture, cx);
3461 if !cx.propagate_event {
3462 break;
3463 }
3464 }
3465
3466 global_listeners.extend(
3467 cx.global_action_listeners
3468 .remove(&action.as_any().type_id())
3469 .unwrap_or_default(),
3470 );
3471
3472 cx.global_action_listeners
3473 .insert(action.as_any().type_id(), global_listeners);
3474 }
3475
3476 if !cx.propagate_event {
3477 return;
3478 }
3479
3480 // Capture phase for window actions.
3481 for node_id in &dispatch_path {
3482 let node = self.rendered_frame.dispatch_tree.node(*node_id);
3483 for DispatchActionListener {
3484 action_type,
3485 listener,
3486 } in node.action_listeners.clone()
3487 {
3488 let any_action = action.as_any();
3489 if action_type == any_action.type_id() {
3490 listener(any_action, DispatchPhase::Capture, self, cx);
3491
3492 if !cx.propagate_event {
3493 return;
3494 }
3495 }
3496 }
3497 }
3498
3499 // Bubble phase for window actions.
3500 for node_id in dispatch_path.iter().rev() {
3501 let node = self.rendered_frame.dispatch_tree.node(*node_id);
3502 for DispatchActionListener {
3503 action_type,
3504 listener,
3505 } in node.action_listeners.clone()
3506 {
3507 let any_action = action.as_any();
3508 if action_type == any_action.type_id() {
3509 cx.propagate_event = false; // Actions stop propagation by default during the bubble phase
3510 listener(any_action, DispatchPhase::Bubble, self, cx);
3511
3512 if !cx.propagate_event {
3513 return;
3514 }
3515 }
3516 }
3517 }
3518
3519 // Bubble phase for global actions.
3520 if let Some(mut global_listeners) = cx
3521 .global_action_listeners
3522 .remove(&action.as_any().type_id())
3523 {
3524 for listener in global_listeners.iter().rev() {
3525 cx.propagate_event = false; // Actions stop propagation by default during the bubble phase
3526
3527 listener(action.as_any(), DispatchPhase::Bubble, cx);
3528 if !cx.propagate_event {
3529 break;
3530 }
3531 }
3532
3533 global_listeners.extend(
3534 cx.global_action_listeners
3535 .remove(&action.as_any().type_id())
3536 .unwrap_or_default(),
3537 );
3538
3539 cx.global_action_listeners
3540 .insert(action.as_any().type_id(), global_listeners);
3541 }
3542 }
3543
3544 /// Register the given handler to be invoked whenever the global of the given type
3545 /// is updated.
3546 pub fn observe_global<G: Global>(
3547 &mut self,
3548 cx: &mut App,
3549 f: impl Fn(&mut Window, &mut App) + 'static,
3550 ) -> Subscription {
3551 let window_handle = self.handle;
3552 let (subscription, activate) = cx.global_observers.insert(
3553 TypeId::of::<G>(),
3554 Box::new(move |cx| {
3555 window_handle
3556 .update(cx, |_, window, cx| f(window, cx))
3557 .is_ok()
3558 }),
3559 );
3560 cx.defer(move |_| activate());
3561 subscription
3562 }
3563
3564 /// Focus the current window and bring it to the foreground at the platform level.
3565 pub fn activate_window(&self) {
3566 self.platform_window.activate();
3567 }
3568
3569 /// Minimize the current window at the platform level.
3570 pub fn minimize_window(&self) {
3571 self.platform_window.minimize();
3572 }
3573
3574 /// Toggle full screen status on the current window at the platform level.
3575 pub fn toggle_fullscreen(&self) {
3576 self.platform_window.toggle_fullscreen();
3577 }
3578
3579 /// Updates the IME panel position suggestions for languages like japanese, chinese.
3580 pub fn invalidate_character_coordinates(&self) {
3581 self.on_next_frame(|window, cx| {
3582 if let Some(mut input_handler) = window.platform_window.take_input_handler() {
3583 if let Some(bounds) = input_handler.selected_bounds(window, cx) {
3584 window
3585 .platform_window
3586 .update_ime_position(bounds.scale(window.scale_factor()));
3587 }
3588 window.platform_window.set_input_handler(input_handler);
3589 }
3590 });
3591 }
3592
3593 /// Present a platform dialog.
3594 /// The provided message will be presented, along with buttons for each answer.
3595 /// When a button is clicked, the returned Receiver will receive the index of the clicked button.
3596 pub fn prompt(
3597 &mut self,
3598 level: PromptLevel,
3599 message: &str,
3600 detail: Option<&str>,
3601 answers: &[&str],
3602 cx: &mut App,
3603 ) -> oneshot::Receiver<usize> {
3604 let prompt_builder = cx.prompt_builder.take();
3605 let Some(prompt_builder) = prompt_builder else {
3606 unreachable!("Re-entrant window prompting is not supported by GPUI");
3607 };
3608
3609 let receiver = match &prompt_builder {
3610 PromptBuilder::Default => self
3611 .platform_window
3612 .prompt(level, message, detail, answers)
3613 .unwrap_or_else(|| {
3614 self.build_custom_prompt(&prompt_builder, level, message, detail, answers, cx)
3615 }),
3616 PromptBuilder::Custom(_) => {
3617 self.build_custom_prompt(&prompt_builder, level, message, detail, answers, cx)
3618 }
3619 };
3620
3621 cx.prompt_builder = Some(prompt_builder);
3622
3623 receiver
3624 }
3625
3626 fn build_custom_prompt(
3627 &mut self,
3628 prompt_builder: &PromptBuilder,
3629 level: PromptLevel,
3630 message: &str,
3631 detail: Option<&str>,
3632 answers: &[&str],
3633 cx: &mut App,
3634 ) -> oneshot::Receiver<usize> {
3635 let (sender, receiver) = oneshot::channel();
3636 let handle = PromptHandle::new(sender);
3637 let handle = (prompt_builder)(level, message, detail, answers, handle, self, cx);
3638 self.prompt = Some(handle);
3639 receiver
3640 }
3641
3642 /// Returns the current context stack.
3643 pub fn context_stack(&self) -> Vec<KeyContext> {
3644 let dispatch_tree = &self.rendered_frame.dispatch_tree;
3645 let node_id = self
3646 .focus
3647 .and_then(|focus_id| dispatch_tree.focusable_node_id(focus_id))
3648 .unwrap_or_else(|| dispatch_tree.root_node_id());
3649
3650 dispatch_tree
3651 .dispatch_path(node_id)
3652 .iter()
3653 .filter_map(move |&node_id| dispatch_tree.node(node_id).context.clone())
3654 .collect()
3655 }
3656
3657 /// Returns all available actions for the focused element.
3658 pub fn available_actions(&self, cx: &App) -> Vec<Box<dyn Action>> {
3659 let node_id = self
3660 .focus
3661 .and_then(|focus_id| {
3662 self.rendered_frame
3663 .dispatch_tree
3664 .focusable_node_id(focus_id)
3665 })
3666 .unwrap_or_else(|| self.rendered_frame.dispatch_tree.root_node_id());
3667
3668 let mut actions = self.rendered_frame.dispatch_tree.available_actions(node_id);
3669 for action_type in cx.global_action_listeners.keys() {
3670 if let Err(ix) = actions.binary_search_by_key(action_type, |a| a.as_any().type_id()) {
3671 let action = cx.actions.build_action_type(action_type).ok();
3672 if let Some(action) = action {
3673 actions.insert(ix, action);
3674 }
3675 }
3676 }
3677 actions
3678 }
3679
3680 /// Returns key bindings that invoke an action on the currently focused element. Bindings are
3681 /// returned in the order they were added. For display, the last binding should take precedence.
3682 pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
3683 self.rendered_frame
3684 .dispatch_tree
3685 .bindings_for_action(action, &self.rendered_frame.dispatch_tree.context_stack)
3686 }
3687
3688 /// Returns any bindings that would invoke an action on the given focus handle if it were
3689 /// focused. Bindings are returned in the order they were added. For display, the last binding
3690 /// should take precedence.
3691 pub fn bindings_for_action_in(
3692 &self,
3693 action: &dyn Action,
3694 focus_handle: &FocusHandle,
3695 ) -> Vec<KeyBinding> {
3696 let dispatch_tree = &self.rendered_frame.dispatch_tree;
3697
3698 let Some(node_id) = dispatch_tree.focusable_node_id(focus_handle.id) else {
3699 return vec![];
3700 };
3701 let context_stack: Vec<_> = dispatch_tree
3702 .dispatch_path(node_id)
3703 .into_iter()
3704 .filter_map(|node_id| dispatch_tree.node(node_id).context.clone())
3705 .collect();
3706 dispatch_tree.bindings_for_action(action, &context_stack)
3707 }
3708
3709 /// Returns the key bindings for the given action in the given context.
3710 pub fn bindings_for_action_in_context(
3711 &self,
3712 action: &dyn Action,
3713 context: KeyContext,
3714 ) -> Vec<KeyBinding> {
3715 let dispatch_tree = &self.rendered_frame.dispatch_tree;
3716 dispatch_tree.bindings_for_action(action, &[context])
3717 }
3718
3719 /// Returns a generic event listener that invokes the given listener with the view and context associated with the given view handle.
3720 pub fn listener_for<V: Render, E>(
3721 &self,
3722 view: &Entity<V>,
3723 f: impl Fn(&mut V, &E, &mut Window, &mut Context<V>) + 'static,
3724 ) -> impl Fn(&E, &mut Window, &mut App) + 'static {
3725 let view = view.downgrade();
3726 move |e: &E, window: &mut Window, cx: &mut App| {
3727 view.update(cx, |view, cx| f(view, e, window, cx)).ok();
3728 }
3729 }
3730
3731 /// Returns a generic handler that invokes the given handler with the view and context associated with the given view handle.
3732 pub fn handler_for<V: Render, Callback: Fn(&mut V, &mut Window, &mut Context<V>) + 'static>(
3733 &self,
3734 view: &Entity<V>,
3735 f: Callback,
3736 ) -> impl Fn(&mut Window, &mut App) + use<V, Callback> {
3737 let view = view.downgrade();
3738 move |window: &mut Window, cx: &mut App| {
3739 view.update(cx, |view, cx| f(view, window, cx)).ok();
3740 }
3741 }
3742
3743 /// Register a callback that can interrupt the closing of the current window based the returned boolean.
3744 /// If the callback returns false, the window won't be closed.
3745 pub fn on_window_should_close(
3746 &self,
3747 cx: &App,
3748 f: impl Fn(&mut Window, &mut App) -> bool + 'static,
3749 ) {
3750 let mut cx = self.to_async(cx);
3751 self.platform_window.on_should_close(Box::new(move || {
3752 cx.update(|window, cx| f(window, cx)).unwrap_or(true)
3753 }))
3754 }
3755
3756 /// Register an action listener on the window for the next frame. The type of action
3757 /// is determined by the first parameter of the given listener. When the next frame is rendered
3758 /// the listener will be cleared.
3759 ///
3760 /// This is a fairly low-level method, so prefer using action handlers on elements unless you have
3761 /// a specific need to register a global listener.
3762 pub fn on_action(
3763 &mut self,
3764 action_type: TypeId,
3765 listener: impl Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static,
3766 ) {
3767 self.next_frame
3768 .dispatch_tree
3769 .on_action(action_type, Rc::new(listener));
3770 }
3771
3772 /// Read information about the GPU backing this window.
3773 /// Currently returns None on Mac and Windows.
3774 pub fn gpu_specs(&self) -> Option<GpuSpecs> {
3775 self.platform_window.gpu_specs()
3776 }
3777}
3778
3779// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
3780slotmap::new_key_type! {
3781 /// A unique identifier for a window.
3782 pub struct WindowId;
3783}
3784
3785impl WindowId {
3786 /// Converts this window ID to a `u64`.
3787 pub fn as_u64(&self) -> u64 {
3788 self.0.as_ffi()
3789 }
3790}
3791
3792impl From<u64> for WindowId {
3793 fn from(value: u64) -> Self {
3794 WindowId(slotmap::KeyData::from_ffi(value))
3795 }
3796}
3797
3798/// A handle to a window with a specific root view type.
3799/// Note that this does not keep the window alive on its own.
3800#[derive(Deref, DerefMut)]
3801pub struct WindowHandle<V> {
3802 #[deref]
3803 #[deref_mut]
3804 pub(crate) any_handle: AnyWindowHandle,
3805 state_type: PhantomData<V>,
3806}
3807
3808impl<V: 'static + Render> WindowHandle<V> {
3809 /// Creates a new handle from a window ID.
3810 /// This does not check if the root type of the window is `V`.
3811 pub fn new(id: WindowId) -> Self {
3812 WindowHandle {
3813 any_handle: AnyWindowHandle {
3814 id,
3815 state_type: TypeId::of::<V>(),
3816 },
3817 state_type: PhantomData,
3818 }
3819 }
3820
3821 /// Get the root view out of this window.
3822 ///
3823 /// This will fail if the window is closed or if the root view's type does not match `V`.
3824 #[cfg(any(test, feature = "test-support"))]
3825 pub fn root<C>(&self, cx: &mut C) -> Result<Entity<V>>
3826 where
3827 C: AppContext,
3828 {
3829 crate::Flatten::flatten(cx.update_window(self.any_handle, |root_view, _, _| {
3830 root_view
3831 .downcast::<V>()
3832 .map_err(|_| anyhow!("the type of the window's root view has changed"))
3833 }))
3834 }
3835
3836 /// Updates the root view of this window.
3837 ///
3838 /// This will fail if the window has been closed or if the root view's type does not match
3839 pub fn update<C, R>(
3840 &self,
3841 cx: &mut C,
3842 update: impl FnOnce(&mut V, &mut Window, &mut Context<V>) -> R,
3843 ) -> Result<R>
3844 where
3845 C: AppContext,
3846 {
3847 cx.update_window(self.any_handle, |root_view, window, cx| {
3848 let view = root_view
3849 .downcast::<V>()
3850 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
3851
3852 Ok(view.update(cx, |view, cx| update(view, window, cx)))
3853 })?
3854 }
3855
3856 /// Read the root view out of this window.
3857 ///
3858 /// This will fail if the window is closed or if the root view's type does not match `V`.
3859 pub fn read<'a>(&self, cx: &'a App) -> Result<&'a V> {
3860 let x = cx
3861 .windows
3862 .get(self.id)
3863 .and_then(|window| {
3864 window
3865 .as_ref()
3866 .and_then(|window| window.root.clone())
3867 .map(|root_view| root_view.downcast::<V>())
3868 })
3869 .ok_or_else(|| anyhow!("window not found"))?
3870 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
3871
3872 Ok(x.read(cx))
3873 }
3874
3875 /// Read the root view out of this window, with a callback
3876 ///
3877 /// This will fail if the window is closed or if the root view's type does not match `V`.
3878 pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &App) -> R) -> Result<R>
3879 where
3880 C: AppContext,
3881 {
3882 cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
3883 }
3884
3885 /// Read the root view pointer off of this window.
3886 ///
3887 /// This will fail if the window is closed or if the root view's type does not match `V`.
3888 pub fn entity<C>(&self, cx: &C) -> Result<Entity<V>>
3889 where
3890 C: AppContext,
3891 {
3892 cx.read_window(self, |root_view, _cx| root_view.clone())
3893 }
3894
3895 /// Check if this window is 'active'.
3896 ///
3897 /// Will return `None` if the window is closed or currently
3898 /// borrowed.
3899 pub fn is_active(&self, cx: &mut App) -> Option<bool> {
3900 cx.update_window(self.any_handle, |_, window, _| window.is_window_active())
3901 .ok()
3902 }
3903}
3904
3905impl<V> Copy for WindowHandle<V> {}
3906
3907impl<V> Clone for WindowHandle<V> {
3908 fn clone(&self) -> Self {
3909 *self
3910 }
3911}
3912
3913impl<V> PartialEq for WindowHandle<V> {
3914 fn eq(&self, other: &Self) -> bool {
3915 self.any_handle == other.any_handle
3916 }
3917}
3918
3919impl<V> Eq for WindowHandle<V> {}
3920
3921impl<V> Hash for WindowHandle<V> {
3922 fn hash<H: Hasher>(&self, state: &mut H) {
3923 self.any_handle.hash(state);
3924 }
3925}
3926
3927impl<V: 'static> From<WindowHandle<V>> for AnyWindowHandle {
3928 fn from(val: WindowHandle<V>) -> Self {
3929 val.any_handle
3930 }
3931}
3932
3933unsafe impl<V> Send for WindowHandle<V> {}
3934unsafe impl<V> Sync for WindowHandle<V> {}
3935
3936/// A handle to a window with any root view type, which can be downcast to a window with a specific root view type.
3937#[derive(Copy, Clone, PartialEq, Eq, Hash)]
3938pub struct AnyWindowHandle {
3939 pub(crate) id: WindowId,
3940 state_type: TypeId,
3941}
3942
3943impl AnyWindowHandle {
3944 /// Get the ID of this window.
3945 pub fn window_id(&self) -> WindowId {
3946 self.id
3947 }
3948
3949 /// Attempt to convert this handle to a window handle with a specific root view type.
3950 /// If the types do not match, this will return `None`.
3951 pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
3952 if TypeId::of::<T>() == self.state_type {
3953 Some(WindowHandle {
3954 any_handle: *self,
3955 state_type: PhantomData,
3956 })
3957 } else {
3958 None
3959 }
3960 }
3961
3962 /// Updates the state of the root view of this window.
3963 ///
3964 /// This will fail if the window has been closed.
3965 pub fn update<C, R>(
3966 self,
3967 cx: &mut C,
3968 update: impl FnOnce(AnyView, &mut Window, &mut App) -> R,
3969 ) -> Result<R>
3970 where
3971 C: AppContext,
3972 {
3973 cx.update_window(self, update)
3974 }
3975
3976 /// Read the state of the root view of this window.
3977 ///
3978 /// This will fail if the window has been closed.
3979 pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(Entity<T>, &App) -> R) -> Result<R>
3980 where
3981 C: AppContext,
3982 T: 'static,
3983 {
3984 let view = self
3985 .downcast::<T>()
3986 .context("the type of the window's root view has changed")?;
3987
3988 cx.read_window(&view, read)
3989 }
3990}
3991
3992impl HasWindowHandle for Window {
3993 fn window_handle(&self) -> Result<raw_window_handle::WindowHandle<'_>, HandleError> {
3994 self.platform_window.window_handle()
3995 }
3996}
3997
3998/// An identifier for an [`Element`](crate::Element).
3999///
4000/// Can be constructed with a string, a number, or both, as well
4001/// as other internal representations.
4002#[derive(Clone, Debug, Eq, PartialEq, Hash)]
4003pub enum ElementId {
4004 /// The ID of a View element
4005 View(EntityId),
4006 /// An integer ID.
4007 Integer(usize),
4008 /// A string based ID.
4009 Name(SharedString),
4010 /// A UUID.
4011 Uuid(Uuid),
4012 /// An ID that's equated with a focus handle.
4013 FocusHandle(FocusId),
4014 /// A combination of a name and an integer.
4015 NamedInteger(SharedString, usize),
4016 /// A path
4017 Path(Arc<std::path::Path>),
4018}
4019
4020impl Display for ElementId {
4021 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4022 match self {
4023 ElementId::View(entity_id) => write!(f, "view-{}", entity_id)?,
4024 ElementId::Integer(ix) => write!(f, "{}", ix)?,
4025 ElementId::Name(name) => write!(f, "{}", name)?,
4026 ElementId::FocusHandle(_) => write!(f, "FocusHandle")?,
4027 ElementId::NamedInteger(s, i) => write!(f, "{}-{}", s, i)?,
4028 ElementId::Uuid(uuid) => write!(f, "{}", uuid)?,
4029 ElementId::Path(path) => write!(f, "{}", path.display())?,
4030 }
4031
4032 Ok(())
4033 }
4034}
4035
4036impl TryInto<SharedString> for ElementId {
4037 type Error = anyhow::Error;
4038
4039 fn try_into(self) -> anyhow::Result<SharedString> {
4040 if let ElementId::Name(name) = self {
4041 Ok(name)
4042 } else {
4043 Err(anyhow!("element id is not string"))
4044 }
4045 }
4046}
4047
4048impl From<usize> for ElementId {
4049 fn from(id: usize) -> Self {
4050 ElementId::Integer(id)
4051 }
4052}
4053
4054impl From<i32> for ElementId {
4055 fn from(id: i32) -> Self {
4056 Self::Integer(id as usize)
4057 }
4058}
4059
4060impl From<SharedString> for ElementId {
4061 fn from(name: SharedString) -> Self {
4062 ElementId::Name(name)
4063 }
4064}
4065
4066impl From<Arc<std::path::Path>> for ElementId {
4067 fn from(path: Arc<std::path::Path>) -> Self {
4068 ElementId::Path(path)
4069 }
4070}
4071
4072impl From<&'static str> for ElementId {
4073 fn from(name: &'static str) -> Self {
4074 ElementId::Name(name.into())
4075 }
4076}
4077
4078impl<'a> From<&'a FocusHandle> for ElementId {
4079 fn from(handle: &'a FocusHandle) -> Self {
4080 ElementId::FocusHandle(handle.id)
4081 }
4082}
4083
4084impl From<(&'static str, EntityId)> for ElementId {
4085 fn from((name, id): (&'static str, EntityId)) -> Self {
4086 ElementId::NamedInteger(name.into(), id.as_u64() as usize)
4087 }
4088}
4089
4090impl From<(&'static str, usize)> for ElementId {
4091 fn from((name, id): (&'static str, usize)) -> Self {
4092 ElementId::NamedInteger(name.into(), id)
4093 }
4094}
4095
4096impl From<(SharedString, usize)> for ElementId {
4097 fn from((name, id): (SharedString, usize)) -> Self {
4098 ElementId::NamedInteger(name, id)
4099 }
4100}
4101
4102impl From<(&'static str, u64)> for ElementId {
4103 fn from((name, id): (&'static str, u64)) -> Self {
4104 ElementId::NamedInteger(name.into(), id as usize)
4105 }
4106}
4107
4108impl From<Uuid> for ElementId {
4109 fn from(value: Uuid) -> Self {
4110 Self::Uuid(value)
4111 }
4112}
4113
4114impl From<(&'static str, u32)> for ElementId {
4115 fn from((name, id): (&'static str, u32)) -> Self {
4116 ElementId::NamedInteger(name.into(), id as usize)
4117 }
4118}
4119
4120/// A rectangle to be rendered in the window at the given position and size.
4121/// Passed as an argument [`Window::paint_quad`].
4122#[derive(Clone)]
4123pub struct PaintQuad {
4124 /// The bounds of the quad within the window.
4125 pub bounds: Bounds<Pixels>,
4126 /// The radii of the quad's corners.
4127 pub corner_radii: Corners<Pixels>,
4128 /// The background color of the quad.
4129 pub background: Background,
4130 /// The widths of the quad's borders.
4131 pub border_widths: Edges<Pixels>,
4132 /// The color of the quad's borders.
4133 pub border_color: Hsla,
4134 /// The style of the quad's borders.
4135 pub border_style: BorderStyle,
4136}
4137
4138impl PaintQuad {
4139 /// Sets the corner radii of the quad.
4140 pub fn corner_radii(self, corner_radii: impl Into<Corners<Pixels>>) -> Self {
4141 PaintQuad {
4142 corner_radii: corner_radii.into(),
4143 ..self
4144 }
4145 }
4146
4147 /// Sets the border widths of the quad.
4148 pub fn border_widths(self, border_widths: impl Into<Edges<Pixels>>) -> Self {
4149 PaintQuad {
4150 border_widths: border_widths.into(),
4151 ..self
4152 }
4153 }
4154
4155 /// Sets the border color of the quad.
4156 pub fn border_color(self, border_color: impl Into<Hsla>) -> Self {
4157 PaintQuad {
4158 border_color: border_color.into(),
4159 ..self
4160 }
4161 }
4162
4163 /// Sets the background color of the quad.
4164 pub fn background(self, background: impl Into<Background>) -> Self {
4165 PaintQuad {
4166 background: background.into(),
4167 ..self
4168 }
4169 }
4170}
4171
4172/// Creates a quad with the given parameters.
4173pub fn quad(
4174 bounds: Bounds<Pixels>,
4175 corner_radii: impl Into<Corners<Pixels>>,
4176 background: impl Into<Background>,
4177 border_widths: impl Into<Edges<Pixels>>,
4178 border_color: impl Into<Hsla>,
4179 border_style: BorderStyle,
4180) -> PaintQuad {
4181 PaintQuad {
4182 bounds,
4183 corner_radii: corner_radii.into(),
4184 background: background.into(),
4185 border_widths: border_widths.into(),
4186 border_color: border_color.into(),
4187 border_style,
4188 }
4189}
4190
4191/// Creates a filled quad with the given bounds and background color.
4192pub fn fill(bounds: impl Into<Bounds<Pixels>>, background: impl Into<Background>) -> PaintQuad {
4193 PaintQuad {
4194 bounds: bounds.into(),
4195 corner_radii: (0.).into(),
4196 background: background.into(),
4197 border_widths: (0.).into(),
4198 border_color: transparent_black(),
4199 border_style: BorderStyle::default(),
4200 }
4201}
4202
4203/// Creates a rectangle outline with the given bounds, border color, and a 1px border width
4204pub fn outline(
4205 bounds: impl Into<Bounds<Pixels>>,
4206 border_color: impl Into<Hsla>,
4207 border_style: BorderStyle,
4208) -> PaintQuad {
4209 PaintQuad {
4210 bounds: bounds.into(),
4211 corner_radii: (0.).into(),
4212 background: transparent_black().into(),
4213 border_widths: (1.).into(),
4214 border_color: border_color.into(),
4215 border_style,
4216 }
4217}