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