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