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