1use crate::{
2 key_dispatch::DispatchActionListener, px, size, Action, AnyDrag, AnyView, AppContext,
3 AsyncWindowContext, AvailableSpace, Bounds, BoxShadow, Context, Corners, CursorStyle,
4 DevicePixels, DispatchNodeId, DispatchTree, DisplayId, Edges, Effect, Entity, EntityId,
5 EventEmitter, FileDropEvent, Flatten, FontId, GlobalElementId, GlyphId, Hsla, ImageData,
6 InputEvent, IsZero, KeyBinding, KeyContext, KeyDownEvent, KeystrokeEvent, LayoutId, Model,
7 ModelContext, Modifiers, MonochromeSprite, MouseButton, MouseMoveEvent, MouseUpEvent, Path,
8 Pixels, PlatformAtlas, PlatformDisplay, PlatformInputHandler, PlatformWindow, Point,
9 PolychromeSprite, PromptLevel, Quad, Render, RenderGlyphParams, RenderImageParams,
10 RenderSvgParams, ScaledPixels, Scene, SceneBuilder, Shadow, SharedString, Size, Style,
11 SubscriberSet, Subscription, Surface, TaffyLayoutEngine, Task, Underline, UnderlineStyle, View,
12 VisualContext, WeakView, WindowBounds, WindowOptions, SUBPIXEL_VARIANTS,
13};
14use anyhow::{anyhow, Context as _, Result};
15use collections::HashMap;
16use derive_more::{Deref, DerefMut};
17use futures::{
18 channel::{mpsc, oneshot},
19 StreamExt,
20};
21use media::core_video::CVImageBuffer;
22use parking_lot::RwLock;
23use slotmap::SlotMap;
24use smallvec::SmallVec;
25use std::{
26 any::{Any, TypeId},
27 borrow::{Borrow, BorrowMut, Cow},
28 fmt::Debug,
29 future::Future,
30 hash::{Hash, Hasher},
31 marker::PhantomData,
32 mem,
33 rc::Rc,
34 sync::{
35 atomic::{AtomicUsize, Ordering::SeqCst},
36 Arc,
37 },
38};
39use util::ResultExt;
40
41const ACTIVE_DRAG_Z_INDEX: u32 = 1;
42
43/// A global stacking order, which is created by stacking successive z-index values.
44/// Each z-index will always be interpreted in the context of its parent z-index.
45#[derive(Deref, DerefMut, Ord, PartialOrd, Eq, PartialEq, Clone, Default, Debug)]
46pub struct StackingOrder(pub(crate) SmallVec<[u32; 16]>);
47
48/// Represents the two different phases when dispatching events.
49#[derive(Default, Copy, Clone, Debug, Eq, PartialEq)]
50pub enum DispatchPhase {
51 /// After the capture phase comes the bubble phase, in which mouse event listeners are
52 /// invoked front to back and keyboard event listeners are invoked from the focused element
53 /// to the root of the element tree. This is the phase you'll most commonly want to use when
54 /// registering event listeners.
55 #[default]
56 Bubble,
57 /// During the initial capture phase, mouse event listeners are invoked back to front, and keyboard
58 /// listeners are invoked from the root of the tree downward toward the focused element. This phase
59 /// is used for special purposes such as clearing the "pressed" state for click events. If
60 /// you stop event propagation during this phase, you need to know what you're doing. Handlers
61 /// outside of the immediate region may rely on detecting non-local events during this phase.
62 Capture,
63}
64
65impl DispatchPhase {
66 pub fn bubble(self) -> bool {
67 self == DispatchPhase::Bubble
68 }
69
70 pub fn capture(self) -> bool {
71 self == DispatchPhase::Capture
72 }
73}
74
75type AnyObserver = Box<dyn FnMut(&mut WindowContext) -> bool + 'static>;
76type AnyMouseListener = Box<dyn FnMut(&dyn Any, DispatchPhase, &mut WindowContext) + 'static>;
77type AnyWindowFocusListener = Box<dyn FnMut(&FocusEvent, &mut WindowContext) -> bool + 'static>;
78
79struct FocusEvent {
80 previous_focus_path: SmallVec<[FocusId; 8]>,
81 current_focus_path: SmallVec<[FocusId; 8]>,
82}
83
84slotmap::new_key_type! { pub struct FocusId; }
85
86impl FocusId {
87 /// Obtains whether the element associated with this handle is currently focused.
88 pub fn is_focused(&self, cx: &WindowContext) -> bool {
89 cx.window.focus == Some(*self)
90 }
91
92 /// Obtains whether the element associated with this handle contains the focused
93 /// element or is itself focused.
94 pub fn contains_focused(&self, cx: &WindowContext) -> bool {
95 cx.focused()
96 .map_or(false, |focused| self.contains(focused.id, cx))
97 }
98
99 /// Obtains whether the element associated with this handle is contained within the
100 /// focused element or is itself focused.
101 pub fn within_focused(&self, cx: &WindowContext) -> bool {
102 let focused = cx.focused();
103 focused.map_or(false, |focused| focused.id.contains(*self, cx))
104 }
105
106 /// Obtains whether this handle contains the given handle in the most recently rendered frame.
107 pub(crate) fn contains(&self, other: Self, cx: &WindowContext) -> bool {
108 cx.window
109 .rendered_frame
110 .dispatch_tree
111 .focus_contains(*self, other)
112 }
113}
114
115/// A handle which can be used to track and manipulate the focused element in a window.
116pub struct FocusHandle {
117 pub(crate) id: FocusId,
118 handles: Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
119}
120
121impl std::fmt::Debug for FocusHandle {
122 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
123 f.write_fmt(format_args!("FocusHandle({:?})", self.id))
124 }
125}
126
127impl FocusHandle {
128 pub(crate) fn new(handles: &Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>) -> Self {
129 let id = handles.write().insert(AtomicUsize::new(1));
130 Self {
131 id,
132 handles: handles.clone(),
133 }
134 }
135
136 pub(crate) fn for_id(
137 id: FocusId,
138 handles: &Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
139 ) -> Option<Self> {
140 let lock = handles.read();
141 let ref_count = lock.get(id)?;
142 if ref_count.load(SeqCst) == 0 {
143 None
144 } else {
145 ref_count.fetch_add(1, SeqCst);
146 Some(Self {
147 id,
148 handles: handles.clone(),
149 })
150 }
151 }
152
153 /// Moves the focus to the element associated with this handle.
154 pub fn focus(&self, cx: &mut WindowContext) {
155 cx.focus(self)
156 }
157
158 /// Obtains whether the element associated with this handle is currently focused.
159 pub fn is_focused(&self, cx: &WindowContext) -> bool {
160 self.id.is_focused(cx)
161 }
162
163 /// Obtains whether the element associated with this handle contains the focused
164 /// element or is itself focused.
165 pub fn contains_focused(&self, cx: &WindowContext) -> bool {
166 self.id.contains_focused(cx)
167 }
168
169 /// Obtains whether the element associated with this handle is contained within the
170 /// focused element or is itself focused.
171 pub fn within_focused(&self, cx: &WindowContext) -> bool {
172 self.id.within_focused(cx)
173 }
174
175 /// Obtains whether this handle contains the given handle in the most recently rendered frame.
176 pub fn contains(&self, other: &Self, cx: &WindowContext) -> bool {
177 self.id.contains(other.id, cx)
178 }
179}
180
181impl Clone for FocusHandle {
182 fn clone(&self) -> Self {
183 Self::for_id(self.id, &self.handles).unwrap()
184 }
185}
186
187impl PartialEq for FocusHandle {
188 fn eq(&self, other: &Self) -> bool {
189 self.id == other.id
190 }
191}
192
193impl Eq for FocusHandle {}
194
195impl Drop for FocusHandle {
196 fn drop(&mut self) {
197 self.handles
198 .read()
199 .get(self.id)
200 .unwrap()
201 .fetch_sub(1, SeqCst);
202 }
203}
204
205/// FocusableView allows users of your view to easily
206/// focus it (using cx.focus_view(view))
207pub trait FocusableView: 'static + Render {
208 fn focus_handle(&self, cx: &AppContext) -> FocusHandle;
209}
210
211/// ManagedView is a view (like a Modal, Popover, Menu, etc.)
212/// where the lifecycle of the view is handled by another view.
213pub trait ManagedView: FocusableView + EventEmitter<DismissEvent> {}
214
215impl<M: FocusableView + EventEmitter<DismissEvent>> ManagedView for M {}
216
217pub struct DismissEvent;
218
219// Holds the state for a specific window.
220pub struct Window {
221 pub(crate) handle: AnyWindowHandle,
222 pub(crate) removed: bool,
223 pub(crate) platform_window: Box<dyn PlatformWindow>,
224 display_id: DisplayId,
225 sprite_atlas: Arc<dyn PlatformAtlas>,
226 rem_size: Pixels,
227 viewport_size: Size<Pixels>,
228 layout_engine: Option<TaffyLayoutEngine>,
229 pub(crate) root_view: Option<AnyView>,
230 pub(crate) element_id_stack: GlobalElementId,
231 pub(crate) rendered_frame: Frame,
232 pub(crate) next_frame: Frame,
233 pub(crate) focus_handles: Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
234 focus_listeners: SubscriberSet<(), AnyWindowFocusListener>,
235 blur_listeners: SubscriberSet<(), AnyObserver>,
236 default_prevented: bool,
237 mouse_position: Point<Pixels>,
238 requested_cursor_style: Option<CursorStyle>,
239 scale_factor: f32,
240 bounds: WindowBounds,
241 bounds_observers: SubscriberSet<(), AnyObserver>,
242 active: bool,
243 pub(crate) dirty: bool,
244 activation_observers: SubscriberSet<(), AnyObserver>,
245 pub(crate) focus: Option<FocusId>,
246
247 #[cfg(any(test, feature = "test-support"))]
248 pub(crate) focus_invalidated: bool,
249}
250
251pub(crate) struct ElementStateBox {
252 inner: Box<dyn Any>,
253 #[cfg(debug_assertions)]
254 type_name: &'static str,
255}
256
257// #[derive(Default)]
258pub(crate) struct Frame {
259 focus: Option<FocusId>,
260 pub(crate) element_states: HashMap<GlobalElementId, ElementStateBox>,
261 mouse_listeners: HashMap<TypeId, Vec<(StackingOrder, AnyMouseListener)>>,
262 pub(crate) dispatch_tree: DispatchTree,
263 pub(crate) scene_builder: SceneBuilder,
264 pub(crate) depth_map: Vec<(StackingOrder, Bounds<Pixels>)>,
265 pub(crate) z_index_stack: StackingOrder,
266 content_mask_stack: Vec<ContentMask<Pixels>>,
267 element_offset_stack: Vec<Point<Pixels>>,
268}
269
270impl Frame {
271 fn new(dispatch_tree: DispatchTree) -> Self {
272 Frame {
273 focus: None,
274 element_states: HashMap::default(),
275 mouse_listeners: HashMap::default(),
276 dispatch_tree,
277 scene_builder: SceneBuilder::default(),
278 z_index_stack: StackingOrder::default(),
279 depth_map: Default::default(),
280 content_mask_stack: Vec::new(),
281 element_offset_stack: Vec::new(),
282 }
283 }
284
285 fn clear(&mut self) {
286 self.element_states.clear();
287 self.mouse_listeners.values_mut().for_each(Vec::clear);
288 self.dispatch_tree.clear();
289 self.depth_map.clear();
290 }
291
292 fn focus_path(&self) -> SmallVec<[FocusId; 8]> {
293 self.focus
294 .map(|focus_id| self.dispatch_tree.focus_path(focus_id))
295 .unwrap_or_default()
296 }
297}
298
299impl Window {
300 pub(crate) fn new(
301 handle: AnyWindowHandle,
302 options: WindowOptions,
303 cx: &mut AppContext,
304 ) -> Self {
305 let platform_window = cx.platform.open_window(
306 handle,
307 options,
308 Box::new({
309 let mut cx = cx.to_async();
310 move || handle.update(&mut cx, |_, cx| cx.draw())
311 }),
312 );
313 let display_id = platform_window.display().id();
314 let sprite_atlas = platform_window.sprite_atlas();
315 let mouse_position = platform_window.mouse_position();
316 let content_size = platform_window.content_size();
317 let scale_factor = platform_window.scale_factor();
318 let bounds = platform_window.bounds();
319
320 platform_window.on_resize(Box::new({
321 let mut cx = cx.to_async();
322 move |_, _| {
323 handle
324 .update(&mut cx, |_, cx| cx.window_bounds_changed())
325 .log_err();
326 }
327 }));
328 platform_window.on_moved(Box::new({
329 let mut cx = cx.to_async();
330 move || {
331 handle
332 .update(&mut cx, |_, cx| cx.window_bounds_changed())
333 .log_err();
334 }
335 }));
336 platform_window.on_active_status_change(Box::new({
337 let mut cx = cx.to_async();
338 move |active| {
339 handle
340 .update(&mut cx, |_, cx| {
341 cx.window.active = active;
342 cx.window
343 .activation_observers
344 .clone()
345 .retain(&(), |callback| callback(cx));
346 })
347 .log_err();
348 }
349 }));
350
351 platform_window.on_input({
352 let mut cx = cx.to_async();
353 Box::new(move |event| {
354 handle
355 .update(&mut cx, |_, cx| cx.dispatch_event(event))
356 .log_err()
357 .unwrap_or(false)
358 })
359 });
360
361 Window {
362 handle,
363 removed: false,
364 platform_window,
365 display_id,
366 sprite_atlas,
367 rem_size: px(16.),
368 viewport_size: content_size,
369 layout_engine: Some(TaffyLayoutEngine::new()),
370 root_view: None,
371 element_id_stack: GlobalElementId::default(),
372 rendered_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
373 next_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
374 focus_handles: Arc::new(RwLock::new(SlotMap::with_key())),
375 focus_listeners: SubscriberSet::new(),
376 blur_listeners: SubscriberSet::new(),
377 default_prevented: true,
378 mouse_position,
379 requested_cursor_style: None,
380 scale_factor,
381 bounds,
382 bounds_observers: SubscriberSet::new(),
383 active: false,
384 dirty: false,
385 activation_observers: SubscriberSet::new(),
386 focus: None,
387
388 #[cfg(any(test, feature = "test-support"))]
389 focus_invalidated: false,
390 }
391 }
392}
393
394/// Indicates which region of the window is visible. Content falling outside of this mask will not be
395/// rendered. Currently, only rectangular content masks are supported, but we give the mask its own type
396/// to leave room to support more complex shapes in the future.
397#[derive(Clone, Debug, Default, PartialEq, Eq)]
398#[repr(C)]
399pub struct ContentMask<P: Clone + Default + Debug> {
400 pub bounds: Bounds<P>,
401}
402
403impl ContentMask<Pixels> {
404 /// Scale the content mask's pixel units by the given scaling factor.
405 pub fn scale(&self, factor: f32) -> ContentMask<ScaledPixels> {
406 ContentMask {
407 bounds: self.bounds.scale(factor),
408 }
409 }
410
411 /// Intersect the content mask with the given content mask.
412 pub fn intersect(&self, other: &Self) -> Self {
413 let bounds = self.bounds.intersect(&other.bounds);
414 ContentMask { bounds }
415 }
416}
417
418/// Provides access to application state in the context of a single window. Derefs
419/// to an `AppContext`, so you can also pass a `WindowContext` to any method that takes
420/// an `AppContext` and call any `AppContext` methods.
421pub struct WindowContext<'a> {
422 pub(crate) app: &'a mut AppContext,
423 pub(crate) window: &'a mut Window,
424}
425
426impl<'a> WindowContext<'a> {
427 pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window) -> Self {
428 Self { app, window }
429 }
430
431 /// Obtain a handle to the window that belongs to this context.
432 pub fn window_handle(&self) -> AnyWindowHandle {
433 self.window.handle
434 }
435
436 /// Mark the window as dirty, scheduling it to be redrawn on the next frame.
437 pub fn notify(&mut self) {
438 self.window.dirty = true;
439 }
440
441 /// Close this window.
442 pub fn remove_window(&mut self) {
443 self.window.removed = true;
444 }
445
446 /// Obtain a new `FocusHandle`, which allows you to track and manipulate the keyboard focus
447 /// for elements rendered within this window.
448 pub fn focus_handle(&mut self) -> FocusHandle {
449 FocusHandle::new(&self.window.focus_handles)
450 }
451
452 /// Obtain the currently focused `FocusHandle`. If no elements are focused, returns `None`.
453 pub fn focused(&self) -> Option<FocusHandle> {
454 self.window
455 .focus
456 .and_then(|id| FocusHandle::for_id(id, &self.window.focus_handles))
457 }
458
459 /// Move focus to the element associated with the given `FocusHandle`.
460 pub fn focus(&mut self, handle: &FocusHandle) {
461 if self.window.focus == Some(handle.id) {
462 return;
463 }
464
465 self.window.focus = Some(handle.id);
466 self.window
467 .rendered_frame
468 .dispatch_tree
469 .clear_pending_keystrokes();
470
471 #[cfg(any(test, feature = "test-support"))]
472 {
473 println!("invalidating focus");
474 self.window.focus_invalidated = true;
475 }
476
477 self.notify();
478 }
479
480 /// Remove focus from all elements within this context's window.
481 pub fn blur(&mut self) {
482 self.window.focus = None;
483 self.notify();
484 }
485
486 pub fn dispatch_action(&mut self, action: Box<dyn Action>) {
487 let focus_handle = self.focused();
488
489 self.defer(move |cx| {
490 let node_id = focus_handle
491 .and_then(|handle| {
492 cx.window
493 .rendered_frame
494 .dispatch_tree
495 .focusable_node_id(handle.id)
496 })
497 .unwrap_or_else(|| cx.window.rendered_frame.dispatch_tree.root_node_id());
498
499 cx.propagate_event = true;
500 cx.dispatch_action_on_node(node_id, action);
501 })
502 }
503
504 pub(crate) fn dispatch_keystroke_observers(
505 &mut self,
506 event: &dyn Any,
507 action: Option<Box<dyn Action>>,
508 ) {
509 let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() else {
510 return;
511 };
512
513 self.keystroke_observers
514 .clone()
515 .retain(&(), move |callback| {
516 (callback)(
517 &KeystrokeEvent {
518 keystroke: key_down_event.keystroke.clone(),
519 action: action.as_ref().map(|action| action.boxed_clone()),
520 },
521 self,
522 );
523 true
524 });
525 }
526
527 /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
528 /// that are currently on the stack to be returned to the app.
529 pub fn defer(&mut self, f: impl FnOnce(&mut WindowContext) + 'static) {
530 let handle = self.window.handle;
531 self.app.defer(move |cx| {
532 handle.update(cx, |_, cx| f(cx)).ok();
533 });
534 }
535
536 pub fn subscribe<Emitter, E, Evt>(
537 &mut self,
538 entity: &E,
539 mut on_event: impl FnMut(E, &Evt, &mut WindowContext<'_>) + 'static,
540 ) -> Subscription
541 where
542 Emitter: EventEmitter<Evt>,
543 E: Entity<Emitter>,
544 Evt: 'static,
545 {
546 let entity_id = entity.entity_id();
547 let entity = entity.downgrade();
548 let window_handle = self.window.handle;
549 let (subscription, activate) = self.app.event_listeners.insert(
550 entity_id,
551 (
552 TypeId::of::<Evt>(),
553 Box::new(move |event, cx| {
554 window_handle
555 .update(cx, |_, cx| {
556 if let Some(handle) = E::upgrade_from(&entity) {
557 let event = event.downcast_ref().expect("invalid event type");
558 on_event(handle, event, cx);
559 true
560 } else {
561 false
562 }
563 })
564 .unwrap_or(false)
565 }),
566 ),
567 );
568 self.app.defer(move |_| activate());
569 subscription
570 }
571
572 /// Create an `AsyncWindowContext`, which has a static lifetime and can be held across
573 /// await points in async code.
574 pub fn to_async(&self) -> AsyncWindowContext {
575 AsyncWindowContext::new(self.app.to_async(), self.window.handle)
576 }
577
578 /// Schedule the given closure to be run directly after the current frame is rendered.
579 pub fn on_next_frame(&mut self, callback: impl FnOnce(&mut WindowContext) + 'static) {
580 let handle = self.window.handle;
581 let display_id = self.window.display_id;
582
583 if !self.frame_consumers.contains_key(&display_id) {
584 let (tx, mut rx) = mpsc::unbounded::<()>();
585 self.platform.set_display_link_output_callback(
586 display_id,
587 Box::new(move |_current_time, _output_time| _ = tx.unbounded_send(())),
588 );
589
590 let consumer_task = self.app.spawn(|cx| async move {
591 while rx.next().await.is_some() {
592 cx.update(|cx| {
593 for callback in cx
594 .next_frame_callbacks
595 .get_mut(&display_id)
596 .unwrap()
597 .drain(..)
598 .collect::<SmallVec<[_; 32]>>()
599 {
600 callback(cx);
601 }
602 })
603 .ok();
604
605 // Flush effects, then stop the display link if no new next_frame_callbacks have been added.
606
607 cx.update(|cx| {
608 if cx.next_frame_callbacks.is_empty() {
609 cx.platform.stop_display_link(display_id);
610 }
611 })
612 .ok();
613 }
614 });
615 self.frame_consumers.insert(display_id, consumer_task);
616 }
617
618 if self.next_frame_callbacks.is_empty() {
619 self.platform.start_display_link(display_id);
620 }
621
622 self.next_frame_callbacks
623 .entry(display_id)
624 .or_default()
625 .push(Box::new(move |cx: &mut AppContext| {
626 cx.update_window(handle, |_root_view, cx| callback(cx)).ok();
627 }));
628 }
629
630 /// Spawn the future returned by the given closure on the application thread pool.
631 /// The closure is provided a handle to the current window and an `AsyncWindowContext` for
632 /// use within your future.
633 pub fn spawn<Fut, R>(&mut self, f: impl FnOnce(AsyncWindowContext) -> Fut) -> Task<R>
634 where
635 R: 'static,
636 Fut: Future<Output = R> + 'static,
637 {
638 self.app
639 .spawn(|app| f(AsyncWindowContext::new(app, self.window.handle)))
640 }
641
642 /// Update the global of the given type. The given closure is given simultaneous mutable
643 /// access both to the global and the context.
644 pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
645 where
646 G: 'static,
647 {
648 let mut global = self.app.lease_global::<G>();
649 let result = f(&mut global, self);
650 self.app.end_global_lease(global);
651 result
652 }
653
654 #[must_use]
655 /// Add a node to the layout tree for the current frame. Takes the `Style` of the element for which
656 /// layout is being requested, along with the layout ids of any children. This method is called during
657 /// calls to the `Element::layout` trait method and enables any element to participate in layout.
658 pub fn request_layout(
659 &mut self,
660 style: &Style,
661 children: impl IntoIterator<Item = LayoutId>,
662 ) -> LayoutId {
663 self.app.layout_id_buffer.clear();
664 self.app.layout_id_buffer.extend(children.into_iter());
665 let rem_size = self.rem_size();
666
667 self.window.layout_engine.as_mut().unwrap().request_layout(
668 style,
669 rem_size,
670 &self.app.layout_id_buffer,
671 )
672 }
673
674 /// Add a node to the layout tree for the current frame. Instead of taking a `Style` and children,
675 /// this variant takes a function that is invoked during layout so you can use arbitrary logic to
676 /// determine the element's size. One place this is used internally is when measuring text.
677 ///
678 /// The given closure is invoked at layout time with the known dimensions and available space and
679 /// returns a `Size`.
680 pub fn request_measured_layout<
681 F: FnMut(Size<Option<Pixels>>, Size<AvailableSpace>, &mut WindowContext) -> Size<Pixels>
682 + 'static,
683 >(
684 &mut self,
685 style: Style,
686 measure: F,
687 ) -> LayoutId {
688 let rem_size = self.rem_size();
689 self.window
690 .layout_engine
691 .as_mut()
692 .unwrap()
693 .request_measured_layout(style, rem_size, measure)
694 }
695
696 pub fn compute_layout(&mut self, layout_id: LayoutId, available_space: Size<AvailableSpace>) {
697 let mut layout_engine = self.window.layout_engine.take().unwrap();
698 layout_engine.compute_layout(layout_id, available_space, self);
699 self.window.layout_engine = Some(layout_engine);
700 }
701
702 /// Obtain the bounds computed for the given LayoutId relative to the window. This method should not
703 /// be invoked until the paint phase begins, and will usually be invoked by GPUI itself automatically
704 /// in order to pass your element its `Bounds` automatically.
705 pub fn layout_bounds(&mut self, layout_id: LayoutId) -> Bounds<Pixels> {
706 let mut bounds = self
707 .window
708 .layout_engine
709 .as_mut()
710 .unwrap()
711 .layout_bounds(layout_id)
712 .map(Into::into);
713 bounds.origin += self.element_offset();
714 bounds
715 }
716
717 fn window_bounds_changed(&mut self) {
718 self.window.scale_factor = self.window.platform_window.scale_factor();
719 self.window.viewport_size = self.window.platform_window.content_size();
720 self.window.bounds = self.window.platform_window.bounds();
721 self.window.display_id = self.window.platform_window.display().id();
722 self.notify();
723
724 self.window
725 .bounds_observers
726 .clone()
727 .retain(&(), |callback| callback(self));
728 }
729
730 pub fn window_bounds(&self) -> WindowBounds {
731 self.window.bounds
732 }
733
734 pub fn viewport_size(&self) -> Size<Pixels> {
735 self.window.viewport_size
736 }
737
738 pub fn is_window_active(&self) -> bool {
739 self.window.active
740 }
741
742 pub fn zoom_window(&self) {
743 self.window.platform_window.zoom();
744 }
745
746 pub fn set_window_title(&mut self, title: &str) {
747 self.window.platform_window.set_title(title);
748 }
749
750 pub fn display(&self) -> Option<Rc<dyn PlatformDisplay>> {
751 self.platform
752 .displays()
753 .into_iter()
754 .find(|display| display.id() == self.window.display_id)
755 }
756
757 pub fn show_character_palette(&self) {
758 self.window.platform_window.show_character_palette();
759 }
760
761 /// The scale factor of the display associated with the window. For example, it could
762 /// return 2.0 for a "retina" display, indicating that each logical pixel should actually
763 /// be rendered as two pixels on screen.
764 pub fn scale_factor(&self) -> f32 {
765 self.window.scale_factor
766 }
767
768 /// The size of an em for the base font of the application. Adjusting this value allows the
769 /// UI to scale, just like zooming a web page.
770 pub fn rem_size(&self) -> Pixels {
771 self.window.rem_size
772 }
773
774 /// Sets the size of an em for the base font of the application. Adjusting this value allows the
775 /// UI to scale, just like zooming a web page.
776 pub fn set_rem_size(&mut self, rem_size: impl Into<Pixels>) {
777 self.window.rem_size = rem_size.into();
778 }
779
780 /// The line height associated with the current text style.
781 pub fn line_height(&self) -> Pixels {
782 let rem_size = self.rem_size();
783 let text_style = self.text_style();
784 text_style
785 .line_height
786 .to_pixels(text_style.font_size.into(), rem_size)
787 }
788
789 /// Call to prevent the default action of an event. Currently only used to prevent
790 /// parent elements from becoming focused on mouse down.
791 pub fn prevent_default(&mut self) {
792 self.window.default_prevented = true;
793 }
794
795 /// Obtain whether default has been prevented for the event currently being dispatched.
796 pub fn default_prevented(&self) -> bool {
797 self.window.default_prevented
798 }
799
800 /// Register a mouse event listener on the window for the next frame. The type of event
801 /// is determined by the first parameter of the given listener. When the next frame is rendered
802 /// the listener will be cleared.
803 ///
804 /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
805 /// a specific need to register a global listener.
806 pub fn on_mouse_event<Event: 'static>(
807 &mut self,
808 handler: impl Fn(&Event, DispatchPhase, &mut WindowContext) + 'static,
809 ) {
810 let order = self.window.next_frame.z_index_stack.clone();
811 self.window
812 .next_frame
813 .mouse_listeners
814 .entry(TypeId::of::<Event>())
815 .or_default()
816 .push((
817 order,
818 Box::new(move |event: &dyn Any, phase, cx| {
819 handler(event.downcast_ref().unwrap(), phase, cx)
820 }),
821 ))
822 }
823
824 /// Register a key event listener on the window for the next frame. The type of event
825 /// is determined by the first parameter of the given listener. When the next frame is rendered
826 /// the listener will be cleared.
827 ///
828 /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
829 /// a specific need to register a global listener.
830 pub fn on_key_event<Event: 'static>(
831 &mut self,
832 handler: impl Fn(&Event, DispatchPhase, &mut WindowContext) + 'static,
833 ) {
834 self.window
835 .next_frame
836 .dispatch_tree
837 .on_key_event(Rc::new(move |event, phase, cx| {
838 if let Some(event) = event.downcast_ref::<Event>() {
839 handler(event, phase, cx)
840 }
841 }));
842 }
843
844 /// Register an action listener on the window for the next frame. The type of action
845 /// is determined by the first parameter of the given listener. When the next frame is rendered
846 /// the listener will be cleared.
847 ///
848 /// This is a fairly low-level method, so prefer using action handlers on elements unless you have
849 /// a specific need to register a global listener.
850 pub fn on_action(
851 &mut self,
852 action_type: TypeId,
853 handler: impl Fn(&dyn Any, DispatchPhase, &mut WindowContext) + 'static,
854 ) {
855 self.window.next_frame.dispatch_tree.on_action(
856 action_type,
857 Rc::new(move |action, phase, cx| handler(action, phase, cx)),
858 );
859 }
860
861 pub fn is_action_available(&self, action: &dyn Action) -> bool {
862 let target = self
863 .focused()
864 .and_then(|focused_handle| {
865 self.window
866 .rendered_frame
867 .dispatch_tree
868 .focusable_node_id(focused_handle.id)
869 })
870 .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
871 self.window
872 .rendered_frame
873 .dispatch_tree
874 .is_action_available(action, target)
875 }
876
877 /// The position of the mouse relative to the window.
878 pub fn mouse_position(&self) -> Point<Pixels> {
879 self.window.mouse_position
880 }
881
882 pub fn set_cursor_style(&mut self, style: CursorStyle) {
883 self.window.requested_cursor_style = Some(style)
884 }
885
886 /// Called during painting to invoke the given closure in a new stacking context. The given
887 /// z-index is interpreted relative to the previous call to `stack`.
888 pub fn with_z_index<R>(&mut self, z_index: u32, f: impl FnOnce(&mut Self) -> R) -> R {
889 self.window.next_frame.z_index_stack.push(z_index);
890 let result = f(self);
891 self.window.next_frame.z_index_stack.pop();
892 result
893 }
894
895 /// Called during painting to track which z-index is on top at each pixel position
896 pub fn add_opaque_layer(&mut self, bounds: Bounds<Pixels>) {
897 let stacking_order = self.window.next_frame.z_index_stack.clone();
898 let depth_map = &mut self.window.next_frame.depth_map;
899 match depth_map.binary_search_by(|(level, _)| stacking_order.cmp(&level)) {
900 Ok(i) | Err(i) => depth_map.insert(i, (stacking_order, bounds)),
901 }
902 }
903
904 /// Returns true if the top-most opaque layer painted over this point was part of the
905 /// same layer as the given stacking order.
906 pub fn was_top_layer(&self, point: &Point<Pixels>, level: &StackingOrder) -> bool {
907 for (stack, bounds) in self.window.rendered_frame.depth_map.iter() {
908 if bounds.contains(point) {
909 return level.starts_with(stack) || stack.starts_with(level);
910 }
911 }
912
913 false
914 }
915
916 pub fn was_top_layer_under_active_drag(
917 &self,
918 point: &Point<Pixels>,
919 level: &StackingOrder,
920 ) -> bool {
921 for (stack, bounds) in self.window.rendered_frame.depth_map.iter() {
922 if stack.starts_with(&[ACTIVE_DRAG_Z_INDEX]) {
923 continue;
924 }
925 if bounds.contains(point) {
926 return level.starts_with(stack) || stack.starts_with(level);
927 }
928 }
929
930 false
931 }
932
933 /// Called during painting to get the current stacking order.
934 pub fn stacking_order(&self) -> &StackingOrder {
935 &self.window.next_frame.z_index_stack
936 }
937
938 /// Paint one or more drop shadows into the scene for the next frame at the current z-index.
939 pub fn paint_shadows(
940 &mut self,
941 bounds: Bounds<Pixels>,
942 corner_radii: Corners<Pixels>,
943 shadows: &[BoxShadow],
944 ) {
945 let scale_factor = self.scale_factor();
946 let content_mask = self.content_mask();
947 let window = &mut *self.window;
948 for shadow in shadows {
949 let mut shadow_bounds = bounds;
950 shadow_bounds.origin += shadow.offset;
951 shadow_bounds.dilate(shadow.spread_radius);
952 window.next_frame.scene_builder.insert(
953 &window.next_frame.z_index_stack,
954 Shadow {
955 order: 0,
956 bounds: shadow_bounds.scale(scale_factor),
957 content_mask: content_mask.scale(scale_factor),
958 corner_radii: corner_radii.scale(scale_factor),
959 color: shadow.color,
960 blur_radius: shadow.blur_radius.scale(scale_factor),
961 },
962 );
963 }
964 }
965
966 /// Paint one or more quads into the scene for the next frame at the current stacking context.
967 /// Quads are colored rectangular regions with an optional background, border, and corner radius.
968 pub fn paint_quad(
969 &mut self,
970 bounds: Bounds<Pixels>,
971 corner_radii: Corners<Pixels>,
972 background: impl Into<Hsla>,
973 border_widths: Edges<Pixels>,
974 border_color: impl Into<Hsla>,
975 ) {
976 let scale_factor = self.scale_factor();
977 let content_mask = self.content_mask();
978
979 let window = &mut *self.window;
980 window.next_frame.scene_builder.insert(
981 &window.next_frame.z_index_stack,
982 Quad {
983 order: 0,
984 bounds: bounds.scale(scale_factor),
985 content_mask: content_mask.scale(scale_factor),
986 background: background.into(),
987 border_color: border_color.into(),
988 corner_radii: corner_radii.scale(scale_factor),
989 border_widths: border_widths.scale(scale_factor),
990 },
991 );
992 }
993
994 /// Paint the given `Path` into the scene for the next frame at the current z-index.
995 pub fn paint_path(&mut self, mut path: Path<Pixels>, color: impl Into<Hsla>) {
996 let scale_factor = self.scale_factor();
997 let content_mask = self.content_mask();
998 path.content_mask = content_mask;
999 path.color = color.into();
1000 let window = &mut *self.window;
1001 window
1002 .next_frame
1003 .scene_builder
1004 .insert(&window.next_frame.z_index_stack, path.scale(scale_factor));
1005 }
1006
1007 /// Paint an underline into the scene for the next frame at the current z-index.
1008 pub fn paint_underline(
1009 &mut self,
1010 origin: Point<Pixels>,
1011 width: Pixels,
1012 style: &UnderlineStyle,
1013 ) {
1014 let scale_factor = self.scale_factor();
1015 let height = if style.wavy {
1016 style.thickness * 3.
1017 } else {
1018 style.thickness
1019 };
1020 let bounds = Bounds {
1021 origin,
1022 size: size(width, height),
1023 };
1024 let content_mask = self.content_mask();
1025 let window = &mut *self.window;
1026 window.next_frame.scene_builder.insert(
1027 &window.next_frame.z_index_stack,
1028 Underline {
1029 order: 0,
1030 bounds: bounds.scale(scale_factor),
1031 content_mask: content_mask.scale(scale_factor),
1032 thickness: style.thickness.scale(scale_factor),
1033 color: style.color.unwrap_or_default(),
1034 wavy: style.wavy,
1035 },
1036 );
1037 }
1038
1039 /// Paint a monochrome (non-emoji) glyph into the scene for the next frame at the current z-index.
1040 /// The y component of the origin is the baseline of the glyph.
1041 pub fn paint_glyph(
1042 &mut self,
1043 origin: Point<Pixels>,
1044 font_id: FontId,
1045 glyph_id: GlyphId,
1046 font_size: Pixels,
1047 color: Hsla,
1048 ) -> Result<()> {
1049 let scale_factor = self.scale_factor();
1050 let glyph_origin = origin.scale(scale_factor);
1051 let subpixel_variant = Point {
1052 x: (glyph_origin.x.0.fract() * SUBPIXEL_VARIANTS as f32).floor() as u8,
1053 y: (glyph_origin.y.0.fract() * SUBPIXEL_VARIANTS as f32).floor() as u8,
1054 };
1055 let params = RenderGlyphParams {
1056 font_id,
1057 glyph_id,
1058 font_size,
1059 subpixel_variant,
1060 scale_factor,
1061 is_emoji: false,
1062 };
1063
1064 let raster_bounds = self.text_system().raster_bounds(¶ms)?;
1065 if !raster_bounds.is_zero() {
1066 let tile =
1067 self.window
1068 .sprite_atlas
1069 .get_or_insert_with(¶ms.clone().into(), &mut || {
1070 let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?;
1071 Ok((size, Cow::Owned(bytes)))
1072 })?;
1073 let bounds = Bounds {
1074 origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
1075 size: tile.bounds.size.map(Into::into),
1076 };
1077 let content_mask = self.content_mask().scale(scale_factor);
1078 let window = &mut *self.window;
1079 window.next_frame.scene_builder.insert(
1080 &window.next_frame.z_index_stack,
1081 MonochromeSprite {
1082 order: 0,
1083 bounds,
1084 content_mask,
1085 color,
1086 tile,
1087 },
1088 );
1089 }
1090 Ok(())
1091 }
1092
1093 /// Paint an emoji glyph into the scene for the next frame at the current z-index.
1094 /// The y component of the origin is the baseline of the glyph.
1095 pub fn paint_emoji(
1096 &mut self,
1097 origin: Point<Pixels>,
1098 font_id: FontId,
1099 glyph_id: GlyphId,
1100 font_size: Pixels,
1101 ) -> Result<()> {
1102 let scale_factor = self.scale_factor();
1103 let glyph_origin = origin.scale(scale_factor);
1104 let params = RenderGlyphParams {
1105 font_id,
1106 glyph_id,
1107 font_size,
1108 // We don't render emojis with subpixel variants.
1109 subpixel_variant: Default::default(),
1110 scale_factor,
1111 is_emoji: true,
1112 };
1113
1114 let raster_bounds = self.text_system().raster_bounds(¶ms)?;
1115 if !raster_bounds.is_zero() {
1116 let tile =
1117 self.window
1118 .sprite_atlas
1119 .get_or_insert_with(¶ms.clone().into(), &mut || {
1120 let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?;
1121 Ok((size, Cow::Owned(bytes)))
1122 })?;
1123 let bounds = Bounds {
1124 origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
1125 size: tile.bounds.size.map(Into::into),
1126 };
1127 let content_mask = self.content_mask().scale(scale_factor);
1128 let window = &mut *self.window;
1129
1130 window.next_frame.scene_builder.insert(
1131 &window.next_frame.z_index_stack,
1132 PolychromeSprite {
1133 order: 0,
1134 bounds,
1135 corner_radii: Default::default(),
1136 content_mask,
1137 tile,
1138 grayscale: false,
1139 },
1140 );
1141 }
1142 Ok(())
1143 }
1144
1145 /// Paint a monochrome SVG into the scene for the next frame at the current stacking context.
1146 pub fn paint_svg(
1147 &mut self,
1148 bounds: Bounds<Pixels>,
1149 path: SharedString,
1150 color: Hsla,
1151 ) -> Result<()> {
1152 let scale_factor = self.scale_factor();
1153 let bounds = bounds.scale(scale_factor);
1154 // Render the SVG at twice the size to get a higher quality result.
1155 let params = RenderSvgParams {
1156 path,
1157 size: bounds
1158 .size
1159 .map(|pixels| DevicePixels::from((pixels.0 * 2.).ceil() as i32)),
1160 };
1161
1162 let tile =
1163 self.window
1164 .sprite_atlas
1165 .get_or_insert_with(¶ms.clone().into(), &mut || {
1166 let bytes = self.svg_renderer.render(¶ms)?;
1167 Ok((params.size, Cow::Owned(bytes)))
1168 })?;
1169 let content_mask = self.content_mask().scale(scale_factor);
1170
1171 let window = &mut *self.window;
1172 window.next_frame.scene_builder.insert(
1173 &window.next_frame.z_index_stack,
1174 MonochromeSprite {
1175 order: 0,
1176 bounds,
1177 content_mask,
1178 color,
1179 tile,
1180 },
1181 );
1182
1183 Ok(())
1184 }
1185
1186 /// Paint an image into the scene for the next frame at the current z-index.
1187 pub fn paint_image(
1188 &mut self,
1189 bounds: Bounds<Pixels>,
1190 corner_radii: Corners<Pixels>,
1191 data: Arc<ImageData>,
1192 grayscale: bool,
1193 ) -> Result<()> {
1194 let scale_factor = self.scale_factor();
1195 let bounds = bounds.scale(scale_factor);
1196 let params = RenderImageParams { image_id: data.id };
1197
1198 let tile = self
1199 .window
1200 .sprite_atlas
1201 .get_or_insert_with(¶ms.clone().into(), &mut || {
1202 Ok((data.size(), Cow::Borrowed(data.as_bytes())))
1203 })?;
1204 let content_mask = self.content_mask().scale(scale_factor);
1205 let corner_radii = corner_radii.scale(scale_factor);
1206
1207 let window = &mut *self.window;
1208 window.next_frame.scene_builder.insert(
1209 &window.next_frame.z_index_stack,
1210 PolychromeSprite {
1211 order: 0,
1212 bounds,
1213 content_mask,
1214 corner_radii,
1215 tile,
1216 grayscale,
1217 },
1218 );
1219 Ok(())
1220 }
1221
1222 /// Paint a surface into the scene for the next frame at the current z-index.
1223 pub fn paint_surface(&mut self, bounds: Bounds<Pixels>, image_buffer: CVImageBuffer) {
1224 let scale_factor = self.scale_factor();
1225 let bounds = bounds.scale(scale_factor);
1226 let content_mask = self.content_mask().scale(scale_factor);
1227 let window = &mut *self.window;
1228 window.next_frame.scene_builder.insert(
1229 &window.next_frame.z_index_stack,
1230 Surface {
1231 order: 0,
1232 bounds,
1233 content_mask,
1234 image_buffer,
1235 },
1236 );
1237 }
1238
1239 /// Draw pixels to the display for this window based on the contents of its scene.
1240 pub(crate) fn draw(&mut self) -> Scene {
1241 #[cfg(any(test, feature = "test-support"))]
1242 {
1243 self.window.focus_invalidated = false;
1244 }
1245
1246 self.text_system().start_frame();
1247 self.window.platform_window.clear_input_handler();
1248 self.window.layout_engine.as_mut().unwrap().clear();
1249 self.window.next_frame.clear();
1250 let root_view = self.window.root_view.take().unwrap();
1251
1252 self.with_z_index(0, |cx| {
1253 cx.with_key_dispatch(Some(KeyContext::default()), None, |_, cx| {
1254 for (action_type, action_listeners) in &cx.app.global_action_listeners {
1255 for action_listener in action_listeners.iter().cloned() {
1256 cx.window.next_frame.dispatch_tree.on_action(
1257 *action_type,
1258 Rc::new(move |action, phase, cx| action_listener(action, phase, cx)),
1259 )
1260 }
1261 }
1262
1263 let available_space = cx.window.viewport_size.map(Into::into);
1264 root_view.draw(Point::default(), available_space, cx);
1265 })
1266 });
1267
1268 if let Some(active_drag) = self.app.active_drag.take() {
1269 self.with_z_index(ACTIVE_DRAG_Z_INDEX, |cx| {
1270 let offset = cx.mouse_position() - active_drag.cursor_offset;
1271 let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
1272 active_drag.view.draw(offset, available_space, cx);
1273 });
1274 self.active_drag = Some(active_drag);
1275 } else if let Some(active_tooltip) = self.app.active_tooltip.take() {
1276 self.with_z_index(1, |cx| {
1277 let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
1278 active_tooltip
1279 .view
1280 .draw(active_tooltip.cursor_offset, available_space, cx);
1281 });
1282 }
1283
1284 self.window
1285 .next_frame
1286 .dispatch_tree
1287 .preserve_pending_keystrokes(
1288 &mut self.window.rendered_frame.dispatch_tree,
1289 self.window.focus,
1290 );
1291 self.window.next_frame.focus = self.window.focus;
1292 self.window.root_view = Some(root_view);
1293
1294 let previous_focus_path = self.window.rendered_frame.focus_path();
1295 mem::swap(&mut self.window.rendered_frame, &mut self.window.next_frame);
1296 let current_focus_path = self.window.rendered_frame.focus_path();
1297
1298 if previous_focus_path != current_focus_path {
1299 if !previous_focus_path.is_empty() && current_focus_path.is_empty() {
1300 self.window
1301 .blur_listeners
1302 .clone()
1303 .retain(&(), |listener| listener(self));
1304 }
1305
1306 let event = FocusEvent {
1307 previous_focus_path,
1308 current_focus_path,
1309 };
1310 self.window
1311 .focus_listeners
1312 .clone()
1313 .retain(&(), |listener| listener(&event, self));
1314 }
1315
1316 let scene = self.window.rendered_frame.scene_builder.build();
1317
1318 // Set the cursor only if we're the active window.
1319 let cursor_style = self
1320 .window
1321 .requested_cursor_style
1322 .take()
1323 .unwrap_or(CursorStyle::Arrow);
1324 if self.is_window_active() {
1325 self.platform.set_cursor_style(cursor_style);
1326 }
1327
1328 self.window.dirty = false;
1329
1330 scene
1331 }
1332
1333 /// Dispatch a mouse or keyboard event on the window.
1334 pub fn dispatch_event(&mut self, event: InputEvent) -> bool {
1335 // Handlers may set this to false by calling `stop_propagation`.
1336 self.app.propagate_event = true;
1337 // Handlers may set this to true by calling `prevent_default`.
1338 self.window.default_prevented = false;
1339
1340 let event = match event {
1341 // Track the mouse position with our own state, since accessing the platform
1342 // API for the mouse position can only occur on the main thread.
1343 InputEvent::MouseMove(mouse_move) => {
1344 self.window.mouse_position = mouse_move.position;
1345 InputEvent::MouseMove(mouse_move)
1346 }
1347 InputEvent::MouseDown(mouse_down) => {
1348 self.window.mouse_position = mouse_down.position;
1349 InputEvent::MouseDown(mouse_down)
1350 }
1351 InputEvent::MouseUp(mouse_up) => {
1352 self.window.mouse_position = mouse_up.position;
1353 InputEvent::MouseUp(mouse_up)
1354 }
1355 // Translate dragging and dropping of external files from the operating system
1356 // to internal drag and drop events.
1357 InputEvent::FileDrop(file_drop) => match file_drop {
1358 FileDropEvent::Entered { position, files } => {
1359 self.window.mouse_position = position;
1360 if self.active_drag.is_none() {
1361 self.active_drag = Some(AnyDrag {
1362 view: self.build_view(|_| files).into(),
1363 cursor_offset: position,
1364 });
1365 }
1366 InputEvent::MouseMove(MouseMoveEvent {
1367 position,
1368 pressed_button: Some(MouseButton::Left),
1369 modifiers: Modifiers::default(),
1370 })
1371 }
1372 FileDropEvent::Pending { position } => {
1373 self.window.mouse_position = position;
1374 InputEvent::MouseMove(MouseMoveEvent {
1375 position,
1376 pressed_button: Some(MouseButton::Left),
1377 modifiers: Modifiers::default(),
1378 })
1379 }
1380 FileDropEvent::Submit { position } => {
1381 self.activate(true);
1382 self.window.mouse_position = position;
1383 InputEvent::MouseUp(MouseUpEvent {
1384 button: MouseButton::Left,
1385 position,
1386 modifiers: Modifiers::default(),
1387 click_count: 1,
1388 })
1389 }
1390 FileDropEvent::Exited => InputEvent::MouseUp(MouseUpEvent {
1391 button: MouseButton::Left,
1392 position: Point::default(),
1393 modifiers: Modifiers::default(),
1394 click_count: 1,
1395 }),
1396 },
1397 _ => event,
1398 };
1399
1400 if let Some(any_mouse_event) = event.mouse_event() {
1401 self.dispatch_mouse_event(any_mouse_event);
1402 } else if let Some(any_key_event) = event.keyboard_event() {
1403 self.dispatch_key_event(any_key_event);
1404 }
1405
1406 !self.app.propagate_event
1407 }
1408
1409 fn dispatch_mouse_event(&mut self, event: &dyn Any) {
1410 if let Some(mut handlers) = self
1411 .window
1412 .rendered_frame
1413 .mouse_listeners
1414 .remove(&event.type_id())
1415 {
1416 // Because handlers may add other handlers, we sort every time.
1417 handlers.sort_by(|(a, _), (b, _)| a.cmp(b));
1418
1419 // Capture phase, events bubble from back to front. Handlers for this phase are used for
1420 // special purposes, such as detecting events outside of a given Bounds.
1421 for (_, handler) in &mut handlers {
1422 handler(event, DispatchPhase::Capture, self);
1423 if !self.app.propagate_event {
1424 break;
1425 }
1426 }
1427
1428 // Bubble phase, where most normal handlers do their work.
1429 if self.app.propagate_event {
1430 for (_, handler) in handlers.iter_mut().rev() {
1431 handler(event, DispatchPhase::Bubble, self);
1432 if !self.app.propagate_event {
1433 break;
1434 }
1435 }
1436 }
1437
1438 if self.app.propagate_event && event.downcast_ref::<MouseUpEvent>().is_some() {
1439 self.active_drag = None;
1440 }
1441
1442 self.window
1443 .rendered_frame
1444 .mouse_listeners
1445 .insert(event.type_id(), handlers);
1446 }
1447 }
1448
1449 fn dispatch_key_event(&mut self, event: &dyn Any) {
1450 let node_id = self
1451 .window
1452 .focus
1453 .and_then(|focus_id| {
1454 self.window
1455 .rendered_frame
1456 .dispatch_tree
1457 .focusable_node_id(focus_id)
1458 })
1459 .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
1460
1461 let dispatch_path = self
1462 .window
1463 .rendered_frame
1464 .dispatch_tree
1465 .dispatch_path(node_id);
1466
1467 let mut actions: Vec<Box<dyn Action>> = Vec::new();
1468
1469 // Capture phase
1470 let mut context_stack: SmallVec<[KeyContext; 16]> = SmallVec::new();
1471 self.propagate_event = true;
1472
1473 for node_id in &dispatch_path {
1474 let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1475
1476 if let Some(context) = node.context.clone() {
1477 context_stack.push(context);
1478 }
1479
1480 for key_listener in node.key_listeners.clone() {
1481 key_listener(event, DispatchPhase::Capture, self);
1482 if !self.propagate_event {
1483 return;
1484 }
1485 }
1486 }
1487
1488 // Bubble phase
1489 for node_id in dispatch_path.iter().rev() {
1490 // Handle low level key events
1491 let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1492 for key_listener in node.key_listeners.clone() {
1493 key_listener(event, DispatchPhase::Bubble, self);
1494 if !self.propagate_event {
1495 return;
1496 }
1497 }
1498
1499 // Match keystrokes
1500 let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1501 if node.context.is_some() {
1502 if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
1503 let mut new_actions = self
1504 .window
1505 .rendered_frame
1506 .dispatch_tree
1507 .dispatch_key(&key_down_event.keystroke, &context_stack);
1508 actions.append(&mut new_actions);
1509 }
1510
1511 context_stack.pop();
1512 }
1513 }
1514
1515 for action in actions {
1516 self.dispatch_action_on_node(node_id, action.boxed_clone());
1517 if !self.propagate_event {
1518 self.dispatch_keystroke_observers(event, Some(action));
1519 return;
1520 }
1521 }
1522 self.dispatch_keystroke_observers(event, None);
1523 }
1524
1525 pub fn has_pending_keystrokes(&self) -> bool {
1526 self.window
1527 .rendered_frame
1528 .dispatch_tree
1529 .has_pending_keystrokes()
1530 }
1531
1532 fn dispatch_action_on_node(&mut self, node_id: DispatchNodeId, action: Box<dyn Action>) {
1533 let dispatch_path = self
1534 .window
1535 .rendered_frame
1536 .dispatch_tree
1537 .dispatch_path(node_id);
1538
1539 // Capture phase
1540 for node_id in &dispatch_path {
1541 let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1542 for DispatchActionListener {
1543 action_type,
1544 listener,
1545 } in node.action_listeners.clone()
1546 {
1547 let any_action = action.as_any();
1548 if action_type == any_action.type_id() {
1549 listener(any_action, DispatchPhase::Capture, self);
1550 if !self.propagate_event {
1551 return;
1552 }
1553 }
1554 }
1555 }
1556 // Bubble phase
1557 for node_id in dispatch_path.iter().rev() {
1558 let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1559 for DispatchActionListener {
1560 action_type,
1561 listener,
1562 } in node.action_listeners.clone()
1563 {
1564 let any_action = action.as_any();
1565 if action_type == any_action.type_id() {
1566 self.propagate_event = false; // Actions stop propagation by default during the bubble phase
1567 listener(any_action, DispatchPhase::Bubble, self);
1568 if !self.propagate_event {
1569 return;
1570 }
1571 }
1572 }
1573 }
1574 }
1575
1576 /// Register the given handler to be invoked whenever the global of the given type
1577 /// is updated.
1578 pub fn observe_global<G: 'static>(
1579 &mut self,
1580 f: impl Fn(&mut WindowContext<'_>) + 'static,
1581 ) -> Subscription {
1582 let window_handle = self.window.handle;
1583 let (subscription, activate) = self.global_observers.insert(
1584 TypeId::of::<G>(),
1585 Box::new(move |cx| window_handle.update(cx, |_, cx| f(cx)).is_ok()),
1586 );
1587 self.app.defer(move |_| activate());
1588 subscription
1589 }
1590
1591 pub fn activate_window(&self) {
1592 self.window.platform_window.activate();
1593 }
1594
1595 pub fn minimize_window(&self) {
1596 self.window.platform_window.minimize();
1597 }
1598
1599 pub fn toggle_full_screen(&self) {
1600 self.window.platform_window.toggle_full_screen();
1601 }
1602
1603 pub fn prompt(
1604 &self,
1605 level: PromptLevel,
1606 msg: &str,
1607 answers: &[&str],
1608 ) -> oneshot::Receiver<usize> {
1609 self.window.platform_window.prompt(level, msg, answers)
1610 }
1611
1612 pub fn available_actions(&self) -> Vec<Box<dyn Action>> {
1613 let node_id = self
1614 .window
1615 .focus
1616 .and_then(|focus_id| {
1617 self.window
1618 .rendered_frame
1619 .dispatch_tree
1620 .focusable_node_id(focus_id)
1621 })
1622 .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
1623
1624 self.window
1625 .rendered_frame
1626 .dispatch_tree
1627 .available_actions(node_id)
1628 }
1629
1630 pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
1631 self.window
1632 .rendered_frame
1633 .dispatch_tree
1634 .bindings_for_action(
1635 action,
1636 &self.window.rendered_frame.dispatch_tree.context_stack,
1637 )
1638 }
1639
1640 pub fn bindings_for_action_in(
1641 &self,
1642 action: &dyn Action,
1643 focus_handle: &FocusHandle,
1644 ) -> Vec<KeyBinding> {
1645 let dispatch_tree = &self.window.rendered_frame.dispatch_tree;
1646
1647 let Some(node_id) = dispatch_tree.focusable_node_id(focus_handle.id) else {
1648 return vec![];
1649 };
1650 let context_stack = dispatch_tree
1651 .dispatch_path(node_id)
1652 .into_iter()
1653 .filter_map(|node_id| dispatch_tree.node(node_id).context.clone())
1654 .collect();
1655 dispatch_tree.bindings_for_action(action, &context_stack)
1656 }
1657
1658 pub fn listener_for<V: Render, E>(
1659 &self,
1660 view: &View<V>,
1661 f: impl Fn(&mut V, &E, &mut ViewContext<V>) + 'static,
1662 ) -> impl Fn(&E, &mut WindowContext) + 'static {
1663 let view = view.downgrade();
1664 move |e: &E, cx: &mut WindowContext| {
1665 view.update(cx, |view, cx| f(view, e, cx)).ok();
1666 }
1667 }
1668
1669 pub fn handler_for<V: Render>(
1670 &self,
1671 view: &View<V>,
1672 f: impl Fn(&mut V, &mut ViewContext<V>) + 'static,
1673 ) -> impl Fn(&mut WindowContext) {
1674 let view = view.downgrade();
1675 move |cx: &mut WindowContext| {
1676 view.update(cx, |view, cx| f(view, cx)).ok();
1677 }
1678 }
1679
1680 //========== ELEMENT RELATED FUNCTIONS ===========
1681 pub fn with_key_dispatch<R>(
1682 &mut self,
1683 context: Option<KeyContext>,
1684 focus_handle: Option<FocusHandle>,
1685 f: impl FnOnce(Option<FocusHandle>, &mut Self) -> R,
1686 ) -> R {
1687 let window = &mut self.window;
1688 window.next_frame.dispatch_tree.push_node(context.clone());
1689 if let Some(focus_handle) = focus_handle.as_ref() {
1690 window
1691 .next_frame
1692 .dispatch_tree
1693 .make_focusable(focus_handle.id);
1694 }
1695 let result = f(focus_handle, self);
1696
1697 self.window.next_frame.dispatch_tree.pop_node();
1698
1699 result
1700 }
1701
1702 /// Set an input handler, such as [ElementInputHandler], which interfaces with the
1703 /// platform to receive textual input with proper integration with concerns such
1704 /// as IME interactions.
1705 pub fn handle_input(
1706 &mut self,
1707 focus_handle: &FocusHandle,
1708 input_handler: impl PlatformInputHandler,
1709 ) {
1710 if focus_handle.is_focused(self) {
1711 self.window
1712 .platform_window
1713 .set_input_handler(Box::new(input_handler));
1714 }
1715 }
1716
1717 pub fn on_window_should_close(&mut self, f: impl Fn(&mut WindowContext) -> bool + 'static) {
1718 let mut this = self.to_async();
1719 self.window
1720 .platform_window
1721 .on_should_close(Box::new(move || this.update(|_, cx| f(cx)).unwrap_or(true)))
1722 }
1723}
1724
1725impl Context for WindowContext<'_> {
1726 type Result<T> = T;
1727
1728 fn build_model<T>(
1729 &mut self,
1730 build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
1731 ) -> Model<T>
1732 where
1733 T: 'static,
1734 {
1735 let slot = self.app.entities.reserve();
1736 let model = build_model(&mut ModelContext::new(&mut *self.app, slot.downgrade()));
1737 self.entities.insert(slot, model)
1738 }
1739
1740 fn update_model<T: 'static, R>(
1741 &mut self,
1742 model: &Model<T>,
1743 update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
1744 ) -> R {
1745 let mut entity = self.entities.lease(model);
1746 let result = update(
1747 &mut *entity,
1748 &mut ModelContext::new(&mut *self.app, model.downgrade()),
1749 );
1750 self.entities.end_lease(entity);
1751 result
1752 }
1753
1754 fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
1755 where
1756 F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
1757 {
1758 if window == self.window.handle {
1759 let root_view = self.window.root_view.clone().unwrap();
1760 Ok(update(root_view, self))
1761 } else {
1762 window.update(self.app, update)
1763 }
1764 }
1765
1766 fn read_model<T, R>(
1767 &self,
1768 handle: &Model<T>,
1769 read: impl FnOnce(&T, &AppContext) -> R,
1770 ) -> Self::Result<R>
1771 where
1772 T: 'static,
1773 {
1774 let entity = self.entities.read(handle);
1775 read(&*entity, &*self.app)
1776 }
1777
1778 fn read_window<T, R>(
1779 &self,
1780 window: &WindowHandle<T>,
1781 read: impl FnOnce(View<T>, &AppContext) -> R,
1782 ) -> Result<R>
1783 where
1784 T: 'static,
1785 {
1786 if window.any_handle == self.window.handle {
1787 let root_view = self
1788 .window
1789 .root_view
1790 .clone()
1791 .unwrap()
1792 .downcast::<T>()
1793 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
1794 Ok(read(root_view, self))
1795 } else {
1796 self.app.read_window(window, read)
1797 }
1798 }
1799}
1800
1801impl VisualContext for WindowContext<'_> {
1802 fn build_view<V>(
1803 &mut self,
1804 build_view_state: impl FnOnce(&mut ViewContext<'_, V>) -> V,
1805 ) -> Self::Result<View<V>>
1806 where
1807 V: 'static + Render,
1808 {
1809 let slot = self.app.entities.reserve();
1810 let view = View {
1811 model: slot.clone(),
1812 };
1813 let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1814 let entity = build_view_state(&mut cx);
1815 cx.entities.insert(slot, entity);
1816
1817 cx.new_view_observers
1818 .clone()
1819 .retain(&TypeId::of::<V>(), |observer| {
1820 let any_view = AnyView::from(view.clone());
1821 (observer)(any_view, self);
1822 true
1823 });
1824
1825 view
1826 }
1827
1828 /// Update the given view. Prefer calling `View::update` instead, which calls this method.
1829 fn update_view<T: 'static, R>(
1830 &mut self,
1831 view: &View<T>,
1832 update: impl FnOnce(&mut T, &mut ViewContext<'_, T>) -> R,
1833 ) -> Self::Result<R> {
1834 let mut lease = self.app.entities.lease(&view.model);
1835 let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1836 let result = update(&mut *lease, &mut cx);
1837 cx.app.entities.end_lease(lease);
1838 result
1839 }
1840
1841 fn replace_root_view<V>(
1842 &mut self,
1843 build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
1844 ) -> Self::Result<View<V>>
1845 where
1846 V: 'static + Render,
1847 {
1848 let slot = self.app.entities.reserve();
1849 let view = View {
1850 model: slot.clone(),
1851 };
1852 let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1853 let entity = build_view(&mut cx);
1854 self.entities.insert(slot, entity);
1855 self.window.root_view = Some(view.clone().into());
1856 view
1857 }
1858
1859 fn focus_view<V: crate::FocusableView>(&mut self, view: &View<V>) -> Self::Result<()> {
1860 self.update_view(view, |view, cx| {
1861 view.focus_handle(cx).clone().focus(cx);
1862 })
1863 }
1864
1865 fn dismiss_view<V>(&mut self, view: &View<V>) -> Self::Result<()>
1866 where
1867 V: ManagedView,
1868 {
1869 self.update_view(view, |_, cx| cx.emit(DismissEvent))
1870 }
1871}
1872
1873impl<'a> std::ops::Deref for WindowContext<'a> {
1874 type Target = AppContext;
1875
1876 fn deref(&self) -> &Self::Target {
1877 &self.app
1878 }
1879}
1880
1881impl<'a> std::ops::DerefMut for WindowContext<'a> {
1882 fn deref_mut(&mut self) -> &mut Self::Target {
1883 &mut self.app
1884 }
1885}
1886
1887impl<'a> Borrow<AppContext> for WindowContext<'a> {
1888 fn borrow(&self) -> &AppContext {
1889 &self.app
1890 }
1891}
1892
1893impl<'a> BorrowMut<AppContext> for WindowContext<'a> {
1894 fn borrow_mut(&mut self) -> &mut AppContext {
1895 &mut self.app
1896 }
1897}
1898
1899pub trait BorrowWindow: BorrowMut<Window> + BorrowMut<AppContext> {
1900 fn app_mut(&mut self) -> &mut AppContext {
1901 self.borrow_mut()
1902 }
1903
1904 fn app(&self) -> &AppContext {
1905 self.borrow()
1906 }
1907
1908 fn window(&self) -> &Window {
1909 self.borrow()
1910 }
1911
1912 fn window_mut(&mut self) -> &mut Window {
1913 self.borrow_mut()
1914 }
1915
1916 /// Pushes the given element id onto the global stack and invokes the given closure
1917 /// with a `GlobalElementId`, which disambiguates the given id in the context of its ancestor
1918 /// ids. Because elements are discarded and recreated on each frame, the `GlobalElementId` is
1919 /// used to associate state with identified elements across separate frames.
1920 fn with_element_id<R>(
1921 &mut self,
1922 id: Option<impl Into<ElementId>>,
1923 f: impl FnOnce(&mut Self) -> R,
1924 ) -> R {
1925 if let Some(id) = id.map(Into::into) {
1926 let window = self.window_mut();
1927 window.element_id_stack.push(id.into());
1928 let result = f(self);
1929 let window: &mut Window = self.borrow_mut();
1930 window.element_id_stack.pop();
1931 result
1932 } else {
1933 f(self)
1934 }
1935 }
1936
1937 /// Invoke the given function with the given content mask after intersecting it
1938 /// with the current mask.
1939 fn with_content_mask<R>(
1940 &mut self,
1941 mask: Option<ContentMask<Pixels>>,
1942 f: impl FnOnce(&mut Self) -> R,
1943 ) -> R {
1944 if let Some(mask) = mask {
1945 let mask = mask.intersect(&self.content_mask());
1946 self.window_mut().next_frame.content_mask_stack.push(mask);
1947 let result = f(self);
1948 self.window_mut().next_frame.content_mask_stack.pop();
1949 result
1950 } else {
1951 f(self)
1952 }
1953 }
1954
1955 /// Invoke the given function with the content mask reset to that
1956 /// of the window.
1957 fn break_content_mask<R>(&mut self, f: impl FnOnce(&mut Self) -> R) -> R {
1958 let mask = ContentMask {
1959 bounds: Bounds {
1960 origin: Point::default(),
1961 size: self.window().viewport_size,
1962 },
1963 };
1964 self.window_mut().next_frame.content_mask_stack.push(mask);
1965 let result = f(self);
1966 self.window_mut().next_frame.content_mask_stack.pop();
1967 result
1968 }
1969
1970 /// Update the global element offset relative to the current offset. This is used to implement
1971 /// scrolling.
1972 fn with_element_offset<R>(
1973 &mut self,
1974 offset: Point<Pixels>,
1975 f: impl FnOnce(&mut Self) -> R,
1976 ) -> R {
1977 if offset.is_zero() {
1978 return f(self);
1979 };
1980
1981 let abs_offset = self.element_offset() + offset;
1982 self.with_absolute_element_offset(abs_offset, f)
1983 }
1984
1985 /// Update the global element offset based on the given offset. This is used to implement
1986 /// drag handles and other manual painting of elements.
1987 fn with_absolute_element_offset<R>(
1988 &mut self,
1989 offset: Point<Pixels>,
1990 f: impl FnOnce(&mut Self) -> R,
1991 ) -> R {
1992 self.window_mut()
1993 .next_frame
1994 .element_offset_stack
1995 .push(offset);
1996 let result = f(self);
1997 self.window_mut().next_frame.element_offset_stack.pop();
1998 result
1999 }
2000
2001 /// Obtain the current element offset.
2002 fn element_offset(&self) -> Point<Pixels> {
2003 self.window()
2004 .next_frame
2005 .element_offset_stack
2006 .last()
2007 .copied()
2008 .unwrap_or_default()
2009 }
2010
2011 /// Update or initialize state for an element with the given id that lives across multiple
2012 /// frames. If an element with this id existed in the rendered frame, its state will be passed
2013 /// to the given closure. The state returned by the closure will be stored so it can be referenced
2014 /// when drawing the next frame.
2015 fn with_element_state<S, R>(
2016 &mut self,
2017 id: ElementId,
2018 f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
2019 ) -> R
2020 where
2021 S: 'static,
2022 {
2023 self.with_element_id(Some(id), |cx| {
2024 let global_id = cx.window().element_id_stack.clone();
2025
2026 if let Some(any) = cx
2027 .window_mut()
2028 .next_frame
2029 .element_states
2030 .remove(&global_id)
2031 .or_else(|| {
2032 cx.window_mut()
2033 .rendered_frame
2034 .element_states
2035 .remove(&global_id)
2036 })
2037 {
2038 let ElementStateBox {
2039 inner,
2040
2041 #[cfg(debug_assertions)]
2042 type_name
2043 } = any;
2044 // Using the extra inner option to avoid needing to reallocate a new box.
2045 let mut state_box = inner
2046 .downcast::<Option<S>>()
2047 .map_err(|_| {
2048 #[cfg(debug_assertions)]
2049 {
2050 anyhow!(
2051 "invalid element state type for id, requested_type {:?}, actual type: {:?}",
2052 std::any::type_name::<S>(),
2053 type_name
2054 )
2055 }
2056
2057 #[cfg(not(debug_assertions))]
2058 {
2059 anyhow!(
2060 "invalid element state type for id, requested_type {:?}",
2061 std::any::type_name::<S>(),
2062 )
2063 }
2064 })
2065 .unwrap();
2066
2067 // Actual: Option<AnyElement> <- View
2068 // Requested: () <- AnyElemet
2069 let state = state_box
2070 .take()
2071 .expect("element state is already on the stack");
2072 let (result, state) = f(Some(state), cx);
2073 state_box.replace(state);
2074 cx.window_mut()
2075 .next_frame
2076 .element_states
2077 .insert(global_id, ElementStateBox {
2078 inner: state_box,
2079
2080 #[cfg(debug_assertions)]
2081 type_name
2082 });
2083 result
2084 } else {
2085 let (result, state) = f(None, cx);
2086 cx.window_mut()
2087 .next_frame
2088 .element_states
2089 .insert(global_id,
2090 ElementStateBox {
2091 inner: Box::new(Some(state)),
2092
2093 #[cfg(debug_assertions)]
2094 type_name: std::any::type_name::<S>()
2095 }
2096
2097 );
2098 result
2099 }
2100 })
2101 }
2102
2103 /// Obtain the current content mask.
2104 fn content_mask(&self) -> ContentMask<Pixels> {
2105 self.window()
2106 .next_frame
2107 .content_mask_stack
2108 .last()
2109 .cloned()
2110 .unwrap_or_else(|| ContentMask {
2111 bounds: Bounds {
2112 origin: Point::default(),
2113 size: self.window().viewport_size,
2114 },
2115 })
2116 }
2117
2118 /// The size of an em for the base font of the application. Adjusting this value allows the
2119 /// UI to scale, just like zooming a web page.
2120 fn rem_size(&self) -> Pixels {
2121 self.window().rem_size
2122 }
2123}
2124
2125impl Borrow<Window> for WindowContext<'_> {
2126 fn borrow(&self) -> &Window {
2127 &self.window
2128 }
2129}
2130
2131impl BorrowMut<Window> for WindowContext<'_> {
2132 fn borrow_mut(&mut self) -> &mut Window {
2133 &mut self.window
2134 }
2135}
2136
2137impl<T> BorrowWindow for T where T: BorrowMut<AppContext> + BorrowMut<Window> {}
2138
2139pub struct ViewContext<'a, V> {
2140 window_cx: WindowContext<'a>,
2141 view: &'a View<V>,
2142}
2143
2144impl<V> Borrow<AppContext> for ViewContext<'_, V> {
2145 fn borrow(&self) -> &AppContext {
2146 &*self.window_cx.app
2147 }
2148}
2149
2150impl<V> BorrowMut<AppContext> for ViewContext<'_, V> {
2151 fn borrow_mut(&mut self) -> &mut AppContext {
2152 &mut *self.window_cx.app
2153 }
2154}
2155
2156impl<V> Borrow<Window> for ViewContext<'_, V> {
2157 fn borrow(&self) -> &Window {
2158 &*self.window_cx.window
2159 }
2160}
2161
2162impl<V> BorrowMut<Window> for ViewContext<'_, V> {
2163 fn borrow_mut(&mut self) -> &mut Window {
2164 &mut *self.window_cx.window
2165 }
2166}
2167
2168impl<'a, V: 'static> ViewContext<'a, V> {
2169 pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window, view: &'a View<V>) -> Self {
2170 Self {
2171 window_cx: WindowContext::new(app, window),
2172 view,
2173 }
2174 }
2175
2176 pub fn entity_id(&self) -> EntityId {
2177 self.view.entity_id()
2178 }
2179
2180 pub fn view(&self) -> &View<V> {
2181 self.view
2182 }
2183
2184 pub fn model(&self) -> &Model<V> {
2185 &self.view.model
2186 }
2187
2188 /// Access the underlying window context.
2189 pub fn window_context(&mut self) -> &mut WindowContext<'a> {
2190 &mut self.window_cx
2191 }
2192
2193 pub fn with_z_index<R>(&mut self, z_index: u32, f: impl FnOnce(&mut Self) -> R) -> R {
2194 self.window.next_frame.z_index_stack.push(z_index);
2195 let result = f(self);
2196 self.window.next_frame.z_index_stack.pop();
2197 result
2198 }
2199
2200 pub fn on_next_frame(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static)
2201 where
2202 V: 'static,
2203 {
2204 let view = self.view().clone();
2205 self.window_cx.on_next_frame(move |cx| view.update(cx, f));
2206 }
2207
2208 /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
2209 /// that are currently on the stack to be returned to the app.
2210 pub fn defer(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static) {
2211 let view = self.view().downgrade();
2212 self.window_cx.defer(move |cx| {
2213 view.update(cx, f).ok();
2214 });
2215 }
2216
2217 pub fn observe<V2, E>(
2218 &mut self,
2219 entity: &E,
2220 mut on_notify: impl FnMut(&mut V, E, &mut ViewContext<'_, V>) + 'static,
2221 ) -> Subscription
2222 where
2223 V2: 'static,
2224 V: 'static,
2225 E: Entity<V2>,
2226 {
2227 let view = self.view().downgrade();
2228 let entity_id = entity.entity_id();
2229 let entity = entity.downgrade();
2230 let window_handle = self.window.handle;
2231 let (subscription, activate) = self.app.observers.insert(
2232 entity_id,
2233 Box::new(move |cx| {
2234 window_handle
2235 .update(cx, |_, cx| {
2236 if let Some(handle) = E::upgrade_from(&entity) {
2237 view.update(cx, |this, cx| on_notify(this, handle, cx))
2238 .is_ok()
2239 } else {
2240 false
2241 }
2242 })
2243 .unwrap_or(false)
2244 }),
2245 );
2246 self.app.defer(move |_| activate());
2247 subscription
2248 }
2249
2250 pub fn subscribe<V2, E, Evt>(
2251 &mut self,
2252 entity: &E,
2253 mut on_event: impl FnMut(&mut V, E, &Evt, &mut ViewContext<'_, V>) + 'static,
2254 ) -> Subscription
2255 where
2256 V2: EventEmitter<Evt>,
2257 E: Entity<V2>,
2258 Evt: 'static,
2259 {
2260 let view = self.view().downgrade();
2261 let entity_id = entity.entity_id();
2262 let handle = entity.downgrade();
2263 let window_handle = self.window.handle;
2264 let (subscription, activate) = self.app.event_listeners.insert(
2265 entity_id,
2266 (
2267 TypeId::of::<Evt>(),
2268 Box::new(move |event, cx| {
2269 window_handle
2270 .update(cx, |_, cx| {
2271 if let Some(handle) = E::upgrade_from(&handle) {
2272 let event = event.downcast_ref().expect("invalid event type");
2273 view.update(cx, |this, cx| on_event(this, handle, event, cx))
2274 .is_ok()
2275 } else {
2276 false
2277 }
2278 })
2279 .unwrap_or(false)
2280 }),
2281 ),
2282 );
2283 self.app.defer(move |_| activate());
2284 subscription
2285 }
2286
2287 pub fn on_release(
2288 &mut self,
2289 on_release: impl FnOnce(&mut V, &mut WindowContext) + 'static,
2290 ) -> Subscription {
2291 let window_handle = self.window.handle;
2292 let (subscription, activate) = self.app.release_listeners.insert(
2293 self.view.model.entity_id,
2294 Box::new(move |this, cx| {
2295 let this = this.downcast_mut().expect("invalid entity type");
2296 let _ = window_handle.update(cx, |_, cx| on_release(this, cx));
2297 }),
2298 );
2299 activate();
2300 subscription
2301 }
2302
2303 pub fn observe_release<V2, E>(
2304 &mut self,
2305 entity: &E,
2306 mut on_release: impl FnMut(&mut V, &mut V2, &mut ViewContext<'_, V>) + 'static,
2307 ) -> Subscription
2308 where
2309 V: 'static,
2310 V2: 'static,
2311 E: Entity<V2>,
2312 {
2313 let view = self.view().downgrade();
2314 let entity_id = entity.entity_id();
2315 let window_handle = self.window.handle;
2316 let (subscription, activate) = self.app.release_listeners.insert(
2317 entity_id,
2318 Box::new(move |entity, cx| {
2319 let entity = entity.downcast_mut().expect("invalid entity type");
2320 let _ = window_handle.update(cx, |_, cx| {
2321 view.update(cx, |this, cx| on_release(this, entity, cx))
2322 });
2323 }),
2324 );
2325 activate();
2326 subscription
2327 }
2328
2329 pub fn notify(&mut self) {
2330 self.window_cx.notify();
2331 self.window_cx.app.push_effect(Effect::Notify {
2332 emitter: self.view.model.entity_id,
2333 });
2334 }
2335
2336 pub fn observe_window_bounds(
2337 &mut self,
2338 mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2339 ) -> Subscription {
2340 let view = self.view.downgrade();
2341 let (subscription, activate) = self.window.bounds_observers.insert(
2342 (),
2343 Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
2344 );
2345 activate();
2346 subscription
2347 }
2348
2349 pub fn observe_window_activation(
2350 &mut self,
2351 mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2352 ) -> Subscription {
2353 let view = self.view.downgrade();
2354 let (subscription, activate) = self.window.activation_observers.insert(
2355 (),
2356 Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
2357 );
2358 activate();
2359 subscription
2360 }
2361
2362 /// Register a listener to be called when the given focus handle receives focus.
2363 /// Unlike [on_focus_changed], returns a subscription and persists until the subscription
2364 /// is dropped.
2365 pub fn on_focus(
2366 &mut self,
2367 handle: &FocusHandle,
2368 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2369 ) -> Subscription {
2370 let view = self.view.downgrade();
2371 let focus_id = handle.id;
2372 let (subscription, activate) = self.window.focus_listeners.insert(
2373 (),
2374 Box::new(move |event, cx| {
2375 view.update(cx, |view, cx| {
2376 if event.previous_focus_path.last() != Some(&focus_id)
2377 && event.current_focus_path.last() == Some(&focus_id)
2378 {
2379 listener(view, cx)
2380 }
2381 })
2382 .is_ok()
2383 }),
2384 );
2385 self.app.defer(move |_| activate());
2386 subscription
2387 }
2388
2389 /// Register a listener to be called when the given focus handle or one of its descendants receives focus.
2390 /// Unlike [on_focus_changed], returns a subscription and persists until the subscription
2391 /// is dropped.
2392 pub fn on_focus_in(
2393 &mut self,
2394 handle: &FocusHandle,
2395 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2396 ) -> Subscription {
2397 let view = self.view.downgrade();
2398 let focus_id = handle.id;
2399 let (subscription, activate) = self.window.focus_listeners.insert(
2400 (),
2401 Box::new(move |event, cx| {
2402 view.update(cx, |view, cx| {
2403 if !event.previous_focus_path.contains(&focus_id)
2404 && event.current_focus_path.contains(&focus_id)
2405 {
2406 listener(view, cx)
2407 }
2408 })
2409 .is_ok()
2410 }),
2411 );
2412 self.app.defer(move |_| activate());
2413 subscription
2414 }
2415
2416 /// Register a listener to be called when the given focus handle loses focus.
2417 /// Unlike [on_focus_changed], returns a subscription and persists until the subscription
2418 /// is dropped.
2419 pub fn on_blur(
2420 &mut self,
2421 handle: &FocusHandle,
2422 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2423 ) -> Subscription {
2424 let view = self.view.downgrade();
2425 let focus_id = handle.id;
2426 let (subscription, activate) = self.window.focus_listeners.insert(
2427 (),
2428 Box::new(move |event, cx| {
2429 view.update(cx, |view, cx| {
2430 if event.previous_focus_path.last() == Some(&focus_id)
2431 && event.current_focus_path.last() != Some(&focus_id)
2432 {
2433 listener(view, cx)
2434 }
2435 })
2436 .is_ok()
2437 }),
2438 );
2439 self.app.defer(move |_| activate());
2440 subscription
2441 }
2442
2443 /// Register a listener to be called when the window loses focus.
2444 /// Unlike [on_focus_changed], returns a subscription and persists until the subscription
2445 /// is dropped.
2446 pub fn on_blur_window(
2447 &mut self,
2448 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2449 ) -> Subscription {
2450 let view = self.view.downgrade();
2451 let (subscription, activate) = self.window.blur_listeners.insert(
2452 (),
2453 Box::new(move |cx| view.update(cx, |view, cx| listener(view, cx)).is_ok()),
2454 );
2455 activate();
2456 subscription
2457 }
2458
2459 /// Register a listener to be called when the given focus handle or one of its descendants loses focus.
2460 /// Unlike [on_focus_changed], returns a subscription and persists until the subscription
2461 /// is dropped.
2462 pub fn on_focus_out(
2463 &mut self,
2464 handle: &FocusHandle,
2465 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2466 ) -> Subscription {
2467 let view = self.view.downgrade();
2468 let focus_id = handle.id;
2469 let (subscription, activate) = self.window.focus_listeners.insert(
2470 (),
2471 Box::new(move |event, cx| {
2472 view.update(cx, |view, cx| {
2473 if event.previous_focus_path.contains(&focus_id)
2474 && !event.current_focus_path.contains(&focus_id)
2475 {
2476 listener(view, cx)
2477 }
2478 })
2479 .is_ok()
2480 }),
2481 );
2482 self.app.defer(move |_| activate());
2483 subscription
2484 }
2485
2486 pub fn spawn<Fut, R>(
2487 &mut self,
2488 f: impl FnOnce(WeakView<V>, AsyncWindowContext) -> Fut,
2489 ) -> Task<R>
2490 where
2491 R: 'static,
2492 Fut: Future<Output = R> + 'static,
2493 {
2494 let view = self.view().downgrade();
2495 self.window_cx.spawn(|cx| f(view, cx))
2496 }
2497
2498 pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
2499 where
2500 G: 'static,
2501 {
2502 let mut global = self.app.lease_global::<G>();
2503 let result = f(&mut global, self);
2504 self.app.end_global_lease(global);
2505 result
2506 }
2507
2508 pub fn observe_global<G: 'static>(
2509 &mut self,
2510 mut f: impl FnMut(&mut V, &mut ViewContext<'_, V>) + 'static,
2511 ) -> Subscription {
2512 let window_handle = self.window.handle;
2513 let view = self.view().downgrade();
2514 let (subscription, activate) = self.global_observers.insert(
2515 TypeId::of::<G>(),
2516 Box::new(move |cx| {
2517 window_handle
2518 .update(cx, |_, cx| view.update(cx, |view, cx| f(view, cx)).is_ok())
2519 .unwrap_or(false)
2520 }),
2521 );
2522 self.app.defer(move |_| activate());
2523 subscription
2524 }
2525
2526 pub fn on_mouse_event<Event: 'static>(
2527 &mut self,
2528 handler: impl Fn(&mut V, &Event, DispatchPhase, &mut ViewContext<V>) + 'static,
2529 ) {
2530 let handle = self.view().clone();
2531 self.window_cx.on_mouse_event(move |event, phase, cx| {
2532 handle.update(cx, |view, cx| {
2533 handler(view, event, phase, cx);
2534 })
2535 });
2536 }
2537
2538 pub fn on_key_event<Event: 'static>(
2539 &mut self,
2540 handler: impl Fn(&mut V, &Event, DispatchPhase, &mut ViewContext<V>) + 'static,
2541 ) {
2542 let handle = self.view().clone();
2543 self.window_cx.on_key_event(move |event, phase, cx| {
2544 handle.update(cx, |view, cx| {
2545 handler(view, event, phase, cx);
2546 })
2547 });
2548 }
2549
2550 pub fn on_action(
2551 &mut self,
2552 action_type: TypeId,
2553 handler: impl Fn(&mut V, &dyn Any, DispatchPhase, &mut ViewContext<V>) + 'static,
2554 ) {
2555 let handle = self.view().clone();
2556 self.window_cx
2557 .on_action(action_type, move |action, phase, cx| {
2558 handle.update(cx, |view, cx| {
2559 handler(view, action, phase, cx);
2560 })
2561 });
2562 }
2563
2564 pub fn emit<Evt>(&mut self, event: Evt)
2565 where
2566 Evt: 'static,
2567 V: EventEmitter<Evt>,
2568 {
2569 let emitter = self.view.model.entity_id;
2570 self.app.push_effect(Effect::Emit {
2571 emitter,
2572 event_type: TypeId::of::<Evt>(),
2573 event: Box::new(event),
2574 });
2575 }
2576
2577 pub fn focus_self(&mut self)
2578 where
2579 V: FocusableView,
2580 {
2581 self.defer(|view, cx| view.focus_handle(cx).focus(cx))
2582 }
2583
2584 pub fn dismiss_self(&mut self)
2585 where
2586 V: ManagedView,
2587 {
2588 self.defer(|_, cx| cx.emit(DismissEvent))
2589 }
2590
2591 pub fn listener<E>(
2592 &self,
2593 f: impl Fn(&mut V, &E, &mut ViewContext<V>) + 'static,
2594 ) -> impl Fn(&E, &mut WindowContext) + 'static {
2595 let view = self.view().downgrade();
2596 move |e: &E, cx: &mut WindowContext| {
2597 view.update(cx, |view, cx| f(view, e, cx)).ok();
2598 }
2599 }
2600}
2601
2602impl<V> Context for ViewContext<'_, V> {
2603 type Result<U> = U;
2604
2605 fn build_model<T: 'static>(
2606 &mut self,
2607 build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
2608 ) -> Model<T> {
2609 self.window_cx.build_model(build_model)
2610 }
2611
2612 fn update_model<T: 'static, R>(
2613 &mut self,
2614 model: &Model<T>,
2615 update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
2616 ) -> R {
2617 self.window_cx.update_model(model, update)
2618 }
2619
2620 fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
2621 where
2622 F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
2623 {
2624 self.window_cx.update_window(window, update)
2625 }
2626
2627 fn read_model<T, R>(
2628 &self,
2629 handle: &Model<T>,
2630 read: impl FnOnce(&T, &AppContext) -> R,
2631 ) -> Self::Result<R>
2632 where
2633 T: 'static,
2634 {
2635 self.window_cx.read_model(handle, read)
2636 }
2637
2638 fn read_window<T, R>(
2639 &self,
2640 window: &WindowHandle<T>,
2641 read: impl FnOnce(View<T>, &AppContext) -> R,
2642 ) -> Result<R>
2643 where
2644 T: 'static,
2645 {
2646 self.window_cx.read_window(window, read)
2647 }
2648}
2649
2650impl<V: 'static> VisualContext for ViewContext<'_, V> {
2651 fn build_view<W: Render + 'static>(
2652 &mut self,
2653 build_view_state: impl FnOnce(&mut ViewContext<'_, W>) -> W,
2654 ) -> Self::Result<View<W>> {
2655 self.window_cx.build_view(build_view_state)
2656 }
2657
2658 fn update_view<V2: 'static, R>(
2659 &mut self,
2660 view: &View<V2>,
2661 update: impl FnOnce(&mut V2, &mut ViewContext<'_, V2>) -> R,
2662 ) -> Self::Result<R> {
2663 self.window_cx.update_view(view, update)
2664 }
2665
2666 fn replace_root_view<W>(
2667 &mut self,
2668 build_view: impl FnOnce(&mut ViewContext<'_, W>) -> W,
2669 ) -> Self::Result<View<W>>
2670 where
2671 W: 'static + Render,
2672 {
2673 self.window_cx.replace_root_view(build_view)
2674 }
2675
2676 fn focus_view<W: FocusableView>(&mut self, view: &View<W>) -> Self::Result<()> {
2677 self.window_cx.focus_view(view)
2678 }
2679
2680 fn dismiss_view<W: ManagedView>(&mut self, view: &View<W>) -> Self::Result<()> {
2681 self.window_cx.dismiss_view(view)
2682 }
2683}
2684
2685impl<'a, V> std::ops::Deref for ViewContext<'a, V> {
2686 type Target = WindowContext<'a>;
2687
2688 fn deref(&self) -> &Self::Target {
2689 &self.window_cx
2690 }
2691}
2692
2693impl<'a, V> std::ops::DerefMut for ViewContext<'a, V> {
2694 fn deref_mut(&mut self) -> &mut Self::Target {
2695 &mut self.window_cx
2696 }
2697}
2698
2699// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
2700slotmap::new_key_type! { pub struct WindowId; }
2701
2702impl WindowId {
2703 pub fn as_u64(&self) -> u64 {
2704 self.0.as_ffi()
2705 }
2706}
2707
2708#[derive(Deref, DerefMut)]
2709pub struct WindowHandle<V> {
2710 #[deref]
2711 #[deref_mut]
2712 pub(crate) any_handle: AnyWindowHandle,
2713 state_type: PhantomData<V>,
2714}
2715
2716impl<V: 'static + Render> WindowHandle<V> {
2717 pub fn new(id: WindowId) -> Self {
2718 WindowHandle {
2719 any_handle: AnyWindowHandle {
2720 id,
2721 state_type: TypeId::of::<V>(),
2722 },
2723 state_type: PhantomData,
2724 }
2725 }
2726
2727 pub fn root<C>(&self, cx: &mut C) -> Result<View<V>>
2728 where
2729 C: Context,
2730 {
2731 Flatten::flatten(cx.update_window(self.any_handle, |root_view, _| {
2732 root_view
2733 .downcast::<V>()
2734 .map_err(|_| anyhow!("the type of the window's root view has changed"))
2735 }))
2736 }
2737
2738 pub fn update<C, R>(
2739 &self,
2740 cx: &mut C,
2741 update: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
2742 ) -> Result<R>
2743 where
2744 C: Context,
2745 {
2746 cx.update_window(self.any_handle, |root_view, cx| {
2747 let view = root_view
2748 .downcast::<V>()
2749 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
2750 Ok(cx.update_view(&view, update))
2751 })?
2752 }
2753
2754 pub fn read<'a>(&self, cx: &'a AppContext) -> Result<&'a V> {
2755 let x = cx
2756 .windows
2757 .get(self.id)
2758 .and_then(|window| {
2759 window
2760 .as_ref()
2761 .and_then(|window| window.root_view.clone())
2762 .map(|root_view| root_view.downcast::<V>())
2763 })
2764 .ok_or_else(|| anyhow!("window not found"))?
2765 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
2766
2767 Ok(x.read(cx))
2768 }
2769
2770 pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &AppContext) -> R) -> Result<R>
2771 where
2772 C: Context,
2773 {
2774 cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
2775 }
2776
2777 pub fn root_view<C>(&self, cx: &C) -> Result<View<V>>
2778 where
2779 C: Context,
2780 {
2781 cx.read_window(self, |root_view, _cx| root_view.clone())
2782 }
2783
2784 pub fn is_active(&self, cx: &AppContext) -> Option<bool> {
2785 cx.windows
2786 .get(self.id)
2787 .and_then(|window| window.as_ref().map(|window| window.active))
2788 }
2789}
2790
2791impl<V> Copy for WindowHandle<V> {}
2792
2793impl<V> Clone for WindowHandle<V> {
2794 fn clone(&self) -> Self {
2795 WindowHandle {
2796 any_handle: self.any_handle,
2797 state_type: PhantomData,
2798 }
2799 }
2800}
2801
2802impl<V> PartialEq for WindowHandle<V> {
2803 fn eq(&self, other: &Self) -> bool {
2804 self.any_handle == other.any_handle
2805 }
2806}
2807
2808impl<V> Eq for WindowHandle<V> {}
2809
2810impl<V> Hash for WindowHandle<V> {
2811 fn hash<H: Hasher>(&self, state: &mut H) {
2812 self.any_handle.hash(state);
2813 }
2814}
2815
2816impl<V: 'static> Into<AnyWindowHandle> for WindowHandle<V> {
2817 fn into(self) -> AnyWindowHandle {
2818 self.any_handle
2819 }
2820}
2821
2822#[derive(Copy, Clone, PartialEq, Eq, Hash)]
2823pub struct AnyWindowHandle {
2824 pub(crate) id: WindowId,
2825 state_type: TypeId,
2826}
2827
2828impl AnyWindowHandle {
2829 pub fn window_id(&self) -> WindowId {
2830 self.id
2831 }
2832
2833 pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
2834 if TypeId::of::<T>() == self.state_type {
2835 Some(WindowHandle {
2836 any_handle: *self,
2837 state_type: PhantomData,
2838 })
2839 } else {
2840 None
2841 }
2842 }
2843
2844 pub fn update<C, R>(
2845 self,
2846 cx: &mut C,
2847 update: impl FnOnce(AnyView, &mut WindowContext<'_>) -> R,
2848 ) -> Result<R>
2849 where
2850 C: Context,
2851 {
2852 cx.update_window(self, update)
2853 }
2854
2855 pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(View<T>, &AppContext) -> R) -> Result<R>
2856 where
2857 C: Context,
2858 T: 'static,
2859 {
2860 let view = self
2861 .downcast::<T>()
2862 .context("the type of the window's root view has changed")?;
2863
2864 cx.read_window(&view, read)
2865 }
2866}
2867
2868#[cfg(any(test, feature = "test-support"))]
2869impl From<SmallVec<[u32; 16]>> for StackingOrder {
2870 fn from(small_vec: SmallVec<[u32; 16]>) -> Self {
2871 StackingOrder(small_vec)
2872 }
2873}
2874
2875#[derive(Clone, Debug, Eq, PartialEq, Hash)]
2876pub enum ElementId {
2877 View(EntityId),
2878 Integer(usize),
2879 Name(SharedString),
2880 FocusHandle(FocusId),
2881 NamedInteger(SharedString, usize),
2882}
2883
2884impl ElementId {
2885 pub(crate) fn from_entity_id(entity_id: EntityId) -> Self {
2886 ElementId::View(entity_id)
2887 }
2888}
2889
2890impl TryInto<SharedString> for ElementId {
2891 type Error = anyhow::Error;
2892
2893 fn try_into(self) -> anyhow::Result<SharedString> {
2894 if let ElementId::Name(name) = self {
2895 Ok(name)
2896 } else {
2897 Err(anyhow!("element id is not string"))
2898 }
2899 }
2900}
2901
2902impl From<usize> for ElementId {
2903 fn from(id: usize) -> Self {
2904 ElementId::Integer(id)
2905 }
2906}
2907
2908impl From<i32> for ElementId {
2909 fn from(id: i32) -> Self {
2910 Self::Integer(id as usize)
2911 }
2912}
2913
2914impl From<SharedString> for ElementId {
2915 fn from(name: SharedString) -> Self {
2916 ElementId::Name(name)
2917 }
2918}
2919
2920impl From<&'static str> for ElementId {
2921 fn from(name: &'static str) -> Self {
2922 ElementId::Name(name.into())
2923 }
2924}
2925
2926impl<'a> From<&'a FocusHandle> for ElementId {
2927 fn from(handle: &'a FocusHandle) -> Self {
2928 ElementId::FocusHandle(handle.id)
2929 }
2930}
2931
2932impl From<(&'static str, EntityId)> for ElementId {
2933 fn from((name, id): (&'static str, EntityId)) -> Self {
2934 ElementId::NamedInteger(name.into(), id.as_u64() as usize)
2935 }
2936}
2937
2938impl From<(&'static str, usize)> for ElementId {
2939 fn from((name, id): (&'static str, usize)) -> Self {
2940 ElementId::NamedInteger(name.into(), id)
2941 }
2942}
2943
2944impl From<(&'static str, u64)> for ElementId {
2945 fn from((name, id): (&'static str, u64)) -> Self {
2946 ElementId::NamedInteger(name.into(), id as usize)
2947 }
2948}