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