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