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