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