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