1use crate::{
2 px, size, transparent_black, Action, AnyDrag, AnyTooltip, AnyView, AppContext, Arena,
3 AsyncWindowContext, AvailableSpace, Bounds, Context, Corners, CursorStyle,
4 DispatchActionListener, DispatchNodeId, DispatchTree, DisplayId, Edges, Effect, Entity,
5 EntityId, EventEmitter, FileDropEvent, Flatten, GlobalElementId, Hsla, KeyBinding, KeyContext,
6 KeyDownEvent, KeystrokeEvent, Model, ModelContext, Modifiers, MouseButton, MouseMoveEvent,
7 MouseUpEvent, Pixels, PlatformAtlas, PlatformDisplay, PlatformInput, PlatformInputHandler,
8 PlatformWindow, Point, PromptLevel, Render, ScaledPixels, Scene, SharedString, Size,
9 SubscriberSet, Subscription, TaffyLayoutEngine, Task, View, VisualContext, WeakView,
10 WindowBounds, WindowOptions,
11};
12use anyhow::{anyhow, Context as _, Result};
13use collections::{FxHashMap, FxHashSet};
14use derive_more::{Deref, DerefMut};
15use futures::{
16 channel::{mpsc, oneshot},
17 StreamExt,
18};
19use parking_lot::RwLock;
20use slotmap::SlotMap;
21use smallvec::SmallVec;
22use std::{
23 any::{Any, TypeId},
24 borrow::{Borrow, BorrowMut},
25 cell::RefCell,
26 collections::hash_map::Entry,
27 fmt::{Debug, Display},
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
40mod element_cx;
41pub use element_cx::*;
42
43const ACTIVE_DRAG_Z_INDEX: u8 = 1;
44
45/// A global stacking order, which is created by stacking successive z-index values.
46/// Each z-index will always be interpreted in the context of its parent z-index.
47#[derive(Deref, DerefMut, Clone, Ord, PartialOrd, PartialEq, Eq, Default)]
48pub struct StackingOrder {
49 #[deref]
50 #[deref_mut]
51 context_stack: SmallVec<[u8; 64]>,
52 pub(crate) id: u32,
53}
54
55impl std::fmt::Debug for StackingOrder {
56 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
57 let mut stacks = self.context_stack.iter().peekable();
58 write!(f, "[({}): ", self.id)?;
59 while let Some(z_index) = stacks.next() {
60 write!(f, "{z_index}")?;
61 if stacks.peek().is_some() {
62 write!(f, "->")?;
63 }
64 }
65 write!(f, "]")?;
66 Ok(())
67 }
68}
69
70/// Represents the two different phases when dispatching events.
71#[derive(Default, Copy, Clone, Debug, Eq, PartialEq)]
72pub enum DispatchPhase {
73 /// After the capture phase comes the bubble phase, in which mouse event listeners are
74 /// invoked front to back and keyboard event listeners are invoked from the focused element
75 /// to the root of the element tree. This is the phase you'll most commonly want to use when
76 /// registering event listeners.
77 #[default]
78 Bubble,
79 /// During the initial capture phase, mouse event listeners are invoked back to front, and keyboard
80 /// listeners are invoked from the root of the tree downward toward the focused element. This phase
81 /// is used for special purposes such as clearing the "pressed" state for click events. If
82 /// you stop event propagation during this phase, you need to know what you're doing. Handlers
83 /// outside of the immediate region may rely on detecting non-local events during this phase.
84 Capture,
85}
86
87impl DispatchPhase {
88 /// Returns true if this represents the "bubble" phase.
89 pub fn bubble(self) -> bool {
90 self == DispatchPhase::Bubble
91 }
92
93 /// Returns true if this represents the "capture" phase.
94 pub fn capture(self) -> bool {
95 self == DispatchPhase::Capture
96 }
97}
98
99type AnyObserver = Box<dyn FnMut(&mut WindowContext) -> bool + 'static>;
100type AnyMouseListener = Box<dyn FnMut(&dyn Any, DispatchPhase, &mut ElementContext) + 'static>;
101type AnyWindowFocusListener = Box<dyn FnMut(&FocusEvent, &mut WindowContext) -> bool + 'static>;
102
103struct FocusEvent {
104 previous_focus_path: SmallVec<[FocusId; 8]>,
105 current_focus_path: SmallVec<[FocusId; 8]>,
106}
107
108slotmap::new_key_type! {
109 /// A globally unique identifier for a focusable element.
110 pub struct FocusId;
111}
112
113thread_local! {
114 pub(crate) static ELEMENT_ARENA: RefCell<Arena> = RefCell::new(Arena::new(4 * 1024 * 1024));
115}
116
117impl FocusId {
118 /// Obtains whether the element associated with this handle is currently focused.
119 pub fn is_focused(&self, cx: &WindowContext) -> bool {
120 cx.window.focus == Some(*self)
121 }
122
123 /// Obtains whether the element associated with this handle contains the focused
124 /// element or is itself focused.
125 pub fn contains_focused(&self, cx: &WindowContext) -> bool {
126 cx.focused()
127 .map_or(false, |focused| self.contains(focused.id, cx))
128 }
129
130 /// Obtains whether the element associated with this handle is contained within the
131 /// focused element or is itself focused.
132 pub fn within_focused(&self, cx: &WindowContext) -> bool {
133 let focused = cx.focused();
134 focused.map_or(false, |focused| focused.id.contains(*self, cx))
135 }
136
137 /// Obtains whether this handle contains the given handle in the most recently rendered frame.
138 pub(crate) fn contains(&self, other: Self, cx: &WindowContext) -> bool {
139 cx.window
140 .rendered_frame
141 .dispatch_tree
142 .focus_contains(*self, other)
143 }
144}
145
146/// A handle which can be used to track and manipulate the focused element in a window.
147pub struct FocusHandle {
148 pub(crate) id: FocusId,
149 handles: Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
150}
151
152impl std::fmt::Debug for FocusHandle {
153 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
154 f.write_fmt(format_args!("FocusHandle({:?})", self.id))
155 }
156}
157
158impl FocusHandle {
159 pub(crate) fn new(handles: &Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>) -> Self {
160 let id = handles.write().insert(AtomicUsize::new(1));
161 Self {
162 id,
163 handles: handles.clone(),
164 }
165 }
166
167 pub(crate) fn for_id(
168 id: FocusId,
169 handles: &Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
170 ) -> Option<Self> {
171 let lock = handles.read();
172 let ref_count = lock.get(id)?;
173 if ref_count.load(SeqCst) == 0 {
174 None
175 } else {
176 ref_count.fetch_add(1, SeqCst);
177 Some(Self {
178 id,
179 handles: handles.clone(),
180 })
181 }
182 }
183
184 /// Moves the focus to the element associated with this handle.
185 pub fn focus(&self, cx: &mut WindowContext) {
186 cx.focus(self)
187 }
188
189 /// Obtains whether the element associated with this handle is currently focused.
190 pub fn is_focused(&self, cx: &WindowContext) -> bool {
191 self.id.is_focused(cx)
192 }
193
194 /// Obtains whether the element associated with this handle contains the focused
195 /// element or is itself focused.
196 pub fn contains_focused(&self, cx: &WindowContext) -> bool {
197 self.id.contains_focused(cx)
198 }
199
200 /// Obtains whether the element associated with this handle is contained within the
201 /// focused element or is itself focused.
202 pub fn within_focused(&self, cx: &WindowContext) -> bool {
203 self.id.within_focused(cx)
204 }
205
206 /// Obtains whether this handle contains the given handle in the most recently rendered frame.
207 pub fn contains(&self, other: &Self, cx: &WindowContext) -> bool {
208 self.id.contains(other.id, cx)
209 }
210}
211
212impl Clone for FocusHandle {
213 fn clone(&self) -> Self {
214 Self::for_id(self.id, &self.handles).unwrap()
215 }
216}
217
218impl PartialEq for FocusHandle {
219 fn eq(&self, other: &Self) -> bool {
220 self.id == other.id
221 }
222}
223
224impl Eq for FocusHandle {}
225
226impl Drop for FocusHandle {
227 fn drop(&mut self) {
228 self.handles
229 .read()
230 .get(self.id)
231 .unwrap()
232 .fetch_sub(1, SeqCst);
233 }
234}
235
236/// FocusableView allows users of your view to easily
237/// focus it (using cx.focus_view(view))
238pub trait FocusableView: 'static + Render {
239 /// Returns the focus handle associated with this view.
240 fn focus_handle(&self, cx: &AppContext) -> FocusHandle;
241}
242
243/// ManagedView is a view (like a Modal, Popover, Menu, etc.)
244/// where the lifecycle of the view is handled by another view.
245pub trait ManagedView: FocusableView + EventEmitter<DismissEvent> {}
246
247impl<M: FocusableView + EventEmitter<DismissEvent>> ManagedView for M {}
248
249/// Emitted by implementers of [`ManagedView`] to indicate the view should be dismissed, such as when a view is presented as a modal.
250pub struct DismissEvent;
251
252// Holds the state for a specific window.
253#[doc(hidden)]
254pub struct Window {
255 pub(crate) handle: AnyWindowHandle,
256 pub(crate) removed: bool,
257 pub(crate) platform_window: Box<dyn PlatformWindow>,
258 display_id: DisplayId,
259 sprite_atlas: Arc<dyn PlatformAtlas>,
260 pub(crate) rem_size: Pixels,
261 pub(crate) viewport_size: Size<Pixels>,
262 layout_engine: Option<TaffyLayoutEngine>,
263 pub(crate) root_view: Option<AnyView>,
264 pub(crate) element_id_stack: GlobalElementId,
265 pub(crate) rendered_frame: Frame,
266 pub(crate) next_frame: Frame,
267 pub(crate) dirty_views: FxHashSet<EntityId>,
268 pub(crate) focus_handles: Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
269 focus_listeners: SubscriberSet<(), AnyWindowFocusListener>,
270 focus_lost_listeners: SubscriberSet<(), AnyObserver>,
271 default_prevented: bool,
272 mouse_position: Point<Pixels>,
273 modifiers: Modifiers,
274 scale_factor: f32,
275 bounds: WindowBounds,
276 bounds_observers: SubscriberSet<(), AnyObserver>,
277 active: bool,
278 pub(crate) dirty: bool,
279 pub(crate) refreshing: bool,
280 pub(crate) drawing: bool,
281 activation_observers: SubscriberSet<(), AnyObserver>,
282 pub(crate) focus: Option<FocusId>,
283 focus_enabled: bool,
284
285 #[cfg(any(test, feature = "test-support"))]
286 pub(crate) focus_invalidated: bool,
287}
288
289struct RequestedInputHandler {
290 view_id: EntityId,
291 handler: Option<PlatformInputHandler>,
292}
293
294struct TooltipRequest {
295 view_id: EntityId,
296 tooltip: AnyTooltip,
297}
298
299pub(crate) struct ElementStateBox {
300 pub(crate) inner: Box<dyn Any>,
301 pub(crate) parent_view_id: EntityId,
302 #[cfg(debug_assertions)]
303 pub(crate) type_name: &'static str,
304}
305
306pub(crate) struct Frame {
307 focus: Option<FocusId>,
308 window_active: bool,
309 pub(crate) element_states: FxHashMap<GlobalElementId, ElementStateBox>,
310 mouse_listeners: FxHashMap<TypeId, Vec<(StackingOrder, EntityId, AnyMouseListener)>>,
311 pub(crate) dispatch_tree: DispatchTree,
312 pub(crate) scene: Scene,
313 pub(crate) depth_map: Vec<(StackingOrder, EntityId, Bounds<Pixels>)>,
314 pub(crate) z_index_stack: StackingOrder,
315 pub(crate) next_stacking_order_id: u32,
316 pub(crate) next_root_z_index: u8,
317 pub(crate) content_mask_stack: Vec<ContentMask<Pixels>>,
318 pub(crate) element_offset_stack: Vec<Point<Pixels>>,
319 requested_input_handler: Option<RequestedInputHandler>,
320 tooltip_request: Option<TooltipRequest>,
321 cursor_styles: FxHashMap<EntityId, CursorStyle>,
322 requested_cursor_style: Option<CursorStyle>,
323 pub(crate) view_stack: Vec<EntityId>,
324 pub(crate) reused_views: FxHashSet<EntityId>,
325
326 #[cfg(any(test, feature = "test-support"))]
327 pub(crate) debug_bounds: collections::FxHashMap<String, Bounds<Pixels>>,
328}
329
330impl Frame {
331 fn new(dispatch_tree: DispatchTree) -> Self {
332 Frame {
333 focus: None,
334 window_active: false,
335 element_states: FxHashMap::default(),
336 mouse_listeners: FxHashMap::default(),
337 dispatch_tree,
338 scene: Scene::default(),
339 depth_map: Vec::new(),
340 z_index_stack: StackingOrder::default(),
341 next_stacking_order_id: 0,
342 next_root_z_index: 0,
343 content_mask_stack: Vec::new(),
344 element_offset_stack: Vec::new(),
345 requested_input_handler: None,
346 tooltip_request: None,
347 cursor_styles: FxHashMap::default(),
348 requested_cursor_style: None,
349 view_stack: Vec::new(),
350 reused_views: FxHashSet::default(),
351
352 #[cfg(any(test, feature = "test-support"))]
353 debug_bounds: FxHashMap::default(),
354 }
355 }
356
357 fn clear(&mut self) {
358 self.element_states.clear();
359 self.mouse_listeners.values_mut().for_each(Vec::clear);
360 self.dispatch_tree.clear();
361 self.depth_map.clear();
362 self.next_stacking_order_id = 0;
363 self.next_root_z_index = 0;
364 self.reused_views.clear();
365 self.scene.clear();
366 self.requested_input_handler.take();
367 self.tooltip_request.take();
368 self.cursor_styles.clear();
369 self.requested_cursor_style.take();
370 debug_assert_eq!(self.view_stack.len(), 0);
371 }
372
373 fn focus_path(&self) -> SmallVec<[FocusId; 8]> {
374 self.focus
375 .map(|focus_id| self.dispatch_tree.focus_path(focus_id))
376 .unwrap_or_default()
377 }
378
379 fn finish(&mut self, prev_frame: &mut Self) {
380 // Reuse mouse listeners that didn't change since the last frame.
381 for (type_id, listeners) in &mut prev_frame.mouse_listeners {
382 let next_listeners = self.mouse_listeners.entry(*type_id).or_default();
383 for (order, view_id, listener) in listeners.drain(..) {
384 if self.reused_views.contains(&view_id) {
385 next_listeners.push((order, view_id, listener));
386 }
387 }
388 }
389
390 // Reuse entries in the depth map that didn't change since the last frame.
391 for (order, view_id, bounds) in prev_frame.depth_map.drain(..) {
392 if self.reused_views.contains(&view_id) {
393 match self
394 .depth_map
395 .binary_search_by(|(level, _, _)| order.cmp(level))
396 {
397 Ok(i) | Err(i) => self.depth_map.insert(i, (order, view_id, bounds)),
398 }
399 }
400 }
401
402 // Retain element states for views that didn't change since the last frame.
403 for (element_id, state) in prev_frame.element_states.drain() {
404 if self.reused_views.contains(&state.parent_view_id) {
405 self.element_states.entry(element_id).or_insert(state);
406 }
407 }
408
409 // Reuse geometry that didn't change since the last frame.
410 self.scene
411 .reuse_views(&self.reused_views, &mut prev_frame.scene);
412 self.scene.finish();
413 }
414}
415
416impl Window {
417 pub(crate) fn new(
418 handle: AnyWindowHandle,
419 options: WindowOptions,
420 cx: &mut AppContext,
421 ) -> Self {
422 let platform_window = cx.platform.open_window(handle, options);
423 let display_id = platform_window.display().id();
424 let sprite_atlas = platform_window.sprite_atlas();
425 let mouse_position = platform_window.mouse_position();
426 let modifiers = platform_window.modifiers();
427 let content_size = platform_window.content_size();
428 let scale_factor = platform_window.scale_factor();
429 let bounds = platform_window.bounds();
430
431 platform_window.on_request_frame(Box::new({
432 let mut cx = cx.to_async();
433 move || {
434 handle.update(&mut cx, |_, cx| cx.draw()).log_err();
435 }
436 }));
437 platform_window.on_resize(Box::new({
438 let mut cx = cx.to_async();
439 move |_, _| {
440 handle
441 .update(&mut cx, |_, cx| cx.window_bounds_changed())
442 .log_err();
443 }
444 }));
445 platform_window.on_moved(Box::new({
446 let mut cx = cx.to_async();
447 move || {
448 handle
449 .update(&mut cx, |_, cx| cx.window_bounds_changed())
450 .log_err();
451 }
452 }));
453 platform_window.on_active_status_change(Box::new({
454 let mut cx = cx.to_async();
455 move |active| {
456 handle
457 .update(&mut cx, |_, cx| {
458 cx.window.active = active;
459 cx.window
460 .activation_observers
461 .clone()
462 .retain(&(), |callback| callback(cx));
463 })
464 .log_err();
465 }
466 }));
467
468 platform_window.on_input({
469 let mut cx = cx.to_async();
470 Box::new(move |event| {
471 handle
472 .update(&mut cx, |_, cx| cx.dispatch_event(event))
473 .log_err()
474 .unwrap_or(false)
475 })
476 });
477
478 Window {
479 handle,
480 removed: false,
481 platform_window,
482 display_id,
483 sprite_atlas,
484 rem_size: px(16.),
485 viewport_size: content_size,
486 layout_engine: Some(TaffyLayoutEngine::new()),
487 root_view: None,
488 element_id_stack: GlobalElementId::default(),
489 rendered_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
490 next_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
491 dirty_views: FxHashSet::default(),
492 focus_handles: Arc::new(RwLock::new(SlotMap::with_key())),
493 focus_listeners: SubscriberSet::new(),
494 focus_lost_listeners: SubscriberSet::new(),
495 default_prevented: true,
496 mouse_position,
497 modifiers,
498 scale_factor,
499 bounds,
500 bounds_observers: SubscriberSet::new(),
501 active: false,
502 dirty: false,
503 refreshing: false,
504 drawing: false,
505 activation_observers: SubscriberSet::new(),
506 focus: None,
507 focus_enabled: true,
508
509 #[cfg(any(test, feature = "test-support"))]
510 focus_invalidated: false,
511 }
512 }
513}
514
515/// Indicates which region of the window is visible. Content falling outside of this mask will not be
516/// rendered. Currently, only rectangular content masks are supported, but we give the mask its own type
517/// to leave room to support more complex shapes in the future.
518#[derive(Clone, Debug, Default, PartialEq, Eq)]
519#[repr(C)]
520pub struct ContentMask<P: Clone + Default + Debug> {
521 /// The bounds
522 pub bounds: Bounds<P>,
523}
524
525impl ContentMask<Pixels> {
526 /// Scale the content mask's pixel units by the given scaling factor.
527 pub fn scale(&self, factor: f32) -> ContentMask<ScaledPixels> {
528 ContentMask {
529 bounds: self.bounds.scale(factor),
530 }
531 }
532
533 /// Intersect the content mask with the given content mask.
534 pub fn intersect(&self, other: &Self) -> Self {
535 let bounds = self.bounds.intersect(&other.bounds);
536 ContentMask { bounds }
537 }
538}
539
540/// Provides access to application state in the context of a single window. Derefs
541/// to an [`AppContext`], so you can also pass a [`WindowContext`] to any method that takes
542/// an [`AppContext`] and call any [`AppContext`] methods.
543pub struct WindowContext<'a> {
544 pub(crate) app: &'a mut AppContext,
545 pub(crate) window: &'a mut Window,
546}
547
548impl<'a> WindowContext<'a> {
549 pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window) -> Self {
550 Self { app, window }
551 }
552
553 /// Obtain a handle to the window that belongs to this context.
554 pub fn window_handle(&self) -> AnyWindowHandle {
555 self.window.handle
556 }
557
558 /// Mark the window as dirty, scheduling it to be redrawn on the next frame.
559 pub fn refresh(&mut self) {
560 if !self.window.drawing {
561 self.window.refreshing = true;
562 self.window.dirty = true;
563 }
564 }
565
566 /// Close this window.
567 pub fn remove_window(&mut self) {
568 self.window.removed = true;
569 }
570
571 /// Obtain a new [`FocusHandle`], which allows you to track and manipulate the keyboard focus
572 /// for elements rendered within this window.
573 pub fn focus_handle(&mut self) -> FocusHandle {
574 FocusHandle::new(&self.window.focus_handles)
575 }
576
577 /// Obtain the currently focused [`FocusHandle`]. If no elements are focused, returns `None`.
578 pub fn focused(&self) -> Option<FocusHandle> {
579 self.window
580 .focus
581 .and_then(|id| FocusHandle::for_id(id, &self.window.focus_handles))
582 }
583
584 /// Move focus to the element associated with the given [`FocusHandle`].
585 pub fn focus(&mut self, handle: &FocusHandle) {
586 if !self.window.focus_enabled || self.window.focus == Some(handle.id) {
587 return;
588 }
589
590 self.window.focus = Some(handle.id);
591 self.window
592 .rendered_frame
593 .dispatch_tree
594 .clear_pending_keystrokes();
595
596 #[cfg(any(test, feature = "test-support"))]
597 {
598 self.window.focus_invalidated = true;
599 }
600
601 self.refresh();
602 }
603
604 /// Remove focus from all elements within this context's window.
605 pub fn blur(&mut self) {
606 if !self.window.focus_enabled {
607 return;
608 }
609
610 self.window.focus = None;
611 self.refresh();
612 }
613
614 /// Blur the window and don't allow anything in it to be focused again.
615 pub fn disable_focus(&mut self) {
616 self.blur();
617 self.window.focus_enabled = false;
618 }
619
620 /// Dispatch the given action on the currently focused element.
621 pub fn dispatch_action(&mut self, action: Box<dyn Action>) {
622 let focus_handle = self.focused();
623
624 self.defer(move |cx| {
625 let node_id = focus_handle
626 .and_then(|handle| {
627 cx.window
628 .rendered_frame
629 .dispatch_tree
630 .focusable_node_id(handle.id)
631 })
632 .unwrap_or_else(|| cx.window.rendered_frame.dispatch_tree.root_node_id());
633
634 cx.propagate_event = true;
635 cx.dispatch_action_on_node(node_id, action);
636 })
637 }
638
639 pub(crate) fn dispatch_keystroke_observers(
640 &mut self,
641 event: &dyn Any,
642 action: Option<Box<dyn Action>>,
643 ) {
644 let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() else {
645 return;
646 };
647
648 self.keystroke_observers
649 .clone()
650 .retain(&(), move |callback| {
651 (callback)(
652 &KeystrokeEvent {
653 keystroke: key_down_event.keystroke.clone(),
654 action: action.as_ref().map(|action| action.boxed_clone()),
655 },
656 self,
657 );
658 true
659 });
660 }
661
662 pub(crate) fn clear_pending_keystrokes(&mut self) {
663 self.window
664 .rendered_frame
665 .dispatch_tree
666 .clear_pending_keystrokes();
667 self.window
668 .next_frame
669 .dispatch_tree
670 .clear_pending_keystrokes();
671 }
672
673 /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
674 /// that are currently on the stack to be returned to the app.
675 pub fn defer(&mut self, f: impl FnOnce(&mut WindowContext) + 'static) {
676 let handle = self.window.handle;
677 self.app.defer(move |cx| {
678 handle.update(cx, |_, cx| f(cx)).ok();
679 });
680 }
681
682 /// Subscribe to events emitted by a model or view.
683 /// The entity to which you're subscribing must implement the [`EventEmitter`] trait.
684 /// The callback will be invoked a handle to the emitting entity (either a [`View`] or [`Model`]), the event, and a window context for the current window.
685 pub fn subscribe<Emitter, E, Evt>(
686 &mut self,
687 entity: &E,
688 mut on_event: impl FnMut(E, &Evt, &mut WindowContext<'_>) + 'static,
689 ) -> Subscription
690 where
691 Emitter: EventEmitter<Evt>,
692 E: Entity<Emitter>,
693 Evt: 'static,
694 {
695 let entity_id = entity.entity_id();
696 let entity = entity.downgrade();
697 let window_handle = self.window.handle;
698 let (subscription, activate) = self.app.event_listeners.insert(
699 entity_id,
700 (
701 TypeId::of::<Evt>(),
702 Box::new(move |event, cx| {
703 window_handle
704 .update(cx, |_, cx| {
705 if let Some(handle) = E::upgrade_from(&entity) {
706 let event = event.downcast_ref().expect("invalid event type");
707 on_event(handle, event, cx);
708 true
709 } else {
710 false
711 }
712 })
713 .unwrap_or(false)
714 }),
715 ),
716 );
717 self.app.defer(move |_| activate());
718 subscription
719 }
720
721 /// Creates an [`AsyncWindowContext`], which has a static lifetime and can be held across
722 /// await points in async code.
723 pub fn to_async(&self) -> AsyncWindowContext {
724 AsyncWindowContext::new(self.app.to_async(), self.window.handle)
725 }
726
727 /// Schedule the given closure to be run directly after the current frame is rendered.
728 pub fn on_next_frame(&mut self, callback: impl FnOnce(&mut WindowContext) + 'static) {
729 let handle = self.window.handle;
730 let display_id = self.window.display_id;
731
732 let mut frame_consumers = std::mem::take(&mut self.app.frame_consumers);
733 if let Entry::Vacant(e) = frame_consumers.entry(display_id) {
734 let (tx, mut rx) = mpsc::unbounded::<()>();
735 self.platform.set_display_link_output_callback(
736 display_id,
737 Box::new(move || _ = tx.unbounded_send(())),
738 );
739
740 let consumer_task = self.app.spawn(|cx| async move {
741 while rx.next().await.is_some() {
742 cx.update(|cx| {
743 for callback in cx
744 .next_frame_callbacks
745 .get_mut(&display_id)
746 .unwrap()
747 .drain(..)
748 .collect::<SmallVec<[_; 32]>>()
749 {
750 callback(cx);
751 }
752 })
753 .ok();
754
755 // Flush effects, then stop the display link if no new next_frame_callbacks have been added.
756
757 cx.update(|cx| {
758 if cx.next_frame_callbacks.is_empty() {
759 cx.platform.stop_display_link(display_id);
760 }
761 })
762 .ok();
763 }
764 });
765 e.insert(consumer_task);
766 }
767 debug_assert!(self.app.frame_consumers.is_empty());
768 self.app.frame_consumers = frame_consumers;
769
770 if self.next_frame_callbacks.is_empty() {
771 self.platform.start_display_link(display_id);
772 }
773
774 self.next_frame_callbacks
775 .entry(display_id)
776 .or_default()
777 .push(Box::new(move |cx: &mut AppContext| {
778 cx.update_window(handle, |_root_view, cx| callback(cx)).ok();
779 }));
780 }
781
782 /// Spawn the future returned by the given closure on the application thread pool.
783 /// The closure is provided a handle to the current window and an `AsyncWindowContext` for
784 /// use within your future.
785 pub fn spawn<Fut, R>(&mut self, f: impl FnOnce(AsyncWindowContext) -> Fut) -> Task<R>
786 where
787 R: 'static,
788 Fut: Future<Output = R> + 'static,
789 {
790 self.app
791 .spawn(|app| f(AsyncWindowContext::new(app, self.window.handle)))
792 }
793
794 /// Updates the global of the given type. The given closure is given simultaneous mutable
795 /// access both to the global and the context.
796 pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
797 where
798 G: 'static,
799 {
800 let mut global = self.app.lease_global::<G>();
801 let result = f(&mut global, self);
802 self.app.end_global_lease(global);
803 result
804 }
805
806 fn window_bounds_changed(&mut self) {
807 self.window.scale_factor = self.window.platform_window.scale_factor();
808 self.window.viewport_size = self.window.platform_window.content_size();
809 self.window.bounds = self.window.platform_window.bounds();
810 self.window.display_id = self.window.platform_window.display().id();
811 self.refresh();
812
813 self.window
814 .bounds_observers
815 .clone()
816 .retain(&(), |callback| callback(self));
817 }
818
819 /// Returns the bounds of the current window in the global coordinate space, which could span across multiple displays.
820 pub fn window_bounds(&self) -> WindowBounds {
821 self.window.bounds
822 }
823
824 /// Returns the size of the drawable area within the window.
825 pub fn viewport_size(&self) -> Size<Pixels> {
826 self.window.viewport_size
827 }
828
829 /// Returns whether this window is focused by the operating system (receiving key events).
830 pub fn is_window_active(&self) -> bool {
831 self.window.active
832 }
833
834 /// Toggle zoom on the window.
835 pub fn zoom_window(&self) {
836 self.window.platform_window.zoom();
837 }
838
839 /// Updates the window's title at the platform level.
840 pub fn set_window_title(&mut self, title: &str) {
841 self.window.platform_window.set_title(title);
842 }
843
844 /// Mark the window as dirty at the platform level.
845 pub fn set_window_edited(&mut self, edited: bool) {
846 self.window.platform_window.set_edited(edited);
847 }
848
849 /// Determine the display on which the window is visible.
850 pub fn display(&self) -> Option<Rc<dyn PlatformDisplay>> {
851 self.platform
852 .displays()
853 .into_iter()
854 .find(|display| display.id() == self.window.display_id)
855 }
856
857 /// Show the platform character palette.
858 pub fn show_character_palette(&self) {
859 self.window.platform_window.show_character_palette();
860 }
861
862 /// The scale factor of the display associated with the window. For example, it could
863 /// return 2.0 for a "retina" display, indicating that each logical pixel should actually
864 /// be rendered as two pixels on screen.
865 pub fn scale_factor(&self) -> f32 {
866 self.window.scale_factor
867 }
868
869 /// The size of an em for the base font of the application. Adjusting this value allows the
870 /// UI to scale, just like zooming a web page.
871 pub fn rem_size(&self) -> Pixels {
872 self.window.rem_size
873 }
874
875 /// Sets the size of an em for the base font of the application. Adjusting this value allows the
876 /// UI to scale, just like zooming a web page.
877 pub fn set_rem_size(&mut self, rem_size: impl Into<Pixels>) {
878 self.window.rem_size = rem_size.into();
879 }
880
881 /// The line height associated with the current text style.
882 pub fn line_height(&self) -> Pixels {
883 let rem_size = self.rem_size();
884 let text_style = self.text_style();
885 text_style
886 .line_height
887 .to_pixels(text_style.font_size, rem_size)
888 }
889
890 /// Call to prevent the default action of an event. Currently only used to prevent
891 /// parent elements from becoming focused on mouse down.
892 pub fn prevent_default(&mut self) {
893 self.window.default_prevented = true;
894 }
895
896 /// Obtain whether default has been prevented for the event currently being dispatched.
897 pub fn default_prevented(&self) -> bool {
898 self.window.default_prevented
899 }
900
901 /// Determine whether the given action is available along the dispatch path to the currently focused element.
902 pub fn is_action_available(&self, action: &dyn Action) -> bool {
903 let target = self
904 .focused()
905 .and_then(|focused_handle| {
906 self.window
907 .rendered_frame
908 .dispatch_tree
909 .focusable_node_id(focused_handle.id)
910 })
911 .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
912 self.window
913 .rendered_frame
914 .dispatch_tree
915 .is_action_available(action, target)
916 }
917
918 /// The position of the mouse relative to the window.
919 pub fn mouse_position(&self) -> Point<Pixels> {
920 self.window.mouse_position
921 }
922
923 /// The current state of the keyboard's modifiers
924 pub fn modifiers(&self) -> Modifiers {
925 self.window.modifiers
926 }
927
928 /// Updates the cursor style at the platform level.
929 pub fn set_cursor_style(&mut self, style: CursorStyle) {
930 let view_id = self.parent_view_id();
931 self.window.next_frame.cursor_styles.insert(view_id, style);
932 self.window.next_frame.requested_cursor_style = Some(style);
933 }
934
935 /// Sets a tooltip to be rendered for the upcoming frame
936 pub fn set_tooltip(&mut self, tooltip: AnyTooltip) {
937 let view_id = self.parent_view_id();
938 self.window.next_frame.tooltip_request = Some(TooltipRequest { view_id, tooltip });
939 }
940
941 /// Returns true if there is no opaque layer containing the given point
942 /// on top of the given level. Layers whose level is an extension of the
943 /// level are not considered to be on top of the level.
944 pub fn was_top_layer(&self, point: &Point<Pixels>, level: &StackingOrder) -> bool {
945 for (opaque_level, _, bounds) in self.window.rendered_frame.depth_map.iter() {
946 if level >= opaque_level {
947 break;
948 }
949
950 if bounds.contains(point) && !opaque_level.starts_with(level) {
951 return false;
952 }
953 }
954 true
955 }
956
957 pub(crate) fn was_top_layer_under_active_drag(
958 &self,
959 point: &Point<Pixels>,
960 level: &StackingOrder,
961 ) -> bool {
962 for (opaque_level, _, bounds) in self.window.rendered_frame.depth_map.iter() {
963 if level >= opaque_level {
964 break;
965 }
966 if opaque_level.starts_with(&[ACTIVE_DRAG_Z_INDEX]) {
967 continue;
968 }
969
970 if bounds.contains(point) && !opaque_level.starts_with(level) {
971 return false;
972 }
973 }
974 true
975 }
976
977 /// Called during painting to get the current stacking order.
978 pub fn stacking_order(&self) -> &StackingOrder {
979 &self.window.next_frame.z_index_stack
980 }
981
982 pub(crate) fn reuse_view(&mut self) {
983 let view_id = self.parent_view_id();
984 let grafted_view_ids = self
985 .window
986 .next_frame
987 .dispatch_tree
988 .reuse_view(view_id, &mut self.window.rendered_frame.dispatch_tree);
989 for view_id in grafted_view_ids {
990 assert!(self.window.next_frame.reused_views.insert(view_id));
991
992 // Reuse the previous input handler requested during painting of the reused view.
993 if self
994 .window
995 .rendered_frame
996 .requested_input_handler
997 .as_ref()
998 .map_or(false, |requested| requested.view_id == view_id)
999 {
1000 self.window.next_frame.requested_input_handler =
1001 self.window.rendered_frame.requested_input_handler.take();
1002 }
1003
1004 // Reuse the tooltip previously requested during painting of the reused view.
1005 if self
1006 .window
1007 .rendered_frame
1008 .tooltip_request
1009 .as_ref()
1010 .map_or(false, |requested| requested.view_id == view_id)
1011 {
1012 self.window.next_frame.tooltip_request =
1013 self.window.rendered_frame.tooltip_request.take();
1014 }
1015
1016 // Reuse the cursor styles previously requested during painting of the reused view.
1017 if let Some(style) = self.window.rendered_frame.cursor_styles.remove(&view_id) {
1018 self.window.next_frame.cursor_styles.insert(view_id, style);
1019 self.window.next_frame.requested_cursor_style = Some(style);
1020 }
1021 }
1022 }
1023
1024 /// Draw pixels to the display for this window based on the contents of its scene.
1025 pub(crate) fn draw(&mut self) {
1026 self.window.dirty = false;
1027 self.window.drawing = true;
1028
1029 #[cfg(any(test, feature = "test-support"))]
1030 {
1031 self.window.focus_invalidated = false;
1032 }
1033
1034 if let Some(requested_handler) = self.window.rendered_frame.requested_input_handler.as_mut()
1035 {
1036 let input_handler = self.window.platform_window.take_input_handler();
1037 requested_handler.handler = input_handler;
1038 }
1039
1040 let root_view = self.window.root_view.take().unwrap();
1041 self.with_element_context(|cx| {
1042 cx.with_z_index(0, |cx| {
1043 cx.with_key_dispatch(Some(KeyContext::default()), None, |_, cx| {
1044 // We need to use cx.cx here so we can utilize borrow splitting
1045 for (action_type, action_listeners) in &cx.cx.app.global_action_listeners {
1046 for action_listener in action_listeners.iter().cloned() {
1047 cx.cx.window.next_frame.dispatch_tree.on_action(
1048 *action_type,
1049 Rc::new(
1050 move |action: &dyn Any, phase, cx: &mut WindowContext<'_>| {
1051 action_listener(action, phase, cx)
1052 },
1053 ),
1054 )
1055 }
1056 }
1057
1058 let available_space = cx.window.viewport_size.map(Into::into);
1059 root_view.draw(Point::default(), available_space, cx);
1060 })
1061 })
1062 });
1063
1064 if let Some(active_drag) = self.app.active_drag.take() {
1065 self.with_element_context(|cx| {
1066 cx.with_z_index(ACTIVE_DRAG_Z_INDEX, |cx| {
1067 let offset = cx.mouse_position() - active_drag.cursor_offset;
1068 let available_space =
1069 size(AvailableSpace::MinContent, AvailableSpace::MinContent);
1070 active_drag.view.draw(offset, available_space, cx);
1071 })
1072 });
1073 self.active_drag = Some(active_drag);
1074 } else if let Some(tooltip_request) = self.window.next_frame.tooltip_request.take() {
1075 self.with_element_context(|cx| {
1076 cx.with_z_index(1, |cx| {
1077 let available_space =
1078 size(AvailableSpace::MinContent, AvailableSpace::MinContent);
1079 tooltip_request.tooltip.view.draw(
1080 tooltip_request.tooltip.cursor_offset,
1081 available_space,
1082 cx,
1083 );
1084 })
1085 });
1086 self.window.next_frame.tooltip_request = Some(tooltip_request);
1087 }
1088 self.window.dirty_views.clear();
1089
1090 self.window
1091 .next_frame
1092 .dispatch_tree
1093 .preserve_pending_keystrokes(
1094 &mut self.window.rendered_frame.dispatch_tree,
1095 self.window.focus,
1096 );
1097 self.window.next_frame.focus = self.window.focus;
1098 self.window.next_frame.window_active = self.window.active;
1099 self.window.root_view = Some(root_view);
1100
1101 // Set the cursor only if we're the active window.
1102 let cursor_style = self
1103 .window
1104 .next_frame
1105 .requested_cursor_style
1106 .take()
1107 .unwrap_or(CursorStyle::Arrow);
1108 if self.is_window_active() {
1109 self.platform.set_cursor_style(cursor_style);
1110 }
1111
1112 // Register requested input handler with the platform window.
1113 if let Some(requested_input) = self.window.next_frame.requested_input_handler.as_mut() {
1114 if let Some(handler) = requested_input.handler.take() {
1115 self.window.platform_window.set_input_handler(handler);
1116 }
1117 }
1118
1119 self.window.layout_engine.as_mut().unwrap().clear();
1120 self.text_system()
1121 .finish_frame(&self.window.next_frame.reused_views);
1122 self.window
1123 .next_frame
1124 .finish(&mut self.window.rendered_frame);
1125 ELEMENT_ARENA.with_borrow_mut(|element_arena| element_arena.clear());
1126
1127 let previous_focus_path = self.window.rendered_frame.focus_path();
1128 let previous_window_active = self.window.rendered_frame.window_active;
1129 mem::swap(&mut self.window.rendered_frame, &mut self.window.next_frame);
1130 self.window.next_frame.clear();
1131 let current_focus_path = self.window.rendered_frame.focus_path();
1132 let current_window_active = self.window.rendered_frame.window_active;
1133
1134 if previous_focus_path != current_focus_path
1135 || previous_window_active != current_window_active
1136 {
1137 if !previous_focus_path.is_empty() && current_focus_path.is_empty() {
1138 self.window
1139 .focus_lost_listeners
1140 .clone()
1141 .retain(&(), |listener| listener(self));
1142 }
1143
1144 let event = FocusEvent {
1145 previous_focus_path: if previous_window_active {
1146 previous_focus_path
1147 } else {
1148 Default::default()
1149 },
1150 current_focus_path: if current_window_active {
1151 current_focus_path
1152 } else {
1153 Default::default()
1154 },
1155 };
1156 self.window
1157 .focus_listeners
1158 .clone()
1159 .retain(&(), |listener| listener(&event, self));
1160 }
1161
1162 self.window
1163 .platform_window
1164 .draw(&self.window.rendered_frame.scene);
1165 self.window.refreshing = false;
1166 self.window.drawing = false;
1167 }
1168
1169 /// Dispatch a mouse or keyboard event on the window.
1170 pub fn dispatch_event(&mut self, event: PlatformInput) -> bool {
1171 // Handlers may set this to false by calling `stop_propagation`.
1172 self.app.propagate_event = true;
1173 // Handlers may set this to true by calling `prevent_default`.
1174 self.window.default_prevented = false;
1175
1176 let event = match event {
1177 // Track the mouse position with our own state, since accessing the platform
1178 // API for the mouse position can only occur on the main thread.
1179 PlatformInput::MouseMove(mouse_move) => {
1180 self.window.mouse_position = mouse_move.position;
1181 self.window.modifiers = mouse_move.modifiers;
1182 PlatformInput::MouseMove(mouse_move)
1183 }
1184 PlatformInput::MouseDown(mouse_down) => {
1185 self.window.mouse_position = mouse_down.position;
1186 self.window.modifiers = mouse_down.modifiers;
1187 PlatformInput::MouseDown(mouse_down)
1188 }
1189 PlatformInput::MouseUp(mouse_up) => {
1190 self.window.mouse_position = mouse_up.position;
1191 self.window.modifiers = mouse_up.modifiers;
1192 PlatformInput::MouseUp(mouse_up)
1193 }
1194 PlatformInput::MouseExited(mouse_exited) => {
1195 self.window.modifiers = mouse_exited.modifiers;
1196 PlatformInput::MouseExited(mouse_exited)
1197 }
1198 PlatformInput::ModifiersChanged(modifiers_changed) => {
1199 self.window.modifiers = modifiers_changed.modifiers;
1200 PlatformInput::ModifiersChanged(modifiers_changed)
1201 }
1202 PlatformInput::ScrollWheel(scroll_wheel) => {
1203 self.window.mouse_position = scroll_wheel.position;
1204 self.window.modifiers = scroll_wheel.modifiers;
1205 PlatformInput::ScrollWheel(scroll_wheel)
1206 }
1207 // Translate dragging and dropping of external files from the operating system
1208 // to internal drag and drop events.
1209 PlatformInput::FileDrop(file_drop) => match file_drop {
1210 FileDropEvent::Entered { position, paths } => {
1211 self.window.mouse_position = position;
1212 if self.active_drag.is_none() {
1213 self.active_drag = Some(AnyDrag {
1214 value: Box::new(paths.clone()),
1215 view: self.new_view(|_| paths).into(),
1216 cursor_offset: position,
1217 });
1218 }
1219 PlatformInput::MouseMove(MouseMoveEvent {
1220 position,
1221 pressed_button: Some(MouseButton::Left),
1222 modifiers: Modifiers::default(),
1223 })
1224 }
1225 FileDropEvent::Pending { position } => {
1226 self.window.mouse_position = position;
1227 PlatformInput::MouseMove(MouseMoveEvent {
1228 position,
1229 pressed_button: Some(MouseButton::Left),
1230 modifiers: Modifiers::default(),
1231 })
1232 }
1233 FileDropEvent::Submit { position } => {
1234 self.activate(true);
1235 self.window.mouse_position = position;
1236 PlatformInput::MouseUp(MouseUpEvent {
1237 button: MouseButton::Left,
1238 position,
1239 modifiers: Modifiers::default(),
1240 click_count: 1,
1241 })
1242 }
1243 FileDropEvent::Exited => PlatformInput::MouseUp(MouseUpEvent {
1244 button: MouseButton::Left,
1245 position: Point::default(),
1246 modifiers: Modifiers::default(),
1247 click_count: 1,
1248 }),
1249 },
1250 PlatformInput::KeyDown(_) | PlatformInput::KeyUp(_) => event,
1251 };
1252
1253 if let Some(any_mouse_event) = event.mouse_event() {
1254 self.dispatch_mouse_event(any_mouse_event);
1255 } else if let Some(any_key_event) = event.keyboard_event() {
1256 self.dispatch_key_event(any_key_event);
1257 }
1258
1259 !self.app.propagate_event
1260 }
1261
1262 fn dispatch_mouse_event(&mut self, event: &dyn Any) {
1263 if let Some(mut handlers) = self
1264 .window
1265 .rendered_frame
1266 .mouse_listeners
1267 .remove(&event.type_id())
1268 {
1269 // Because handlers may add other handlers, we sort every time.
1270 handlers.sort_by(|(a, _, _), (b, _, _)| a.cmp(b));
1271
1272 // Capture phase, events bubble from back to front. Handlers for this phase are used for
1273 // special purposes, such as detecting events outside of a given Bounds.
1274 for (_, _, handler) in &mut handlers {
1275 self.with_element_context(|cx| {
1276 handler(event, DispatchPhase::Capture, cx);
1277 });
1278 if !self.app.propagate_event {
1279 break;
1280 }
1281 }
1282
1283 // Bubble phase, where most normal handlers do their work.
1284 if self.app.propagate_event {
1285 for (_, _, handler) in handlers.iter_mut().rev() {
1286 self.with_element_context(|cx| {
1287 handler(event, DispatchPhase::Bubble, cx);
1288 });
1289 if !self.app.propagate_event {
1290 break;
1291 }
1292 }
1293 }
1294
1295 self.window
1296 .rendered_frame
1297 .mouse_listeners
1298 .insert(event.type_id(), handlers);
1299 }
1300
1301 if self.app.propagate_event && self.has_active_drag() {
1302 if event.is::<MouseMoveEvent>() {
1303 // If this was a mouse move event, redraw the window so that the
1304 // active drag can follow the mouse cursor.
1305 self.refresh();
1306 } else if event.is::<MouseUpEvent>() {
1307 // If this was a mouse up event, cancel the active drag and redraw
1308 // the window.
1309 self.active_drag = None;
1310 self.refresh();
1311 }
1312 }
1313 }
1314
1315 fn dispatch_key_event(&mut self, event: &dyn Any) {
1316 let node_id = self
1317 .window
1318 .focus
1319 .and_then(|focus_id| {
1320 self.window
1321 .rendered_frame
1322 .dispatch_tree
1323 .focusable_node_id(focus_id)
1324 })
1325 .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
1326
1327 let dispatch_path = self
1328 .window
1329 .rendered_frame
1330 .dispatch_tree
1331 .dispatch_path(node_id);
1332
1333 let mut actions: Vec<Box<dyn Action>> = Vec::new();
1334
1335 let mut context_stack: SmallVec<[KeyContext; 16]> = SmallVec::new();
1336 for node_id in &dispatch_path {
1337 let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1338
1339 if let Some(context) = node.context.clone() {
1340 context_stack.push(context);
1341 }
1342 }
1343
1344 for node_id in dispatch_path.iter().rev() {
1345 // Match keystrokes
1346 let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1347 if node.context.is_some() {
1348 if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
1349 let mut new_actions = self
1350 .window
1351 .rendered_frame
1352 .dispatch_tree
1353 .dispatch_key(&key_down_event.keystroke, &context_stack);
1354 actions.append(&mut new_actions);
1355 }
1356
1357 context_stack.pop();
1358 }
1359 }
1360
1361 if !actions.is_empty() {
1362 self.clear_pending_keystrokes();
1363 }
1364
1365 self.propagate_event = true;
1366 for action in actions {
1367 self.dispatch_action_on_node(node_id, action.boxed_clone());
1368 if !self.propagate_event {
1369 self.dispatch_keystroke_observers(event, Some(action));
1370 return;
1371 }
1372 }
1373
1374 // Capture phase
1375 for node_id in &dispatch_path {
1376 let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1377
1378 for key_listener in node.key_listeners.clone() {
1379 self.with_element_context(|cx| {
1380 key_listener(event, DispatchPhase::Capture, cx);
1381 });
1382 if !self.propagate_event {
1383 return;
1384 }
1385 }
1386 }
1387
1388 // Bubble phase
1389 for node_id in dispatch_path.iter().rev() {
1390 // Handle low level key events
1391 let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1392 for key_listener in node.key_listeners.clone() {
1393 self.with_element_context(|cx| {
1394 key_listener(event, DispatchPhase::Bubble, cx);
1395 });
1396 if !self.propagate_event {
1397 return;
1398 }
1399 }
1400 }
1401
1402 self.dispatch_keystroke_observers(event, None);
1403 }
1404
1405 /// Determine whether a potential multi-stroke key binding is in progress on this window.
1406 pub fn has_pending_keystrokes(&self) -> bool {
1407 self.window
1408 .rendered_frame
1409 .dispatch_tree
1410 .has_pending_keystrokes()
1411 }
1412
1413 fn dispatch_action_on_node(&mut self, node_id: DispatchNodeId, action: Box<dyn Action>) {
1414 let dispatch_path = self
1415 .window
1416 .rendered_frame
1417 .dispatch_tree
1418 .dispatch_path(node_id);
1419
1420 // Capture phase
1421 for node_id in &dispatch_path {
1422 let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1423 for DispatchActionListener {
1424 action_type,
1425 listener,
1426 } in node.action_listeners.clone()
1427 {
1428 let any_action = action.as_any();
1429 if action_type == any_action.type_id() {
1430 self.with_element_context(|cx| {
1431 listener(any_action, DispatchPhase::Capture, cx);
1432 });
1433
1434 if !self.propagate_event {
1435 return;
1436 }
1437 }
1438 }
1439 }
1440 // Bubble phase
1441 for node_id in dispatch_path.iter().rev() {
1442 let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1443 for DispatchActionListener {
1444 action_type,
1445 listener,
1446 } in node.action_listeners.clone()
1447 {
1448 let any_action = action.as_any();
1449 if action_type == any_action.type_id() {
1450 self.propagate_event = false; // Actions stop propagation by default during the bubble phase
1451
1452 self.with_element_context(|cx| {
1453 listener(any_action, DispatchPhase::Bubble, cx);
1454 });
1455
1456 if !self.propagate_event {
1457 return;
1458 }
1459 }
1460 }
1461 }
1462 }
1463
1464 /// Register the given handler to be invoked whenever the global of the given type
1465 /// is updated.
1466 pub fn observe_global<G: 'static>(
1467 &mut self,
1468 f: impl Fn(&mut WindowContext<'_>) + 'static,
1469 ) -> Subscription {
1470 let window_handle = self.window.handle;
1471 let (subscription, activate) = self.global_observers.insert(
1472 TypeId::of::<G>(),
1473 Box::new(move |cx| window_handle.update(cx, |_, cx| f(cx)).is_ok()),
1474 );
1475 self.app.defer(move |_| activate());
1476 subscription
1477 }
1478
1479 /// Focus the current window and bring it to the foreground at the platform level.
1480 pub fn activate_window(&self) {
1481 self.window.platform_window.activate();
1482 }
1483
1484 /// Minimize the current window at the platform level.
1485 pub fn minimize_window(&self) {
1486 self.window.platform_window.minimize();
1487 }
1488
1489 /// Toggle full screen status on the current window at the platform level.
1490 pub fn toggle_full_screen(&self) {
1491 self.window.platform_window.toggle_full_screen();
1492 }
1493
1494 /// Present a platform dialog.
1495 /// The provided message will be presented, along with buttons for each answer.
1496 /// When a button is clicked, the returned Receiver will receive the index of the clicked button.
1497 pub fn prompt(
1498 &self,
1499 level: PromptLevel,
1500 message: &str,
1501 answers: &[&str],
1502 ) -> oneshot::Receiver<usize> {
1503 self.window.platform_window.prompt(level, message, answers)
1504 }
1505
1506 /// Returns all available actions for the focused element.
1507 pub fn available_actions(&self) -> Vec<Box<dyn Action>> {
1508 let node_id = self
1509 .window
1510 .focus
1511 .and_then(|focus_id| {
1512 self.window
1513 .rendered_frame
1514 .dispatch_tree
1515 .focusable_node_id(focus_id)
1516 })
1517 .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
1518
1519 self.window
1520 .rendered_frame
1521 .dispatch_tree
1522 .available_actions(node_id)
1523 }
1524
1525 /// Returns key bindings that invoke the given action on the currently focused element.
1526 pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
1527 self.window
1528 .rendered_frame
1529 .dispatch_tree
1530 .bindings_for_action(
1531 action,
1532 &self.window.rendered_frame.dispatch_tree.context_stack,
1533 )
1534 }
1535
1536 /// Returns any bindings that would invoke the given action on the given focus handle if it were focused.
1537 pub fn bindings_for_action_in(
1538 &self,
1539 action: &dyn Action,
1540 focus_handle: &FocusHandle,
1541 ) -> Vec<KeyBinding> {
1542 let dispatch_tree = &self.window.rendered_frame.dispatch_tree;
1543
1544 let Some(node_id) = dispatch_tree.focusable_node_id(focus_handle.id) else {
1545 return vec![];
1546 };
1547 let context_stack = dispatch_tree
1548 .dispatch_path(node_id)
1549 .into_iter()
1550 .filter_map(|node_id| dispatch_tree.node(node_id).context.clone())
1551 .collect();
1552 dispatch_tree.bindings_for_action(action, &context_stack)
1553 }
1554
1555 /// Returns a generic event listener that invokes the given listener with the view and context associated with the given view handle.
1556 pub fn listener_for<V: Render, E>(
1557 &self,
1558 view: &View<V>,
1559 f: impl Fn(&mut V, &E, &mut ViewContext<V>) + 'static,
1560 ) -> impl Fn(&E, &mut WindowContext) + 'static {
1561 let view = view.downgrade();
1562 move |e: &E, cx: &mut WindowContext| {
1563 view.update(cx, |view, cx| f(view, e, cx)).ok();
1564 }
1565 }
1566
1567 /// Returns a generic handler that invokes the given handler with the view and context associated with the given view handle.
1568 pub fn handler_for<V: Render>(
1569 &self,
1570 view: &View<V>,
1571 f: impl Fn(&mut V, &mut ViewContext<V>) + 'static,
1572 ) -> impl Fn(&mut WindowContext) {
1573 let view = view.downgrade();
1574 move |cx: &mut WindowContext| {
1575 view.update(cx, |view, cx| f(view, cx)).ok();
1576 }
1577 }
1578
1579 /// Register a callback that can interrupt the closing of the current window based the returned boolean.
1580 /// If the callback returns false, the window won't be closed.
1581 pub fn on_window_should_close(&mut self, f: impl Fn(&mut WindowContext) -> bool + 'static) {
1582 let mut this = self.to_async();
1583 self.window
1584 .platform_window
1585 .on_should_close(Box::new(move || {
1586 this.update(|cx| {
1587 // Ensure that the window is removed from the app if it's been closed
1588 // by always pre-empting the system close event.
1589 if f(cx) {
1590 cx.remove_window();
1591 }
1592 false
1593 })
1594 .unwrap_or(true)
1595 }))
1596 }
1597
1598 pub(crate) fn parent_view_id(&self) -> EntityId {
1599 *self
1600 .window
1601 .next_frame
1602 .view_stack
1603 .last()
1604 .expect("a view should always be on the stack while drawing")
1605 }
1606
1607 /// Register an action listener on the window for the next frame. The type of action
1608 /// is determined by the first parameter of the given listener. When the next frame is rendered
1609 /// the listener will be cleared.
1610 ///
1611 /// This is a fairly low-level method, so prefer using action handlers on elements unless you have
1612 /// a specific need to register a global listener.
1613 pub fn on_action(
1614 &mut self,
1615 action_type: TypeId,
1616 listener: impl Fn(&dyn Any, DispatchPhase, &mut WindowContext) + 'static,
1617 ) {
1618 self.window
1619 .next_frame
1620 .dispatch_tree
1621 .on_action(action_type, Rc::new(listener));
1622 }
1623}
1624
1625impl Context for WindowContext<'_> {
1626 type Result<T> = T;
1627
1628 fn new_model<T>(&mut self, build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T) -> Model<T>
1629 where
1630 T: 'static,
1631 {
1632 let slot = self.app.entities.reserve();
1633 let model = build_model(&mut ModelContext::new(&mut *self.app, slot.downgrade()));
1634 self.entities.insert(slot, model)
1635 }
1636
1637 fn update_model<T: 'static, R>(
1638 &mut self,
1639 model: &Model<T>,
1640 update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
1641 ) -> R {
1642 let mut entity = self.entities.lease(model);
1643 let result = update(
1644 &mut *entity,
1645 &mut ModelContext::new(&mut *self.app, model.downgrade()),
1646 );
1647 self.entities.end_lease(entity);
1648 result
1649 }
1650
1651 fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
1652 where
1653 F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
1654 {
1655 if window == self.window.handle {
1656 let root_view = self.window.root_view.clone().unwrap();
1657 Ok(update(root_view, self))
1658 } else {
1659 window.update(self.app, update)
1660 }
1661 }
1662
1663 fn read_model<T, R>(
1664 &self,
1665 handle: &Model<T>,
1666 read: impl FnOnce(&T, &AppContext) -> R,
1667 ) -> Self::Result<R>
1668 where
1669 T: 'static,
1670 {
1671 let entity = self.entities.read(handle);
1672 read(entity, &*self.app)
1673 }
1674
1675 fn read_window<T, R>(
1676 &self,
1677 window: &WindowHandle<T>,
1678 read: impl FnOnce(View<T>, &AppContext) -> R,
1679 ) -> Result<R>
1680 where
1681 T: 'static,
1682 {
1683 if window.any_handle == self.window.handle {
1684 let root_view = self
1685 .window
1686 .root_view
1687 .clone()
1688 .unwrap()
1689 .downcast::<T>()
1690 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
1691 Ok(read(root_view, self))
1692 } else {
1693 self.app.read_window(window, read)
1694 }
1695 }
1696}
1697
1698impl VisualContext for WindowContext<'_> {
1699 fn new_view<V>(
1700 &mut self,
1701 build_view_state: impl FnOnce(&mut ViewContext<'_, V>) -> V,
1702 ) -> Self::Result<View<V>>
1703 where
1704 V: 'static + Render,
1705 {
1706 let slot = self.app.entities.reserve();
1707 let view = View {
1708 model: slot.clone(),
1709 };
1710 let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1711 let entity = build_view_state(&mut cx);
1712 cx.entities.insert(slot, entity);
1713
1714 cx.new_view_observers
1715 .clone()
1716 .retain(&TypeId::of::<V>(), |observer| {
1717 let any_view = AnyView::from(view.clone());
1718 (observer)(any_view, self);
1719 true
1720 });
1721
1722 view
1723 }
1724
1725 /// Updates the given view. Prefer calling [`View::update`] instead, which calls this method.
1726 fn update_view<T: 'static, R>(
1727 &mut self,
1728 view: &View<T>,
1729 update: impl FnOnce(&mut T, &mut ViewContext<'_, T>) -> R,
1730 ) -> Self::Result<R> {
1731 let mut lease = self.app.entities.lease(&view.model);
1732 let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, view);
1733 let result = update(&mut *lease, &mut cx);
1734 cx.app.entities.end_lease(lease);
1735 result
1736 }
1737
1738 fn replace_root_view<V>(
1739 &mut self,
1740 build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
1741 ) -> Self::Result<View<V>>
1742 where
1743 V: 'static + Render,
1744 {
1745 let view = self.new_view(build_view);
1746 self.window.root_view = Some(view.clone().into());
1747 self.refresh();
1748 view
1749 }
1750
1751 fn focus_view<V: crate::FocusableView>(&mut self, view: &View<V>) -> Self::Result<()> {
1752 self.update_view(view, |view, cx| {
1753 view.focus_handle(cx).clone().focus(cx);
1754 })
1755 }
1756
1757 fn dismiss_view<V>(&mut self, view: &View<V>) -> Self::Result<()>
1758 where
1759 V: ManagedView,
1760 {
1761 self.update_view(view, |_, cx| cx.emit(DismissEvent))
1762 }
1763}
1764
1765impl<'a> std::ops::Deref for WindowContext<'a> {
1766 type Target = AppContext;
1767
1768 fn deref(&self) -> &Self::Target {
1769 self.app
1770 }
1771}
1772
1773impl<'a> std::ops::DerefMut for WindowContext<'a> {
1774 fn deref_mut(&mut self) -> &mut Self::Target {
1775 self.app
1776 }
1777}
1778
1779impl<'a> Borrow<AppContext> for WindowContext<'a> {
1780 fn borrow(&self) -> &AppContext {
1781 self.app
1782 }
1783}
1784
1785impl<'a> BorrowMut<AppContext> for WindowContext<'a> {
1786 fn borrow_mut(&mut self) -> &mut AppContext {
1787 self.app
1788 }
1789}
1790
1791/// This trait contains functionality that is shared across [`ViewContext`] and [`WindowContext`]
1792pub trait BorrowWindow: BorrowMut<Window> + BorrowMut<AppContext> {
1793 #[doc(hidden)]
1794 fn app_mut(&mut self) -> &mut AppContext {
1795 self.borrow_mut()
1796 }
1797
1798 #[doc(hidden)]
1799 fn app(&self) -> &AppContext {
1800 self.borrow()
1801 }
1802
1803 #[doc(hidden)]
1804 fn window(&self) -> &Window {
1805 self.borrow()
1806 }
1807
1808 #[doc(hidden)]
1809 fn window_mut(&mut self) -> &mut Window {
1810 self.borrow_mut()
1811 }
1812}
1813
1814impl Borrow<Window> for WindowContext<'_> {
1815 fn borrow(&self) -> &Window {
1816 self.window
1817 }
1818}
1819
1820impl BorrowMut<Window> for WindowContext<'_> {
1821 fn borrow_mut(&mut self) -> &mut Window {
1822 self.window
1823 }
1824}
1825
1826impl<T> BorrowWindow for T where T: BorrowMut<AppContext> + BorrowMut<Window> {}
1827
1828/// Provides access to application state that is specialized for a particular [`View`].
1829/// Allows you to interact with focus, emit events, etc.
1830/// ViewContext also derefs to [`WindowContext`], giving you access to all of its methods as well.
1831/// When you call [`View::update`], you're passed a `&mut V` and an `&mut ViewContext<V>`.
1832pub struct ViewContext<'a, V> {
1833 window_cx: WindowContext<'a>,
1834 view: &'a View<V>,
1835}
1836
1837impl<V> Borrow<AppContext> for ViewContext<'_, V> {
1838 fn borrow(&self) -> &AppContext {
1839 &*self.window_cx.app
1840 }
1841}
1842
1843impl<V> BorrowMut<AppContext> for ViewContext<'_, V> {
1844 fn borrow_mut(&mut self) -> &mut AppContext {
1845 &mut *self.window_cx.app
1846 }
1847}
1848
1849impl<V> Borrow<Window> for ViewContext<'_, V> {
1850 fn borrow(&self) -> &Window {
1851 &*self.window_cx.window
1852 }
1853}
1854
1855impl<V> BorrowMut<Window> for ViewContext<'_, V> {
1856 fn borrow_mut(&mut self) -> &mut Window {
1857 &mut *self.window_cx.window
1858 }
1859}
1860
1861impl<'a, V: 'static> ViewContext<'a, V> {
1862 pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window, view: &'a View<V>) -> Self {
1863 Self {
1864 window_cx: WindowContext::new(app, window),
1865 view,
1866 }
1867 }
1868
1869 /// Get the entity_id of this view.
1870 pub fn entity_id(&self) -> EntityId {
1871 self.view.entity_id()
1872 }
1873
1874 /// Get the view pointer underlying this context.
1875 pub fn view(&self) -> &View<V> {
1876 self.view
1877 }
1878
1879 /// Get the model underlying this view.
1880 pub fn model(&self) -> &Model<V> {
1881 &self.view.model
1882 }
1883
1884 /// Access the underlying window context.
1885 pub fn window_context(&mut self) -> &mut WindowContext<'a> {
1886 &mut self.window_cx
1887 }
1888
1889 /// Sets a given callback to be run on the next frame.
1890 pub fn on_next_frame(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static)
1891 where
1892 V: 'static,
1893 {
1894 let view = self.view().clone();
1895 self.window_cx.on_next_frame(move |cx| view.update(cx, f));
1896 }
1897
1898 /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
1899 /// that are currently on the stack to be returned to the app.
1900 pub fn defer(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static) {
1901 let view = self.view().downgrade();
1902 self.window_cx.defer(move |cx| {
1903 view.update(cx, f).ok();
1904 });
1905 }
1906
1907 /// Observe another model or view for changes to its state, as tracked by [`ModelContext::notify`].
1908 pub fn observe<V2, E>(
1909 &mut self,
1910 entity: &E,
1911 mut on_notify: impl FnMut(&mut V, E, &mut ViewContext<'_, V>) + 'static,
1912 ) -> Subscription
1913 where
1914 V2: 'static,
1915 V: 'static,
1916 E: Entity<V2>,
1917 {
1918 let view = self.view().downgrade();
1919 let entity_id = entity.entity_id();
1920 let entity = entity.downgrade();
1921 let window_handle = self.window.handle;
1922 let (subscription, activate) = self.app.observers.insert(
1923 entity_id,
1924 Box::new(move |cx| {
1925 window_handle
1926 .update(cx, |_, cx| {
1927 if let Some(handle) = E::upgrade_from(&entity) {
1928 view.update(cx, |this, cx| on_notify(this, handle, cx))
1929 .is_ok()
1930 } else {
1931 false
1932 }
1933 })
1934 .unwrap_or(false)
1935 }),
1936 );
1937 self.app.defer(move |_| activate());
1938 subscription
1939 }
1940
1941 /// Subscribe to events emitted by another model or view.
1942 /// The entity to which you're subscribing must implement the [`EventEmitter`] trait.
1943 /// The callback will be invoked with a reference to the current view, a handle to the emitting entity (either a [`View`] or [`Model`]), the event, and a view context for the current view.
1944 pub fn subscribe<V2, E, Evt>(
1945 &mut self,
1946 entity: &E,
1947 mut on_event: impl FnMut(&mut V, E, &Evt, &mut ViewContext<'_, V>) + 'static,
1948 ) -> Subscription
1949 where
1950 V2: EventEmitter<Evt>,
1951 E: Entity<V2>,
1952 Evt: 'static,
1953 {
1954 let view = self.view().downgrade();
1955 let entity_id = entity.entity_id();
1956 let handle = entity.downgrade();
1957 let window_handle = self.window.handle;
1958 let (subscription, activate) = self.app.event_listeners.insert(
1959 entity_id,
1960 (
1961 TypeId::of::<Evt>(),
1962 Box::new(move |event, cx| {
1963 window_handle
1964 .update(cx, |_, cx| {
1965 if let Some(handle) = E::upgrade_from(&handle) {
1966 let event = event.downcast_ref().expect("invalid event type");
1967 view.update(cx, |this, cx| on_event(this, handle, event, cx))
1968 .is_ok()
1969 } else {
1970 false
1971 }
1972 })
1973 .unwrap_or(false)
1974 }),
1975 ),
1976 );
1977 self.app.defer(move |_| activate());
1978 subscription
1979 }
1980
1981 /// Register a callback to be invoked when the view is released.
1982 ///
1983 /// The callback receives a handle to the view's window. This handle may be
1984 /// invalid, if the window was closed before the view was released.
1985 pub fn on_release(
1986 &mut self,
1987 on_release: impl FnOnce(&mut V, AnyWindowHandle, &mut AppContext) + 'static,
1988 ) -> Subscription {
1989 let window_handle = self.window.handle;
1990 let (subscription, activate) = self.app.release_listeners.insert(
1991 self.view.model.entity_id,
1992 Box::new(move |this, cx| {
1993 let this = this.downcast_mut().expect("invalid entity type");
1994 on_release(this, window_handle, cx)
1995 }),
1996 );
1997 activate();
1998 subscription
1999 }
2000
2001 /// Register a callback to be invoked when the given Model or View is released.
2002 pub fn observe_release<V2, E>(
2003 &mut self,
2004 entity: &E,
2005 mut on_release: impl FnMut(&mut V, &mut V2, &mut ViewContext<'_, V>) + 'static,
2006 ) -> Subscription
2007 where
2008 V: 'static,
2009 V2: 'static,
2010 E: Entity<V2>,
2011 {
2012 let view = self.view().downgrade();
2013 let entity_id = entity.entity_id();
2014 let window_handle = self.window.handle;
2015 let (subscription, activate) = self.app.release_listeners.insert(
2016 entity_id,
2017 Box::new(move |entity, cx| {
2018 let entity = entity.downcast_mut().expect("invalid entity type");
2019 let _ = window_handle.update(cx, |_, cx| {
2020 view.update(cx, |this, cx| on_release(this, entity, cx))
2021 });
2022 }),
2023 );
2024 activate();
2025 subscription
2026 }
2027
2028 /// Indicate that this view has changed, which will invoke any observers and also mark the window as dirty.
2029 /// If this view or any of its ancestors are *cached*, notifying it will cause it or its ancestors to be redrawn.
2030 pub fn notify(&mut self) {
2031 for view_id in self
2032 .window
2033 .rendered_frame
2034 .dispatch_tree
2035 .view_path(self.view.entity_id())
2036 .into_iter()
2037 .rev()
2038 {
2039 if !self.window.dirty_views.insert(view_id) {
2040 break;
2041 }
2042 }
2043
2044 if !self.window.drawing {
2045 self.window_cx.window.dirty = true;
2046 self.window_cx.app.push_effect(Effect::Notify {
2047 emitter: self.view.model.entity_id,
2048 });
2049 }
2050 }
2051
2052 /// Register a callback to be invoked when the window is resized.
2053 pub fn observe_window_bounds(
2054 &mut self,
2055 mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2056 ) -> Subscription {
2057 let view = self.view.downgrade();
2058 let (subscription, activate) = self.window.bounds_observers.insert(
2059 (),
2060 Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
2061 );
2062 activate();
2063 subscription
2064 }
2065
2066 /// Register a callback to be invoked when the window is activated or deactivated.
2067 pub fn observe_window_activation(
2068 &mut self,
2069 mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2070 ) -> Subscription {
2071 let view = self.view.downgrade();
2072 let (subscription, activate) = self.window.activation_observers.insert(
2073 (),
2074 Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
2075 );
2076 activate();
2077 subscription
2078 }
2079
2080 /// Register a listener to be called when the given focus handle receives focus.
2081 /// Returns a subscription and persists until the subscription is dropped.
2082 pub fn on_focus(
2083 &mut self,
2084 handle: &FocusHandle,
2085 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2086 ) -> Subscription {
2087 let view = self.view.downgrade();
2088 let focus_id = handle.id;
2089 let (subscription, activate) = self.window.focus_listeners.insert(
2090 (),
2091 Box::new(move |event, cx| {
2092 view.update(cx, |view, cx| {
2093 if event.previous_focus_path.last() != Some(&focus_id)
2094 && event.current_focus_path.last() == Some(&focus_id)
2095 {
2096 listener(view, cx)
2097 }
2098 })
2099 .is_ok()
2100 }),
2101 );
2102 self.app.defer(move |_| activate());
2103 subscription
2104 }
2105
2106 /// Register a listener to be called when the given focus handle or one of its descendants receives focus.
2107 /// Returns a subscription and persists until the subscription is dropped.
2108 pub fn on_focus_in(
2109 &mut self,
2110 handle: &FocusHandle,
2111 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2112 ) -> Subscription {
2113 let view = self.view.downgrade();
2114 let focus_id = handle.id;
2115 let (subscription, activate) = self.window.focus_listeners.insert(
2116 (),
2117 Box::new(move |event, cx| {
2118 view.update(cx, |view, cx| {
2119 if !event.previous_focus_path.contains(&focus_id)
2120 && event.current_focus_path.contains(&focus_id)
2121 {
2122 listener(view, cx)
2123 }
2124 })
2125 .is_ok()
2126 }),
2127 );
2128 self.app.defer(move |_| activate());
2129 subscription
2130 }
2131
2132 /// Register a listener to be called when the given focus handle loses focus.
2133 /// Returns a subscription and persists until the subscription is dropped.
2134 pub fn on_blur(
2135 &mut self,
2136 handle: &FocusHandle,
2137 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2138 ) -> Subscription {
2139 let view = self.view.downgrade();
2140 let focus_id = handle.id;
2141 let (subscription, activate) = self.window.focus_listeners.insert(
2142 (),
2143 Box::new(move |event, cx| {
2144 view.update(cx, |view, cx| {
2145 if event.previous_focus_path.last() == Some(&focus_id)
2146 && event.current_focus_path.last() != Some(&focus_id)
2147 {
2148 listener(view, cx)
2149 }
2150 })
2151 .is_ok()
2152 }),
2153 );
2154 self.app.defer(move |_| activate());
2155 subscription
2156 }
2157
2158 /// Register a listener to be called when nothing in the window has focus.
2159 /// This typically happens when the node that was focused is removed from the tree,
2160 /// and this callback lets you chose a default place to restore the users focus.
2161 /// Returns a subscription and persists until the subscription is dropped.
2162 pub fn on_focus_lost(
2163 &mut self,
2164 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2165 ) -> Subscription {
2166 let view = self.view.downgrade();
2167 let (subscription, activate) = self.window.focus_lost_listeners.insert(
2168 (),
2169 Box::new(move |cx| view.update(cx, |view, cx| listener(view, cx)).is_ok()),
2170 );
2171 activate();
2172 subscription
2173 }
2174
2175 /// Register a listener to be called when the given focus handle or one of its descendants loses focus.
2176 /// Returns a subscription and persists until the subscription is dropped.
2177 pub fn on_focus_out(
2178 &mut self,
2179 handle: &FocusHandle,
2180 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2181 ) -> Subscription {
2182 let view = self.view.downgrade();
2183 let focus_id = handle.id;
2184 let (subscription, activate) = self.window.focus_listeners.insert(
2185 (),
2186 Box::new(move |event, cx| {
2187 view.update(cx, |view, cx| {
2188 if event.previous_focus_path.contains(&focus_id)
2189 && !event.current_focus_path.contains(&focus_id)
2190 {
2191 listener(view, cx)
2192 }
2193 })
2194 .is_ok()
2195 }),
2196 );
2197 self.app.defer(move |_| activate());
2198 subscription
2199 }
2200
2201 /// Schedule a future to be run asynchronously.
2202 /// The given callback is invoked with a [`WeakView<V>`] to avoid leaking the view for a long-running process.
2203 /// It's also given an [`AsyncWindowContext`], which can be used to access the state of the view across await points.
2204 /// The returned future will be polled on the main thread.
2205 pub fn spawn<Fut, R>(
2206 &mut self,
2207 f: impl FnOnce(WeakView<V>, AsyncWindowContext) -> Fut,
2208 ) -> Task<R>
2209 where
2210 R: 'static,
2211 Fut: Future<Output = R> + 'static,
2212 {
2213 let view = self.view().downgrade();
2214 self.window_cx.spawn(|cx| f(view, cx))
2215 }
2216
2217 /// Updates the global state of the given type.
2218 pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
2219 where
2220 G: 'static,
2221 {
2222 let mut global = self.app.lease_global::<G>();
2223 let result = f(&mut global, self);
2224 self.app.end_global_lease(global);
2225 result
2226 }
2227
2228 /// Register a callback to be invoked when the given global state changes.
2229 pub fn observe_global<G: 'static>(
2230 &mut self,
2231 mut f: impl FnMut(&mut V, &mut ViewContext<'_, V>) + 'static,
2232 ) -> Subscription {
2233 let window_handle = self.window.handle;
2234 let view = self.view().downgrade();
2235 let (subscription, activate) = self.global_observers.insert(
2236 TypeId::of::<G>(),
2237 Box::new(move |cx| {
2238 window_handle
2239 .update(cx, |_, cx| view.update(cx, |view, cx| f(view, cx)).is_ok())
2240 .unwrap_or(false)
2241 }),
2242 );
2243 self.app.defer(move |_| activate());
2244 subscription
2245 }
2246
2247 /// Register a callback to be invoked when the given Action type is dispatched to the window.
2248 pub fn on_action(
2249 &mut self,
2250 action_type: TypeId,
2251 listener: impl Fn(&mut V, &dyn Any, DispatchPhase, &mut ViewContext<V>) + 'static,
2252 ) {
2253 let handle = self.view().clone();
2254 self.window_cx
2255 .on_action(action_type, move |action, phase, cx| {
2256 handle.update(cx, |view, cx| {
2257 listener(view, action, phase, cx);
2258 })
2259 });
2260 }
2261
2262 /// Emit an event to be handled any other views that have subscribed via [ViewContext::subscribe].
2263 pub fn emit<Evt>(&mut self, event: Evt)
2264 where
2265 Evt: 'static,
2266 V: EventEmitter<Evt>,
2267 {
2268 let emitter = self.view.model.entity_id;
2269 self.app.push_effect(Effect::Emit {
2270 emitter,
2271 event_type: TypeId::of::<Evt>(),
2272 event: Box::new(event),
2273 });
2274 }
2275
2276 /// Move focus to the current view, assuming it implements [`FocusableView`].
2277 pub fn focus_self(&mut self)
2278 where
2279 V: FocusableView,
2280 {
2281 self.defer(|view, cx| view.focus_handle(cx).focus(cx))
2282 }
2283
2284 /// Convenience method for accessing view state in an event callback.
2285 ///
2286 /// Many GPUI callbacks take the form of `Fn(&E, &mut WindowContext)`,
2287 /// but it's often useful to be able to access view state in these
2288 /// callbacks. This method provides a convenient way to do so.
2289 pub fn listener<E>(
2290 &self,
2291 f: impl Fn(&mut V, &E, &mut ViewContext<V>) + 'static,
2292 ) -> impl Fn(&E, &mut WindowContext) + 'static {
2293 let view = self.view().downgrade();
2294 move |e: &E, cx: &mut WindowContext| {
2295 view.update(cx, |view, cx| f(view, e, cx)).ok();
2296 }
2297 }
2298}
2299
2300impl<V> Context for ViewContext<'_, V> {
2301 type Result<U> = U;
2302
2303 fn new_model<T: 'static>(
2304 &mut self,
2305 build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
2306 ) -> Model<T> {
2307 self.window_cx.new_model(build_model)
2308 }
2309
2310 fn update_model<T: 'static, R>(
2311 &mut self,
2312 model: &Model<T>,
2313 update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
2314 ) -> R {
2315 self.window_cx.update_model(model, update)
2316 }
2317
2318 fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
2319 where
2320 F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
2321 {
2322 self.window_cx.update_window(window, update)
2323 }
2324
2325 fn read_model<T, R>(
2326 &self,
2327 handle: &Model<T>,
2328 read: impl FnOnce(&T, &AppContext) -> R,
2329 ) -> Self::Result<R>
2330 where
2331 T: 'static,
2332 {
2333 self.window_cx.read_model(handle, read)
2334 }
2335
2336 fn read_window<T, R>(
2337 &self,
2338 window: &WindowHandle<T>,
2339 read: impl FnOnce(View<T>, &AppContext) -> R,
2340 ) -> Result<R>
2341 where
2342 T: 'static,
2343 {
2344 self.window_cx.read_window(window, read)
2345 }
2346}
2347
2348impl<V: 'static> VisualContext for ViewContext<'_, V> {
2349 fn new_view<W: Render + 'static>(
2350 &mut self,
2351 build_view_state: impl FnOnce(&mut ViewContext<'_, W>) -> W,
2352 ) -> Self::Result<View<W>> {
2353 self.window_cx.new_view(build_view_state)
2354 }
2355
2356 fn update_view<V2: 'static, R>(
2357 &mut self,
2358 view: &View<V2>,
2359 update: impl FnOnce(&mut V2, &mut ViewContext<'_, V2>) -> R,
2360 ) -> Self::Result<R> {
2361 self.window_cx.update_view(view, update)
2362 }
2363
2364 fn replace_root_view<W>(
2365 &mut self,
2366 build_view: impl FnOnce(&mut ViewContext<'_, W>) -> W,
2367 ) -> Self::Result<View<W>>
2368 where
2369 W: 'static + Render,
2370 {
2371 self.window_cx.replace_root_view(build_view)
2372 }
2373
2374 fn focus_view<W: FocusableView>(&mut self, view: &View<W>) -> Self::Result<()> {
2375 self.window_cx.focus_view(view)
2376 }
2377
2378 fn dismiss_view<W: ManagedView>(&mut self, view: &View<W>) -> Self::Result<()> {
2379 self.window_cx.dismiss_view(view)
2380 }
2381}
2382
2383impl<'a, V> std::ops::Deref for ViewContext<'a, V> {
2384 type Target = WindowContext<'a>;
2385
2386 fn deref(&self) -> &Self::Target {
2387 &self.window_cx
2388 }
2389}
2390
2391impl<'a, V> std::ops::DerefMut for ViewContext<'a, V> {
2392 fn deref_mut(&mut self) -> &mut Self::Target {
2393 &mut self.window_cx
2394 }
2395}
2396
2397// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
2398slotmap::new_key_type! {
2399 /// A unique identifier for a window.
2400 pub struct WindowId;
2401}
2402
2403impl WindowId {
2404 /// Converts this window ID to a `u64`.
2405 pub fn as_u64(&self) -> u64 {
2406 self.0.as_ffi()
2407 }
2408}
2409
2410/// A handle to a window with a specific root view type.
2411/// Note that this does not keep the window alive on its own.
2412#[derive(Deref, DerefMut)]
2413pub struct WindowHandle<V> {
2414 #[deref]
2415 #[deref_mut]
2416 pub(crate) any_handle: AnyWindowHandle,
2417 state_type: PhantomData<V>,
2418}
2419
2420impl<V: 'static + Render> WindowHandle<V> {
2421 /// Creates a new handle from a window ID.
2422 /// This does not check if the root type of the window is `V`.
2423 pub fn new(id: WindowId) -> Self {
2424 WindowHandle {
2425 any_handle: AnyWindowHandle {
2426 id,
2427 state_type: TypeId::of::<V>(),
2428 },
2429 state_type: PhantomData,
2430 }
2431 }
2432
2433 /// Get the root view out of this window.
2434 ///
2435 /// This will fail if the window is closed or if the root view's type does not match `V`.
2436 pub fn root<C>(&self, cx: &mut C) -> Result<View<V>>
2437 where
2438 C: Context,
2439 {
2440 Flatten::flatten(cx.update_window(self.any_handle, |root_view, _| {
2441 root_view
2442 .downcast::<V>()
2443 .map_err(|_| anyhow!("the type of the window's root view has changed"))
2444 }))
2445 }
2446
2447 /// Updates the root view of this window.
2448 ///
2449 /// This will fail if the window has been closed or if the root view's type does not match
2450 pub fn update<C, R>(
2451 &self,
2452 cx: &mut C,
2453 update: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
2454 ) -> Result<R>
2455 where
2456 C: Context,
2457 {
2458 cx.update_window(self.any_handle, |root_view, cx| {
2459 let view = root_view
2460 .downcast::<V>()
2461 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
2462 Ok(cx.update_view(&view, update))
2463 })?
2464 }
2465
2466 /// Read the root view out of this window.
2467 ///
2468 /// This will fail if the window is closed or if the root view's type does not match `V`.
2469 pub fn read<'a>(&self, cx: &'a AppContext) -> Result<&'a V> {
2470 let x = cx
2471 .windows
2472 .get(self.id)
2473 .and_then(|window| {
2474 window
2475 .as_ref()
2476 .and_then(|window| window.root_view.clone())
2477 .map(|root_view| root_view.downcast::<V>())
2478 })
2479 .ok_or_else(|| anyhow!("window not found"))?
2480 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
2481
2482 Ok(x.read(cx))
2483 }
2484
2485 /// Read the root view out of this window, with a callback
2486 ///
2487 /// This will fail if the window is closed or if the root view's type does not match `V`.
2488 pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &AppContext) -> R) -> Result<R>
2489 where
2490 C: Context,
2491 {
2492 cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
2493 }
2494
2495 /// Read the root view pointer off of this window.
2496 ///
2497 /// This will fail if the window is closed or if the root view's type does not match `V`.
2498 pub fn root_view<C>(&self, cx: &C) -> Result<View<V>>
2499 where
2500 C: Context,
2501 {
2502 cx.read_window(self, |root_view, _cx| root_view.clone())
2503 }
2504
2505 /// Check if this window is 'active'.
2506 ///
2507 /// Will return `None` if the window is closed.
2508 pub fn is_active(&self, cx: &AppContext) -> Option<bool> {
2509 cx.windows
2510 .get(self.id)
2511 .and_then(|window| window.as_ref().map(|window| window.active))
2512 }
2513}
2514
2515impl<V> Copy for WindowHandle<V> {}
2516
2517impl<V> Clone for WindowHandle<V> {
2518 fn clone(&self) -> Self {
2519 *self
2520 }
2521}
2522
2523impl<V> PartialEq for WindowHandle<V> {
2524 fn eq(&self, other: &Self) -> bool {
2525 self.any_handle == other.any_handle
2526 }
2527}
2528
2529impl<V> Eq for WindowHandle<V> {}
2530
2531impl<V> Hash for WindowHandle<V> {
2532 fn hash<H: Hasher>(&self, state: &mut H) {
2533 self.any_handle.hash(state);
2534 }
2535}
2536
2537impl<V: 'static> From<WindowHandle<V>> for AnyWindowHandle {
2538 fn from(val: WindowHandle<V>) -> Self {
2539 val.any_handle
2540 }
2541}
2542
2543/// A handle to a window with any root view type, which can be downcast to a window with a specific root view type.
2544#[derive(Copy, Clone, PartialEq, Eq, Hash)]
2545pub struct AnyWindowHandle {
2546 pub(crate) id: WindowId,
2547 state_type: TypeId,
2548}
2549
2550impl AnyWindowHandle {
2551 /// Get the ID of this window.
2552 pub fn window_id(&self) -> WindowId {
2553 self.id
2554 }
2555
2556 /// Attempt to convert this handle to a window handle with a specific root view type.
2557 /// If the types do not match, this will return `None`.
2558 pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
2559 if TypeId::of::<T>() == self.state_type {
2560 Some(WindowHandle {
2561 any_handle: *self,
2562 state_type: PhantomData,
2563 })
2564 } else {
2565 None
2566 }
2567 }
2568
2569 /// Updates the state of the root view of this window.
2570 ///
2571 /// This will fail if the window has been closed.
2572 pub fn update<C, R>(
2573 self,
2574 cx: &mut C,
2575 update: impl FnOnce(AnyView, &mut WindowContext<'_>) -> R,
2576 ) -> Result<R>
2577 where
2578 C: Context,
2579 {
2580 cx.update_window(self, update)
2581 }
2582
2583 /// Read the state of the root view of this window.
2584 ///
2585 /// This will fail if the window has been closed.
2586 pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(View<T>, &AppContext) -> R) -> Result<R>
2587 where
2588 C: Context,
2589 T: 'static,
2590 {
2591 let view = self
2592 .downcast::<T>()
2593 .context("the type of the window's root view has changed")?;
2594
2595 cx.read_window(&view, read)
2596 }
2597}
2598
2599/// An identifier for an [`Element`](crate::Element).
2600///
2601/// Can be constructed with a string, a number, or both, as well
2602/// as other internal representations.
2603#[derive(Clone, Debug, Eq, PartialEq, Hash)]
2604pub enum ElementId {
2605 /// The ID of a View element
2606 View(EntityId),
2607 /// An integer ID.
2608 Integer(usize),
2609 /// A string based ID.
2610 Name(SharedString),
2611 /// An ID that's equated with a focus handle.
2612 FocusHandle(FocusId),
2613 /// A combination of a name and an integer.
2614 NamedInteger(SharedString, usize),
2615}
2616
2617impl Display for ElementId {
2618 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2619 match self {
2620 ElementId::View(entity_id) => write!(f, "view-{}", entity_id)?,
2621 ElementId::Integer(ix) => write!(f, "{}", ix)?,
2622 ElementId::Name(name) => write!(f, "{}", name)?,
2623 ElementId::FocusHandle(__) => write!(f, "FocusHandle")?,
2624 ElementId::NamedInteger(s, i) => write!(f, "{}-{}", s, i)?,
2625 }
2626
2627 Ok(())
2628 }
2629}
2630
2631impl ElementId {
2632 pub(crate) fn from_entity_id(entity_id: EntityId) -> Self {
2633 ElementId::View(entity_id)
2634 }
2635}
2636
2637impl TryInto<SharedString> for ElementId {
2638 type Error = anyhow::Error;
2639
2640 fn try_into(self) -> anyhow::Result<SharedString> {
2641 if let ElementId::Name(name) = self {
2642 Ok(name)
2643 } else {
2644 Err(anyhow!("element id is not string"))
2645 }
2646 }
2647}
2648
2649impl From<usize> for ElementId {
2650 fn from(id: usize) -> Self {
2651 ElementId::Integer(id)
2652 }
2653}
2654
2655impl From<i32> for ElementId {
2656 fn from(id: i32) -> Self {
2657 Self::Integer(id as usize)
2658 }
2659}
2660
2661impl From<SharedString> for ElementId {
2662 fn from(name: SharedString) -> Self {
2663 ElementId::Name(name)
2664 }
2665}
2666
2667impl From<&'static str> for ElementId {
2668 fn from(name: &'static str) -> Self {
2669 ElementId::Name(name.into())
2670 }
2671}
2672
2673impl<'a> From<&'a FocusHandle> for ElementId {
2674 fn from(handle: &'a FocusHandle) -> Self {
2675 ElementId::FocusHandle(handle.id)
2676 }
2677}
2678
2679impl From<(&'static str, EntityId)> for ElementId {
2680 fn from((name, id): (&'static str, EntityId)) -> Self {
2681 ElementId::NamedInteger(name.into(), id.as_u64() as usize)
2682 }
2683}
2684
2685impl From<(&'static str, usize)> for ElementId {
2686 fn from((name, id): (&'static str, usize)) -> Self {
2687 ElementId::NamedInteger(name.into(), id)
2688 }
2689}
2690
2691impl From<(&'static str, u64)> for ElementId {
2692 fn from((name, id): (&'static str, u64)) -> Self {
2693 ElementId::NamedInteger(name.into(), id as usize)
2694 }
2695}
2696
2697/// A rectangle to be rendered in the window at the given position and size.
2698/// Passed as an argument [`WindowContext::paint_quad`].
2699#[derive(Clone)]
2700pub struct PaintQuad {
2701 bounds: Bounds<Pixels>,
2702 corner_radii: Corners<Pixels>,
2703 background: Hsla,
2704 border_widths: Edges<Pixels>,
2705 border_color: Hsla,
2706}
2707
2708impl PaintQuad {
2709 /// Sets the corner radii of the quad.
2710 pub fn corner_radii(self, corner_radii: impl Into<Corners<Pixels>>) -> Self {
2711 PaintQuad {
2712 corner_radii: corner_radii.into(),
2713 ..self
2714 }
2715 }
2716
2717 /// Sets the border widths of the quad.
2718 pub fn border_widths(self, border_widths: impl Into<Edges<Pixels>>) -> Self {
2719 PaintQuad {
2720 border_widths: border_widths.into(),
2721 ..self
2722 }
2723 }
2724
2725 /// Sets the border color of the quad.
2726 pub fn border_color(self, border_color: impl Into<Hsla>) -> Self {
2727 PaintQuad {
2728 border_color: border_color.into(),
2729 ..self
2730 }
2731 }
2732
2733 /// Sets the background color of the quad.
2734 pub fn background(self, background: impl Into<Hsla>) -> Self {
2735 PaintQuad {
2736 background: background.into(),
2737 ..self
2738 }
2739 }
2740}
2741
2742/// Creates a quad with the given parameters.
2743pub fn quad(
2744 bounds: Bounds<Pixels>,
2745 corner_radii: impl Into<Corners<Pixels>>,
2746 background: impl Into<Hsla>,
2747 border_widths: impl Into<Edges<Pixels>>,
2748 border_color: impl Into<Hsla>,
2749) -> PaintQuad {
2750 PaintQuad {
2751 bounds,
2752 corner_radii: corner_radii.into(),
2753 background: background.into(),
2754 border_widths: border_widths.into(),
2755 border_color: border_color.into(),
2756 }
2757}
2758
2759/// Creates a filled quad with the given bounds and background color.
2760pub fn fill(bounds: impl Into<Bounds<Pixels>>, background: impl Into<Hsla>) -> PaintQuad {
2761 PaintQuad {
2762 bounds: bounds.into(),
2763 corner_radii: (0.).into(),
2764 background: background.into(),
2765 border_widths: (0.).into(),
2766 border_color: transparent_black(),
2767 }
2768}
2769
2770/// Creates a rectangle outline with the given bounds, border color, and a 1px border width
2771pub fn outline(bounds: impl Into<Bounds<Pixels>>, border_color: impl Into<Hsla>) -> PaintQuad {
2772 PaintQuad {
2773 bounds: bounds.into(),
2774 corner_radii: (0.).into(),
2775 background: transparent_black(),
2776 border_widths: (1.).into(),
2777 border_color: border_color.into(),
2778 }
2779}