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