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