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