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