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