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