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