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::zero(), available_space, cx);
1187 })
1188 });
1189
1190 if let Some(active_drag) = self.app.active_drag.take() {
1191 self.with_z_index(1, |cx| {
1192 let offset = cx.mouse_position() - active_drag.cursor_offset;
1193 let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
1194 active_drag.view.draw(offset, available_space, cx);
1195 cx.active_drag = Some(active_drag);
1196 });
1197 } else if let Some(active_tooltip) = self.app.active_tooltip.take() {
1198 self.with_z_index(1, |cx| {
1199 let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
1200 active_tooltip
1201 .view
1202 .draw(active_tooltip.cursor_offset, available_space, cx);
1203 });
1204 }
1205
1206 self.window
1207 .current_frame
1208 .dispatch_tree
1209 .preserve_pending_keystrokes(
1210 &mut self.window.previous_frame.dispatch_tree,
1211 self.window.focus,
1212 );
1213
1214 self.window.root_view = Some(root_view);
1215 let scene = self.window.current_frame.scene_builder.build();
1216
1217 self.window.platform_window.draw(scene);
1218 let cursor_style = self
1219 .window
1220 .requested_cursor_style
1221 .take()
1222 .unwrap_or(CursorStyle::Arrow);
1223 self.platform.set_cursor_style(cursor_style);
1224
1225 self.window.dirty = false;
1226 }
1227
1228 /// Rotate the current frame and the previous frame, then clear the current frame.
1229 /// We repopulate all state in the current frame during each paint.
1230 fn start_frame(&mut self) {
1231 self.text_system().start_frame();
1232
1233 let window = &mut *self.window;
1234 window.layout_engine.as_mut().unwrap().clear();
1235
1236 mem::swap(&mut window.previous_frame, &mut window.current_frame);
1237 let frame = &mut window.current_frame;
1238 frame.element_states.clear();
1239 frame.mouse_listeners.values_mut().for_each(Vec::clear);
1240 frame.focus_listeners.clear();
1241 frame.dispatch_tree.clear();
1242 frame.depth_map.clear();
1243 }
1244
1245 /// Dispatch a mouse or keyboard event on the window.
1246 pub fn dispatch_event(&mut self, event: InputEvent) -> bool {
1247 // Handlers may set this to false by calling `stop_propagation`
1248 self.app.propagate_event = true;
1249 self.window.default_prevented = false;
1250
1251 let event = match event {
1252 // Track the mouse position with our own state, since accessing the platform
1253 // API for the mouse position can only occur on the main thread.
1254 InputEvent::MouseMove(mouse_move) => {
1255 self.window.mouse_position = mouse_move.position;
1256 InputEvent::MouseMove(mouse_move)
1257 }
1258 InputEvent::MouseDown(mouse_down) => {
1259 self.window.mouse_position = mouse_down.position;
1260 InputEvent::MouseDown(mouse_down)
1261 }
1262 InputEvent::MouseUp(mouse_up) => {
1263 self.window.mouse_position = mouse_up.position;
1264 InputEvent::MouseUp(mouse_up)
1265 }
1266 // Translate dragging and dropping of external files from the operating system
1267 // to internal drag and drop events.
1268 InputEvent::FileDrop(file_drop) => match file_drop {
1269 FileDropEvent::Entered { position, files } => {
1270 self.window.mouse_position = position;
1271 if self.active_drag.is_none() {
1272 self.active_drag = Some(AnyDrag {
1273 view: self.build_view(|_| files).into(),
1274 cursor_offset: position,
1275 });
1276 }
1277 InputEvent::MouseDown(MouseDownEvent {
1278 position,
1279 button: MouseButton::Left,
1280 click_count: 1,
1281 modifiers: Modifiers::default(),
1282 })
1283 }
1284 FileDropEvent::Pending { position } => {
1285 self.window.mouse_position = position;
1286 InputEvent::MouseMove(MouseMoveEvent {
1287 position,
1288 pressed_button: Some(MouseButton::Left),
1289 modifiers: Modifiers::default(),
1290 })
1291 }
1292 FileDropEvent::Submit { position } => {
1293 self.window.mouse_position = position;
1294 InputEvent::MouseUp(MouseUpEvent {
1295 button: MouseButton::Left,
1296 position,
1297 modifiers: Modifiers::default(),
1298 click_count: 1,
1299 })
1300 }
1301 FileDropEvent::Exited => InputEvent::MouseUp(MouseUpEvent {
1302 button: MouseButton::Left,
1303 position: Point::default(),
1304 modifiers: Modifiers::default(),
1305 click_count: 1,
1306 }),
1307 },
1308 _ => event,
1309 };
1310
1311 if let Some(any_mouse_event) = event.mouse_event() {
1312 self.dispatch_mouse_event(any_mouse_event);
1313 } else if let Some(any_key_event) = event.keyboard_event() {
1314 self.dispatch_key_event(any_key_event);
1315 }
1316
1317 !self.app.propagate_event
1318 }
1319
1320 fn dispatch_mouse_event(&mut self, event: &dyn Any) {
1321 if let Some(mut handlers) = self
1322 .window
1323 .current_frame
1324 .mouse_listeners
1325 .remove(&event.type_id())
1326 {
1327 // Because handlers may add other handlers, we sort every time.
1328 handlers.sort_by(|(a, _), (b, _)| a.cmp(b));
1329
1330 // Capture phase, events bubble from back to front. Handlers for this phase are used for
1331 // special purposes, such as detecting events outside of a given Bounds.
1332 for (_, handler) in &mut handlers {
1333 handler(event, DispatchPhase::Capture, self);
1334 if !self.app.propagate_event {
1335 break;
1336 }
1337 }
1338
1339 // Bubble phase, where most normal handlers do their work.
1340 if self.app.propagate_event {
1341 for (_, handler) in handlers.iter_mut().rev() {
1342 handler(event, DispatchPhase::Bubble, self);
1343 if !self.app.propagate_event {
1344 break;
1345 }
1346 }
1347 }
1348
1349 if self.app.propagate_event && event.downcast_ref::<MouseUpEvent>().is_some() {
1350 self.active_drag = None;
1351 }
1352
1353 // Just in case any handlers added new handlers, which is weird, but possible.
1354 handlers.extend(
1355 self.window
1356 .current_frame
1357 .mouse_listeners
1358 .get_mut(&event.type_id())
1359 .into_iter()
1360 .flat_map(|handlers| handlers.drain(..)),
1361 );
1362 self.window
1363 .current_frame
1364 .mouse_listeners
1365 .insert(event.type_id(), handlers);
1366 }
1367 }
1368
1369 fn dispatch_key_event(&mut self, event: &dyn Any) {
1370 let node_id = self
1371 .window
1372 .focus
1373 .and_then(|focus_id| {
1374 self.window
1375 .current_frame
1376 .dispatch_tree
1377 .focusable_node_id(focus_id)
1378 })
1379 .unwrap_or_else(|| self.window.current_frame.dispatch_tree.root_node_id());
1380
1381 let dispatch_path = self
1382 .window
1383 .current_frame
1384 .dispatch_tree
1385 .dispatch_path(node_id);
1386
1387 let mut actions: Vec<Box<dyn Action>> = Vec::new();
1388
1389 // Capture phase
1390 let mut context_stack: SmallVec<[KeyContext; 16]> = SmallVec::new();
1391 self.propagate_event = true;
1392
1393 for node_id in &dispatch_path {
1394 let node = self.window.current_frame.dispatch_tree.node(*node_id);
1395
1396 if let Some(context) = node.context.clone() {
1397 context_stack.push(context);
1398 }
1399
1400 for key_listener in node.key_listeners.clone() {
1401 key_listener(event, DispatchPhase::Capture, self);
1402 if !self.propagate_event {
1403 return;
1404 }
1405 }
1406 }
1407
1408 // Bubble phase
1409 for node_id in dispatch_path.iter().rev() {
1410 // Handle low level key events
1411 let node = self.window.current_frame.dispatch_tree.node(*node_id);
1412 for key_listener in node.key_listeners.clone() {
1413 key_listener(event, DispatchPhase::Bubble, self);
1414 if !self.propagate_event {
1415 return;
1416 }
1417 }
1418
1419 // Match keystrokes
1420 let node = self.window.current_frame.dispatch_tree.node(*node_id);
1421 if node.context.is_some() {
1422 if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
1423 if let Some(found) = self
1424 .window
1425 .current_frame
1426 .dispatch_tree
1427 .dispatch_key(&key_down_event.keystroke, &context_stack)
1428 {
1429 actions.push(found.boxed_clone())
1430 }
1431 }
1432
1433 context_stack.pop();
1434 }
1435 }
1436
1437 for action in actions {
1438 self.dispatch_action_on_node(node_id, action);
1439 if !self.propagate_event {
1440 return;
1441 }
1442 }
1443 }
1444
1445 fn dispatch_action_on_node(&mut self, node_id: DispatchNodeId, action: Box<dyn Action>) {
1446 let dispatch_path = self
1447 .window
1448 .current_frame
1449 .dispatch_tree
1450 .dispatch_path(node_id);
1451
1452 // Capture phase
1453 for node_id in &dispatch_path {
1454 let node = self.window.current_frame.dispatch_tree.node(*node_id);
1455 for DispatchActionListener {
1456 action_type,
1457 listener,
1458 } in node.action_listeners.clone()
1459 {
1460 let any_action = action.as_any();
1461 if action_type == any_action.type_id() {
1462 listener(any_action, DispatchPhase::Capture, self);
1463 if !self.propagate_event {
1464 return;
1465 }
1466 }
1467 }
1468 }
1469 // Bubble phase
1470 for node_id in dispatch_path.iter().rev() {
1471 let node = self.window.current_frame.dispatch_tree.node(*node_id);
1472 for DispatchActionListener {
1473 action_type,
1474 listener,
1475 } in node.action_listeners.clone()
1476 {
1477 let any_action = action.as_any();
1478 if action_type == any_action.type_id() {
1479 self.propagate_event = false; // Actions stop propagation by default during the bubble phase
1480 listener(any_action, DispatchPhase::Bubble, self);
1481 if !self.propagate_event {
1482 return;
1483 }
1484 }
1485 }
1486 }
1487 }
1488
1489 /// Register the given handler to be invoked whenever the global of the given type
1490 /// is updated.
1491 pub fn observe_global<G: 'static>(
1492 &mut self,
1493 f: impl Fn(&mut WindowContext<'_>) + 'static,
1494 ) -> Subscription {
1495 let window_handle = self.window.handle;
1496 let (subscription, activate) = self.global_observers.insert(
1497 TypeId::of::<G>(),
1498 Box::new(move |cx| window_handle.update(cx, |_, cx| f(cx)).is_ok()),
1499 );
1500 self.app.defer(move |_| activate());
1501 subscription
1502 }
1503
1504 pub fn activate_window(&self) {
1505 self.window.platform_window.activate();
1506 }
1507
1508 pub fn minimize_window(&self) {
1509 self.window.platform_window.minimize();
1510 }
1511
1512 pub fn toggle_full_screen(&self) {
1513 self.window.platform_window.toggle_full_screen();
1514 }
1515
1516 pub fn prompt(
1517 &self,
1518 level: PromptLevel,
1519 msg: &str,
1520 answers: &[&str],
1521 ) -> oneshot::Receiver<usize> {
1522 self.window.platform_window.prompt(level, msg, answers)
1523 }
1524
1525 pub fn available_actions(&self) -> Vec<Box<dyn Action>> {
1526 let node_id = self
1527 .window
1528 .focus
1529 .and_then(|focus_id| {
1530 self.window
1531 .current_frame
1532 .dispatch_tree
1533 .focusable_node_id(focus_id)
1534 })
1535 .unwrap_or_else(|| self.window.current_frame.dispatch_tree.root_node_id());
1536
1537 self.window
1538 .current_frame
1539 .dispatch_tree
1540 .available_actions(node_id)
1541 }
1542
1543 pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
1544 self.window
1545 .previous_frame
1546 .dispatch_tree
1547 .bindings_for_action(
1548 action,
1549 &self.window.previous_frame.dispatch_tree.context_stack,
1550 )
1551 }
1552
1553 pub fn bindings_for_action_in(
1554 &self,
1555 action: &dyn Action,
1556 focus_handle: &FocusHandle,
1557 ) -> Vec<KeyBinding> {
1558 let dispatch_tree = &self.window.previous_frame.dispatch_tree;
1559
1560 let Some(node_id) = dispatch_tree.focusable_node_id(focus_handle.id) else {
1561 return vec![];
1562 };
1563 let context_stack = dispatch_tree
1564 .dispatch_path(node_id)
1565 .into_iter()
1566 .filter_map(|node_id| dispatch_tree.node(node_id).context.clone())
1567 .collect();
1568 dispatch_tree.bindings_for_action(action, &context_stack)
1569 }
1570
1571 pub fn listener_for<V: Render, E>(
1572 &self,
1573 view: &View<V>,
1574 f: impl Fn(&mut V, &E, &mut ViewContext<V>) + 'static,
1575 ) -> impl Fn(&E, &mut WindowContext) + 'static {
1576 let view = view.downgrade();
1577 move |e: &E, cx: &mut WindowContext| {
1578 view.update(cx, |view, cx| f(view, e, cx)).ok();
1579 }
1580 }
1581
1582 pub fn handler_for<V: Render>(
1583 &self,
1584 view: &View<V>,
1585 f: impl Fn(&mut V, &mut ViewContext<V>) + 'static,
1586 ) -> impl Fn(&mut WindowContext) {
1587 let view = view.downgrade();
1588 move |cx: &mut WindowContext| {
1589 view.update(cx, |view, cx| f(view, cx)).ok();
1590 }
1591 }
1592
1593 //========== ELEMENT RELATED FUNCTIONS ===========
1594 pub fn with_key_dispatch<R>(
1595 &mut self,
1596 context: Option<KeyContext>,
1597 focus_handle: Option<FocusHandle>,
1598 f: impl FnOnce(Option<FocusHandle>, &mut Self) -> R,
1599 ) -> R {
1600 let window = &mut self.window;
1601 window
1602 .current_frame
1603 .dispatch_tree
1604 .push_node(context.clone());
1605 if let Some(focus_handle) = focus_handle.as_ref() {
1606 window
1607 .current_frame
1608 .dispatch_tree
1609 .make_focusable(focus_handle.id);
1610 }
1611 let result = f(focus_handle, self);
1612
1613 self.window.current_frame.dispatch_tree.pop_node();
1614
1615 result
1616 }
1617
1618 /// Register a focus listener for the current frame only. It will be cleared
1619 /// on the next frame render. You should use this method only from within elements,
1620 /// and we may want to enforce that better via a different context type.
1621 // todo!() Move this to `FrameContext` to emphasize its individuality?
1622 pub fn on_focus_changed(
1623 &mut self,
1624 listener: impl Fn(&FocusEvent, &mut WindowContext) + 'static,
1625 ) {
1626 self.window
1627 .current_frame
1628 .focus_listeners
1629 .push(Box::new(move |event, cx| {
1630 listener(event, cx);
1631 }));
1632 }
1633
1634 /// Set an input handler, such as [ElementInputHandler], which interfaces with the
1635 /// platform to receive textual input with proper integration with concerns such
1636 /// as IME interactions.
1637 pub fn handle_input(
1638 &mut self,
1639 focus_handle: &FocusHandle,
1640 input_handler: impl PlatformInputHandler,
1641 ) {
1642 if focus_handle.is_focused(self) {
1643 self.window
1644 .platform_window
1645 .set_input_handler(Box::new(input_handler));
1646 }
1647 }
1648
1649 pub fn on_window_should_close(&mut self, f: impl Fn(&mut WindowContext) -> bool + 'static) {
1650 let mut this = self.to_async();
1651 self.window
1652 .platform_window
1653 .on_should_close(Box::new(move || this.update(|_, cx| f(cx)).unwrap_or(true)))
1654 }
1655}
1656
1657impl Context for WindowContext<'_> {
1658 type Result<T> = T;
1659
1660 fn build_model<T>(
1661 &mut self,
1662 build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
1663 ) -> Model<T>
1664 where
1665 T: 'static,
1666 {
1667 let slot = self.app.entities.reserve();
1668 let model = build_model(&mut ModelContext::new(&mut *self.app, slot.downgrade()));
1669 self.entities.insert(slot, model)
1670 }
1671
1672 fn update_model<T: 'static, R>(
1673 &mut self,
1674 model: &Model<T>,
1675 update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
1676 ) -> R {
1677 let mut entity = self.entities.lease(model);
1678 let result = update(
1679 &mut *entity,
1680 &mut ModelContext::new(&mut *self.app, model.downgrade()),
1681 );
1682 self.entities.end_lease(entity);
1683 result
1684 }
1685
1686 fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
1687 where
1688 F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
1689 {
1690 if window == self.window.handle {
1691 let root_view = self.window.root_view.clone().unwrap();
1692 Ok(update(root_view, self))
1693 } else {
1694 window.update(self.app, update)
1695 }
1696 }
1697
1698 fn read_model<T, R>(
1699 &self,
1700 handle: &Model<T>,
1701 read: impl FnOnce(&T, &AppContext) -> R,
1702 ) -> Self::Result<R>
1703 where
1704 T: 'static,
1705 {
1706 let entity = self.entities.read(handle);
1707 read(&*entity, &*self.app)
1708 }
1709
1710 fn read_window<T, R>(
1711 &self,
1712 window: &WindowHandle<T>,
1713 read: impl FnOnce(View<T>, &AppContext) -> R,
1714 ) -> Result<R>
1715 where
1716 T: 'static,
1717 {
1718 if window.any_handle == self.window.handle {
1719 let root_view = self
1720 .window
1721 .root_view
1722 .clone()
1723 .unwrap()
1724 .downcast::<T>()
1725 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
1726 Ok(read(root_view, self))
1727 } else {
1728 self.app.read_window(window, read)
1729 }
1730 }
1731}
1732
1733impl VisualContext for WindowContext<'_> {
1734 fn build_view<V>(
1735 &mut self,
1736 build_view_state: impl FnOnce(&mut ViewContext<'_, V>) -> V,
1737 ) -> Self::Result<View<V>>
1738 where
1739 V: 'static + Render,
1740 {
1741 let slot = self.app.entities.reserve();
1742 let view = View {
1743 model: slot.clone(),
1744 };
1745 let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1746 let entity = build_view_state(&mut cx);
1747 cx.entities.insert(slot, entity);
1748
1749 cx.new_view_observers
1750 .clone()
1751 .retain(&TypeId::of::<V>(), |observer| {
1752 let any_view = AnyView::from(view.clone());
1753 (observer)(any_view, self);
1754 true
1755 });
1756
1757 view
1758 }
1759
1760 /// Update the given view. Prefer calling `View::update` instead, which calls this method.
1761 fn update_view<T: 'static, R>(
1762 &mut self,
1763 view: &View<T>,
1764 update: impl FnOnce(&mut T, &mut ViewContext<'_, T>) -> R,
1765 ) -> Self::Result<R> {
1766 let mut lease = self.app.entities.lease(&view.model);
1767 let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1768 let result = update(&mut *lease, &mut cx);
1769 cx.app.entities.end_lease(lease);
1770 result
1771 }
1772
1773 fn replace_root_view<V>(
1774 &mut self,
1775 build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
1776 ) -> Self::Result<View<V>>
1777 where
1778 V: 'static + Render,
1779 {
1780 let slot = self.app.entities.reserve();
1781 let view = View {
1782 model: slot.clone(),
1783 };
1784 let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1785 let entity = build_view(&mut cx);
1786 self.entities.insert(slot, entity);
1787 self.window.root_view = Some(view.clone().into());
1788 view
1789 }
1790
1791 fn focus_view<V: crate::FocusableView>(&mut self, view: &View<V>) -> Self::Result<()> {
1792 self.update_view(view, |view, cx| {
1793 view.focus_handle(cx).clone().focus(cx);
1794 })
1795 }
1796
1797 fn dismiss_view<V>(&mut self, view: &View<V>) -> Self::Result<()>
1798 where
1799 V: ManagedView,
1800 {
1801 self.update_view(view, |_, cx| cx.emit(DismissEvent))
1802 }
1803}
1804
1805impl<'a> std::ops::Deref for WindowContext<'a> {
1806 type Target = AppContext;
1807
1808 fn deref(&self) -> &Self::Target {
1809 &self.app
1810 }
1811}
1812
1813impl<'a> std::ops::DerefMut for WindowContext<'a> {
1814 fn deref_mut(&mut self) -> &mut Self::Target {
1815 &mut self.app
1816 }
1817}
1818
1819impl<'a> Borrow<AppContext> for WindowContext<'a> {
1820 fn borrow(&self) -> &AppContext {
1821 &self.app
1822 }
1823}
1824
1825impl<'a> BorrowMut<AppContext> for WindowContext<'a> {
1826 fn borrow_mut(&mut self) -> &mut AppContext {
1827 &mut self.app
1828 }
1829}
1830
1831pub trait BorrowWindow: BorrowMut<Window> + BorrowMut<AppContext> {
1832 fn app_mut(&mut self) -> &mut AppContext {
1833 self.borrow_mut()
1834 }
1835
1836 fn app(&self) -> &AppContext {
1837 self.borrow()
1838 }
1839
1840 fn window(&self) -> &Window {
1841 self.borrow()
1842 }
1843
1844 fn window_mut(&mut self) -> &mut Window {
1845 self.borrow_mut()
1846 }
1847
1848 /// Pushes the given element id onto the global stack and invokes the given closure
1849 /// with a `GlobalElementId`, which disambiguates the given id in the context of its ancestor
1850 /// ids. Because elements are discarded and recreated on each frame, the `GlobalElementId` is
1851 /// used to associate state with identified elements across separate frames.
1852 fn with_element_id<R>(
1853 &mut self,
1854 id: Option<impl Into<ElementId>>,
1855 f: impl FnOnce(&mut Self) -> R,
1856 ) -> R {
1857 if let Some(id) = id.map(Into::into) {
1858 let window = self.window_mut();
1859 window.element_id_stack.push(id.into());
1860 let result = f(self);
1861 let window: &mut Window = self.borrow_mut();
1862 window.element_id_stack.pop();
1863 result
1864 } else {
1865 f(self)
1866 }
1867 }
1868
1869 /// Invoke the given function with the given content mask after intersecting it
1870 /// with the current mask.
1871 fn with_content_mask<R>(
1872 &mut self,
1873 mask: Option<ContentMask<Pixels>>,
1874 f: impl FnOnce(&mut Self) -> R,
1875 ) -> R {
1876 if let Some(mask) = mask {
1877 let mask = mask.intersect(&self.content_mask());
1878 self.window_mut()
1879 .current_frame
1880 .content_mask_stack
1881 .push(mask);
1882 let result = f(self);
1883 self.window_mut().current_frame.content_mask_stack.pop();
1884 result
1885 } else {
1886 f(self)
1887 }
1888 }
1889
1890 /// Invoke the given function with the content mask reset to that
1891 /// of the window.
1892 fn break_content_mask<R>(&mut self, f: impl FnOnce(&mut Self) -> R) -> R {
1893 let mask = ContentMask {
1894 bounds: Bounds {
1895 origin: Point::default(),
1896 size: self.window().viewport_size,
1897 },
1898 };
1899 self.window_mut()
1900 .current_frame
1901 .content_mask_stack
1902 .push(mask);
1903 let result = f(self);
1904 self.window_mut().current_frame.content_mask_stack.pop();
1905 result
1906 }
1907
1908 /// Update the global element offset relative to the current offset. This is used to implement
1909 /// scrolling.
1910 fn with_element_offset<R>(
1911 &mut self,
1912 offset: Point<Pixels>,
1913 f: impl FnOnce(&mut Self) -> R,
1914 ) -> R {
1915 if offset.is_zero() {
1916 return f(self);
1917 };
1918
1919 let abs_offset = self.element_offset() + offset;
1920 self.with_absolute_element_offset(abs_offset, f)
1921 }
1922
1923 /// Update the global element offset based on the given offset. This is used to implement
1924 /// drag handles and other manual painting of elements.
1925 fn with_absolute_element_offset<R>(
1926 &mut self,
1927 offset: Point<Pixels>,
1928 f: impl FnOnce(&mut Self) -> R,
1929 ) -> R {
1930 self.window_mut()
1931 .current_frame
1932 .element_offset_stack
1933 .push(offset);
1934 let result = f(self);
1935 self.window_mut().current_frame.element_offset_stack.pop();
1936 result
1937 }
1938
1939 /// Obtain the current element offset.
1940 fn element_offset(&self) -> Point<Pixels> {
1941 self.window()
1942 .current_frame
1943 .element_offset_stack
1944 .last()
1945 .copied()
1946 .unwrap_or_default()
1947 }
1948
1949 /// Update or intialize state for an element with the given id that lives across multiple
1950 /// frames. If an element with this id existed in the previous frame, its state will be passed
1951 /// to the given closure. The state returned by the closure will be stored so it can be referenced
1952 /// when drawing the next frame.
1953 fn with_element_state<S, R>(
1954 &mut self,
1955 id: ElementId,
1956 f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
1957 ) -> R
1958 where
1959 S: 'static,
1960 {
1961 self.with_element_id(Some(id), |cx| {
1962 let global_id = cx.window().element_id_stack.clone();
1963
1964 if let Some(any) = cx
1965 .window_mut()
1966 .current_frame
1967 .element_states
1968 .remove(&global_id)
1969 .or_else(|| {
1970 cx.window_mut()
1971 .previous_frame
1972 .element_states
1973 .remove(&global_id)
1974 })
1975 {
1976 let ElementStateBox {
1977 inner,
1978
1979 #[cfg(debug_assertions)]
1980 type_name
1981 } = any;
1982 // Using the extra inner option to avoid needing to reallocate a new box.
1983 let mut state_box = inner
1984 .downcast::<Option<S>>()
1985 .map_err(|_| {
1986 #[cfg(debug_assertions)]
1987 {
1988 anyhow!(
1989 "invalid element state type for id, requested_type {:?}, actual type: {:?}",
1990 std::any::type_name::<S>(),
1991 type_name
1992 )
1993 }
1994
1995 #[cfg(not(debug_assertions))]
1996 {
1997 anyhow!(
1998 "invalid element state type for id, requested_type {:?}",
1999 std::any::type_name::<S>(),
2000 )
2001 }
2002 })
2003 .unwrap();
2004
2005 // Actual: Option<AnyElement> <- View
2006 // Requested: () <- AnyElemet
2007 let state = state_box
2008 .take()
2009 .expect("element state is already on the stack");
2010 let (result, state) = f(Some(state), cx);
2011 state_box.replace(state);
2012 cx.window_mut()
2013 .current_frame
2014 .element_states
2015 .insert(global_id, ElementStateBox {
2016 inner: state_box,
2017
2018 #[cfg(debug_assertions)]
2019 type_name
2020 });
2021 result
2022 } else {
2023 let (result, state) = f(None, cx);
2024 cx.window_mut()
2025 .current_frame
2026 .element_states
2027 .insert(global_id,
2028 ElementStateBox {
2029 inner: Box::new(Some(state)),
2030
2031 #[cfg(debug_assertions)]
2032 type_name: std::any::type_name::<S>()
2033 }
2034
2035 );
2036 result
2037 }
2038 })
2039 }
2040
2041 /// Obtain the current content mask.
2042 fn content_mask(&self) -> ContentMask<Pixels> {
2043 self.window()
2044 .current_frame
2045 .content_mask_stack
2046 .last()
2047 .cloned()
2048 .unwrap_or_else(|| ContentMask {
2049 bounds: Bounds {
2050 origin: Point::default(),
2051 size: self.window().viewport_size,
2052 },
2053 })
2054 }
2055
2056 /// The size of an em for the base font of the application. Adjusting this value allows the
2057 /// UI to scale, just like zooming a web page.
2058 fn rem_size(&self) -> Pixels {
2059 self.window().rem_size
2060 }
2061}
2062
2063impl Borrow<Window> for WindowContext<'_> {
2064 fn borrow(&self) -> &Window {
2065 &self.window
2066 }
2067}
2068
2069impl BorrowMut<Window> for WindowContext<'_> {
2070 fn borrow_mut(&mut self) -> &mut Window {
2071 &mut self.window
2072 }
2073}
2074
2075impl<T> BorrowWindow for T where T: BorrowMut<AppContext> + BorrowMut<Window> {}
2076
2077pub struct ViewContext<'a, V> {
2078 window_cx: WindowContext<'a>,
2079 view: &'a View<V>,
2080}
2081
2082impl<V> Borrow<AppContext> for ViewContext<'_, V> {
2083 fn borrow(&self) -> &AppContext {
2084 &*self.window_cx.app
2085 }
2086}
2087
2088impl<V> BorrowMut<AppContext> for ViewContext<'_, V> {
2089 fn borrow_mut(&mut self) -> &mut AppContext {
2090 &mut *self.window_cx.app
2091 }
2092}
2093
2094impl<V> Borrow<Window> for ViewContext<'_, V> {
2095 fn borrow(&self) -> &Window {
2096 &*self.window_cx.window
2097 }
2098}
2099
2100impl<V> BorrowMut<Window> for ViewContext<'_, V> {
2101 fn borrow_mut(&mut self) -> &mut Window {
2102 &mut *self.window_cx.window
2103 }
2104}
2105
2106impl<'a, V: 'static> ViewContext<'a, V> {
2107 pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window, view: &'a View<V>) -> Self {
2108 Self {
2109 window_cx: WindowContext::new(app, window),
2110 view,
2111 }
2112 }
2113
2114 pub fn entity_id(&self) -> EntityId {
2115 self.view.entity_id()
2116 }
2117
2118 pub fn view(&self) -> &View<V> {
2119 self.view
2120 }
2121
2122 pub fn model(&self) -> &Model<V> {
2123 &self.view.model
2124 }
2125
2126 /// Access the underlying window context.
2127 pub fn window_context(&mut self) -> &mut WindowContext<'a> {
2128 &mut self.window_cx
2129 }
2130
2131 pub fn with_z_index<R>(&mut self, z_index: u32, f: impl FnOnce(&mut Self) -> R) -> R {
2132 self.window.current_frame.z_index_stack.push(z_index);
2133 let result = f(self);
2134 self.window.current_frame.z_index_stack.pop();
2135 result
2136 }
2137
2138 pub fn on_next_frame(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static)
2139 where
2140 V: 'static,
2141 {
2142 let view = self.view().clone();
2143 self.window_cx.on_next_frame(move |cx| view.update(cx, f));
2144 }
2145
2146 /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
2147 /// that are currently on the stack to be returned to the app.
2148 pub fn defer(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static) {
2149 let view = self.view().downgrade();
2150 self.window_cx.defer(move |cx| {
2151 view.update(cx, f).ok();
2152 });
2153 }
2154
2155 pub fn observe<V2, E>(
2156 &mut self,
2157 entity: &E,
2158 mut on_notify: impl FnMut(&mut V, E, &mut ViewContext<'_, V>) + 'static,
2159 ) -> Subscription
2160 where
2161 V2: 'static,
2162 V: 'static,
2163 E: Entity<V2>,
2164 {
2165 let view = self.view().downgrade();
2166 let entity_id = entity.entity_id();
2167 let entity = entity.downgrade();
2168 let window_handle = self.window.handle;
2169 let (subscription, activate) = self.app.observers.insert(
2170 entity_id,
2171 Box::new(move |cx| {
2172 window_handle
2173 .update(cx, |_, cx| {
2174 if let Some(handle) = E::upgrade_from(&entity) {
2175 view.update(cx, |this, cx| on_notify(this, handle, cx))
2176 .is_ok()
2177 } else {
2178 false
2179 }
2180 })
2181 .unwrap_or(false)
2182 }),
2183 );
2184 self.app.defer(move |_| activate());
2185 subscription
2186 }
2187
2188 pub fn subscribe<V2, E, Evt>(
2189 &mut self,
2190 entity: &E,
2191 mut on_event: impl FnMut(&mut V, E, &Evt, &mut ViewContext<'_, V>) + 'static,
2192 ) -> Subscription
2193 where
2194 V2: EventEmitter<Evt>,
2195 E: Entity<V2>,
2196 Evt: 'static,
2197 {
2198 let view = self.view().downgrade();
2199 let entity_id = entity.entity_id();
2200 let handle = entity.downgrade();
2201 let window_handle = self.window.handle;
2202 let (subscription, activate) = self.app.event_listeners.insert(
2203 entity_id,
2204 (
2205 TypeId::of::<Evt>(),
2206 Box::new(move |event, cx| {
2207 window_handle
2208 .update(cx, |_, cx| {
2209 if let Some(handle) = E::upgrade_from(&handle) {
2210 let event = event.downcast_ref().expect("invalid event type");
2211 view.update(cx, |this, cx| on_event(this, handle, event, cx))
2212 .is_ok()
2213 } else {
2214 false
2215 }
2216 })
2217 .unwrap_or(false)
2218 }),
2219 ),
2220 );
2221 self.app.defer(move |_| activate());
2222 subscription
2223 }
2224
2225 pub fn on_release(
2226 &mut self,
2227 on_release: impl FnOnce(&mut V, &mut WindowContext) + 'static,
2228 ) -> Subscription {
2229 let window_handle = self.window.handle;
2230 let (subscription, activate) = self.app.release_listeners.insert(
2231 self.view.model.entity_id,
2232 Box::new(move |this, cx| {
2233 let this = this.downcast_mut().expect("invalid entity type");
2234 let _ = window_handle.update(cx, |_, cx| on_release(this, cx));
2235 }),
2236 );
2237 activate();
2238 subscription
2239 }
2240
2241 pub fn observe_release<V2, E>(
2242 &mut self,
2243 entity: &E,
2244 mut on_release: impl FnMut(&mut V, &mut V2, &mut ViewContext<'_, V>) + 'static,
2245 ) -> Subscription
2246 where
2247 V: 'static,
2248 V2: 'static,
2249 E: Entity<V2>,
2250 {
2251 let view = self.view().downgrade();
2252 let entity_id = entity.entity_id();
2253 let window_handle = self.window.handle;
2254 let (subscription, activate) = self.app.release_listeners.insert(
2255 entity_id,
2256 Box::new(move |entity, cx| {
2257 let entity = entity.downcast_mut().expect("invalid entity type");
2258 let _ = window_handle.update(cx, |_, cx| {
2259 view.update(cx, |this, cx| on_release(this, entity, cx))
2260 });
2261 }),
2262 );
2263 activate();
2264 subscription
2265 }
2266
2267 pub fn notify(&mut self) {
2268 self.window_cx.notify();
2269 self.window_cx.app.push_effect(Effect::Notify {
2270 emitter: self.view.model.entity_id,
2271 });
2272 }
2273
2274 pub fn observe_window_bounds(
2275 &mut self,
2276 mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2277 ) -> Subscription {
2278 let view = self.view.downgrade();
2279 let (subscription, activate) = self.window.bounds_observers.insert(
2280 (),
2281 Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
2282 );
2283 activate();
2284 subscription
2285 }
2286
2287 pub fn observe_window_activation(
2288 &mut self,
2289 mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2290 ) -> Subscription {
2291 let view = self.view.downgrade();
2292 let (subscription, activate) = self.window.activation_observers.insert(
2293 (),
2294 Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
2295 );
2296 activate();
2297 subscription
2298 }
2299
2300 /// Register a listener to be called when the given focus handle receives focus.
2301 /// Unlike [on_focus_changed], returns a subscription and persists until the subscription
2302 /// is dropped.
2303 pub fn on_focus(
2304 &mut self,
2305 handle: &FocusHandle,
2306 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2307 ) -> Subscription {
2308 let view = self.view.downgrade();
2309 let focus_id = handle.id;
2310 let (subscription, activate) = self.window.focus_listeners.insert(
2311 (),
2312 Box::new(move |event, cx| {
2313 view.update(cx, |view, cx| {
2314 if event.focused.as_ref().map(|focused| focused.id) == Some(focus_id) {
2315 listener(view, cx)
2316 }
2317 })
2318 .is_ok()
2319 }),
2320 );
2321 self.app.defer(move |_| activate());
2322 subscription
2323 }
2324
2325 /// Register a listener to be called when the given focus handle or one of its descendants receives focus.
2326 /// Unlike [on_focus_changed], returns a subscription and persists until the subscription
2327 /// is dropped.
2328 pub fn on_focus_in(
2329 &mut self,
2330 handle: &FocusHandle,
2331 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2332 ) -> Subscription {
2333 let view = self.view.downgrade();
2334 let focus_id = handle.id;
2335 let (subscription, activate) = self.window.focus_listeners.insert(
2336 (),
2337 Box::new(move |event, cx| {
2338 view.update(cx, |view, cx| {
2339 if event
2340 .focused
2341 .as_ref()
2342 .map_or(false, |focused| focus_id.contains(focused.id, cx))
2343 {
2344 listener(view, cx)
2345 }
2346 })
2347 .is_ok()
2348 }),
2349 );
2350 self.app.defer(move |_| activate());
2351 subscription
2352 }
2353
2354 /// Register a listener to be called when the given focus handle loses focus.
2355 /// Unlike [on_focus_changed], returns a subscription and persists until the subscription
2356 /// is dropped.
2357 pub fn on_blur(
2358 &mut self,
2359 handle: &FocusHandle,
2360 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2361 ) -> Subscription {
2362 let view = self.view.downgrade();
2363 let focus_id = handle.id;
2364 let (subscription, activate) = self.window.focus_listeners.insert(
2365 (),
2366 Box::new(move |event, cx| {
2367 view.update(cx, |view, cx| {
2368 if event.blurred.as_ref().map(|blurred| blurred.id) == Some(focus_id) {
2369 listener(view, cx)
2370 }
2371 })
2372 .is_ok()
2373 }),
2374 );
2375 self.app.defer(move |_| activate());
2376 subscription
2377 }
2378
2379 /// Register a listener to be called when the given focus handle or one of its descendants loses focus.
2380 /// Unlike [on_focus_changed], returns a subscription and persists until the subscription
2381 /// is dropped.
2382 pub fn on_focus_out(
2383 &mut self,
2384 handle: &FocusHandle,
2385 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2386 ) -> Subscription {
2387 let view = self.view.downgrade();
2388 let focus_id = handle.id;
2389 let (subscription, activate) = self.window.focus_listeners.insert(
2390 (),
2391 Box::new(move |event, cx| {
2392 view.update(cx, |view, cx| {
2393 if event
2394 .blurred
2395 .as_ref()
2396 .map_or(false, |blurred| focus_id.contains(blurred.id, cx))
2397 {
2398 listener(view, cx)
2399 }
2400 })
2401 .is_ok()
2402 }),
2403 );
2404 self.app.defer(move |_| activate());
2405 subscription
2406 }
2407
2408 pub fn spawn<Fut, R>(
2409 &mut self,
2410 f: impl FnOnce(WeakView<V>, AsyncWindowContext) -> Fut,
2411 ) -> Task<R>
2412 where
2413 R: 'static,
2414 Fut: Future<Output = R> + 'static,
2415 {
2416 let view = self.view().downgrade();
2417 self.window_cx.spawn(|cx| f(view, cx))
2418 }
2419
2420 pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
2421 where
2422 G: 'static,
2423 {
2424 let mut global = self.app.lease_global::<G>();
2425 let result = f(&mut global, self);
2426 self.app.end_global_lease(global);
2427 result
2428 }
2429
2430 pub fn observe_global<G: 'static>(
2431 &mut self,
2432 mut f: impl FnMut(&mut V, &mut ViewContext<'_, V>) + 'static,
2433 ) -> Subscription {
2434 let window_handle = self.window.handle;
2435 let view = self.view().downgrade();
2436 let (subscription, activate) = self.global_observers.insert(
2437 TypeId::of::<G>(),
2438 Box::new(move |cx| {
2439 window_handle
2440 .update(cx, |_, cx| view.update(cx, |view, cx| f(view, cx)).is_ok())
2441 .unwrap_or(false)
2442 }),
2443 );
2444 self.app.defer(move |_| activate());
2445 subscription
2446 }
2447
2448 pub fn on_mouse_event<Event: 'static>(
2449 &mut self,
2450 handler: impl Fn(&mut V, &Event, DispatchPhase, &mut ViewContext<V>) + 'static,
2451 ) {
2452 let handle = self.view().clone();
2453 self.window_cx.on_mouse_event(move |event, phase, cx| {
2454 handle.update(cx, |view, cx| {
2455 handler(view, event, phase, cx);
2456 })
2457 });
2458 }
2459
2460 pub fn on_key_event<Event: 'static>(
2461 &mut self,
2462 handler: impl Fn(&mut V, &Event, DispatchPhase, &mut ViewContext<V>) + 'static,
2463 ) {
2464 let handle = self.view().clone();
2465 self.window_cx.on_key_event(move |event, phase, cx| {
2466 handle.update(cx, |view, cx| {
2467 handler(view, event, phase, cx);
2468 })
2469 });
2470 }
2471
2472 pub fn on_action(
2473 &mut self,
2474 action_type: TypeId,
2475 handler: impl Fn(&mut V, &dyn Any, DispatchPhase, &mut ViewContext<V>) + 'static,
2476 ) {
2477 let handle = self.view().clone();
2478 self.window_cx
2479 .on_action(action_type, move |action, phase, cx| {
2480 handle.update(cx, |view, cx| {
2481 handler(view, action, phase, cx);
2482 })
2483 });
2484 }
2485
2486 pub fn emit<Evt>(&mut self, event: Evt)
2487 where
2488 Evt: 'static,
2489 V: EventEmitter<Evt>,
2490 {
2491 let emitter = self.view.model.entity_id;
2492 self.app.push_effect(Effect::Emit {
2493 emitter,
2494 event_type: TypeId::of::<Evt>(),
2495 event: Box::new(event),
2496 });
2497 }
2498
2499 pub fn focus_self(&mut self)
2500 where
2501 V: FocusableView,
2502 {
2503 self.defer(|view, cx| view.focus_handle(cx).focus(cx))
2504 }
2505
2506 pub fn dismiss_self(&mut self)
2507 where
2508 V: ManagedView,
2509 {
2510 self.defer(|_, cx| cx.emit(DismissEvent))
2511 }
2512
2513 pub fn listener<E>(
2514 &self,
2515 f: impl Fn(&mut V, &E, &mut ViewContext<V>) + 'static,
2516 ) -> impl Fn(&E, &mut WindowContext) + 'static {
2517 let view = self.view().downgrade();
2518 move |e: &E, cx: &mut WindowContext| {
2519 view.update(cx, |view, cx| f(view, e, cx)).ok();
2520 }
2521 }
2522}
2523
2524impl<V> Context for ViewContext<'_, V> {
2525 type Result<U> = U;
2526
2527 fn build_model<T: 'static>(
2528 &mut self,
2529 build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
2530 ) -> Model<T> {
2531 self.window_cx.build_model(build_model)
2532 }
2533
2534 fn update_model<T: 'static, R>(
2535 &mut self,
2536 model: &Model<T>,
2537 update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
2538 ) -> R {
2539 self.window_cx.update_model(model, update)
2540 }
2541
2542 fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
2543 where
2544 F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
2545 {
2546 self.window_cx.update_window(window, update)
2547 }
2548
2549 fn read_model<T, R>(
2550 &self,
2551 handle: &Model<T>,
2552 read: impl FnOnce(&T, &AppContext) -> R,
2553 ) -> Self::Result<R>
2554 where
2555 T: 'static,
2556 {
2557 self.window_cx.read_model(handle, read)
2558 }
2559
2560 fn read_window<T, R>(
2561 &self,
2562 window: &WindowHandle<T>,
2563 read: impl FnOnce(View<T>, &AppContext) -> R,
2564 ) -> Result<R>
2565 where
2566 T: 'static,
2567 {
2568 self.window_cx.read_window(window, read)
2569 }
2570}
2571
2572impl<V: 'static> VisualContext for ViewContext<'_, V> {
2573 fn build_view<W: Render + 'static>(
2574 &mut self,
2575 build_view_state: impl FnOnce(&mut ViewContext<'_, W>) -> W,
2576 ) -> Self::Result<View<W>> {
2577 self.window_cx.build_view(build_view_state)
2578 }
2579
2580 fn update_view<V2: 'static, R>(
2581 &mut self,
2582 view: &View<V2>,
2583 update: impl FnOnce(&mut V2, &mut ViewContext<'_, V2>) -> R,
2584 ) -> Self::Result<R> {
2585 self.window_cx.update_view(view, update)
2586 }
2587
2588 fn replace_root_view<W>(
2589 &mut self,
2590 build_view: impl FnOnce(&mut ViewContext<'_, W>) -> W,
2591 ) -> Self::Result<View<W>>
2592 where
2593 W: 'static + Render,
2594 {
2595 self.window_cx.replace_root_view(build_view)
2596 }
2597
2598 fn focus_view<W: FocusableView>(&mut self, view: &View<W>) -> Self::Result<()> {
2599 self.window_cx.focus_view(view)
2600 }
2601
2602 fn dismiss_view<W: ManagedView>(&mut self, view: &View<W>) -> Self::Result<()> {
2603 self.window_cx.dismiss_view(view)
2604 }
2605}
2606
2607impl<'a, V> std::ops::Deref for ViewContext<'a, V> {
2608 type Target = WindowContext<'a>;
2609
2610 fn deref(&self) -> &Self::Target {
2611 &self.window_cx
2612 }
2613}
2614
2615impl<'a, V> std::ops::DerefMut for ViewContext<'a, V> {
2616 fn deref_mut(&mut self) -> &mut Self::Target {
2617 &mut self.window_cx
2618 }
2619}
2620
2621// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
2622slotmap::new_key_type! { pub struct WindowId; }
2623
2624impl WindowId {
2625 pub fn as_u64(&self) -> u64 {
2626 self.0.as_ffi()
2627 }
2628}
2629
2630#[derive(Deref, DerefMut)]
2631pub struct WindowHandle<V> {
2632 #[deref]
2633 #[deref_mut]
2634 pub(crate) any_handle: AnyWindowHandle,
2635 state_type: PhantomData<V>,
2636}
2637
2638impl<V: 'static + Render> WindowHandle<V> {
2639 pub fn new(id: WindowId) -> Self {
2640 WindowHandle {
2641 any_handle: AnyWindowHandle {
2642 id,
2643 state_type: TypeId::of::<V>(),
2644 },
2645 state_type: PhantomData,
2646 }
2647 }
2648
2649 pub fn root<C>(&self, cx: &mut C) -> Result<View<V>>
2650 where
2651 C: Context,
2652 {
2653 Flatten::flatten(cx.update_window(self.any_handle, |root_view, _| {
2654 root_view
2655 .downcast::<V>()
2656 .map_err(|_| anyhow!("the type of the window's root view has changed"))
2657 }))
2658 }
2659
2660 pub fn update<C, R>(
2661 &self,
2662 cx: &mut C,
2663 update: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
2664 ) -> Result<R>
2665 where
2666 C: Context,
2667 {
2668 cx.update_window(self.any_handle, |root_view, cx| {
2669 let view = root_view
2670 .downcast::<V>()
2671 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
2672 Ok(cx.update_view(&view, update))
2673 })?
2674 }
2675
2676 pub fn read<'a>(&self, cx: &'a AppContext) -> Result<&'a V> {
2677 let x = cx
2678 .windows
2679 .get(self.id)
2680 .and_then(|window| {
2681 window
2682 .as_ref()
2683 .and_then(|window| window.root_view.clone())
2684 .map(|root_view| root_view.downcast::<V>())
2685 })
2686 .ok_or_else(|| anyhow!("window not found"))?
2687 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
2688
2689 Ok(x.read(cx))
2690 }
2691
2692 pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &AppContext) -> R) -> Result<R>
2693 where
2694 C: Context,
2695 {
2696 cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
2697 }
2698
2699 pub fn root_view<C>(&self, cx: &C) -> Result<View<V>>
2700 where
2701 C: Context,
2702 {
2703 cx.read_window(self, |root_view, _cx| root_view.clone())
2704 }
2705
2706 pub fn is_active(&self, cx: &AppContext) -> Option<bool> {
2707 cx.windows
2708 .get(self.id)
2709 .and_then(|window| window.as_ref().map(|window| window.active))
2710 }
2711}
2712
2713impl<V> Copy for WindowHandle<V> {}
2714
2715impl<V> Clone for WindowHandle<V> {
2716 fn clone(&self) -> Self {
2717 WindowHandle {
2718 any_handle: self.any_handle,
2719 state_type: PhantomData,
2720 }
2721 }
2722}
2723
2724impl<V> PartialEq for WindowHandle<V> {
2725 fn eq(&self, other: &Self) -> bool {
2726 self.any_handle == other.any_handle
2727 }
2728}
2729
2730impl<V> Eq for WindowHandle<V> {}
2731
2732impl<V> Hash for WindowHandle<V> {
2733 fn hash<H: Hasher>(&self, state: &mut H) {
2734 self.any_handle.hash(state);
2735 }
2736}
2737
2738impl<V: 'static> Into<AnyWindowHandle> for WindowHandle<V> {
2739 fn into(self) -> AnyWindowHandle {
2740 self.any_handle
2741 }
2742}
2743
2744#[derive(Copy, Clone, PartialEq, Eq, Hash)]
2745pub struct AnyWindowHandle {
2746 pub(crate) id: WindowId,
2747 state_type: TypeId,
2748}
2749
2750impl AnyWindowHandle {
2751 pub fn window_id(&self) -> WindowId {
2752 self.id
2753 }
2754
2755 pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
2756 if TypeId::of::<T>() == self.state_type {
2757 Some(WindowHandle {
2758 any_handle: *self,
2759 state_type: PhantomData,
2760 })
2761 } else {
2762 None
2763 }
2764 }
2765
2766 pub fn update<C, R>(
2767 self,
2768 cx: &mut C,
2769 update: impl FnOnce(AnyView, &mut WindowContext<'_>) -> R,
2770 ) -> Result<R>
2771 where
2772 C: Context,
2773 {
2774 cx.update_window(self, update)
2775 }
2776
2777 pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(View<T>, &AppContext) -> R) -> Result<R>
2778 where
2779 C: Context,
2780 T: 'static,
2781 {
2782 let view = self
2783 .downcast::<T>()
2784 .context("the type of the window's root view has changed")?;
2785
2786 cx.read_window(&view, read)
2787 }
2788}
2789
2790#[cfg(any(test, feature = "test-support"))]
2791impl From<SmallVec<[u32; 16]>> for StackingOrder {
2792 fn from(small_vec: SmallVec<[u32; 16]>) -> Self {
2793 StackingOrder(small_vec)
2794 }
2795}
2796
2797#[derive(Clone, Debug, Eq, PartialEq, Hash)]
2798pub enum ElementId {
2799 View(EntityId),
2800 Integer(usize),
2801 Name(SharedString),
2802 FocusHandle(FocusId),
2803 NamedInteger(SharedString, usize),
2804}
2805
2806impl ElementId {
2807 pub(crate) fn from_entity_id(entity_id: EntityId) -> Self {
2808 ElementId::View(entity_id)
2809 }
2810}
2811
2812impl TryInto<SharedString> for ElementId {
2813 type Error = anyhow::Error;
2814
2815 fn try_into(self) -> anyhow::Result<SharedString> {
2816 if let ElementId::Name(name) = self {
2817 Ok(name)
2818 } else {
2819 Err(anyhow!("element id is not string"))
2820 }
2821 }
2822}
2823
2824impl From<usize> for ElementId {
2825 fn from(id: usize) -> Self {
2826 ElementId::Integer(id)
2827 }
2828}
2829
2830impl From<i32> for ElementId {
2831 fn from(id: i32) -> Self {
2832 Self::Integer(id as usize)
2833 }
2834}
2835
2836impl From<SharedString> for ElementId {
2837 fn from(name: SharedString) -> Self {
2838 ElementId::Name(name)
2839 }
2840}
2841
2842impl From<&'static str> for ElementId {
2843 fn from(name: &'static str) -> Self {
2844 ElementId::Name(name.into())
2845 }
2846}
2847
2848impl<'a> From<&'a FocusHandle> for ElementId {
2849 fn from(handle: &'a FocusHandle) -> Self {
2850 ElementId::FocusHandle(handle.id)
2851 }
2852}
2853
2854impl From<(&'static str, EntityId)> for ElementId {
2855 fn from((name, id): (&'static str, EntityId)) -> Self {
2856 ElementId::NamedInteger(name.into(), id.as_u64() as usize)
2857 }
2858}
2859
2860impl From<(&'static str, usize)> for ElementId {
2861 fn from((name, id): (&'static str, usize)) -> Self {
2862 ElementId::NamedInteger(name.into(), id)
2863 }
2864}