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