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