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