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