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