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