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