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