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