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