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