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