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