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