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