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