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