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