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