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