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