1use crate::{
2 px, size, Action, AnyBox, AnyDrag, AnyView, AppContext, AsyncWindowContext, AvailableSpace,
3 Bounds, BoxShadow, Context, Corners, DevicePixels, DispatchContext, DisplayId, Edges, Effect,
4 Entity, EntityId, EventEmitter, FileDropEvent, FocusEvent, FontId, GlobalElementId, GlyphId,
5 Hsla, ImageData, InputEvent, IsZero, KeyListener, KeyMatch, KeyMatcher, Keystroke, LayoutId,
6 MainThread, MainThreadOnly, Model, ModelContext, Modifiers, MonochromeSprite, MouseButton,
7 MouseDownEvent, MouseMoveEvent, MouseUpEvent, Path, Pixels, PlatformAtlas, PlatformWindow,
8 Point, PolychromeSprite, Quad, Render, RenderGlyphParams, RenderImageParams, RenderSvgParams,
9 ScaledPixels, SceneBuilder, Shadow, SharedString, Size, Style, Subscription, TaffyLayoutEngine,
10 Task, Underline, UnderlineStyle, UpdateView, View, VisualContext, WeakView, WindowOptions,
11 SUBPIXEL_VARIANTS,
12};
13use anyhow::{anyhow, Result};
14use collections::HashMap;
15use derive_more::{Deref, DerefMut};
16use parking_lot::RwLock;
17use slotmap::SlotMap;
18use smallvec::SmallVec;
19use std::{
20 any::{Any, TypeId},
21 borrow::{Borrow, BorrowMut, Cow},
22 fmt::Debug,
23 future::Future,
24 hash::{Hash, Hasher},
25 marker::PhantomData,
26 mem,
27 sync::{
28 atomic::{AtomicUsize, Ordering::SeqCst},
29 Arc,
30 },
31};
32use util::ResultExt;
33
34/// A global stacking order, which is created by stacking successive z-index values.
35/// Each z-index will always be interpreted in the context of its parent z-index.
36#[derive(Deref, DerefMut, Ord, PartialOrd, Eq, PartialEq, Clone, Default)]
37pub(crate) struct StackingOrder(pub(crate) SmallVec<[u32; 16]>);
38
39/// Represents the two different phases when dispatching events.
40#[derive(Default, Copy, Clone, Debug, Eq, PartialEq)]
41pub enum DispatchPhase {
42 /// After the capture phase comes the bubble phase, in which mouse event listeners are
43 /// invoked front to back and keyboard event listeners are invoked from the focused element
44 /// to the root of the element tree. This is the phase you'll most commonly want to use when
45 /// registering event listeners.
46 #[default]
47 Bubble,
48 /// During the initial capture phase, mouse event listeners are invoked back to front, and keyboard
49 /// listeners are invoked from the root of the tree downward toward the focused element. This phase
50 /// is used for special purposes such as clearing the "pressed" state for click events. If
51 /// you stop event propagation during this phase, you need to know what you're doing. Handlers
52 /// outside of the immediate region may rely on detecting non-local events during this phase.
53 Capture,
54}
55
56type AnyListener = Box<dyn Fn(&dyn Any, DispatchPhase, &mut WindowContext) + Send + 'static>;
57type AnyKeyListener = Box<
58 dyn Fn(
59 &dyn Any,
60 &[&DispatchContext],
61 DispatchPhase,
62 &mut WindowContext,
63 ) -> Option<Box<dyn Action>>
64 + Send
65 + 'static,
66>;
67type AnyFocusListener = Box<dyn Fn(&FocusEvent, &mut WindowContext) + Send + 'static>;
68
69slotmap::new_key_type! { pub struct FocusId; }
70
71/// A handle which can be used to track and manipulate the focused element in a window.
72pub struct FocusHandle {
73 pub(crate) id: FocusId,
74 handles: Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
75}
76
77impl FocusHandle {
78 pub(crate) fn new(handles: &Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>) -> Self {
79 let id = handles.write().insert(AtomicUsize::new(1));
80 Self {
81 id,
82 handles: handles.clone(),
83 }
84 }
85
86 pub(crate) fn for_id(
87 id: FocusId,
88 handles: &Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
89 ) -> Option<Self> {
90 let lock = handles.read();
91 let ref_count = lock.get(id)?;
92 if ref_count.load(SeqCst) == 0 {
93 None
94 } else {
95 ref_count.fetch_add(1, SeqCst);
96 Some(Self {
97 id,
98 handles: handles.clone(),
99 })
100 }
101 }
102
103 /// Obtains whether the element associated with this handle is currently focused.
104 pub fn is_focused(&self, cx: &WindowContext) -> bool {
105 cx.window.focus == Some(self.id)
106 }
107
108 /// Obtains whether the element associated with this handle contains the focused
109 /// element or is itself focused.
110 pub fn contains_focused(&self, cx: &WindowContext) -> bool {
111 cx.focused()
112 .map_or(false, |focused| self.contains(&focused, cx))
113 }
114
115 /// Obtains whether the element associated with this handle is contained within the
116 /// focused element or is itself focused.
117 pub fn within_focused(&self, cx: &WindowContext) -> bool {
118 let focused = cx.focused();
119 focused.map_or(false, |focused| focused.contains(self, cx))
120 }
121
122 /// Obtains whether this handle contains the given handle in the most recently rendered frame.
123 pub(crate) fn contains(&self, other: &Self, cx: &WindowContext) -> bool {
124 let mut ancestor = Some(other.id);
125 while let Some(ancestor_id) = ancestor {
126 if self.id == ancestor_id {
127 return true;
128 } else {
129 ancestor = cx.window.focus_parents_by_child.get(&ancestor_id).copied();
130 }
131 }
132 false
133 }
134}
135
136impl Clone for FocusHandle {
137 fn clone(&self) -> Self {
138 Self::for_id(self.id, &self.handles).unwrap()
139 }
140}
141
142impl PartialEq for FocusHandle {
143 fn eq(&self, other: &Self) -> bool {
144 self.id == other.id
145 }
146}
147
148impl Eq for FocusHandle {}
149
150impl Drop for FocusHandle {
151 fn drop(&mut self) {
152 self.handles
153 .read()
154 .get(self.id)
155 .unwrap()
156 .fetch_sub(1, SeqCst);
157 }
158}
159
160// Holds the state for a specific window.
161pub struct Window {
162 pub(crate) handle: AnyWindowHandle,
163 platform_window: MainThreadOnly<Box<dyn PlatformWindow>>,
164 display_id: DisplayId,
165 sprite_atlas: Arc<dyn PlatformAtlas>,
166 rem_size: Pixels,
167 content_size: Size<Pixels>,
168 pub(crate) layout_engine: TaffyLayoutEngine,
169 pub(crate) root_view: Option<AnyView>,
170 pub(crate) element_id_stack: GlobalElementId,
171 prev_frame_element_states: HashMap<GlobalElementId, AnyBox>,
172 element_states: HashMap<GlobalElementId, AnyBox>,
173 prev_frame_key_matchers: HashMap<GlobalElementId, KeyMatcher>,
174 key_matchers: HashMap<GlobalElementId, KeyMatcher>,
175 z_index_stack: StackingOrder,
176 content_mask_stack: Vec<ContentMask<Pixels>>,
177 element_offset_stack: Vec<Point<Pixels>>,
178 mouse_listeners: HashMap<TypeId, Vec<(StackingOrder, AnyListener)>>,
179 key_dispatch_stack: Vec<KeyDispatchStackFrame>,
180 freeze_key_dispatch_stack: bool,
181 focus_stack: Vec<FocusId>,
182 focus_parents_by_child: HashMap<FocusId, FocusId>,
183 pub(crate) focus_listeners: Vec<AnyFocusListener>,
184 pub(crate) focus_handles: Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
185 default_prevented: bool,
186 mouse_position: Point<Pixels>,
187 scale_factor: f32,
188 pub(crate) scene_builder: SceneBuilder,
189 pub(crate) dirty: bool,
190 pub(crate) last_blur: Option<Option<FocusId>>,
191 pub(crate) focus: Option<FocusId>,
192}
193
194impl Window {
195 pub(crate) fn new(
196 handle: AnyWindowHandle,
197 options: WindowOptions,
198 cx: &mut MainThread<AppContext>,
199 ) -> Self {
200 let platform_window = cx.platform().open_window(handle, options);
201 let display_id = platform_window.display().id();
202 let sprite_atlas = platform_window.sprite_atlas();
203 let mouse_position = platform_window.mouse_position();
204 let content_size = platform_window.content_size();
205 let scale_factor = platform_window.scale_factor();
206 platform_window.on_resize(Box::new({
207 let mut cx = cx.to_async();
208 move |content_size, scale_factor| {
209 handle
210 .update(&mut cx, |_, cx| {
211 cx.window.scale_factor = scale_factor;
212 cx.window.scene_builder = SceneBuilder::new();
213 cx.window.content_size = content_size;
214 cx.window.display_id = cx
215 .window
216 .platform_window
217 .borrow_on_main_thread()
218 .display()
219 .id();
220 cx.window.dirty = true;
221 })
222 .log_err();
223 }
224 }));
225
226 platform_window.on_input({
227 let mut cx = cx.to_async();
228 Box::new(move |event| {
229 handle
230 .update(&mut cx, |_, cx| cx.dispatch_event(event))
231 .log_err()
232 .unwrap_or(true)
233 })
234 });
235
236 let platform_window = MainThreadOnly::new(Arc::new(platform_window), cx.executor.clone());
237
238 Window {
239 handle,
240 platform_window,
241 display_id,
242 sprite_atlas,
243 rem_size: px(16.),
244 content_size,
245 layout_engine: TaffyLayoutEngine::new(),
246 root_view: None,
247 element_id_stack: GlobalElementId::default(),
248 prev_frame_element_states: HashMap::default(),
249 element_states: HashMap::default(),
250 prev_frame_key_matchers: HashMap::default(),
251 key_matchers: HashMap::default(),
252 z_index_stack: StackingOrder(SmallVec::new()),
253 content_mask_stack: Vec::new(),
254 element_offset_stack: Vec::new(),
255 mouse_listeners: HashMap::default(),
256 key_dispatch_stack: Vec::new(),
257 freeze_key_dispatch_stack: false,
258 focus_stack: Vec::new(),
259 focus_parents_by_child: HashMap::default(),
260 focus_listeners: Vec::new(),
261 focus_handles: Arc::new(RwLock::new(SlotMap::with_key())),
262 default_prevented: true,
263 mouse_position,
264 scale_factor,
265 scene_builder: SceneBuilder::new(),
266 dirty: true,
267 last_blur: None,
268 focus: None,
269 }
270 }
271}
272
273/// When constructing the element tree, we maintain a stack of key dispatch frames until we
274/// find the focused element. We interleave key listeners with dispatch contexts so we can use the
275/// contexts when matching key events against the keymap.
276enum KeyDispatchStackFrame {
277 Listener {
278 event_type: TypeId,
279 listener: AnyKeyListener,
280 },
281 Context(DispatchContext),
282}
283
284/// Indicates which region of the window is visible. Content falling outside of this mask will not be
285/// rendered. Currently, only rectangular content masks are supported, but we give the mask its own type
286/// to leave room to support more complex shapes in the future.
287#[derive(Clone, Debug, Default, PartialEq, Eq)]
288#[repr(C)]
289pub struct ContentMask<P: Clone + Default + Debug> {
290 pub bounds: Bounds<P>,
291}
292
293impl ContentMask<Pixels> {
294 /// Scale the content mask's pixel units by the given scaling factor.
295 pub fn scale(&self, factor: f32) -> ContentMask<ScaledPixels> {
296 ContentMask {
297 bounds: self.bounds.scale(factor),
298 }
299 }
300
301 /// Intersect the content mask with the given content mask.
302 pub fn intersect(&self, other: &Self) -> Self {
303 let bounds = self.bounds.intersect(&other.bounds);
304 ContentMask { bounds }
305 }
306}
307
308/// Provides access to application state in the context of a single window. Derefs
309/// to an `AppContext`, so you can also pass a `WindowContext` to any method that takes
310/// an `AppContext` and call any `AppContext` methods.
311pub struct WindowContext<'a> {
312 pub(crate) app: &'a mut AppContext,
313 pub(crate) window: &'a mut Window,
314}
315
316impl<'a> WindowContext<'a> {
317 pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window) -> Self {
318 Self { app, window }
319 }
320
321 /// Obtain a handle to the window that belongs to this context.
322 pub fn window_handle(&self) -> AnyWindowHandle {
323 self.window.handle
324 }
325
326 /// Mark the window as dirty, scheduling it to be redrawn on the next frame.
327 pub fn notify(&mut self) {
328 self.window.dirty = true;
329 }
330
331 /// Obtain a new `FocusHandle`, which allows you to track and manipulate the keyboard focus
332 /// for elements rendered within this window.
333 pub fn focus_handle(&mut self) -> FocusHandle {
334 FocusHandle::new(&self.window.focus_handles)
335 }
336
337 /// Obtain the currently focused `FocusHandle`. If no elements are focused, returns `None`.
338 pub fn focused(&self) -> Option<FocusHandle> {
339 self.window
340 .focus
341 .and_then(|id| FocusHandle::for_id(id, &self.window.focus_handles))
342 }
343
344 /// Move focus to the element associated with the given `FocusHandle`.
345 pub fn focus(&mut self, handle: &FocusHandle) {
346 if self.window.last_blur.is_none() {
347 self.window.last_blur = Some(self.window.focus);
348 }
349
350 self.window.focus = Some(handle.id);
351 self.app.push_effect(Effect::FocusChanged {
352 window_handle: self.window.handle,
353 focused: Some(handle.id),
354 });
355 self.notify();
356 }
357
358 /// Remove focus from all elements within this context's window.
359 pub fn blur(&mut self) {
360 if self.window.last_blur.is_none() {
361 self.window.last_blur = Some(self.window.focus);
362 }
363
364 self.window.focus = None;
365 self.app.push_effect(Effect::FocusChanged {
366 window_handle: self.window.handle,
367 focused: None,
368 });
369 self.notify();
370 }
371
372 /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
373 /// that are currently on the stack to be returned to the app.
374 pub fn defer(&mut self, f: impl FnOnce(&mut WindowContext) + 'static + Send) {
375 let handle = self.window.handle;
376 self.app.defer(move |cx| {
377 handle.update(cx, |_, cx| f(cx)).ok();
378 });
379 }
380
381 pub fn subscribe<Emitter, E>(
382 &mut self,
383 entity: &E,
384 mut on_event: impl FnMut(E, &Emitter::Event, &mut WindowContext<'_>) + Send + 'static,
385 ) -> Subscription
386 where
387 Emitter: EventEmitter,
388 E: Entity<Emitter>,
389 {
390 let entity_id = entity.entity_id();
391 let entity = entity.downgrade();
392 let window_handle = self.window.handle;
393 self.app.event_listeners.insert(
394 entity_id,
395 Box::new(move |event, cx| {
396 window_handle
397 .update(cx, |_, cx| {
398 if let Some(handle) = E::upgrade_from(&entity) {
399 let event = event.downcast_ref().expect("invalid event type");
400 on_event(handle, event, cx);
401 true
402 } else {
403 false
404 }
405 })
406 .unwrap_or(false)
407 }),
408 )
409 }
410
411 /// Schedule the given closure to be run on the main thread. It will be invoked with
412 /// a `MainThread<WindowContext>`, which provides access to platform-specific functionality
413 /// of the window.
414 pub fn run_on_main<R>(
415 &mut self,
416 f: impl FnOnce(&mut MainThread<WindowContext<'_>>) -> R + Send + 'static,
417 ) -> Task<Result<R>>
418 where
419 R: Send + 'static,
420 {
421 if self.executor.is_main_thread() {
422 Task::ready(Ok(f(unsafe {
423 mem::transmute::<&mut Self, &mut MainThread<Self>>(self)
424 })))
425 } else {
426 let handle = self.window.handle;
427 self.app
428 .run_on_main(move |cx| handle.update(cx, |_, cx| f(cx)))
429 }
430 }
431
432 /// Create an `AsyncWindowContext`, which has a static lifetime and can be held across
433 /// await points in async code.
434 pub fn to_async(&self) -> AsyncWindowContext {
435 AsyncWindowContext::new(self.app.to_async(), self.window.handle)
436 }
437
438 /// Schedule the given closure to be run directly after the current frame is rendered.
439 pub fn on_next_frame(&mut self, f: impl FnOnce(&mut WindowContext) + Send + 'static) {
440 let f = Box::new(f);
441 let display_id = self.window.display_id;
442 self.run_on_main(move |cx| {
443 if let Some(callbacks) = cx.next_frame_callbacks.get_mut(&display_id) {
444 callbacks.push(f);
445 // If there was already a callback, it means that we already scheduled a frame.
446 if callbacks.len() > 1 {
447 return;
448 }
449 } else {
450 let mut async_cx = cx.to_async();
451 cx.next_frame_callbacks.insert(display_id, vec![f]);
452 cx.platform().set_display_link_output_callback(
453 display_id,
454 Box::new(move |_current_time, _output_time| {
455 let _ = async_cx.update(|_, cx| {
456 let callbacks = cx
457 .next_frame_callbacks
458 .get_mut(&display_id)
459 .unwrap()
460 .drain(..)
461 .collect::<Vec<_>>();
462 for callback in callbacks {
463 callback(cx);
464 }
465
466 cx.run_on_main(move |cx| {
467 if cx.next_frame_callbacks.get(&display_id).unwrap().is_empty() {
468 cx.platform().stop_display_link(display_id);
469 }
470 })
471 .detach();
472 });
473 }),
474 );
475 }
476
477 cx.platform().start_display_link(display_id);
478 })
479 .detach();
480 }
481
482 /// Spawn the future returned by the given closure on the application thread pool.
483 /// The closure is provided a handle to the current window and an `AsyncWindowContext` for
484 /// use within your future.
485 pub fn spawn<Fut, R>(
486 &mut self,
487 f: impl FnOnce(AnyWindowHandle, AsyncWindowContext) -> Fut,
488 ) -> Task<R>
489 where
490 R: Send + 'static,
491 Fut: Future<Output = R> + Send + 'static,
492 {
493 let window = self.window.handle;
494 self.app.spawn(move |app| {
495 let cx = AsyncWindowContext::new(app, window);
496 f(window, cx)
497 })
498 }
499
500 /// Update the global of the given type. The given closure is given simultaneous mutable
501 /// access both to the global and the context.
502 pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
503 where
504 G: 'static,
505 {
506 let mut global = self.app.lease_global::<G>();
507 let result = f(&mut global, self);
508 self.app.end_global_lease(global);
509 result
510 }
511
512 /// Add a node to the layout tree for the current frame. Takes the `Style` of the element for which
513 /// layout is being requested, along with the layout ids of any children. This method is called during
514 /// calls to the `Element::layout` trait method and enables any element to participate in layout.
515 pub fn request_layout(
516 &mut self,
517 style: &Style,
518 children: impl IntoIterator<Item = LayoutId>,
519 ) -> LayoutId {
520 self.app.layout_id_buffer.clear();
521 self.app.layout_id_buffer.extend(children.into_iter());
522 let rem_size = self.rem_size();
523
524 self.window
525 .layout_engine
526 .request_layout(style, rem_size, &self.app.layout_id_buffer)
527 }
528
529 /// Add a node to the layout tree for the current frame. Instead of taking a `Style` and children,
530 /// this variant takes a function that is invoked during layout so you can use arbitrary logic to
531 /// determine the element's size. One place this is used internally is when measuring text.
532 ///
533 /// The given closure is invoked at layout time with the known dimensions and available space and
534 /// returns a `Size`.
535 pub fn request_measured_layout<
536 F: Fn(Size<Option<Pixels>>, Size<AvailableSpace>) -> Size<Pixels> + Send + Sync + 'static,
537 >(
538 &mut self,
539 style: Style,
540 rem_size: Pixels,
541 measure: F,
542 ) -> LayoutId {
543 self.window
544 .layout_engine
545 .request_measured_layout(style, rem_size, measure)
546 }
547
548 /// Obtain the bounds computed for the given LayoutId relative to the window. This method should not
549 /// be invoked until the paint phase begins, and will usually be invoked by GPUI itself automatically
550 /// in order to pass your element its `Bounds` automatically.
551 pub fn layout_bounds(&mut self, layout_id: LayoutId) -> Bounds<Pixels> {
552 let mut bounds = self
553 .window
554 .layout_engine
555 .layout_bounds(layout_id)
556 .map(Into::into);
557 bounds.origin += self.element_offset();
558 bounds
559 }
560
561 /// The scale factor of the display associated with the window. For example, it could
562 /// return 2.0 for a "retina" display, indicating that each logical pixel should actually
563 /// be rendered as two pixels on screen.
564 pub fn scale_factor(&self) -> f32 {
565 self.window.scale_factor
566 }
567
568 /// The size of an em for the base font of the application. Adjusting this value allows the
569 /// UI to scale, just like zooming a web page.
570 pub fn rem_size(&self) -> Pixels {
571 self.window.rem_size
572 }
573
574 /// Sets the size of an em for the base font of the application. Adjusting this value allows the
575 /// UI to scale, just like zooming a web page.
576 pub fn set_rem_size(&mut self, rem_size: impl Into<Pixels>) {
577 self.window.rem_size = rem_size.into();
578 }
579
580 /// The line height associated with the current text style.
581 pub fn line_height(&self) -> Pixels {
582 let rem_size = self.rem_size();
583 let text_style = self.text_style();
584 text_style
585 .line_height
586 .to_pixels(text_style.font_size.into(), rem_size)
587 }
588
589 /// Call to prevent the default action of an event. Currently only used to prevent
590 /// parent elements from becoming focused on mouse down.
591 pub fn prevent_default(&mut self) {
592 self.window.default_prevented = true;
593 }
594
595 /// Obtain whether default has been prevented for the event currently being dispatched.
596 pub fn default_prevented(&self) -> bool {
597 self.window.default_prevented
598 }
599
600 /// Register a mouse event listener on the window for the current frame. The type of event
601 /// is determined by the first parameter of the given listener. When the next frame is rendered
602 /// the listener will be cleared.
603 ///
604 /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
605 /// a specific need to register a global listener.
606 pub fn on_mouse_event<Event: 'static>(
607 &mut self,
608 handler: impl Fn(&Event, DispatchPhase, &mut WindowContext) + Send + 'static,
609 ) {
610 let order = self.window.z_index_stack.clone();
611 self.window
612 .mouse_listeners
613 .entry(TypeId::of::<Event>())
614 .or_default()
615 .push((
616 order,
617 Box::new(move |event: &dyn Any, phase, cx| {
618 handler(event.downcast_ref().unwrap(), phase, cx)
619 }),
620 ))
621 }
622
623 /// The position of the mouse relative to the window.
624 pub fn mouse_position(&self) -> Point<Pixels> {
625 self.window.mouse_position
626 }
627
628 /// Called during painting to invoke the given closure in a new stacking context. The given
629 /// z-index is interpreted relative to the previous call to `stack`.
630 pub fn stack<R>(&mut self, z_index: u32, f: impl FnOnce(&mut Self) -> R) -> R {
631 self.window.z_index_stack.push(z_index);
632 let result = f(self);
633 self.window.z_index_stack.pop();
634 result
635 }
636
637 /// Paint one or more drop shadows into the scene for the current frame at the current z-index.
638 pub fn paint_shadows(
639 &mut self,
640 bounds: Bounds<Pixels>,
641 corner_radii: Corners<Pixels>,
642 shadows: &[BoxShadow],
643 ) {
644 let scale_factor = self.scale_factor();
645 let content_mask = self.content_mask();
646 let window = &mut *self.window;
647 for shadow in shadows {
648 let mut shadow_bounds = bounds;
649 shadow_bounds.origin += shadow.offset;
650 shadow_bounds.dilate(shadow.spread_radius);
651 window.scene_builder.insert(
652 &window.z_index_stack,
653 Shadow {
654 order: 0,
655 bounds: shadow_bounds.scale(scale_factor),
656 content_mask: content_mask.scale(scale_factor),
657 corner_radii: corner_radii.scale(scale_factor),
658 color: shadow.color,
659 blur_radius: shadow.blur_radius.scale(scale_factor),
660 },
661 );
662 }
663 }
664
665 /// Paint one or more quads into the scene for the current frame at the current stacking context.
666 /// Quads are colored rectangular regions with an optional background, border, and corner radius.
667 pub fn paint_quad(
668 &mut self,
669 bounds: Bounds<Pixels>,
670 corner_radii: Corners<Pixels>,
671 background: impl Into<Hsla>,
672 border_widths: Edges<Pixels>,
673 border_color: impl Into<Hsla>,
674 ) {
675 let scale_factor = self.scale_factor();
676 let content_mask = self.content_mask();
677
678 let window = &mut *self.window;
679 window.scene_builder.insert(
680 &window.z_index_stack,
681 Quad {
682 order: 0,
683 bounds: bounds.scale(scale_factor),
684 content_mask: content_mask.scale(scale_factor),
685 background: background.into(),
686 border_color: border_color.into(),
687 corner_radii: corner_radii.scale(scale_factor),
688 border_widths: border_widths.scale(scale_factor),
689 },
690 );
691 }
692
693 /// Paint the given `Path` into the scene for the current frame at the current z-index.
694 pub fn paint_path(&mut self, mut path: Path<Pixels>, color: impl Into<Hsla>) {
695 let scale_factor = self.scale_factor();
696 let content_mask = self.content_mask();
697 path.content_mask = content_mask;
698 path.color = color.into();
699 let window = &mut *self.window;
700 window
701 .scene_builder
702 .insert(&window.z_index_stack, path.scale(scale_factor));
703 }
704
705 /// Paint an underline into the scene for the current frame at the current z-index.
706 pub fn paint_underline(
707 &mut self,
708 origin: Point<Pixels>,
709 width: Pixels,
710 style: &UnderlineStyle,
711 ) -> Result<()> {
712 let scale_factor = self.scale_factor();
713 let height = if style.wavy {
714 style.thickness * 3.
715 } else {
716 style.thickness
717 };
718 let bounds = Bounds {
719 origin,
720 size: size(width, height),
721 };
722 let content_mask = self.content_mask();
723 let window = &mut *self.window;
724 window.scene_builder.insert(
725 &window.z_index_stack,
726 Underline {
727 order: 0,
728 bounds: bounds.scale(scale_factor),
729 content_mask: content_mask.scale(scale_factor),
730 thickness: style.thickness.scale(scale_factor),
731 color: style.color.unwrap_or_default(),
732 wavy: style.wavy,
733 },
734 );
735 Ok(())
736 }
737
738 /// Paint a monochrome (non-emoji) glyph into the scene for the current frame at the current z-index.
739 pub fn paint_glyph(
740 &mut self,
741 origin: Point<Pixels>,
742 font_id: FontId,
743 glyph_id: GlyphId,
744 font_size: Pixels,
745 color: Hsla,
746 ) -> Result<()> {
747 let scale_factor = self.scale_factor();
748 let glyph_origin = origin.scale(scale_factor);
749 let subpixel_variant = Point {
750 x: (glyph_origin.x.0.fract() * SUBPIXEL_VARIANTS as f32).floor() as u8,
751 y: (glyph_origin.y.0.fract() * SUBPIXEL_VARIANTS as f32).floor() as u8,
752 };
753 let params = RenderGlyphParams {
754 font_id,
755 glyph_id,
756 font_size,
757 subpixel_variant,
758 scale_factor,
759 is_emoji: false,
760 };
761
762 let raster_bounds = self.text_system().raster_bounds(¶ms)?;
763 if !raster_bounds.is_zero() {
764 let tile =
765 self.window
766 .sprite_atlas
767 .get_or_insert_with(¶ms.clone().into(), &mut || {
768 let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?;
769 Ok((size, Cow::Owned(bytes)))
770 })?;
771 let bounds = Bounds {
772 origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
773 size: tile.bounds.size.map(Into::into),
774 };
775 let content_mask = self.content_mask().scale(scale_factor);
776 let window = &mut *self.window;
777 window.scene_builder.insert(
778 &window.z_index_stack,
779 MonochromeSprite {
780 order: 0,
781 bounds,
782 content_mask,
783 color,
784 tile,
785 },
786 );
787 }
788 Ok(())
789 }
790
791 /// Paint an emoji glyph into the scene for the current frame at the current z-index.
792 pub fn paint_emoji(
793 &mut self,
794 origin: Point<Pixels>,
795 font_id: FontId,
796 glyph_id: GlyphId,
797 font_size: Pixels,
798 ) -> Result<()> {
799 let scale_factor = self.scale_factor();
800 let glyph_origin = origin.scale(scale_factor);
801 let params = RenderGlyphParams {
802 font_id,
803 glyph_id,
804 font_size,
805 // We don't render emojis with subpixel variants.
806 subpixel_variant: Default::default(),
807 scale_factor,
808 is_emoji: true,
809 };
810
811 let raster_bounds = self.text_system().raster_bounds(¶ms)?;
812 if !raster_bounds.is_zero() {
813 let tile =
814 self.window
815 .sprite_atlas
816 .get_or_insert_with(¶ms.clone().into(), &mut || {
817 let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?;
818 Ok((size, Cow::Owned(bytes)))
819 })?;
820 let bounds = Bounds {
821 origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
822 size: tile.bounds.size.map(Into::into),
823 };
824 let content_mask = self.content_mask().scale(scale_factor);
825 let window = &mut *self.window;
826
827 window.scene_builder.insert(
828 &window.z_index_stack,
829 PolychromeSprite {
830 order: 0,
831 bounds,
832 corner_radii: Default::default(),
833 content_mask,
834 tile,
835 grayscale: false,
836 },
837 );
838 }
839 Ok(())
840 }
841
842 /// Paint a monochrome SVG into the scene for the current frame at the current stacking context.
843 pub fn paint_svg(
844 &mut self,
845 bounds: Bounds<Pixels>,
846 path: SharedString,
847 color: Hsla,
848 ) -> Result<()> {
849 let scale_factor = self.scale_factor();
850 let bounds = bounds.scale(scale_factor);
851 // Render the SVG at twice the size to get a higher quality result.
852 let params = RenderSvgParams {
853 path,
854 size: bounds
855 .size
856 .map(|pixels| DevicePixels::from((pixels.0 * 2.).ceil() as i32)),
857 };
858
859 let tile =
860 self.window
861 .sprite_atlas
862 .get_or_insert_with(¶ms.clone().into(), &mut || {
863 let bytes = self.svg_renderer.render(¶ms)?;
864 Ok((params.size, Cow::Owned(bytes)))
865 })?;
866 let content_mask = self.content_mask().scale(scale_factor);
867
868 let window = &mut *self.window;
869 window.scene_builder.insert(
870 &window.z_index_stack,
871 MonochromeSprite {
872 order: 0,
873 bounds,
874 content_mask,
875 color,
876 tile,
877 },
878 );
879
880 Ok(())
881 }
882
883 /// Paint an image into the scene for the current frame at the current z-index.
884 pub fn paint_image(
885 &mut self,
886 bounds: Bounds<Pixels>,
887 corner_radii: Corners<Pixels>,
888 data: Arc<ImageData>,
889 grayscale: bool,
890 ) -> Result<()> {
891 let scale_factor = self.scale_factor();
892 let bounds = bounds.scale(scale_factor);
893 let params = RenderImageParams { image_id: data.id };
894
895 let tile = self
896 .window
897 .sprite_atlas
898 .get_or_insert_with(¶ms.clone().into(), &mut || {
899 Ok((data.size(), Cow::Borrowed(data.as_bytes())))
900 })?;
901 let content_mask = self.content_mask().scale(scale_factor);
902 let corner_radii = corner_radii.scale(scale_factor);
903
904 let window = &mut *self.window;
905 window.scene_builder.insert(
906 &window.z_index_stack,
907 PolychromeSprite {
908 order: 0,
909 bounds,
910 content_mask,
911 corner_radii,
912 tile,
913 grayscale,
914 },
915 );
916 Ok(())
917 }
918
919 /// Draw pixels to the display for this window based on the contents of its scene.
920 pub(crate) fn draw(&mut self) {
921 let root_view = self.window.root_view.take().unwrap();
922
923 self.start_frame();
924
925 self.stack(0, |cx| {
926 let available_space = cx.window.content_size.map(Into::into);
927 root_view.draw(available_space, cx);
928 });
929
930 if let Some(active_drag) = self.app.active_drag.take() {
931 self.stack(1, |cx| {
932 let offset = cx.mouse_position() - active_drag.cursor_offset;
933 cx.with_element_offset(Some(offset), |cx| {
934 let available_space =
935 size(AvailableSpace::MinContent, AvailableSpace::MinContent);
936 active_drag.view.draw(available_space, cx);
937 cx.active_drag = Some(active_drag);
938 });
939 });
940 }
941
942 self.window.root_view = Some(root_view);
943 let scene = self.window.scene_builder.build();
944
945 self.run_on_main(|cx| {
946 cx.window
947 .platform_window
948 .borrow_on_main_thread()
949 .draw(scene);
950 cx.window.dirty = false;
951 })
952 .detach();
953 }
954
955 fn start_frame(&mut self) {
956 self.text_system().start_frame();
957
958 let window = &mut *self.window;
959
960 // Move the current frame element states to the previous frame.
961 // The new empty element states map will be populated for any element states we
962 // reference during the upcoming frame.
963 mem::swap(
964 &mut window.element_states,
965 &mut window.prev_frame_element_states,
966 );
967 window.element_states.clear();
968
969 // Make the current key matchers the previous, and then clear the current.
970 // An empty key matcher map will be created for every identified element in the
971 // upcoming frame.
972 mem::swap(
973 &mut window.key_matchers,
974 &mut window.prev_frame_key_matchers,
975 );
976 window.key_matchers.clear();
977
978 // Clear mouse event listeners, because elements add new element listeners
979 // when the upcoming frame is painted.
980 window.mouse_listeners.values_mut().for_each(Vec::clear);
981
982 // Clear focus state, because we determine what is focused when the new elements
983 // in the upcoming frame are initialized.
984 window.focus_listeners.clear();
985 window.key_dispatch_stack.clear();
986 window.focus_parents_by_child.clear();
987 window.freeze_key_dispatch_stack = false;
988 }
989
990 /// Dispatch a mouse or keyboard event on the window.
991 fn dispatch_event(&mut self, event: InputEvent) -> bool {
992 let event = match event {
993 // Track the mouse position with our own state, since accessing the platform
994 // API for the mouse position can only occur on the main thread.
995 InputEvent::MouseMove(mouse_move) => {
996 self.window.mouse_position = mouse_move.position;
997 InputEvent::MouseMove(mouse_move)
998 }
999 // Translate dragging and dropping of external files from the operating system
1000 // to internal drag and drop events.
1001 InputEvent::FileDrop(file_drop) => match file_drop {
1002 FileDropEvent::Entered { position, files } => {
1003 self.window.mouse_position = position;
1004 if self.active_drag.is_none() {
1005 self.active_drag = Some(AnyDrag {
1006 view: self.build_view(|_| files).into(),
1007 cursor_offset: position,
1008 });
1009 }
1010 InputEvent::MouseDown(MouseDownEvent {
1011 position,
1012 button: MouseButton::Left,
1013 click_count: 1,
1014 modifiers: Modifiers::default(),
1015 })
1016 }
1017 FileDropEvent::Pending { position } => {
1018 self.window.mouse_position = position;
1019 InputEvent::MouseMove(MouseMoveEvent {
1020 position,
1021 pressed_button: Some(MouseButton::Left),
1022 modifiers: Modifiers::default(),
1023 })
1024 }
1025 FileDropEvent::Submit { position } => {
1026 self.window.mouse_position = position;
1027 InputEvent::MouseUp(MouseUpEvent {
1028 button: MouseButton::Left,
1029 position,
1030 modifiers: Modifiers::default(),
1031 click_count: 1,
1032 })
1033 }
1034 FileDropEvent::Exited => InputEvent::MouseUp(MouseUpEvent {
1035 button: MouseButton::Left,
1036 position: Point::default(),
1037 modifiers: Modifiers::default(),
1038 click_count: 1,
1039 }),
1040 },
1041 _ => event,
1042 };
1043
1044 if let Some(any_mouse_event) = event.mouse_event() {
1045 // Handlers may set this to false by calling `stop_propagation`
1046 self.app.propagate_event = true;
1047 self.window.default_prevented = false;
1048
1049 if let Some(mut handlers) = self
1050 .window
1051 .mouse_listeners
1052 .remove(&any_mouse_event.type_id())
1053 {
1054 // Because handlers may add other handlers, we sort every time.
1055 handlers.sort_by(|(a, _), (b, _)| a.cmp(b));
1056
1057 // Capture phase, events bubble from back to front. Handlers for this phase are used for
1058 // special purposes, such as detecting events outside of a given Bounds.
1059 for (_, handler) in &handlers {
1060 handler(any_mouse_event, DispatchPhase::Capture, self);
1061 if !self.app.propagate_event {
1062 break;
1063 }
1064 }
1065
1066 // Bubble phase, where most normal handlers do their work.
1067 if self.app.propagate_event {
1068 for (_, handler) in handlers.iter().rev() {
1069 handler(any_mouse_event, DispatchPhase::Bubble, self);
1070 if !self.app.propagate_event {
1071 break;
1072 }
1073 }
1074 }
1075
1076 if self.app.propagate_event
1077 && any_mouse_event.downcast_ref::<MouseUpEvent>().is_some()
1078 {
1079 self.active_drag = None;
1080 }
1081
1082 // Just in case any handlers added new handlers, which is weird, but possible.
1083 handlers.extend(
1084 self.window
1085 .mouse_listeners
1086 .get_mut(&any_mouse_event.type_id())
1087 .into_iter()
1088 .flat_map(|handlers| handlers.drain(..)),
1089 );
1090 self.window
1091 .mouse_listeners
1092 .insert(any_mouse_event.type_id(), handlers);
1093 }
1094 } else if let Some(any_key_event) = event.keyboard_event() {
1095 let key_dispatch_stack = mem::take(&mut self.window.key_dispatch_stack);
1096 let key_event_type = any_key_event.type_id();
1097 let mut context_stack = SmallVec::<[&DispatchContext; 16]>::new();
1098
1099 for (ix, frame) in key_dispatch_stack.iter().enumerate() {
1100 match frame {
1101 KeyDispatchStackFrame::Listener {
1102 event_type,
1103 listener,
1104 } => {
1105 if key_event_type == *event_type {
1106 if let Some(action) = listener(
1107 any_key_event,
1108 &context_stack,
1109 DispatchPhase::Capture,
1110 self,
1111 ) {
1112 self.dispatch_action(action, &key_dispatch_stack[..ix]);
1113 }
1114 if !self.app.propagate_event {
1115 break;
1116 }
1117 }
1118 }
1119 KeyDispatchStackFrame::Context(context) => {
1120 context_stack.push(&context);
1121 }
1122 }
1123 }
1124
1125 if self.app.propagate_event {
1126 for (ix, frame) in key_dispatch_stack.iter().enumerate().rev() {
1127 match frame {
1128 KeyDispatchStackFrame::Listener {
1129 event_type,
1130 listener,
1131 } => {
1132 if key_event_type == *event_type {
1133 if let Some(action) = listener(
1134 any_key_event,
1135 &context_stack,
1136 DispatchPhase::Bubble,
1137 self,
1138 ) {
1139 self.dispatch_action(action, &key_dispatch_stack[..ix]);
1140 }
1141
1142 if !self.app.propagate_event {
1143 break;
1144 }
1145 }
1146 }
1147 KeyDispatchStackFrame::Context(_) => {
1148 context_stack.pop();
1149 }
1150 }
1151 }
1152 }
1153
1154 drop(context_stack);
1155 self.window.key_dispatch_stack = key_dispatch_stack;
1156 }
1157
1158 true
1159 }
1160
1161 /// Attempt to map a keystroke to an action based on the keymap.
1162 pub fn match_keystroke(
1163 &mut self,
1164 element_id: &GlobalElementId,
1165 keystroke: &Keystroke,
1166 context_stack: &[&DispatchContext],
1167 ) -> KeyMatch {
1168 let key_match = self
1169 .window
1170 .key_matchers
1171 .get_mut(element_id)
1172 .unwrap()
1173 .match_keystroke(keystroke, context_stack);
1174
1175 if key_match.is_some() {
1176 for matcher in self.window.key_matchers.values_mut() {
1177 matcher.clear_pending();
1178 }
1179 }
1180
1181 key_match
1182 }
1183
1184 /// Register the given handler to be invoked whenever the global of the given type
1185 /// is updated.
1186 pub fn observe_global<G: 'static>(
1187 &mut self,
1188 f: impl Fn(&mut WindowContext<'_>) + Send + 'static,
1189 ) -> Subscription {
1190 let window_handle = self.window.handle;
1191 self.global_observers.insert(
1192 TypeId::of::<G>(),
1193 Box::new(move |cx| window_handle.update(cx, |_, cx| f(cx)).is_ok()),
1194 )
1195 }
1196
1197 fn dispatch_action(
1198 &mut self,
1199 action: Box<dyn Action>,
1200 dispatch_stack: &[KeyDispatchStackFrame],
1201 ) {
1202 let action_type = action.as_any().type_id();
1203
1204 if let Some(mut global_listeners) = self.app.global_action_listeners.remove(&action_type) {
1205 for listener in &global_listeners {
1206 listener(action.as_ref(), DispatchPhase::Capture, self);
1207 if !self.app.propagate_event {
1208 break;
1209 }
1210 }
1211 global_listeners.extend(
1212 self.global_action_listeners
1213 .remove(&action_type)
1214 .unwrap_or_default(),
1215 );
1216 self.global_action_listeners
1217 .insert(action_type, global_listeners);
1218 }
1219
1220 if self.app.propagate_event {
1221 for stack_frame in dispatch_stack {
1222 if let KeyDispatchStackFrame::Listener {
1223 event_type,
1224 listener,
1225 } = stack_frame
1226 {
1227 if action_type == *event_type {
1228 listener(action.as_any(), &[], DispatchPhase::Capture, self);
1229 if !self.app.propagate_event {
1230 break;
1231 }
1232 }
1233 }
1234 }
1235 }
1236
1237 if self.app.propagate_event {
1238 for stack_frame in dispatch_stack.iter().rev() {
1239 if let KeyDispatchStackFrame::Listener {
1240 event_type,
1241 listener,
1242 } = stack_frame
1243 {
1244 if action_type == *event_type {
1245 listener(action.as_any(), &[], DispatchPhase::Bubble, self);
1246 if !self.app.propagate_event {
1247 break;
1248 }
1249 }
1250 }
1251 }
1252 }
1253
1254 if self.app.propagate_event {
1255 if let Some(mut global_listeners) =
1256 self.app.global_action_listeners.remove(&action_type)
1257 {
1258 for listener in global_listeners.iter().rev() {
1259 listener(action.as_ref(), DispatchPhase::Bubble, self);
1260 if !self.app.propagate_event {
1261 break;
1262 }
1263 }
1264 global_listeners.extend(
1265 self.global_action_listeners
1266 .remove(&action_type)
1267 .unwrap_or_default(),
1268 );
1269 self.global_action_listeners
1270 .insert(action_type, global_listeners);
1271 }
1272 }
1273 }
1274}
1275
1276impl Context for WindowContext<'_> {
1277 type WindowContext<'a> = WindowContext<'a>;
1278 type ModelContext<'a, T> = ModelContext<'a, T>;
1279 type Result<T> = T;
1280
1281 fn build_model<T>(
1282 &mut self,
1283 build_model: impl FnOnce(&mut Self::ModelContext<'_, T>) -> T,
1284 ) -> Model<T>
1285 where
1286 T: 'static + Send,
1287 {
1288 let slot = self.app.entities.reserve();
1289 let model = build_model(&mut ModelContext::new(&mut *self.app, slot.downgrade()));
1290 self.entities.insert(slot, model)
1291 }
1292
1293 fn update_model<T: 'static, R>(
1294 &mut self,
1295 model: &Model<T>,
1296 update: impl FnOnce(&mut T, &mut Self::ModelContext<'_, T>) -> R,
1297 ) -> R {
1298 let mut entity = self.entities.lease(model);
1299 let result = update(
1300 &mut *entity,
1301 &mut ModelContext::new(&mut *self.app, model.downgrade()),
1302 );
1303 self.entities.end_lease(entity);
1304 result
1305 }
1306
1307 fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
1308 where
1309 F: FnOnce(AnyView, &mut Self::WindowContext<'_>) -> T,
1310 {
1311 if window == self.window.handle {
1312 let root_view = self.window.root_view.clone().unwrap();
1313 Ok(update(root_view, self))
1314 } else {
1315 window.update(self.app, update)
1316 }
1317 }
1318}
1319
1320impl VisualContext for WindowContext<'_> {
1321 type ViewContext<'a, V: 'static> = ViewContext<'a, V>;
1322
1323 fn build_view<V>(
1324 &mut self,
1325 build_view_state: impl FnOnce(&mut Self::ViewContext<'_, V>) -> V,
1326 ) -> Self::Result<View<V>>
1327 where
1328 V: 'static + Send,
1329 {
1330 let slot = self.app.entities.reserve();
1331 let view = View {
1332 model: slot.clone(),
1333 };
1334 let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1335 let entity = build_view_state(&mut cx);
1336 self.entities.insert(slot, entity);
1337 view
1338 }
1339
1340 /// Update the given view. Prefer calling `View::update` instead, which calls this method.
1341 fn update_view<T: 'static, R>(
1342 &mut self,
1343 view: &View<T>,
1344 update: impl FnOnce(&mut T, &mut Self::ViewContext<'_, T>) -> R,
1345 ) -> Self::Result<R> {
1346 let mut lease = self.app.entities.lease(&view.model);
1347 let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1348 let result = update(&mut *lease, &mut cx);
1349 cx.app.entities.end_lease(lease);
1350 result
1351 }
1352
1353 fn replace_root_view<V>(
1354 &mut self,
1355 build_view: impl FnOnce(&mut Self::ViewContext<'_, V>) -> V,
1356 ) -> Self::Result<View<V>>
1357 where
1358 V: 'static + Send + Render,
1359 {
1360 let slot = self.app.entities.reserve();
1361 let view = View {
1362 model: slot.clone(),
1363 };
1364 let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1365 let entity = build_view(&mut cx);
1366 self.entities.insert(slot, entity);
1367 self.window.root_view = Some(view.clone().into());
1368 view
1369 }
1370}
1371
1372impl UpdateView for WindowContext<'_> {
1373 type ViewContext<'a, V: 'static> = ViewContext<'a, V>;
1374
1375 fn update_view<V: 'static, R>(
1376 &mut self,
1377 view: &View<V>,
1378 update: impl FnOnce(&mut V, &mut Self::ViewContext<'_, V>) -> R,
1379 ) -> R {
1380 VisualContext::update_view(self, view, update)
1381 }
1382}
1383
1384impl<'a> std::ops::Deref for WindowContext<'a> {
1385 type Target = AppContext;
1386
1387 fn deref(&self) -> &Self::Target {
1388 &self.app
1389 }
1390}
1391
1392impl<'a> std::ops::DerefMut for WindowContext<'a> {
1393 fn deref_mut(&mut self) -> &mut Self::Target {
1394 &mut self.app
1395 }
1396}
1397
1398impl<'a> Borrow<AppContext> for WindowContext<'a> {
1399 fn borrow(&self) -> &AppContext {
1400 &self.app
1401 }
1402}
1403
1404impl<'a> BorrowMut<AppContext> for WindowContext<'a> {
1405 fn borrow_mut(&mut self) -> &mut AppContext {
1406 &mut self.app
1407 }
1408}
1409
1410pub trait BorrowWindow: BorrowMut<Window> + BorrowMut<AppContext> {
1411 fn app_mut(&mut self) -> &mut AppContext {
1412 self.borrow_mut()
1413 }
1414
1415 fn window(&self) -> &Window {
1416 self.borrow()
1417 }
1418
1419 fn window_mut(&mut self) -> &mut Window {
1420 self.borrow_mut()
1421 }
1422
1423 /// Pushes the given element id onto the global stack and invokes the given closure
1424 /// with a `GlobalElementId`, which disambiguates the given id in the context of its ancestor
1425 /// ids. Because elements are discarded and recreated on each frame, the `GlobalElementId` is
1426 /// used to associate state with identified elements across separate frames.
1427 fn with_element_id<R>(
1428 &mut self,
1429 id: impl Into<ElementId>,
1430 f: impl FnOnce(GlobalElementId, &mut Self) -> R,
1431 ) -> R {
1432 let keymap = self.app_mut().keymap.clone();
1433 let window = self.window_mut();
1434 window.element_id_stack.push(id.into());
1435 let global_id = window.element_id_stack.clone();
1436
1437 if window.key_matchers.get(&global_id).is_none() {
1438 window.key_matchers.insert(
1439 global_id.clone(),
1440 window
1441 .prev_frame_key_matchers
1442 .remove(&global_id)
1443 .unwrap_or_else(|| KeyMatcher::new(keymap)),
1444 );
1445 }
1446
1447 let result = f(global_id, self);
1448 let window: &mut Window = self.borrow_mut();
1449 window.element_id_stack.pop();
1450 result
1451 }
1452
1453 /// Invoke the given function with the given content mask after intersecting it
1454 /// with the current mask.
1455 fn with_content_mask<R>(
1456 &mut self,
1457 mask: ContentMask<Pixels>,
1458 f: impl FnOnce(&mut Self) -> R,
1459 ) -> R {
1460 let mask = mask.intersect(&self.content_mask());
1461 self.window_mut().content_mask_stack.push(mask);
1462 let result = f(self);
1463 self.window_mut().content_mask_stack.pop();
1464 result
1465 }
1466
1467 /// Update the global element offset based on the given offset. This is used to implement
1468 /// scrolling and position drag handles.
1469 fn with_element_offset<R>(
1470 &mut self,
1471 offset: Option<Point<Pixels>>,
1472 f: impl FnOnce(&mut Self) -> R,
1473 ) -> R {
1474 let Some(offset) = offset else {
1475 return f(self);
1476 };
1477
1478 let offset = self.element_offset() + offset;
1479 self.window_mut().element_offset_stack.push(offset);
1480 let result = f(self);
1481 self.window_mut().element_offset_stack.pop();
1482 result
1483 }
1484
1485 /// Obtain the current element offset.
1486 fn element_offset(&self) -> Point<Pixels> {
1487 self.window()
1488 .element_offset_stack
1489 .last()
1490 .copied()
1491 .unwrap_or_default()
1492 }
1493
1494 /// Update or intialize state for an element with the given id that lives across multiple
1495 /// frames. If an element with this id existed in the previous frame, its state will be passed
1496 /// to the given closure. The state returned by the closure will be stored so it can be referenced
1497 /// when drawing the next frame.
1498 fn with_element_state<S, R>(
1499 &mut self,
1500 id: ElementId,
1501 f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
1502 ) -> R
1503 where
1504 S: 'static + Send,
1505 {
1506 self.with_element_id(id, |global_id, cx| {
1507 if let Some(any) = cx
1508 .window_mut()
1509 .element_states
1510 .remove(&global_id)
1511 .or_else(|| cx.window_mut().prev_frame_element_states.remove(&global_id))
1512 {
1513 // Using the extra inner option to avoid needing to reallocate a new box.
1514 let mut state_box = any
1515 .downcast::<Option<S>>()
1516 .expect("invalid element state type for id");
1517 let state = state_box
1518 .take()
1519 .expect("element state is already on the stack");
1520 let (result, state) = f(Some(state), cx);
1521 state_box.replace(state);
1522 cx.window_mut().element_states.insert(global_id, state_box);
1523 result
1524 } else {
1525 let (result, state) = f(None, cx);
1526 cx.window_mut()
1527 .element_states
1528 .insert(global_id, Box::new(Some(state)));
1529 result
1530 }
1531 })
1532 }
1533
1534 /// Like `with_element_state`, but for situations where the element_id is optional. If the
1535 /// id is `None`, no state will be retrieved or stored.
1536 fn with_optional_element_state<S, R>(
1537 &mut self,
1538 element_id: Option<ElementId>,
1539 f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
1540 ) -> R
1541 where
1542 S: 'static + Send,
1543 {
1544 if let Some(element_id) = element_id {
1545 self.with_element_state(element_id, f)
1546 } else {
1547 f(None, self).0
1548 }
1549 }
1550
1551 /// Obtain the current content mask.
1552 fn content_mask(&self) -> ContentMask<Pixels> {
1553 self.window()
1554 .content_mask_stack
1555 .last()
1556 .cloned()
1557 .unwrap_or_else(|| ContentMask {
1558 bounds: Bounds {
1559 origin: Point::default(),
1560 size: self.window().content_size,
1561 },
1562 })
1563 }
1564
1565 /// The size of an em for the base font of the application. Adjusting this value allows the
1566 /// UI to scale, just like zooming a web page.
1567 fn rem_size(&self) -> Pixels {
1568 self.window().rem_size
1569 }
1570}
1571
1572impl Borrow<Window> for WindowContext<'_> {
1573 fn borrow(&self) -> &Window {
1574 &self.window
1575 }
1576}
1577
1578impl BorrowMut<Window> for WindowContext<'_> {
1579 fn borrow_mut(&mut self) -> &mut Window {
1580 &mut self.window
1581 }
1582}
1583
1584impl<T> BorrowWindow for T where T: BorrowMut<AppContext> + BorrowMut<Window> {}
1585
1586pub struct ViewContext<'a, V> {
1587 window_cx: WindowContext<'a>,
1588 view: &'a View<V>,
1589}
1590
1591impl<V> Borrow<AppContext> for ViewContext<'_, V> {
1592 fn borrow(&self) -> &AppContext {
1593 &*self.window_cx.app
1594 }
1595}
1596
1597impl<V> BorrowMut<AppContext> for ViewContext<'_, V> {
1598 fn borrow_mut(&mut self) -> &mut AppContext {
1599 &mut *self.window_cx.app
1600 }
1601}
1602
1603impl<V> Borrow<Window> for ViewContext<'_, V> {
1604 fn borrow(&self) -> &Window {
1605 &*self.window_cx.window
1606 }
1607}
1608
1609impl<V> BorrowMut<Window> for ViewContext<'_, V> {
1610 fn borrow_mut(&mut self) -> &mut Window {
1611 &mut *self.window_cx.window
1612 }
1613}
1614
1615impl<'a, V: 'static> ViewContext<'a, V> {
1616 pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window, view: &'a View<V>) -> Self {
1617 Self {
1618 window_cx: WindowContext::new(app, window),
1619 view,
1620 }
1621 }
1622
1623 pub fn view(&self) -> View<V> {
1624 self.view.clone()
1625 }
1626
1627 pub fn model(&self) -> Model<V> {
1628 self.view.model.clone()
1629 }
1630
1631 pub fn stack<R>(&mut self, order: u32, f: impl FnOnce(&mut Self) -> R) -> R {
1632 self.window.z_index_stack.push(order);
1633 let result = f(self);
1634 self.window.z_index_stack.pop();
1635 result
1636 }
1637
1638 pub fn on_next_frame(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + Send + 'static)
1639 where
1640 V: Any + Send,
1641 {
1642 let view = self.view();
1643 self.window_cx.on_next_frame(move |cx| view.update(cx, f));
1644 }
1645
1646 /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
1647 /// that are currently on the stack to be returned to the app.
1648 pub fn defer(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static + Send) {
1649 let view = self.view().downgrade();
1650 self.window_cx.defer(move |cx| {
1651 view.update(cx, f).ok();
1652 });
1653 }
1654
1655 pub fn observe<V2, E>(
1656 &mut self,
1657 entity: &E,
1658 mut on_notify: impl FnMut(&mut V, E, &mut ViewContext<'_, V>) + Send + 'static,
1659 ) -> Subscription
1660 where
1661 V2: 'static,
1662 V: 'static + Send,
1663 E: Entity<V2>,
1664 {
1665 let view = self.view().downgrade();
1666 let entity_id = entity.entity_id();
1667 let entity = entity.downgrade();
1668 let window_handle = self.window.handle;
1669 self.app.observers.insert(
1670 entity_id,
1671 Box::new(move |cx| {
1672 window_handle
1673 .update(cx, |_, cx| {
1674 if let Some(handle) = E::upgrade_from(&entity) {
1675 view.update(cx, |this, cx| on_notify(this, handle, cx))
1676 .is_ok()
1677 } else {
1678 false
1679 }
1680 })
1681 .unwrap_or(false)
1682 }),
1683 )
1684 }
1685
1686 pub fn subscribe<V2, E>(
1687 &mut self,
1688 entity: &E,
1689 mut on_event: impl FnMut(&mut V, E, &V2::Event, &mut ViewContext<'_, V>) + Send + 'static,
1690 ) -> Subscription
1691 where
1692 V2: EventEmitter,
1693 E: Entity<V2>,
1694 {
1695 let view = self.view().downgrade();
1696 let entity_id = entity.entity_id();
1697 let handle = entity.downgrade();
1698 let window_handle = self.window.handle;
1699 self.app.event_listeners.insert(
1700 entity_id,
1701 Box::new(move |event, cx| {
1702 window_handle
1703 .update(cx, |_, cx| {
1704 if let Some(handle) = E::upgrade_from(&handle) {
1705 let event = event.downcast_ref().expect("invalid event type");
1706 view.update(cx, |this, cx| on_event(this, handle, event, cx))
1707 .is_ok()
1708 } else {
1709 false
1710 }
1711 })
1712 .unwrap_or(false)
1713 }),
1714 )
1715 }
1716
1717 pub fn on_release(
1718 &mut self,
1719 on_release: impl FnOnce(&mut V, &mut WindowContext) + Send + 'static,
1720 ) -> Subscription {
1721 let window_handle = self.window.handle;
1722 self.app.release_listeners.insert(
1723 self.view.model.entity_id,
1724 Box::new(move |this, cx| {
1725 let this = this.downcast_mut().expect("invalid entity type");
1726 // todo!("are we okay with silently swallowing the error?")
1727 let _ = window_handle.update(cx, |_, cx| on_release(this, cx));
1728 }),
1729 )
1730 }
1731
1732 pub fn observe_release<V2, E>(
1733 &mut self,
1734 entity: &E,
1735 mut on_release: impl FnMut(&mut V, &mut V2, &mut ViewContext<'_, V>) + Send + 'static,
1736 ) -> Subscription
1737 where
1738 V: Any + Send,
1739 V2: 'static,
1740 E: Entity<V2>,
1741 {
1742 let view = self.view().downgrade();
1743 let entity_id = entity.entity_id();
1744 let window_handle = self.window.handle;
1745 self.app.release_listeners.insert(
1746 entity_id,
1747 Box::new(move |entity, cx| {
1748 let entity = entity.downcast_mut().expect("invalid entity type");
1749 let _ = window_handle.update(cx, |_, cx| {
1750 view.update(cx, |this, cx| on_release(this, entity, cx))
1751 });
1752 }),
1753 )
1754 }
1755
1756 pub fn notify(&mut self) {
1757 self.window_cx.notify();
1758 self.window_cx.app.push_effect(Effect::Notify {
1759 emitter: self.view.model.entity_id,
1760 });
1761 }
1762
1763 pub fn on_focus_changed(
1764 &mut self,
1765 listener: impl Fn(&mut V, &FocusEvent, &mut ViewContext<V>) + Send + 'static,
1766 ) {
1767 let handle = self.view().downgrade();
1768 self.window.focus_listeners.push(Box::new(move |event, cx| {
1769 handle
1770 .update(cx, |view, cx| listener(view, event, cx))
1771 .log_err();
1772 }));
1773 }
1774
1775 pub fn with_key_listeners<R>(
1776 &mut self,
1777 key_listeners: impl IntoIterator<Item = (TypeId, KeyListener<V>)>,
1778 f: impl FnOnce(&mut Self) -> R,
1779 ) -> R {
1780 let old_stack_len = self.window.key_dispatch_stack.len();
1781 if !self.window.freeze_key_dispatch_stack {
1782 for (event_type, listener) in key_listeners {
1783 let handle = self.view().downgrade();
1784 let listener = Box::new(
1785 move |event: &dyn Any,
1786 context_stack: &[&DispatchContext],
1787 phase: DispatchPhase,
1788 cx: &mut WindowContext<'_>| {
1789 handle
1790 .update(cx, |view, cx| {
1791 listener(view, event, context_stack, phase, cx)
1792 })
1793 .log_err()
1794 .flatten()
1795 },
1796 );
1797 self.window
1798 .key_dispatch_stack
1799 .push(KeyDispatchStackFrame::Listener {
1800 event_type,
1801 listener,
1802 });
1803 }
1804 }
1805
1806 let result = f(self);
1807
1808 if !self.window.freeze_key_dispatch_stack {
1809 self.window.key_dispatch_stack.truncate(old_stack_len);
1810 }
1811
1812 result
1813 }
1814
1815 pub fn with_key_dispatch_context<R>(
1816 &mut self,
1817 context: DispatchContext,
1818 f: impl FnOnce(&mut Self) -> R,
1819 ) -> R {
1820 if context.is_empty() {
1821 return f(self);
1822 }
1823
1824 if !self.window.freeze_key_dispatch_stack {
1825 self.window
1826 .key_dispatch_stack
1827 .push(KeyDispatchStackFrame::Context(context));
1828 }
1829
1830 let result = f(self);
1831
1832 if !self.window.freeze_key_dispatch_stack {
1833 self.window.key_dispatch_stack.pop();
1834 }
1835
1836 result
1837 }
1838
1839 pub fn with_focus<R>(
1840 &mut self,
1841 focus_handle: FocusHandle,
1842 f: impl FnOnce(&mut Self) -> R,
1843 ) -> R {
1844 if let Some(parent_focus_id) = self.window.focus_stack.last().copied() {
1845 self.window
1846 .focus_parents_by_child
1847 .insert(focus_handle.id, parent_focus_id);
1848 }
1849 self.window.focus_stack.push(focus_handle.id);
1850
1851 if Some(focus_handle.id) == self.window.focus {
1852 self.window.freeze_key_dispatch_stack = true;
1853 }
1854
1855 let result = f(self);
1856
1857 self.window.focus_stack.pop();
1858 result
1859 }
1860
1861 pub fn run_on_main<R>(
1862 &mut self,
1863 view: &mut V,
1864 f: impl FnOnce(&mut V, &mut MainThread<ViewContext<'_, V>>) -> R + Send + 'static,
1865 ) -> Task<Result<R>>
1866 where
1867 R: Send + 'static,
1868 {
1869 if self.executor.is_main_thread() {
1870 let cx = unsafe { mem::transmute::<&mut Self, &mut MainThread<Self>>(self) };
1871 Task::ready(Ok(f(view, cx)))
1872 } else {
1873 let view = self.view();
1874 self.window_cx.run_on_main(move |cx| view.update(cx, f))
1875 }
1876 }
1877
1878 pub fn spawn<Fut, R>(
1879 &mut self,
1880 f: impl FnOnce(WeakView<V>, AsyncWindowContext) -> Fut,
1881 ) -> Task<R>
1882 where
1883 R: Send + 'static,
1884 Fut: Future<Output = R> + Send + 'static,
1885 {
1886 let view = self.view().downgrade();
1887 self.window_cx.spawn(move |_, cx| f(view, cx))
1888 }
1889
1890 pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
1891 where
1892 G: 'static + Send,
1893 {
1894 let mut global = self.app.lease_global::<G>();
1895 let result = f(&mut global, self);
1896 self.app.end_global_lease(global);
1897 result
1898 }
1899
1900 pub fn observe_global<G: 'static>(
1901 &mut self,
1902 f: impl Fn(&mut V, &mut ViewContext<'_, V>) + Send + 'static,
1903 ) -> Subscription {
1904 let window_handle = self.window.handle;
1905 let view = self.view().downgrade();
1906 self.global_observers.insert(
1907 TypeId::of::<G>(),
1908 Box::new(move |cx| {
1909 window_handle
1910 .update(cx, |_, cx| view.update(cx, |view, cx| f(view, cx)).is_ok())
1911 .unwrap_or(false)
1912 }),
1913 )
1914 }
1915
1916 pub fn on_mouse_event<Event: 'static>(
1917 &mut self,
1918 handler: impl Fn(&mut V, &Event, DispatchPhase, &mut ViewContext<V>) + Send + 'static,
1919 ) {
1920 let handle = self.view();
1921 self.window_cx.on_mouse_event(move |event, phase, cx| {
1922 handle.update(cx, |view, cx| {
1923 handler(view, event, phase, cx);
1924 })
1925 });
1926 }
1927}
1928
1929impl<V> ViewContext<'_, V>
1930where
1931 V: EventEmitter,
1932 V::Event: 'static + Send,
1933{
1934 pub fn emit(&mut self, event: V::Event) {
1935 let emitter = self.view.model.entity_id;
1936 self.app.push_effect(Effect::Emit {
1937 emitter,
1938 event: Box::new(event),
1939 });
1940 }
1941}
1942
1943impl<V: 'static> MainThread<ViewContext<'_, V>> {
1944 fn platform_window(&self) -> &dyn PlatformWindow {
1945 self.window.platform_window.borrow_on_main_thread().as_ref()
1946 }
1947
1948 pub fn activate_window(&self) {
1949 self.platform_window().activate();
1950 }
1951}
1952
1953impl<V> Context for ViewContext<'_, V> {
1954 type WindowContext<'a> = WindowContext<'a>;
1955 type ModelContext<'b, U> = ModelContext<'b, U>;
1956 type Result<U> = U;
1957
1958 fn build_model<T>(
1959 &mut self,
1960 build_model: impl FnOnce(&mut Self::ModelContext<'_, T>) -> T,
1961 ) -> Model<T>
1962 where
1963 T: 'static + Send,
1964 {
1965 self.window_cx.build_model(build_model)
1966 }
1967
1968 fn update_model<T: 'static, R>(
1969 &mut self,
1970 model: &Model<T>,
1971 update: impl FnOnce(&mut T, &mut Self::ModelContext<'_, T>) -> R,
1972 ) -> R {
1973 self.window_cx.update_model(model, update)
1974 }
1975
1976 fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
1977 where
1978 F: FnOnce(AnyView, &mut Self::WindowContext<'_>) -> T,
1979 {
1980 self.window_cx.update_window(window, update)
1981 }
1982}
1983
1984impl<V: 'static> VisualContext for ViewContext<'_, V> {
1985 type ViewContext<'a, W: 'static> = ViewContext<'a, W>;
1986
1987 fn build_view<W: 'static + Send>(
1988 &mut self,
1989 build_view: impl FnOnce(&mut Self::ViewContext<'_, W>) -> W,
1990 ) -> Self::Result<View<W>> {
1991 self.window_cx.build_view(build_view)
1992 }
1993
1994 fn update_view<V2: 'static, R>(
1995 &mut self,
1996 view: &View<V2>,
1997 update: impl FnOnce(&mut V2, &mut Self::ViewContext<'_, V2>) -> R,
1998 ) -> Self::Result<R> {
1999 VisualContext::update_view(&mut self.window_cx, view, update)
2000 }
2001
2002 fn replace_root_view<W>(
2003 &mut self,
2004 build_view: impl FnOnce(&mut Self::ViewContext<'_, W>) -> W,
2005 ) -> Self::Result<View<W>>
2006 where
2007 W: 'static + Send + Render,
2008 {
2009 self.window_cx.replace_root_view(build_view)
2010 }
2011}
2012
2013impl<'a, V> std::ops::Deref for ViewContext<'a, V> {
2014 type Target = WindowContext<'a>;
2015
2016 fn deref(&self) -> &Self::Target {
2017 &self.window_cx
2018 }
2019}
2020
2021impl<'a, V> std::ops::DerefMut for ViewContext<'a, V> {
2022 fn deref_mut(&mut self) -> &mut Self::Target {
2023 &mut self.window_cx
2024 }
2025}
2026
2027// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
2028slotmap::new_key_type! { pub struct WindowId; }
2029
2030impl WindowId {
2031 pub fn as_u64(&self) -> u64 {
2032 self.0.as_ffi()
2033 }
2034}
2035
2036#[derive(Deref, DerefMut)]
2037pub struct WindowHandle<V> {
2038 #[deref]
2039 #[deref_mut]
2040 pub(crate) any_handle: AnyWindowHandle,
2041 state_type: PhantomData<V>,
2042}
2043
2044impl<V: 'static + Render> WindowHandle<V> {
2045 pub fn new(id: WindowId) -> Self {
2046 WindowHandle {
2047 any_handle: AnyWindowHandle {
2048 id,
2049 state_type: TypeId::of::<V>(),
2050 },
2051 state_type: PhantomData,
2052 }
2053 }
2054
2055 pub fn update<C, R>(
2056 &self,
2057 cx: &mut C,
2058 update: impl FnOnce(&mut V, &mut <C::WindowContext<'_> as UpdateView>::ViewContext<'_, V>) -> R,
2059 ) -> Result<R>
2060 where
2061 C: Context,
2062 {
2063 cx.update_window(self.any_handle, |root_view, cx| {
2064 let view = root_view
2065 .downcast::<V>()
2066 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
2067
2068 Ok(cx.update_view(&view, update))
2069 })?
2070 }
2071}
2072
2073impl<V> Copy for WindowHandle<V> {}
2074
2075impl<V> Clone for WindowHandle<V> {
2076 fn clone(&self) -> Self {
2077 WindowHandle {
2078 any_handle: self.any_handle,
2079 state_type: PhantomData,
2080 }
2081 }
2082}
2083
2084impl<V> PartialEq for WindowHandle<V> {
2085 fn eq(&self, other: &Self) -> bool {
2086 self.any_handle == other.any_handle
2087 }
2088}
2089
2090impl<V> Eq for WindowHandle<V> {}
2091
2092impl<V> Hash for WindowHandle<V> {
2093 fn hash<H: Hasher>(&self, state: &mut H) {
2094 self.any_handle.hash(state);
2095 }
2096}
2097
2098impl<V: 'static> Into<AnyWindowHandle> for WindowHandle<V> {
2099 fn into(self) -> AnyWindowHandle {
2100 self.any_handle
2101 }
2102}
2103
2104#[derive(Copy, Clone, PartialEq, Eq, Hash)]
2105pub struct AnyWindowHandle {
2106 pub(crate) id: WindowId,
2107 state_type: TypeId,
2108}
2109
2110impl AnyWindowHandle {
2111 pub fn window_id(&self) -> WindowId {
2112 self.id
2113 }
2114
2115 pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
2116 if TypeId::of::<T>() == self.state_type {
2117 Some(WindowHandle {
2118 any_handle: *self,
2119 state_type: PhantomData,
2120 })
2121 } else {
2122 None
2123 }
2124 }
2125
2126 pub fn update<C, R>(
2127 &self,
2128 cx: &mut C,
2129 update: impl FnOnce(AnyView, &mut C::WindowContext<'_>) -> R,
2130 ) -> Result<R>
2131 where
2132 C: Context,
2133 {
2134 cx.update_window(*self, update)
2135 }
2136}
2137
2138#[cfg(any(test, feature = "test-support"))]
2139impl From<SmallVec<[u32; 16]>> for StackingOrder {
2140 fn from(small_vec: SmallVec<[u32; 16]>) -> Self {
2141 StackingOrder(small_vec)
2142 }
2143}
2144
2145#[derive(Clone, Debug, Eq, PartialEq, Hash)]
2146pub enum ElementId {
2147 View(EntityId),
2148 Number(usize),
2149 Name(SharedString),
2150 FocusHandle(FocusId),
2151}
2152
2153impl From<EntityId> for ElementId {
2154 fn from(id: EntityId) -> Self {
2155 ElementId::View(id)
2156 }
2157}
2158
2159impl From<usize> for ElementId {
2160 fn from(id: usize) -> Self {
2161 ElementId::Number(id)
2162 }
2163}
2164
2165impl From<i32> for ElementId {
2166 fn from(id: i32) -> Self {
2167 Self::Number(id as usize)
2168 }
2169}
2170
2171impl From<SharedString> for ElementId {
2172 fn from(name: SharedString) -> Self {
2173 ElementId::Name(name)
2174 }
2175}
2176
2177impl From<&'static str> for ElementId {
2178 fn from(name: &'static str) -> Self {
2179 ElementId::Name(name.into())
2180 }
2181}
2182
2183impl<'a> From<&'a FocusHandle> for ElementId {
2184 fn from(handle: &'a FocusHandle) -> Self {
2185 ElementId::FocusHandle(handle.id)
2186 }
2187}