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