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