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