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