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