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