1#[cfg(any(feature = "inspector", debug_assertions))]
2use crate::Inspector;
3use crate::{
4 Action, AnyDrag, AnyElement, AnyImageCache, AnyTooltip, AnyView, App, AppContext, Arena, Asset,
5 AsyncWindowContext, AvailableSpace, Background, BackdropBlur, BorderStyle, Bounds, BoxShadow,
6 Capslock, Context, Corners, CursorStyle, Decorations, DevicePixels, DispatchActionListener,
7 DispatchNodeId, DispatchTree, DisplayId, Edges, Effect, Entity, EntityId, EventEmitter,
8 FileDropEvent, FontId, Global, GlobalElementId, GlyphId, GpuSpecs, Hsla, InputHandler, IsZero,
9 KeyBinding, KeyContext, KeyDownEvent, KeyEvent, Keystroke, KeystrokeEvent, LayoutId,
10 LineLayoutIndex, Modifiers, ModifiersChangedEvent, MonochromeSprite, MouseButton, MouseEvent,
11 MouseMoveEvent, MouseUpEvent, Path, Pixels, PlatformAtlas, PlatformDisplay, PlatformInput,
12 PlatformInputHandler, PlatformWindow, Point, PolychromeSprite, Priority, PromptButton,
13 PromptLevel, Quad, Render, RenderGlyphParams, RenderImage, RenderImageParams, RenderSvgParams,
14 Replay, ResizeEdge, SMOOTH_SVG_SCALE_FACTOR, SUBPIXEL_VARIANTS_X, SUBPIXEL_VARIANTS_Y,
15 ScaledPixels, Scene, Shadow, SharedString, Size, StrikethroughStyle, Style, SubpixelSprite,
16 SubscriberSet, Subscription, SystemWindowTab, SystemWindowTabController, TabStopMap,
17 TaffyLayoutEngine, Task, TextRenderingMode, TextStyle, TextStyleRefinement,
18 TransformationMatrix, Underline, UnderlineStyle, WindowAppearance, WindowBackgroundAppearance,
19 WindowBounds, WindowControls, WindowDecorations, WindowOptions, WindowParams, WindowTextSystem,
20 point, prelude::*, px, rems, size, transparent_black,
21};
22use anyhow::{Context as _, Result, anyhow};
23use collections::{FxHashMap, FxHashSet};
24#[cfg(target_os = "macos")]
25use core_video::pixel_buffer::CVPixelBuffer;
26use derive_more::{Deref, DerefMut};
27use futures::FutureExt;
28use futures::channel::oneshot;
29use itertools::FoldWhile::{Continue, Done};
30use itertools::Itertools;
31use parking_lot::RwLock;
32use raw_window_handle::{HandleError, HasDisplayHandle, HasWindowHandle};
33use refineable::Refineable;
34use slotmap::SlotMap;
35use smallvec::SmallVec;
36use std::{
37 any::{Any, TypeId},
38 borrow::Cow,
39 cell::{Cell, RefCell},
40 cmp,
41 fmt::{Debug, Display},
42 hash::{Hash, Hasher},
43 marker::PhantomData,
44 mem,
45 ops::{DerefMut, Range},
46 rc::Rc,
47 sync::{
48 Arc, Weak,
49 atomic::{AtomicUsize, Ordering::SeqCst},
50 },
51 time::{Duration, Instant},
52};
53use util::post_inc;
54use util::{ResultExt, measure};
55use uuid::Uuid;
56
57mod prompts;
58
59use crate::util::atomic_incr_if_not_zero;
60pub use prompts::*;
61
62pub(crate) const DEFAULT_WINDOW_SIZE: Size<Pixels> = size(px(1536.), px(864.));
63
64pub const DEFAULT_ADDITIONAL_WINDOW_SIZE: Size<Pixels> = Size {
67 width: Pixels(900.),
68 height: Pixels(750.),
69};
70
71#[derive(Default, Copy, Clone, Debug, Eq, PartialEq)]
73pub enum DispatchPhase {
74 #[default]
79 Bubble,
80 Capture,
86}
87
88impl DispatchPhase {
89 #[inline]
91 pub fn bubble(self) -> bool {
92 self == DispatchPhase::Bubble
93 }
94
95 #[inline]
97 pub fn capture(self) -> bool {
98 self == DispatchPhase::Capture
99 }
100}
101
102struct WindowInvalidatorInner {
103 pub dirty: bool,
104 pub draw_phase: DrawPhase,
105 pub dirty_views: FxHashSet<EntityId>,
106}
107
108#[derive(Clone)]
109pub(crate) struct WindowInvalidator {
110 inner: Rc<RefCell<WindowInvalidatorInner>>,
111}
112
113impl WindowInvalidator {
114 pub fn new() -> Self {
115 WindowInvalidator {
116 inner: Rc::new(RefCell::new(WindowInvalidatorInner {
117 dirty: true,
118 draw_phase: DrawPhase::None,
119 dirty_views: FxHashSet::default(),
120 })),
121 }
122 }
123
124 pub fn invalidate_view(&self, entity: EntityId, cx: &mut App) -> bool {
125 let mut inner = self.inner.borrow_mut();
126 inner.dirty_views.insert(entity);
127 if inner.draw_phase == DrawPhase::None {
128 inner.dirty = true;
129 cx.push_effect(Effect::Notify { emitter: entity });
130 true
131 } else {
132 false
133 }
134 }
135
136 pub fn is_dirty(&self) -> bool {
137 self.inner.borrow().dirty
138 }
139
140 pub fn set_dirty(&self, dirty: bool) {
141 self.inner.borrow_mut().dirty = dirty
142 }
143
144 pub fn set_phase(&self, phase: DrawPhase) {
145 self.inner.borrow_mut().draw_phase = phase
146 }
147
148 pub fn take_views(&self) -> FxHashSet<EntityId> {
149 mem::take(&mut self.inner.borrow_mut().dirty_views)
150 }
151
152 pub fn replace_views(&self, views: FxHashSet<EntityId>) {
153 self.inner.borrow_mut().dirty_views = views;
154 }
155
156 pub fn not_drawing(&self) -> bool {
157 self.inner.borrow().draw_phase == DrawPhase::None
158 }
159
160 #[track_caller]
161 pub fn debug_assert_paint(&self) {
162 debug_assert!(
163 matches!(self.inner.borrow().draw_phase, DrawPhase::Paint),
164 "this method can only be called during paint"
165 );
166 }
167
168 #[track_caller]
169 pub fn debug_assert_prepaint(&self) {
170 debug_assert!(
171 matches!(self.inner.borrow().draw_phase, DrawPhase::Prepaint),
172 "this method can only be called during request_layout, or prepaint"
173 );
174 }
175
176 #[track_caller]
177 pub fn debug_assert_paint_or_prepaint(&self) {
178 debug_assert!(
179 matches!(
180 self.inner.borrow().draw_phase,
181 DrawPhase::Paint | DrawPhase::Prepaint
182 ),
183 "this method can only be called during request_layout, prepaint, or paint"
184 );
185 }
186}
187
188type AnyObserver = Box<dyn FnMut(&mut Window, &mut App) -> bool + 'static>;
189
190pub(crate) type AnyWindowFocusListener =
191 Box<dyn FnMut(&WindowFocusEvent, &mut Window, &mut App) -> bool + 'static>;
192
193pub(crate) struct WindowFocusEvent {
194 pub(crate) previous_focus_path: SmallVec<[FocusId; 8]>,
195 pub(crate) current_focus_path: SmallVec<[FocusId; 8]>,
196}
197
198impl WindowFocusEvent {
199 pub fn is_focus_in(&self, focus_id: FocusId) -> bool {
200 !self.previous_focus_path.contains(&focus_id) && self.current_focus_path.contains(&focus_id)
201 }
202
203 pub fn is_focus_out(&self, focus_id: FocusId) -> bool {
204 self.previous_focus_path.contains(&focus_id) && !self.current_focus_path.contains(&focus_id)
205 }
206}
207
208pub struct FocusOutEvent {
210 pub blurred: WeakFocusHandle,
212}
213
214slotmap::new_key_type! {
215 pub struct FocusId;
217}
218
219thread_local! {
220 pub(crate) static ELEMENT_ARENA: RefCell<Arena> = RefCell::new(Arena::new(1024 * 1024));
221}
222
223#[must_use]
225pub struct ArenaClearNeeded;
226
227impl ArenaClearNeeded {
228 pub fn clear(self) {
230 ELEMENT_ARENA.with_borrow_mut(|element_arena| {
231 element_arena.clear();
232 });
233 }
234}
235
236pub(crate) type FocusMap = RwLock<SlotMap<FocusId, FocusRef>>;
237pub(crate) struct FocusRef {
238 pub(crate) ref_count: AtomicUsize,
239 pub(crate) tab_index: isize,
240 pub(crate) tab_stop: bool,
241}
242
243impl FocusId {
244 pub fn is_focused(&self, window: &Window) -> bool {
246 window.focus == Some(*self)
247 }
248
249 pub fn contains_focused(&self, window: &Window, cx: &App) -> bool {
252 window
253 .focused(cx)
254 .is_some_and(|focused| self.contains(focused.id, window))
255 }
256
257 pub fn within_focused(&self, window: &Window, cx: &App) -> bool {
260 let focused = window.focused(cx);
261 focused.is_some_and(|focused| focused.id.contains(*self, window))
262 }
263
264 pub(crate) fn contains(&self, other: Self, window: &Window) -> bool {
266 window
267 .rendered_frame
268 .dispatch_tree
269 .focus_contains(*self, other)
270 }
271}
272
273pub struct FocusHandle {
275 pub(crate) id: FocusId,
276 handles: Arc<FocusMap>,
277 pub tab_index: isize,
279 pub tab_stop: bool,
281}
282
283impl std::fmt::Debug for FocusHandle {
284 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
285 f.write_fmt(format_args!("FocusHandle({:?})", self.id))
286 }
287}
288
289impl FocusHandle {
290 pub(crate) fn new(handles: &Arc<FocusMap>) -> Self {
291 let id = handles.write().insert(FocusRef {
292 ref_count: AtomicUsize::new(1),
293 tab_index: 0,
294 tab_stop: false,
295 });
296
297 Self {
298 id,
299 tab_index: 0,
300 tab_stop: false,
301 handles: handles.clone(),
302 }
303 }
304
305 pub(crate) fn for_id(id: FocusId, handles: &Arc<FocusMap>) -> Option<Self> {
306 let lock = handles.read();
307 let focus = lock.get(id)?;
308 if atomic_incr_if_not_zero(&focus.ref_count) == 0 {
309 return None;
310 }
311 Some(Self {
312 id,
313 tab_index: focus.tab_index,
314 tab_stop: focus.tab_stop,
315 handles: handles.clone(),
316 })
317 }
318
319 pub fn tab_index(mut self, index: isize) -> Self {
321 self.tab_index = index;
322 if let Some(focus) = self.handles.write().get_mut(self.id) {
323 focus.tab_index = index;
324 }
325 self
326 }
327
328 pub fn tab_stop(mut self, tab_stop: bool) -> Self {
332 self.tab_stop = tab_stop;
333 if let Some(focus) = self.handles.write().get_mut(self.id) {
334 focus.tab_stop = tab_stop;
335 }
336 self
337 }
338
339 pub fn downgrade(&self) -> WeakFocusHandle {
341 WeakFocusHandle {
342 id: self.id,
343 handles: Arc::downgrade(&self.handles),
344 }
345 }
346
347 pub fn focus(&self, window: &mut Window, cx: &mut App) {
349 window.focus(self, cx)
350 }
351
352 pub fn is_focused(&self, window: &Window) -> bool {
354 self.id.is_focused(window)
355 }
356
357 pub fn contains_focused(&self, window: &Window, cx: &App) -> bool {
360 self.id.contains_focused(window, cx)
361 }
362
363 pub fn within_focused(&self, window: &Window, cx: &mut App) -> bool {
366 self.id.within_focused(window, cx)
367 }
368
369 pub fn contains(&self, other: &Self, window: &Window) -> bool {
371 self.id.contains(other.id, window)
372 }
373
374 pub fn dispatch_action(&self, action: &dyn Action, window: &mut Window, cx: &mut App) {
376 if let Some(node_id) = window
377 .rendered_frame
378 .dispatch_tree
379 .focusable_node_id(self.id)
380 {
381 window.dispatch_action_on_node(node_id, action, cx)
382 }
383 }
384}
385
386impl Clone for FocusHandle {
387 fn clone(&self) -> Self {
388 Self::for_id(self.id, &self.handles).unwrap()
389 }
390}
391
392impl PartialEq for FocusHandle {
393 fn eq(&self, other: &Self) -> bool {
394 self.id == other.id
395 }
396}
397
398impl Eq for FocusHandle {}
399
400impl Drop for FocusHandle {
401 fn drop(&mut self) {
402 self.handles
403 .read()
404 .get(self.id)
405 .unwrap()
406 .ref_count
407 .fetch_sub(1, SeqCst);
408 }
409}
410
411#[derive(Clone, Debug)]
413pub struct WeakFocusHandle {
414 pub(crate) id: FocusId,
415 pub(crate) handles: Weak<FocusMap>,
416}
417
418impl WeakFocusHandle {
419 pub fn upgrade(&self) -> Option<FocusHandle> {
421 let handles = self.handles.upgrade()?;
422 FocusHandle::for_id(self.id, &handles)
423 }
424}
425
426impl PartialEq for WeakFocusHandle {
427 fn eq(&self, other: &WeakFocusHandle) -> bool {
428 self.id == other.id
429 }
430}
431
432impl Eq for WeakFocusHandle {}
433
434impl PartialEq<FocusHandle> for WeakFocusHandle {
435 fn eq(&self, other: &FocusHandle) -> bool {
436 self.id == other.id
437 }
438}
439
440impl PartialEq<WeakFocusHandle> for FocusHandle {
441 fn eq(&self, other: &WeakFocusHandle) -> bool {
442 self.id == other.id
443 }
444}
445
446pub trait Focusable: 'static {
449 fn focus_handle(&self, cx: &App) -> FocusHandle;
451}
452
453impl<V: Focusable> Focusable for Entity<V> {
454 fn focus_handle(&self, cx: &App) -> FocusHandle {
455 self.read(cx).focus_handle(cx)
456 }
457}
458
459pub trait ManagedView: Focusable + EventEmitter<DismissEvent> + Render {}
462
463impl<M: Focusable + EventEmitter<DismissEvent> + Render> ManagedView for M {}
464
465pub struct DismissEvent;
467
468type FrameCallback = Box<dyn FnOnce(&mut Window, &mut App)>;
469
470pub(crate) type AnyMouseListener =
471 Box<dyn FnMut(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static>;
472
473#[derive(Clone)]
474pub(crate) struct CursorStyleRequest {
475 pub(crate) hitbox_id: Option<HitboxId>,
476 pub(crate) style: CursorStyle,
477}
478
479#[derive(Default, Eq, PartialEq)]
480pub(crate) struct HitTest {
481 pub(crate) ids: SmallVec<[HitboxId; 8]>,
482 pub(crate) hover_hitbox_count: usize,
483}
484
485#[derive(Clone, Copy, Debug, Eq, PartialEq)]
487pub enum WindowControlArea {
488 Drag,
490 Close,
492 Max,
494 Min,
496}
497
498#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
500pub struct HitboxId(u64);
501
502impl HitboxId {
503 pub fn is_hovered(self, window: &Window) -> bool {
509 let hit_test = &window.mouse_hit_test;
510 for id in hit_test.ids.iter().take(hit_test.hover_hitbox_count) {
511 if self == *id {
512 return true;
513 }
514 }
515 false
516 }
517
518 pub fn should_handle_scroll(self, window: &Window) -> bool {
523 window.mouse_hit_test.ids.contains(&self)
524 }
525
526 fn next(mut self) -> HitboxId {
527 HitboxId(self.0.wrapping_add(1))
528 }
529}
530
531#[derive(Clone, Debug, Deref)]
534pub struct Hitbox {
535 pub id: HitboxId,
537 #[deref]
539 pub bounds: Bounds<Pixels>,
540 pub content_mask: ContentMask<Pixels>,
542 pub behavior: HitboxBehavior,
544}
545
546impl Hitbox {
547 pub fn is_hovered(&self, window: &Window) -> bool {
562 self.id.is_hovered(window)
563 }
564
565 pub fn should_handle_scroll(&self, window: &Window) -> bool {
572 self.id.should_handle_scroll(window)
573 }
574}
575
576#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
578pub enum HitboxBehavior {
579 #[default]
581 Normal,
582
583 BlockMouse,
605
606 BlockMouseExceptScroll,
633}
634
635#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
637pub struct TooltipId(usize);
638
639impl TooltipId {
640 pub fn is_hovered(&self, window: &Window) -> bool {
642 window
643 .tooltip_bounds
644 .as_ref()
645 .is_some_and(|tooltip_bounds| {
646 tooltip_bounds.id == *self
647 && tooltip_bounds.bounds.contains(&window.mouse_position())
648 })
649 }
650}
651
652pub(crate) struct TooltipBounds {
653 id: TooltipId,
654 bounds: Bounds<Pixels>,
655}
656
657#[derive(Clone)]
658pub(crate) struct TooltipRequest {
659 id: TooltipId,
660 tooltip: AnyTooltip,
661}
662
663pub(crate) struct DeferredDraw {
664 current_view: EntityId,
665 priority: usize,
666 parent_node: DispatchNodeId,
667 element_id_stack: SmallVec<[ElementId; 32]>,
668 text_style_stack: Vec<TextStyleRefinement>,
669 element: Option<AnyElement>,
670 absolute_offset: Point<Pixels>,
671 prepaint_range: Range<PrepaintStateIndex>,
672 paint_range: Range<PaintIndex>,
673}
674
675pub(crate) struct Frame {
676 pub(crate) focus: Option<FocusId>,
677 pub(crate) window_active: bool,
678 pub(crate) element_states: FxHashMap<(GlobalElementId, TypeId), ElementStateBox>,
679 accessed_element_states: Vec<(GlobalElementId, TypeId)>,
680 pub(crate) mouse_listeners: Vec<Option<AnyMouseListener>>,
681 pub(crate) dispatch_tree: DispatchTree,
682 pub(crate) scene: Scene,
683 pub(crate) hitboxes: Vec<Hitbox>,
684 pub(crate) window_control_hitboxes: Vec<(WindowControlArea, Hitbox)>,
685 pub(crate) deferred_draws: Vec<DeferredDraw>,
686 pub(crate) input_handlers: Vec<Option<PlatformInputHandler>>,
687 pub(crate) tooltip_requests: Vec<Option<TooltipRequest>>,
688 pub(crate) cursor_styles: Vec<CursorStyleRequest>,
689 #[cfg(any(test, feature = "test-support"))]
690 pub(crate) debug_bounds: FxHashMap<String, Bounds<Pixels>>,
691 #[cfg(any(feature = "inspector", debug_assertions))]
692 pub(crate) next_inspector_instance_ids: FxHashMap<Rc<crate::InspectorElementPath>, usize>,
693 #[cfg(any(feature = "inspector", debug_assertions))]
694 pub(crate) inspector_hitboxes: FxHashMap<HitboxId, crate::InspectorElementId>,
695 pub(crate) tab_stops: TabStopMap,
696}
697
698#[derive(Clone, Default)]
699pub(crate) struct PrepaintStateIndex {
700 hitboxes_index: usize,
701 tooltips_index: usize,
702 deferred_draws_index: usize,
703 dispatch_tree_index: usize,
704 accessed_element_states_index: usize,
705 line_layout_index: LineLayoutIndex,
706}
707
708#[derive(Clone, Default)]
709pub(crate) struct PaintIndex {
710 scene_index: usize,
711 mouse_listeners_index: usize,
712 input_handlers_index: usize,
713 cursor_styles_index: usize,
714 accessed_element_states_index: usize,
715 tab_handle_index: usize,
716 line_layout_index: LineLayoutIndex,
717}
718
719impl Frame {
720 pub(crate) fn new(dispatch_tree: DispatchTree) -> Self {
721 Frame {
722 focus: None,
723 window_active: false,
724 element_states: FxHashMap::default(),
725 accessed_element_states: Vec::new(),
726 mouse_listeners: Vec::new(),
727 dispatch_tree,
728 scene: Scene::default(),
729 hitboxes: Vec::new(),
730 window_control_hitboxes: Vec::new(),
731 deferred_draws: Vec::new(),
732 input_handlers: Vec::new(),
733 tooltip_requests: Vec::new(),
734 cursor_styles: Vec::new(),
735
736 #[cfg(any(test, feature = "test-support"))]
737 debug_bounds: FxHashMap::default(),
738
739 #[cfg(any(feature = "inspector", debug_assertions))]
740 next_inspector_instance_ids: FxHashMap::default(),
741
742 #[cfg(any(feature = "inspector", debug_assertions))]
743 inspector_hitboxes: FxHashMap::default(),
744 tab_stops: TabStopMap::default(),
745 }
746 }
747
748 pub(crate) fn clear(&mut self) {
749 self.element_states.clear();
750 self.accessed_element_states.clear();
751 self.mouse_listeners.clear();
752 self.dispatch_tree.clear();
753 self.scene.clear();
754 self.input_handlers.clear();
755 self.tooltip_requests.clear();
756 self.cursor_styles.clear();
757 self.hitboxes.clear();
758 self.window_control_hitboxes.clear();
759 self.deferred_draws.clear();
760 self.tab_stops.clear();
761 self.focus = None;
762
763 #[cfg(any(feature = "inspector", debug_assertions))]
764 {
765 self.next_inspector_instance_ids.clear();
766 self.inspector_hitboxes.clear();
767 }
768 }
769
770 pub(crate) fn cursor_style(&self, window: &Window) -> Option<CursorStyle> {
771 self.cursor_styles
772 .iter()
773 .rev()
774 .fold_while(None, |style, request| match request.hitbox_id {
775 None => Done(Some(request.style)),
776 Some(hitbox_id) => Continue(
777 style.or_else(|| hitbox_id.is_hovered(window).then_some(request.style)),
778 ),
779 })
780 .into_inner()
781 }
782
783 pub(crate) fn hit_test(&self, position: Point<Pixels>) -> HitTest {
784 let mut set_hover_hitbox_count = false;
785 let mut hit_test = HitTest::default();
786 for hitbox in self.hitboxes.iter().rev() {
787 let bounds = hitbox.bounds.intersect(&hitbox.content_mask.bounds);
788 if bounds.contains(&position) {
789 hit_test.ids.push(hitbox.id);
790 if !set_hover_hitbox_count
791 && hitbox.behavior == HitboxBehavior::BlockMouseExceptScroll
792 {
793 hit_test.hover_hitbox_count = hit_test.ids.len();
794 set_hover_hitbox_count = true;
795 }
796 if hitbox.behavior == HitboxBehavior::BlockMouse {
797 break;
798 }
799 }
800 }
801 if !set_hover_hitbox_count {
802 hit_test.hover_hitbox_count = hit_test.ids.len();
803 }
804 hit_test
805 }
806
807 pub(crate) fn focus_path(&self) -> SmallVec<[FocusId; 8]> {
808 self.focus
809 .map(|focus_id| self.dispatch_tree.focus_path(focus_id))
810 .unwrap_or_default()
811 }
812
813 pub(crate) fn finish(&mut self, prev_frame: &mut Self) {
814 for element_state_key in &self.accessed_element_states {
815 if let Some((element_state_key, element_state)) =
816 prev_frame.element_states.remove_entry(element_state_key)
817 {
818 self.element_states.insert(element_state_key, element_state);
819 }
820 }
821
822 self.scene.finish();
823 }
824}
825
826#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
827enum InputModality {
828 Mouse,
829 Keyboard,
830}
831
832pub struct Window {
834 pub(crate) handle: AnyWindowHandle,
835 pub(crate) invalidator: WindowInvalidator,
836 pub(crate) removed: bool,
837 pub(crate) platform_window: Box<dyn PlatformWindow>,
838 display_id: Option<DisplayId>,
839 sprite_atlas: Arc<dyn PlatformAtlas>,
840 text_system: Arc<WindowTextSystem>,
841 text_rendering_mode: Rc<Cell<TextRenderingMode>>,
842 rem_size: Pixels,
843 rem_size_override_stack: SmallVec<[Pixels; 8]>,
848 pub(crate) viewport_size: Size<Pixels>,
849 layout_engine: Option<TaffyLayoutEngine>,
850 pub(crate) root: Option<AnyView>,
851 pub(crate) element_id_stack: SmallVec<[ElementId; 32]>,
852 pub(crate) text_style_stack: Vec<TextStyleRefinement>,
853 pub(crate) rendered_entity_stack: Vec<EntityId>,
854 pub(crate) element_offset_stack: Vec<Point<Pixels>>,
855 pub(crate) element_opacity: f32,
856 pub(crate) content_mask_stack: Vec<ContentMask<Pixels>>,
857 pub(crate) requested_autoscroll: Option<Bounds<Pixels>>,
858 pub(crate) image_cache_stack: Vec<AnyImageCache>,
859 pub(crate) rendered_frame: Frame,
860 pub(crate) next_frame: Frame,
861 next_hitbox_id: HitboxId,
862 pub(crate) next_tooltip_id: TooltipId,
863 pub(crate) tooltip_bounds: Option<TooltipBounds>,
864 next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>>,
865 render_layers: FxHashMap<ElementId, RenderLayerRegistration>,
866 next_render_layer_seq: usize,
867 pub(crate) dirty_views: FxHashSet<EntityId>,
868 focus_listeners: SubscriberSet<(), AnyWindowFocusListener>,
869 pub(crate) focus_lost_listeners: SubscriberSet<(), AnyObserver>,
870 default_prevented: bool,
871 mouse_position: Point<Pixels>,
872 mouse_hit_test: HitTest,
873 modifiers: Modifiers,
874 capslock: Capslock,
875 scale_factor: f32,
876 pub(crate) bounds_observers: SubscriberSet<(), AnyObserver>,
877 appearance: WindowAppearance,
878 pub(crate) appearance_observers: SubscriberSet<(), AnyObserver>,
879 active: Rc<Cell<bool>>,
880 hovered: Rc<Cell<bool>>,
881 pub(crate) needs_present: Rc<Cell<bool>>,
882 pub(crate) input_rate_tracker: Rc<RefCell<InputRateTracker>>,
885 last_input_modality: InputModality,
886 pub(crate) refreshing: bool,
887 pub(crate) activation_observers: SubscriberSet<(), AnyObserver>,
888 pub(crate) focus: Option<FocusId>,
889 focus_enabled: bool,
890 pending_input: Option<PendingInput>,
891 pending_modifier: ModifierState,
892 pub(crate) pending_input_observers: SubscriberSet<(), AnyObserver>,
893 prompt: Option<RenderablePromptHandle>,
894 pub(crate) client_inset: Option<Pixels>,
895 #[cfg(any(feature = "inspector", debug_assertions))]
896 inspector: Option<Entity<Inspector>>,
897}
898
899type RenderLayerBuilder = Arc<dyn Fn(&mut Window, &mut App) -> AnyElement + 'static>;
900
901#[derive(Clone)]
902struct RenderLayerRegistration {
903 order: i32,
904 seq: usize,
905 build: RenderLayerBuilder,
906}
907
908#[derive(Clone, Debug, Default)]
909struct ModifierState {
910 modifiers: Modifiers,
911 saw_keystroke: bool,
912}
913
914#[derive(Clone, Debug)]
917pub(crate) struct InputRateTracker {
918 timestamps: Vec<Instant>,
919 window: Duration,
920 inputs_per_second: u32,
921 sustain_until: Instant,
922 sustain_duration: Duration,
923}
924
925impl Default for InputRateTracker {
926 fn default() -> Self {
927 Self {
928 timestamps: Vec::new(),
929 window: Duration::from_millis(100),
930 inputs_per_second: 60,
931 sustain_until: Instant::now(),
932 sustain_duration: Duration::from_secs(1),
933 }
934 }
935}
936
937impl InputRateTracker {
938 pub fn record_input(&mut self) {
939 let now = Instant::now();
940 self.timestamps.push(now);
941 self.prune_old_timestamps(now);
942
943 let min_events = self.inputs_per_second as u128 * self.window.as_millis() / 1000;
944 if self.timestamps.len() as u128 >= min_events {
945 self.sustain_until = now + self.sustain_duration;
946 }
947 }
948
949 pub fn is_high_rate(&self) -> bool {
950 Instant::now() < self.sustain_until
951 }
952
953 fn prune_old_timestamps(&mut self, now: Instant) {
954 self.timestamps
955 .retain(|&t| now.duration_since(t) <= self.window);
956 }
957}
958
959#[derive(Clone, Copy, Debug, Eq, PartialEq)]
960pub(crate) enum DrawPhase {
961 None,
962 Prepaint,
963 Paint,
964 Focus,
965}
966
967#[derive(Default, Debug)]
968struct PendingInput {
969 keystrokes: SmallVec<[Keystroke; 1]>,
970 focus: Option<FocusId>,
971 timer: Option<Task<()>>,
972 needs_timeout: bool,
973}
974
975pub(crate) struct ElementStateBox {
976 pub(crate) inner: Box<dyn Any>,
977 #[cfg(debug_assertions)]
978 pub(crate) type_name: &'static str,
979}
980
981fn default_bounds(display_id: Option<DisplayId>, cx: &mut App) -> WindowBounds {
982 let active_window_bounds = cx
987 .active_window()
988 .and_then(|w| w.update(cx, |_, window, _| window.window_bounds()).ok());
989
990 const CASCADE_OFFSET: f32 = 25.0;
991
992 let display = display_id
993 .map(|id| cx.find_display(id))
994 .unwrap_or_else(|| cx.primary_display());
995
996 let default_placement = || Bounds::new(point(px(0.), px(0.)), DEFAULT_WINDOW_SIZE);
997
998 let display_bounds = display
1000 .as_ref()
1001 .map(|d| d.visible_bounds())
1002 .unwrap_or_else(default_placement);
1003
1004 let (
1005 Bounds {
1006 origin: base_origin,
1007 size: base_size,
1008 },
1009 window_bounds_ctor,
1010 ): (_, fn(Bounds<Pixels>) -> WindowBounds) = match active_window_bounds {
1011 Some(bounds) => match bounds {
1012 WindowBounds::Windowed(bounds) => (bounds, WindowBounds::Windowed),
1013 WindowBounds::Maximized(bounds) => (bounds, WindowBounds::Maximized),
1014 WindowBounds::Fullscreen(bounds) => (bounds, WindowBounds::Fullscreen),
1015 },
1016 None => (
1017 display
1018 .as_ref()
1019 .map(|d| d.default_bounds())
1020 .unwrap_or_else(default_placement),
1021 WindowBounds::Windowed,
1022 ),
1023 };
1024
1025 let cascade_offset = point(px(CASCADE_OFFSET), px(CASCADE_OFFSET));
1026 let proposed_origin = base_origin + cascade_offset;
1027 let proposed_bounds = Bounds::new(proposed_origin, base_size);
1028
1029 let display_right = display_bounds.origin.x + display_bounds.size.width;
1030 let display_bottom = display_bounds.origin.y + display_bounds.size.height;
1031 let window_right = proposed_bounds.origin.x + proposed_bounds.size.width;
1032 let window_bottom = proposed_bounds.origin.y + proposed_bounds.size.height;
1033
1034 let fits_horizontally = window_right <= display_right;
1035 let fits_vertically = window_bottom <= display_bottom;
1036
1037 let final_origin = match (fits_horizontally, fits_vertically) {
1038 (true, true) => proposed_origin,
1039 (false, true) => point(display_bounds.origin.x, base_origin.y),
1040 (true, false) => point(base_origin.x, display_bounds.origin.y),
1041 (false, false) => display_bounds.origin,
1042 };
1043 window_bounds_ctor(Bounds::new(final_origin, base_size))
1044}
1045
1046impl Window {
1047 pub(crate) fn new(
1048 handle: AnyWindowHandle,
1049 options: WindowOptions,
1050 cx: &mut App,
1051 ) -> Result<Self> {
1052 let WindowOptions {
1053 window_bounds,
1054 titlebar,
1055 focus,
1056 show,
1057 kind,
1058 is_movable,
1059 is_resizable,
1060 is_minimizable,
1061 display_id,
1062 window_background,
1063 app_id,
1064 window_min_size,
1065 window_decorations,
1066 #[cfg_attr(not(target_os = "macos"), allow(unused_variables))]
1067 tabbing_identifier,
1068 } = options;
1069
1070 let window_bounds = window_bounds.unwrap_or_else(|| default_bounds(display_id, cx));
1071 let mut platform_window = cx.platform.open_window(
1072 handle,
1073 WindowParams {
1074 bounds: window_bounds.get_bounds(),
1075 titlebar,
1076 kind,
1077 is_movable,
1078 is_resizable,
1079 is_minimizable,
1080 focus,
1081 show,
1082 display_id,
1083 window_min_size,
1084 #[cfg(target_os = "macos")]
1085 tabbing_identifier,
1086 },
1087 )?;
1088
1089 let tab_bar_visible = platform_window.tab_bar_visible();
1090 SystemWindowTabController::init_visible(cx, tab_bar_visible);
1091 if let Some(tabs) = platform_window.tabbed_windows() {
1092 SystemWindowTabController::add_tab(cx, handle.window_id(), tabs);
1093 }
1094
1095 let display_id = platform_window.display().map(|display| display.id());
1096 let sprite_atlas = platform_window.sprite_atlas();
1097 let mouse_position = platform_window.mouse_position();
1098 let modifiers = platform_window.modifiers();
1099 let capslock = platform_window.capslock();
1100 let content_size = platform_window.content_size();
1101 let scale_factor = platform_window.scale_factor();
1102 let appearance = platform_window.appearance();
1103 let text_system = Arc::new(WindowTextSystem::new(cx.text_system().clone()));
1104 let invalidator = WindowInvalidator::new();
1105 let active = Rc::new(Cell::new(platform_window.is_active()));
1106 let hovered = Rc::new(Cell::new(platform_window.is_hovered()));
1107 let needs_present = Rc::new(Cell::new(false));
1108 let next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>> = Default::default();
1109 let input_rate_tracker = Rc::new(RefCell::new(InputRateTracker::default()));
1110
1111 platform_window
1112 .request_decorations(window_decorations.unwrap_or(WindowDecorations::Server));
1113 platform_window.set_background_appearance(window_background);
1114
1115 match window_bounds {
1116 WindowBounds::Fullscreen(_) => platform_window.toggle_fullscreen(),
1117 WindowBounds::Maximized(_) => platform_window.zoom(),
1118 WindowBounds::Windowed(_) => {}
1119 }
1120
1121 platform_window.on_close(Box::new({
1122 let window_id = handle.window_id();
1123 let mut cx = cx.to_async();
1124 move || {
1125 let _ = handle.update(&mut cx, |_, window, _| window.remove_window());
1126 let _ = cx.update(|cx| {
1127 SystemWindowTabController::remove_tab(cx, window_id);
1128 });
1129 }
1130 }));
1131 platform_window.on_request_frame(Box::new({
1132 let mut cx = cx.to_async();
1133 let invalidator = invalidator.clone();
1134 let active = active.clone();
1135 let needs_present = needs_present.clone();
1136 let next_frame_callbacks = next_frame_callbacks.clone();
1137 let input_rate_tracker = input_rate_tracker.clone();
1138 move |request_frame_options| {
1139 let next_frame_callbacks = next_frame_callbacks.take();
1140 if !next_frame_callbacks.is_empty() {
1141 handle
1142 .update(&mut cx, |_, window, cx| {
1143 for callback in next_frame_callbacks {
1144 callback(window, cx);
1145 }
1146 })
1147 .log_err();
1148 }
1149
1150 let needs_present = request_frame_options.require_presentation
1154 || needs_present.get()
1155 || (active.get() && input_rate_tracker.borrow_mut().is_high_rate());
1156
1157 if invalidator.is_dirty() || request_frame_options.force_render {
1158 measure("frame duration", || {
1159 handle
1160 .update(&mut cx, |_, window, cx| {
1161 let arena_clear_needed = window.draw(cx);
1162 window.present();
1163 arena_clear_needed.clear();
1164 })
1165 .log_err();
1166 })
1167 } else if needs_present {
1168 handle
1169 .update(&mut cx, |_, window, _| window.present())
1170 .log_err();
1171 }
1172
1173 handle
1174 .update(&mut cx, |_, window, _| {
1175 window.complete_frame();
1176 })
1177 .log_err();
1178 }
1179 }));
1180 platform_window.on_resize(Box::new({
1181 let mut cx = cx.to_async();
1182 move |_, _| {
1183 handle
1184 .update(&mut cx, |_, window, cx| window.bounds_changed(cx))
1185 .log_err();
1186 }
1187 }));
1188 platform_window.on_moved(Box::new({
1189 let mut cx = cx.to_async();
1190 move || {
1191 handle
1192 .update(&mut cx, |_, window, cx| window.bounds_changed(cx))
1193 .log_err();
1194 }
1195 }));
1196 platform_window.on_appearance_changed(Box::new({
1197 let mut cx = cx.to_async();
1198 move || {
1199 handle
1200 .update(&mut cx, |_, window, cx| window.appearance_changed(cx))
1201 .log_err();
1202 }
1203 }));
1204 platform_window.on_active_status_change(Box::new({
1205 let mut cx = cx.to_async();
1206 move |active| {
1207 handle
1208 .update(&mut cx, |_, window, cx| {
1209 window.active.set(active);
1210 window.modifiers = window.platform_window.modifiers();
1211 window.capslock = window.platform_window.capslock();
1212 window
1213 .activation_observers
1214 .clone()
1215 .retain(&(), |callback| callback(window, cx));
1216
1217 window.bounds_changed(cx);
1218 window.refresh();
1219
1220 SystemWindowTabController::update_last_active(cx, window.handle.id);
1221 })
1222 .log_err();
1223 }
1224 }));
1225 platform_window.on_hover_status_change(Box::new({
1226 let mut cx = cx.to_async();
1227 move |active| {
1228 handle
1229 .update(&mut cx, |_, window, _| {
1230 window.hovered.set(active);
1231 window.refresh();
1232 })
1233 .log_err();
1234 }
1235 }));
1236 platform_window.on_input({
1237 let mut cx = cx.to_async();
1238 Box::new(move |event| {
1239 handle
1240 .update(&mut cx, |_, window, cx| window.dispatch_event(event, cx))
1241 .log_err()
1242 .unwrap_or(DispatchEventResult::default())
1243 })
1244 });
1245 platform_window.on_hit_test_window_control({
1246 let mut cx = cx.to_async();
1247 Box::new(move || {
1248 handle
1249 .update(&mut cx, |_, window, _cx| {
1250 for (area, hitbox) in &window.rendered_frame.window_control_hitboxes {
1251 if window.mouse_hit_test.ids.contains(&hitbox.id) {
1252 return Some(*area);
1253 }
1254 }
1255 None
1256 })
1257 .log_err()
1258 .unwrap_or(None)
1259 })
1260 });
1261 platform_window.on_move_tab_to_new_window({
1262 let mut cx = cx.to_async();
1263 Box::new(move || {
1264 handle
1265 .update(&mut cx, |_, _window, cx| {
1266 SystemWindowTabController::move_tab_to_new_window(cx, handle.window_id());
1267 })
1268 .log_err();
1269 })
1270 });
1271 platform_window.on_merge_all_windows({
1272 let mut cx = cx.to_async();
1273 Box::new(move || {
1274 handle
1275 .update(&mut cx, |_, _window, cx| {
1276 SystemWindowTabController::merge_all_windows(cx, handle.window_id());
1277 })
1278 .log_err();
1279 })
1280 });
1281 platform_window.on_select_next_tab({
1282 let mut cx = cx.to_async();
1283 Box::new(move || {
1284 handle
1285 .update(&mut cx, |_, _window, cx| {
1286 SystemWindowTabController::select_next_tab(cx, handle.window_id());
1287 })
1288 .log_err();
1289 })
1290 });
1291 platform_window.on_select_previous_tab({
1292 let mut cx = cx.to_async();
1293 Box::new(move || {
1294 handle
1295 .update(&mut cx, |_, _window, cx| {
1296 SystemWindowTabController::select_previous_tab(cx, handle.window_id())
1297 })
1298 .log_err();
1299 })
1300 });
1301 platform_window.on_toggle_tab_bar({
1302 let mut cx = cx.to_async();
1303 Box::new(move || {
1304 handle
1305 .update(&mut cx, |_, window, cx| {
1306 let tab_bar_visible = window.platform_window.tab_bar_visible();
1307 SystemWindowTabController::set_visible(cx, tab_bar_visible);
1308 })
1309 .log_err();
1310 })
1311 });
1312
1313 if let Some(app_id) = app_id {
1314 platform_window.set_app_id(&app_id);
1315 }
1316
1317 platform_window.map_window().unwrap();
1318
1319 Ok(Window {
1320 handle,
1321 invalidator,
1322 removed: false,
1323 platform_window,
1324 display_id,
1325 sprite_atlas,
1326 text_system,
1327 text_rendering_mode: cx.text_rendering_mode.clone(),
1328 rem_size: px(16.),
1329 rem_size_override_stack: SmallVec::new(),
1330 viewport_size: content_size,
1331 layout_engine: Some(TaffyLayoutEngine::new()),
1332 root: None,
1333 element_id_stack: SmallVec::default(),
1334 text_style_stack: Vec::new(),
1335 rendered_entity_stack: Vec::new(),
1336 element_offset_stack: Vec::new(),
1337 content_mask_stack: Vec::new(),
1338 element_opacity: 1.0,
1339 requested_autoscroll: None,
1340 rendered_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
1341 next_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
1342 next_frame_callbacks,
1343 next_hitbox_id: HitboxId(0),
1344 next_tooltip_id: TooltipId::default(),
1345 tooltip_bounds: None,
1346 render_layers: FxHashMap::default(),
1347 next_render_layer_seq: 0,
1348 dirty_views: FxHashSet::default(),
1349 focus_listeners: SubscriberSet::new(),
1350 focus_lost_listeners: SubscriberSet::new(),
1351 default_prevented: true,
1352 mouse_position,
1353 mouse_hit_test: HitTest::default(),
1354 modifiers,
1355 capslock,
1356 scale_factor,
1357 bounds_observers: SubscriberSet::new(),
1358 appearance,
1359 appearance_observers: SubscriberSet::new(),
1360 active,
1361 hovered,
1362 needs_present,
1363 input_rate_tracker,
1364 last_input_modality: InputModality::Mouse,
1365 refreshing: false,
1366 activation_observers: SubscriberSet::new(),
1367 focus: None,
1368 focus_enabled: true,
1369 pending_input: None,
1370 pending_modifier: ModifierState::default(),
1371 pending_input_observers: SubscriberSet::new(),
1372 prompt: None,
1373 client_inset: None,
1374 image_cache_stack: Vec::new(),
1375 #[cfg(any(feature = "inspector", debug_assertions))]
1376 inspector: None,
1377 })
1378 }
1379
1380 pub(crate) fn new_focus_listener(
1381 &self,
1382 value: AnyWindowFocusListener,
1383 ) -> (Subscription, impl FnOnce() + use<>) {
1384 self.focus_listeners.insert((), value)
1385 }
1386}
1387
1388#[derive(Clone, Debug, Default, PartialEq, Eq)]
1389pub(crate) struct DispatchEventResult {
1390 pub propagate: bool,
1391 pub default_prevented: bool,
1392}
1393
1394#[derive(Clone, Debug, Default, PartialEq, Eq)]
1398#[repr(C)]
1399pub struct ContentMask<P: Clone + Debug + Default + PartialEq> {
1400 pub bounds: Bounds<P>,
1402}
1403
1404impl ContentMask<Pixels> {
1405 pub fn scale(&self, factor: f32) -> ContentMask<ScaledPixels> {
1407 ContentMask {
1408 bounds: self.bounds.scale(factor),
1409 }
1410 }
1411
1412 pub fn intersect(&self, other: &Self) -> Self {
1414 let bounds = self.bounds.intersect(&other.bounds);
1415 ContentMask { bounds }
1416 }
1417}
1418
1419impl Window {
1420 fn mark_view_dirty(&mut self, view_id: EntityId) {
1421 for view_id in self
1424 .rendered_frame
1425 .dispatch_tree
1426 .view_path_reversed(view_id)
1427 {
1428 if !self.dirty_views.insert(view_id) {
1429 break;
1430 }
1431 }
1432 }
1433
1434 pub fn observe_window_appearance(
1436 &self,
1437 mut callback: impl FnMut(&mut Window, &mut App) + 'static,
1438 ) -> Subscription {
1439 let (subscription, activate) = self.appearance_observers.insert(
1440 (),
1441 Box::new(move |window, cx| {
1442 callback(window, cx);
1443 true
1444 }),
1445 );
1446 activate();
1447 subscription
1448 }
1449
1450 pub fn replace_root<E>(
1452 &mut self,
1453 cx: &mut App,
1454 build_view: impl FnOnce(&mut Window, &mut Context<E>) -> E,
1455 ) -> Entity<E>
1456 where
1457 E: 'static + Render,
1458 {
1459 let view = cx.new(|cx| build_view(self, cx));
1460 self.root = Some(view.clone().into());
1461 self.refresh();
1462 view
1463 }
1464
1465 pub fn root<E>(&self) -> Option<Option<Entity<E>>>
1467 where
1468 E: 'static + Render,
1469 {
1470 self.root
1471 .as_ref()
1472 .map(|view| view.clone().downcast::<E>().ok())
1473 }
1474
1475 pub fn window_handle(&self) -> AnyWindowHandle {
1477 self.handle
1478 }
1479
1480 pub fn refresh(&mut self) {
1482 if self.invalidator.not_drawing() {
1483 self.refreshing = true;
1484 self.invalidator.set_dirty(true);
1485 }
1486 }
1487
1488 pub fn remove_window(&mut self) {
1490 self.removed = true;
1491 }
1492
1493 pub fn focused(&self, cx: &App) -> Option<FocusHandle> {
1495 self.focus
1496 .and_then(|id| FocusHandle::for_id(id, &cx.focus_handles))
1497 }
1498
1499 pub fn focus(&mut self, handle: &FocusHandle, cx: &mut App) {
1501 if !self.focus_enabled || self.focus == Some(handle.id) {
1502 return;
1503 }
1504
1505 self.focus = Some(handle.id);
1506 self.clear_pending_keystrokes();
1507
1508 let window_handle = self.handle;
1511 cx.defer(move |cx| {
1512 window_handle
1513 .update(cx, |_, window, cx| {
1514 window.pending_input_changed(cx);
1515 })
1516 .ok();
1517 });
1518
1519 self.refresh();
1520 }
1521
1522 pub fn blur(&mut self) {
1524 if !self.focus_enabled {
1525 return;
1526 }
1527
1528 self.focus = None;
1529 self.refresh();
1530 }
1531
1532 pub fn disable_focus(&mut self) {
1534 self.blur();
1535 self.focus_enabled = false;
1536 }
1537
1538 pub fn focus_next(&mut self, cx: &mut App) {
1540 if !self.focus_enabled {
1541 return;
1542 }
1543
1544 if let Some(handle) = self.rendered_frame.tab_stops.next(self.focus.as_ref()) {
1545 self.focus(&handle, cx)
1546 }
1547 }
1548
1549 pub fn focus_prev(&mut self, cx: &mut App) {
1551 if !self.focus_enabled {
1552 return;
1553 }
1554
1555 if let Some(handle) = self.rendered_frame.tab_stops.prev(self.focus.as_ref()) {
1556 self.focus(&handle, cx)
1557 }
1558 }
1559
1560 pub fn text_system(&self) -> &Arc<WindowTextSystem> {
1562 &self.text_system
1563 }
1564
1565 pub fn text_style(&self) -> TextStyle {
1567 let mut style = TextStyle::default();
1568 for refinement in &self.text_style_stack {
1569 style.refine(refinement);
1570 }
1571 style
1572 }
1573
1574 pub fn is_maximized(&self) -> bool {
1578 self.platform_window.is_maximized()
1579 }
1580
1581 pub fn request_decorations(&self, decorations: WindowDecorations) {
1583 self.platform_window.request_decorations(decorations);
1584 }
1585
1586 pub fn start_window_resize(&self, edge: ResizeEdge) {
1588 self.platform_window.start_window_resize(edge);
1589 }
1590
1591 pub fn window_bounds(&self) -> WindowBounds {
1594 self.platform_window.window_bounds()
1595 }
1596
1597 pub fn inner_window_bounds(&self) -> WindowBounds {
1599 self.platform_window.inner_window_bounds()
1600 }
1601
1602 pub fn dispatch_action(&mut self, action: Box<dyn Action>, cx: &mut App) {
1604 let focus_id = self.focused(cx).map(|handle| handle.id);
1605
1606 let window = self.handle;
1607 cx.defer(move |cx| {
1608 window
1609 .update(cx, |_, window, cx| {
1610 let node_id = window.focus_node_id_in_rendered_frame(focus_id);
1611 window.dispatch_action_on_node(node_id, action.as_ref(), cx);
1612 })
1613 .log_err();
1614 })
1615 }
1616
1617 pub(crate) fn dispatch_keystroke_observers(
1618 &mut self,
1619 event: &dyn Any,
1620 action: Option<Box<dyn Action>>,
1621 context_stack: Vec<KeyContext>,
1622 cx: &mut App,
1623 ) {
1624 let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() else {
1625 return;
1626 };
1627
1628 cx.keystroke_observers.clone().retain(&(), move |callback| {
1629 (callback)(
1630 &KeystrokeEvent {
1631 keystroke: key_down_event.keystroke.clone(),
1632 action: action.as_ref().map(|action| action.boxed_clone()),
1633 context_stack: context_stack.clone(),
1634 },
1635 self,
1636 cx,
1637 )
1638 });
1639 }
1640
1641 pub(crate) fn dispatch_keystroke_interceptors(
1642 &mut self,
1643 event: &dyn Any,
1644 context_stack: Vec<KeyContext>,
1645 cx: &mut App,
1646 ) {
1647 let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() else {
1648 return;
1649 };
1650
1651 cx.keystroke_interceptors
1652 .clone()
1653 .retain(&(), move |callback| {
1654 (callback)(
1655 &KeystrokeEvent {
1656 keystroke: key_down_event.keystroke.clone(),
1657 action: None,
1658 context_stack: context_stack.clone(),
1659 },
1660 self,
1661 cx,
1662 )
1663 });
1664 }
1665
1666 pub fn defer(&self, cx: &mut App, f: impl FnOnce(&mut Window, &mut App) + 'static) {
1669 let handle = self.handle;
1670 cx.defer(move |cx| {
1671 handle.update(cx, |_, window, cx| f(window, cx)).ok();
1672 });
1673 }
1674
1675 pub fn observe<T: 'static>(
1679 &mut self,
1680 observed: &Entity<T>,
1681 cx: &mut App,
1682 mut on_notify: impl FnMut(Entity<T>, &mut Window, &mut App) + 'static,
1683 ) -> Subscription {
1684 let entity_id = observed.entity_id();
1685 let observed = observed.downgrade();
1686 let window_handle = self.handle;
1687 cx.new_observer(
1688 entity_id,
1689 Box::new(move |cx| {
1690 window_handle
1691 .update(cx, |_, window, cx| {
1692 if let Some(handle) = observed.upgrade() {
1693 on_notify(handle, window, cx);
1694 true
1695 } else {
1696 false
1697 }
1698 })
1699 .unwrap_or(false)
1700 }),
1701 )
1702 }
1703
1704 pub fn subscribe<Emitter, Evt>(
1708 &mut self,
1709 entity: &Entity<Emitter>,
1710 cx: &mut App,
1711 mut on_event: impl FnMut(Entity<Emitter>, &Evt, &mut Window, &mut App) + 'static,
1712 ) -> Subscription
1713 where
1714 Emitter: EventEmitter<Evt>,
1715 Evt: 'static,
1716 {
1717 let entity_id = entity.entity_id();
1718 let handle = entity.downgrade();
1719 let window_handle = self.handle;
1720 cx.new_subscription(
1721 entity_id,
1722 (
1723 TypeId::of::<Evt>(),
1724 Box::new(move |event, cx| {
1725 window_handle
1726 .update(cx, |_, window, cx| {
1727 if let Some(entity) = handle.upgrade() {
1728 let event = event.downcast_ref().expect("invalid event type");
1729 on_event(entity, event, window, cx);
1730 true
1731 } else {
1732 false
1733 }
1734 })
1735 .unwrap_or(false)
1736 }),
1737 ),
1738 )
1739 }
1740
1741 pub fn observe_release<T>(
1743 &self,
1744 entity: &Entity<T>,
1745 cx: &mut App,
1746 mut on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,
1747 ) -> Subscription
1748 where
1749 T: 'static,
1750 {
1751 let entity_id = entity.entity_id();
1752 let window_handle = self.handle;
1753 let (subscription, activate) = cx.release_listeners.insert(
1754 entity_id,
1755 Box::new(move |entity, cx| {
1756 let entity = entity.downcast_mut().expect("invalid entity type");
1757 let _ = window_handle.update(cx, |_, window, cx| on_release(entity, window, cx));
1758 }),
1759 );
1760 activate();
1761 subscription
1762 }
1763
1764 pub fn to_async(&self, cx: &App) -> AsyncWindowContext {
1767 AsyncWindowContext::new_context(cx.to_async(), self.handle)
1768 }
1769
1770 pub fn on_next_frame(&self, callback: impl FnOnce(&mut Window, &mut App) + 'static) {
1772 RefCell::borrow_mut(&self.next_frame_callbacks).push(Box::new(callback));
1773 }
1774
1775 pub fn request_animation_frame(&self) {
1782 let entity = self.current_view();
1783 self.on_next_frame(move |_, cx| cx.notify(entity));
1784 }
1785
1786 #[track_caller]
1790 pub fn spawn<AsyncFn, R>(&self, cx: &App, f: AsyncFn) -> Task<R>
1791 where
1792 R: 'static,
1793 AsyncFn: AsyncFnOnce(&mut AsyncWindowContext) -> R + 'static,
1794 {
1795 let handle = self.handle;
1796 cx.spawn(async move |app| {
1797 let mut async_window_cx = AsyncWindowContext::new_context(app.clone(), handle);
1798 f(&mut async_window_cx).await
1799 })
1800 }
1801
1802 #[track_caller]
1806 pub fn spawn_with_priority<AsyncFn, R>(
1807 &self,
1808 priority: Priority,
1809 cx: &App,
1810 f: AsyncFn,
1811 ) -> Task<R>
1812 where
1813 R: 'static,
1814 AsyncFn: AsyncFnOnce(&mut AsyncWindowContext) -> R + 'static,
1815 {
1816 let handle = self.handle;
1817 cx.spawn_with_priority(priority, async move |app| {
1818 let mut async_window_cx = AsyncWindowContext::new_context(app.clone(), handle);
1819 f(&mut async_window_cx).await
1820 })
1821 }
1822
1823 fn bounds_changed(&mut self, cx: &mut App) {
1824 self.scale_factor = self.platform_window.scale_factor();
1825 self.viewport_size = self.platform_window.content_size();
1826 self.display_id = self.platform_window.display().map(|display| display.id());
1827
1828 self.refresh();
1829
1830 self.bounds_observers
1831 .clone()
1832 .retain(&(), |callback| callback(self, cx));
1833 }
1834
1835 pub fn bounds(&self) -> Bounds<Pixels> {
1837 self.platform_window.bounds()
1838 }
1839
1840 #[cfg(any(test, feature = "test-support"))]
1844 pub fn render_to_image(&self) -> anyhow::Result<image::RgbaImage> {
1845 self.platform_window
1846 .render_to_image(&self.rendered_frame.scene)
1847 }
1848
1849 pub fn resize(&mut self, size: Size<Pixels>) {
1851 self.platform_window.resize(size);
1852 }
1853
1854 pub fn is_fullscreen(&self) -> bool {
1856 self.platform_window.is_fullscreen()
1857 }
1858
1859 pub(crate) fn appearance_changed(&mut self, cx: &mut App) {
1860 self.appearance = self.platform_window.appearance();
1861
1862 self.appearance_observers
1863 .clone()
1864 .retain(&(), |callback| callback(self, cx));
1865 }
1866
1867 pub fn appearance(&self) -> WindowAppearance {
1869 self.appearance
1870 }
1871
1872 pub fn viewport_size(&self) -> Size<Pixels> {
1874 self.viewport_size
1875 }
1876
1877 pub fn is_window_active(&self) -> bool {
1879 self.active.get()
1880 }
1881
1882 pub fn is_window_hovered(&self) -> bool {
1886 if cfg!(any(
1887 target_os = "windows",
1888 target_os = "linux",
1889 target_os = "freebsd"
1890 )) {
1891 self.hovered.get()
1892 } else {
1893 self.is_window_active()
1894 }
1895 }
1896
1897 pub fn zoom_window(&self) {
1899 self.platform_window.zoom();
1900 }
1901
1902 pub fn show_window_menu(&self, position: Point<Pixels>) {
1904 self.platform_window.show_window_menu(position)
1905 }
1906
1907 pub fn start_window_move(&self) {
1912 self.platform_window.start_window_move()
1913 }
1914
1915 pub fn set_client_inset(&mut self, inset: Pixels) {
1917 self.client_inset = Some(inset);
1918 self.platform_window.set_client_inset(inset);
1919 }
1920
1921 pub fn client_inset(&self) -> Option<Pixels> {
1923 self.client_inset
1924 }
1925
1926 pub fn window_decorations(&self) -> Decorations {
1928 self.platform_window.window_decorations()
1929 }
1930
1931 pub fn window_controls(&self) -> WindowControls {
1933 self.platform_window.window_controls()
1934 }
1935
1936 pub fn set_window_title(&mut self, title: &str) {
1938 self.platform_window.set_title(title);
1939 }
1940
1941 pub fn set_app_id(&mut self, app_id: &str) {
1943 self.platform_window.set_app_id(app_id);
1944 }
1945
1946 pub fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance) {
1948 self.platform_window
1949 .set_background_appearance(background_appearance);
1950 }
1951
1952 pub fn set_window_edited(&mut self, edited: bool) {
1954 self.platform_window.set_edited(edited);
1955 }
1956
1957 pub fn display(&self, cx: &App) -> Option<Rc<dyn PlatformDisplay>> {
1959 cx.platform
1960 .displays()
1961 .into_iter()
1962 .find(|display| Some(display.id()) == self.display_id)
1963 }
1964
1965 pub fn show_character_palette(&self) {
1967 self.platform_window.show_character_palette();
1968 }
1969
1970 pub fn scale_factor(&self) -> f32 {
1974 self.scale_factor
1975 }
1976
1977 pub fn rem_size(&self) -> Pixels {
1980 self.rem_size_override_stack
1981 .last()
1982 .copied()
1983 .unwrap_or(self.rem_size)
1984 }
1985
1986 pub fn set_rem_size(&mut self, rem_size: impl Into<Pixels>) {
1989 self.rem_size = rem_size.into();
1990 }
1991
1992 pub fn with_global_id<R>(
1995 &mut self,
1996 element_id: ElementId,
1997 f: impl FnOnce(&GlobalElementId, &mut Self) -> R,
1998 ) -> R {
1999 self.element_id_stack.push(element_id);
2000 let global_id = GlobalElementId(Arc::from(&*self.element_id_stack));
2001
2002 let result = f(&global_id, self);
2003 self.element_id_stack.pop();
2004 result
2005 }
2006
2007 #[inline]
2013 pub fn with_rem_size<F, R>(&mut self, rem_size: Option<impl Into<Pixels>>, f: F) -> R
2014 where
2015 F: FnOnce(&mut Self) -> R,
2016 {
2017 self.invalidator.debug_assert_paint_or_prepaint();
2018
2019 if let Some(rem_size) = rem_size {
2020 self.rem_size_override_stack.push(rem_size.into());
2021 let result = f(self);
2022 self.rem_size_override_stack.pop();
2023 result
2024 } else {
2025 f(self)
2026 }
2027 }
2028
2029 pub fn line_height(&self) -> Pixels {
2031 self.text_style().line_height_in_pixels(self.rem_size())
2032 }
2033
2034 pub fn prevent_default(&mut self) {
2037 self.default_prevented = true;
2038 }
2039
2040 pub fn default_prevented(&self) -> bool {
2042 self.default_prevented
2043 }
2044
2045 pub fn register_render_layer<F>(&mut self, key: impl Into<ElementId>, order: i32, build: F)
2055 where
2056 F: Fn(&mut Window, &mut App) -> AnyElement + 'static,
2057 {
2058 let key = key.into();
2059 let build: RenderLayerBuilder = Arc::new(build);
2060
2061 if let Some(registration) = self.render_layers.get_mut(&key) {
2062 registration.order = order;
2063 registration.build = build;
2064 return;
2065 }
2066
2067 let seq = self.next_render_layer_seq;
2068 self.next_render_layer_seq = self.next_render_layer_seq.saturating_add(1);
2069 self.render_layers.insert(
2070 key,
2071 RenderLayerRegistration {
2072 order,
2073 seq,
2074 build,
2075 },
2076 );
2077 }
2078
2079 pub fn unregister_render_layer(&mut self, key: &ElementId) {
2081 self.render_layers.remove(key);
2082 }
2083
2084 pub fn has_render_layer(&self, key: &ElementId) -> bool {
2086 self.render_layers.contains_key(key)
2087 }
2088
2089 pub fn is_action_available(&self, action: &dyn Action, cx: &App) -> bool {
2091 let node_id =
2092 self.focus_node_id_in_rendered_frame(self.focused(cx).map(|handle| handle.id));
2093 self.rendered_frame
2094 .dispatch_tree
2095 .is_action_available(action, node_id)
2096 }
2097
2098 pub fn is_action_available_in(&self, action: &dyn Action, focus_handle: &FocusHandle) -> bool {
2100 let node_id = self.focus_node_id_in_rendered_frame(Some(focus_handle.id));
2101 self.rendered_frame
2102 .dispatch_tree
2103 .is_action_available(action, node_id)
2104 }
2105
2106 pub fn mouse_position(&self) -> Point<Pixels> {
2108 self.mouse_position
2109 }
2110
2111 pub fn hit_test_ids(&self, position: Point<Pixels>) -> SmallVec<[HitboxId; 8]> {
2115 self.rendered_frame.hit_test(position).ids
2116 }
2117
2118 pub fn modifiers(&self) -> Modifiers {
2120 self.modifiers
2121 }
2122
2123 pub fn last_input_was_keyboard(&self) -> bool {
2126 self.last_input_modality == InputModality::Keyboard
2127 }
2128
2129 pub fn capslock(&self) -> Capslock {
2131 self.capslock
2132 }
2133
2134 fn complete_frame(&self) {
2135 self.platform_window.completed_frame();
2136 }
2137
2138 #[profiling::function]
2141 pub fn draw(&mut self, cx: &mut App) -> ArenaClearNeeded {
2142 self.invalidate_entities();
2143 cx.entities.clear_accessed();
2144 debug_assert!(self.rendered_entity_stack.is_empty());
2145 self.invalidator.set_dirty(false);
2146 self.requested_autoscroll = None;
2147
2148 if let Some(input_handler) = self.platform_window.take_input_handler() {
2150 self.rendered_frame.input_handlers.push(Some(input_handler));
2151 }
2152 if !cx.mode.skip_drawing() {
2153 self.draw_roots(cx);
2154 }
2155 self.dirty_views.clear();
2156 self.next_frame.window_active = self.active.get();
2157
2158 if let Some(input_handler) = self.next_frame.input_handlers.pop() {
2160 self.platform_window
2161 .set_input_handler(input_handler.unwrap());
2162 }
2163
2164 self.layout_engine.as_mut().unwrap().clear();
2165 self.text_system().finish_frame();
2166 self.next_frame.finish(&mut self.rendered_frame);
2167
2168 self.invalidator.set_phase(DrawPhase::Focus);
2169 let previous_focus_path = self.rendered_frame.focus_path();
2170 let previous_window_active = self.rendered_frame.window_active;
2171 mem::swap(&mut self.rendered_frame, &mut self.next_frame);
2172 self.next_frame.clear();
2173 let current_focus_path = self.rendered_frame.focus_path();
2174 let current_window_active = self.rendered_frame.window_active;
2175
2176 if previous_focus_path != current_focus_path
2177 || previous_window_active != current_window_active
2178 {
2179 if !previous_focus_path.is_empty() && current_focus_path.is_empty() {
2180 self.focus_lost_listeners
2181 .clone()
2182 .retain(&(), |listener| listener(self, cx));
2183 }
2184
2185 let event = WindowFocusEvent {
2186 previous_focus_path: if previous_window_active {
2187 previous_focus_path
2188 } else {
2189 Default::default()
2190 },
2191 current_focus_path: if current_window_active {
2192 current_focus_path
2193 } else {
2194 Default::default()
2195 },
2196 };
2197 self.focus_listeners
2198 .clone()
2199 .retain(&(), |listener| listener(&event, self, cx));
2200 }
2201
2202 debug_assert!(self.rendered_entity_stack.is_empty());
2203 self.record_entities_accessed(cx);
2204 self.reset_cursor_style(cx);
2205 self.refreshing = false;
2206 self.invalidator.set_phase(DrawPhase::None);
2207 self.needs_present.set(true);
2208
2209 ArenaClearNeeded
2210 }
2211
2212 fn record_entities_accessed(&mut self, cx: &mut App) {
2213 let mut entities_ref = cx.entities.accessed_entities.borrow_mut();
2214 let mut entities = mem::take(entities_ref.deref_mut());
2215 drop(entities_ref);
2216 let handle = self.handle;
2217 cx.record_entities_accessed(
2218 handle,
2219 self.invalidator.clone(),
2221 &entities,
2222 );
2223 let mut entities_ref = cx.entities.accessed_entities.borrow_mut();
2224 mem::swap(&mut entities, entities_ref.deref_mut());
2225 }
2226
2227 fn invalidate_entities(&mut self) {
2228 let mut views = self.invalidator.take_views();
2229 for entity in views.drain() {
2230 self.mark_view_dirty(entity);
2231 }
2232 self.invalidator.replace_views(views);
2233 }
2234
2235 #[profiling::function]
2236 fn present(&self) {
2237 self.platform_window.draw(&self.rendered_frame.scene);
2238 self.needs_present.set(false);
2239 profiling::finish_frame!();
2240 }
2241
2242 fn prepaint_render_layers(
2243 &mut self,
2244 root_size: Size<Pixels>,
2245 cx: &mut App,
2246 ) -> Vec<(ElementId, AnyElement)> {
2247 if self.render_layers.is_empty() {
2248 return Vec::new();
2249 }
2250
2251 let mut layers: Vec<(ElementId, i32, usize, RenderLayerBuilder)> = self
2252 .render_layers
2253 .iter()
2254 .map(|(key, reg)| (key.clone(), reg.order, reg.seq, reg.build.clone()))
2255 .collect();
2256 layers.sort_by_key(|(_, order, seq, _)| (*order, *seq));
2257
2258 let root_view_id = self.root.as_ref().map(|v| v.entity_id());
2261 let mut elements: Vec<(ElementId, AnyElement)> = Vec::with_capacity(layers.len());
2262 if let Some(root_view_id) = root_view_id {
2263 self.with_rendered_view(root_view_id, |window| {
2264 for (key, _order, _seq, build) in layers {
2265 let mut element = (&*build)(window, cx);
2266 window.element_id_stack.push(key.clone());
2267 element.prepaint_as_root(Point::default(), root_size.into(), window, cx);
2268 window.element_id_stack.pop();
2269 elements.push((key, element));
2270 }
2271 });
2272 } else {
2273 for (key, _order, _seq, build) in layers {
2274 let mut element = (&*build)(self, cx);
2275 self.element_id_stack.push(key.clone());
2276 element.prepaint_as_root(Point::default(), root_size.into(), self, cx);
2277 self.element_id_stack.pop();
2278 elements.push((key, element));
2279 }
2280 }
2281
2282 elements
2283 }
2284
2285 fn paint_render_layers(&mut self, elements: &mut [(ElementId, AnyElement)], cx: &mut App) {
2286 let root_view_id = self.root.as_ref().map(|v| v.entity_id());
2287 if let Some(root_view_id) = root_view_id {
2288 self.with_rendered_view(root_view_id, |window| {
2289 for (key, element) in elements.iter_mut() {
2290 window.element_id_stack.push(key.clone());
2291 element.paint(window, cx);
2292 window.element_id_stack.pop();
2293 }
2294 });
2295 return;
2296 }
2297
2298 for (key, element) in elements.iter_mut() {
2299 self.element_id_stack.push(key.clone());
2300 element.paint(self, cx);
2301 self.element_id_stack.pop();
2302 }
2303 }
2304
2305 fn draw_roots(&mut self, cx: &mut App) {
2306 self.invalidator.set_phase(DrawPhase::Prepaint);
2307 self.tooltip_bounds.take();
2308
2309 let _inspector_width: Pixels = rems(30.0).to_pixels(self.rem_size());
2310 let root_size = {
2311 #[cfg(any(feature = "inspector", debug_assertions))]
2312 {
2313 if self.inspector.is_some() {
2314 let mut size = self.viewport_size;
2315 size.width = (size.width - _inspector_width).max(px(0.0));
2316 size
2317 } else {
2318 self.viewport_size
2319 }
2320 }
2321 #[cfg(not(any(feature = "inspector", debug_assertions)))]
2322 {
2323 self.viewport_size
2324 }
2325 };
2326
2327 let mut root_element = self.root.as_ref().unwrap().clone().into_any();
2329 root_element.prepaint_as_root(Point::default(), root_size.into(), self, cx);
2330
2331 let mut render_layer_elements = self.prepaint_render_layers(root_size, cx);
2332
2333 #[cfg(any(feature = "inspector", debug_assertions))]
2334 let inspector_element = self.prepaint_inspector(_inspector_width, cx);
2335
2336 let mut sorted_deferred_draws =
2337 (0..self.next_frame.deferred_draws.len()).collect::<SmallVec<[_; 8]>>();
2338 sorted_deferred_draws.sort_by_key(|ix| self.next_frame.deferred_draws[*ix].priority);
2339 self.prepaint_deferred_draws(&sorted_deferred_draws, cx);
2340
2341 let mut prompt_element = None;
2342 let mut active_drag_element = None;
2343 let mut tooltip_element = None;
2344 if let Some(prompt) = self.prompt.take() {
2345 let mut element = prompt.view.any_view().into_any();
2346 element.prepaint_as_root(Point::default(), root_size.into(), self, cx);
2347 prompt_element = Some(element);
2348 self.prompt = Some(prompt);
2349 } else if let Some(active_drag) = cx.active_drag.take() {
2350 let mut element = active_drag.view.clone().into_any();
2351 let offset = self.mouse_position() - active_drag.cursor_offset;
2352 element.prepaint_as_root(offset, AvailableSpace::min_size(), self, cx);
2353 active_drag_element = Some(element);
2354 cx.active_drag = Some(active_drag);
2355 } else {
2356 tooltip_element = self.prepaint_tooltip(cx);
2357 }
2358
2359 self.mouse_hit_test = self.next_frame.hit_test(self.mouse_position);
2360
2361 self.invalidator.set_phase(DrawPhase::Paint);
2363 root_element.paint(self, cx);
2364
2365 self.paint_render_layers(&mut render_layer_elements, cx);
2366
2367 #[cfg(any(feature = "inspector", debug_assertions))]
2368 self.paint_inspector(inspector_element, cx);
2369
2370 self.paint_deferred_draws(&sorted_deferred_draws, cx);
2371
2372 if let Some(mut prompt_element) = prompt_element {
2373 prompt_element.paint(self, cx);
2374 } else if let Some(mut drag_element) = active_drag_element {
2375 drag_element.paint(self, cx);
2376 } else if let Some(mut tooltip_element) = tooltip_element {
2377 tooltip_element.paint(self, cx);
2378 }
2379
2380 #[cfg(any(feature = "inspector", debug_assertions))]
2381 self.paint_inspector_hitbox(cx);
2382 }
2383
2384 fn prepaint_tooltip(&mut self, cx: &mut App) -> Option<AnyElement> {
2385 for tooltip_request_index in (0..self.next_frame.tooltip_requests.len()).rev() {
2387 let Some(Some(tooltip_request)) = self
2388 .next_frame
2389 .tooltip_requests
2390 .get(tooltip_request_index)
2391 .cloned()
2392 else {
2393 log::error!("Unexpectedly absent TooltipRequest");
2394 continue;
2395 };
2396 let mut element = tooltip_request.tooltip.view.clone().into_any();
2397 let mouse_position = tooltip_request.tooltip.mouse_position;
2398 let tooltip_size = element.layout_as_root(AvailableSpace::min_size(), self, cx);
2399
2400 let mut tooltip_bounds =
2401 Bounds::new(mouse_position + point(px(1.), px(1.)), tooltip_size);
2402 let window_bounds = Bounds {
2403 origin: Point::default(),
2404 size: self.viewport_size(),
2405 };
2406
2407 if tooltip_bounds.right() > window_bounds.right() {
2408 let new_x = mouse_position.x - tooltip_bounds.size.width - px(1.);
2409 if new_x >= Pixels::ZERO {
2410 tooltip_bounds.origin.x = new_x;
2411 } else {
2412 tooltip_bounds.origin.x = cmp::max(
2413 Pixels::ZERO,
2414 tooltip_bounds.origin.x - tooltip_bounds.right() - window_bounds.right(),
2415 );
2416 }
2417 }
2418
2419 if tooltip_bounds.bottom() > window_bounds.bottom() {
2420 let new_y = mouse_position.y - tooltip_bounds.size.height - px(1.);
2421 if new_y >= Pixels::ZERO {
2422 tooltip_bounds.origin.y = new_y;
2423 } else {
2424 tooltip_bounds.origin.y = cmp::max(
2425 Pixels::ZERO,
2426 tooltip_bounds.origin.y - tooltip_bounds.bottom() - window_bounds.bottom(),
2427 );
2428 }
2429 }
2430
2431 let is_visible =
2435 (tooltip_request.tooltip.check_visible_and_update)(tooltip_bounds, self, cx);
2436 if !is_visible {
2437 continue;
2438 }
2439
2440 self.with_absolute_element_offset(tooltip_bounds.origin, |window| {
2441 element.prepaint(window, cx)
2442 });
2443
2444 self.tooltip_bounds = Some(TooltipBounds {
2445 id: tooltip_request.id,
2446 bounds: tooltip_bounds,
2447 });
2448 return Some(element);
2449 }
2450 None
2451 }
2452
2453 fn prepaint_deferred_draws(&mut self, deferred_draw_indices: &[usize], cx: &mut App) {
2454 assert_eq!(self.element_id_stack.len(), 0);
2455
2456 let mut deferred_draws = mem::take(&mut self.next_frame.deferred_draws);
2457 for deferred_draw_ix in deferred_draw_indices {
2458 let deferred_draw = &mut deferred_draws[*deferred_draw_ix];
2459 self.element_id_stack
2460 .clone_from(&deferred_draw.element_id_stack);
2461 self.text_style_stack
2462 .clone_from(&deferred_draw.text_style_stack);
2463 self.next_frame
2464 .dispatch_tree
2465 .set_active_node(deferred_draw.parent_node);
2466
2467 let prepaint_start = self.prepaint_index();
2468 if let Some(element) = deferred_draw.element.as_mut() {
2469 self.with_rendered_view(deferred_draw.current_view, |window| {
2470 window.with_absolute_element_offset(deferred_draw.absolute_offset, |window| {
2471 element.prepaint(window, cx)
2472 });
2473 })
2474 } else {
2475 self.reuse_prepaint(deferred_draw.prepaint_range.clone());
2476 }
2477 let prepaint_end = self.prepaint_index();
2478 deferred_draw.prepaint_range = prepaint_start..prepaint_end;
2479 }
2480 assert_eq!(
2481 self.next_frame.deferred_draws.len(),
2482 0,
2483 "cannot call defer_draw during deferred drawing"
2484 );
2485 self.next_frame.deferred_draws = deferred_draws;
2486 self.element_id_stack.clear();
2487 self.text_style_stack.clear();
2488 }
2489
2490 fn paint_deferred_draws(&mut self, deferred_draw_indices: &[usize], cx: &mut App) {
2491 assert_eq!(self.element_id_stack.len(), 0);
2492
2493 let mut deferred_draws = mem::take(&mut self.next_frame.deferred_draws);
2494 for deferred_draw_ix in deferred_draw_indices {
2495 let mut deferred_draw = &mut deferred_draws[*deferred_draw_ix];
2496 self.element_id_stack
2497 .clone_from(&deferred_draw.element_id_stack);
2498 self.next_frame
2499 .dispatch_tree
2500 .set_active_node(deferred_draw.parent_node);
2501
2502 let paint_start = self.paint_index();
2503 if let Some(element) = deferred_draw.element.as_mut() {
2504 self.with_rendered_view(deferred_draw.current_view, |window| {
2505 element.paint(window, cx);
2506 })
2507 } else {
2508 self.reuse_paint(deferred_draw.paint_range.clone());
2509 }
2510 let paint_end = self.paint_index();
2511 deferred_draw.paint_range = paint_start..paint_end;
2512 }
2513 self.next_frame.deferred_draws = deferred_draws;
2514 self.element_id_stack.clear();
2515 }
2516
2517 pub(crate) fn prepaint_index(&self) -> PrepaintStateIndex {
2518 PrepaintStateIndex {
2519 hitboxes_index: self.next_frame.hitboxes.len(),
2520 tooltips_index: self.next_frame.tooltip_requests.len(),
2521 deferred_draws_index: self.next_frame.deferred_draws.len(),
2522 dispatch_tree_index: self.next_frame.dispatch_tree.len(),
2523 accessed_element_states_index: self.next_frame.accessed_element_states.len(),
2524 line_layout_index: self.text_system.layout_index(),
2525 }
2526 }
2527
2528 pub(crate) fn reuse_prepaint(&mut self, range: Range<PrepaintStateIndex>) {
2529 self.next_frame.hitboxes.extend(
2530 self.rendered_frame.hitboxes[range.start.hitboxes_index..range.end.hitboxes_index]
2531 .iter()
2532 .cloned(),
2533 );
2534 self.next_frame.tooltip_requests.extend(
2535 self.rendered_frame.tooltip_requests
2536 [range.start.tooltips_index..range.end.tooltips_index]
2537 .iter_mut()
2538 .map(|request| request.take()),
2539 );
2540 self.next_frame.accessed_element_states.extend(
2541 self.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
2542 ..range.end.accessed_element_states_index]
2543 .iter()
2544 .map(|(id, type_id)| (id.clone(), *type_id)),
2545 );
2546 self.text_system
2547 .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
2548
2549 let reused_subtree = self.next_frame.dispatch_tree.reuse_subtree(
2550 range.start.dispatch_tree_index..range.end.dispatch_tree_index,
2551 &mut self.rendered_frame.dispatch_tree,
2552 self.focus,
2553 );
2554
2555 if reused_subtree.contains_focus() {
2556 self.next_frame.focus = self.focus;
2557 }
2558
2559 self.next_frame.deferred_draws.extend(
2560 self.rendered_frame.deferred_draws
2561 [range.start.deferred_draws_index..range.end.deferred_draws_index]
2562 .iter()
2563 .map(|deferred_draw| DeferredDraw {
2564 current_view: deferred_draw.current_view,
2565 parent_node: reused_subtree.refresh_node_id(deferred_draw.parent_node),
2566 element_id_stack: deferred_draw.element_id_stack.clone(),
2567 text_style_stack: deferred_draw.text_style_stack.clone(),
2568 priority: deferred_draw.priority,
2569 element: None,
2570 absolute_offset: deferred_draw.absolute_offset,
2571 prepaint_range: deferred_draw.prepaint_range.clone(),
2572 paint_range: deferred_draw.paint_range.clone(),
2573 }),
2574 );
2575 }
2576
2577 pub(crate) fn paint_index(&self) -> PaintIndex {
2578 PaintIndex {
2579 scene_index: self.next_frame.scene.len(),
2580 mouse_listeners_index: self.next_frame.mouse_listeners.len(),
2581 input_handlers_index: self.next_frame.input_handlers.len(),
2582 cursor_styles_index: self.next_frame.cursor_styles.len(),
2583 accessed_element_states_index: self.next_frame.accessed_element_states.len(),
2584 tab_handle_index: self.next_frame.tab_stops.paint_index(),
2585 line_layout_index: self.text_system.layout_index(),
2586 }
2587 }
2588
2589 pub(crate) fn reuse_paint(&mut self, range: Range<PaintIndex>) {
2590 self.next_frame.cursor_styles.extend(
2591 self.rendered_frame.cursor_styles
2592 [range.start.cursor_styles_index..range.end.cursor_styles_index]
2593 .iter()
2594 .cloned(),
2595 );
2596 self.next_frame.input_handlers.extend(
2597 self.rendered_frame.input_handlers
2598 [range.start.input_handlers_index..range.end.input_handlers_index]
2599 .iter_mut()
2600 .map(|handler| handler.take()),
2601 );
2602 self.next_frame.mouse_listeners.extend(
2603 self.rendered_frame.mouse_listeners
2604 [range.start.mouse_listeners_index..range.end.mouse_listeners_index]
2605 .iter_mut()
2606 .map(|listener| listener.take()),
2607 );
2608 self.next_frame.accessed_element_states.extend(
2609 self.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
2610 ..range.end.accessed_element_states_index]
2611 .iter()
2612 .map(|(id, type_id)| (id.clone(), *type_id)),
2613 );
2614 self.next_frame.tab_stops.replay(
2615 &self.rendered_frame.tab_stops.insertion_history
2616 [range.start.tab_handle_index..range.end.tab_handle_index],
2617 );
2618
2619 self.text_system
2620 .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
2621 self.next_frame.scene.replay(
2622 range.start.scene_index..range.end.scene_index,
2623 &self.rendered_frame.scene,
2624 );
2625 }
2626
2627 #[inline]
2633 pub fn with_text_style<F, R>(&mut self, style: Option<TextStyleRefinement>, f: F) -> R
2634 where
2635 F: FnOnce(&mut Self) -> R,
2636 {
2637 self.invalidator.debug_assert_paint_or_prepaint();
2638 if let Some(style) = style {
2639 self.text_style_stack.push(style);
2640 let result = f(self);
2641 self.text_style_stack.pop();
2642 result
2643 } else {
2644 f(self)
2645 }
2646 }
2647
2648 pub fn set_cursor_style(&mut self, style: CursorStyle, hitbox: &Hitbox) {
2651 self.invalidator.debug_assert_paint();
2652 self.next_frame.cursor_styles.push(CursorStyleRequest {
2653 hitbox_id: Some(hitbox.id),
2654 style,
2655 });
2656 }
2657
2658 pub fn set_window_cursor_style(&mut self, style: CursorStyle) {
2663 self.invalidator.debug_assert_paint();
2664 self.next_frame.cursor_styles.push(CursorStyleRequest {
2665 hitbox_id: None,
2666 style,
2667 })
2668 }
2669
2670 pub fn set_tooltip(&mut self, tooltip: AnyTooltip) -> TooltipId {
2673 self.invalidator.debug_assert_prepaint();
2674 let id = TooltipId(post_inc(&mut self.next_tooltip_id.0));
2675 self.next_frame
2676 .tooltip_requests
2677 .push(Some(TooltipRequest { id, tooltip }));
2678 id
2679 }
2680
2681 #[inline]
2686 pub fn with_content_mask<R>(
2687 &mut self,
2688 mask: Option<ContentMask<Pixels>>,
2689 f: impl FnOnce(&mut Self) -> R,
2690 ) -> R {
2691 self.invalidator.debug_assert_paint_or_prepaint();
2692 if let Some(mask) = mask {
2693 let mask = mask.intersect(&self.content_mask());
2694 self.content_mask_stack.push(mask);
2695 let result = f(self);
2696 self.content_mask_stack.pop();
2697 result
2698 } else {
2699 f(self)
2700 }
2701 }
2702
2703 pub fn with_element_offset<R>(
2706 &mut self,
2707 offset: Point<Pixels>,
2708 f: impl FnOnce(&mut Self) -> R,
2709 ) -> R {
2710 self.invalidator.debug_assert_paint_or_prepaint();
2711
2712 if offset.is_zero() {
2713 return f(self);
2714 };
2715
2716 let abs_offset = self.element_offset() + offset;
2717 self.with_absolute_element_offset(abs_offset, f)
2718 }
2719
2720 pub fn with_absolute_element_offset<R>(
2724 &mut self,
2725 offset: Point<Pixels>,
2726 f: impl FnOnce(&mut Self) -> R,
2727 ) -> R {
2728 self.invalidator.debug_assert_paint_or_prepaint();
2729 self.element_offset_stack.push(offset);
2730 let result = f(self);
2731 self.element_offset_stack.pop();
2732 result
2733 }
2734
2735 pub fn with_element_opacity<R>(
2742 &mut self,
2743 opacity: Option<f32>,
2744 f: impl FnOnce(&mut Self) -> R,
2745 ) -> R {
2746 self.invalidator.debug_assert_paint_or_prepaint();
2747
2748 let Some(opacity) = opacity else {
2749 return f(self);
2750 };
2751
2752 let previous_opacity = self.element_opacity;
2753 self.element_opacity = previous_opacity * opacity;
2754 let result = f(self);
2755 self.element_opacity = previous_opacity;
2756 result
2757 }
2758
2759 pub fn transact<T, U>(&mut self, f: impl FnOnce(&mut Self) -> Result<T, U>) -> Result<T, U> {
2765 self.invalidator.debug_assert_prepaint();
2766 let index = self.prepaint_index();
2767 let result = f(self);
2768 if result.is_err() {
2769 self.next_frame.hitboxes.truncate(index.hitboxes_index);
2770 self.next_frame
2771 .tooltip_requests
2772 .truncate(index.tooltips_index);
2773 self.next_frame
2774 .deferred_draws
2775 .truncate(index.deferred_draws_index);
2776 self.next_frame
2777 .dispatch_tree
2778 .truncate(index.dispatch_tree_index);
2779 self.next_frame
2780 .accessed_element_states
2781 .truncate(index.accessed_element_states_index);
2782 self.text_system.truncate_layouts(index.line_layout_index);
2783 }
2784 result
2785 }
2786
2787 pub fn request_autoscroll(&mut self, bounds: Bounds<Pixels>) {
2793 self.invalidator.debug_assert_prepaint();
2794 self.requested_autoscroll = Some(bounds);
2795 }
2796
2797 pub fn take_autoscroll(&mut self) -> Option<Bounds<Pixels>> {
2800 self.invalidator.debug_assert_prepaint();
2801 self.requested_autoscroll.take()
2802 }
2803
2804 pub fn use_asset<A: Asset>(&mut self, source: &A::Source, cx: &mut App) -> Option<A::Output> {
2810 let (task, is_first) = cx.fetch_asset::<A>(source);
2811 task.clone().now_or_never().or_else(|| {
2812 if is_first {
2813 let entity_id = self.current_view();
2814 self.spawn(cx, {
2815 let task = task.clone();
2816 async move |cx| {
2817 task.await;
2818
2819 cx.on_next_frame(move |_, cx| {
2820 cx.notify(entity_id);
2821 });
2822 }
2823 })
2824 .detach();
2825 }
2826
2827 None
2828 })
2829 }
2830
2831 pub fn get_asset<A: Asset>(&mut self, source: &A::Source, cx: &mut App) -> Option<A::Output> {
2837 let (task, _) = cx.fetch_asset::<A>(source);
2838 task.now_or_never()
2839 }
2840 pub fn element_offset(&self) -> Point<Pixels> {
2842 self.invalidator.debug_assert_paint_or_prepaint();
2843 self.element_offset_stack
2844 .last()
2845 .copied()
2846 .unwrap_or_default()
2847 }
2848
2849 #[inline]
2852 pub(crate) fn element_opacity(&self) -> f32 {
2853 self.invalidator.debug_assert_paint_or_prepaint();
2854 self.element_opacity
2855 }
2856
2857 pub fn content_mask(&self) -> ContentMask<Pixels> {
2859 self.invalidator.debug_assert_paint_or_prepaint();
2860 self.content_mask_stack
2861 .last()
2862 .cloned()
2863 .unwrap_or_else(|| ContentMask {
2864 bounds: Bounds {
2865 origin: Point::default(),
2866 size: self.viewport_size,
2867 },
2868 })
2869 }
2870
2871 pub fn with_element_namespace<R>(
2874 &mut self,
2875 element_id: impl Into<ElementId>,
2876 f: impl FnOnce(&mut Self) -> R,
2877 ) -> R {
2878 self.element_id_stack.push(element_id.into());
2879 let result = f(self);
2880 self.element_id_stack.pop();
2881 result
2882 }
2883
2884 pub fn use_keyed_state<S: 'static>(
2886 &mut self,
2887 key: impl Into<ElementId>,
2888 cx: &mut App,
2889 init: impl FnOnce(&mut Self, &mut Context<S>) -> S,
2890 ) -> Entity<S> {
2891 let current_view = self.current_view();
2892 self.with_global_id(key.into(), |global_id, window| {
2893 window.with_element_state(global_id, |state: Option<Entity<S>>, window| {
2894 if let Some(state) = state {
2895 (state.clone(), state)
2896 } else {
2897 let new_state = cx.new(|cx| init(window, cx));
2898 cx.observe(&new_state, move |_, cx| {
2899 cx.notify(current_view);
2900 })
2901 .detach();
2902 (new_state.clone(), new_state)
2903 }
2904 })
2905 })
2906 }
2907
2908 pub fn with_id<R>(&mut self, id: impl Into<ElementId>, f: impl FnOnce(&mut Self) -> R) -> R {
2910 self.with_global_id(id.into(), |_, window| f(window))
2911 }
2912
2913 #[track_caller]
2919 pub fn use_state<S: 'static>(
2920 &mut self,
2921 cx: &mut App,
2922 init: impl FnOnce(&mut Self, &mut Context<S>) -> S,
2923 ) -> Entity<S> {
2924 self.use_keyed_state(
2925 ElementId::CodeLocation(*core::panic::Location::caller()),
2926 cx,
2927 init,
2928 )
2929 }
2930
2931 pub fn with_element_state<S, R>(
2936 &mut self,
2937 global_id: &GlobalElementId,
2938 f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
2939 ) -> R
2940 where
2941 S: 'static,
2942 {
2943 self.invalidator.debug_assert_paint_or_prepaint();
2944
2945 let key = (global_id.clone(), TypeId::of::<S>());
2946 self.next_frame.accessed_element_states.push(key.clone());
2947
2948 if let Some(any) = self
2949 .next_frame
2950 .element_states
2951 .remove(&key)
2952 .or_else(|| self.rendered_frame.element_states.remove(&key))
2953 {
2954 let ElementStateBox {
2955 inner,
2956 #[cfg(debug_assertions)]
2957 type_name,
2958 } = any;
2959 let mut state_box = inner
2961 .downcast::<Option<S>>()
2962 .map_err(|_| {
2963 #[cfg(debug_assertions)]
2964 {
2965 anyhow::anyhow!(
2966 "invalid element state type for id, requested {:?}, actual: {:?}",
2967 std::any::type_name::<S>(),
2968 type_name
2969 )
2970 }
2971
2972 #[cfg(not(debug_assertions))]
2973 {
2974 anyhow::anyhow!(
2975 "invalid element state type for id, requested {:?}",
2976 std::any::type_name::<S>(),
2977 )
2978 }
2979 })
2980 .unwrap();
2981
2982 let state = state_box.take().expect(
2983 "reentrant call to with_element_state for the same state type and element id",
2984 );
2985 let (result, state) = f(Some(state), self);
2986 state_box.replace(state);
2987 self.next_frame.element_states.insert(
2988 key,
2989 ElementStateBox {
2990 inner: state_box,
2991 #[cfg(debug_assertions)]
2992 type_name,
2993 },
2994 );
2995 result
2996 } else {
2997 let (result, state) = f(None, self);
2998 self.next_frame.element_states.insert(
2999 key,
3000 ElementStateBox {
3001 inner: Box::new(Some(state)),
3002 #[cfg(debug_assertions)]
3003 type_name: std::any::type_name::<S>(),
3004 },
3005 );
3006 result
3007 }
3008 }
3009
3010 pub fn with_optional_element_state<S, R>(
3017 &mut self,
3018 global_id: Option<&GlobalElementId>,
3019 f: impl FnOnce(Option<Option<S>>, &mut Self) -> (R, Option<S>),
3020 ) -> R
3021 where
3022 S: 'static,
3023 {
3024 self.invalidator.debug_assert_paint_or_prepaint();
3025
3026 if let Some(global_id) = global_id {
3027 self.with_element_state(global_id, |state, cx| {
3028 let (result, state) = f(Some(state), cx);
3029 let state =
3030 state.expect("you must return some state when you pass some element id");
3031 (result, state)
3032 })
3033 } else {
3034 let (result, state) = f(None, self);
3035 debug_assert!(
3036 state.is_none(),
3037 "you must not return an element state when passing None for the global id"
3038 );
3039 result
3040 }
3041 }
3042
3043 #[inline]
3045 pub fn with_tab_group<R>(&mut self, index: Option<isize>, f: impl FnOnce(&mut Self) -> R) -> R {
3046 if let Some(index) = index {
3047 self.next_frame.tab_stops.begin_group(index);
3048 let result = f(self);
3049 self.next_frame.tab_stops.end_group();
3050 result
3051 } else {
3052 f(self)
3053 }
3054 }
3055
3056 pub fn register_tab_stop(&mut self, focus_handle: &FocusHandle, tab_index: isize) {
3060 self.invalidator.debug_assert_paint();
3061 let handle = focus_handle.clone().tab_stop(true).tab_index(tab_index);
3062 self.next_frame.tab_stops.insert(&handle);
3063 }
3064
3065 pub fn defer_draw(
3071 &mut self,
3072 element: AnyElement,
3073 absolute_offset: Point<Pixels>,
3074 priority: usize,
3075 ) {
3076 self.invalidator.debug_assert_prepaint();
3077 let parent_node = self.next_frame.dispatch_tree.active_node_id().unwrap();
3078 self.next_frame.deferred_draws.push(DeferredDraw {
3079 current_view: self.current_view(),
3080 parent_node,
3081 element_id_stack: self.element_id_stack.clone(),
3082 text_style_stack: self.text_style_stack.clone(),
3083 priority,
3084 element: Some(element),
3085 absolute_offset,
3086 prepaint_range: PrepaintStateIndex::default()..PrepaintStateIndex::default(),
3087 paint_range: PaintIndex::default()..PaintIndex::default(),
3088 });
3089 }
3090
3091 pub fn paint_layer<R>(&mut self, bounds: Bounds<Pixels>, f: impl FnOnce(&mut Self) -> R) -> R {
3097 self.invalidator.debug_assert_paint();
3098
3099 let scale_factor = self.scale_factor();
3100 let content_mask = self.content_mask();
3101 let clipped_bounds = bounds.intersect(&content_mask.bounds);
3102 if !clipped_bounds.is_empty() {
3103 self.next_frame
3104 .scene
3105 .push_layer(clipped_bounds.scale(scale_factor));
3106 }
3107
3108 let result = f(self);
3109
3110 if !clipped_bounds.is_empty() {
3111 self.next_frame.scene.pop_layer();
3112 }
3113
3114 result
3115 }
3116
3117 pub fn paint_shadows(
3121 &mut self,
3122 bounds: Bounds<Pixels>,
3123 corner_radii: Corners<Pixels>,
3124 shadows: &[BoxShadow],
3125 ) {
3126 self.paint_shadows_with_transform(
3127 bounds,
3128 corner_radii,
3129 shadows,
3130 TransformationMatrix::unit(),
3131 );
3132 }
3133
3134 pub fn paint_shadows_with_transform(
3138 &mut self,
3139 bounds: Bounds<Pixels>,
3140 corner_radii: Corners<Pixels>,
3141 shadows: &[BoxShadow],
3142 transform: TransformationMatrix,
3143 ) {
3144 self.invalidator.debug_assert_paint();
3145
3146 let scale_factor = self.scale_factor();
3147 let content_mask = self.content_mask();
3148 let opacity = self.element_opacity();
3149 let transform = self.scale_transform_for_scene(transform);
3150 for shadow in shadows {
3151 let shadow_bounds = (bounds + shadow.offset).dilate(shadow.spread_radius);
3152 self.next_frame.scene.insert_primitive((
3153 Shadow {
3154 order: 0,
3155 blur_radius: shadow.blur_radius.scale(scale_factor),
3156 bounds: shadow_bounds.scale(scale_factor),
3157 content_mask: content_mask.scale(scale_factor),
3158 corner_radii: corner_radii.scale(scale_factor),
3159 color: shadow.color.opacity(opacity),
3160 },
3161 transform,
3162 ));
3163 }
3164 }
3165
3166 pub fn paint_quad(&mut self, quad: PaintQuad) {
3176 self.paint_quad_with_transform(quad, TransformationMatrix::unit());
3177 }
3178
3179 pub fn paint_quad_with_transform(&mut self, quad: PaintQuad, transform: TransformationMatrix) {
3183 self.invalidator.debug_assert_paint();
3184
3185 let scale_factor = self.scale_factor();
3186 let content_mask = self.content_mask();
3187 let opacity = self.element_opacity();
3188 let transform = self.scale_transform_for_scene(transform);
3189
3190 self.next_frame.scene.insert_primitive((
3191 Quad {
3192 order: 0,
3193 bounds: quad.bounds.scale(scale_factor),
3194 content_mask: content_mask.scale(scale_factor),
3195 background: quad.background.opacity(opacity),
3196 border_color: quad.border_color.opacity(opacity),
3197 corner_radii: quad.corner_radii.scale(scale_factor),
3198 border_widths: quad.border_widths.scale(scale_factor),
3199 border_style: quad.border_style,
3200 },
3201 transform,
3202 ));
3203 }
3204
3205 pub fn paint_backdrop_blur(
3209 &mut self,
3210 bounds: Bounds<Pixels>,
3211 corner_radii: Corners<Pixels>,
3212 blur_radius: Pixels,
3213 tint: Hsla,
3214 ) {
3215 self.paint_backdrop_blur_with_transform(
3216 bounds,
3217 corner_radii,
3218 blur_radius,
3219 tint,
3220 TransformationMatrix::unit(),
3221 );
3222 }
3223
3224 pub fn paint_backdrop_blur_with_transform(
3228 &mut self,
3229 bounds: Bounds<Pixels>,
3230 corner_radii: Corners<Pixels>,
3231 blur_radius: Pixels,
3232 tint: Hsla,
3233 transform: TransformationMatrix,
3234 ) {
3235 self.invalidator.debug_assert_paint();
3236
3237 let scale_factor = self.scale_factor();
3238 let content_mask = self.content_mask();
3239 let opacity = self.element_opacity();
3240 let transform = self.scale_transform_for_scene(transform);
3241
3242 self.next_frame.scene.insert_primitive((
3243 BackdropBlur {
3244 order: 0,
3245 blur_radius: blur_radius.scale(scale_factor),
3246 bounds: bounds.scale(scale_factor),
3247 corner_radii: corner_radii.scale(scale_factor),
3248 content_mask: content_mask.scale(scale_factor),
3249 tint: tint.opacity(opacity),
3250 },
3251 transform,
3252 ));
3253 }
3254
3255 pub fn paint_path(&mut self, mut path: Path<Pixels>, color: impl Into<Background>) {
3259 self.invalidator.debug_assert_paint();
3260
3261 let scale_factor = self.scale_factor();
3262 let content_mask = self.content_mask();
3263 let opacity = self.element_opacity();
3264 path.content_mask = content_mask;
3265 let color: Background = color.into();
3266 path.color = color.opacity(opacity);
3267 self.next_frame
3268 .scene
3269 .insert_primitive(path.scale(scale_factor));
3270 }
3271
3272 pub fn paint_underline(
3276 &mut self,
3277 origin: Point<Pixels>,
3278 width: Pixels,
3279 style: &UnderlineStyle,
3280 ) {
3281 self.paint_underline_with_transform(origin, width, style, TransformationMatrix::unit());
3282 }
3283
3284 pub fn paint_underline_with_transform(
3288 &mut self,
3289 origin: Point<Pixels>,
3290 width: Pixels,
3291 style: &UnderlineStyle,
3292 transform: TransformationMatrix,
3293 ) {
3294 self.invalidator.debug_assert_paint();
3295
3296 let scale_factor = self.scale_factor();
3297 let height = if style.wavy {
3298 style.thickness * 3.
3299 } else {
3300 style.thickness
3301 };
3302 let bounds = Bounds {
3303 origin,
3304 size: size(width, height),
3305 };
3306 let content_mask = self.content_mask();
3307 let element_opacity = self.element_opacity();
3308 let transform = self.scale_transform_for_scene(transform);
3309
3310 self.next_frame.scene.insert_primitive((
3311 Underline {
3312 order: 0,
3313 pad: 0,
3314 bounds: bounds.scale(scale_factor),
3315 content_mask: content_mask.scale(scale_factor),
3316 color: style.color.unwrap_or_default().opacity(element_opacity),
3317 thickness: style.thickness.scale(scale_factor),
3318 wavy: if style.wavy { 1 } else { 0 },
3319 },
3320 transform,
3321 ));
3322 }
3323
3324 pub fn paint_strikethrough(
3328 &mut self,
3329 origin: Point<Pixels>,
3330 width: Pixels,
3331 style: &StrikethroughStyle,
3332 ) {
3333 self.paint_strikethrough_with_transform(origin, width, style, TransformationMatrix::unit());
3334 }
3335
3336 pub fn paint_strikethrough_with_transform(
3340 &mut self,
3341 origin: Point<Pixels>,
3342 width: Pixels,
3343 style: &StrikethroughStyle,
3344 transform: TransformationMatrix,
3345 ) {
3346 self.invalidator.debug_assert_paint();
3347
3348 let scale_factor = self.scale_factor();
3349 let height = style.thickness;
3350 let bounds = Bounds {
3351 origin,
3352 size: size(width, height),
3353 };
3354 let content_mask = self.content_mask();
3355 let opacity = self.element_opacity();
3356 let transform = self.scale_transform_for_scene(transform);
3357
3358 self.next_frame.scene.insert_primitive((
3359 Underline {
3360 order: 0,
3361 pad: 0,
3362 bounds: bounds.scale(scale_factor),
3363 content_mask: content_mask.scale(scale_factor),
3364 thickness: style.thickness.scale(scale_factor),
3365 color: style.color.unwrap_or_default().opacity(opacity),
3366 wavy: 0,
3367 },
3368 transform,
3369 ));
3370 }
3371
3372 pub fn paint_glyph(
3381 &mut self,
3382 origin: Point<Pixels>,
3383 font_id: FontId,
3384 glyph_id: GlyphId,
3385 font_size: Pixels,
3386 color: Hsla,
3387 ) -> Result<()> {
3388 self.paint_glyph_with_transform(
3389 origin,
3390 font_id,
3391 glyph_id,
3392 font_size,
3393 color,
3394 TransformationMatrix::unit(),
3395 )
3396 }
3397
3398 pub fn paint_glyph_with_transform(
3400 &mut self,
3401 origin: Point<Pixels>,
3402 font_id: FontId,
3403 glyph_id: GlyphId,
3404 font_size: Pixels,
3405 color: Hsla,
3406 transform: TransformationMatrix,
3407 ) -> Result<()> {
3408 self.invalidator.debug_assert_paint();
3409
3410 let element_opacity = self.element_opacity();
3411 let scale_factor = self.scale_factor();
3412 let glyph_origin = origin.scale(scale_factor);
3413 let transform = self.scale_transform_for_scene(transform);
3414
3415 let subpixel_variant = Point {
3416 x: (glyph_origin.x.0.fract() * SUBPIXEL_VARIANTS_X as f32).floor() as u8,
3417 y: (glyph_origin.y.0.fract() * SUBPIXEL_VARIANTS_Y as f32).floor() as u8,
3418 };
3419 let subpixel_rendering = self.should_use_subpixel_rendering(font_id, font_size);
3420 let params = RenderGlyphParams {
3421 font_id,
3422 glyph_id,
3423 font_size,
3424 subpixel_variant,
3425 scale_factor,
3426 is_emoji: false,
3427 subpixel_rendering,
3428 };
3429
3430 let raster_bounds = self.text_system().raster_bounds(¶ms)?;
3431 if !raster_bounds.is_zero() {
3432 let tile = self
3433 .sprite_atlas
3434 .get_or_insert_with(¶ms.clone().into(), &mut || {
3435 let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?;
3436 Ok(Some((size, Cow::Owned(bytes))))
3437 })?
3438 .expect("Callback above only errors or returns Some");
3439 let bounds = Bounds {
3440 origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
3441 size: tile.bounds.size.map(Into::into),
3442 };
3443 let content_mask = self.content_mask().scale(scale_factor);
3444
3445 if subpixel_rendering {
3446 self.next_frame.scene.insert_primitive(SubpixelSprite {
3447 order: 0,
3448 pad: 0,
3449 bounds,
3450 content_mask,
3451 color: color.opacity(element_opacity),
3452 tile,
3453 transformation: TransformationMatrix::unit(),
3454 });
3455 } else {
3456 self.next_frame.scene.insert_primitive(MonochromeSprite {
3457 order: 0,
3458 pad: 0,
3459 bounds,
3460 content_mask,
3461 color: color.opacity(element_opacity),
3462 tile,
3463 transformation: transform,
3464 });
3465 }
3466 }
3467 Ok(())
3468 }
3469
3470 fn should_use_subpixel_rendering(&self, font_id: FontId, font_size: Pixels) -> bool {
3471 if self.platform_window.background_appearance() != WindowBackgroundAppearance::Opaque {
3472 return false;
3473 }
3474
3475 if !self.platform_window.is_subpixel_rendering_supported() {
3476 return false;
3477 }
3478
3479 let mode = match self.text_rendering_mode.get() {
3480 TextRenderingMode::PlatformDefault => self
3481 .text_system()
3482 .recommended_rendering_mode(font_id, font_size),
3483 mode => mode,
3484 };
3485
3486 mode == TextRenderingMode::Subpixel
3487 }
3488
3489 pub fn paint_emoji(
3498 &mut self,
3499 origin: Point<Pixels>,
3500 font_id: FontId,
3501 glyph_id: GlyphId,
3502 font_size: Pixels,
3503 ) -> Result<()> {
3504 self.paint_emoji_with_transform(
3505 origin,
3506 font_id,
3507 glyph_id,
3508 font_size,
3509 TransformationMatrix::unit(),
3510 )
3511 }
3512
3513 pub fn paint_emoji_with_transform(
3515 &mut self,
3516 origin: Point<Pixels>,
3517 font_id: FontId,
3518 glyph_id: GlyphId,
3519 font_size: Pixels,
3520 transform: TransformationMatrix,
3521 ) -> Result<()> {
3522 self.invalidator.debug_assert_paint();
3523
3524 let scale_factor = self.scale_factor();
3525 let glyph_origin = origin.scale(scale_factor);
3526 let transform = self.scale_transform_for_scene(transform);
3527 let params = RenderGlyphParams {
3528 font_id,
3529 glyph_id,
3530 font_size,
3531 subpixel_variant: Default::default(),
3533 scale_factor,
3534 is_emoji: true,
3535 subpixel_rendering: false,
3536 };
3537
3538 let raster_bounds = self.text_system().raster_bounds(¶ms)?;
3539 if !raster_bounds.is_zero() {
3540 let tile = self
3541 .sprite_atlas
3542 .get_or_insert_with(¶ms.clone().into(), &mut || {
3543 let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?;
3544 Ok(Some((size, Cow::Owned(bytes))))
3545 })?
3546 .expect("Callback above only errors or returns Some");
3547
3548 let bounds = Bounds {
3549 origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
3550 size: tile.bounds.size.map(Into::into),
3551 };
3552 let content_mask = self.content_mask().scale(scale_factor);
3553 let opacity = self.element_opacity();
3554
3555 self.next_frame.scene.insert_primitive((
3556 PolychromeSprite {
3557 order: 0,
3558 pad: 0,
3559 grayscale: false,
3560 bounds,
3561 corner_radii: Default::default(),
3562 content_mask,
3563 tile,
3564 opacity,
3565 },
3566 transform,
3567 ));
3568 }
3569 Ok(())
3570 }
3571
3572 pub fn paint_svg(
3576 &mut self,
3577 bounds: Bounds<Pixels>,
3578 path: SharedString,
3579 mut data: Option<&[u8]>,
3580 transformation: TransformationMatrix,
3581 color: Hsla,
3582 cx: &App,
3583 ) -> Result<()> {
3584 self.invalidator.debug_assert_paint();
3585
3586 let element_opacity = self.element_opacity();
3587 let scale_factor = self.scale_factor();
3588
3589 let bounds = bounds.scale(scale_factor);
3590 let params = RenderSvgParams {
3591 path,
3592 size: bounds.size.map(|pixels| {
3593 DevicePixels::from((pixels.0 * SMOOTH_SVG_SCALE_FACTOR).ceil() as i32)
3594 }),
3595 };
3596
3597 let Some(tile) =
3598 self.sprite_atlas
3599 .get_or_insert_with(¶ms.clone().into(), &mut || {
3600 let Some((size, bytes)) = cx.svg_renderer.render_alpha_mask(¶ms, data)?
3601 else {
3602 return Ok(None);
3603 };
3604 Ok(Some((size, Cow::Owned(bytes))))
3605 })?
3606 else {
3607 return Ok(());
3608 };
3609 let content_mask = self.content_mask().scale(scale_factor);
3610 let svg_bounds = Bounds {
3611 origin: bounds.center()
3612 - Point::new(
3613 ScaledPixels(tile.bounds.size.width.0 as f32 / SMOOTH_SVG_SCALE_FACTOR / 2.),
3614 ScaledPixels(tile.bounds.size.height.0 as f32 / SMOOTH_SVG_SCALE_FACTOR / 2.),
3615 ),
3616 size: tile
3617 .bounds
3618 .size
3619 .map(|value| ScaledPixels(value.0 as f32 / SMOOTH_SVG_SCALE_FACTOR)),
3620 };
3621
3622 self.next_frame.scene.insert_primitive(MonochromeSprite {
3623 order: 0,
3624 pad: 0,
3625 bounds: svg_bounds
3626 .map_origin(|origin| origin.round())
3627 .map_size(|size| size.ceil()),
3628 content_mask,
3629 color: color.opacity(element_opacity),
3630 tile,
3631 transformation,
3632 });
3633
3634 Ok(())
3635 }
3636
3637 pub fn paint_image(
3642 &mut self,
3643 bounds: Bounds<Pixels>,
3644 corner_radii: Corners<Pixels>,
3645 data: Arc<RenderImage>,
3646 frame_index: usize,
3647 grayscale: bool,
3648 ) -> Result<()> {
3649 self.paint_image_with_transform(
3650 bounds,
3651 corner_radii,
3652 data,
3653 frame_index,
3654 grayscale,
3655 TransformationMatrix::unit(),
3656 )
3657 }
3658
3659 pub fn paint_image_with_transform(
3661 &mut self,
3662 bounds: Bounds<Pixels>,
3663 corner_radii: Corners<Pixels>,
3664 data: Arc<RenderImage>,
3665 frame_index: usize,
3666 grayscale: bool,
3667 transform: TransformationMatrix,
3668 ) -> Result<()> {
3669 self.invalidator.debug_assert_paint();
3670
3671 let scale_factor = self.scale_factor();
3672 let bounds = bounds.scale(scale_factor);
3673 let params = RenderImageParams {
3674 image_id: data.id,
3675 frame_index,
3676 };
3677
3678 let tile = self
3679 .sprite_atlas
3680 .get_or_insert_with(¶ms.into(), &mut || {
3681 Ok(Some((
3682 data.size(frame_index),
3683 Cow::Borrowed(
3684 data.as_bytes(frame_index)
3685 .expect("It's the caller's job to pass a valid frame index"),
3686 ),
3687 )))
3688 })?
3689 .expect("Callback above only returns Some");
3690 let content_mask = self.content_mask().scale(scale_factor);
3691 let corner_radii = corner_radii.scale(scale_factor);
3692 let opacity = self.element_opacity();
3693 let transform = self.scale_transform_for_scene(transform);
3694
3695 self.next_frame.scene.insert_primitive((
3696 PolychromeSprite {
3697 order: 0,
3698 pad: 0,
3699 grayscale,
3700 bounds: bounds
3701 .map_origin(|origin| origin.floor())
3702 .map_size(|size| size.ceil()),
3703 content_mask,
3704 corner_radii,
3705 tile,
3706 opacity,
3707 },
3708 transform,
3709 ));
3710 Ok(())
3711 }
3712
3713 fn scale_transform_for_scene(&self, transform: TransformationMatrix) -> TransformationMatrix {
3714 if transform.is_unit() {
3715 return transform;
3716 }
3717 let scale_factor = self.scale_factor();
3718 let mut scaled = transform;
3719 scaled.translation[0] *= scale_factor;
3720 scaled.translation[1] *= scale_factor;
3721 scaled
3722 }
3723
3724 #[cfg(target_os = "macos")]
3728 pub fn paint_surface(&mut self, bounds: Bounds<Pixels>, image_buffer: CVPixelBuffer) {
3729 use crate::PaintSurface;
3730
3731 self.invalidator.debug_assert_paint();
3732
3733 let scale_factor = self.scale_factor();
3734 let bounds = bounds.scale(scale_factor);
3735 let content_mask = self.content_mask().scale(scale_factor);
3736 self.next_frame.scene.insert_primitive(PaintSurface {
3737 order: 0,
3738 bounds,
3739 content_mask,
3740 image_buffer,
3741 });
3742 }
3743
3744 pub fn drop_image(&mut self, data: Arc<RenderImage>) -> Result<()> {
3746 for frame_index in 0..data.frame_count() {
3747 let params = RenderImageParams {
3748 image_id: data.id,
3749 frame_index,
3750 };
3751
3752 self.sprite_atlas.remove(¶ms.clone().into());
3753 }
3754
3755 Ok(())
3756 }
3757
3758 #[must_use]
3764 pub fn request_layout(
3765 &mut self,
3766 style: Style,
3767 children: impl IntoIterator<Item = LayoutId>,
3768 cx: &mut App,
3769 ) -> LayoutId {
3770 self.invalidator.debug_assert_prepaint();
3771
3772 cx.layout_id_buffer.clear();
3773 cx.layout_id_buffer.extend(children);
3774 let rem_size = self.rem_size();
3775 let scale_factor = self.scale_factor();
3776
3777 self.layout_engine.as_mut().unwrap().request_layout(
3778 style,
3779 rem_size,
3780 scale_factor,
3781 &cx.layout_id_buffer,
3782 )
3783 }
3784
3785 pub fn request_measured_layout<F>(&mut self, style: Style, measure: F) -> LayoutId
3794 where
3795 F: Fn(Size<Option<Pixels>>, Size<AvailableSpace>, &mut Window, &mut App) -> Size<Pixels>
3796 + 'static,
3797 {
3798 self.invalidator.debug_assert_prepaint();
3799
3800 let rem_size = self.rem_size();
3801 let scale_factor = self.scale_factor();
3802 self.layout_engine
3803 .as_mut()
3804 .unwrap()
3805 .request_measured_layout(style, rem_size, scale_factor, measure)
3806 }
3807
3808 pub fn compute_layout(
3814 &mut self,
3815 layout_id: LayoutId,
3816 available_space: Size<AvailableSpace>,
3817 cx: &mut App,
3818 ) {
3819 self.invalidator.debug_assert_prepaint();
3820
3821 let mut layout_engine = self.layout_engine.take().unwrap();
3822 layout_engine.compute_layout(layout_id, available_space, self, cx);
3823 self.layout_engine = Some(layout_engine);
3824 }
3825
3826 pub fn layout_bounds(&mut self, layout_id: LayoutId) -> Bounds<Pixels> {
3831 self.invalidator.debug_assert_prepaint();
3832
3833 let scale_factor = self.scale_factor();
3834 let mut bounds = self
3835 .layout_engine
3836 .as_mut()
3837 .unwrap()
3838 .layout_bounds(layout_id, scale_factor)
3839 .map(Into::into);
3840 bounds.origin += self.element_offset();
3841 bounds
3842 }
3843
3844 pub fn insert_hitbox(&mut self, bounds: Bounds<Pixels>, behavior: HitboxBehavior) -> Hitbox {
3850 self.invalidator.debug_assert_prepaint();
3851
3852 let content_mask = self.content_mask();
3853 let mut id = self.next_hitbox_id;
3854 self.next_hitbox_id = self.next_hitbox_id.next();
3855 let hitbox = Hitbox {
3856 id,
3857 bounds,
3858 content_mask,
3859 behavior,
3860 };
3861 self.next_frame.hitboxes.push(hitbox.clone());
3862 hitbox
3863 }
3864
3865 pub fn insert_window_control_hitbox(&mut self, area: WindowControlArea, hitbox: Hitbox) {
3869 self.invalidator.debug_assert_paint();
3870 self.next_frame.window_control_hitboxes.push((area, hitbox));
3871 }
3872
3873 pub fn set_key_context(&mut self, context: KeyContext) {
3878 self.invalidator.debug_assert_paint();
3879 self.next_frame.dispatch_tree.set_key_context(context);
3880 }
3881
3882 pub fn set_focus_handle(&mut self, focus_handle: &FocusHandle, _: &App) {
3887 self.invalidator.debug_assert_prepaint();
3888 if focus_handle.is_focused(self) {
3889 self.next_frame.focus = Some(focus_handle.id);
3890 }
3891 self.next_frame.dispatch_tree.set_focus_id(focus_handle.id);
3892 }
3893
3894 pub fn set_view_id(&mut self, view_id: EntityId) {
3900 self.invalidator.debug_assert_prepaint();
3901 self.next_frame.dispatch_tree.set_view_id(view_id);
3902 }
3903
3904 pub fn current_view(&self) -> EntityId {
3906 self.invalidator.debug_assert_paint_or_prepaint();
3907 if let Some(id) = self.rendered_entity_stack.last().copied() {
3908 return id;
3909 }
3910
3911 self.root
3916 .as_ref()
3917 .map(|root| root.entity_id())
3918 .expect("Window::current_view called with no rendered view and no root view")
3919 }
3920
3921 pub fn with_rendered_view<R>(
3927 &mut self,
3928 id: EntityId,
3929 f: impl FnOnce(&mut Self) -> R,
3930 ) -> R {
3931 self.rendered_entity_stack.push(id);
3932 let result = f(self);
3933 self.rendered_entity_stack.pop();
3934 result
3935 }
3936
3937 pub fn with_image_cache<F, R>(&mut self, image_cache: Option<AnyImageCache>, f: F) -> R
3939 where
3940 F: FnOnce(&mut Self) -> R,
3941 {
3942 if let Some(image_cache) = image_cache {
3943 self.image_cache_stack.push(image_cache);
3944 let result = f(self);
3945 self.image_cache_stack.pop();
3946 result
3947 } else {
3948 f(self)
3949 }
3950 }
3951
3952 pub fn handle_input(
3961 &mut self,
3962 focus_handle: &FocusHandle,
3963 input_handler: impl InputHandler,
3964 cx: &App,
3965 ) {
3966 self.invalidator.debug_assert_paint();
3967
3968 if focus_handle.is_focused(self) {
3969 let cx = self.to_async(cx);
3970 self.next_frame
3971 .input_handlers
3972 .push(Some(PlatformInputHandler::new(cx, Box::new(input_handler))));
3973 }
3974 }
3975
3976 pub fn on_mouse_event<Event: MouseEvent>(
3982 &mut self,
3983 mut listener: impl FnMut(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
3984 ) {
3985 self.invalidator.debug_assert_paint();
3986
3987 self.next_frame.mouse_listeners.push(Some(Box::new(
3988 move |event: &dyn Any, phase: DispatchPhase, window: &mut Window, cx: &mut App| {
3989 if let Some(event) = event.downcast_ref() {
3990 listener(event, phase, window, cx)
3991 }
3992 },
3993 )));
3994 }
3995
3996 pub fn on_key_event<Event: KeyEvent>(
4005 &mut self,
4006 listener: impl Fn(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
4007 ) {
4008 self.invalidator.debug_assert_paint();
4009
4010 self.next_frame.dispatch_tree.on_key_event(Rc::new(
4011 move |event: &dyn Any, phase, window: &mut Window, cx: &mut App| {
4012 if let Some(event) = event.downcast_ref::<Event>() {
4013 listener(event, phase, window, cx)
4014 }
4015 },
4016 ));
4017 }
4018
4019 pub fn on_modifiers_changed(
4026 &mut self,
4027 listener: impl Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static,
4028 ) {
4029 self.invalidator.debug_assert_paint();
4030
4031 self.next_frame.dispatch_tree.on_modifiers_changed(Rc::new(
4032 move |event: &ModifiersChangedEvent, window: &mut Window, cx: &mut App| {
4033 listener(event, window, cx)
4034 },
4035 ));
4036 }
4037
4038 pub fn on_focus_in(
4042 &mut self,
4043 handle: &FocusHandle,
4044 cx: &mut App,
4045 mut listener: impl FnMut(&mut Window, &mut App) + 'static,
4046 ) -> Subscription {
4047 let focus_id = handle.id;
4048 let (subscription, activate) =
4049 self.new_focus_listener(Box::new(move |event, window, cx| {
4050 if event.is_focus_in(focus_id) {
4051 listener(window, cx);
4052 }
4053 true
4054 }));
4055 cx.defer(move |_| activate());
4056 subscription
4057 }
4058
4059 pub fn on_focus_out(
4062 &mut self,
4063 handle: &FocusHandle,
4064 cx: &mut App,
4065 mut listener: impl FnMut(FocusOutEvent, &mut Window, &mut App) + 'static,
4066 ) -> Subscription {
4067 let focus_id = handle.id;
4068 let (subscription, activate) =
4069 self.new_focus_listener(Box::new(move |event, window, cx| {
4070 if let Some(blurred_id) = event.previous_focus_path.last().copied()
4071 && event.is_focus_out(focus_id)
4072 {
4073 let event = FocusOutEvent {
4074 blurred: WeakFocusHandle {
4075 id: blurred_id,
4076 handles: Arc::downgrade(&cx.focus_handles),
4077 },
4078 };
4079 listener(event, window, cx)
4080 }
4081 true
4082 }));
4083 cx.defer(move |_| activate());
4084 subscription
4085 }
4086
4087 fn reset_cursor_style(&self, cx: &mut App) {
4088 if self.is_window_hovered() {
4090 let style = self
4091 .rendered_frame
4092 .cursor_style(self)
4093 .unwrap_or(CursorStyle::Arrow);
4094 cx.platform.set_cursor_style(style);
4095 }
4096 }
4097
4098 pub fn dispatch_keystroke(&mut self, keystroke: Keystroke, cx: &mut App) -> bool {
4101 let keystroke = keystroke.with_simulated_ime();
4102 let result = self.dispatch_event(
4103 PlatformInput::KeyDown(KeyDownEvent {
4104 keystroke: keystroke.clone(),
4105 is_held: false,
4106 prefer_character_input: false,
4107 }),
4108 cx,
4109 );
4110 if !result.propagate {
4111 return true;
4112 }
4113
4114 if let Some(input) = keystroke.key_char
4115 && let Some(mut input_handler) = self.platform_window.take_input_handler()
4116 {
4117 input_handler.dispatch_input(&input, self, cx);
4118 self.platform_window.set_input_handler(input_handler);
4119 return true;
4120 }
4121
4122 false
4123 }
4124
4125 pub fn keystroke_text_for(&self, action: &dyn Action) -> String {
4128 self.highest_precedence_binding_for_action(action)
4129 .map(|binding| {
4130 binding
4131 .keystrokes()
4132 .iter()
4133 .map(ToString::to_string)
4134 .collect::<Vec<_>>()
4135 .join(" ")
4136 })
4137 .unwrap_or_else(|| action.name().to_string())
4138 }
4139
4140 #[profiling::function]
4142 pub fn dispatch_event(&mut self, event: PlatformInput, cx: &mut App) -> DispatchEventResult {
4143 self.last_input_modality = match &event {
4145 PlatformInput::KeyDown(_) | PlatformInput::ModifiersChanged(_) => {
4146 InputModality::Keyboard
4147 }
4148 PlatformInput::MouseDown(e) if e.is_focusing() => InputModality::Mouse,
4149 _ => self.last_input_modality,
4150 };
4151
4152 cx.propagate_event = true;
4154 self.default_prevented = false;
4156
4157 let event = match event {
4158 PlatformInput::MouseMove(mouse_move) => {
4161 self.mouse_position = mouse_move.position;
4162 self.modifiers = mouse_move.modifiers;
4163 PlatformInput::MouseMove(mouse_move)
4164 }
4165 PlatformInput::MouseDown(mouse_down) => {
4166 self.mouse_position = mouse_down.position;
4167 self.modifiers = mouse_down.modifiers;
4168 PlatformInput::MouseDown(mouse_down)
4169 }
4170 PlatformInput::MouseUp(mouse_up) => {
4171 self.mouse_position = mouse_up.position;
4172 self.modifiers = mouse_up.modifiers;
4173 PlatformInput::MouseUp(mouse_up)
4174 }
4175 PlatformInput::MousePressure(mouse_pressure) => {
4176 PlatformInput::MousePressure(mouse_pressure)
4177 }
4178 PlatformInput::MouseExited(mouse_exited) => {
4179 self.modifiers = mouse_exited.modifiers;
4180 PlatformInput::MouseExited(mouse_exited)
4181 }
4182 PlatformInput::ModifiersChanged(modifiers_changed) => {
4183 self.modifiers = modifiers_changed.modifiers;
4184 self.capslock = modifiers_changed.capslock;
4185 PlatformInput::ModifiersChanged(modifiers_changed)
4186 }
4187 PlatformInput::ScrollWheel(scroll_wheel) => {
4188 self.mouse_position = scroll_wheel.position;
4189 self.modifiers = scroll_wheel.modifiers;
4190 PlatformInput::ScrollWheel(scroll_wheel)
4191 }
4192 PlatformInput::FileDrop(file_drop) => match file_drop {
4195 FileDropEvent::Entered { position, paths } => {
4196 self.mouse_position = position;
4197 if cx.active_drag.is_none() {
4198 cx.active_drag = Some(AnyDrag {
4199 value: Arc::new(paths.clone()),
4200 view: cx.new(|_| paths).into(),
4201 cursor_offset: position,
4202 cursor_style: None,
4203 });
4204 }
4205 PlatformInput::MouseMove(MouseMoveEvent {
4206 position,
4207 pressed_button: Some(MouseButton::Left),
4208 modifiers: Modifiers::default(),
4209 })
4210 }
4211 FileDropEvent::Pending { position } => {
4212 self.mouse_position = position;
4213 PlatformInput::MouseMove(MouseMoveEvent {
4214 position,
4215 pressed_button: Some(MouseButton::Left),
4216 modifiers: Modifiers::default(),
4217 })
4218 }
4219 FileDropEvent::Submit { position } => {
4220 cx.activate(true);
4221 self.mouse_position = position;
4222 PlatformInput::MouseUp(MouseUpEvent {
4223 button: MouseButton::Left,
4224 position,
4225 modifiers: Modifiers::default(),
4226 click_count: 1,
4227 })
4228 }
4229 FileDropEvent::Exited => {
4230 cx.active_drag.take();
4231 PlatformInput::FileDrop(FileDropEvent::Exited)
4232 }
4233 },
4234 PlatformInput::KeyDown(_) | PlatformInput::KeyUp(_) => event,
4235 };
4236
4237 if let Some(any_mouse_event) = event.mouse_event() {
4238 self.dispatch_mouse_event(any_mouse_event, cx);
4239 } else if let Some(any_key_event) = event.keyboard_event() {
4240 self.dispatch_key_event(any_key_event, cx);
4241 }
4242
4243 if self.invalidator.is_dirty() {
4244 self.input_rate_tracker.borrow_mut().record_input();
4245 }
4246
4247 DispatchEventResult {
4248 propagate: cx.propagate_event,
4249 default_prevented: self.default_prevented,
4250 }
4251 }
4252
4253 fn dispatch_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
4254 let hit_test = self.rendered_frame.hit_test(self.mouse_position());
4255 if hit_test != self.mouse_hit_test {
4256 self.mouse_hit_test = hit_test;
4257 self.reset_cursor_style(cx);
4258 }
4259
4260 #[cfg(any(feature = "inspector", debug_assertions))]
4261 if self.is_inspector_picking(cx) {
4262 self.handle_inspector_mouse_event(event, cx);
4263 return;
4265 }
4266
4267 let mut mouse_listeners = mem::take(&mut self.rendered_frame.mouse_listeners);
4268
4269 for listener in &mut mouse_listeners {
4272 let listener = listener.as_mut().unwrap();
4273 listener(event, DispatchPhase::Capture, self, cx);
4274 if !cx.propagate_event {
4275 break;
4276 }
4277 }
4278
4279 if cx.propagate_event {
4281 for listener in mouse_listeners.iter_mut().rev() {
4282 let listener = listener.as_mut().unwrap();
4283 listener(event, DispatchPhase::Bubble, self, cx);
4284 if !cx.propagate_event {
4285 break;
4286 }
4287 }
4288 }
4289
4290 self.rendered_frame.mouse_listeners = mouse_listeners;
4291
4292 if cx.has_active_drag() {
4293 if event.is::<MouseMoveEvent>() {
4294 self.refresh();
4297 } else if event.is::<MouseUpEvent>() {
4298 cx.active_drag = None;
4301 self.refresh();
4302 }
4303 }
4304 }
4305
4306 fn dispatch_key_event(&mut self, event: &dyn Any, cx: &mut App) {
4307 if self.invalidator.is_dirty() {
4308 self.draw(cx).clear();
4309 }
4310
4311 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
4312 let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
4313
4314 let mut keystroke: Option<Keystroke> = None;
4315
4316 if let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() {
4317 if event.modifiers.number_of_modifiers() == 0
4318 && self.pending_modifier.modifiers.number_of_modifiers() == 1
4319 && !self.pending_modifier.saw_keystroke
4320 {
4321 let key = match self.pending_modifier.modifiers {
4322 modifiers if modifiers.shift => Some("shift"),
4323 modifiers if modifiers.control => Some("control"),
4324 modifiers if modifiers.alt => Some("alt"),
4325 modifiers if modifiers.platform => Some("platform"),
4326 modifiers if modifiers.function => Some("function"),
4327 _ => None,
4328 };
4329 if let Some(key) = key {
4330 keystroke = Some(Keystroke {
4331 key: key.to_string(),
4332 key_char: None,
4333 modifiers: Modifiers::default(),
4334 });
4335 }
4336 }
4337
4338 if self.pending_modifier.modifiers.number_of_modifiers() == 0
4339 && event.modifiers.number_of_modifiers() == 1
4340 {
4341 self.pending_modifier.saw_keystroke = false
4342 }
4343 self.pending_modifier.modifiers = event.modifiers
4344 } else if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
4345 self.pending_modifier.saw_keystroke = true;
4346 keystroke = Some(key_down_event.keystroke.clone());
4347 }
4348
4349 let Some(keystroke) = keystroke else {
4350 self.finish_dispatch_key_event(event, dispatch_path, self.context_stack(), cx);
4351 return;
4352 };
4353
4354 cx.propagate_event = true;
4355 self.dispatch_keystroke_interceptors(event, self.context_stack(), cx);
4356 if !cx.propagate_event {
4357 self.finish_dispatch_key_event(event, dispatch_path, self.context_stack(), cx);
4358 return;
4359 }
4360
4361 let mut currently_pending = self.pending_input.take().unwrap_or_default();
4362 if currently_pending.focus.is_some() && currently_pending.focus != self.focus {
4363 currently_pending = PendingInput::default();
4364 }
4365
4366 let match_result = self.rendered_frame.dispatch_tree.dispatch_key(
4367 currently_pending.keystrokes,
4368 keystroke,
4369 &dispatch_path,
4370 );
4371
4372 if !match_result.to_replay.is_empty() {
4373 self.replay_pending_input(match_result.to_replay, cx);
4374 cx.propagate_event = true;
4375 }
4376
4377 if !match_result.pending.is_empty() {
4378 currently_pending.timer.take();
4379 currently_pending.keystrokes = match_result.pending;
4380 currently_pending.focus = self.focus;
4381
4382 let text_input_requires_timeout = event
4383 .downcast_ref::<KeyDownEvent>()
4384 .filter(|key_down| key_down.keystroke.key_char.is_some())
4385 .and_then(|_| self.platform_window.take_input_handler())
4386 .map_or(false, |mut input_handler| {
4387 let accepts = input_handler.accepts_text_input(self, cx);
4388 self.platform_window.set_input_handler(input_handler);
4389 accepts
4390 });
4391
4392 currently_pending.needs_timeout |=
4393 match_result.pending_has_binding || text_input_requires_timeout;
4394
4395 if currently_pending.needs_timeout {
4396 currently_pending.timer = Some(self.spawn(cx, async move |cx| {
4397 cx.background_executor.timer(Duration::from_secs(1)).await;
4398 cx.update(move |window, cx| {
4399 let Some(currently_pending) = window
4400 .pending_input
4401 .take()
4402 .filter(|pending| pending.focus == window.focus)
4403 else {
4404 return;
4405 };
4406
4407 let node_id = window.focus_node_id_in_rendered_frame(window.focus);
4408 let dispatch_path =
4409 window.rendered_frame.dispatch_tree.dispatch_path(node_id);
4410
4411 let to_replay = window
4412 .rendered_frame
4413 .dispatch_tree
4414 .flush_dispatch(currently_pending.keystrokes, &dispatch_path);
4415
4416 window.pending_input_changed(cx);
4417 window.replay_pending_input(to_replay, cx)
4418 })
4419 .log_err();
4420 }));
4421 } else {
4422 currently_pending.timer = None;
4423 }
4424 self.pending_input = Some(currently_pending);
4425 self.pending_input_changed(cx);
4426 cx.propagate_event = false;
4427 return;
4428 }
4429
4430 let skip_bindings = event
4431 .downcast_ref::<KeyDownEvent>()
4432 .filter(|key_down_event| key_down_event.prefer_character_input)
4433 .map(|_| {
4434 self.platform_window
4435 .take_input_handler()
4436 .map_or(false, |mut input_handler| {
4437 let accepts = input_handler.accepts_text_input(self, cx);
4438 self.platform_window.set_input_handler(input_handler);
4439 accepts
4442 })
4443 })
4444 .unwrap_or(false);
4445
4446 if !skip_bindings {
4447 for binding in match_result.bindings {
4448 self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
4449 if !cx.propagate_event {
4450 self.dispatch_keystroke_observers(
4451 event,
4452 Some(binding.action),
4453 match_result.context_stack,
4454 cx,
4455 );
4456 self.pending_input_changed(cx);
4457 return;
4458 }
4459 }
4460 }
4461
4462 self.finish_dispatch_key_event(event, dispatch_path, match_result.context_stack, cx);
4463 self.pending_input_changed(cx);
4464 }
4465
4466 fn finish_dispatch_key_event(
4467 &mut self,
4468 event: &dyn Any,
4469 dispatch_path: SmallVec<[DispatchNodeId; 32]>,
4470 context_stack: Vec<KeyContext>,
4471 cx: &mut App,
4472 ) {
4473 self.dispatch_key_down_up_event(event, &dispatch_path, cx);
4474 if !cx.propagate_event {
4475 return;
4476 }
4477
4478 self.dispatch_modifiers_changed_event(event, &dispatch_path, cx);
4479 if !cx.propagate_event {
4480 return;
4481 }
4482
4483 self.dispatch_keystroke_observers(event, None, context_stack, cx);
4484 }
4485
4486 pub(crate) fn pending_input_changed(&mut self, cx: &mut App) {
4487 self.pending_input_observers
4488 .clone()
4489 .retain(&(), |callback| callback(self, cx));
4490 }
4491
4492 fn dispatch_key_down_up_event(
4493 &mut self,
4494 event: &dyn Any,
4495 dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
4496 cx: &mut App,
4497 ) {
4498 for node_id in dispatch_path {
4500 let node = self.rendered_frame.dispatch_tree.node(*node_id);
4501
4502 for key_listener in node.key_listeners.clone() {
4503 key_listener(event, DispatchPhase::Capture, self, cx);
4504 if !cx.propagate_event {
4505 return;
4506 }
4507 }
4508 }
4509
4510 for node_id in dispatch_path.iter().rev() {
4512 let node = self.rendered_frame.dispatch_tree.node(*node_id);
4514 for key_listener in node.key_listeners.clone() {
4515 key_listener(event, DispatchPhase::Bubble, self, cx);
4516 if !cx.propagate_event {
4517 return;
4518 }
4519 }
4520 }
4521 }
4522
4523 fn dispatch_modifiers_changed_event(
4524 &mut self,
4525 event: &dyn Any,
4526 dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
4527 cx: &mut App,
4528 ) {
4529 let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() else {
4530 return;
4531 };
4532 for node_id in dispatch_path.iter().rev() {
4533 let node = self.rendered_frame.dispatch_tree.node(*node_id);
4534 for listener in node.modifiers_changed_listeners.clone() {
4535 listener(event, self, cx);
4536 if !cx.propagate_event {
4537 return;
4538 }
4539 }
4540 }
4541 }
4542
4543 pub fn has_pending_keystrokes(&self) -> bool {
4545 self.pending_input.is_some()
4546 }
4547
4548 pub(crate) fn clear_pending_keystrokes(&mut self) {
4549 self.pending_input.take();
4550 }
4551
4552 pub fn pending_input_keystrokes(&self) -> Option<&[Keystroke]> {
4554 self.pending_input
4555 .as_ref()
4556 .map(|pending_input| pending_input.keystrokes.as_slice())
4557 }
4558
4559 fn replay_pending_input(&mut self, replays: SmallVec<[Replay; 1]>, cx: &mut App) {
4560 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
4561 let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
4562
4563 'replay: for replay in replays {
4564 let event = KeyDownEvent {
4565 keystroke: replay.keystroke.clone(),
4566 is_held: false,
4567 prefer_character_input: true,
4568 };
4569
4570 cx.propagate_event = true;
4571 for binding in replay.bindings {
4572 self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
4573 if !cx.propagate_event {
4574 self.dispatch_keystroke_observers(
4575 &event,
4576 Some(binding.action),
4577 Vec::default(),
4578 cx,
4579 );
4580 continue 'replay;
4581 }
4582 }
4583
4584 self.dispatch_key_down_up_event(&event, &dispatch_path, cx);
4585 if !cx.propagate_event {
4586 continue 'replay;
4587 }
4588 if let Some(input) = replay.keystroke.key_char.as_ref().cloned()
4589 && let Some(mut input_handler) = self.platform_window.take_input_handler()
4590 {
4591 input_handler.dispatch_input(&input, self, cx);
4592 self.platform_window.set_input_handler(input_handler)
4593 }
4594 }
4595 }
4596
4597 fn focus_node_id_in_rendered_frame(&self, focus_id: Option<FocusId>) -> DispatchNodeId {
4598 focus_id
4599 .and_then(|focus_id| {
4600 self.rendered_frame
4601 .dispatch_tree
4602 .focusable_node_id(focus_id)
4603 })
4604 .unwrap_or_else(|| self.rendered_frame.dispatch_tree.root_node_id())
4605 }
4606
4607 fn dispatch_action_on_node(
4608 &mut self,
4609 node_id: DispatchNodeId,
4610 action: &dyn Action,
4611 cx: &mut App,
4612 ) {
4613 let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
4614
4615 cx.propagate_event = true;
4617 if let Some(mut global_listeners) = cx
4618 .global_action_listeners
4619 .remove(&action.as_any().type_id())
4620 {
4621 for listener in &global_listeners {
4622 listener(action.as_any(), DispatchPhase::Capture, cx);
4623 if !cx.propagate_event {
4624 break;
4625 }
4626 }
4627
4628 global_listeners.extend(
4629 cx.global_action_listeners
4630 .remove(&action.as_any().type_id())
4631 .unwrap_or_default(),
4632 );
4633
4634 cx.global_action_listeners
4635 .insert(action.as_any().type_id(), global_listeners);
4636 }
4637
4638 if !cx.propagate_event {
4639 return;
4640 }
4641
4642 for node_id in &dispatch_path {
4644 let node = self.rendered_frame.dispatch_tree.node(*node_id);
4645 for DispatchActionListener {
4646 action_type,
4647 listener,
4648 } in node.action_listeners.clone()
4649 {
4650 let any_action = action.as_any();
4651 if action_type == any_action.type_id() {
4652 listener(any_action, DispatchPhase::Capture, self, cx);
4653
4654 if !cx.propagate_event {
4655 return;
4656 }
4657 }
4658 }
4659 }
4660
4661 for node_id in dispatch_path.iter().rev() {
4663 let node = self.rendered_frame.dispatch_tree.node(*node_id);
4664 for DispatchActionListener {
4665 action_type,
4666 listener,
4667 } in node.action_listeners.clone()
4668 {
4669 let any_action = action.as_any();
4670 if action_type == any_action.type_id() {
4671 cx.propagate_event = false; listener(any_action, DispatchPhase::Bubble, self, cx);
4673
4674 if !cx.propagate_event {
4675 return;
4676 }
4677 }
4678 }
4679 }
4680
4681 if let Some(mut global_listeners) = cx
4683 .global_action_listeners
4684 .remove(&action.as_any().type_id())
4685 {
4686 for listener in global_listeners.iter().rev() {
4687 cx.propagate_event = false; listener(action.as_any(), DispatchPhase::Bubble, cx);
4690 if !cx.propagate_event {
4691 break;
4692 }
4693 }
4694
4695 global_listeners.extend(
4696 cx.global_action_listeners
4697 .remove(&action.as_any().type_id())
4698 .unwrap_or_default(),
4699 );
4700
4701 cx.global_action_listeners
4702 .insert(action.as_any().type_id(), global_listeners);
4703 }
4704 }
4705
4706 pub fn observe_global<G: Global>(
4709 &mut self,
4710 cx: &mut App,
4711 f: impl Fn(&mut Window, &mut App) + 'static,
4712 ) -> Subscription {
4713 let window_handle = self.handle;
4714 let (subscription, activate) = cx.global_observers.insert(
4715 TypeId::of::<G>(),
4716 Box::new(move |cx| {
4717 window_handle
4718 .update(cx, |_, window, cx| f(window, cx))
4719 .is_ok()
4720 }),
4721 );
4722 cx.defer(move |_| activate());
4723 subscription
4724 }
4725
4726 pub fn activate_window(&self) {
4728 self.platform_window.activate();
4729 }
4730
4731 pub fn minimize_window(&self) {
4733 self.platform_window.minimize();
4734 }
4735
4736 pub fn toggle_fullscreen(&self) {
4738 self.platform_window.toggle_fullscreen();
4739 }
4740
4741 pub fn invalidate_character_coordinates(&self) {
4743 self.on_next_frame(|window, cx| {
4744 if let Some(mut input_handler) = window.platform_window.take_input_handler() {
4745 if let Some(bounds) = input_handler.selected_bounds(window, cx) {
4746 window.platform_window.update_ime_position(bounds);
4747 }
4748 window.platform_window.set_input_handler(input_handler);
4749 }
4750 });
4751 }
4752
4753 pub fn prompt<T>(
4757 &mut self,
4758 level: PromptLevel,
4759 message: &str,
4760 detail: Option<&str>,
4761 answers: &[T],
4762 cx: &mut App,
4763 ) -> oneshot::Receiver<usize>
4764 where
4765 T: Clone + Into<PromptButton>,
4766 {
4767 let prompt_builder = cx.prompt_builder.take();
4768 let Some(prompt_builder) = prompt_builder else {
4769 unreachable!("Re-entrant window prompting is not supported by GPUI");
4770 };
4771
4772 let answers = answers
4773 .iter()
4774 .map(|answer| answer.clone().into())
4775 .collect::<Vec<_>>();
4776
4777 let receiver = match &prompt_builder {
4778 PromptBuilder::Default => self
4779 .platform_window
4780 .prompt(level, message, detail, &answers)
4781 .unwrap_or_else(|| {
4782 self.build_custom_prompt(&prompt_builder, level, message, detail, &answers, cx)
4783 }),
4784 PromptBuilder::Custom(_) => {
4785 self.build_custom_prompt(&prompt_builder, level, message, detail, &answers, cx)
4786 }
4787 };
4788
4789 cx.prompt_builder = Some(prompt_builder);
4790
4791 receiver
4792 }
4793
4794 fn build_custom_prompt(
4795 &mut self,
4796 prompt_builder: &PromptBuilder,
4797 level: PromptLevel,
4798 message: &str,
4799 detail: Option<&str>,
4800 answers: &[PromptButton],
4801 cx: &mut App,
4802 ) -> oneshot::Receiver<usize> {
4803 let (sender, receiver) = oneshot::channel();
4804 let handle = PromptHandle::new(sender);
4805 let handle = (prompt_builder)(level, message, detail, answers, handle, self, cx);
4806 self.prompt = Some(handle);
4807 receiver
4808 }
4809
4810 pub fn context_stack(&self) -> Vec<KeyContext> {
4812 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
4813 let dispatch_tree = &self.rendered_frame.dispatch_tree;
4814 dispatch_tree
4815 .dispatch_path(node_id)
4816 .iter()
4817 .filter_map(move |&node_id| dispatch_tree.node(node_id).context.clone())
4818 .collect()
4819 }
4820
4821 pub fn available_actions(&self, cx: &App) -> Vec<Box<dyn Action>> {
4823 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
4824 let mut actions = self.rendered_frame.dispatch_tree.available_actions(node_id);
4825 for action_type in cx.global_action_listeners.keys() {
4826 if let Err(ix) = actions.binary_search_by_key(action_type, |a| a.as_any().type_id()) {
4827 let action = cx.actions.build_action_type(action_type).ok();
4828 if let Some(action) = action {
4829 actions.insert(ix, action);
4830 }
4831 }
4832 }
4833 actions
4834 }
4835
4836 pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
4839 self.rendered_frame
4840 .dispatch_tree
4841 .bindings_for_action(action, &self.rendered_frame.dispatch_tree.context_stack)
4842 }
4843
4844 pub fn highest_precedence_binding_for_action(&self, action: &dyn Action) -> Option<KeyBinding> {
4847 self.rendered_frame
4848 .dispatch_tree
4849 .highest_precedence_binding_for_action(
4850 action,
4851 &self.rendered_frame.dispatch_tree.context_stack,
4852 )
4853 }
4854
4855 pub fn bindings_for_action_in_context(
4857 &self,
4858 action: &dyn Action,
4859 context: KeyContext,
4860 ) -> Vec<KeyBinding> {
4861 let dispatch_tree = &self.rendered_frame.dispatch_tree;
4862 dispatch_tree.bindings_for_action(action, &[context])
4863 }
4864
4865 pub fn highest_precedence_binding_for_action_in_context(
4868 &self,
4869 action: &dyn Action,
4870 context: KeyContext,
4871 ) -> Option<KeyBinding> {
4872 let dispatch_tree = &self.rendered_frame.dispatch_tree;
4873 dispatch_tree.highest_precedence_binding_for_action(action, &[context])
4874 }
4875
4876 pub fn bindings_for_action_in(
4880 &self,
4881 action: &dyn Action,
4882 focus_handle: &FocusHandle,
4883 ) -> Vec<KeyBinding> {
4884 let dispatch_tree = &self.rendered_frame.dispatch_tree;
4885 let Some(context_stack) = self.context_stack_for_focus_handle(focus_handle) else {
4886 return vec![];
4887 };
4888 dispatch_tree.bindings_for_action(action, &context_stack)
4889 }
4890
4891 pub fn highest_precedence_binding_for_action_in(
4895 &self,
4896 action: &dyn Action,
4897 focus_handle: &FocusHandle,
4898 ) -> Option<KeyBinding> {
4899 let dispatch_tree = &self.rendered_frame.dispatch_tree;
4900 let context_stack = self.context_stack_for_focus_handle(focus_handle)?;
4901 dispatch_tree.highest_precedence_binding_for_action(action, &context_stack)
4902 }
4903
4904 pub fn possible_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
4906 self.rendered_frame
4907 .dispatch_tree
4908 .possible_next_bindings_for_input(input, &self.context_stack())
4909 }
4910
4911 fn context_stack_for_focus_handle(
4912 &self,
4913 focus_handle: &FocusHandle,
4914 ) -> Option<Vec<KeyContext>> {
4915 let dispatch_tree = &self.rendered_frame.dispatch_tree;
4916 let node_id = dispatch_tree.focusable_node_id(focus_handle.id)?;
4917 let context_stack: Vec<_> = dispatch_tree
4918 .dispatch_path(node_id)
4919 .into_iter()
4920 .filter_map(|node_id| dispatch_tree.node(node_id).context.clone())
4921 .collect();
4922 Some(context_stack)
4923 }
4924
4925 pub fn listener_for<T: 'static, E>(
4927 &self,
4928 view: &Entity<T>,
4929 f: impl Fn(&mut T, &E, &mut Window, &mut Context<T>) + 'static,
4930 ) -> impl Fn(&E, &mut Window, &mut App) + 'static {
4931 let view = view.downgrade();
4932 move |e: &E, window: &mut Window, cx: &mut App| {
4933 view.update(cx, |view, cx| f(view, e, window, cx)).ok();
4934 }
4935 }
4936
4937 pub fn handler_for<E: 'static, Callback: Fn(&mut E, &mut Window, &mut Context<E>) + 'static>(
4939 &self,
4940 entity: &Entity<E>,
4941 f: Callback,
4942 ) -> impl Fn(&mut Window, &mut App) + 'static {
4943 let entity = entity.downgrade();
4944 move |window: &mut Window, cx: &mut App| {
4945 entity.update(cx, |entity, cx| f(entity, window, cx)).ok();
4946 }
4947 }
4948
4949 pub fn on_window_should_close(
4952 &self,
4953 cx: &App,
4954 f: impl Fn(&mut Window, &mut App) -> bool + 'static,
4955 ) {
4956 let mut cx = self.to_async(cx);
4957 self.platform_window.on_should_close(Box::new(move || {
4958 cx.update(|window, cx| f(window, cx)).unwrap_or(true)
4959 }))
4960 }
4961
4962 pub fn on_action(
4971 &mut self,
4972 action_type: TypeId,
4973 listener: impl Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static,
4974 ) {
4975 self.invalidator.debug_assert_paint();
4976
4977 self.next_frame
4978 .dispatch_tree
4979 .on_action(action_type, Rc::new(listener));
4980 }
4981
4982 pub fn on_action_when(
4991 &mut self,
4992 condition: bool,
4993 action_type: TypeId,
4994 listener: impl Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static,
4995 ) {
4996 self.invalidator.debug_assert_paint();
4997
4998 if condition {
4999 self.next_frame
5000 .dispatch_tree
5001 .on_action(action_type, Rc::new(listener));
5002 }
5003 }
5004
5005 pub fn gpu_specs(&self) -> Option<GpuSpecs> {
5008 self.platform_window.gpu_specs()
5009 }
5010
5011 pub fn titlebar_double_click(&self) {
5014 self.platform_window.titlebar_double_click();
5015 }
5016
5017 pub fn window_title(&self) -> String {
5020 self.platform_window.get_title()
5021 }
5022
5023 pub fn tabbed_windows(&self) -> Option<Vec<SystemWindowTab>> {
5026 self.platform_window.tabbed_windows()
5027 }
5028
5029 pub fn tab_bar_visible(&self) -> bool {
5032 self.platform_window.tab_bar_visible()
5033 }
5034
5035 pub fn merge_all_windows(&self) {
5038 self.platform_window.merge_all_windows()
5039 }
5040
5041 pub fn move_tab_to_new_window(&self) {
5044 self.platform_window.move_tab_to_new_window()
5045 }
5046
5047 pub fn toggle_window_tab_overview(&self) {
5050 self.platform_window.toggle_window_tab_overview()
5051 }
5052
5053 pub fn set_tabbing_identifier(&self, tabbing_identifier: Option<String>) {
5056 self.platform_window
5057 .set_tabbing_identifier(tabbing_identifier)
5058 }
5059
5060 #[cfg(any(feature = "inspector", debug_assertions))]
5062 pub fn toggle_inspector(&mut self, cx: &mut App) {
5063 self.inspector = match self.inspector {
5064 None => Some(cx.new(|_| Inspector::new())),
5065 Some(_) => None,
5066 };
5067 self.refresh();
5068 }
5069
5070 pub fn is_inspector_picking(&self, _cx: &App) -> bool {
5072 #[cfg(any(feature = "inspector", debug_assertions))]
5073 {
5074 if let Some(inspector) = &self.inspector {
5075 return inspector.read(_cx).is_picking();
5076 }
5077 }
5078 false
5079 }
5080
5081 #[cfg(any(feature = "inspector", debug_assertions))]
5083 pub fn with_inspector_state<T: 'static, R>(
5084 &mut self,
5085 _inspector_id: Option<&crate::InspectorElementId>,
5086 cx: &mut App,
5087 f: impl FnOnce(&mut Option<T>, &mut Self) -> R,
5088 ) -> R {
5089 if let Some(inspector_id) = _inspector_id
5090 && let Some(inspector) = &self.inspector
5091 {
5092 let inspector = inspector.clone();
5093 let active_element_id = inspector.read(cx).active_element_id();
5094 if Some(inspector_id) == active_element_id {
5095 return inspector.update(cx, |inspector, _cx| {
5096 inspector.with_active_element_state(self, f)
5097 });
5098 }
5099 }
5100 f(&mut None, self)
5101 }
5102
5103 #[cfg(any(feature = "inspector", debug_assertions))]
5104 pub(crate) fn build_inspector_element_id(
5105 &mut self,
5106 path: crate::InspectorElementPath,
5107 ) -> crate::InspectorElementId {
5108 self.invalidator.debug_assert_paint_or_prepaint();
5109 let path = Rc::new(path);
5110 let next_instance_id = self
5111 .next_frame
5112 .next_inspector_instance_ids
5113 .entry(path.clone())
5114 .or_insert(0);
5115 let instance_id = *next_instance_id;
5116 *next_instance_id += 1;
5117 crate::InspectorElementId { path, instance_id }
5118 }
5119
5120 #[cfg(any(feature = "inspector", debug_assertions))]
5121 fn prepaint_inspector(&mut self, inspector_width: Pixels, cx: &mut App) -> Option<AnyElement> {
5122 if let Some(inspector) = self.inspector.take() {
5123 let mut inspector_element = AnyView::from(inspector.clone()).into_any_element();
5124 inspector_element.prepaint_as_root(
5125 point(self.viewport_size.width - inspector_width, px(0.0)),
5126 size(inspector_width, self.viewport_size.height).into(),
5127 self,
5128 cx,
5129 );
5130 self.inspector = Some(inspector);
5131 Some(inspector_element)
5132 } else {
5133 None
5134 }
5135 }
5136
5137 #[cfg(any(feature = "inspector", debug_assertions))]
5138 fn paint_inspector(&mut self, mut inspector_element: Option<AnyElement>, cx: &mut App) {
5139 if let Some(mut inspector_element) = inspector_element {
5140 inspector_element.paint(self, cx);
5141 };
5142 }
5143
5144 #[cfg(any(feature = "inspector", debug_assertions))]
5147 pub fn insert_inspector_hitbox(
5148 &mut self,
5149 hitbox_id: HitboxId,
5150 inspector_id: Option<&crate::InspectorElementId>,
5151 cx: &App,
5152 ) {
5153 self.invalidator.debug_assert_paint_or_prepaint();
5154 if !self.is_inspector_picking(cx) {
5155 return;
5156 }
5157 if let Some(inspector_id) = inspector_id {
5158 self.next_frame
5159 .inspector_hitboxes
5160 .insert(hitbox_id, inspector_id.clone());
5161 }
5162 }
5163
5164 #[cfg(any(feature = "inspector", debug_assertions))]
5165 fn paint_inspector_hitbox(&mut self, cx: &App) {
5166 if let Some(inspector) = self.inspector.as_ref() {
5167 let inspector = inspector.read(cx);
5168 if let Some((hitbox_id, _)) = self.hovered_inspector_hitbox(inspector, &self.next_frame)
5169 && let Some(hitbox) = self
5170 .next_frame
5171 .hitboxes
5172 .iter()
5173 .find(|hitbox| hitbox.id == hitbox_id)
5174 {
5175 self.paint_quad(crate::fill(hitbox.bounds, crate::rgba(0x61afef4d)));
5176 }
5177 }
5178 }
5179
5180 #[cfg(any(feature = "inspector", debug_assertions))]
5181 fn handle_inspector_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
5182 let Some(inspector) = self.inspector.clone() else {
5183 return;
5184 };
5185 if event.downcast_ref::<MouseMoveEvent>().is_some() {
5186 inspector.update(cx, |inspector, _cx| {
5187 if let Some((_, inspector_id)) =
5188 self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
5189 {
5190 inspector.hover(inspector_id, self);
5191 }
5192 });
5193 } else if event.downcast_ref::<crate::MouseDownEvent>().is_some() {
5194 inspector.update(cx, |inspector, _cx| {
5195 if let Some((_, inspector_id)) =
5196 self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
5197 {
5198 inspector.select(inspector_id, self);
5199 }
5200 });
5201 } else if let Some(event) = event.downcast_ref::<crate::ScrollWheelEvent>() {
5202 const SCROLL_LINES: f32 = 3.0;
5204 const SCROLL_PIXELS_PER_LAYER: f32 = 36.0;
5205 let delta_y = event
5206 .delta
5207 .pixel_delta(px(SCROLL_PIXELS_PER_LAYER / SCROLL_LINES))
5208 .y;
5209 if let Some(inspector) = self.inspector.clone() {
5210 inspector.update(cx, |inspector, _cx| {
5211 if let Some(depth) = inspector.pick_depth.as_mut() {
5212 *depth += f32::from(delta_y) / SCROLL_PIXELS_PER_LAYER;
5213 let max_depth = self.mouse_hit_test.ids.len() as f32 - 0.5;
5214 if *depth < 0.0 {
5215 *depth = 0.0;
5216 } else if *depth > max_depth {
5217 *depth = max_depth;
5218 }
5219 if let Some((_, inspector_id)) =
5220 self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
5221 {
5222 inspector.set_active_element_id(inspector_id, self);
5223 }
5224 }
5225 });
5226 }
5227 }
5228 }
5229
5230 #[cfg(any(feature = "inspector", debug_assertions))]
5231 fn hovered_inspector_hitbox(
5232 &self,
5233 inspector: &Inspector,
5234 frame: &Frame,
5235 ) -> Option<(HitboxId, crate::InspectorElementId)> {
5236 if let Some(pick_depth) = inspector.pick_depth {
5237 let depth = (pick_depth as i64).try_into().unwrap_or(0);
5238 let max_skipped = self.mouse_hit_test.ids.len().saturating_sub(1);
5239 let skip_count = (depth as usize).min(max_skipped);
5240 for hitbox_id in self.mouse_hit_test.ids.iter().skip(skip_count) {
5241 if let Some(inspector_id) = frame.inspector_hitboxes.get(hitbox_id) {
5242 return Some((*hitbox_id, inspector_id.clone()));
5243 }
5244 }
5245 }
5246 None
5247 }
5248
5249 #[cfg(any(test, feature = "test-support"))]
5252 pub fn set_modifiers(&mut self, modifiers: Modifiers) {
5253 self.modifiers = modifiers;
5254 }
5255}
5256
5257slotmap::new_key_type! {
5259 pub struct WindowId;
5261}
5262
5263impl WindowId {
5264 pub fn as_u64(&self) -> u64 {
5266 self.0.as_ffi()
5267 }
5268}
5269
5270impl From<u64> for WindowId {
5271 fn from(value: u64) -> Self {
5272 WindowId(slotmap::KeyData::from_ffi(value))
5273 }
5274}
5275
5276#[derive(Deref, DerefMut)]
5279pub struct WindowHandle<V> {
5280 #[deref]
5281 #[deref_mut]
5282 pub(crate) any_handle: AnyWindowHandle,
5283 state_type: PhantomData<fn(V) -> V>,
5284}
5285
5286impl<V> Debug for WindowHandle<V> {
5287 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
5288 f.debug_struct("WindowHandle")
5289 .field("any_handle", &self.any_handle.id.as_u64())
5290 .finish()
5291 }
5292}
5293
5294impl<V: 'static + Render> WindowHandle<V> {
5295 pub fn new(id: WindowId) -> Self {
5298 WindowHandle {
5299 any_handle: AnyWindowHandle {
5300 id,
5301 state_type: TypeId::of::<V>(),
5302 },
5303 state_type: PhantomData,
5304 }
5305 }
5306
5307 #[cfg(any(test, feature = "test-support"))]
5311 pub fn root<C>(&self, cx: &mut C) -> Result<Entity<V>>
5312 where
5313 C: AppContext,
5314 {
5315 crate::Flatten::flatten(cx.update_window(self.any_handle, |root_view, _, _| {
5316 root_view
5317 .downcast::<V>()
5318 .map_err(|_| anyhow!("the type of the window's root view has changed"))
5319 }))
5320 }
5321
5322 pub fn update<C, R>(
5326 &self,
5327 cx: &mut C,
5328 update: impl FnOnce(&mut V, &mut Window, &mut Context<V>) -> R,
5329 ) -> Result<R>
5330 where
5331 C: AppContext,
5332 {
5333 cx.update_window(self.any_handle, |root_view, window, cx| {
5334 let view = root_view
5335 .downcast::<V>()
5336 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
5337
5338 Ok(view.update(cx, |view, cx| update(view, window, cx)))
5339 })?
5340 }
5341
5342 pub fn read<'a>(&self, cx: &'a App) -> Result<&'a V> {
5346 let x = cx
5347 .windows
5348 .get(self.id)
5349 .and_then(|window| {
5350 window
5351 .as_deref()
5352 .and_then(|window| window.root.clone())
5353 .map(|root_view| root_view.downcast::<V>())
5354 })
5355 .context("window not found")?
5356 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
5357
5358 Ok(x.read(cx))
5359 }
5360
5361 pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &App) -> R) -> Result<R>
5365 where
5366 C: AppContext,
5367 {
5368 cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
5369 }
5370
5371 pub fn entity<C>(&self, cx: &C) -> Result<Entity<V>>
5375 where
5376 C: AppContext,
5377 {
5378 cx.read_window(self, |root_view, _cx| root_view)
5379 }
5380
5381 pub fn is_active(&self, cx: &mut App) -> Option<bool> {
5386 cx.update_window(self.any_handle, |_, window, _| window.is_window_active())
5387 .ok()
5388 }
5389}
5390
5391impl<V> Copy for WindowHandle<V> {}
5392
5393impl<V> Clone for WindowHandle<V> {
5394 fn clone(&self) -> Self {
5395 *self
5396 }
5397}
5398
5399impl<V> PartialEq for WindowHandle<V> {
5400 fn eq(&self, other: &Self) -> bool {
5401 self.any_handle == other.any_handle
5402 }
5403}
5404
5405impl<V> Eq for WindowHandle<V> {}
5406
5407impl<V> Hash for WindowHandle<V> {
5408 fn hash<H: Hasher>(&self, state: &mut H) {
5409 self.any_handle.hash(state);
5410 }
5411}
5412
5413impl<V: 'static> From<WindowHandle<V>> for AnyWindowHandle {
5414 fn from(val: WindowHandle<V>) -> Self {
5415 val.any_handle
5416 }
5417}
5418
5419#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
5421pub struct AnyWindowHandle {
5422 pub(crate) id: WindowId,
5423 state_type: TypeId,
5424}
5425
5426impl AnyWindowHandle {
5427 pub fn window_id(&self) -> WindowId {
5429 self.id
5430 }
5431
5432 pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
5435 if TypeId::of::<T>() == self.state_type {
5436 Some(WindowHandle {
5437 any_handle: *self,
5438 state_type: PhantomData,
5439 })
5440 } else {
5441 None
5442 }
5443 }
5444
5445 pub fn update<C, R>(
5449 self,
5450 cx: &mut C,
5451 update: impl FnOnce(AnyView, &mut Window, &mut App) -> R,
5452 ) -> Result<R>
5453 where
5454 C: AppContext,
5455 {
5456 cx.update_window(self, update)
5457 }
5458
5459 pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(Entity<T>, &App) -> R) -> Result<R>
5463 where
5464 C: AppContext,
5465 T: 'static,
5466 {
5467 let view = self
5468 .downcast::<T>()
5469 .context("the type of the window's root view has changed")?;
5470
5471 cx.read_window(&view, read)
5472 }
5473}
5474
5475impl HasWindowHandle for Window {
5476 fn window_handle(&self) -> Result<raw_window_handle::WindowHandle<'_>, HandleError> {
5477 self.platform_window.window_handle()
5478 }
5479}
5480
5481impl HasDisplayHandle for Window {
5482 fn display_handle(
5483 &self,
5484 ) -> std::result::Result<raw_window_handle::DisplayHandle<'_>, HandleError> {
5485 self.platform_window.display_handle()
5486 }
5487}
5488
5489#[derive(Clone, Debug, Eq, PartialEq, Hash)]
5494pub enum ElementId {
5495 View(EntityId),
5497 Integer(u64),
5499 Name(SharedString),
5501 Uuid(Uuid),
5503 FocusHandle(FocusId),
5505 NamedInteger(SharedString, u64),
5507 Path(Arc<std::path::Path>),
5509 CodeLocation(core::panic::Location<'static>),
5511 NamedChild(Arc<ElementId>, SharedString),
5513}
5514
5515impl ElementId {
5516 pub fn named_usize(name: impl Into<SharedString>, integer: usize) -> ElementId {
5518 Self::NamedInteger(name.into(), integer as u64)
5519 }
5520}
5521
5522impl Display for ElementId {
5523 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
5524 match self {
5525 ElementId::View(entity_id) => write!(f, "view-{}", entity_id)?,
5526 ElementId::Integer(ix) => write!(f, "{}", ix)?,
5527 ElementId::Name(name) => write!(f, "{}", name)?,
5528 ElementId::FocusHandle(_) => write!(f, "FocusHandle")?,
5529 ElementId::NamedInteger(s, i) => write!(f, "{}-{}", s, i)?,
5530 ElementId::Uuid(uuid) => write!(f, "{}", uuid)?,
5531 ElementId::Path(path) => write!(f, "{}", path.display())?,
5532 ElementId::CodeLocation(location) => write!(f, "{}", location)?,
5533 ElementId::NamedChild(id, name) => write!(f, "{}-{}", id, name)?,
5534 }
5535
5536 Ok(())
5537 }
5538}
5539
5540impl TryInto<SharedString> for ElementId {
5541 type Error = anyhow::Error;
5542
5543 fn try_into(self) -> anyhow::Result<SharedString> {
5544 if let ElementId::Name(name) = self {
5545 Ok(name)
5546 } else {
5547 anyhow::bail!("element id is not string")
5548 }
5549 }
5550}
5551
5552impl From<usize> for ElementId {
5553 fn from(id: usize) -> Self {
5554 ElementId::Integer(id as u64)
5555 }
5556}
5557
5558impl From<i32> for ElementId {
5559 fn from(id: i32) -> Self {
5560 Self::Integer(id as u64)
5561 }
5562}
5563
5564impl From<SharedString> for ElementId {
5565 fn from(name: SharedString) -> Self {
5566 ElementId::Name(name)
5567 }
5568}
5569
5570impl From<String> for ElementId {
5571 fn from(name: String) -> Self {
5572 ElementId::Name(name.into())
5573 }
5574}
5575
5576impl From<Arc<str>> for ElementId {
5577 fn from(name: Arc<str>) -> Self {
5578 ElementId::Name(name.into())
5579 }
5580}
5581
5582impl From<Arc<std::path::Path>> for ElementId {
5583 fn from(path: Arc<std::path::Path>) -> Self {
5584 ElementId::Path(path)
5585 }
5586}
5587
5588impl From<&'static str> for ElementId {
5589 fn from(name: &'static str) -> Self {
5590 ElementId::Name(name.into())
5591 }
5592}
5593
5594impl<'a> From<&'a FocusHandle> for ElementId {
5595 fn from(handle: &'a FocusHandle) -> Self {
5596 ElementId::FocusHandle(handle.id)
5597 }
5598}
5599
5600impl From<(&'static str, EntityId)> for ElementId {
5601 fn from((name, id): (&'static str, EntityId)) -> Self {
5602 ElementId::NamedInteger(name.into(), id.as_u64())
5603 }
5604}
5605
5606impl From<(&'static str, usize)> for ElementId {
5607 fn from((name, id): (&'static str, usize)) -> Self {
5608 ElementId::NamedInteger(name.into(), id as u64)
5609 }
5610}
5611
5612impl From<(SharedString, usize)> for ElementId {
5613 fn from((name, id): (SharedString, usize)) -> Self {
5614 ElementId::NamedInteger(name, id as u64)
5615 }
5616}
5617
5618impl From<(&'static str, u64)> for ElementId {
5619 fn from((name, id): (&'static str, u64)) -> Self {
5620 ElementId::NamedInteger(name.into(), id)
5621 }
5622}
5623
5624impl From<Uuid> for ElementId {
5625 fn from(value: Uuid) -> Self {
5626 Self::Uuid(value)
5627 }
5628}
5629
5630impl From<(&'static str, u32)> for ElementId {
5631 fn from((name, id): (&'static str, u32)) -> Self {
5632 ElementId::NamedInteger(name.into(), id.into())
5633 }
5634}
5635
5636impl<T: Into<SharedString>> From<(ElementId, T)> for ElementId {
5637 fn from((id, name): (ElementId, T)) -> Self {
5638 ElementId::NamedChild(Arc::new(id), name.into())
5639 }
5640}
5641
5642impl From<&'static core::panic::Location<'static>> for ElementId {
5643 fn from(location: &'static core::panic::Location<'static>) -> Self {
5644 ElementId::CodeLocation(*location)
5645 }
5646}
5647
5648#[derive(Clone)]
5651pub struct PaintQuad {
5652 pub bounds: Bounds<Pixels>,
5654 pub corner_radii: Corners<Pixels>,
5656 pub background: Background,
5658 pub border_widths: Edges<Pixels>,
5660 pub border_color: Hsla,
5662 pub border_style: BorderStyle,
5664}
5665
5666impl PaintQuad {
5667 pub fn corner_radii(self, corner_radii: impl Into<Corners<Pixels>>) -> Self {
5669 PaintQuad {
5670 corner_radii: corner_radii.into(),
5671 ..self
5672 }
5673 }
5674
5675 pub fn border_widths(self, border_widths: impl Into<Edges<Pixels>>) -> Self {
5677 PaintQuad {
5678 border_widths: border_widths.into(),
5679 ..self
5680 }
5681 }
5682
5683 pub fn border_color(self, border_color: impl Into<Hsla>) -> Self {
5685 PaintQuad {
5686 border_color: border_color.into(),
5687 ..self
5688 }
5689 }
5690
5691 pub fn background(self, background: impl Into<Background>) -> Self {
5693 PaintQuad {
5694 background: background.into(),
5695 ..self
5696 }
5697 }
5698}
5699
5700pub fn quad(
5702 bounds: Bounds<Pixels>,
5703 corner_radii: impl Into<Corners<Pixels>>,
5704 background: impl Into<Background>,
5705 border_widths: impl Into<Edges<Pixels>>,
5706 border_color: impl Into<Hsla>,
5707 border_style: BorderStyle,
5708) -> PaintQuad {
5709 PaintQuad {
5710 bounds,
5711 corner_radii: corner_radii.into(),
5712 background: background.into(),
5713 border_widths: border_widths.into(),
5714 border_color: border_color.into(),
5715 border_style,
5716 }
5717}
5718
5719pub fn fill(bounds: impl Into<Bounds<Pixels>>, background: impl Into<Background>) -> PaintQuad {
5721 PaintQuad {
5722 bounds: bounds.into(),
5723 corner_radii: (0.).into(),
5724 background: background.into(),
5725 border_widths: (0.).into(),
5726 border_color: transparent_black(),
5727 border_style: BorderStyle::default(),
5728 }
5729}
5730
5731pub fn outline(
5733 bounds: impl Into<Bounds<Pixels>>,
5734 border_color: impl Into<Hsla>,
5735 border_style: BorderStyle,
5736) -> PaintQuad {
5737 PaintQuad {
5738 bounds: bounds.into(),
5739 corner_radii: (0.).into(),
5740 background: transparent_black().into(),
5741 border_widths: (1.).into(),
5742 border_color: border_color.into(),
5743 border_style,
5744 }
5745}