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