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