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