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