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