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