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