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