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