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