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