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