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 content_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 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.content_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 is_window_active(&self) -> bool {
649 self.window.active
650 }
651
652 pub fn zoom_window(&self) {
653 self.window.platform_window.zoom();
654 }
655
656 pub fn display(&self) -> Option<Rc<dyn PlatformDisplay>> {
657 self.platform
658 .displays()
659 .into_iter()
660 .find(|display| display.id() == self.window.display_id)
661 }
662
663 pub fn show_character_palette(&self) {
664 self.window.platform_window.show_character_palette();
665 }
666
667 /// The scale factor of the display associated with the window. For example, it could
668 /// return 2.0 for a "retina" display, indicating that each logical pixel should actually
669 /// be rendered as two pixels on screen.
670 pub fn scale_factor(&self) -> f32 {
671 self.window.scale_factor
672 }
673
674 /// The size of an em for the base font of the application. Adjusting this value allows the
675 /// UI to scale, just like zooming a web page.
676 pub fn rem_size(&self) -> Pixels {
677 self.window.rem_size
678 }
679
680 /// Sets the size of an em for the base font of the application. Adjusting this value allows the
681 /// UI to scale, just like zooming a web page.
682 pub fn set_rem_size(&mut self, rem_size: impl Into<Pixels>) {
683 self.window.rem_size = rem_size.into();
684 }
685
686 /// The line height associated with the current text style.
687 pub fn line_height(&self) -> Pixels {
688 let rem_size = self.rem_size();
689 let text_style = self.text_style();
690 text_style
691 .line_height
692 .to_pixels(text_style.font_size.into(), rem_size)
693 }
694
695 /// Call to prevent the default action of an event. Currently only used to prevent
696 /// parent elements from becoming focused on mouse down.
697 pub fn prevent_default(&mut self) {
698 self.window.default_prevented = true;
699 }
700
701 /// Obtain whether default has been prevented for the event currently being dispatched.
702 pub fn default_prevented(&self) -> bool {
703 self.window.default_prevented
704 }
705
706 /// Register a mouse event listener on the window for the current frame. The type of event
707 /// is determined by the first parameter of the given listener. When the next frame is rendered
708 /// the listener will be cleared.
709 ///
710 /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
711 /// a specific need to register a global listener.
712 pub fn on_mouse_event<Event: 'static>(
713 &mut self,
714 handler: impl Fn(&Event, DispatchPhase, &mut WindowContext) + 'static,
715 ) {
716 let order = self.window.current_frame.z_index_stack.clone();
717 self.window
718 .current_frame
719 .mouse_listeners
720 .entry(TypeId::of::<Event>())
721 .or_default()
722 .push((
723 order,
724 Box::new(move |event: &dyn Any, phase, cx| {
725 handler(event.downcast_ref().unwrap(), phase, cx)
726 }),
727 ))
728 }
729
730 /// The position of the mouse relative to the window.
731 pub fn mouse_position(&self) -> Point<Pixels> {
732 self.window.mouse_position
733 }
734
735 pub fn set_cursor_style(&mut self, style: CursorStyle) {
736 self.window.requested_cursor_style = Some(style)
737 }
738
739 /// Called during painting to invoke the given closure in a new stacking context. The given
740 /// z-index is interpreted relative to the previous call to `stack`.
741 pub fn stack<R>(&mut self, z_index: u32, f: impl FnOnce(&mut Self) -> R) -> R {
742 self.window.current_frame.z_index_stack.push(z_index);
743 let result = f(self);
744 self.window.current_frame.z_index_stack.pop();
745 result
746 }
747
748 /// Paint one or more drop shadows into the scene for the current frame at the current z-index.
749 pub fn paint_shadows(
750 &mut self,
751 bounds: Bounds<Pixels>,
752 corner_radii: Corners<Pixels>,
753 shadows: &[BoxShadow],
754 ) {
755 let scale_factor = self.scale_factor();
756 let content_mask = self.content_mask();
757 let window = &mut *self.window;
758 for shadow in shadows {
759 let mut shadow_bounds = bounds;
760 shadow_bounds.origin += shadow.offset;
761 shadow_bounds.dilate(shadow.spread_radius);
762 window.current_frame.scene_builder.insert(
763 &window.current_frame.z_index_stack,
764 Shadow {
765 order: 0,
766 bounds: shadow_bounds.scale(scale_factor),
767 content_mask: content_mask.scale(scale_factor),
768 corner_radii: corner_radii.scale(scale_factor),
769 color: shadow.color,
770 blur_radius: shadow.blur_radius.scale(scale_factor),
771 },
772 );
773 }
774 }
775
776 /// Paint one or more quads into the scene for the current frame at the current stacking context.
777 /// Quads are colored rectangular regions with an optional background, border, and corner radius.
778 pub fn paint_quad(
779 &mut self,
780 bounds: Bounds<Pixels>,
781 corner_radii: Corners<Pixels>,
782 background: impl Into<Hsla>,
783 border_widths: Edges<Pixels>,
784 border_color: impl Into<Hsla>,
785 ) {
786 let scale_factor = self.scale_factor();
787 let content_mask = self.content_mask();
788
789 let window = &mut *self.window;
790 window.current_frame.scene_builder.insert(
791 &window.current_frame.z_index_stack,
792 Quad {
793 order: 0,
794 bounds: bounds.scale(scale_factor),
795 content_mask: content_mask.scale(scale_factor),
796 background: background.into(),
797 border_color: border_color.into(),
798 corner_radii: corner_radii.scale(scale_factor),
799 border_widths: border_widths.scale(scale_factor),
800 },
801 );
802 }
803
804 /// Paint the given `Path` into the scene for the current frame at the current z-index.
805 pub fn paint_path(&mut self, mut path: Path<Pixels>, color: impl Into<Hsla>) {
806 let scale_factor = self.scale_factor();
807 let content_mask = self.content_mask();
808 path.content_mask = content_mask;
809 path.color = color.into();
810 let window = &mut *self.window;
811 window.current_frame.scene_builder.insert(
812 &window.current_frame.z_index_stack,
813 path.scale(scale_factor),
814 );
815 }
816
817 /// Paint an underline into the scene for the current frame at the current z-index.
818 pub fn paint_underline(
819 &mut self,
820 origin: Point<Pixels>,
821 width: Pixels,
822 style: &UnderlineStyle,
823 ) -> Result<()> {
824 let scale_factor = self.scale_factor();
825 let height = if style.wavy {
826 style.thickness * 3.
827 } else {
828 style.thickness
829 };
830 let bounds = Bounds {
831 origin,
832 size: size(width, height),
833 };
834 let content_mask = self.content_mask();
835 let window = &mut *self.window;
836 window.current_frame.scene_builder.insert(
837 &window.current_frame.z_index_stack,
838 Underline {
839 order: 0,
840 bounds: bounds.scale(scale_factor),
841 content_mask: content_mask.scale(scale_factor),
842 thickness: style.thickness.scale(scale_factor),
843 color: style.color.unwrap_or_default(),
844 wavy: style.wavy,
845 },
846 );
847 Ok(())
848 }
849
850 /// Paint a monochrome (non-emoji) glyph into the scene for the current frame at the current z-index.
851 /// The y component of the origin is the baseline of the glyph.
852 pub fn paint_glyph(
853 &mut self,
854 origin: Point<Pixels>,
855 font_id: FontId,
856 glyph_id: GlyphId,
857 font_size: Pixels,
858 color: Hsla,
859 ) -> Result<()> {
860 let scale_factor = self.scale_factor();
861 let glyph_origin = origin.scale(scale_factor);
862 let subpixel_variant = Point {
863 x: (glyph_origin.x.0.fract() * SUBPIXEL_VARIANTS as f32).floor() as u8,
864 y: (glyph_origin.y.0.fract() * SUBPIXEL_VARIANTS as f32).floor() as u8,
865 };
866 let params = RenderGlyphParams {
867 font_id,
868 glyph_id,
869 font_size,
870 subpixel_variant,
871 scale_factor,
872 is_emoji: false,
873 };
874
875 let raster_bounds = self.text_system().raster_bounds(¶ms)?;
876 if !raster_bounds.is_zero() {
877 let tile =
878 self.window
879 .sprite_atlas
880 .get_or_insert_with(¶ms.clone().into(), &mut || {
881 let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?;
882 Ok((size, Cow::Owned(bytes)))
883 })?;
884 let bounds = Bounds {
885 origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
886 size: tile.bounds.size.map(Into::into),
887 };
888 let content_mask = self.content_mask().scale(scale_factor);
889 let window = &mut *self.window;
890 window.current_frame.scene_builder.insert(
891 &window.current_frame.z_index_stack,
892 MonochromeSprite {
893 order: 0,
894 bounds,
895 content_mask,
896 color,
897 tile,
898 },
899 );
900 }
901 Ok(())
902 }
903
904 /// Paint an emoji glyph into the scene for the current frame at the current z-index.
905 /// The y component of the origin is the baseline of the glyph.
906 pub fn paint_emoji(
907 &mut self,
908 origin: Point<Pixels>,
909 font_id: FontId,
910 glyph_id: GlyphId,
911 font_size: Pixels,
912 ) -> Result<()> {
913 let scale_factor = self.scale_factor();
914 let glyph_origin = origin.scale(scale_factor);
915 let params = RenderGlyphParams {
916 font_id,
917 glyph_id,
918 font_size,
919 // We don't render emojis with subpixel variants.
920 subpixel_variant: Default::default(),
921 scale_factor,
922 is_emoji: true,
923 };
924
925 let raster_bounds = self.text_system().raster_bounds(¶ms)?;
926 if !raster_bounds.is_zero() {
927 let tile =
928 self.window
929 .sprite_atlas
930 .get_or_insert_with(¶ms.clone().into(), &mut || {
931 let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?;
932 Ok((size, Cow::Owned(bytes)))
933 })?;
934 let bounds = Bounds {
935 origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
936 size: tile.bounds.size.map(Into::into),
937 };
938 let content_mask = self.content_mask().scale(scale_factor);
939 let window = &mut *self.window;
940
941 window.current_frame.scene_builder.insert(
942 &window.current_frame.z_index_stack,
943 PolychromeSprite {
944 order: 0,
945 bounds,
946 corner_radii: Default::default(),
947 content_mask,
948 tile,
949 grayscale: false,
950 },
951 );
952 }
953 Ok(())
954 }
955
956 /// Paint a monochrome SVG into the scene for the current frame at the current stacking context.
957 pub fn paint_svg(
958 &mut self,
959 bounds: Bounds<Pixels>,
960 path: SharedString,
961 color: Hsla,
962 ) -> Result<()> {
963 let scale_factor = self.scale_factor();
964 let bounds = bounds.scale(scale_factor);
965 // Render the SVG at twice the size to get a higher quality result.
966 let params = RenderSvgParams {
967 path,
968 size: bounds
969 .size
970 .map(|pixels| DevicePixels::from((pixels.0 * 2.).ceil() as i32)),
971 };
972
973 let tile =
974 self.window
975 .sprite_atlas
976 .get_or_insert_with(¶ms.clone().into(), &mut || {
977 let bytes = self.svg_renderer.render(¶ms)?;
978 Ok((params.size, Cow::Owned(bytes)))
979 })?;
980 let content_mask = self.content_mask().scale(scale_factor);
981
982 let window = &mut *self.window;
983 window.current_frame.scene_builder.insert(
984 &window.current_frame.z_index_stack,
985 MonochromeSprite {
986 order: 0,
987 bounds,
988 content_mask,
989 color,
990 tile,
991 },
992 );
993
994 Ok(())
995 }
996
997 /// Paint an image into the scene for the current frame at the current z-index.
998 pub fn paint_image(
999 &mut self,
1000 bounds: Bounds<Pixels>,
1001 corner_radii: Corners<Pixels>,
1002 data: Arc<ImageData>,
1003 grayscale: bool,
1004 ) -> Result<()> {
1005 let scale_factor = self.scale_factor();
1006 let bounds = bounds.scale(scale_factor);
1007 let params = RenderImageParams { image_id: data.id };
1008
1009 let tile = self
1010 .window
1011 .sprite_atlas
1012 .get_or_insert_with(¶ms.clone().into(), &mut || {
1013 Ok((data.size(), Cow::Borrowed(data.as_bytes())))
1014 })?;
1015 let content_mask = self.content_mask().scale(scale_factor);
1016 let corner_radii = corner_radii.scale(scale_factor);
1017
1018 let window = &mut *self.window;
1019 window.current_frame.scene_builder.insert(
1020 &window.current_frame.z_index_stack,
1021 PolychromeSprite {
1022 order: 0,
1023 bounds,
1024 content_mask,
1025 corner_radii,
1026 tile,
1027 grayscale,
1028 },
1029 );
1030 Ok(())
1031 }
1032
1033 /// Draw pixels to the display for this window based on the contents of its scene.
1034 pub(crate) fn draw(&mut self) {
1035 let root_view = self.window.root_view.take().unwrap();
1036
1037 self.start_frame();
1038
1039 self.stack(0, |cx| {
1040 let available_space = cx.window.content_size.map(Into::into);
1041 root_view.draw(available_space, cx);
1042 });
1043
1044 if let Some(active_drag) = self.app.active_drag.take() {
1045 self.stack(1, |cx| {
1046 let offset = cx.mouse_position() - active_drag.cursor_offset;
1047 cx.with_element_offset(Some(offset), |cx| {
1048 let available_space =
1049 size(AvailableSpace::MinContent, AvailableSpace::MinContent);
1050 active_drag.view.draw(available_space, cx);
1051 cx.active_drag = Some(active_drag);
1052 });
1053 });
1054 } else if let Some(active_tooltip) = self.app.active_tooltip.take() {
1055 self.stack(1, |cx| {
1056 cx.with_element_offset(Some(active_tooltip.cursor_offset), |cx| {
1057 let available_space =
1058 size(AvailableSpace::MinContent, AvailableSpace::MinContent);
1059 active_tooltip.view.draw(available_space, cx);
1060 });
1061 });
1062 }
1063
1064 self.window.root_view = Some(root_view);
1065 let scene = self.window.current_frame.scene_builder.build();
1066
1067 self.window.platform_window.draw(scene);
1068 let cursor_style = self
1069 .window
1070 .requested_cursor_style
1071 .take()
1072 .unwrap_or(CursorStyle::Arrow);
1073 self.platform.set_cursor_style(cursor_style);
1074
1075 self.window.dirty = false;
1076 }
1077
1078 pub(crate) fn dispatch_stack(&mut self) -> Vec<KeyDispatchStackFrame> {
1079 let root_view = self.window.root_view.take().unwrap();
1080 let window = &mut *self.window;
1081 let mut spare_frame = Frame::default();
1082 mem::swap(&mut spare_frame, &mut window.previous_frame);
1083
1084 self.start_frame();
1085
1086 root_view.draw_dispatch_stack(self);
1087
1088 let window = &mut *self.window;
1089 // restore the old values of current and previous frame,
1090 // putting the new frame into spare_frame.
1091 mem::swap(&mut window.current_frame, &mut window.previous_frame);
1092 mem::swap(&mut spare_frame, &mut window.previous_frame);
1093 self.window.root_view = Some(root_view);
1094
1095 spare_frame.key_dispatch_stack
1096 }
1097
1098 /// Rotate the current frame and the previous frame, then clear the current frame.
1099 /// We repopulate all state in the current frame during each paint.
1100 fn start_frame(&mut self) {
1101 self.text_system().start_frame();
1102
1103 let window = &mut *self.window;
1104 mem::swap(&mut window.previous_frame, &mut window.current_frame);
1105 let frame = &mut window.current_frame;
1106 frame.element_states.clear();
1107 frame.key_matchers.clear();
1108 frame.mouse_listeners.values_mut().for_each(Vec::clear);
1109 frame.focus_listeners.clear();
1110 frame.key_dispatch_stack.clear();
1111 frame.focus_parents_by_child.clear();
1112 frame.freeze_key_dispatch_stack = false;
1113 }
1114
1115 /// Dispatch a mouse or keyboard event on the window.
1116 pub fn dispatch_event(&mut self, event: InputEvent) -> bool {
1117 // Handlers may set this to false by calling `stop_propagation`
1118 self.app.propagate_event = true;
1119 self.window.default_prevented = false;
1120
1121 let event = match event {
1122 // Track the mouse position with our own state, since accessing the platform
1123 // API for the mouse position can only occur on the main thread.
1124 InputEvent::MouseMove(mouse_move) => {
1125 self.window.mouse_position = mouse_move.position;
1126 InputEvent::MouseMove(mouse_move)
1127 }
1128 // Translate dragging and dropping of external files from the operating system
1129 // to internal drag and drop events.
1130 InputEvent::FileDrop(file_drop) => match file_drop {
1131 FileDropEvent::Entered { position, files } => {
1132 self.window.mouse_position = position;
1133 if self.active_drag.is_none() {
1134 self.active_drag = Some(AnyDrag {
1135 view: self.build_view(|_| files).into(),
1136 cursor_offset: position,
1137 });
1138 }
1139 InputEvent::MouseDown(MouseDownEvent {
1140 position,
1141 button: MouseButton::Left,
1142 click_count: 1,
1143 modifiers: Modifiers::default(),
1144 })
1145 }
1146 FileDropEvent::Pending { position } => {
1147 self.window.mouse_position = position;
1148 InputEvent::MouseMove(MouseMoveEvent {
1149 position,
1150 pressed_button: Some(MouseButton::Left),
1151 modifiers: Modifiers::default(),
1152 })
1153 }
1154 FileDropEvent::Submit { position } => {
1155 self.window.mouse_position = position;
1156 InputEvent::MouseUp(MouseUpEvent {
1157 button: MouseButton::Left,
1158 position,
1159 modifiers: Modifiers::default(),
1160 click_count: 1,
1161 })
1162 }
1163 FileDropEvent::Exited => InputEvent::MouseUp(MouseUpEvent {
1164 button: MouseButton::Left,
1165 position: Point::default(),
1166 modifiers: Modifiers::default(),
1167 click_count: 1,
1168 }),
1169 },
1170 _ => event,
1171 };
1172
1173 if let Some(any_mouse_event) = event.mouse_event() {
1174 if let Some(mut handlers) = self
1175 .window
1176 .current_frame
1177 .mouse_listeners
1178 .remove(&any_mouse_event.type_id())
1179 {
1180 // Because handlers may add other handlers, we sort every time.
1181 handlers.sort_by(|(a, _), (b, _)| a.cmp(b));
1182
1183 // Capture phase, events bubble from back to front. Handlers for this phase are used for
1184 // special purposes, such as detecting events outside of a given Bounds.
1185 for (_, handler) in &mut handlers {
1186 handler(any_mouse_event, DispatchPhase::Capture, self);
1187 if !self.app.propagate_event {
1188 break;
1189 }
1190 }
1191
1192 // Bubble phase, where most normal handlers do their work.
1193 if self.app.propagate_event {
1194 for (_, handler) in handlers.iter_mut().rev() {
1195 handler(any_mouse_event, DispatchPhase::Bubble, self);
1196 if !self.app.propagate_event {
1197 break;
1198 }
1199 }
1200 }
1201
1202 if self.app.propagate_event
1203 && any_mouse_event.downcast_ref::<MouseUpEvent>().is_some()
1204 {
1205 self.active_drag = None;
1206 }
1207
1208 // Just in case any handlers added new handlers, which is weird, but possible.
1209 handlers.extend(
1210 self.window
1211 .current_frame
1212 .mouse_listeners
1213 .get_mut(&any_mouse_event.type_id())
1214 .into_iter()
1215 .flat_map(|handlers| handlers.drain(..)),
1216 );
1217 self.window
1218 .current_frame
1219 .mouse_listeners
1220 .insert(any_mouse_event.type_id(), handlers);
1221 }
1222 } else if let Some(any_key_event) = event.keyboard_event() {
1223 let key_dispatch_stack = mem::take(&mut self.window.current_frame.key_dispatch_stack);
1224 let key_event_type = any_key_event.type_id();
1225 let mut context_stack = SmallVec::<[&DispatchContext; 16]>::new();
1226
1227 for (ix, frame) in key_dispatch_stack.iter().enumerate() {
1228 match frame {
1229 KeyDispatchStackFrame::Listener {
1230 event_type,
1231 listener,
1232 } => {
1233 if key_event_type == *event_type {
1234 if let Some(action) = listener(
1235 any_key_event,
1236 &context_stack,
1237 DispatchPhase::Capture,
1238 self,
1239 ) {
1240 self.dispatch_action_internal(action, &key_dispatch_stack[..ix]);
1241 }
1242 if !self.app.propagate_event {
1243 break;
1244 }
1245 }
1246 }
1247 KeyDispatchStackFrame::Context(context) => {
1248 context_stack.push(&context);
1249 }
1250 }
1251 }
1252
1253 if self.app.propagate_event {
1254 for (ix, frame) in key_dispatch_stack.iter().enumerate().rev() {
1255 match frame {
1256 KeyDispatchStackFrame::Listener {
1257 event_type,
1258 listener,
1259 } => {
1260 if key_event_type == *event_type {
1261 if let Some(action) = listener(
1262 any_key_event,
1263 &context_stack,
1264 DispatchPhase::Bubble,
1265 self,
1266 ) {
1267 self.dispatch_action_internal(
1268 action,
1269 &key_dispatch_stack[..ix],
1270 );
1271 }
1272
1273 if !self.app.propagate_event {
1274 break;
1275 }
1276 }
1277 }
1278 KeyDispatchStackFrame::Context(_) => {
1279 context_stack.pop();
1280 }
1281 }
1282 }
1283 }
1284
1285 drop(context_stack);
1286 self.window.current_frame.key_dispatch_stack = key_dispatch_stack;
1287 }
1288
1289 !self.app.propagate_event
1290 }
1291
1292 /// Attempt to map a keystroke to an action based on the keymap.
1293 pub fn match_keystroke(
1294 &mut self,
1295 element_id: &GlobalElementId,
1296 keystroke: &Keystroke,
1297 context_stack: &[&DispatchContext],
1298 ) -> KeyMatch {
1299 let key_match = self
1300 .window
1301 .current_frame
1302 .key_matchers
1303 .get_mut(element_id)
1304 .unwrap()
1305 .match_keystroke(keystroke, context_stack);
1306
1307 if key_match.is_some() {
1308 for matcher in self.window.current_frame.key_matchers.values_mut() {
1309 matcher.clear_pending();
1310 }
1311 }
1312
1313 key_match
1314 }
1315
1316 /// Register the given handler to be invoked whenever the global of the given type
1317 /// is updated.
1318 pub fn observe_global<G: 'static>(
1319 &mut self,
1320 f: impl Fn(&mut WindowContext<'_>) + 'static,
1321 ) -> Subscription {
1322 let window_handle = self.window.handle;
1323 self.global_observers.insert(
1324 TypeId::of::<G>(),
1325 Box::new(move |cx| window_handle.update(cx, |_, cx| f(cx)).is_ok()),
1326 )
1327 }
1328
1329 pub fn activate_window(&self) {
1330 self.window.platform_window.activate();
1331 }
1332
1333 pub fn prompt(
1334 &self,
1335 level: PromptLevel,
1336 msg: &str,
1337 answers: &[&str],
1338 ) -> oneshot::Receiver<usize> {
1339 self.window.platform_window.prompt(level, msg, answers)
1340 }
1341
1342 pub fn available_actions(&self) -> impl Iterator<Item = Box<dyn Action>> + '_ {
1343 let key_dispatch_stack = &self.window.previous_frame.key_dispatch_stack;
1344 key_dispatch_stack.iter().filter_map(|frame| {
1345 match frame {
1346 // todo!factor out a KeyDispatchStackFrame::Action
1347 KeyDispatchStackFrame::Listener {
1348 event_type,
1349 listener: _,
1350 } => {
1351 match build_action_from_type(event_type) {
1352 Ok(action) => Some(action),
1353 Err(err) => {
1354 dbg!(err);
1355 None
1356 } // we'll hit his if TypeId == KeyDown
1357 }
1358 }
1359 KeyDispatchStackFrame::Context(_) => None,
1360 }
1361 })
1362 }
1363
1364 pub(crate) fn dispatch_action_internal(
1365 &mut self,
1366 action: Box<dyn Action>,
1367 dispatch_stack: &[KeyDispatchStackFrame],
1368 ) {
1369 let action_type = action.as_any().type_id();
1370
1371 if let Some(mut global_listeners) = self.app.global_action_listeners.remove(&action_type) {
1372 for listener in &global_listeners {
1373 listener(action.as_ref(), DispatchPhase::Capture, self);
1374 if !self.app.propagate_event {
1375 break;
1376 }
1377 }
1378 global_listeners.extend(
1379 self.global_action_listeners
1380 .remove(&action_type)
1381 .unwrap_or_default(),
1382 );
1383 self.global_action_listeners
1384 .insert(action_type, global_listeners);
1385 }
1386
1387 if self.app.propagate_event {
1388 for stack_frame in dispatch_stack {
1389 if let KeyDispatchStackFrame::Listener {
1390 event_type,
1391 listener,
1392 } = stack_frame
1393 {
1394 if action_type == *event_type {
1395 listener(action.as_any(), &[], DispatchPhase::Capture, self);
1396 if !self.app.propagate_event {
1397 break;
1398 }
1399 }
1400 }
1401 }
1402 }
1403
1404 if self.app.propagate_event {
1405 for stack_frame in dispatch_stack.iter().rev() {
1406 if let KeyDispatchStackFrame::Listener {
1407 event_type,
1408 listener,
1409 } = stack_frame
1410 {
1411 if action_type == *event_type {
1412 self.app.propagate_event = false;
1413 listener(action.as_any(), &[], DispatchPhase::Bubble, self);
1414 if !self.app.propagate_event {
1415 break;
1416 }
1417 }
1418 }
1419 }
1420 }
1421
1422 if self.app.propagate_event {
1423 if let Some(mut global_listeners) =
1424 self.app.global_action_listeners.remove(&action_type)
1425 {
1426 for listener in global_listeners.iter().rev() {
1427 self.app.propagate_event = false;
1428 listener(action.as_ref(), DispatchPhase::Bubble, self);
1429 if !self.app.propagate_event {
1430 break;
1431 }
1432 }
1433 global_listeners.extend(
1434 self.global_action_listeners
1435 .remove(&action_type)
1436 .unwrap_or_default(),
1437 );
1438 self.global_action_listeners
1439 .insert(action_type, global_listeners);
1440 }
1441 }
1442 }
1443}
1444
1445impl Context for WindowContext<'_> {
1446 type Result<T> = T;
1447
1448 fn build_model<T>(
1449 &mut self,
1450 build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
1451 ) -> Model<T>
1452 where
1453 T: 'static,
1454 {
1455 let slot = self.app.entities.reserve();
1456 let model = build_model(&mut ModelContext::new(&mut *self.app, slot.downgrade()));
1457 self.entities.insert(slot, model)
1458 }
1459
1460 fn update_model<T: 'static, R>(
1461 &mut self,
1462 model: &Model<T>,
1463 update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
1464 ) -> R {
1465 let mut entity = self.entities.lease(model);
1466 let result = update(
1467 &mut *entity,
1468 &mut ModelContext::new(&mut *self.app, model.downgrade()),
1469 );
1470 self.entities.end_lease(entity);
1471 result
1472 }
1473
1474 fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
1475 where
1476 F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
1477 {
1478 if window == self.window.handle {
1479 let root_view = self.window.root_view.clone().unwrap();
1480 Ok(update(root_view, self))
1481 } else {
1482 window.update(self.app, update)
1483 }
1484 }
1485
1486 fn read_model<T, R>(
1487 &self,
1488 handle: &Model<T>,
1489 read: impl FnOnce(&T, &AppContext) -> R,
1490 ) -> Self::Result<R>
1491 where
1492 T: 'static,
1493 {
1494 let entity = self.entities.read(handle);
1495 read(&*entity, &*self.app)
1496 }
1497}
1498
1499impl VisualContext for WindowContext<'_> {
1500 fn build_view<V>(
1501 &mut self,
1502 build_view_state: impl FnOnce(&mut ViewContext<'_, V>) -> V,
1503 ) -> Self::Result<View<V>>
1504 where
1505 V: 'static + Render,
1506 {
1507 let slot = self.app.entities.reserve();
1508 let view = View {
1509 model: slot.clone(),
1510 };
1511 let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1512 let entity = build_view_state(&mut cx);
1513 cx.entities.insert(slot, entity);
1514
1515 cx.new_view_observers
1516 .clone()
1517 .retain(&TypeId::of::<V>(), |observer| {
1518 let any_view = AnyView::from(view.clone());
1519 (observer)(any_view, self);
1520 true
1521 });
1522
1523 view
1524 }
1525
1526 /// Update the given view. Prefer calling `View::update` instead, which calls this method.
1527 fn update_view<T: 'static, R>(
1528 &mut self,
1529 view: &View<T>,
1530 update: impl FnOnce(&mut T, &mut ViewContext<'_, T>) -> R,
1531 ) -> Self::Result<R> {
1532 let mut lease = self.app.entities.lease(&view.model);
1533 let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1534 let result = update(&mut *lease, &mut cx);
1535 cx.app.entities.end_lease(lease);
1536 result
1537 }
1538
1539 fn replace_root_view<V>(
1540 &mut self,
1541 build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
1542 ) -> Self::Result<View<V>>
1543 where
1544 V: Render,
1545 {
1546 let slot = self.app.entities.reserve();
1547 let view = View {
1548 model: slot.clone(),
1549 };
1550 let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1551 let entity = build_view(&mut cx);
1552 self.entities.insert(slot, entity);
1553 self.window.root_view = Some(view.clone().into());
1554 view
1555 }
1556}
1557
1558impl<'a> std::ops::Deref for WindowContext<'a> {
1559 type Target = AppContext;
1560
1561 fn deref(&self) -> &Self::Target {
1562 &self.app
1563 }
1564}
1565
1566impl<'a> std::ops::DerefMut for WindowContext<'a> {
1567 fn deref_mut(&mut self) -> &mut Self::Target {
1568 &mut self.app
1569 }
1570}
1571
1572impl<'a> Borrow<AppContext> for WindowContext<'a> {
1573 fn borrow(&self) -> &AppContext {
1574 &self.app
1575 }
1576}
1577
1578impl<'a> BorrowMut<AppContext> for WindowContext<'a> {
1579 fn borrow_mut(&mut self) -> &mut AppContext {
1580 &mut self.app
1581 }
1582}
1583
1584pub trait BorrowWindow: BorrowMut<Window> + BorrowMut<AppContext> {
1585 fn app_mut(&mut self) -> &mut AppContext {
1586 self.borrow_mut()
1587 }
1588
1589 fn window(&self) -> &Window {
1590 self.borrow()
1591 }
1592
1593 fn window_mut(&mut self) -> &mut Window {
1594 self.borrow_mut()
1595 }
1596
1597 /// Pushes the given element id onto the global stack and invokes the given closure
1598 /// with a `GlobalElementId`, which disambiguates the given id in the context of its ancestor
1599 /// ids. Because elements are discarded and recreated on each frame, the `GlobalElementId` is
1600 /// used to associate state with identified elements across separate frames.
1601 fn with_element_id<R>(
1602 &mut self,
1603 id: impl Into<ElementId>,
1604 f: impl FnOnce(GlobalElementId, &mut Self) -> R,
1605 ) -> R {
1606 let keymap = self.app_mut().keymap.clone();
1607 let window = self.window_mut();
1608 window.element_id_stack.push(id.into());
1609 let global_id = window.element_id_stack.clone();
1610
1611 if window.current_frame.key_matchers.get(&global_id).is_none() {
1612 window.current_frame.key_matchers.insert(
1613 global_id.clone(),
1614 window
1615 .previous_frame
1616 .key_matchers
1617 .remove(&global_id)
1618 .unwrap_or_else(|| KeyMatcher::new(keymap)),
1619 );
1620 }
1621
1622 let result = f(global_id, self);
1623 let window: &mut Window = self.borrow_mut();
1624 window.element_id_stack.pop();
1625 result
1626 }
1627
1628 /// Invoke the given function with the given content mask after intersecting it
1629 /// with the current mask.
1630 fn with_content_mask<R>(
1631 &mut self,
1632 mask: ContentMask<Pixels>,
1633 f: impl FnOnce(&mut Self) -> R,
1634 ) -> R {
1635 let mask = mask.intersect(&self.content_mask());
1636 self.window_mut()
1637 .current_frame
1638 .content_mask_stack
1639 .push(mask);
1640 let result = f(self);
1641 self.window_mut().current_frame.content_mask_stack.pop();
1642 result
1643 }
1644
1645 /// Update the global element offset based on the given offset. This is used to implement
1646 /// scrolling and position drag handles.
1647 fn with_element_offset<R>(
1648 &mut self,
1649 offset: Option<Point<Pixels>>,
1650 f: impl FnOnce(&mut Self) -> R,
1651 ) -> R {
1652 let Some(offset) = offset else {
1653 return f(self);
1654 };
1655
1656 let offset = self.element_offset() + offset;
1657 self.window_mut()
1658 .current_frame
1659 .element_offset_stack
1660 .push(offset);
1661 let result = f(self);
1662 self.window_mut().current_frame.element_offset_stack.pop();
1663 result
1664 }
1665
1666 /// Obtain the current element offset.
1667 fn element_offset(&self) -> Point<Pixels> {
1668 self.window()
1669 .current_frame
1670 .element_offset_stack
1671 .last()
1672 .copied()
1673 .unwrap_or_default()
1674 }
1675
1676 /// Update or intialize state for an element with the given id that lives across multiple
1677 /// frames. If an element with this id existed in the previous frame, its state will be passed
1678 /// to the given closure. The state returned by the closure will be stored so it can be referenced
1679 /// when drawing the next frame.
1680 fn with_element_state<S, R>(
1681 &mut self,
1682 id: ElementId,
1683 f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
1684 ) -> R
1685 where
1686 S: 'static,
1687 {
1688 self.with_element_id(id, |global_id, cx| {
1689 if let Some(any) = cx
1690 .window_mut()
1691 .current_frame
1692 .element_states
1693 .remove(&global_id)
1694 .or_else(|| {
1695 cx.window_mut()
1696 .previous_frame
1697 .element_states
1698 .remove(&global_id)
1699 })
1700 {
1701 // Using the extra inner option to avoid needing to reallocate a new box.
1702 let mut state_box = any
1703 .downcast::<Option<S>>()
1704 .expect("invalid element state type for id");
1705 let state = state_box
1706 .take()
1707 .expect("element state is already on the stack");
1708 let (result, state) = f(Some(state), cx);
1709 state_box.replace(state);
1710 cx.window_mut()
1711 .current_frame
1712 .element_states
1713 .insert(global_id, state_box);
1714 result
1715 } else {
1716 let (result, state) = f(None, cx);
1717 cx.window_mut()
1718 .current_frame
1719 .element_states
1720 .insert(global_id, Box::new(Some(state)));
1721 result
1722 }
1723 })
1724 }
1725
1726 /// Like `with_element_state`, but for situations where the element_id is optional. If the
1727 /// id is `None`, no state will be retrieved or stored.
1728 fn with_optional_element_state<S, R>(
1729 &mut self,
1730 element_id: Option<ElementId>,
1731 f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
1732 ) -> R
1733 where
1734 S: 'static,
1735 {
1736 if let Some(element_id) = element_id {
1737 self.with_element_state(element_id, f)
1738 } else {
1739 f(None, self).0
1740 }
1741 }
1742
1743 /// Obtain the current content mask.
1744 fn content_mask(&self) -> ContentMask<Pixels> {
1745 self.window()
1746 .current_frame
1747 .content_mask_stack
1748 .last()
1749 .cloned()
1750 .unwrap_or_else(|| ContentMask {
1751 bounds: Bounds {
1752 origin: Point::default(),
1753 size: self.window().content_size,
1754 },
1755 })
1756 }
1757
1758 /// The size of an em for the base font of the application. Adjusting this value allows the
1759 /// UI to scale, just like zooming a web page.
1760 fn rem_size(&self) -> Pixels {
1761 self.window().rem_size
1762 }
1763}
1764
1765impl Borrow<Window> for WindowContext<'_> {
1766 fn borrow(&self) -> &Window {
1767 &self.window
1768 }
1769}
1770
1771impl BorrowMut<Window> for WindowContext<'_> {
1772 fn borrow_mut(&mut self) -> &mut Window {
1773 &mut self.window
1774 }
1775}
1776
1777impl<T> BorrowWindow for T where T: BorrowMut<AppContext> + BorrowMut<Window> {}
1778
1779pub struct ViewContext<'a, V> {
1780 window_cx: WindowContext<'a>,
1781 view: &'a View<V>,
1782}
1783
1784impl<V> Borrow<AppContext> for ViewContext<'_, V> {
1785 fn borrow(&self) -> &AppContext {
1786 &*self.window_cx.app
1787 }
1788}
1789
1790impl<V> BorrowMut<AppContext> for ViewContext<'_, V> {
1791 fn borrow_mut(&mut self) -> &mut AppContext {
1792 &mut *self.window_cx.app
1793 }
1794}
1795
1796impl<V> Borrow<Window> for ViewContext<'_, V> {
1797 fn borrow(&self) -> &Window {
1798 &*self.window_cx.window
1799 }
1800}
1801
1802impl<V> BorrowMut<Window> for ViewContext<'_, V> {
1803 fn borrow_mut(&mut self) -> &mut Window {
1804 &mut *self.window_cx.window
1805 }
1806}
1807
1808impl<'a, V: 'static> ViewContext<'a, V> {
1809 pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window, view: &'a View<V>) -> Self {
1810 Self {
1811 window_cx: WindowContext::new(app, window),
1812 view,
1813 }
1814 }
1815
1816 // todo!("change this to return a reference");
1817 pub fn view(&self) -> View<V> {
1818 self.view.clone()
1819 }
1820
1821 pub fn model(&self) -> Model<V> {
1822 self.view.model.clone()
1823 }
1824
1825 /// Access the underlying window context.
1826 pub fn window_context(&mut self) -> &mut WindowContext<'a> {
1827 &mut self.window_cx
1828 }
1829
1830 pub fn with_z_index<R>(&mut self, z_index: u32, f: impl FnOnce(&mut Self) -> R) -> R {
1831 self.window.current_frame.z_index_stack.push(z_index);
1832 let result = f(self);
1833 self.window.current_frame.z_index_stack.pop();
1834 result
1835 }
1836
1837 pub fn on_next_frame(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static)
1838 where
1839 V: 'static,
1840 {
1841 let view = self.view();
1842 self.window_cx.on_next_frame(move |cx| view.update(cx, f));
1843 }
1844
1845 /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
1846 /// that are currently on the stack to be returned to the app.
1847 pub fn defer(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static) {
1848 let view = self.view().downgrade();
1849 self.window_cx.defer(move |cx| {
1850 view.update(cx, f).ok();
1851 });
1852 }
1853
1854 pub fn observe<V2, E>(
1855 &mut self,
1856 entity: &E,
1857 mut on_notify: impl FnMut(&mut V, E, &mut ViewContext<'_, V>) + 'static,
1858 ) -> Subscription
1859 where
1860 V2: 'static,
1861 V: 'static,
1862 E: Entity<V2>,
1863 {
1864 let view = self.view().downgrade();
1865 let entity_id = entity.entity_id();
1866 let entity = entity.downgrade();
1867 let window_handle = self.window.handle;
1868 self.app.observers.insert(
1869 entity_id,
1870 Box::new(move |cx| {
1871 window_handle
1872 .update(cx, |_, cx| {
1873 if let Some(handle) = E::upgrade_from(&entity) {
1874 view.update(cx, |this, cx| on_notify(this, handle, cx))
1875 .is_ok()
1876 } else {
1877 false
1878 }
1879 })
1880 .unwrap_or(false)
1881 }),
1882 )
1883 }
1884
1885 pub fn subscribe<V2, E, Evt>(
1886 &mut self,
1887 entity: &E,
1888 mut on_event: impl FnMut(&mut V, E, &Evt, &mut ViewContext<'_, V>) + 'static,
1889 ) -> Subscription
1890 where
1891 V2: EventEmitter<Evt>,
1892 E: Entity<V2>,
1893 Evt: 'static,
1894 {
1895 let view = self.view().downgrade();
1896 let entity_id = entity.entity_id();
1897 let handle = entity.downgrade();
1898 let window_handle = self.window.handle;
1899 self.app.event_listeners.insert(
1900 entity_id,
1901 (
1902 TypeId::of::<Evt>(),
1903 Box::new(move |event, cx| {
1904 window_handle
1905 .update(cx, |_, cx| {
1906 if let Some(handle) = E::upgrade_from(&handle) {
1907 let event = event.downcast_ref().expect("invalid event type");
1908 view.update(cx, |this, cx| on_event(this, handle, event, cx))
1909 .is_ok()
1910 } else {
1911 false
1912 }
1913 })
1914 .unwrap_or(false)
1915 }),
1916 ),
1917 )
1918 }
1919
1920 pub fn on_release(
1921 &mut self,
1922 on_release: impl FnOnce(&mut V, &mut WindowContext) + 'static,
1923 ) -> Subscription {
1924 let window_handle = self.window.handle;
1925 self.app.release_listeners.insert(
1926 self.view.model.entity_id,
1927 Box::new(move |this, cx| {
1928 let this = this.downcast_mut().expect("invalid entity type");
1929 let _ = window_handle.update(cx, |_, cx| on_release(this, cx));
1930 }),
1931 )
1932 }
1933
1934 pub fn observe_release<V2, E>(
1935 &mut self,
1936 entity: &E,
1937 mut on_release: impl FnMut(&mut V, &mut V2, &mut ViewContext<'_, V>) + 'static,
1938 ) -> Subscription
1939 where
1940 V: 'static,
1941 V2: 'static,
1942 E: Entity<V2>,
1943 {
1944 let view = self.view().downgrade();
1945 let entity_id = entity.entity_id();
1946 let window_handle = self.window.handle;
1947 self.app.release_listeners.insert(
1948 entity_id,
1949 Box::new(move |entity, cx| {
1950 let entity = entity.downcast_mut().expect("invalid entity type");
1951 let _ = window_handle.update(cx, |_, cx| {
1952 view.update(cx, |this, cx| on_release(this, entity, cx))
1953 });
1954 }),
1955 )
1956 }
1957
1958 pub fn notify(&mut self) {
1959 self.window_cx.notify();
1960 self.window_cx.app.push_effect(Effect::Notify {
1961 emitter: self.view.model.entity_id,
1962 });
1963 }
1964
1965 pub fn observe_window_bounds(
1966 &mut self,
1967 mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
1968 ) -> Subscription {
1969 let view = self.view.downgrade();
1970 self.window.bounds_observers.insert(
1971 (),
1972 Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
1973 )
1974 }
1975
1976 pub fn observe_window_activation(
1977 &mut self,
1978 mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
1979 ) -> Subscription {
1980 let view = self.view.downgrade();
1981 self.window.activation_observers.insert(
1982 (),
1983 Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
1984 )
1985 }
1986
1987 /// Register a listener to be called when the given focus handle receives focus.
1988 /// Unlike [on_focus_changed], returns a subscription and persists until the subscription
1989 /// is dropped.
1990 pub fn on_focus(
1991 &mut self,
1992 handle: &FocusHandle,
1993 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
1994 ) -> Subscription {
1995 let view = self.view.downgrade();
1996 let focus_id = handle.id;
1997 self.window.focus_listeners.insert(
1998 (),
1999 Box::new(move |event, cx| {
2000 view.update(cx, |view, cx| {
2001 if event.focused.as_ref().map(|focused| focused.id) == Some(focus_id) {
2002 listener(view, cx)
2003 }
2004 })
2005 .is_ok()
2006 }),
2007 )
2008 }
2009
2010 /// Register a listener to be called when the given focus handle or one of its descendants receives focus.
2011 /// Unlike [on_focus_changed], returns a subscription and persists until the subscription
2012 /// is dropped.
2013 pub fn on_focus_in(
2014 &mut self,
2015 handle: &FocusHandle,
2016 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2017 ) -> Subscription {
2018 let view = self.view.downgrade();
2019 let focus_id = handle.id;
2020 self.window.focus_listeners.insert(
2021 (),
2022 Box::new(move |event, cx| {
2023 view.update(cx, |view, cx| {
2024 if event
2025 .focused
2026 .as_ref()
2027 .map_or(false, |focused| focus_id.contains(focused.id, cx))
2028 {
2029 listener(view, cx)
2030 }
2031 })
2032 .is_ok()
2033 }),
2034 )
2035 }
2036
2037 /// Register a listener to be called when the given focus handle loses focus.
2038 /// Unlike [on_focus_changed], returns a subscription and persists until the subscription
2039 /// is dropped.
2040 pub fn on_blur(
2041 &mut self,
2042 handle: &FocusHandle,
2043 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2044 ) -> Subscription {
2045 let view = self.view.downgrade();
2046 let focus_id = handle.id;
2047 self.window.focus_listeners.insert(
2048 (),
2049 Box::new(move |event, cx| {
2050 view.update(cx, |view, cx| {
2051 if event.blurred.as_ref().map(|blurred| blurred.id) == Some(focus_id) {
2052 listener(view, cx)
2053 }
2054 })
2055 .is_ok()
2056 }),
2057 )
2058 }
2059
2060 /// Register a listener to be called when the given focus handle or one of its descendants loses focus.
2061 /// Unlike [on_focus_changed], returns a subscription and persists until the subscription
2062 /// is dropped.
2063 pub fn on_focus_out(
2064 &mut self,
2065 handle: &FocusHandle,
2066 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2067 ) -> Subscription {
2068 let view = self.view.downgrade();
2069 let focus_id = handle.id;
2070 self.window.focus_listeners.insert(
2071 (),
2072 Box::new(move |event, cx| {
2073 view.update(cx, |view, cx| {
2074 if event
2075 .blurred
2076 .as_ref()
2077 .map_or(false, |blurred| focus_id.contains(blurred.id, cx))
2078 {
2079 listener(view, cx)
2080 }
2081 })
2082 .is_ok()
2083 }),
2084 )
2085 }
2086
2087 /// Register a focus listener for the current frame only. It will be cleared
2088 /// on the next frame render. You should use this method only from within elements,
2089 /// and we may want to enforce that better via a different context type.
2090 // todo!() Move this to `FrameContext` to emphasize its individuality?
2091 pub fn on_focus_changed(
2092 &mut self,
2093 listener: impl Fn(&mut V, &FocusEvent, &mut ViewContext<V>) + 'static,
2094 ) {
2095 let handle = self.view().downgrade();
2096 self.window
2097 .current_frame
2098 .focus_listeners
2099 .push(Box::new(move |event, cx| {
2100 handle
2101 .update(cx, |view, cx| listener(view, event, cx))
2102 .log_err();
2103 }));
2104 }
2105
2106 pub fn with_key_listeners<R>(
2107 &mut self,
2108 key_listeners: impl IntoIterator<Item = (TypeId, KeyListener<V>)>,
2109 f: impl FnOnce(&mut Self) -> R,
2110 ) -> R {
2111 let old_stack_len = self.window.current_frame.key_dispatch_stack.len();
2112 if !self.window.current_frame.freeze_key_dispatch_stack {
2113 for (event_type, listener) in key_listeners {
2114 let handle = self.view().downgrade();
2115 let listener = Box::new(
2116 move |event: &dyn Any,
2117 context_stack: &[&DispatchContext],
2118 phase: DispatchPhase,
2119 cx: &mut WindowContext<'_>| {
2120 handle
2121 .update(cx, |view, cx| {
2122 listener(view, event, context_stack, phase, cx)
2123 })
2124 .log_err()
2125 .flatten()
2126 },
2127 );
2128 self.window.current_frame.key_dispatch_stack.push(
2129 KeyDispatchStackFrame::Listener {
2130 event_type,
2131 listener,
2132 },
2133 );
2134 }
2135 }
2136
2137 let result = f(self);
2138
2139 if !self.window.current_frame.freeze_key_dispatch_stack {
2140 self.window
2141 .current_frame
2142 .key_dispatch_stack
2143 .truncate(old_stack_len);
2144 }
2145
2146 result
2147 }
2148
2149 pub fn with_key_dispatch_context<R>(
2150 &mut self,
2151 context: DispatchContext,
2152 f: impl FnOnce(&mut Self) -> R,
2153 ) -> R {
2154 if context.is_empty() {
2155 return f(self);
2156 }
2157
2158 if !self.window.current_frame.freeze_key_dispatch_stack {
2159 self.window
2160 .current_frame
2161 .key_dispatch_stack
2162 .push(KeyDispatchStackFrame::Context(context));
2163 }
2164
2165 let result = f(self);
2166
2167 if !self.window.previous_frame.freeze_key_dispatch_stack {
2168 self.window.previous_frame.key_dispatch_stack.pop();
2169 }
2170
2171 result
2172 }
2173
2174 pub fn with_focus<R>(
2175 &mut self,
2176 focus_handle: FocusHandle,
2177 f: impl FnOnce(&mut Self) -> R,
2178 ) -> R {
2179 if let Some(parent_focus_id) = self.window.current_frame.focus_stack.last().copied() {
2180 self.window
2181 .current_frame
2182 .focus_parents_by_child
2183 .insert(focus_handle.id, parent_focus_id);
2184 }
2185 self.window.current_frame.focus_stack.push(focus_handle.id);
2186
2187 if Some(focus_handle.id) == self.window.focus {
2188 self.window.current_frame.freeze_key_dispatch_stack = true;
2189 }
2190
2191 let result = f(self);
2192
2193 self.window.current_frame.focus_stack.pop();
2194 result
2195 }
2196
2197 pub fn spawn<Fut, R>(
2198 &mut self,
2199 f: impl FnOnce(WeakView<V>, AsyncWindowContext) -> Fut,
2200 ) -> Task<R>
2201 where
2202 R: 'static,
2203 Fut: Future<Output = R> + 'static,
2204 {
2205 let view = self.view().downgrade();
2206 self.window_cx.spawn(|cx| f(view, cx))
2207 }
2208
2209 pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
2210 where
2211 G: 'static,
2212 {
2213 let mut global = self.app.lease_global::<G>();
2214 let result = f(&mut global, self);
2215 self.app.end_global_lease(global);
2216 result
2217 }
2218
2219 pub fn observe_global<G: 'static>(
2220 &mut self,
2221 f: impl Fn(&mut V, &mut ViewContext<'_, V>) + 'static,
2222 ) -> Subscription {
2223 let window_handle = self.window.handle;
2224 let view = self.view().downgrade();
2225 self.global_observers.insert(
2226 TypeId::of::<G>(),
2227 Box::new(move |cx| {
2228 window_handle
2229 .update(cx, |_, cx| view.update(cx, |view, cx| f(view, cx)).is_ok())
2230 .unwrap_or(false)
2231 }),
2232 )
2233 }
2234
2235 pub fn on_mouse_event<Event: 'static>(
2236 &mut self,
2237 handler: impl Fn(&mut V, &Event, DispatchPhase, &mut ViewContext<V>) + 'static,
2238 ) {
2239 let handle = self.view();
2240 self.window_cx.on_mouse_event(move |event, phase, cx| {
2241 handle.update(cx, |view, cx| {
2242 handler(view, event, phase, cx);
2243 })
2244 });
2245 }
2246
2247 /// Set an input handler, such as [ElementInputHandler], which interfaces with the
2248 /// platform to receive textual input with proper integration with concerns such
2249 /// as IME interactions.
2250 pub fn handle_input(
2251 &mut self,
2252 focus_handle: &FocusHandle,
2253 input_handler: impl PlatformInputHandler,
2254 ) {
2255 if focus_handle.is_focused(self) {
2256 self.window
2257 .platform_window
2258 .set_input_handler(Box::new(input_handler));
2259 }
2260 }
2261}
2262
2263impl<V> ViewContext<'_, V> {
2264 pub fn emit<Evt>(&mut self, event: Evt)
2265 where
2266 Evt: 'static,
2267 V: EventEmitter<Evt>,
2268 {
2269 let emitter = self.view.model.entity_id;
2270 self.app.push_effect(Effect::Emit {
2271 emitter,
2272 event_type: TypeId::of::<Evt>(),
2273 event: Box::new(event),
2274 });
2275 }
2276}
2277
2278impl<V> Context for ViewContext<'_, V> {
2279 type Result<U> = U;
2280
2281 fn build_model<T: 'static>(
2282 &mut self,
2283 build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
2284 ) -> Model<T> {
2285 self.window_cx.build_model(build_model)
2286 }
2287
2288 fn update_model<T: 'static, R>(
2289 &mut self,
2290 model: &Model<T>,
2291 update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
2292 ) -> R {
2293 self.window_cx.update_model(model, update)
2294 }
2295
2296 fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
2297 where
2298 F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
2299 {
2300 self.window_cx.update_window(window, update)
2301 }
2302
2303 fn read_model<T, R>(
2304 &self,
2305 handle: &Model<T>,
2306 read: impl FnOnce(&T, &AppContext) -> R,
2307 ) -> Self::Result<R>
2308 where
2309 T: 'static,
2310 {
2311 self.window_cx.read_model(handle, read)
2312 }
2313}
2314
2315impl<V: 'static> VisualContext for ViewContext<'_, V> {
2316 fn build_view<W: Render + 'static>(
2317 &mut self,
2318 build_view_state: impl FnOnce(&mut ViewContext<'_, W>) -> W,
2319 ) -> Self::Result<View<W>> {
2320 self.window_cx.build_view(build_view_state)
2321 }
2322
2323 fn update_view<V2: 'static, R>(
2324 &mut self,
2325 view: &View<V2>,
2326 update: impl FnOnce(&mut V2, &mut ViewContext<'_, V2>) -> R,
2327 ) -> Self::Result<R> {
2328 self.window_cx.update_view(view, update)
2329 }
2330
2331 fn replace_root_view<W>(
2332 &mut self,
2333 build_view: impl FnOnce(&mut ViewContext<'_, W>) -> W,
2334 ) -> Self::Result<View<W>>
2335 where
2336 W: Render,
2337 {
2338 self.window_cx.replace_root_view(build_view)
2339 }
2340}
2341
2342impl<'a, V> std::ops::Deref for ViewContext<'a, V> {
2343 type Target = WindowContext<'a>;
2344
2345 fn deref(&self) -> &Self::Target {
2346 &self.window_cx
2347 }
2348}
2349
2350impl<'a, V> std::ops::DerefMut for ViewContext<'a, V> {
2351 fn deref_mut(&mut self) -> &mut Self::Target {
2352 &mut self.window_cx
2353 }
2354}
2355
2356// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
2357slotmap::new_key_type! { pub struct WindowId; }
2358
2359impl WindowId {
2360 pub fn as_u64(&self) -> u64 {
2361 self.0.as_ffi()
2362 }
2363}
2364
2365#[derive(Deref, DerefMut)]
2366pub struct WindowHandle<V> {
2367 #[deref]
2368 #[deref_mut]
2369 pub(crate) any_handle: AnyWindowHandle,
2370 state_type: PhantomData<V>,
2371}
2372
2373impl<V: 'static + Render> WindowHandle<V> {
2374 pub fn new(id: WindowId) -> Self {
2375 WindowHandle {
2376 any_handle: AnyWindowHandle {
2377 id,
2378 state_type: TypeId::of::<V>(),
2379 },
2380 state_type: PhantomData,
2381 }
2382 }
2383
2384 pub fn update<C, R>(
2385 self,
2386 cx: &mut C,
2387 update: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
2388 ) -> Result<R>
2389 where
2390 C: Context,
2391 {
2392 cx.update_window(self.any_handle, |root_view, cx| {
2393 let view = root_view
2394 .downcast::<V>()
2395 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
2396 Ok(cx.update_view(&view, update))
2397 })?
2398 }
2399}
2400
2401impl<V> Copy for WindowHandle<V> {}
2402
2403impl<V> Clone for WindowHandle<V> {
2404 fn clone(&self) -> Self {
2405 WindowHandle {
2406 any_handle: self.any_handle,
2407 state_type: PhantomData,
2408 }
2409 }
2410}
2411
2412impl<V> PartialEq for WindowHandle<V> {
2413 fn eq(&self, other: &Self) -> bool {
2414 self.any_handle == other.any_handle
2415 }
2416}
2417
2418impl<V> Eq for WindowHandle<V> {}
2419
2420impl<V> Hash for WindowHandle<V> {
2421 fn hash<H: Hasher>(&self, state: &mut H) {
2422 self.any_handle.hash(state);
2423 }
2424}
2425
2426impl<V: 'static> Into<AnyWindowHandle> for WindowHandle<V> {
2427 fn into(self) -> AnyWindowHandle {
2428 self.any_handle
2429 }
2430}
2431
2432#[derive(Copy, Clone, PartialEq, Eq, Hash)]
2433pub struct AnyWindowHandle {
2434 pub(crate) id: WindowId,
2435 state_type: TypeId,
2436}
2437
2438impl AnyWindowHandle {
2439 pub fn window_id(&self) -> WindowId {
2440 self.id
2441 }
2442
2443 pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
2444 if TypeId::of::<T>() == self.state_type {
2445 Some(WindowHandle {
2446 any_handle: *self,
2447 state_type: PhantomData,
2448 })
2449 } else {
2450 None
2451 }
2452 }
2453
2454 pub fn update<C, R>(
2455 self,
2456 cx: &mut C,
2457 update: impl FnOnce(AnyView, &mut WindowContext<'_>) -> R,
2458 ) -> Result<R>
2459 where
2460 C: Context,
2461 {
2462 cx.update_window(self, update)
2463 }
2464}
2465
2466#[cfg(any(test, feature = "test-support"))]
2467impl From<SmallVec<[u32; 16]>> for StackingOrder {
2468 fn from(small_vec: SmallVec<[u32; 16]>) -> Self {
2469 StackingOrder(small_vec)
2470 }
2471}
2472
2473#[derive(Clone, Debug, Eq, PartialEq, Hash)]
2474pub enum ElementId {
2475 View(EntityId),
2476 Number(usize),
2477 Name(SharedString),
2478 FocusHandle(FocusId),
2479}
2480
2481impl From<EntityId> for ElementId {
2482 fn from(id: EntityId) -> Self {
2483 ElementId::View(id)
2484 }
2485}
2486
2487impl From<usize> for ElementId {
2488 fn from(id: usize) -> Self {
2489 ElementId::Number(id)
2490 }
2491}
2492
2493impl From<i32> for ElementId {
2494 fn from(id: i32) -> Self {
2495 Self::Number(id as usize)
2496 }
2497}
2498
2499impl From<SharedString> for ElementId {
2500 fn from(name: SharedString) -> Self {
2501 ElementId::Name(name)
2502 }
2503}
2504
2505impl From<&'static str> for ElementId {
2506 fn from(name: &'static str) -> Self {
2507 ElementId::Name(name.into())
2508 }
2509}
2510
2511impl<'a> From<&'a FocusHandle> for ElementId {
2512 fn from(handle: &'a FocusHandle) -> Self {
2513 ElementId::FocusHandle(handle.id)
2514 }
2515}