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