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