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