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