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