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 self.window.drawing = false;
1433 ELEMENT_ARENA.with_borrow_mut(|element_arena| element_arena.clear());
1434
1435 if previous_focus_path != current_focus_path
1436 || previous_window_active != current_window_active
1437 {
1438 if !previous_focus_path.is_empty() && current_focus_path.is_empty() {
1439 self.window
1440 .focus_lost_listeners
1441 .clone()
1442 .retain(&(), |listener| listener(self));
1443 }
1444
1445 let event = FocusEvent {
1446 previous_focus_path: if previous_window_active {
1447 previous_focus_path
1448 } else {
1449 Default::default()
1450 },
1451 current_focus_path: if current_window_active {
1452 current_focus_path
1453 } else {
1454 Default::default()
1455 },
1456 };
1457 self.window
1458 .focus_listeners
1459 .clone()
1460 .retain(&(), |listener| listener(&event, self));
1461 }
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 // todo!("Should we record that the mouse is outside of the window somehow? Or are these global pixels?")
1493 self.window.modifiers = mouse_exited.modifiers;
1494
1495 InputEvent::MouseExited(mouse_exited)
1496 }
1497 InputEvent::ModifiersChanged(modifiers_changed) => {
1498 self.window.modifiers = modifiers_changed.modifiers;
1499 InputEvent::ModifiersChanged(modifiers_changed)
1500 }
1501 InputEvent::ScrollWheel(scroll_wheel) => {
1502 self.window.mouse_position = scroll_wheel.position;
1503 self.window.modifiers = scroll_wheel.modifiers;
1504 InputEvent::ScrollWheel(scroll_wheel)
1505 }
1506 // Translate dragging and dropping of external files from the operating system
1507 // to internal drag and drop events.
1508 InputEvent::FileDrop(file_drop) => match file_drop {
1509 FileDropEvent::Entered { position, paths } => {
1510 self.window.mouse_position = position;
1511 if self.active_drag.is_none() {
1512 self.active_drag = Some(AnyDrag {
1513 value: Box::new(paths.clone()),
1514 view: self.new_view(|_| paths).into(),
1515 cursor_offset: position,
1516 });
1517 }
1518 InputEvent::MouseMove(MouseMoveEvent {
1519 position,
1520 pressed_button: Some(MouseButton::Left),
1521 modifiers: Modifiers::default(),
1522 })
1523 }
1524 FileDropEvent::Pending { position } => {
1525 self.window.mouse_position = position;
1526 InputEvent::MouseMove(MouseMoveEvent {
1527 position,
1528 pressed_button: Some(MouseButton::Left),
1529 modifiers: Modifiers::default(),
1530 })
1531 }
1532 FileDropEvent::Submit { position } => {
1533 self.activate(true);
1534 self.window.mouse_position = position;
1535 InputEvent::MouseUp(MouseUpEvent {
1536 button: MouseButton::Left,
1537 position,
1538 modifiers: Modifiers::default(),
1539 click_count: 1,
1540 })
1541 }
1542 FileDropEvent::Exited => InputEvent::MouseUp(MouseUpEvent {
1543 button: MouseButton::Left,
1544 position: Point::default(),
1545 modifiers: Modifiers::default(),
1546 click_count: 1,
1547 }),
1548 },
1549 InputEvent::KeyDown(_) | InputEvent::KeyUp(_) => event,
1550 };
1551
1552 if let Some(any_mouse_event) = event.mouse_event() {
1553 self.dispatch_mouse_event(any_mouse_event);
1554 } else if let Some(any_key_event) = event.keyboard_event() {
1555 self.dispatch_key_event(any_key_event);
1556 }
1557
1558 !self.app.propagate_event
1559 }
1560
1561 fn dispatch_mouse_event(&mut self, event: &dyn Any) {
1562 if let Some(mut handlers) = self
1563 .window
1564 .rendered_frame
1565 .mouse_listeners
1566 .remove(&event.type_id())
1567 {
1568 // Because handlers may add other handlers, we sort every time.
1569 handlers.sort_by(|(a, _), (b, _)| a.cmp(b));
1570
1571 // Capture phase, events bubble from back to front. Handlers for this phase are used for
1572 // special purposes, such as detecting events outside of a given Bounds.
1573 for (_, handler) in &mut handlers {
1574 handler(event, DispatchPhase::Capture, self);
1575 if !self.app.propagate_event {
1576 break;
1577 }
1578 }
1579
1580 // Bubble phase, where most normal handlers do their work.
1581 if self.app.propagate_event {
1582 for (_, handler) in handlers.iter_mut().rev() {
1583 handler(event, DispatchPhase::Bubble, self);
1584 if !self.app.propagate_event {
1585 break;
1586 }
1587 }
1588 }
1589
1590 self.window
1591 .rendered_frame
1592 .mouse_listeners
1593 .insert(event.type_id(), handlers);
1594 }
1595
1596 if self.app.propagate_event && self.has_active_drag() {
1597 if event.is::<MouseMoveEvent>() {
1598 // If this was a mouse move event, redraw the window so that the
1599 // active drag can follow the mouse cursor.
1600 self.notify();
1601 } else if event.is::<MouseUpEvent>() {
1602 // If this was a mouse up event, cancel the active drag and redraw
1603 // the window.
1604 self.active_drag = None;
1605 self.notify();
1606 }
1607 }
1608 }
1609
1610 fn dispatch_key_event(&mut self, event: &dyn Any) {
1611 let node_id = self
1612 .window
1613 .focus
1614 .and_then(|focus_id| {
1615 self.window
1616 .rendered_frame
1617 .dispatch_tree
1618 .focusable_node_id(focus_id)
1619 })
1620 .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
1621
1622 let dispatch_path = self
1623 .window
1624 .rendered_frame
1625 .dispatch_tree
1626 .dispatch_path(node_id);
1627
1628 let mut actions: Vec<Box<dyn Action>> = Vec::new();
1629
1630 let mut context_stack: SmallVec<[KeyContext; 16]> = SmallVec::new();
1631 for node_id in &dispatch_path {
1632 let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1633
1634 if let Some(context) = node.context.clone() {
1635 context_stack.push(context);
1636 }
1637 }
1638
1639 for node_id in dispatch_path.iter().rev() {
1640 // Match keystrokes
1641 let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1642 if node.context.is_some() {
1643 if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
1644 let mut new_actions = self
1645 .window
1646 .rendered_frame
1647 .dispatch_tree
1648 .dispatch_key(&key_down_event.keystroke, &context_stack);
1649 actions.append(&mut new_actions);
1650 }
1651
1652 context_stack.pop();
1653 }
1654 }
1655
1656 if !actions.is_empty() {
1657 self.clear_pending_keystrokes();
1658 }
1659
1660 self.propagate_event = true;
1661 for action in actions {
1662 self.dispatch_action_on_node(node_id, action.boxed_clone());
1663 if !self.propagate_event {
1664 self.dispatch_keystroke_observers(event, Some(action));
1665 return;
1666 }
1667 }
1668
1669 // Capture phase
1670 for node_id in &dispatch_path {
1671 let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1672
1673 for key_listener in node.key_listeners.clone() {
1674 key_listener(event, DispatchPhase::Capture, self);
1675 if !self.propagate_event {
1676 return;
1677 }
1678 }
1679 }
1680
1681 // Bubble phase
1682 for node_id in dispatch_path.iter().rev() {
1683 // Handle low level key events
1684 let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1685 for key_listener in node.key_listeners.clone() {
1686 key_listener(event, DispatchPhase::Bubble, self);
1687 if !self.propagate_event {
1688 return;
1689 }
1690 }
1691 }
1692
1693 self.dispatch_keystroke_observers(event, None);
1694 }
1695
1696 /// Determine whether a potential multi-stroke key binding is in progress on this window.
1697 pub fn has_pending_keystrokes(&self) -> bool {
1698 self.window
1699 .rendered_frame
1700 .dispatch_tree
1701 .has_pending_keystrokes()
1702 }
1703
1704 fn dispatch_action_on_node(&mut self, node_id: DispatchNodeId, action: Box<dyn Action>) {
1705 let dispatch_path = self
1706 .window
1707 .rendered_frame
1708 .dispatch_tree
1709 .dispatch_path(node_id);
1710
1711 // Capture phase
1712 for node_id in &dispatch_path {
1713 let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1714 for DispatchActionListener {
1715 action_type,
1716 listener,
1717 } in node.action_listeners.clone()
1718 {
1719 let any_action = action.as_any();
1720 if action_type == any_action.type_id() {
1721 listener(any_action, DispatchPhase::Capture, self);
1722 if !self.propagate_event {
1723 return;
1724 }
1725 }
1726 }
1727 }
1728 // Bubble phase
1729 for node_id in dispatch_path.iter().rev() {
1730 let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1731 for DispatchActionListener {
1732 action_type,
1733 listener,
1734 } in node.action_listeners.clone()
1735 {
1736 let any_action = action.as_any();
1737 if action_type == any_action.type_id() {
1738 self.propagate_event = false; // Actions stop propagation by default during the bubble phase
1739 listener(any_action, DispatchPhase::Bubble, self);
1740 if !self.propagate_event {
1741 return;
1742 }
1743 }
1744 }
1745 }
1746 }
1747
1748 /// Register the given handler to be invoked whenever the global of the given type
1749 /// is updated.
1750 pub fn observe_global<G: 'static>(
1751 &mut self,
1752 f: impl Fn(&mut WindowContext<'_>) + 'static,
1753 ) -> Subscription {
1754 let window_handle = self.window.handle;
1755 let (subscription, activate) = self.global_observers.insert(
1756 TypeId::of::<G>(),
1757 Box::new(move |cx| window_handle.update(cx, |_, cx| f(cx)).is_ok()),
1758 );
1759 self.app.defer(move |_| activate());
1760 subscription
1761 }
1762
1763 /// Focus the current window and bring it to the foreground at the platform level.
1764 pub fn activate_window(&self) {
1765 self.window.platform_window.activate();
1766 }
1767
1768 /// Minimize the current window at the platform level.
1769 pub fn minimize_window(&self) {
1770 self.window.platform_window.minimize();
1771 }
1772
1773 /// Toggle full screen status on the current window at the platform level.
1774 pub fn toggle_full_screen(&self) {
1775 self.window.platform_window.toggle_full_screen();
1776 }
1777
1778 /// Present a platform dialog.
1779 /// The provided message will be presented, along with buttons for each answer.
1780 /// When a button is clicked, the returned Receiver will receive the index of the clicked button.
1781 pub fn prompt(
1782 &self,
1783 level: PromptLevel,
1784 message: &str,
1785 answers: &[&str],
1786 ) -> oneshot::Receiver<usize> {
1787 self.window.platform_window.prompt(level, message, answers)
1788 }
1789
1790 /// Returns all available actions for the focused element.
1791 pub fn available_actions(&self) -> Vec<Box<dyn Action>> {
1792 let node_id = self
1793 .window
1794 .focus
1795 .and_then(|focus_id| {
1796 self.window
1797 .rendered_frame
1798 .dispatch_tree
1799 .focusable_node_id(focus_id)
1800 })
1801 .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
1802
1803 self.window
1804 .rendered_frame
1805 .dispatch_tree
1806 .available_actions(node_id)
1807 }
1808
1809 /// Returns key bindings that invoke the given action on the currently focused element.
1810 pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
1811 self.window
1812 .rendered_frame
1813 .dispatch_tree
1814 .bindings_for_action(
1815 action,
1816 &self.window.rendered_frame.dispatch_tree.context_stack,
1817 )
1818 }
1819
1820 /// Returns any bindings that would invoke the given action on the given focus handle if it were focused.
1821 pub fn bindings_for_action_in(
1822 &self,
1823 action: &dyn Action,
1824 focus_handle: &FocusHandle,
1825 ) -> Vec<KeyBinding> {
1826 let dispatch_tree = &self.window.rendered_frame.dispatch_tree;
1827
1828 let Some(node_id) = dispatch_tree.focusable_node_id(focus_handle.id) else {
1829 return vec![];
1830 };
1831 let context_stack = dispatch_tree
1832 .dispatch_path(node_id)
1833 .into_iter()
1834 .filter_map(|node_id| dispatch_tree.node(node_id).context.clone())
1835 .collect();
1836 dispatch_tree.bindings_for_action(action, &context_stack)
1837 }
1838
1839 /// Returns a generic event listener that invokes the given listener with the view and context associated with the given view handle.
1840 pub fn listener_for<V: Render, E>(
1841 &self,
1842 view: &View<V>,
1843 f: impl Fn(&mut V, &E, &mut ViewContext<V>) + 'static,
1844 ) -> impl Fn(&E, &mut WindowContext) + 'static {
1845 let view = view.downgrade();
1846 move |e: &E, cx: &mut WindowContext| {
1847 view.update(cx, |view, cx| f(view, e, cx)).ok();
1848 }
1849 }
1850
1851 /// Returns a generic handler that invokes the given handler with the view and context associated with the given view handle.
1852 pub fn handler_for<V: Render>(
1853 &self,
1854 view: &View<V>,
1855 f: impl Fn(&mut V, &mut ViewContext<V>) + 'static,
1856 ) -> impl Fn(&mut WindowContext) {
1857 let view = view.downgrade();
1858 move |cx: &mut WindowContext| {
1859 view.update(cx, |view, cx| f(view, cx)).ok();
1860 }
1861 }
1862
1863 /// Invoke the given function with the given focus handle present on the key dispatch stack.
1864 /// 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.
1865 pub fn with_key_dispatch<R>(
1866 &mut self,
1867 context: Option<KeyContext>,
1868 focus_handle: Option<FocusHandle>,
1869 f: impl FnOnce(Option<FocusHandle>, &mut Self) -> R,
1870 ) -> R {
1871 let window = &mut self.window;
1872 window.next_frame.dispatch_tree.push_node(context.clone());
1873 if let Some(focus_handle) = focus_handle.as_ref() {
1874 window
1875 .next_frame
1876 .dispatch_tree
1877 .make_focusable(focus_handle.id);
1878 }
1879 let result = f(focus_handle, self);
1880
1881 self.window.next_frame.dispatch_tree.pop_node();
1882
1883 result
1884 }
1885
1886 /// Set an input handler, such as [`ElementInputHandler`][element_input_handler], which interfaces with the
1887 /// platform to receive textual input with proper integration with concerns such
1888 /// as IME interactions.
1889 ///
1890 /// [element_input_handler]: crate::ElementInputHandler
1891 pub fn handle_input(
1892 &mut self,
1893 focus_handle: &FocusHandle,
1894 input_handler: impl PlatformInputHandler,
1895 ) {
1896 if focus_handle.is_focused(self) {
1897 self.window
1898 .platform_window
1899 .set_input_handler(Box::new(input_handler));
1900 }
1901 }
1902
1903 /// Register a callback that can interrupt the closing of the current window based the returned boolean.
1904 /// If the callback returns false, the window won't be closed.
1905 pub fn on_window_should_close(&mut self, f: impl Fn(&mut WindowContext) -> bool + 'static) {
1906 let mut this = self.to_async();
1907 self.window
1908 .platform_window
1909 .on_should_close(Box::new(move || this.update(|_, cx| f(cx)).unwrap_or(true)))
1910 }
1911}
1912
1913impl Context for WindowContext<'_> {
1914 type Result<T> = T;
1915
1916 fn new_model<T>(&mut self, build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T) -> Model<T>
1917 where
1918 T: 'static,
1919 {
1920 let slot = self.app.entities.reserve();
1921 let model = build_model(&mut ModelContext::new(&mut *self.app, slot.downgrade()));
1922 self.entities.insert(slot, model)
1923 }
1924
1925 fn update_model<T: 'static, R>(
1926 &mut self,
1927 model: &Model<T>,
1928 update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
1929 ) -> R {
1930 let mut entity = self.entities.lease(model);
1931 let result = update(
1932 &mut *entity,
1933 &mut ModelContext::new(&mut *self.app, model.downgrade()),
1934 );
1935 self.entities.end_lease(entity);
1936 result
1937 }
1938
1939 fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
1940 where
1941 F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
1942 {
1943 if window == self.window.handle {
1944 let root_view = self.window.root_view.clone().unwrap();
1945 Ok(update(root_view, self))
1946 } else {
1947 window.update(self.app, update)
1948 }
1949 }
1950
1951 fn read_model<T, R>(
1952 &self,
1953 handle: &Model<T>,
1954 read: impl FnOnce(&T, &AppContext) -> R,
1955 ) -> Self::Result<R>
1956 where
1957 T: 'static,
1958 {
1959 let entity = self.entities.read(handle);
1960 read(entity, &*self.app)
1961 }
1962
1963 fn read_window<T, R>(
1964 &self,
1965 window: &WindowHandle<T>,
1966 read: impl FnOnce(View<T>, &AppContext) -> R,
1967 ) -> Result<R>
1968 where
1969 T: 'static,
1970 {
1971 if window.any_handle == self.window.handle {
1972 let root_view = self
1973 .window
1974 .root_view
1975 .clone()
1976 .unwrap()
1977 .downcast::<T>()
1978 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
1979 Ok(read(root_view, self))
1980 } else {
1981 self.app.read_window(window, read)
1982 }
1983 }
1984}
1985
1986impl VisualContext for WindowContext<'_> {
1987 fn new_view<V>(
1988 &mut self,
1989 build_view_state: impl FnOnce(&mut ViewContext<'_, V>) -> V,
1990 ) -> Self::Result<View<V>>
1991 where
1992 V: 'static + Render,
1993 {
1994 let slot = self.app.entities.reserve();
1995 let view = View {
1996 model: slot.clone(),
1997 };
1998 let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1999 let entity = build_view_state(&mut cx);
2000 cx.entities.insert(slot, entity);
2001
2002 cx.new_view_observers
2003 .clone()
2004 .retain(&TypeId::of::<V>(), |observer| {
2005 let any_view = AnyView::from(view.clone());
2006 (observer)(any_view, self);
2007 true
2008 });
2009
2010 view
2011 }
2012
2013 /// Update the given view. Prefer calling `View::update` instead, which calls this method.
2014 fn update_view<T: 'static, R>(
2015 &mut self,
2016 view: &View<T>,
2017 update: impl FnOnce(&mut T, &mut ViewContext<'_, T>) -> R,
2018 ) -> Self::Result<R> {
2019 let mut lease = self.app.entities.lease(&view.model);
2020 let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, view);
2021 let result = update(&mut *lease, &mut cx);
2022 cx.app.entities.end_lease(lease);
2023 result
2024 }
2025
2026 fn replace_root_view<V>(
2027 &mut self,
2028 build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
2029 ) -> Self::Result<View<V>>
2030 where
2031 V: 'static + Render,
2032 {
2033 let view = self.new_view(build_view);
2034 self.window.root_view = Some(view.clone().into());
2035 self.notify();
2036 view
2037 }
2038
2039 fn focus_view<V: crate::FocusableView>(&mut self, view: &View<V>) -> Self::Result<()> {
2040 self.update_view(view, |view, cx| {
2041 view.focus_handle(cx).clone().focus(cx);
2042 })
2043 }
2044
2045 fn dismiss_view<V>(&mut self, view: &View<V>) -> Self::Result<()>
2046 where
2047 V: ManagedView,
2048 {
2049 self.update_view(view, |_, cx| cx.emit(DismissEvent))
2050 }
2051}
2052
2053impl<'a> std::ops::Deref for WindowContext<'a> {
2054 type Target = AppContext;
2055
2056 fn deref(&self) -> &Self::Target {
2057 self.app
2058 }
2059}
2060
2061impl<'a> std::ops::DerefMut for WindowContext<'a> {
2062 fn deref_mut(&mut self) -> &mut Self::Target {
2063 self.app
2064 }
2065}
2066
2067impl<'a> Borrow<AppContext> for WindowContext<'a> {
2068 fn borrow(&self) -> &AppContext {
2069 self.app
2070 }
2071}
2072
2073impl<'a> BorrowMut<AppContext> for WindowContext<'a> {
2074 fn borrow_mut(&mut self) -> &mut AppContext {
2075 self.app
2076 }
2077}
2078
2079/// This trait contains functionality that is shared across [`ViewContext`] and [`WindowContext`]
2080pub trait BorrowWindow: BorrowMut<Window> + BorrowMut<AppContext> {
2081 #[doc(hidden)]
2082 fn app_mut(&mut self) -> &mut AppContext {
2083 self.borrow_mut()
2084 }
2085
2086 #[doc(hidden)]
2087 fn app(&self) -> &AppContext {
2088 self.borrow()
2089 }
2090
2091 #[doc(hidden)]
2092 fn window(&self) -> &Window {
2093 self.borrow()
2094 }
2095
2096 #[doc(hidden)]
2097 fn window_mut(&mut self) -> &mut Window {
2098 self.borrow_mut()
2099 }
2100
2101 /// Pushes the given element id onto the global stack and invokes the given closure
2102 /// with a `GlobalElementId`, which disambiguates the given id in the context of its ancestor
2103 /// ids. Because elements are discarded and recreated on each frame, the `GlobalElementId` is
2104 /// used to associate state with identified elements across separate frames.
2105 fn with_element_id<R>(
2106 &mut self,
2107 id: Option<impl Into<ElementId>>,
2108 f: impl FnOnce(&mut Self) -> R,
2109 ) -> R {
2110 if let Some(id) = id.map(Into::into) {
2111 let window = self.window_mut();
2112 window.element_id_stack.push(id);
2113 let result = f(self);
2114 let window: &mut Window = self.borrow_mut();
2115 window.element_id_stack.pop();
2116 result
2117 } else {
2118 f(self)
2119 }
2120 }
2121
2122 /// Invoke the given function with the given content mask after intersecting it
2123 /// with the current mask.
2124 fn with_content_mask<R>(
2125 &mut self,
2126 mask: Option<ContentMask<Pixels>>,
2127 f: impl FnOnce(&mut Self) -> R,
2128 ) -> R {
2129 if let Some(mask) = mask {
2130 let mask = mask.intersect(&self.content_mask());
2131 self.window_mut().next_frame.content_mask_stack.push(mask);
2132 let result = f(self);
2133 self.window_mut().next_frame.content_mask_stack.pop();
2134 result
2135 } else {
2136 f(self)
2137 }
2138 }
2139
2140 /// Invoke the given function with the content mask reset to that
2141 /// of the window.
2142 fn break_content_mask<R>(&mut self, f: impl FnOnce(&mut Self) -> R) -> R {
2143 let mask = ContentMask {
2144 bounds: Bounds {
2145 origin: Point::default(),
2146 size: self.window().viewport_size,
2147 },
2148 };
2149 let new_stacking_order_id =
2150 post_inc(&mut self.window_mut().next_frame.next_stacking_order_id);
2151 let old_stacking_order = mem::take(&mut self.window_mut().next_frame.z_index_stack);
2152 self.window_mut().next_frame.z_index_stack.id = new_stacking_order_id;
2153 self.window_mut().next_frame.content_mask_stack.push(mask);
2154 let result = f(self);
2155 self.window_mut().next_frame.content_mask_stack.pop();
2156 self.window_mut().next_frame.z_index_stack = old_stacking_order;
2157 result
2158 }
2159
2160 /// Called during painting to invoke the given closure in a new stacking context. The given
2161 /// z-index is interpreted relative to the previous call to `stack`.
2162 fn with_z_index<R>(&mut self, z_index: u8, f: impl FnOnce(&mut Self) -> R) -> R {
2163 let new_stacking_order_id =
2164 post_inc(&mut self.window_mut().next_frame.next_stacking_order_id);
2165 let old_stacking_order_id = mem::replace(
2166 &mut self.window_mut().next_frame.z_index_stack.id,
2167 new_stacking_order_id,
2168 );
2169 self.window_mut().next_frame.z_index_stack.id = new_stacking_order_id;
2170 self.window_mut().next_frame.z_index_stack.push(z_index);
2171 let result = f(self);
2172 self.window_mut().next_frame.z_index_stack.id = old_stacking_order_id;
2173 self.window_mut().next_frame.z_index_stack.pop();
2174 result
2175 }
2176
2177 /// Update the global element offset relative to the current offset. This is used to implement
2178 /// scrolling.
2179 fn with_element_offset<R>(
2180 &mut self,
2181 offset: Point<Pixels>,
2182 f: impl FnOnce(&mut Self) -> R,
2183 ) -> R {
2184 if offset.is_zero() {
2185 return f(self);
2186 };
2187
2188 let abs_offset = self.element_offset() + offset;
2189 self.with_absolute_element_offset(abs_offset, f)
2190 }
2191
2192 /// Update the global element offset based on the given offset. This is used to implement
2193 /// drag handles and other manual painting of elements.
2194 fn with_absolute_element_offset<R>(
2195 &mut self,
2196 offset: Point<Pixels>,
2197 f: impl FnOnce(&mut Self) -> R,
2198 ) -> R {
2199 self.window_mut()
2200 .next_frame
2201 .element_offset_stack
2202 .push(offset);
2203 let result = f(self);
2204 self.window_mut().next_frame.element_offset_stack.pop();
2205 result
2206 }
2207
2208 /// Obtain the current element offset.
2209 fn element_offset(&self) -> Point<Pixels> {
2210 self.window()
2211 .next_frame
2212 .element_offset_stack
2213 .last()
2214 .copied()
2215 .unwrap_or_default()
2216 }
2217
2218 /// Update or initialize state for an element with the given id that lives across multiple
2219 /// frames. If an element with this id existed in the rendered frame, its state will be passed
2220 /// to the given closure. The state returned by the closure will be stored so it can be referenced
2221 /// when drawing the next frame.
2222 fn with_element_state<S, R>(
2223 &mut self,
2224 id: ElementId,
2225 f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
2226 ) -> R
2227 where
2228 S: 'static,
2229 {
2230 self.with_element_id(Some(id), |cx| {
2231 let global_id = cx.window().element_id_stack.clone();
2232
2233 if let Some(any) = cx
2234 .window_mut()
2235 .next_frame
2236 .element_states
2237 .remove(&global_id)
2238 .or_else(|| {
2239 cx.window_mut()
2240 .rendered_frame
2241 .element_states
2242 .remove(&global_id)
2243 })
2244 {
2245 let ElementStateBox {
2246 inner,
2247
2248 #[cfg(debug_assertions)]
2249 type_name
2250 } = any;
2251 // Using the extra inner option to avoid needing to reallocate a new box.
2252 let mut state_box = inner
2253 .downcast::<Option<S>>()
2254 .map_err(|_| {
2255 #[cfg(debug_assertions)]
2256 {
2257 anyhow!(
2258 "invalid element state type for id, requested_type {:?}, actual type: {:?}",
2259 std::any::type_name::<S>(),
2260 type_name
2261 )
2262 }
2263
2264 #[cfg(not(debug_assertions))]
2265 {
2266 anyhow!(
2267 "invalid element state type for id, requested_type {:?}",
2268 std::any::type_name::<S>(),
2269 )
2270 }
2271 })
2272 .unwrap();
2273
2274 // Actual: Option<AnyElement> <- View
2275 // Requested: () <- AnyElemet
2276 let state = state_box
2277 .take()
2278 .expect("element state is already on the stack");
2279 let (result, state) = f(Some(state), cx);
2280 state_box.replace(state);
2281 cx.window_mut()
2282 .next_frame
2283 .element_states
2284 .insert(global_id, ElementStateBox {
2285 inner: state_box,
2286
2287 #[cfg(debug_assertions)]
2288 type_name
2289 });
2290 result
2291 } else {
2292 let (result, state) = f(None, cx);
2293 cx.window_mut()
2294 .next_frame
2295 .element_states
2296 .insert(global_id,
2297 ElementStateBox {
2298 inner: Box::new(Some(state)),
2299
2300 #[cfg(debug_assertions)]
2301 type_name: std::any::type_name::<S>()
2302 }
2303
2304 );
2305 result
2306 }
2307 })
2308 }
2309
2310 /// Obtain the current content mask.
2311 fn content_mask(&self) -> ContentMask<Pixels> {
2312 self.window()
2313 .next_frame
2314 .content_mask_stack
2315 .last()
2316 .cloned()
2317 .unwrap_or_else(|| ContentMask {
2318 bounds: Bounds {
2319 origin: Point::default(),
2320 size: self.window().viewport_size,
2321 },
2322 })
2323 }
2324
2325 /// The size of an em for the base font of the application. Adjusting this value allows the
2326 /// UI to scale, just like zooming a web page.
2327 fn rem_size(&self) -> Pixels {
2328 self.window().rem_size
2329 }
2330}
2331
2332impl Borrow<Window> for WindowContext<'_> {
2333 fn borrow(&self) -> &Window {
2334 self.window
2335 }
2336}
2337
2338impl BorrowMut<Window> for WindowContext<'_> {
2339 fn borrow_mut(&mut self) -> &mut Window {
2340 self.window
2341 }
2342}
2343
2344impl<T> BorrowWindow for T where T: BorrowMut<AppContext> + BorrowMut<Window> {}
2345
2346/// Provides access to application state that is specialized for a particular [`View`].
2347/// Allows you to interact with focus, emit events, etc.
2348/// ViewContext also derefs to [`WindowContext`], giving you access to all of its methods as well.
2349/// When you call [`View::update`], you're passed a `&mut V` and an `&mut ViewContext<V>`.
2350pub struct ViewContext<'a, V> {
2351 window_cx: WindowContext<'a>,
2352 view: &'a View<V>,
2353}
2354
2355impl<V> Borrow<AppContext> for ViewContext<'_, V> {
2356 fn borrow(&self) -> &AppContext {
2357 &*self.window_cx.app
2358 }
2359}
2360
2361impl<V> BorrowMut<AppContext> for ViewContext<'_, V> {
2362 fn borrow_mut(&mut self) -> &mut AppContext {
2363 &mut *self.window_cx.app
2364 }
2365}
2366
2367impl<V> Borrow<Window> for ViewContext<'_, V> {
2368 fn borrow(&self) -> &Window {
2369 &*self.window_cx.window
2370 }
2371}
2372
2373impl<V> BorrowMut<Window> for ViewContext<'_, V> {
2374 fn borrow_mut(&mut self) -> &mut Window {
2375 &mut *self.window_cx.window
2376 }
2377}
2378
2379impl<'a, V: 'static> ViewContext<'a, V> {
2380 pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window, view: &'a View<V>) -> Self {
2381 Self {
2382 window_cx: WindowContext::new(app, window),
2383 view,
2384 }
2385 }
2386
2387 /// Get the entity_id of this view.
2388 pub fn entity_id(&self) -> EntityId {
2389 self.view.entity_id()
2390 }
2391
2392 /// Get the view pointer underlying this context.
2393 pub fn view(&self) -> &View<V> {
2394 self.view
2395 }
2396
2397 /// Get the model underlying this view.
2398 pub fn model(&self) -> &Model<V> {
2399 &self.view.model
2400 }
2401
2402 /// Access the underlying window context.
2403 pub fn window_context(&mut self) -> &mut WindowContext<'a> {
2404 &mut self.window_cx
2405 }
2406
2407 /// Set a given callback to be run on the next frame.
2408 pub fn on_next_frame(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static)
2409 where
2410 V: 'static,
2411 {
2412 let view = self.view().clone();
2413 self.window_cx.on_next_frame(move |cx| view.update(cx, f));
2414 }
2415
2416 /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
2417 /// that are currently on the stack to be returned to the app.
2418 pub fn defer(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static) {
2419 let view = self.view().downgrade();
2420 self.window_cx.defer(move |cx| {
2421 view.update(cx, f).ok();
2422 });
2423 }
2424
2425 /// Observe another model or view for changes to its state, as tracked by [`ModelContext::notify`].
2426 pub fn observe<V2, E>(
2427 &mut self,
2428 entity: &E,
2429 mut on_notify: impl FnMut(&mut V, E, &mut ViewContext<'_, V>) + 'static,
2430 ) -> Subscription
2431 where
2432 V2: 'static,
2433 V: 'static,
2434 E: Entity<V2>,
2435 {
2436 let view = self.view().downgrade();
2437 let entity_id = entity.entity_id();
2438 let entity = entity.downgrade();
2439 let window_handle = self.window.handle;
2440 let (subscription, activate) = self.app.observers.insert(
2441 entity_id,
2442 Box::new(move |cx| {
2443 window_handle
2444 .update(cx, |_, cx| {
2445 if let Some(handle) = E::upgrade_from(&entity) {
2446 view.update(cx, |this, cx| on_notify(this, handle, cx))
2447 .is_ok()
2448 } else {
2449 false
2450 }
2451 })
2452 .unwrap_or(false)
2453 }),
2454 );
2455 self.app.defer(move |_| activate());
2456 subscription
2457 }
2458
2459 /// Subscribe to events emitted by another model or view.
2460 /// The entity to which you're subscribing must implement the [`EventEmitter`] trait.
2461 /// 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.
2462 pub fn subscribe<V2, E, Evt>(
2463 &mut self,
2464 entity: &E,
2465 mut on_event: impl FnMut(&mut V, E, &Evt, &mut ViewContext<'_, V>) + 'static,
2466 ) -> Subscription
2467 where
2468 V2: EventEmitter<Evt>,
2469 E: Entity<V2>,
2470 Evt: 'static,
2471 {
2472 let view = self.view().downgrade();
2473 let entity_id = entity.entity_id();
2474 let handle = entity.downgrade();
2475 let window_handle = self.window.handle;
2476 let (subscription, activate) = self.app.event_listeners.insert(
2477 entity_id,
2478 (
2479 TypeId::of::<Evt>(),
2480 Box::new(move |event, cx| {
2481 window_handle
2482 .update(cx, |_, cx| {
2483 if let Some(handle) = E::upgrade_from(&handle) {
2484 let event = event.downcast_ref().expect("invalid event type");
2485 view.update(cx, |this, cx| on_event(this, handle, event, cx))
2486 .is_ok()
2487 } else {
2488 false
2489 }
2490 })
2491 .unwrap_or(false)
2492 }),
2493 ),
2494 );
2495 self.app.defer(move |_| activate());
2496 subscription
2497 }
2498
2499 /// Register a callback to be invoked when the view is released.
2500 ///
2501 /// The callback receives a handle to the view's window. This handle may be
2502 /// invalid, if the window was closed before the view was released.
2503 pub fn on_release(
2504 &mut self,
2505 on_release: impl FnOnce(&mut V, AnyWindowHandle, &mut AppContext) + 'static,
2506 ) -> Subscription {
2507 let window_handle = self.window.handle;
2508 let (subscription, activate) = self.app.release_listeners.insert(
2509 self.view.model.entity_id,
2510 Box::new(move |this, cx| {
2511 let this = this.downcast_mut().expect("invalid entity type");
2512 on_release(this, window_handle, cx)
2513 }),
2514 );
2515 activate();
2516 subscription
2517 }
2518
2519 /// Register a callback to be invoked when the given Model or View is released.
2520 pub fn observe_release<V2, E>(
2521 &mut self,
2522 entity: &E,
2523 mut on_release: impl FnMut(&mut V, &mut V2, &mut ViewContext<'_, V>) + 'static,
2524 ) -> Subscription
2525 where
2526 V: 'static,
2527 V2: 'static,
2528 E: Entity<V2>,
2529 {
2530 let view = self.view().downgrade();
2531 let entity_id = entity.entity_id();
2532 let window_handle = self.window.handle;
2533 let (subscription, activate) = self.app.release_listeners.insert(
2534 entity_id,
2535 Box::new(move |entity, cx| {
2536 let entity = entity.downcast_mut().expect("invalid entity type");
2537 let _ = window_handle.update(cx, |_, cx| {
2538 view.update(cx, |this, cx| on_release(this, entity, cx))
2539 });
2540 }),
2541 );
2542 activate();
2543 subscription
2544 }
2545
2546 /// Indicate that this view has changed, which will invoke any observers and also mark the window as dirty.
2547 /// If this view or any of its ancestors are *cached*, notifying it will cause it or its ancestors to be redrawn.
2548 pub fn notify(&mut self) {
2549 if !self.window.drawing {
2550 self.window_cx.notify();
2551 self.window_cx.app.push_effect(Effect::Notify {
2552 emitter: self.view.model.entity_id,
2553 });
2554 }
2555 }
2556
2557 /// Register a callback to be invoked when the window is resized.
2558 pub fn observe_window_bounds(
2559 &mut self,
2560 mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2561 ) -> Subscription {
2562 let view = self.view.downgrade();
2563 let (subscription, activate) = self.window.bounds_observers.insert(
2564 (),
2565 Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
2566 );
2567 activate();
2568 subscription
2569 }
2570
2571 /// Register a callback to be invoked when the window is activated or deactivated.
2572 pub fn observe_window_activation(
2573 &mut self,
2574 mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2575 ) -> Subscription {
2576 let view = self.view.downgrade();
2577 let (subscription, activate) = self.window.activation_observers.insert(
2578 (),
2579 Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
2580 );
2581 activate();
2582 subscription
2583 }
2584
2585 /// Register a listener to be called when the given focus handle receives focus.
2586 /// Returns a subscription and persists until the subscription is dropped.
2587 pub fn on_focus(
2588 &mut self,
2589 handle: &FocusHandle,
2590 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2591 ) -> Subscription {
2592 let view = self.view.downgrade();
2593 let focus_id = handle.id;
2594 let (subscription, activate) = self.window.focus_listeners.insert(
2595 (),
2596 Box::new(move |event, cx| {
2597 view.update(cx, |view, cx| {
2598 if event.previous_focus_path.last() != Some(&focus_id)
2599 && event.current_focus_path.last() == Some(&focus_id)
2600 {
2601 listener(view, cx)
2602 }
2603 })
2604 .is_ok()
2605 }),
2606 );
2607 self.app.defer(move |_| activate());
2608 subscription
2609 }
2610
2611 /// Register a listener to be called when the given focus handle or one of its descendants receives focus.
2612 /// Returns a subscription and persists until the subscription is dropped.
2613 pub fn on_focus_in(
2614 &mut self,
2615 handle: &FocusHandle,
2616 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2617 ) -> Subscription {
2618 let view = self.view.downgrade();
2619 let focus_id = handle.id;
2620 let (subscription, activate) = self.window.focus_listeners.insert(
2621 (),
2622 Box::new(move |event, cx| {
2623 view.update(cx, |view, cx| {
2624 if !event.previous_focus_path.contains(&focus_id)
2625 && event.current_focus_path.contains(&focus_id)
2626 {
2627 listener(view, cx)
2628 }
2629 })
2630 .is_ok()
2631 }),
2632 );
2633 self.app.defer(move |_| activate());
2634 subscription
2635 }
2636
2637 /// Register a listener to be called when the given focus handle loses focus.
2638 /// Returns a subscription and persists until the subscription is dropped.
2639 pub fn on_blur(
2640 &mut self,
2641 handle: &FocusHandle,
2642 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2643 ) -> Subscription {
2644 let view = self.view.downgrade();
2645 let focus_id = handle.id;
2646 let (subscription, activate) = self.window.focus_listeners.insert(
2647 (),
2648 Box::new(move |event, cx| {
2649 view.update(cx, |view, cx| {
2650 if event.previous_focus_path.last() == Some(&focus_id)
2651 && event.current_focus_path.last() != Some(&focus_id)
2652 {
2653 listener(view, cx)
2654 }
2655 })
2656 .is_ok()
2657 }),
2658 );
2659 self.app.defer(move |_| activate());
2660 subscription
2661 }
2662
2663 /// Register a listener to be called when nothing in the window has focus.
2664 /// This typically happens when the node that was focused is removed from the tree,
2665 /// and this callback lets you chose a default place to restore the users focus.
2666 /// Returns a subscription and persists until the subscription is dropped.
2667 pub fn on_focus_lost(
2668 &mut self,
2669 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2670 ) -> Subscription {
2671 let view = self.view.downgrade();
2672 let (subscription, activate) = self.window.focus_lost_listeners.insert(
2673 (),
2674 Box::new(move |cx| view.update(cx, |view, cx| listener(view, cx)).is_ok()),
2675 );
2676 activate();
2677 subscription
2678 }
2679
2680 /// Register a listener to be called when the given focus handle or one of its descendants loses focus.
2681 /// Returns a subscription and persists until the subscription is dropped.
2682 pub fn on_focus_out(
2683 &mut self,
2684 handle: &FocusHandle,
2685 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2686 ) -> Subscription {
2687 let view = self.view.downgrade();
2688 let focus_id = handle.id;
2689 let (subscription, activate) = self.window.focus_listeners.insert(
2690 (),
2691 Box::new(move |event, cx| {
2692 view.update(cx, |view, cx| {
2693 if event.previous_focus_path.contains(&focus_id)
2694 && !event.current_focus_path.contains(&focus_id)
2695 {
2696 listener(view, cx)
2697 }
2698 })
2699 .is_ok()
2700 }),
2701 );
2702 self.app.defer(move |_| activate());
2703 subscription
2704 }
2705
2706 /// Schedule a future to be run asynchronously.
2707 /// The given callback is invoked with a [`WeakView<V>`] to avoid leaking the view for a long-running process.
2708 /// It's also given an [`AsyncWindowContext`], which can be used to access the state of the view across await points.
2709 /// The returned future will be polled on the main thread.
2710 pub fn spawn<Fut, R>(
2711 &mut self,
2712 f: impl FnOnce(WeakView<V>, AsyncWindowContext) -> Fut,
2713 ) -> Task<R>
2714 where
2715 R: 'static,
2716 Fut: Future<Output = R> + 'static,
2717 {
2718 let view = self.view().downgrade();
2719 self.window_cx.spawn(|cx| f(view, cx))
2720 }
2721
2722 /// Update the global state of the given type.
2723 pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
2724 where
2725 G: 'static,
2726 {
2727 let mut global = self.app.lease_global::<G>();
2728 let result = f(&mut global, self);
2729 self.app.end_global_lease(global);
2730 result
2731 }
2732
2733 /// Register a callback to be invoked when the given global state changes.
2734 pub fn observe_global<G: 'static>(
2735 &mut self,
2736 mut f: impl FnMut(&mut V, &mut ViewContext<'_, V>) + 'static,
2737 ) -> Subscription {
2738 let window_handle = self.window.handle;
2739 let view = self.view().downgrade();
2740 let (subscription, activate) = self.global_observers.insert(
2741 TypeId::of::<G>(),
2742 Box::new(move |cx| {
2743 window_handle
2744 .update(cx, |_, cx| view.update(cx, |view, cx| f(view, cx)).is_ok())
2745 .unwrap_or(false)
2746 }),
2747 );
2748 self.app.defer(move |_| activate());
2749 subscription
2750 }
2751
2752 /// Add a listener for any mouse event that occurs in the window.
2753 /// This is a fairly low level method.
2754 /// Typically, you'll want to use methods on UI elements, which perform bounds checking etc.
2755 pub fn on_mouse_event<Event: 'static>(
2756 &mut self,
2757 handler: impl Fn(&mut V, &Event, DispatchPhase, &mut ViewContext<V>) + 'static,
2758 ) {
2759 let handle = self.view().clone();
2760 self.window_cx.on_mouse_event(move |event, phase, cx| {
2761 handle.update(cx, |view, cx| {
2762 handler(view, event, phase, cx);
2763 })
2764 });
2765 }
2766
2767 /// Register a callback to be invoked when the given Key Event is dispatched to the window.
2768 pub fn on_key_event<Event: 'static>(
2769 &mut self,
2770 handler: impl Fn(&mut V, &Event, DispatchPhase, &mut ViewContext<V>) + 'static,
2771 ) {
2772 let handle = self.view().clone();
2773 self.window_cx.on_key_event(move |event, phase, cx| {
2774 handle.update(cx, |view, cx| {
2775 handler(view, event, phase, cx);
2776 })
2777 });
2778 }
2779
2780 /// Register a callback to be invoked when the given Action type is dispatched to the window.
2781 pub fn on_action(
2782 &mut self,
2783 action_type: TypeId,
2784 listener: impl Fn(&mut V, &dyn Any, DispatchPhase, &mut ViewContext<V>) + 'static,
2785 ) {
2786 let handle = self.view().clone();
2787 self.window_cx
2788 .on_action(action_type, move |action, phase, cx| {
2789 handle.update(cx, |view, cx| {
2790 listener(view, action, phase, cx);
2791 })
2792 });
2793 }
2794
2795 /// Emit an event to be handled any other views that have subscribed via [ViewContext::subscribe].
2796 pub fn emit<Evt>(&mut self, event: Evt)
2797 where
2798 Evt: 'static,
2799 V: EventEmitter<Evt>,
2800 {
2801 let emitter = self.view.model.entity_id;
2802 self.app.push_effect(Effect::Emit {
2803 emitter,
2804 event_type: TypeId::of::<Evt>(),
2805 event: Box::new(event),
2806 });
2807 }
2808
2809 /// Move focus to the current view, assuming it implements [`FocusableView`].
2810 pub fn focus_self(&mut self)
2811 where
2812 V: FocusableView,
2813 {
2814 self.defer(|view, cx| view.focus_handle(cx).focus(cx))
2815 }
2816
2817 /// Convenience method for accessing view state in an event callback.
2818 ///
2819 /// Many GPUI callbacks take the form of `Fn(&E, &mut WindowContext)`,
2820 /// but it's often useful to be able to access view state in these
2821 /// callbacks. This method provides a convenient way to do so.
2822 pub fn listener<E>(
2823 &self,
2824 f: impl Fn(&mut V, &E, &mut ViewContext<V>) + 'static,
2825 ) -> impl Fn(&E, &mut WindowContext) + 'static {
2826 let view = self.view().downgrade();
2827 move |e: &E, cx: &mut WindowContext| {
2828 view.update(cx, |view, cx| f(view, e, cx)).ok();
2829 }
2830 }
2831}
2832
2833impl<V> Context for ViewContext<'_, V> {
2834 type Result<U> = U;
2835
2836 fn new_model<T: 'static>(
2837 &mut self,
2838 build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
2839 ) -> Model<T> {
2840 self.window_cx.new_model(build_model)
2841 }
2842
2843 fn update_model<T: 'static, R>(
2844 &mut self,
2845 model: &Model<T>,
2846 update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
2847 ) -> R {
2848 self.window_cx.update_model(model, update)
2849 }
2850
2851 fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
2852 where
2853 F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
2854 {
2855 self.window_cx.update_window(window, update)
2856 }
2857
2858 fn read_model<T, R>(
2859 &self,
2860 handle: &Model<T>,
2861 read: impl FnOnce(&T, &AppContext) -> R,
2862 ) -> Self::Result<R>
2863 where
2864 T: 'static,
2865 {
2866 self.window_cx.read_model(handle, read)
2867 }
2868
2869 fn read_window<T, R>(
2870 &self,
2871 window: &WindowHandle<T>,
2872 read: impl FnOnce(View<T>, &AppContext) -> R,
2873 ) -> Result<R>
2874 where
2875 T: 'static,
2876 {
2877 self.window_cx.read_window(window, read)
2878 }
2879}
2880
2881impl<V: 'static> VisualContext for ViewContext<'_, V> {
2882 fn new_view<W: Render + 'static>(
2883 &mut self,
2884 build_view_state: impl FnOnce(&mut ViewContext<'_, W>) -> W,
2885 ) -> Self::Result<View<W>> {
2886 self.window_cx.new_view(build_view_state)
2887 }
2888
2889 fn update_view<V2: 'static, R>(
2890 &mut self,
2891 view: &View<V2>,
2892 update: impl FnOnce(&mut V2, &mut ViewContext<'_, V2>) -> R,
2893 ) -> Self::Result<R> {
2894 self.window_cx.update_view(view, update)
2895 }
2896
2897 fn replace_root_view<W>(
2898 &mut self,
2899 build_view: impl FnOnce(&mut ViewContext<'_, W>) -> W,
2900 ) -> Self::Result<View<W>>
2901 where
2902 W: 'static + Render,
2903 {
2904 self.window_cx.replace_root_view(build_view)
2905 }
2906
2907 fn focus_view<W: FocusableView>(&mut self, view: &View<W>) -> Self::Result<()> {
2908 self.window_cx.focus_view(view)
2909 }
2910
2911 fn dismiss_view<W: ManagedView>(&mut self, view: &View<W>) -> Self::Result<()> {
2912 self.window_cx.dismiss_view(view)
2913 }
2914}
2915
2916impl<'a, V> std::ops::Deref for ViewContext<'a, V> {
2917 type Target = WindowContext<'a>;
2918
2919 fn deref(&self) -> &Self::Target {
2920 &self.window_cx
2921 }
2922}
2923
2924impl<'a, V> std::ops::DerefMut for ViewContext<'a, V> {
2925 fn deref_mut(&mut self) -> &mut Self::Target {
2926 &mut self.window_cx
2927 }
2928}
2929
2930// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
2931slotmap::new_key_type! {
2932 /// A unique identifier for a window.
2933 pub struct WindowId;
2934}
2935
2936impl WindowId {
2937 /// Converts this window ID to a `u64`.
2938 pub fn as_u64(&self) -> u64 {
2939 self.0.as_ffi()
2940 }
2941}
2942
2943/// A handle to a window with a specific root view type.
2944/// Note that this does not keep the window alive on its own.
2945#[derive(Deref, DerefMut)]
2946pub struct WindowHandle<V> {
2947 #[deref]
2948 #[deref_mut]
2949 pub(crate) any_handle: AnyWindowHandle,
2950 state_type: PhantomData<V>,
2951}
2952
2953impl<V: 'static + Render> WindowHandle<V> {
2954 /// Create a new handle from a window ID.
2955 /// This does not check if the root type of the window is `V`.
2956 pub fn new(id: WindowId) -> Self {
2957 WindowHandle {
2958 any_handle: AnyWindowHandle {
2959 id,
2960 state_type: TypeId::of::<V>(),
2961 },
2962 state_type: PhantomData,
2963 }
2964 }
2965
2966 /// Get the root view out of this window.
2967 ///
2968 /// This will fail if the window is closed or if the root view's type does not match `V`.
2969 pub fn root<C>(&self, cx: &mut C) -> Result<View<V>>
2970 where
2971 C: Context,
2972 {
2973 Flatten::flatten(cx.update_window(self.any_handle, |root_view, _| {
2974 root_view
2975 .downcast::<V>()
2976 .map_err(|_| anyhow!("the type of the window's root view has changed"))
2977 }))
2978 }
2979
2980 /// Update the root view of this window.
2981 ///
2982 /// This will fail if the window has been closed or if the root view's type does not match
2983 pub fn update<C, R>(
2984 &self,
2985 cx: &mut C,
2986 update: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
2987 ) -> Result<R>
2988 where
2989 C: Context,
2990 {
2991 cx.update_window(self.any_handle, |root_view, cx| {
2992 let view = root_view
2993 .downcast::<V>()
2994 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
2995 Ok(cx.update_view(&view, update))
2996 })?
2997 }
2998
2999 /// Read the root view out of this window.
3000 ///
3001 /// This will fail if the window is closed or if the root view's type does not match `V`.
3002 pub fn read<'a>(&self, cx: &'a AppContext) -> Result<&'a V> {
3003 let x = cx
3004 .windows
3005 .get(self.id)
3006 .and_then(|window| {
3007 window
3008 .as_ref()
3009 .and_then(|window| window.root_view.clone())
3010 .map(|root_view| root_view.downcast::<V>())
3011 })
3012 .ok_or_else(|| anyhow!("window not found"))?
3013 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
3014
3015 Ok(x.read(cx))
3016 }
3017
3018 /// Read the root view out of this window, with a callback
3019 ///
3020 /// This will fail if the window is closed or if the root view's type does not match `V`.
3021 pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &AppContext) -> R) -> Result<R>
3022 where
3023 C: Context,
3024 {
3025 cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
3026 }
3027
3028 /// Read the root view pointer off of this window.
3029 ///
3030 /// This will fail if the window is closed or if the root view's type does not match `V`.
3031 pub fn root_view<C>(&self, cx: &C) -> Result<View<V>>
3032 where
3033 C: Context,
3034 {
3035 cx.read_window(self, |root_view, _cx| root_view.clone())
3036 }
3037
3038 /// Check if this window is 'active'.
3039 ///
3040 /// Will return `None` if the window is closed.
3041 pub fn is_active(&self, cx: &AppContext) -> Option<bool> {
3042 cx.windows
3043 .get(self.id)
3044 .and_then(|window| window.as_ref().map(|window| window.active))
3045 }
3046}
3047
3048impl<V> Copy for WindowHandle<V> {}
3049
3050impl<V> Clone for WindowHandle<V> {
3051 fn clone(&self) -> Self {
3052 *self
3053 }
3054}
3055
3056impl<V> PartialEq for WindowHandle<V> {
3057 fn eq(&self, other: &Self) -> bool {
3058 self.any_handle == other.any_handle
3059 }
3060}
3061
3062impl<V> Eq for WindowHandle<V> {}
3063
3064impl<V> Hash for WindowHandle<V> {
3065 fn hash<H: Hasher>(&self, state: &mut H) {
3066 self.any_handle.hash(state);
3067 }
3068}
3069
3070impl<V: 'static> From<WindowHandle<V>> for AnyWindowHandle {
3071 fn from(val: WindowHandle<V>) -> Self {
3072 val.any_handle
3073 }
3074}
3075
3076/// A handle to a window with any root view type, which can be downcast to a window with a specific root view type.
3077#[derive(Copy, Clone, PartialEq, Eq, Hash)]
3078pub struct AnyWindowHandle {
3079 pub(crate) id: WindowId,
3080 state_type: TypeId,
3081}
3082
3083impl AnyWindowHandle {
3084 /// Get the ID of this window.
3085 pub fn window_id(&self) -> WindowId {
3086 self.id
3087 }
3088
3089 /// Attempt to convert this handle to a window handle with a specific root view type.
3090 /// If the types do not match, this will return `None`.
3091 pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
3092 if TypeId::of::<T>() == self.state_type {
3093 Some(WindowHandle {
3094 any_handle: *self,
3095 state_type: PhantomData,
3096 })
3097 } else {
3098 None
3099 }
3100 }
3101
3102 /// Update the state of the root view of this window.
3103 ///
3104 /// This will fail if the window has been closed.
3105 pub fn update<C, R>(
3106 self,
3107 cx: &mut C,
3108 update: impl FnOnce(AnyView, &mut WindowContext<'_>) -> R,
3109 ) -> Result<R>
3110 where
3111 C: Context,
3112 {
3113 cx.update_window(self, update)
3114 }
3115
3116 /// Read the state of the root view of this window.
3117 ///
3118 /// This will fail if the window has been closed.
3119 pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(View<T>, &AppContext) -> R) -> Result<R>
3120 where
3121 C: Context,
3122 T: 'static,
3123 {
3124 let view = self
3125 .downcast::<T>()
3126 .context("the type of the window's root view has changed")?;
3127
3128 cx.read_window(&view, read)
3129 }
3130}
3131
3132// #[cfg(any(test, feature = "test-support"))]
3133// impl From<SmallVec<[u32; 16]>> for StackingOrder {
3134// fn from(small_vec: SmallVec<[u32; 16]>) -> Self {
3135// StackingOrder(small_vec)
3136// }
3137// }
3138
3139/// An identifier for an [`Element`](crate::Element).
3140///
3141/// Can be constructed with a string, a number, or both, as well
3142/// as other internal representations.
3143#[derive(Clone, Debug, Eq, PartialEq, Hash)]
3144pub enum ElementId {
3145 /// The ID of a View element
3146 View(EntityId),
3147 /// An integer ID.
3148 Integer(usize),
3149 /// A string based ID.
3150 Name(SharedString),
3151 /// An ID that's equated with a focus handle.
3152 FocusHandle(FocusId),
3153 /// A combination of a name and an integer.
3154 NamedInteger(SharedString, usize),
3155}
3156
3157impl ElementId {
3158 pub(crate) fn from_entity_id(entity_id: EntityId) -> Self {
3159 ElementId::View(entity_id)
3160 }
3161}
3162
3163impl TryInto<SharedString> for ElementId {
3164 type Error = anyhow::Error;
3165
3166 fn try_into(self) -> anyhow::Result<SharedString> {
3167 if let ElementId::Name(name) = self {
3168 Ok(name)
3169 } else {
3170 Err(anyhow!("element id is not string"))
3171 }
3172 }
3173}
3174
3175impl From<usize> for ElementId {
3176 fn from(id: usize) -> Self {
3177 ElementId::Integer(id)
3178 }
3179}
3180
3181impl From<i32> for ElementId {
3182 fn from(id: i32) -> Self {
3183 Self::Integer(id as usize)
3184 }
3185}
3186
3187impl From<SharedString> for ElementId {
3188 fn from(name: SharedString) -> Self {
3189 ElementId::Name(name)
3190 }
3191}
3192
3193impl From<&'static str> for ElementId {
3194 fn from(name: &'static str) -> Self {
3195 ElementId::Name(name.into())
3196 }
3197}
3198
3199impl<'a> From<&'a FocusHandle> for ElementId {
3200 fn from(handle: &'a FocusHandle) -> Self {
3201 ElementId::FocusHandle(handle.id)
3202 }
3203}
3204
3205impl From<(&'static str, EntityId)> for ElementId {
3206 fn from((name, id): (&'static str, EntityId)) -> Self {
3207 ElementId::NamedInteger(name.into(), id.as_u64() as usize)
3208 }
3209}
3210
3211impl From<(&'static str, usize)> for ElementId {
3212 fn from((name, id): (&'static str, usize)) -> Self {
3213 ElementId::NamedInteger(name.into(), id)
3214 }
3215}
3216
3217impl From<(&'static str, u64)> for ElementId {
3218 fn from((name, id): (&'static str, u64)) -> Self {
3219 ElementId::NamedInteger(name.into(), id as usize)
3220 }
3221}
3222
3223/// A rectangle to be rendered in the window at the given position and size.
3224/// Passed as an argument [`WindowContext::paint_quad`].
3225#[derive(Clone)]
3226pub struct PaintQuad {
3227 bounds: Bounds<Pixels>,
3228 corner_radii: Corners<Pixels>,
3229 background: Hsla,
3230 border_widths: Edges<Pixels>,
3231 border_color: Hsla,
3232}
3233
3234impl PaintQuad {
3235 /// Set the corner radii of the quad.
3236 pub fn corner_radii(self, corner_radii: impl Into<Corners<Pixels>>) -> Self {
3237 PaintQuad {
3238 corner_radii: corner_radii.into(),
3239 ..self
3240 }
3241 }
3242
3243 /// Set the border widths of the quad.
3244 pub fn border_widths(self, border_widths: impl Into<Edges<Pixels>>) -> Self {
3245 PaintQuad {
3246 border_widths: border_widths.into(),
3247 ..self
3248 }
3249 }
3250
3251 /// Set the border color of the quad.
3252 pub fn border_color(self, border_color: impl Into<Hsla>) -> Self {
3253 PaintQuad {
3254 border_color: border_color.into(),
3255 ..self
3256 }
3257 }
3258
3259 /// Set the background color of the quad.
3260 pub fn background(self, background: impl Into<Hsla>) -> Self {
3261 PaintQuad {
3262 background: background.into(),
3263 ..self
3264 }
3265 }
3266}
3267
3268/// Create a quad with the given parameters.
3269pub fn quad(
3270 bounds: Bounds<Pixels>,
3271 corner_radii: impl Into<Corners<Pixels>>,
3272 background: impl Into<Hsla>,
3273 border_widths: impl Into<Edges<Pixels>>,
3274 border_color: impl Into<Hsla>,
3275) -> PaintQuad {
3276 PaintQuad {
3277 bounds,
3278 corner_radii: corner_radii.into(),
3279 background: background.into(),
3280 border_widths: border_widths.into(),
3281 border_color: border_color.into(),
3282 }
3283}
3284
3285/// Create a filled quad with the given bounds and background color.
3286pub fn fill(bounds: impl Into<Bounds<Pixels>>, background: impl Into<Hsla>) -> PaintQuad {
3287 PaintQuad {
3288 bounds: bounds.into(),
3289 corner_radii: (0.).into(),
3290 background: background.into(),
3291 border_widths: (0.).into(),
3292 border_color: transparent_black(),
3293 }
3294}
3295
3296/// Create a rectangle outline with the given bounds, border color, and a 1px border width
3297pub fn outline(bounds: impl Into<Bounds<Pixels>>, border_color: impl Into<Hsla>) -> PaintQuad {
3298 PaintQuad {
3299 bounds: bounds.into(),
3300 corner_radii: (0.).into(),
3301 background: transparent_black(),
3302 border_widths: (1.).into(),
3303 border_color: border_color.into(),
3304 }
3305}