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