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