1#![deny(missing_docs)]
2
3use crate::{
4 px, size, transparent_black, Action, AnyDrag, AnyTooltip, AnyView, AppContext, Arena,
5 AsyncWindowContext, AvailableSpace, Bounds, BoxShadow, Context, Corners, CursorStyle,
6 DevicePixels, DispatchActionListener, DispatchNodeId, DispatchTree, DisplayId, Edges, Effect,
7 Entity, EntityId, EventEmitter, FileDropEvent, Flatten, FontId, GlobalElementId, GlyphId, Hsla,
8 ImageData, IsZero, KeyBinding, KeyContext, KeyDownEvent, KeyEvent, KeystrokeEvent, LayoutId,
9 Model, ModelContext, Modifiers, MonochromeSprite, MouseButton, MouseEvent, MouseMoveEvent,
10 MouseUpEvent, Path, Pixels, PlatformAtlas, PlatformDisplay, PlatformInput,
11 PlatformInputHandler, PlatformWindow, Point, PolychromeSprite, PromptLevel, Quad, Render,
12 RenderGlyphParams, RenderImageParams, RenderSvgParams, ScaledPixels, Scene, Shadow,
13 SharedString, Size, Style, SubscriberSet, Subscription, Surface, TaffyLayoutEngine, Task,
14 Underline, UnderlineStyle, View, VisualContext, WeakView, WindowBounds, WindowOptions,
15 SUBPIXEL_VARIANTS,
16};
17use anyhow::{anyhow, Context as _, Result};
18use collections::{FxHashMap, FxHashSet};
19use derive_more::{Deref, DerefMut};
20use futures::{
21 channel::{mpsc, oneshot},
22 StreamExt,
23};
24use media::core_video::CVImageBuffer;
25use parking_lot::RwLock;
26use slotmap::SlotMap;
27use smallvec::SmallVec;
28use std::{
29 any::{Any, TypeId},
30 borrow::{Borrow, BorrowMut, Cow},
31 cell::RefCell,
32 collections::hash_map::Entry,
33 fmt::Debug,
34 future::Future,
35 hash::{Hash, Hasher},
36 marker::PhantomData,
37 mem,
38 rc::Rc,
39 sync::{
40 atomic::{AtomicUsize, Ordering::SeqCst},
41 Arc,
42 },
43};
44use util::{post_inc, ResultExt};
45
46const ACTIVE_DRAG_Z_INDEX: u8 = 1;
47
48/// A global stacking order, which is created by stacking successive z-index values.
49/// Each z-index will always be interpreted in the context of its parent z-index.
50#[derive(Deref, DerefMut, Clone, Ord, PartialOrd, PartialEq, Eq, Default)]
51pub struct StackingOrder {
52 #[deref]
53 #[deref_mut]
54 context_stack: SmallVec<[u8; 64]>,
55 id: u32,
56}
57
58impl std::fmt::Debug for StackingOrder {
59 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
60 let mut stacks = self.context_stack.iter().peekable();
61 write!(f, "[({}): ", self.id)?;
62 while let Some(z_index) = stacks.next() {
63 write!(f, "{z_index}")?;
64 if stacks.peek().is_some() {
65 write!(f, "->")?;
66 }
67 }
68 write!(f, "]")?;
69 Ok(())
70 }
71}
72
73/// Represents the two different phases when dispatching events.
74#[derive(Default, Copy, Clone, Debug, Eq, PartialEq)]
75pub enum DispatchPhase {
76 /// After the capture phase comes the bubble phase, in which mouse event listeners are
77 /// invoked front to back and keyboard event listeners are invoked from the focused element
78 /// to the root of the element tree. This is the phase you'll most commonly want to use when
79 /// registering event listeners.
80 #[default]
81 Bubble,
82 /// During the initial capture phase, mouse event listeners are invoked back to front, and keyboard
83 /// listeners are invoked from the root of the tree downward toward the focused element. This phase
84 /// is used for special purposes such as clearing the "pressed" state for click events. If
85 /// you stop event propagation during this phase, you need to know what you're doing. Handlers
86 /// outside of the immediate region may rely on detecting non-local events during this phase.
87 Capture,
88}
89
90impl DispatchPhase {
91 /// Returns true if this represents the "bubble" phase.
92 pub fn bubble(self) -> bool {
93 self == DispatchPhase::Bubble
94 }
95
96 /// Returns true if this represents the "capture" phase.
97 pub fn capture(self) -> bool {
98 self == DispatchPhase::Capture
99 }
100}
101
102type AnyObserver = Box<dyn FnMut(&mut WindowContext) -> bool + 'static>;
103type AnyMouseListener = Box<dyn FnMut(&dyn Any, DispatchPhase, &mut WindowContext) + 'static>;
104type AnyWindowFocusListener = Box<dyn FnMut(&FocusEvent, &mut WindowContext) -> bool + 'static>;
105
106struct FocusEvent {
107 previous_focus_path: SmallVec<[FocusId; 8]>,
108 current_focus_path: SmallVec<[FocusId; 8]>,
109}
110
111slotmap::new_key_type! {
112 /// A globally unique identifier for a focusable element.
113 pub struct FocusId;
114}
115
116thread_local! {
117 pub(crate) static ELEMENT_ARENA: RefCell<Arena> = RefCell::new(Arena::new(4 * 1024 * 1024));
118}
119
120impl FocusId {
121 /// Obtains whether the element associated with this handle is currently focused.
122 pub fn is_focused(&self, cx: &WindowContext) -> bool {
123 cx.window.focus == Some(*self)
124 }
125
126 /// Obtains whether the element associated with this handle contains the focused
127 /// element or is itself focused.
128 pub fn contains_focused(&self, cx: &WindowContext) -> bool {
129 cx.focused()
130 .map_or(false, |focused| self.contains(focused.id, cx))
131 }
132
133 /// Obtains whether the element associated with this handle is contained within the
134 /// focused element or is itself focused.
135 pub fn within_focused(&self, cx: &WindowContext) -> bool {
136 let focused = cx.focused();
137 focused.map_or(false, |focused| focused.id.contains(*self, cx))
138 }
139
140 /// Obtains whether this handle contains the given handle in the most recently rendered frame.
141 pub(crate) fn contains(&self, other: Self, cx: &WindowContext) -> bool {
142 cx.window
143 .rendered_frame
144 .dispatch_tree
145 .focus_contains(*self, other)
146 }
147}
148
149/// A handle which can be used to track and manipulate the focused element in a window.
150pub struct FocusHandle {
151 pub(crate) id: FocusId,
152 handles: Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
153}
154
155impl std::fmt::Debug for FocusHandle {
156 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
157 f.write_fmt(format_args!("FocusHandle({:?})", self.id))
158 }
159}
160
161impl FocusHandle {
162 pub(crate) fn new(handles: &Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>) -> Self {
163 let id = handles.write().insert(AtomicUsize::new(1));
164 Self {
165 id,
166 handles: handles.clone(),
167 }
168 }
169
170 pub(crate) fn for_id(
171 id: FocusId,
172 handles: &Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
173 ) -> Option<Self> {
174 let lock = handles.read();
175 let ref_count = lock.get(id)?;
176 if ref_count.load(SeqCst) == 0 {
177 None
178 } else {
179 ref_count.fetch_add(1, SeqCst);
180 Some(Self {
181 id,
182 handles: handles.clone(),
183 })
184 }
185 }
186
187 /// Moves the focus to the element associated with this handle.
188 pub fn focus(&self, cx: &mut WindowContext) {
189 cx.focus(self)
190 }
191
192 /// Obtains whether the element associated with this handle is currently focused.
193 pub fn is_focused(&self, cx: &WindowContext) -> bool {
194 self.id.is_focused(cx)
195 }
196
197 /// Obtains whether the element associated with this handle contains the focused
198 /// element or is itself focused.
199 pub fn contains_focused(&self, cx: &WindowContext) -> bool {
200 self.id.contains_focused(cx)
201 }
202
203 /// Obtains whether the element associated with this handle is contained within the
204 /// focused element or is itself focused.
205 pub fn within_focused(&self, cx: &WindowContext) -> bool {
206 self.id.within_focused(cx)
207 }
208
209 /// Obtains whether this handle contains the given handle in the most recently rendered frame.
210 pub fn contains(&self, other: &Self, cx: &WindowContext) -> bool {
211 self.id.contains(other.id, cx)
212 }
213}
214
215impl Clone for FocusHandle {
216 fn clone(&self) -> Self {
217 Self::for_id(self.id, &self.handles).unwrap()
218 }
219}
220
221impl PartialEq for FocusHandle {
222 fn eq(&self, other: &Self) -> bool {
223 self.id == other.id
224 }
225}
226
227impl Eq for FocusHandle {}
228
229impl Drop for FocusHandle {
230 fn drop(&mut self) {
231 self.handles
232 .read()
233 .get(self.id)
234 .unwrap()
235 .fetch_sub(1, SeqCst);
236 }
237}
238
239/// FocusableView allows users of your view to easily
240/// focus it (using cx.focus_view(view))
241pub trait FocusableView: 'static + Render {
242 /// Returns the focus handle associated with this view.
243 fn focus_handle(&self, cx: &AppContext) -> FocusHandle;
244}
245
246/// ManagedView is a view (like a Modal, Popover, Menu, etc.)
247/// where the lifecycle of the view is handled by another view.
248pub trait ManagedView: FocusableView + EventEmitter<DismissEvent> {}
249
250impl<M: FocusableView + EventEmitter<DismissEvent>> ManagedView for M {}
251
252/// Emitted by implementers of [`ManagedView`] to indicate the view should be dismissed, such as when a view is presented as a modal.
253pub struct DismissEvent;
254
255// Holds the state for a specific window.
256#[doc(hidden)]
257pub struct Window {
258 pub(crate) handle: AnyWindowHandle,
259 pub(crate) removed: bool,
260 pub(crate) platform_window: Box<dyn PlatformWindow>,
261 display_id: DisplayId,
262 sprite_atlas: Arc<dyn PlatformAtlas>,
263 rem_size: Pixels,
264 viewport_size: Size<Pixels>,
265 layout_engine: Option<TaffyLayoutEngine>,
266 pub(crate) root_view: Option<AnyView>,
267 pub(crate) element_id_stack: GlobalElementId,
268 pub(crate) rendered_frame: Frame,
269 pub(crate) next_frame: Frame,
270 pub(crate) dirty_views: FxHashSet<EntityId>,
271 pub(crate) focus_handles: Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
272 focus_listeners: SubscriberSet<(), AnyWindowFocusListener>,
273 focus_lost_listeners: SubscriberSet<(), AnyObserver>,
274 default_prevented: bool,
275 mouse_position: Point<Pixels>,
276 modifiers: Modifiers,
277 scale_factor: f32,
278 bounds: WindowBounds,
279 bounds_observers: SubscriberSet<(), AnyObserver>,
280 active: bool,
281 pub(crate) dirty: bool,
282 pub(crate) refreshing: bool,
283 pub(crate) drawing: bool,
284 activation_observers: SubscriberSet<(), AnyObserver>,
285 pub(crate) focus: Option<FocusId>,
286 focus_enabled: bool,
287
288 #[cfg(any(test, feature = "test-support"))]
289 pub(crate) focus_invalidated: bool,
290}
291
292pub(crate) struct ElementStateBox {
293 inner: Box<dyn Any>,
294 parent_view_id: EntityId,
295 #[cfg(debug_assertions)]
296 type_name: &'static str,
297}
298
299struct RequestedInputHandler {
300 view_id: EntityId,
301 handler: Option<Box<dyn PlatformInputHandler>>,
302}
303
304struct TooltipRequest {
305 view_id: EntityId,
306 tooltip: AnyTooltip,
307}
308
309pub(crate) struct Frame {
310 focus: Option<FocusId>,
311 window_active: bool,
312 pub(crate) element_states: FxHashMap<GlobalElementId, ElementStateBox>,
313 mouse_listeners: FxHashMap<TypeId, Vec<(StackingOrder, EntityId, AnyMouseListener)>>,
314 pub(crate) dispatch_tree: DispatchTree,
315 pub(crate) scene: Scene,
316 pub(crate) depth_map: Vec<(StackingOrder, EntityId, Bounds<Pixels>)>,
317 pub(crate) z_index_stack: StackingOrder,
318 pub(crate) next_stacking_order_id: u32,
319 content_mask_stack: Vec<ContentMask<Pixels>>,
320 element_offset_stack: Vec<Point<Pixels>>,
321 requested_input_handler: Option<RequestedInputHandler>,
322 tooltip_request: Option<TooltipRequest>,
323 cursor_styles: FxHashMap<EntityId, CursorStyle>,
324 requested_cursor_style: Option<CursorStyle>,
325 pub(crate) view_stack: Vec<EntityId>,
326 pub(crate) reused_views: FxHashSet<EntityId>,
327}
328
329impl Frame {
330 fn new(dispatch_tree: DispatchTree) -> Self {
331 Frame {
332 focus: None,
333 window_active: false,
334 element_states: FxHashMap::default(),
335 mouse_listeners: FxHashMap::default(),
336 dispatch_tree,
337 scene: Scene::default(),
338 depth_map: Vec::new(),
339 z_index_stack: StackingOrder::default(),
340 next_stacking_order_id: 0,
341 content_mask_stack: Vec::new(),
342 element_offset_stack: Vec::new(),
343 requested_input_handler: None,
344 tooltip_request: None,
345 cursor_styles: FxHashMap::default(),
346 requested_cursor_style: None,
347 view_stack: Vec::new(),
348 reused_views: FxHashSet::default(),
349 }
350 }
351
352 fn clear(&mut self) {
353 self.element_states.clear();
354 self.mouse_listeners.values_mut().for_each(Vec::clear);
355 self.dispatch_tree.clear();
356 self.depth_map.clear();
357 self.next_stacking_order_id = 0;
358 self.reused_views.clear();
359 self.scene.clear();
360 self.requested_input_handler.take();
361 self.tooltip_request.take();
362 self.cursor_styles.clear();
363 self.requested_cursor_style.take();
364 debug_assert_eq!(self.view_stack.len(), 0);
365 }
366
367 fn focus_path(&self) -> SmallVec<[FocusId; 8]> {
368 self.focus
369 .map(|focus_id| self.dispatch_tree.focus_path(focus_id))
370 .unwrap_or_default()
371 }
372
373 fn finish(&mut self, prev_frame: &mut Self) {
374 // Reuse mouse listeners that didn't change since the last frame.
375 for (type_id, listeners) in &mut prev_frame.mouse_listeners {
376 let next_listeners = self.mouse_listeners.entry(*type_id).or_default();
377 for (order, view_id, listener) in listeners.drain(..) {
378 if self.reused_views.contains(&view_id) {
379 next_listeners.push((order, view_id, listener));
380 }
381 }
382 }
383
384 // Reuse entries in the depth map that didn't change since the last frame.
385 for (order, view_id, bounds) in prev_frame.depth_map.drain(..) {
386 if self.reused_views.contains(&view_id) {
387 match self
388 .depth_map
389 .binary_search_by(|(level, _, _)| order.cmp(level))
390 {
391 Ok(i) | Err(i) => self.depth_map.insert(i, (order, view_id, bounds)),
392 }
393 }
394 }
395
396 // Retain element states for views that didn't change since the last frame.
397 for (element_id, state) in prev_frame.element_states.drain() {
398 if self.reused_views.contains(&state.parent_view_id) {
399 self.element_states.entry(element_id).or_insert(state);
400 }
401 }
402
403 // Reuse geometry that didn't change since the last frame.
404 self.scene
405 .reuse_views(&self.reused_views, &mut prev_frame.scene);
406 self.scene.finish();
407 }
408}
409
410impl Window {
411 pub(crate) fn new(
412 handle: AnyWindowHandle,
413 options: WindowOptions,
414 cx: &mut AppContext,
415 ) -> Self {
416 let platform_window = cx.platform.open_window(handle, options);
417 let display_id = platform_window.display().id();
418 let sprite_atlas = platform_window.sprite_atlas();
419 let mouse_position = platform_window.mouse_position();
420 let modifiers = platform_window.modifiers();
421 let content_size = platform_window.content_size();
422 let scale_factor = platform_window.scale_factor();
423 let bounds = platform_window.bounds();
424
425 platform_window.on_request_frame(Box::new({
426 let mut cx = cx.to_async();
427 move || {
428 handle.update(&mut cx, |_, cx| cx.draw()).log_err();
429 }
430 }));
431 platform_window.on_resize(Box::new({
432 let mut cx = cx.to_async();
433 move |_, _| {
434 handle
435 .update(&mut cx, |_, cx| cx.window_bounds_changed())
436 .log_err();
437 }
438 }));
439 platform_window.on_moved(Box::new({
440 let mut cx = cx.to_async();
441 move || {
442 handle
443 .update(&mut cx, |_, cx| cx.window_bounds_changed())
444 .log_err();
445 }
446 }));
447 platform_window.on_active_status_change(Box::new({
448 let mut cx = cx.to_async();
449 move |active| {
450 handle
451 .update(&mut cx, |_, cx| {
452 cx.window.active = active;
453 cx.window
454 .activation_observers
455 .clone()
456 .retain(&(), |callback| callback(cx));
457 })
458 .log_err();
459 }
460 }));
461
462 platform_window.on_input({
463 let mut cx = cx.to_async();
464 Box::new(move |event| {
465 handle
466 .update(&mut cx, |_, cx| cx.dispatch_event(event))
467 .log_err()
468 .unwrap_or(false)
469 })
470 });
471
472 Window {
473 handle,
474 removed: false,
475 platform_window,
476 display_id,
477 sprite_atlas,
478 rem_size: px(16.),
479 viewport_size: content_size,
480 layout_engine: Some(TaffyLayoutEngine::new()),
481 root_view: None,
482 element_id_stack: GlobalElementId::default(),
483 rendered_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
484 next_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
485 dirty_views: FxHashSet::default(),
486 focus_handles: Arc::new(RwLock::new(SlotMap::with_key())),
487 focus_listeners: SubscriberSet::new(),
488 focus_lost_listeners: SubscriberSet::new(),
489 default_prevented: true,
490 mouse_position,
491 modifiers,
492 scale_factor,
493 bounds,
494 bounds_observers: SubscriberSet::new(),
495 active: false,
496 dirty: false,
497 refreshing: false,
498 drawing: false,
499 activation_observers: SubscriberSet::new(),
500 focus: None,
501 focus_enabled: true,
502
503 #[cfg(any(test, feature = "test-support"))]
504 focus_invalidated: false,
505 }
506 }
507}
508
509/// Indicates which region of the window is visible. Content falling outside of this mask will not be
510/// rendered. Currently, only rectangular content masks are supported, but we give the mask its own type
511/// to leave room to support more complex shapes in the future.
512#[derive(Clone, Debug, Default, PartialEq, Eq)]
513#[repr(C)]
514pub struct ContentMask<P: Clone + Default + Debug> {
515 /// The bounds
516 pub bounds: Bounds<P>,
517}
518
519impl ContentMask<Pixels> {
520 /// Scale the content mask's pixel units by the given scaling factor.
521 pub fn scale(&self, factor: f32) -> ContentMask<ScaledPixels> {
522 ContentMask {
523 bounds: self.bounds.scale(factor),
524 }
525 }
526
527 /// Intersect the content mask with the given content mask.
528 pub fn intersect(&self, other: &Self) -> Self {
529 let bounds = self.bounds.intersect(&other.bounds);
530 ContentMask { bounds }
531 }
532}
533
534/// Provides access to application state in the context of a single window. Derefs
535/// to an [`AppContext`], so you can also pass a [`WindowContext`] to any method that takes
536/// an [`AppContext`] and call any [`AppContext`] methods.
537pub struct WindowContext<'a> {
538 pub(crate) app: &'a mut AppContext,
539 pub(crate) window: &'a mut Window,
540}
541
542impl<'a> WindowContext<'a> {
543 pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window) -> Self {
544 Self { app, window }
545 }
546
547 /// Obtain a handle to the window that belongs to this context.
548 pub fn window_handle(&self) -> AnyWindowHandle {
549 self.window.handle
550 }
551
552 /// Mark the window as dirty, scheduling it to be redrawn on the next frame.
553 pub fn refresh(&mut self) {
554 if !self.window.drawing {
555 self.window.refreshing = true;
556 self.window.dirty = true;
557 }
558 }
559
560 /// Close this window.
561 pub fn remove_window(&mut self) {
562 self.window.removed = true;
563 }
564
565 /// Obtain a new [`FocusHandle`], which allows you to track and manipulate the keyboard focus
566 /// for elements rendered within this window.
567 pub fn focus_handle(&mut self) -> FocusHandle {
568 FocusHandle::new(&self.window.focus_handles)
569 }
570
571 /// Obtain the currently focused [`FocusHandle`]. If no elements are focused, returns `None`.
572 pub fn focused(&self) -> Option<FocusHandle> {
573 self.window
574 .focus
575 .and_then(|id| FocusHandle::for_id(id, &self.window.focus_handles))
576 }
577
578 /// Move focus to the element associated with the given [`FocusHandle`].
579 pub fn focus(&mut self, handle: &FocusHandle) {
580 if !self.window.focus_enabled || self.window.focus == Some(handle.id) {
581 return;
582 }
583
584 self.window.focus = Some(handle.id);
585 self.window
586 .rendered_frame
587 .dispatch_tree
588 .clear_pending_keystrokes();
589
590 #[cfg(any(test, feature = "test-support"))]
591 {
592 self.window.focus_invalidated = true;
593 }
594
595 self.refresh();
596 }
597
598 /// Remove focus from all elements within this context's window.
599 pub fn blur(&mut self) {
600 if !self.window.focus_enabled {
601 return;
602 }
603
604 self.window.focus = None;
605 self.refresh();
606 }
607
608 /// Blur the window and don't allow anything in it to be focused again.
609 pub fn disable_focus(&mut self) {
610 self.blur();
611 self.window.focus_enabled = false;
612 }
613
614 /// Dispatch the given action on the currently focused element.
615 pub fn dispatch_action(&mut self, action: Box<dyn Action>) {
616 let focus_handle = self.focused();
617
618 self.defer(move |cx| {
619 let node_id = focus_handle
620 .and_then(|handle| {
621 cx.window
622 .rendered_frame
623 .dispatch_tree
624 .focusable_node_id(handle.id)
625 })
626 .unwrap_or_else(|| cx.window.rendered_frame.dispatch_tree.root_node_id());
627
628 cx.propagate_event = true;
629 cx.dispatch_action_on_node(node_id, action);
630 })
631 }
632
633 pub(crate) fn dispatch_keystroke_observers(
634 &mut self,
635 event: &dyn Any,
636 action: Option<Box<dyn Action>>,
637 ) {
638 let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() else {
639 return;
640 };
641
642 self.keystroke_observers
643 .clone()
644 .retain(&(), move |callback| {
645 (callback)(
646 &KeystrokeEvent {
647 keystroke: key_down_event.keystroke.clone(),
648 action: action.as_ref().map(|action| action.boxed_clone()),
649 },
650 self,
651 );
652 true
653 });
654 }
655
656 pub(crate) fn clear_pending_keystrokes(&mut self) {
657 self.window
658 .rendered_frame
659 .dispatch_tree
660 .clear_pending_keystrokes();
661 self.window
662 .next_frame
663 .dispatch_tree
664 .clear_pending_keystrokes();
665 }
666
667 /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
668 /// that are currently on the stack to be returned to the app.
669 pub fn defer(&mut self, f: impl FnOnce(&mut WindowContext) + 'static) {
670 let handle = self.window.handle;
671 self.app.defer(move |cx| {
672 handle.update(cx, |_, cx| f(cx)).ok();
673 });
674 }
675
676 /// Subscribe to events emitted by a model or view.
677 /// The entity to which you're subscribing must implement the [`EventEmitter`] trait.
678 /// The callback will be invoked a handle to the emitting entity (either a [`View`] or [`Model`]), the event, and a window context for the current window.
679 pub fn subscribe<Emitter, E, Evt>(
680 &mut self,
681 entity: &E,
682 mut on_event: impl FnMut(E, &Evt, &mut WindowContext<'_>) + 'static,
683 ) -> Subscription
684 where
685 Emitter: EventEmitter<Evt>,
686 E: Entity<Emitter>,
687 Evt: 'static,
688 {
689 let entity_id = entity.entity_id();
690 let entity = entity.downgrade();
691 let window_handle = self.window.handle;
692 let (subscription, activate) = self.app.event_listeners.insert(
693 entity_id,
694 (
695 TypeId::of::<Evt>(),
696 Box::new(move |event, cx| {
697 window_handle
698 .update(cx, |_, cx| {
699 if let Some(handle) = E::upgrade_from(&entity) {
700 let event = event.downcast_ref().expect("invalid event type");
701 on_event(handle, event, cx);
702 true
703 } else {
704 false
705 }
706 })
707 .unwrap_or(false)
708 }),
709 ),
710 );
711 self.app.defer(move |_| activate());
712 subscription
713 }
714
715 /// Create an `AsyncWindowContext`, which has a static lifetime and can be held across
716 /// await points in async code.
717 pub fn to_async(&self) -> AsyncWindowContext {
718 AsyncWindowContext::new(self.app.to_async(), self.window.handle)
719 }
720
721 /// Schedule the given closure to be run directly after the current frame is rendered.
722 pub fn on_next_frame(&mut self, callback: impl FnOnce(&mut WindowContext) + 'static) {
723 let handle = self.window.handle;
724 let display_id = self.window.display_id;
725
726 let mut frame_consumers = std::mem::take(&mut self.app.frame_consumers);
727 if let Entry::Vacant(e) = frame_consumers.entry(display_id) {
728 let (tx, mut rx) = mpsc::unbounded::<()>();
729 self.platform.set_display_link_output_callback(
730 display_id,
731 Box::new(move |_current_time, _output_time| _ = tx.unbounded_send(())),
732 );
733
734 let consumer_task = self.app.spawn(|cx| async move {
735 while rx.next().await.is_some() {
736 cx.update(|cx| {
737 for callback in cx
738 .next_frame_callbacks
739 .get_mut(&display_id)
740 .unwrap()
741 .drain(..)
742 .collect::<SmallVec<[_; 32]>>()
743 {
744 callback(cx);
745 }
746 })
747 .ok();
748
749 // Flush effects, then stop the display link if no new next_frame_callbacks have been added.
750
751 cx.update(|cx| {
752 if cx.next_frame_callbacks.is_empty() {
753 cx.platform.stop_display_link(display_id);
754 }
755 })
756 .ok();
757 }
758 });
759 e.insert(consumer_task);
760 }
761 debug_assert!(self.app.frame_consumers.is_empty());
762 self.app.frame_consumers = frame_consumers;
763
764 if self.next_frame_callbacks.is_empty() {
765 self.platform.start_display_link(display_id);
766 }
767
768 self.next_frame_callbacks
769 .entry(display_id)
770 .or_default()
771 .push(Box::new(move |cx: &mut AppContext| {
772 cx.update_window(handle, |_root_view, cx| callback(cx)).ok();
773 }));
774 }
775
776 /// Spawn the future returned by the given closure on the application thread pool.
777 /// The closure is provided a handle to the current window and an `AsyncWindowContext` for
778 /// use within your future.
779 pub fn spawn<Fut, R>(&mut self, f: impl FnOnce(AsyncWindowContext) -> Fut) -> Task<R>
780 where
781 R: 'static,
782 Fut: Future<Output = R> + 'static,
783 {
784 self.app
785 .spawn(|app| f(AsyncWindowContext::new(app, self.window.handle)))
786 }
787
788 /// Update the global of the given type. The given closure is given simultaneous mutable
789 /// access both to the global and the context.
790 pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
791 where
792 G: 'static,
793 {
794 let mut global = self.app.lease_global::<G>();
795 let result = f(&mut global, self);
796 self.app.end_global_lease(global);
797 result
798 }
799
800 #[must_use]
801 /// Add a node to the layout tree for the current frame. Takes the `Style` of the element for which
802 /// layout is being requested, along with the layout ids of any children. This method is called during
803 /// calls to the `Element::layout` trait method and enables any element to participate in layout.
804 pub fn request_layout(
805 &mut self,
806 style: &Style,
807 children: impl IntoIterator<Item = LayoutId>,
808 ) -> LayoutId {
809 self.app.layout_id_buffer.clear();
810 self.app.layout_id_buffer.extend(children);
811 let rem_size = self.rem_size();
812
813 self.window.layout_engine.as_mut().unwrap().request_layout(
814 style,
815 rem_size,
816 &self.app.layout_id_buffer,
817 )
818 }
819
820 /// Add a node to the layout tree for the current frame. Instead of taking a `Style` and children,
821 /// this variant takes a function that is invoked during layout so you can use arbitrary logic to
822 /// determine the element's size. One place this is used internally is when measuring text.
823 ///
824 /// The given closure is invoked at layout time with the known dimensions and available space and
825 /// returns a `Size`.
826 pub fn request_measured_layout<
827 F: FnMut(Size<Option<Pixels>>, Size<AvailableSpace>, &mut WindowContext) -> Size<Pixels>
828 + 'static,
829 >(
830 &mut self,
831 style: Style,
832 measure: F,
833 ) -> LayoutId {
834 let rem_size = self.rem_size();
835 self.window
836 .layout_engine
837 .as_mut()
838 .unwrap()
839 .request_measured_layout(style, rem_size, measure)
840 }
841
842 pub(crate) fn layout_style(&self, layout_id: LayoutId) -> Option<&Style> {
843 self.window
844 .layout_engine
845 .as_ref()
846 .unwrap()
847 .requested_style(layout_id)
848 }
849
850 /// Compute the layout for the given id within the given available space.
851 /// This method is called for its side effect, typically by the framework prior to painting.
852 /// After calling it, you can request the bounds of the given layout node id or any descendant.
853 pub fn compute_layout(&mut self, layout_id: LayoutId, available_space: Size<AvailableSpace>) {
854 let mut layout_engine = self.window.layout_engine.take().unwrap();
855 layout_engine.compute_layout(layout_id, available_space, self);
856 self.window.layout_engine = Some(layout_engine);
857 }
858
859 /// Obtain the bounds computed for the given LayoutId relative to the window. This method should not
860 /// be invoked until the paint phase begins, and will usually be invoked by GPUI itself automatically
861 /// in order to pass your element its `Bounds` automatically.
862 pub fn layout_bounds(&mut self, layout_id: LayoutId) -> Bounds<Pixels> {
863 let mut bounds = self
864 .window
865 .layout_engine
866 .as_mut()
867 .unwrap()
868 .layout_bounds(layout_id)
869 .map(Into::into);
870 bounds.origin += self.element_offset();
871 bounds
872 }
873
874 fn window_bounds_changed(&mut self) {
875 self.window.scale_factor = self.window.platform_window.scale_factor();
876 self.window.viewport_size = self.window.platform_window.content_size();
877 self.window.bounds = self.window.platform_window.bounds();
878 self.window.display_id = self.window.platform_window.display().id();
879 self.refresh();
880
881 self.window
882 .bounds_observers
883 .clone()
884 .retain(&(), |callback| callback(self));
885 }
886
887 /// Returns the bounds of the current window in the global coordinate space, which could span across multiple displays.
888 pub fn window_bounds(&self) -> WindowBounds {
889 self.window.bounds
890 }
891
892 /// Returns the size of the drawable area within the window.
893 pub fn viewport_size(&self) -> Size<Pixels> {
894 self.window.viewport_size
895 }
896
897 /// Returns whether this window is focused by the operating system (receiving key events).
898 pub fn is_window_active(&self) -> bool {
899 self.window.active
900 }
901
902 /// Toggle zoom on the window.
903 pub fn zoom_window(&self) {
904 self.window.platform_window.zoom();
905 }
906
907 /// Update the window's title at the platform level.
908 pub fn set_window_title(&mut self, title: &str) {
909 self.window.platform_window.set_title(title);
910 }
911
912 /// Mark the window as dirty at the platform level.
913 pub fn set_window_edited(&mut self, edited: bool) {
914 self.window.platform_window.set_edited(edited);
915 }
916
917 /// Determine the display on which the window is visible.
918 pub fn display(&self) -> Option<Rc<dyn PlatformDisplay>> {
919 self.platform
920 .displays()
921 .into_iter()
922 .find(|display| display.id() == self.window.display_id)
923 }
924
925 /// Show the platform character palette.
926 pub fn show_character_palette(&self) {
927 self.window.platform_window.show_character_palette();
928 }
929
930 /// The scale factor of the display associated with the window. For example, it could
931 /// return 2.0 for a "retina" display, indicating that each logical pixel should actually
932 /// be rendered as two pixels on screen.
933 pub fn scale_factor(&self) -> f32 {
934 self.window.scale_factor
935 }
936
937 /// The size of an em for the base font of the application. Adjusting this value allows the
938 /// UI to scale, just like zooming a web page.
939 pub fn rem_size(&self) -> Pixels {
940 self.window.rem_size
941 }
942
943 /// Sets the size of an em for the base font of the application. Adjusting this value allows the
944 /// UI to scale, just like zooming a web page.
945 pub fn set_rem_size(&mut self, rem_size: impl Into<Pixels>) {
946 self.window.rem_size = rem_size.into();
947 }
948
949 /// The line height associated with the current text style.
950 pub fn line_height(&self) -> Pixels {
951 let rem_size = self.rem_size();
952 let text_style = self.text_style();
953 text_style
954 .line_height
955 .to_pixels(text_style.font_size, rem_size)
956 }
957
958 /// Call to prevent the default action of an event. Currently only used to prevent
959 /// parent elements from becoming focused on mouse down.
960 pub fn prevent_default(&mut self) {
961 self.window.default_prevented = true;
962 }
963
964 /// Obtain whether default has been prevented for the event currently being dispatched.
965 pub fn default_prevented(&self) -> bool {
966 self.window.default_prevented
967 }
968
969 /// Register a mouse event listener on the window for the next frame. The type of event
970 /// is determined by the first parameter of the given listener. When the next frame is rendered
971 /// the listener will be cleared.
972 pub fn on_mouse_event<Event: MouseEvent>(
973 &mut self,
974 mut handler: impl FnMut(&Event, DispatchPhase, &mut WindowContext) + 'static,
975 ) {
976 let view_id = self.parent_view_id();
977 let order = self.window.next_frame.z_index_stack.clone();
978 self.window
979 .next_frame
980 .mouse_listeners
981 .entry(TypeId::of::<Event>())
982 .or_default()
983 .push((
984 order,
985 view_id,
986 Box::new(
987 move |event: &dyn Any, phase: DispatchPhase, cx: &mut WindowContext<'_>| {
988 handler(event.downcast_ref().unwrap(), phase, cx)
989 },
990 ),
991 ))
992 }
993
994 /// Register a key event listener on the window for the next frame. The type of event
995 /// is determined by the first parameter of the given listener. When the next frame is rendered
996 /// the listener will be cleared.
997 ///
998 /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
999 /// a specific need to register a global listener.
1000 pub fn on_key_event<Event: KeyEvent>(
1001 &mut self,
1002 listener: impl Fn(&Event, DispatchPhase, &mut WindowContext) + 'static,
1003 ) {
1004 self.window.next_frame.dispatch_tree.on_key_event(Rc::new(
1005 move |event: &dyn Any, phase, cx: &mut WindowContext<'_>| {
1006 if let Some(event) = event.downcast_ref::<Event>() {
1007 listener(event, phase, cx)
1008 }
1009 },
1010 ));
1011 }
1012
1013 /// Register an action listener on the window for the next frame. The type of action
1014 /// is determined by the first parameter of the given listener. When the next frame is rendered
1015 /// the listener will be cleared.
1016 ///
1017 /// This is a fairly low-level method, so prefer using action handlers on elements unless you have
1018 /// a specific need to register a global listener.
1019 pub fn on_action(
1020 &mut self,
1021 action_type: TypeId,
1022 listener: impl Fn(&dyn Any, DispatchPhase, &mut WindowContext) + 'static,
1023 ) {
1024 self.window
1025 .next_frame
1026 .dispatch_tree
1027 .on_action(action_type, Rc::new(listener));
1028 }
1029
1030 /// Determine whether the given action is available along the dispatch path to the currently focused element.
1031 pub fn is_action_available(&self, action: &dyn Action) -> bool {
1032 let target = self
1033 .focused()
1034 .and_then(|focused_handle| {
1035 self.window
1036 .rendered_frame
1037 .dispatch_tree
1038 .focusable_node_id(focused_handle.id)
1039 })
1040 .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
1041 self.window
1042 .rendered_frame
1043 .dispatch_tree
1044 .is_action_available(action, target)
1045 }
1046
1047 /// The position of the mouse relative to the window.
1048 pub fn mouse_position(&self) -> Point<Pixels> {
1049 self.window.mouse_position
1050 }
1051
1052 /// The current state of the keyboard's modifiers
1053 pub fn modifiers(&self) -> Modifiers {
1054 self.window.modifiers
1055 }
1056
1057 /// Update the cursor style at the platform level.
1058 pub fn set_cursor_style(&mut self, style: CursorStyle) {
1059 let view_id = self.parent_view_id();
1060 self.window.next_frame.cursor_styles.insert(view_id, style);
1061 self.window.next_frame.requested_cursor_style = Some(style);
1062 }
1063
1064 /// Set a tooltip to be rendered for the upcoming frame
1065 pub fn set_tooltip(&mut self, tooltip: AnyTooltip) {
1066 let view_id = self.parent_view_id();
1067 self.window.next_frame.tooltip_request = Some(TooltipRequest { view_id, tooltip });
1068 }
1069
1070 /// Called during painting to track which z-index is on top at each pixel position
1071 pub fn add_opaque_layer(&mut self, bounds: Bounds<Pixels>) {
1072 let stacking_order = self.window.next_frame.z_index_stack.clone();
1073 let view_id = self.parent_view_id();
1074 let depth_map = &mut self.window.next_frame.depth_map;
1075 match depth_map.binary_search_by(|(level, _, _)| stacking_order.cmp(level)) {
1076 Ok(i) | Err(i) => depth_map.insert(i, (stacking_order, view_id, bounds)),
1077 }
1078 }
1079
1080 /// Returns true if there is no opaque layer containing the given point
1081 /// on top of the given level. Layers whose level is an extension of the
1082 /// level are not considered to be on top of the level.
1083 pub fn was_top_layer(&self, point: &Point<Pixels>, level: &StackingOrder) -> bool {
1084 for (opaque_level, _, bounds) in self.window.rendered_frame.depth_map.iter() {
1085 if level >= opaque_level {
1086 break;
1087 }
1088
1089 if bounds.contains(point) && !opaque_level.starts_with(level) {
1090 return false;
1091 }
1092 }
1093 true
1094 }
1095
1096 pub(crate) fn was_top_layer_under_active_drag(
1097 &self,
1098 point: &Point<Pixels>,
1099 level: &StackingOrder,
1100 ) -> bool {
1101 for (opaque_level, _, bounds) in self.window.rendered_frame.depth_map.iter() {
1102 if level >= opaque_level {
1103 break;
1104 }
1105 if opaque_level.starts_with(&[ACTIVE_DRAG_Z_INDEX]) {
1106 continue;
1107 }
1108
1109 if bounds.contains(point) && !opaque_level.starts_with(level) {
1110 return false;
1111 }
1112 }
1113 true
1114 }
1115
1116 /// Called during painting to get the current stacking order.
1117 pub fn stacking_order(&self) -> &StackingOrder {
1118 &self.window.next_frame.z_index_stack
1119 }
1120
1121 /// Paint one or more drop shadows into the scene for the next frame at the current z-index.
1122 pub fn paint_shadows(
1123 &mut self,
1124 bounds: Bounds<Pixels>,
1125 corner_radii: Corners<Pixels>,
1126 shadows: &[BoxShadow],
1127 ) {
1128 let scale_factor = self.scale_factor();
1129 let content_mask = self.content_mask();
1130 let view_id = self.parent_view_id();
1131 let window = &mut *self.window;
1132 for shadow in shadows {
1133 let mut shadow_bounds = bounds;
1134 shadow_bounds.origin += shadow.offset;
1135 shadow_bounds.dilate(shadow.spread_radius);
1136 window.next_frame.scene.insert(
1137 &window.next_frame.z_index_stack,
1138 Shadow {
1139 view_id: view_id.into(),
1140 layer_id: 0,
1141 order: 0,
1142 bounds: shadow_bounds.scale(scale_factor),
1143 content_mask: content_mask.scale(scale_factor),
1144 corner_radii: corner_radii.scale(scale_factor),
1145 color: shadow.color,
1146 blur_radius: shadow.blur_radius.scale(scale_factor),
1147 },
1148 );
1149 }
1150 }
1151
1152 /// Paint one or more quads into the scene for the next frame at the current stacking context.
1153 /// Quads are colored rectangular regions with an optional background, border, and corner radius.
1154 /// see [`fill`], [`outline`], and [`quad`] to construct this type.
1155 pub fn paint_quad(&mut self, quad: PaintQuad) {
1156 let scale_factor = self.scale_factor();
1157 let content_mask = self.content_mask();
1158 let view_id = self.parent_view_id();
1159
1160 let window = &mut *self.window;
1161 window.next_frame.scene.insert(
1162 &window.next_frame.z_index_stack,
1163 Quad {
1164 view_id: view_id.into(),
1165 layer_id: 0,
1166 order: 0,
1167 bounds: quad.bounds.scale(scale_factor),
1168 content_mask: content_mask.scale(scale_factor),
1169 background: quad.background,
1170 border_color: quad.border_color,
1171 corner_radii: quad.corner_radii.scale(scale_factor),
1172 border_widths: quad.border_widths.scale(scale_factor),
1173 },
1174 );
1175 }
1176
1177 /// Paint the given `Path` into the scene for the next frame at the current z-index.
1178 pub fn paint_path(&mut self, mut path: Path<Pixels>, color: impl Into<Hsla>) {
1179 let scale_factor = self.scale_factor();
1180 let content_mask = self.content_mask();
1181 let view_id = self.parent_view_id();
1182
1183 path.content_mask = content_mask;
1184 path.color = color.into();
1185 path.view_id = view_id.into();
1186 let window = &mut *self.window;
1187 window
1188 .next_frame
1189 .scene
1190 .insert(&window.next_frame.z_index_stack, path.scale(scale_factor));
1191 }
1192
1193 /// Paint an underline into the scene for the next frame at the current z-index.
1194 pub fn paint_underline(
1195 &mut self,
1196 origin: Point<Pixels>,
1197 width: Pixels,
1198 style: &UnderlineStyle,
1199 ) {
1200 let scale_factor = self.scale_factor();
1201 let height = if style.wavy {
1202 style.thickness * 3.
1203 } else {
1204 style.thickness
1205 };
1206 let bounds = Bounds {
1207 origin,
1208 size: size(width, height),
1209 };
1210 let content_mask = self.content_mask();
1211 let view_id = self.parent_view_id();
1212
1213 let window = &mut *self.window;
1214 window.next_frame.scene.insert(
1215 &window.next_frame.z_index_stack,
1216 Underline {
1217 view_id: view_id.into(),
1218 layer_id: 0,
1219 order: 0,
1220 bounds: bounds.scale(scale_factor),
1221 content_mask: content_mask.scale(scale_factor),
1222 thickness: style.thickness.scale(scale_factor),
1223 color: style.color.unwrap_or_default(),
1224 wavy: style.wavy,
1225 },
1226 );
1227 }
1228
1229 /// Paint a monochrome (non-emoji) glyph into the scene for the next frame at the current z-index.
1230 /// The y component of the origin is the baseline of the glyph.
1231 pub fn paint_glyph(
1232 &mut self,
1233 origin: Point<Pixels>,
1234 font_id: FontId,
1235 glyph_id: GlyphId,
1236 font_size: Pixels,
1237 color: Hsla,
1238 ) -> Result<()> {
1239 let scale_factor = self.scale_factor();
1240 let glyph_origin = origin.scale(scale_factor);
1241 let subpixel_variant = Point {
1242 x: (glyph_origin.x.0.fract() * SUBPIXEL_VARIANTS as f32).floor() as u8,
1243 y: (glyph_origin.y.0.fract() * SUBPIXEL_VARIANTS as f32).floor() as u8,
1244 };
1245 let params = RenderGlyphParams {
1246 font_id,
1247 glyph_id,
1248 font_size,
1249 subpixel_variant,
1250 scale_factor,
1251 is_emoji: false,
1252 };
1253
1254 let raster_bounds = self.text_system().raster_bounds(¶ms)?;
1255 if !raster_bounds.is_zero() {
1256 let tile =
1257 self.window
1258 .sprite_atlas
1259 .get_or_insert_with(¶ms.clone().into(), &mut || {
1260 let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?;
1261 Ok((size, Cow::Owned(bytes)))
1262 })?;
1263 let bounds = Bounds {
1264 origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
1265 size: tile.bounds.size.map(Into::into),
1266 };
1267 let content_mask = self.content_mask().scale(scale_factor);
1268 let view_id = self.parent_view_id();
1269 let window = &mut *self.window;
1270 window.next_frame.scene.insert(
1271 &window.next_frame.z_index_stack,
1272 MonochromeSprite {
1273 view_id: view_id.into(),
1274 layer_id: 0,
1275 order: 0,
1276 bounds,
1277 content_mask,
1278 color,
1279 tile,
1280 },
1281 );
1282 }
1283 Ok(())
1284 }
1285
1286 /// Paint an emoji glyph into the scene for the next frame at the current z-index.
1287 /// The y component of the origin is the baseline of the glyph.
1288 pub fn paint_emoji(
1289 &mut self,
1290 origin: Point<Pixels>,
1291 font_id: FontId,
1292 glyph_id: GlyphId,
1293 font_size: Pixels,
1294 ) -> Result<()> {
1295 let scale_factor = self.scale_factor();
1296 let glyph_origin = origin.scale(scale_factor);
1297 let params = RenderGlyphParams {
1298 font_id,
1299 glyph_id,
1300 font_size,
1301 // We don't render emojis with subpixel variants.
1302 subpixel_variant: Default::default(),
1303 scale_factor,
1304 is_emoji: true,
1305 };
1306
1307 let raster_bounds = self.text_system().raster_bounds(¶ms)?;
1308 if !raster_bounds.is_zero() {
1309 let tile =
1310 self.window
1311 .sprite_atlas
1312 .get_or_insert_with(¶ms.clone().into(), &mut || {
1313 let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?;
1314 Ok((size, Cow::Owned(bytes)))
1315 })?;
1316 let bounds = Bounds {
1317 origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
1318 size: tile.bounds.size.map(Into::into),
1319 };
1320 let content_mask = self.content_mask().scale(scale_factor);
1321 let view_id = self.parent_view_id();
1322 let window = &mut *self.window;
1323
1324 window.next_frame.scene.insert(
1325 &window.next_frame.z_index_stack,
1326 PolychromeSprite {
1327 view_id: view_id.into(),
1328 layer_id: 0,
1329 order: 0,
1330 bounds,
1331 corner_radii: Default::default(),
1332 content_mask,
1333 tile,
1334 grayscale: false,
1335 },
1336 );
1337 }
1338 Ok(())
1339 }
1340
1341 /// Paint a monochrome SVG into the scene for the next frame at the current stacking context.
1342 pub fn paint_svg(
1343 &mut self,
1344 bounds: Bounds<Pixels>,
1345 path: SharedString,
1346 color: Hsla,
1347 ) -> Result<()> {
1348 let scale_factor = self.scale_factor();
1349 let bounds = bounds.scale(scale_factor);
1350 // Render the SVG at twice the size to get a higher quality result.
1351 let params = RenderSvgParams {
1352 path,
1353 size: bounds
1354 .size
1355 .map(|pixels| DevicePixels::from((pixels.0 * 2.).ceil() as i32)),
1356 };
1357
1358 let tile =
1359 self.window
1360 .sprite_atlas
1361 .get_or_insert_with(¶ms.clone().into(), &mut || {
1362 let bytes = self.svg_renderer.render(¶ms)?;
1363 Ok((params.size, Cow::Owned(bytes)))
1364 })?;
1365 let content_mask = self.content_mask().scale(scale_factor);
1366 let view_id = self.parent_view_id();
1367
1368 let window = &mut *self.window;
1369 window.next_frame.scene.insert(
1370 &window.next_frame.z_index_stack,
1371 MonochromeSprite {
1372 view_id: view_id.into(),
1373 layer_id: 0,
1374 order: 0,
1375 bounds,
1376 content_mask,
1377 color,
1378 tile,
1379 },
1380 );
1381
1382 Ok(())
1383 }
1384
1385 /// Paint an image into the scene for the next frame at the current z-index.
1386 pub fn paint_image(
1387 &mut self,
1388 bounds: Bounds<Pixels>,
1389 corner_radii: Corners<Pixels>,
1390 data: Arc<ImageData>,
1391 grayscale: bool,
1392 ) -> Result<()> {
1393 let scale_factor = self.scale_factor();
1394 let bounds = bounds.scale(scale_factor);
1395 let params = RenderImageParams { image_id: data.id };
1396
1397 let tile = self
1398 .window
1399 .sprite_atlas
1400 .get_or_insert_with(¶ms.clone().into(), &mut || {
1401 Ok((data.size(), Cow::Borrowed(data.as_bytes())))
1402 })?;
1403 let content_mask = self.content_mask().scale(scale_factor);
1404 let corner_radii = corner_radii.scale(scale_factor);
1405 let view_id = self.parent_view_id();
1406
1407 let window = &mut *self.window;
1408 window.next_frame.scene.insert(
1409 &window.next_frame.z_index_stack,
1410 PolychromeSprite {
1411 view_id: view_id.into(),
1412 layer_id: 0,
1413 order: 0,
1414 bounds,
1415 content_mask,
1416 corner_radii,
1417 tile,
1418 grayscale,
1419 },
1420 );
1421 Ok(())
1422 }
1423
1424 /// Paint a surface into the scene for the next frame at the current z-index.
1425 pub fn paint_surface(&mut self, bounds: Bounds<Pixels>, image_buffer: CVImageBuffer) {
1426 let scale_factor = self.scale_factor();
1427 let bounds = bounds.scale(scale_factor);
1428 let content_mask = self.content_mask().scale(scale_factor);
1429 let view_id = self.parent_view_id();
1430 let window = &mut *self.window;
1431 window.next_frame.scene.insert(
1432 &window.next_frame.z_index_stack,
1433 Surface {
1434 view_id: view_id.into(),
1435 layer_id: 0,
1436 order: 0,
1437 bounds,
1438 content_mask,
1439 image_buffer,
1440 },
1441 );
1442 }
1443
1444 pub(crate) fn reuse_view(&mut self) {
1445 let view_id = self.parent_view_id();
1446 let grafted_view_ids = self
1447 .window
1448 .next_frame
1449 .dispatch_tree
1450 .reuse_view(view_id, &mut self.window.rendered_frame.dispatch_tree);
1451 for view_id in grafted_view_ids {
1452 assert!(self.window.next_frame.reused_views.insert(view_id));
1453
1454 // Reuse the previous input handler requested during painting of the reused view.
1455 if self
1456 .window
1457 .rendered_frame
1458 .requested_input_handler
1459 .as_ref()
1460 .map_or(false, |requested| requested.view_id == view_id)
1461 {
1462 self.window.next_frame.requested_input_handler =
1463 self.window.rendered_frame.requested_input_handler.take();
1464 }
1465
1466 // Reuse the tooltip previously requested during painting of the reused view.
1467 if self
1468 .window
1469 .rendered_frame
1470 .tooltip_request
1471 .as_ref()
1472 .map_or(false, |requested| requested.view_id == view_id)
1473 {
1474 self.window.next_frame.tooltip_request =
1475 self.window.rendered_frame.tooltip_request.take();
1476 }
1477
1478 // Reuse the cursor styles previously requested during painting of the reused view.
1479 if let Some(style) = self.window.rendered_frame.cursor_styles.remove(&view_id) {
1480 self.window.next_frame.cursor_styles.insert(view_id, style);
1481 self.window.next_frame.requested_cursor_style = Some(style);
1482 }
1483 }
1484 }
1485
1486 /// Draw pixels to the display for this window based on the contents of its scene.
1487 pub(crate) fn draw(&mut self) {
1488 self.window.dirty = false;
1489 self.window.drawing = true;
1490
1491 #[cfg(any(test, feature = "test-support"))]
1492 {
1493 self.window.focus_invalidated = false;
1494 }
1495
1496 if let Some(requested_handler) = self.window.rendered_frame.requested_input_handler.as_mut()
1497 {
1498 requested_handler.handler = self.window.platform_window.take_input_handler();
1499 }
1500
1501 let root_view = self.window.root_view.take().unwrap();
1502
1503 self.with_z_index(0, |cx| {
1504 cx.with_key_dispatch(Some(KeyContext::default()), None, |_, cx| {
1505 for (action_type, action_listeners) in &cx.app.global_action_listeners {
1506 for action_listener in action_listeners.iter().cloned() {
1507 cx.window.next_frame.dispatch_tree.on_action(
1508 *action_type,
1509 Rc::new(move |action: &dyn Any, phase, cx: &mut WindowContext<'_>| {
1510 action_listener(action, phase, cx)
1511 }),
1512 )
1513 }
1514 }
1515
1516 let available_space = cx.window.viewport_size.map(Into::into);
1517 root_view.draw(Point::default(), available_space, cx);
1518 })
1519 });
1520
1521 if let Some(active_drag) = self.app.active_drag.take() {
1522 self.with_z_index(ACTIVE_DRAG_Z_INDEX, |cx| {
1523 let offset = cx.mouse_position() - active_drag.cursor_offset;
1524 let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
1525 active_drag.view.draw(offset, available_space, cx);
1526 });
1527 self.active_drag = Some(active_drag);
1528 } else if let Some(tooltip_request) = self.window.next_frame.tooltip_request.take() {
1529 self.with_z_index(1, |cx| {
1530 let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
1531 tooltip_request.tooltip.view.draw(
1532 tooltip_request.tooltip.cursor_offset,
1533 available_space,
1534 cx,
1535 );
1536 });
1537 self.window.next_frame.tooltip_request = Some(tooltip_request);
1538 }
1539 self.window.dirty_views.clear();
1540
1541 self.window
1542 .next_frame
1543 .dispatch_tree
1544 .preserve_pending_keystrokes(
1545 &mut self.window.rendered_frame.dispatch_tree,
1546 self.window.focus,
1547 );
1548 self.window.next_frame.focus = self.window.focus;
1549 self.window.next_frame.window_active = self.window.active;
1550 self.window.root_view = Some(root_view);
1551
1552 // Set the cursor only if we're the active window.
1553 let cursor_style = self
1554 .window
1555 .next_frame
1556 .requested_cursor_style
1557 .take()
1558 .unwrap_or(CursorStyle::Arrow);
1559 if self.is_window_active() {
1560 self.platform.set_cursor_style(cursor_style);
1561 }
1562
1563 // Register requested input handler with the platform window.
1564 if let Some(requested_input) = self.window.next_frame.requested_input_handler.as_mut() {
1565 if let Some(handler) = requested_input.handler.take() {
1566 self.window.platform_window.set_input_handler(handler);
1567 }
1568 }
1569
1570 self.window.layout_engine.as_mut().unwrap().clear();
1571 self.text_system()
1572 .finish_frame(&self.window.next_frame.reused_views);
1573 self.window
1574 .next_frame
1575 .finish(&mut self.window.rendered_frame);
1576 ELEMENT_ARENA.with_borrow_mut(|element_arena| element_arena.clear());
1577
1578 let previous_focus_path = self.window.rendered_frame.focus_path();
1579 let previous_window_active = self.window.rendered_frame.window_active;
1580 mem::swap(&mut self.window.rendered_frame, &mut self.window.next_frame);
1581 self.window.next_frame.clear();
1582 let current_focus_path = self.window.rendered_frame.focus_path();
1583 let current_window_active = self.window.rendered_frame.window_active;
1584
1585 if previous_focus_path != current_focus_path
1586 || previous_window_active != current_window_active
1587 {
1588 if !previous_focus_path.is_empty() && current_focus_path.is_empty() {
1589 self.window
1590 .focus_lost_listeners
1591 .clone()
1592 .retain(&(), |listener| listener(self));
1593 }
1594
1595 let event = FocusEvent {
1596 previous_focus_path: if previous_window_active {
1597 previous_focus_path
1598 } else {
1599 Default::default()
1600 },
1601 current_focus_path: if current_window_active {
1602 current_focus_path
1603 } else {
1604 Default::default()
1605 },
1606 };
1607 self.window
1608 .focus_listeners
1609 .clone()
1610 .retain(&(), |listener| listener(&event, self));
1611 }
1612
1613 self.window
1614 .platform_window
1615 .draw(&self.window.rendered_frame.scene);
1616 self.window.refreshing = false;
1617 self.window.drawing = false;
1618 }
1619
1620 /// Dispatch a mouse or keyboard event on the window.
1621 pub fn dispatch_event(&mut self, event: PlatformInput) -> bool {
1622 // Handlers may set this to false by calling `stop_propagation`.
1623 self.app.propagate_event = true;
1624 // Handlers may set this to true by calling `prevent_default`.
1625 self.window.default_prevented = false;
1626
1627 let event = match event {
1628 // Track the mouse position with our own state, since accessing the platform
1629 // API for the mouse position can only occur on the main thread.
1630 PlatformInput::MouseMove(mouse_move) => {
1631 self.window.mouse_position = mouse_move.position;
1632 self.window.modifiers = mouse_move.modifiers;
1633 PlatformInput::MouseMove(mouse_move)
1634 }
1635 PlatformInput::MouseDown(mouse_down) => {
1636 self.window.mouse_position = mouse_down.position;
1637 self.window.modifiers = mouse_down.modifiers;
1638 PlatformInput::MouseDown(mouse_down)
1639 }
1640 PlatformInput::MouseUp(mouse_up) => {
1641 self.window.mouse_position = mouse_up.position;
1642 self.window.modifiers = mouse_up.modifiers;
1643 PlatformInput::MouseUp(mouse_up)
1644 }
1645 PlatformInput::MouseExited(mouse_exited) => {
1646 self.window.modifiers = mouse_exited.modifiers;
1647 PlatformInput::MouseExited(mouse_exited)
1648 }
1649 PlatformInput::ModifiersChanged(modifiers_changed) => {
1650 self.window.modifiers = modifiers_changed.modifiers;
1651 PlatformInput::ModifiersChanged(modifiers_changed)
1652 }
1653 PlatformInput::ScrollWheel(scroll_wheel) => {
1654 self.window.mouse_position = scroll_wheel.position;
1655 self.window.modifiers = scroll_wheel.modifiers;
1656 PlatformInput::ScrollWheel(scroll_wheel)
1657 }
1658 // Translate dragging and dropping of external files from the operating system
1659 // to internal drag and drop events.
1660 PlatformInput::FileDrop(file_drop) => match file_drop {
1661 FileDropEvent::Entered { position, paths } => {
1662 self.window.mouse_position = position;
1663 if self.active_drag.is_none() {
1664 self.active_drag = Some(AnyDrag {
1665 value: Box::new(paths.clone()),
1666 view: self.new_view(|_| paths).into(),
1667 cursor_offset: position,
1668 });
1669 }
1670 PlatformInput::MouseMove(MouseMoveEvent {
1671 position,
1672 pressed_button: Some(MouseButton::Left),
1673 modifiers: Modifiers::default(),
1674 })
1675 }
1676 FileDropEvent::Pending { position } => {
1677 self.window.mouse_position = position;
1678 PlatformInput::MouseMove(MouseMoveEvent {
1679 position,
1680 pressed_button: Some(MouseButton::Left),
1681 modifiers: Modifiers::default(),
1682 })
1683 }
1684 FileDropEvent::Submit { position } => {
1685 self.activate(true);
1686 self.window.mouse_position = position;
1687 PlatformInput::MouseUp(MouseUpEvent {
1688 button: MouseButton::Left,
1689 position,
1690 modifiers: Modifiers::default(),
1691 click_count: 1,
1692 })
1693 }
1694 FileDropEvent::Exited => PlatformInput::MouseUp(MouseUpEvent {
1695 button: MouseButton::Left,
1696 position: Point::default(),
1697 modifiers: Modifiers::default(),
1698 click_count: 1,
1699 }),
1700 },
1701 PlatformInput::KeyDown(_) | PlatformInput::KeyUp(_) => event,
1702 };
1703
1704 if let Some(any_mouse_event) = event.mouse_event() {
1705 self.dispatch_mouse_event(any_mouse_event);
1706 } else if let Some(any_key_event) = event.keyboard_event() {
1707 self.dispatch_key_event(any_key_event);
1708 }
1709
1710 !self.app.propagate_event
1711 }
1712
1713 fn dispatch_mouse_event(&mut self, event: &dyn Any) {
1714 if let Some(mut handlers) = self
1715 .window
1716 .rendered_frame
1717 .mouse_listeners
1718 .remove(&event.type_id())
1719 {
1720 dbg!(handlers.len());
1721 // Because handlers may add other handlers, we sort every time.
1722 handlers.sort_by(|(a, _, _), (b, _, _)| a.cmp(b));
1723
1724 // Capture phase, events bubble from back to front. Handlers for this phase are used for
1725 // special purposes, such as detecting events outside of a given Bounds.
1726 for (_, _, handler) in &mut handlers {
1727 handler(event, DispatchPhase::Capture, self);
1728 if !self.app.propagate_event {
1729 break;
1730 }
1731 }
1732
1733 // Bubble phase, where most normal handlers do their work.
1734 if self.app.propagate_event {
1735 for (_, _, handler) in handlers.iter_mut().rev() {
1736 handler(event, DispatchPhase::Bubble, self);
1737 if !self.app.propagate_event {
1738 break;
1739 }
1740 }
1741 }
1742
1743 self.window
1744 .rendered_frame
1745 .mouse_listeners
1746 .insert(event.type_id(), handlers);
1747 }
1748
1749 if self.app.propagate_event && self.has_active_drag() {
1750 if event.is::<MouseMoveEvent>() {
1751 // If this was a mouse move event, redraw the window so that the
1752 // active drag can follow the mouse cursor.
1753 self.refresh();
1754 } else if event.is::<MouseUpEvent>() {
1755 // If this was a mouse up event, cancel the active drag and redraw
1756 // the window.
1757 self.active_drag = None;
1758 self.refresh();
1759 }
1760 }
1761 }
1762
1763 fn dispatch_key_event(&mut self, event: &dyn Any) {
1764 let node_id = self
1765 .window
1766 .focus
1767 .and_then(|focus_id| {
1768 self.window
1769 .rendered_frame
1770 .dispatch_tree
1771 .focusable_node_id(focus_id)
1772 })
1773 .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
1774
1775 let dispatch_path = self
1776 .window
1777 .rendered_frame
1778 .dispatch_tree
1779 .dispatch_path(node_id);
1780
1781 let mut actions: Vec<Box<dyn Action>> = Vec::new();
1782
1783 let mut context_stack: SmallVec<[KeyContext; 16]> = SmallVec::new();
1784 for node_id in &dispatch_path {
1785 let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1786
1787 if let Some(context) = node.context.clone() {
1788 context_stack.push(context);
1789 }
1790 }
1791
1792 for node_id in dispatch_path.iter().rev() {
1793 // Match keystrokes
1794 let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1795 if node.context.is_some() {
1796 if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
1797 let mut new_actions = self
1798 .window
1799 .rendered_frame
1800 .dispatch_tree
1801 .dispatch_key(&key_down_event.keystroke, &context_stack);
1802 actions.append(&mut new_actions);
1803 }
1804
1805 context_stack.pop();
1806 }
1807 }
1808
1809 if !actions.is_empty() {
1810 self.clear_pending_keystrokes();
1811 }
1812
1813 self.propagate_event = true;
1814 for action in actions {
1815 self.dispatch_action_on_node(node_id, action.boxed_clone());
1816 if !self.propagate_event {
1817 self.dispatch_keystroke_observers(event, Some(action));
1818 return;
1819 }
1820 }
1821
1822 // Capture phase
1823 for node_id in &dispatch_path {
1824 let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1825
1826 for key_listener in node.key_listeners.clone() {
1827 key_listener(event, DispatchPhase::Capture, self);
1828 if !self.propagate_event {
1829 return;
1830 }
1831 }
1832 }
1833
1834 // Bubble phase
1835 for node_id in dispatch_path.iter().rev() {
1836 // Handle low level key events
1837 let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1838 for key_listener in node.key_listeners.clone() {
1839 key_listener(event, DispatchPhase::Bubble, self);
1840 if !self.propagate_event {
1841 return;
1842 }
1843 }
1844 }
1845
1846 self.dispatch_keystroke_observers(event, None);
1847 }
1848
1849 /// Determine whether a potential multi-stroke key binding is in progress on this window.
1850 pub fn has_pending_keystrokes(&self) -> bool {
1851 self.window
1852 .rendered_frame
1853 .dispatch_tree
1854 .has_pending_keystrokes()
1855 }
1856
1857 fn dispatch_action_on_node(&mut self, node_id: DispatchNodeId, action: Box<dyn Action>) {
1858 let dispatch_path = self
1859 .window
1860 .rendered_frame
1861 .dispatch_tree
1862 .dispatch_path(node_id);
1863
1864 // Capture phase
1865 for node_id in &dispatch_path {
1866 let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1867 for DispatchActionListener {
1868 action_type,
1869 listener,
1870 } in node.action_listeners.clone()
1871 {
1872 let any_action = action.as_any();
1873 if action_type == any_action.type_id() {
1874 listener(any_action, DispatchPhase::Capture, self);
1875 if !self.propagate_event {
1876 return;
1877 }
1878 }
1879 }
1880 }
1881 // Bubble phase
1882 for node_id in dispatch_path.iter().rev() {
1883 let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1884 for DispatchActionListener {
1885 action_type,
1886 listener,
1887 } in node.action_listeners.clone()
1888 {
1889 let any_action = action.as_any();
1890 if action_type == any_action.type_id() {
1891 self.propagate_event = false; // Actions stop propagation by default during the bubble phase
1892 listener(any_action, DispatchPhase::Bubble, self);
1893 if !self.propagate_event {
1894 return;
1895 }
1896 }
1897 }
1898 }
1899 }
1900
1901 /// Register the given handler to be invoked whenever the global of the given type
1902 /// is updated.
1903 pub fn observe_global<G: 'static>(
1904 &mut self,
1905 f: impl Fn(&mut WindowContext<'_>) + 'static,
1906 ) -> Subscription {
1907 let window_handle = self.window.handle;
1908 let (subscription, activate) = self.global_observers.insert(
1909 TypeId::of::<G>(),
1910 Box::new(move |cx| window_handle.update(cx, |_, cx| f(cx)).is_ok()),
1911 );
1912 self.app.defer(move |_| activate());
1913 subscription
1914 }
1915
1916 /// Focus the current window and bring it to the foreground at the platform level.
1917 pub fn activate_window(&self) {
1918 self.window.platform_window.activate();
1919 }
1920
1921 /// Minimize the current window at the platform level.
1922 pub fn minimize_window(&self) {
1923 self.window.platform_window.minimize();
1924 }
1925
1926 /// Toggle full screen status on the current window at the platform level.
1927 pub fn toggle_full_screen(&self) {
1928 self.window.platform_window.toggle_full_screen();
1929 }
1930
1931 /// Present a platform dialog.
1932 /// The provided message will be presented, along with buttons for each answer.
1933 /// When a button is clicked, the returned Receiver will receive the index of the clicked button.
1934 pub fn prompt(
1935 &self,
1936 level: PromptLevel,
1937 message: &str,
1938 answers: &[&str],
1939 ) -> oneshot::Receiver<usize> {
1940 self.window.platform_window.prompt(level, message, answers)
1941 }
1942
1943 /// Returns all available actions for the focused element.
1944 pub fn available_actions(&self) -> Vec<Box<dyn Action>> {
1945 let node_id = self
1946 .window
1947 .focus
1948 .and_then(|focus_id| {
1949 self.window
1950 .rendered_frame
1951 .dispatch_tree
1952 .focusable_node_id(focus_id)
1953 })
1954 .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
1955
1956 self.window
1957 .rendered_frame
1958 .dispatch_tree
1959 .available_actions(node_id)
1960 }
1961
1962 /// Returns key bindings that invoke the given action on the currently focused element.
1963 pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
1964 self.window
1965 .rendered_frame
1966 .dispatch_tree
1967 .bindings_for_action(
1968 action,
1969 &self.window.rendered_frame.dispatch_tree.context_stack,
1970 )
1971 }
1972
1973 /// Returns any bindings that would invoke the given action on the given focus handle if it were focused.
1974 pub fn bindings_for_action_in(
1975 &self,
1976 action: &dyn Action,
1977 focus_handle: &FocusHandle,
1978 ) -> Vec<KeyBinding> {
1979 let dispatch_tree = &self.window.rendered_frame.dispatch_tree;
1980
1981 let Some(node_id) = dispatch_tree.focusable_node_id(focus_handle.id) else {
1982 return vec![];
1983 };
1984 let context_stack = dispatch_tree
1985 .dispatch_path(node_id)
1986 .into_iter()
1987 .filter_map(|node_id| dispatch_tree.node(node_id).context.clone())
1988 .collect();
1989 dispatch_tree.bindings_for_action(action, &context_stack)
1990 }
1991
1992 /// Returns a generic event listener that invokes the given listener with the view and context associated with the given view handle.
1993 pub fn listener_for<V: Render, E>(
1994 &self,
1995 view: &View<V>,
1996 f: impl Fn(&mut V, &E, &mut ViewContext<V>) + 'static,
1997 ) -> impl Fn(&E, &mut WindowContext) + 'static {
1998 let view = view.downgrade();
1999 move |e: &E, cx: &mut WindowContext| {
2000 view.update(cx, |view, cx| f(view, e, cx)).ok();
2001 }
2002 }
2003
2004 /// Returns a generic handler that invokes the given handler with the view and context associated with the given view handle.
2005 pub fn handler_for<V: Render>(
2006 &self,
2007 view: &View<V>,
2008 f: impl Fn(&mut V, &mut ViewContext<V>) + 'static,
2009 ) -> impl Fn(&mut WindowContext) {
2010 let view = view.downgrade();
2011 move |cx: &mut WindowContext| {
2012 view.update(cx, |view, cx| f(view, cx)).ok();
2013 }
2014 }
2015
2016 /// Invoke the given function with the given focus handle present on the key dispatch stack.
2017 /// If you want an element to participate in key dispatch, use this method to push its key context and focus handle into the stack during paint.
2018 pub fn with_key_dispatch<R>(
2019 &mut self,
2020 context: Option<KeyContext>,
2021 focus_handle: Option<FocusHandle>,
2022 f: impl FnOnce(Option<FocusHandle>, &mut Self) -> R,
2023 ) -> R {
2024 let window = &mut self.window;
2025 let focus_id = focus_handle.as_ref().map(|handle| handle.id);
2026 window
2027 .next_frame
2028 .dispatch_tree
2029 .push_node(context.clone(), focus_id, None);
2030
2031 let result = f(focus_handle, self);
2032
2033 self.window.next_frame.dispatch_tree.pop_node();
2034
2035 result
2036 }
2037
2038 /// Invoke the given function with the given view id present on the view stack.
2039 /// This is a fairly low-level method used to layout views.
2040 pub fn with_view_id<R>(&mut self, view_id: EntityId, f: impl FnOnce(&mut Self) -> R) -> R {
2041 let text_system = self.text_system().clone();
2042 text_system.with_view(view_id, || {
2043 if self.window.next_frame.view_stack.last() == Some(&view_id) {
2044 return f(self);
2045 } else {
2046 self.window.next_frame.view_stack.push(view_id);
2047 let result = f(self);
2048 self.window.next_frame.view_stack.pop();
2049 result
2050 }
2051 })
2052 }
2053
2054 /// Invoke the given function with the given view id present on the view stack.
2055 /// This is a fairly low-level method used to paint views.
2056 pub fn paint_view<R>(&mut self, view_id: EntityId, f: impl FnOnce(&mut Self) -> R) -> R {
2057 let text_system = self.text_system().clone();
2058 text_system.with_view(view_id, || {
2059 if self.window.next_frame.view_stack.last() == Some(&view_id) {
2060 return f(self);
2061 } else {
2062 self.window.next_frame.view_stack.push(view_id);
2063 self.window
2064 .next_frame
2065 .dispatch_tree
2066 .push_node(None, None, Some(view_id));
2067 let result = f(self);
2068 self.window.next_frame.dispatch_tree.pop_node();
2069 self.window.next_frame.view_stack.pop();
2070 result
2071 }
2072 })
2073 }
2074
2075 /// Update or initialize state for an element with the given id that lives across multiple
2076 /// frames. If an element with this id existed in the rendered frame, its state will be passed
2077 /// to the given closure. The state returned by the closure will be stored so it can be referenced
2078 /// when drawing the next frame.
2079 pub(crate) fn with_element_state<S, R>(
2080 &mut self,
2081 id: ElementId,
2082 f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
2083 ) -> R
2084 where
2085 S: 'static,
2086 {
2087 self.with_element_id(Some(id), |cx| {
2088 let global_id = cx.window().element_id_stack.clone();
2089
2090 if let Some(any) = cx
2091 .window_mut()
2092 .next_frame
2093 .element_states
2094 .remove(&global_id)
2095 .or_else(|| {
2096 cx.window_mut()
2097 .rendered_frame
2098 .element_states
2099 .remove(&global_id)
2100 })
2101 {
2102 let ElementStateBox {
2103 inner,
2104 parent_view_id,
2105 #[cfg(debug_assertions)]
2106 type_name
2107 } = any;
2108 // Using the extra inner option to avoid needing to reallocate a new box.
2109 let mut state_box = inner
2110 .downcast::<Option<S>>()
2111 .map_err(|_| {
2112 #[cfg(debug_assertions)]
2113 {
2114 anyhow!(
2115 "invalid element state type for id, requested_type {:?}, actual type: {:?}",
2116 std::any::type_name::<S>(),
2117 type_name
2118 )
2119 }
2120
2121 #[cfg(not(debug_assertions))]
2122 {
2123 anyhow!(
2124 "invalid element state type for id, requested_type {:?}",
2125 std::any::type_name::<S>(),
2126 )
2127 }
2128 })
2129 .unwrap();
2130
2131 // Actual: Option<AnyElement> <- View
2132 // Requested: () <- AnyElemet
2133 let state = state_box
2134 .take()
2135 .expect("element state is already on the stack");
2136 let (result, state) = f(Some(state), cx);
2137 state_box.replace(state);
2138 cx.window_mut()
2139 .next_frame
2140 .element_states
2141 .insert(global_id, ElementStateBox {
2142 inner: state_box,
2143 parent_view_id,
2144 #[cfg(debug_assertions)]
2145 type_name
2146 });
2147 result
2148 } else {
2149 let (result, state) = f(None, cx);
2150 let parent_view_id = cx.parent_view_id();
2151 cx.window_mut()
2152 .next_frame
2153 .element_states
2154 .insert(global_id,
2155 ElementStateBox {
2156 inner: Box::new(Some(state)),
2157 parent_view_id,
2158 #[cfg(debug_assertions)]
2159 type_name: std::any::type_name::<S>()
2160 }
2161
2162 );
2163 result
2164 }
2165 })
2166 }
2167
2168 fn parent_view_id(&self) -> EntityId {
2169 *self
2170 .window
2171 .next_frame
2172 .view_stack
2173 .last()
2174 .expect("a view should always be on the stack while drawing")
2175 }
2176
2177 /// Set an input handler, such as [`ElementInputHandler`][element_input_handler], which interfaces with the
2178 /// platform to receive textual input with proper integration with concerns such
2179 /// as IME interactions. This handler will be active for the upcoming frame until the following frame is
2180 /// rendered.
2181 ///
2182 /// [element_input_handler]: crate::ElementInputHandler
2183 pub fn handle_input(
2184 &mut self,
2185 focus_handle: &FocusHandle,
2186 input_handler: impl PlatformInputHandler,
2187 ) {
2188 if focus_handle.is_focused(self) {
2189 let view_id = self.parent_view_id();
2190 self.window.next_frame.requested_input_handler = Some(RequestedInputHandler {
2191 view_id,
2192 handler: Some(Box::new(input_handler)),
2193 })
2194 }
2195 }
2196
2197 /// Register a callback that can interrupt the closing of the current window based the returned boolean.
2198 /// If the callback returns false, the window won't be closed.
2199 pub fn on_window_should_close(&mut self, f: impl Fn(&mut WindowContext) -> bool + 'static) {
2200 let mut this = self.to_async();
2201 self.window
2202 .platform_window
2203 .on_should_close(Box::new(move || {
2204 this.update(|_, cx| {
2205 // Ensure that the window is removed from the app if it's been closed
2206 // by always pre-empting the system close event.
2207 if f(cx) {
2208 cx.remove_window();
2209 }
2210 false
2211 })
2212 .unwrap_or(true)
2213 }))
2214 }
2215}
2216
2217impl Context for WindowContext<'_> {
2218 type Result<T> = T;
2219
2220 fn new_model<T>(&mut self, build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T) -> Model<T>
2221 where
2222 T: 'static,
2223 {
2224 let slot = self.app.entities.reserve();
2225 let model = build_model(&mut ModelContext::new(&mut *self.app, slot.downgrade()));
2226 self.entities.insert(slot, model)
2227 }
2228
2229 fn update_model<T: 'static, R>(
2230 &mut self,
2231 model: &Model<T>,
2232 update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
2233 ) -> R {
2234 let mut entity = self.entities.lease(model);
2235 let result = update(
2236 &mut *entity,
2237 &mut ModelContext::new(&mut *self.app, model.downgrade()),
2238 );
2239 self.entities.end_lease(entity);
2240 result
2241 }
2242
2243 fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
2244 where
2245 F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
2246 {
2247 if window == self.window.handle {
2248 let root_view = self.window.root_view.clone().unwrap();
2249 Ok(update(root_view, self))
2250 } else {
2251 window.update(self.app, update)
2252 }
2253 }
2254
2255 fn read_model<T, R>(
2256 &self,
2257 handle: &Model<T>,
2258 read: impl FnOnce(&T, &AppContext) -> R,
2259 ) -> Self::Result<R>
2260 where
2261 T: 'static,
2262 {
2263 let entity = self.entities.read(handle);
2264 read(entity, &*self.app)
2265 }
2266
2267 fn read_window<T, R>(
2268 &self,
2269 window: &WindowHandle<T>,
2270 read: impl FnOnce(View<T>, &AppContext) -> R,
2271 ) -> Result<R>
2272 where
2273 T: 'static,
2274 {
2275 if window.any_handle == self.window.handle {
2276 let root_view = self
2277 .window
2278 .root_view
2279 .clone()
2280 .unwrap()
2281 .downcast::<T>()
2282 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
2283 Ok(read(root_view, self))
2284 } else {
2285 self.app.read_window(window, read)
2286 }
2287 }
2288}
2289
2290impl VisualContext for WindowContext<'_> {
2291 fn new_view<V>(
2292 &mut self,
2293 build_view_state: impl FnOnce(&mut ViewContext<'_, V>) -> V,
2294 ) -> Self::Result<View<V>>
2295 where
2296 V: 'static + Render,
2297 {
2298 let slot = self.app.entities.reserve();
2299 let view = View {
2300 model: slot.clone(),
2301 };
2302 let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
2303 let entity = build_view_state(&mut cx);
2304 cx.entities.insert(slot, entity);
2305
2306 cx.new_view_observers
2307 .clone()
2308 .retain(&TypeId::of::<V>(), |observer| {
2309 let any_view = AnyView::from(view.clone());
2310 (observer)(any_view, self);
2311 true
2312 });
2313
2314 view
2315 }
2316
2317 /// Update the given view. Prefer calling `View::update` instead, which calls this method.
2318 fn update_view<T: 'static, R>(
2319 &mut self,
2320 view: &View<T>,
2321 update: impl FnOnce(&mut T, &mut ViewContext<'_, T>) -> R,
2322 ) -> Self::Result<R> {
2323 let mut lease = self.app.entities.lease(&view.model);
2324 let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, view);
2325 let result = update(&mut *lease, &mut cx);
2326 cx.app.entities.end_lease(lease);
2327 result
2328 }
2329
2330 fn replace_root_view<V>(
2331 &mut self,
2332 build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
2333 ) -> Self::Result<View<V>>
2334 where
2335 V: 'static + Render,
2336 {
2337 let view = self.new_view(build_view);
2338 self.window.root_view = Some(view.clone().into());
2339 self.refresh();
2340 view
2341 }
2342
2343 fn focus_view<V: crate::FocusableView>(&mut self, view: &View<V>) -> Self::Result<()> {
2344 self.update_view(view, |view, cx| {
2345 view.focus_handle(cx).clone().focus(cx);
2346 })
2347 }
2348
2349 fn dismiss_view<V>(&mut self, view: &View<V>) -> Self::Result<()>
2350 where
2351 V: ManagedView,
2352 {
2353 self.update_view(view, |_, cx| cx.emit(DismissEvent))
2354 }
2355}
2356
2357impl<'a> std::ops::Deref for WindowContext<'a> {
2358 type Target = AppContext;
2359
2360 fn deref(&self) -> &Self::Target {
2361 self.app
2362 }
2363}
2364
2365impl<'a> std::ops::DerefMut for WindowContext<'a> {
2366 fn deref_mut(&mut self) -> &mut Self::Target {
2367 self.app
2368 }
2369}
2370
2371impl<'a> Borrow<AppContext> for WindowContext<'a> {
2372 fn borrow(&self) -> &AppContext {
2373 self.app
2374 }
2375}
2376
2377impl<'a> BorrowMut<AppContext> for WindowContext<'a> {
2378 fn borrow_mut(&mut self) -> &mut AppContext {
2379 self.app
2380 }
2381}
2382
2383/// This trait contains functionality that is shared across [`ViewContext`] and [`WindowContext`]
2384pub trait BorrowWindow: BorrowMut<Window> + BorrowMut<AppContext> {
2385 #[doc(hidden)]
2386 fn app_mut(&mut self) -> &mut AppContext {
2387 self.borrow_mut()
2388 }
2389
2390 #[doc(hidden)]
2391 fn app(&self) -> &AppContext {
2392 self.borrow()
2393 }
2394
2395 #[doc(hidden)]
2396 fn window(&self) -> &Window {
2397 self.borrow()
2398 }
2399
2400 #[doc(hidden)]
2401 fn window_mut(&mut self) -> &mut Window {
2402 self.borrow_mut()
2403 }
2404
2405 /// Pushes the given element id onto the global stack and invokes the given closure
2406 /// with a `GlobalElementId`, which disambiguates the given id in the context of its ancestor
2407 /// ids. Because elements are discarded and recreated on each frame, the `GlobalElementId` is
2408 /// used to associate state with identified elements across separate frames.
2409 fn with_element_id<R>(
2410 &mut self,
2411 id: Option<impl Into<ElementId>>,
2412 f: impl FnOnce(&mut Self) -> R,
2413 ) -> R {
2414 if let Some(id) = id.map(Into::into) {
2415 let window = self.window_mut();
2416 window.element_id_stack.push(id);
2417 let result = f(self);
2418 let window: &mut Window = self.borrow_mut();
2419 window.element_id_stack.pop();
2420 result
2421 } else {
2422 f(self)
2423 }
2424 }
2425
2426 /// Invoke the given function with the given content mask after intersecting it
2427 /// with the current mask.
2428 fn with_content_mask<R>(
2429 &mut self,
2430 mask: Option<ContentMask<Pixels>>,
2431 f: impl FnOnce(&mut Self) -> R,
2432 ) -> R {
2433 if let Some(mask) = mask {
2434 let mask = mask.intersect(&self.content_mask());
2435 self.window_mut().next_frame.content_mask_stack.push(mask);
2436 let result = f(self);
2437 self.window_mut().next_frame.content_mask_stack.pop();
2438 result
2439 } else {
2440 f(self)
2441 }
2442 }
2443
2444 /// Invoke the given function with the content mask reset to that
2445 /// of the window.
2446 fn break_content_mask<R>(&mut self, f: impl FnOnce(&mut Self) -> R) -> R {
2447 let mask = ContentMask {
2448 bounds: Bounds {
2449 origin: Point::default(),
2450 size: self.window().viewport_size,
2451 },
2452 };
2453 let new_stacking_order_id =
2454 post_inc(&mut self.window_mut().next_frame.next_stacking_order_id);
2455 let old_stacking_order = mem::take(&mut self.window_mut().next_frame.z_index_stack);
2456 self.window_mut().next_frame.z_index_stack.id = new_stacking_order_id;
2457 self.window_mut().next_frame.content_mask_stack.push(mask);
2458 let result = f(self);
2459 self.window_mut().next_frame.content_mask_stack.pop();
2460 self.window_mut().next_frame.z_index_stack = old_stacking_order;
2461 result
2462 }
2463
2464 /// Called during painting to invoke the given closure in a new stacking context. The given
2465 /// z-index is interpreted relative to the previous call to `stack`.
2466 fn with_z_index<R>(&mut self, z_index: u8, f: impl FnOnce(&mut Self) -> R) -> R {
2467 let new_stacking_order_id =
2468 post_inc(&mut self.window_mut().next_frame.next_stacking_order_id);
2469 let old_stacking_order_id = mem::replace(
2470 &mut self.window_mut().next_frame.z_index_stack.id,
2471 new_stacking_order_id,
2472 );
2473 self.window_mut().next_frame.z_index_stack.id = new_stacking_order_id;
2474 self.window_mut().next_frame.z_index_stack.push(z_index);
2475 let result = f(self);
2476 self.window_mut().next_frame.z_index_stack.id = old_stacking_order_id;
2477 self.window_mut().next_frame.z_index_stack.pop();
2478 result
2479 }
2480
2481 /// Update the global element offset relative to the current offset. This is used to implement
2482 /// scrolling.
2483 fn with_element_offset<R>(
2484 &mut self,
2485 offset: Point<Pixels>,
2486 f: impl FnOnce(&mut Self) -> R,
2487 ) -> R {
2488 if offset.is_zero() {
2489 return f(self);
2490 };
2491
2492 let abs_offset = self.element_offset() + offset;
2493 self.with_absolute_element_offset(abs_offset, f)
2494 }
2495
2496 /// Update the global element offset based on the given offset. This is used to implement
2497 /// drag handles and other manual painting of elements.
2498 fn with_absolute_element_offset<R>(
2499 &mut self,
2500 offset: Point<Pixels>,
2501 f: impl FnOnce(&mut Self) -> R,
2502 ) -> R {
2503 self.window_mut()
2504 .next_frame
2505 .element_offset_stack
2506 .push(offset);
2507 let result = f(self);
2508 self.window_mut().next_frame.element_offset_stack.pop();
2509 result
2510 }
2511
2512 /// Obtain the current element offset.
2513 fn element_offset(&self) -> Point<Pixels> {
2514 self.window()
2515 .next_frame
2516 .element_offset_stack
2517 .last()
2518 .copied()
2519 .unwrap_or_default()
2520 }
2521
2522 /// Obtain the current content mask.
2523 fn content_mask(&self) -> ContentMask<Pixels> {
2524 self.window()
2525 .next_frame
2526 .content_mask_stack
2527 .last()
2528 .cloned()
2529 .unwrap_or_else(|| ContentMask {
2530 bounds: Bounds {
2531 origin: Point::default(),
2532 size: self.window().viewport_size,
2533 },
2534 })
2535 }
2536
2537 /// The size of an em for the base font of the application. Adjusting this value allows the
2538 /// UI to scale, just like zooming a web page.
2539 fn rem_size(&self) -> Pixels {
2540 self.window().rem_size
2541 }
2542}
2543
2544impl Borrow<Window> for WindowContext<'_> {
2545 fn borrow(&self) -> &Window {
2546 self.window
2547 }
2548}
2549
2550impl BorrowMut<Window> for WindowContext<'_> {
2551 fn borrow_mut(&mut self) -> &mut Window {
2552 self.window
2553 }
2554}
2555
2556impl<T> BorrowWindow for T where T: BorrowMut<AppContext> + BorrowMut<Window> {}
2557
2558/// Provides access to application state that is specialized for a particular [`View`].
2559/// Allows you to interact with focus, emit events, etc.
2560/// ViewContext also derefs to [`WindowContext`], giving you access to all of its methods as well.
2561/// When you call [`View::update`], you're passed a `&mut V` and an `&mut ViewContext<V>`.
2562pub struct ViewContext<'a, V> {
2563 window_cx: WindowContext<'a>,
2564 view: &'a View<V>,
2565}
2566
2567impl<V> Borrow<AppContext> for ViewContext<'_, V> {
2568 fn borrow(&self) -> &AppContext {
2569 &*self.window_cx.app
2570 }
2571}
2572
2573impl<V> BorrowMut<AppContext> for ViewContext<'_, V> {
2574 fn borrow_mut(&mut self) -> &mut AppContext {
2575 &mut *self.window_cx.app
2576 }
2577}
2578
2579impl<V> Borrow<Window> for ViewContext<'_, V> {
2580 fn borrow(&self) -> &Window {
2581 &*self.window_cx.window
2582 }
2583}
2584
2585impl<V> BorrowMut<Window> for ViewContext<'_, V> {
2586 fn borrow_mut(&mut self) -> &mut Window {
2587 &mut *self.window_cx.window
2588 }
2589}
2590
2591impl<'a, V: 'static> ViewContext<'a, V> {
2592 pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window, view: &'a View<V>) -> Self {
2593 Self {
2594 window_cx: WindowContext::new(app, window),
2595 view,
2596 }
2597 }
2598
2599 /// Get the entity_id of this view.
2600 pub fn entity_id(&self) -> EntityId {
2601 self.view.entity_id()
2602 }
2603
2604 /// Get the view pointer underlying this context.
2605 pub fn view(&self) -> &View<V> {
2606 self.view
2607 }
2608
2609 /// Get the model underlying this view.
2610 pub fn model(&self) -> &Model<V> {
2611 &self.view.model
2612 }
2613
2614 /// Access the underlying window context.
2615 pub fn window_context(&mut self) -> &mut WindowContext<'a> {
2616 &mut self.window_cx
2617 }
2618
2619 /// Set a given callback to be run on the next frame.
2620 pub fn on_next_frame(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static)
2621 where
2622 V: 'static,
2623 {
2624 let view = self.view().clone();
2625 self.window_cx.on_next_frame(move |cx| view.update(cx, f));
2626 }
2627
2628 /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
2629 /// that are currently on the stack to be returned to the app.
2630 pub fn defer(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static) {
2631 let view = self.view().downgrade();
2632 self.window_cx.defer(move |cx| {
2633 view.update(cx, f).ok();
2634 });
2635 }
2636
2637 /// Observe another model or view for changes to its state, as tracked by [`ModelContext::notify`].
2638 pub fn observe<V2, E>(
2639 &mut self,
2640 entity: &E,
2641 mut on_notify: impl FnMut(&mut V, E, &mut ViewContext<'_, V>) + 'static,
2642 ) -> Subscription
2643 where
2644 V2: 'static,
2645 V: 'static,
2646 E: Entity<V2>,
2647 {
2648 let view = self.view().downgrade();
2649 let entity_id = entity.entity_id();
2650 let entity = entity.downgrade();
2651 let window_handle = self.window.handle;
2652 let (subscription, activate) = self.app.observers.insert(
2653 entity_id,
2654 Box::new(move |cx| {
2655 window_handle
2656 .update(cx, |_, cx| {
2657 if let Some(handle) = E::upgrade_from(&entity) {
2658 view.update(cx, |this, cx| on_notify(this, handle, cx))
2659 .is_ok()
2660 } else {
2661 false
2662 }
2663 })
2664 .unwrap_or(false)
2665 }),
2666 );
2667 self.app.defer(move |_| activate());
2668 subscription
2669 }
2670
2671 /// Subscribe to events emitted by another model or view.
2672 /// The entity to which you're subscribing must implement the [`EventEmitter`] trait.
2673 /// The callback will be invoked with a reference to the current view, a handle to the emitting entity (either a [`View`] or [`Model`]), the event, and a view context for the current view.
2674 pub fn subscribe<V2, E, Evt>(
2675 &mut self,
2676 entity: &E,
2677 mut on_event: impl FnMut(&mut V, E, &Evt, &mut ViewContext<'_, V>) + 'static,
2678 ) -> Subscription
2679 where
2680 V2: EventEmitter<Evt>,
2681 E: Entity<V2>,
2682 Evt: 'static,
2683 {
2684 let view = self.view().downgrade();
2685 let entity_id = entity.entity_id();
2686 let handle = entity.downgrade();
2687 let window_handle = self.window.handle;
2688 let (subscription, activate) = self.app.event_listeners.insert(
2689 entity_id,
2690 (
2691 TypeId::of::<Evt>(),
2692 Box::new(move |event, cx| {
2693 window_handle
2694 .update(cx, |_, cx| {
2695 if let Some(handle) = E::upgrade_from(&handle) {
2696 let event = event.downcast_ref().expect("invalid event type");
2697 view.update(cx, |this, cx| on_event(this, handle, event, cx))
2698 .is_ok()
2699 } else {
2700 false
2701 }
2702 })
2703 .unwrap_or(false)
2704 }),
2705 ),
2706 );
2707 self.app.defer(move |_| activate());
2708 subscription
2709 }
2710
2711 /// Register a callback to be invoked when the view is released.
2712 ///
2713 /// The callback receives a handle to the view's window. This handle may be
2714 /// invalid, if the window was closed before the view was released.
2715 pub fn on_release(
2716 &mut self,
2717 on_release: impl FnOnce(&mut V, AnyWindowHandle, &mut AppContext) + 'static,
2718 ) -> Subscription {
2719 let window_handle = self.window.handle;
2720 let (subscription, activate) = self.app.release_listeners.insert(
2721 self.view.model.entity_id,
2722 Box::new(move |this, cx| {
2723 let this = this.downcast_mut().expect("invalid entity type");
2724 on_release(this, window_handle, cx)
2725 }),
2726 );
2727 activate();
2728 subscription
2729 }
2730
2731 /// Register a callback to be invoked when the given Model or View is released.
2732 pub fn observe_release<V2, E>(
2733 &mut self,
2734 entity: &E,
2735 mut on_release: impl FnMut(&mut V, &mut V2, &mut ViewContext<'_, V>) + 'static,
2736 ) -> Subscription
2737 where
2738 V: 'static,
2739 V2: 'static,
2740 E: Entity<V2>,
2741 {
2742 let view = self.view().downgrade();
2743 let entity_id = entity.entity_id();
2744 let window_handle = self.window.handle;
2745 let (subscription, activate) = self.app.release_listeners.insert(
2746 entity_id,
2747 Box::new(move |entity, cx| {
2748 let entity = entity.downcast_mut().expect("invalid entity type");
2749 let _ = window_handle.update(cx, |_, cx| {
2750 view.update(cx, |this, cx| on_release(this, entity, cx))
2751 });
2752 }),
2753 );
2754 activate();
2755 subscription
2756 }
2757
2758 /// Indicate that this view has changed, which will invoke any observers and also mark the window as dirty.
2759 /// If this view or any of its ancestors are *cached*, notifying it will cause it or its ancestors to be redrawn.
2760 pub fn notify(&mut self) {
2761 for view_id in self
2762 .window
2763 .rendered_frame
2764 .dispatch_tree
2765 .view_path(self.view.entity_id())
2766 .into_iter()
2767 .rev()
2768 {
2769 if !self.window.dirty_views.insert(view_id) {
2770 break;
2771 }
2772 }
2773
2774 if !self.window.drawing {
2775 self.window_cx.window.dirty = true;
2776 self.window_cx.app.push_effect(Effect::Notify {
2777 emitter: self.view.model.entity_id,
2778 });
2779 }
2780 }
2781
2782 /// Register a callback to be invoked when the window is resized.
2783 pub fn observe_window_bounds(
2784 &mut self,
2785 mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2786 ) -> Subscription {
2787 let view = self.view.downgrade();
2788 let (subscription, activate) = self.window.bounds_observers.insert(
2789 (),
2790 Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
2791 );
2792 activate();
2793 subscription
2794 }
2795
2796 /// Register a callback to be invoked when the window is activated or deactivated.
2797 pub fn observe_window_activation(
2798 &mut self,
2799 mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2800 ) -> Subscription {
2801 let view = self.view.downgrade();
2802 let (subscription, activate) = self.window.activation_observers.insert(
2803 (),
2804 Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
2805 );
2806 activate();
2807 subscription
2808 }
2809
2810 /// Register a listener to be called when the given focus handle receives focus.
2811 /// Returns a subscription and persists until the subscription is dropped.
2812 pub fn on_focus(
2813 &mut self,
2814 handle: &FocusHandle,
2815 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2816 ) -> Subscription {
2817 let view = self.view.downgrade();
2818 let focus_id = handle.id;
2819 let (subscription, activate) = self.window.focus_listeners.insert(
2820 (),
2821 Box::new(move |event, cx| {
2822 view.update(cx, |view, cx| {
2823 if event.previous_focus_path.last() != Some(&focus_id)
2824 && event.current_focus_path.last() == Some(&focus_id)
2825 {
2826 listener(view, cx)
2827 }
2828 })
2829 .is_ok()
2830 }),
2831 );
2832 self.app.defer(move |_| activate());
2833 subscription
2834 }
2835
2836 /// Register a listener to be called when the given focus handle or one of its descendants receives focus.
2837 /// Returns a subscription and persists until the subscription is dropped.
2838 pub fn on_focus_in(
2839 &mut self,
2840 handle: &FocusHandle,
2841 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2842 ) -> Subscription {
2843 let view = self.view.downgrade();
2844 let focus_id = handle.id;
2845 let (subscription, activate) = self.window.focus_listeners.insert(
2846 (),
2847 Box::new(move |event, cx| {
2848 view.update(cx, |view, cx| {
2849 if !event.previous_focus_path.contains(&focus_id)
2850 && event.current_focus_path.contains(&focus_id)
2851 {
2852 listener(view, cx)
2853 }
2854 })
2855 .is_ok()
2856 }),
2857 );
2858 self.app.defer(move |_| activate());
2859 subscription
2860 }
2861
2862 /// Register a listener to be called when the given focus handle loses focus.
2863 /// Returns a subscription and persists until the subscription is dropped.
2864 pub fn on_blur(
2865 &mut self,
2866 handle: &FocusHandle,
2867 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2868 ) -> Subscription {
2869 let view = self.view.downgrade();
2870 let focus_id = handle.id;
2871 let (subscription, activate) = self.window.focus_listeners.insert(
2872 (),
2873 Box::new(move |event, cx| {
2874 view.update(cx, |view, cx| {
2875 if event.previous_focus_path.last() == Some(&focus_id)
2876 && event.current_focus_path.last() != Some(&focus_id)
2877 {
2878 listener(view, cx)
2879 }
2880 })
2881 .is_ok()
2882 }),
2883 );
2884 self.app.defer(move |_| activate());
2885 subscription
2886 }
2887
2888 /// Register a listener to be called when nothing in the window has focus.
2889 /// This typically happens when the node that was focused is removed from the tree,
2890 /// and this callback lets you chose a default place to restore the users focus.
2891 /// Returns a subscription and persists until the subscription is dropped.
2892 pub fn on_focus_lost(
2893 &mut self,
2894 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2895 ) -> Subscription {
2896 let view = self.view.downgrade();
2897 let (subscription, activate) = self.window.focus_lost_listeners.insert(
2898 (),
2899 Box::new(move |cx| view.update(cx, |view, cx| listener(view, cx)).is_ok()),
2900 );
2901 activate();
2902 subscription
2903 }
2904
2905 /// Register a listener to be called when the given focus handle or one of its descendants loses focus.
2906 /// Returns a subscription and persists until the subscription is dropped.
2907 pub fn on_focus_out(
2908 &mut self,
2909 handle: &FocusHandle,
2910 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2911 ) -> Subscription {
2912 let view = self.view.downgrade();
2913 let focus_id = handle.id;
2914 let (subscription, activate) = self.window.focus_listeners.insert(
2915 (),
2916 Box::new(move |event, cx| {
2917 view.update(cx, |view, cx| {
2918 if event.previous_focus_path.contains(&focus_id)
2919 && !event.current_focus_path.contains(&focus_id)
2920 {
2921 listener(view, cx)
2922 }
2923 })
2924 .is_ok()
2925 }),
2926 );
2927 self.app.defer(move |_| activate());
2928 subscription
2929 }
2930
2931 /// Schedule a future to be run asynchronously.
2932 /// The given callback is invoked with a [`WeakView<V>`] to avoid leaking the view for a long-running process.
2933 /// It's also given an [`AsyncWindowContext`], which can be used to access the state of the view across await points.
2934 /// The returned future will be polled on the main thread.
2935 pub fn spawn<Fut, R>(
2936 &mut self,
2937 f: impl FnOnce(WeakView<V>, AsyncWindowContext) -> Fut,
2938 ) -> Task<R>
2939 where
2940 R: 'static,
2941 Fut: Future<Output = R> + 'static,
2942 {
2943 let view = self.view().downgrade();
2944 self.window_cx.spawn(|cx| f(view, cx))
2945 }
2946
2947 /// Update the global state of the given type.
2948 pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
2949 where
2950 G: 'static,
2951 {
2952 let mut global = self.app.lease_global::<G>();
2953 let result = f(&mut global, self);
2954 self.app.end_global_lease(global);
2955 result
2956 }
2957
2958 /// Register a callback to be invoked when the given global state changes.
2959 pub fn observe_global<G: 'static>(
2960 &mut self,
2961 mut f: impl FnMut(&mut V, &mut ViewContext<'_, V>) + 'static,
2962 ) -> Subscription {
2963 let window_handle = self.window.handle;
2964 let view = self.view().downgrade();
2965 let (subscription, activate) = self.global_observers.insert(
2966 TypeId::of::<G>(),
2967 Box::new(move |cx| {
2968 window_handle
2969 .update(cx, |_, cx| view.update(cx, |view, cx| f(view, cx)).is_ok())
2970 .unwrap_or(false)
2971 }),
2972 );
2973 self.app.defer(move |_| activate());
2974 subscription
2975 }
2976
2977 /// Add a listener for any mouse event that occurs in the window.
2978 /// This is a fairly low level method.
2979 /// Typically, you'll want to use methods on UI elements, which perform bounds checking etc.
2980 pub fn on_mouse_event<Event: MouseEvent>(
2981 &mut self,
2982 handler: impl Fn(&mut V, &Event, DispatchPhase, &mut ViewContext<V>) + 'static,
2983 ) {
2984 let handle = self.view().clone();
2985 self.window_cx.on_mouse_event(move |event, phase, cx| {
2986 handle.update(cx, |view, cx| {
2987 handler(view, event, phase, cx);
2988 })
2989 });
2990 }
2991
2992 /// Register a callback to be invoked when the given Key Event is dispatched to the window.
2993 pub fn on_key_event<Event: KeyEvent>(
2994 &mut self,
2995 handler: impl Fn(&mut V, &Event, DispatchPhase, &mut ViewContext<V>) + 'static,
2996 ) {
2997 let handle = self.view().clone();
2998 self.window_cx.on_key_event(move |event, phase, cx| {
2999 handle.update(cx, |view, cx| {
3000 handler(view, event, phase, cx);
3001 })
3002 });
3003 }
3004
3005 /// Register a callback to be invoked when the given Action type is dispatched to the window.
3006 pub fn on_action(
3007 &mut self,
3008 action_type: TypeId,
3009 listener: impl Fn(&mut V, &dyn Any, DispatchPhase, &mut ViewContext<V>) + 'static,
3010 ) {
3011 let handle = self.view().clone();
3012 self.window_cx
3013 .on_action(action_type, move |action, phase, cx| {
3014 handle.update(cx, |view, cx| {
3015 listener(view, action, phase, cx);
3016 })
3017 });
3018 }
3019
3020 /// Emit an event to be handled any other views that have subscribed via [ViewContext::subscribe].
3021 pub fn emit<Evt>(&mut self, event: Evt)
3022 where
3023 Evt: 'static,
3024 V: EventEmitter<Evt>,
3025 {
3026 let emitter = self.view.model.entity_id;
3027 self.app.push_effect(Effect::Emit {
3028 emitter,
3029 event_type: TypeId::of::<Evt>(),
3030 event: Box::new(event),
3031 });
3032 }
3033
3034 /// Move focus to the current view, assuming it implements [`FocusableView`].
3035 pub fn focus_self(&mut self)
3036 where
3037 V: FocusableView,
3038 {
3039 self.defer(|view, cx| view.focus_handle(cx).focus(cx))
3040 }
3041
3042 /// Convenience method for accessing view state in an event callback.
3043 ///
3044 /// Many GPUI callbacks take the form of `Fn(&E, &mut WindowContext)`,
3045 /// but it's often useful to be able to access view state in these
3046 /// callbacks. This method provides a convenient way to do so.
3047 pub fn listener<E>(
3048 &self,
3049 f: impl Fn(&mut V, &E, &mut ViewContext<V>) + 'static,
3050 ) -> impl Fn(&E, &mut WindowContext) + 'static {
3051 let view = self.view().downgrade();
3052 move |e: &E, cx: &mut WindowContext| {
3053 view.update(cx, |view, cx| f(view, e, cx)).ok();
3054 }
3055 }
3056}
3057
3058impl<V> Context for ViewContext<'_, V> {
3059 type Result<U> = U;
3060
3061 fn new_model<T: 'static>(
3062 &mut self,
3063 build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
3064 ) -> Model<T> {
3065 self.window_cx.new_model(build_model)
3066 }
3067
3068 fn update_model<T: 'static, R>(
3069 &mut self,
3070 model: &Model<T>,
3071 update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
3072 ) -> R {
3073 self.window_cx.update_model(model, update)
3074 }
3075
3076 fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
3077 where
3078 F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
3079 {
3080 self.window_cx.update_window(window, update)
3081 }
3082
3083 fn read_model<T, R>(
3084 &self,
3085 handle: &Model<T>,
3086 read: impl FnOnce(&T, &AppContext) -> R,
3087 ) -> Self::Result<R>
3088 where
3089 T: 'static,
3090 {
3091 self.window_cx.read_model(handle, read)
3092 }
3093
3094 fn read_window<T, R>(
3095 &self,
3096 window: &WindowHandle<T>,
3097 read: impl FnOnce(View<T>, &AppContext) -> R,
3098 ) -> Result<R>
3099 where
3100 T: 'static,
3101 {
3102 self.window_cx.read_window(window, read)
3103 }
3104}
3105
3106impl<V: 'static> VisualContext for ViewContext<'_, V> {
3107 fn new_view<W: Render + 'static>(
3108 &mut self,
3109 build_view_state: impl FnOnce(&mut ViewContext<'_, W>) -> W,
3110 ) -> Self::Result<View<W>> {
3111 self.window_cx.new_view(build_view_state)
3112 }
3113
3114 fn update_view<V2: 'static, R>(
3115 &mut self,
3116 view: &View<V2>,
3117 update: impl FnOnce(&mut V2, &mut ViewContext<'_, V2>) -> R,
3118 ) -> Self::Result<R> {
3119 self.window_cx.update_view(view, update)
3120 }
3121
3122 fn replace_root_view<W>(
3123 &mut self,
3124 build_view: impl FnOnce(&mut ViewContext<'_, W>) -> W,
3125 ) -> Self::Result<View<W>>
3126 where
3127 W: 'static + Render,
3128 {
3129 self.window_cx.replace_root_view(build_view)
3130 }
3131
3132 fn focus_view<W: FocusableView>(&mut self, view: &View<W>) -> Self::Result<()> {
3133 self.window_cx.focus_view(view)
3134 }
3135
3136 fn dismiss_view<W: ManagedView>(&mut self, view: &View<W>) -> Self::Result<()> {
3137 self.window_cx.dismiss_view(view)
3138 }
3139}
3140
3141impl<'a, V> std::ops::Deref for ViewContext<'a, V> {
3142 type Target = WindowContext<'a>;
3143
3144 fn deref(&self) -> &Self::Target {
3145 &self.window_cx
3146 }
3147}
3148
3149impl<'a, V> std::ops::DerefMut for ViewContext<'a, V> {
3150 fn deref_mut(&mut self) -> &mut Self::Target {
3151 &mut self.window_cx
3152 }
3153}
3154
3155// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
3156slotmap::new_key_type! {
3157 /// A unique identifier for a window.
3158 pub struct WindowId;
3159}
3160
3161impl WindowId {
3162 /// Converts this window ID to a `u64`.
3163 pub fn as_u64(&self) -> u64 {
3164 self.0.as_ffi()
3165 }
3166}
3167
3168/// A handle to a window with a specific root view type.
3169/// Note that this does not keep the window alive on its own.
3170#[derive(Deref, DerefMut)]
3171pub struct WindowHandle<V> {
3172 #[deref]
3173 #[deref_mut]
3174 pub(crate) any_handle: AnyWindowHandle,
3175 state_type: PhantomData<V>,
3176}
3177
3178impl<V: 'static + Render> WindowHandle<V> {
3179 /// Create a new handle from a window ID.
3180 /// This does not check if the root type of the window is `V`.
3181 pub fn new(id: WindowId) -> Self {
3182 WindowHandle {
3183 any_handle: AnyWindowHandle {
3184 id,
3185 state_type: TypeId::of::<V>(),
3186 },
3187 state_type: PhantomData,
3188 }
3189 }
3190
3191 /// Get the root view out of this window.
3192 ///
3193 /// This will fail if the window is closed or if the root view's type does not match `V`.
3194 pub fn root<C>(&self, cx: &mut C) -> Result<View<V>>
3195 where
3196 C: Context,
3197 {
3198 Flatten::flatten(cx.update_window(self.any_handle, |root_view, _| {
3199 root_view
3200 .downcast::<V>()
3201 .map_err(|_| anyhow!("the type of the window's root view has changed"))
3202 }))
3203 }
3204
3205 /// Update the root view of this window.
3206 ///
3207 /// This will fail if the window has been closed or if the root view's type does not match
3208 pub fn update<C, R>(
3209 &self,
3210 cx: &mut C,
3211 update: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
3212 ) -> Result<R>
3213 where
3214 C: Context,
3215 {
3216 cx.update_window(self.any_handle, |root_view, cx| {
3217 let view = root_view
3218 .downcast::<V>()
3219 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
3220 Ok(cx.update_view(&view, update))
3221 })?
3222 }
3223
3224 /// Read the root view out of this window.
3225 ///
3226 /// This will fail if the window is closed or if the root view's type does not match `V`.
3227 pub fn read<'a>(&self, cx: &'a AppContext) -> Result<&'a V> {
3228 let x = cx
3229 .windows
3230 .get(self.id)
3231 .and_then(|window| {
3232 window
3233 .as_ref()
3234 .and_then(|window| window.root_view.clone())
3235 .map(|root_view| root_view.downcast::<V>())
3236 })
3237 .ok_or_else(|| anyhow!("window not found"))?
3238 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
3239
3240 Ok(x.read(cx))
3241 }
3242
3243 /// Read the root view out of this window, with a callback
3244 ///
3245 /// This will fail if the window is closed or if the root view's type does not match `V`.
3246 pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &AppContext) -> R) -> Result<R>
3247 where
3248 C: Context,
3249 {
3250 cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
3251 }
3252
3253 /// Read the root view pointer off of this window.
3254 ///
3255 /// This will fail if the window is closed or if the root view's type does not match `V`.
3256 pub fn root_view<C>(&self, cx: &C) -> Result<View<V>>
3257 where
3258 C: Context,
3259 {
3260 cx.read_window(self, |root_view, _cx| root_view.clone())
3261 }
3262
3263 /// Check if this window is 'active'.
3264 ///
3265 /// Will return `None` if the window is closed.
3266 pub fn is_active(&self, cx: &AppContext) -> Option<bool> {
3267 cx.windows
3268 .get(self.id)
3269 .and_then(|window| window.as_ref().map(|window| window.active))
3270 }
3271}
3272
3273impl<V> Copy for WindowHandle<V> {}
3274
3275impl<V> Clone for WindowHandle<V> {
3276 fn clone(&self) -> Self {
3277 *self
3278 }
3279}
3280
3281impl<V> PartialEq for WindowHandle<V> {
3282 fn eq(&self, other: &Self) -> bool {
3283 self.any_handle == other.any_handle
3284 }
3285}
3286
3287impl<V> Eq for WindowHandle<V> {}
3288
3289impl<V> Hash for WindowHandle<V> {
3290 fn hash<H: Hasher>(&self, state: &mut H) {
3291 self.any_handle.hash(state);
3292 }
3293}
3294
3295impl<V: 'static> From<WindowHandle<V>> for AnyWindowHandle {
3296 fn from(val: WindowHandle<V>) -> Self {
3297 val.any_handle
3298 }
3299}
3300
3301/// A handle to a window with any root view type, which can be downcast to a window with a specific root view type.
3302#[derive(Copy, Clone, PartialEq, Eq, Hash)]
3303pub struct AnyWindowHandle {
3304 pub(crate) id: WindowId,
3305 state_type: TypeId,
3306}
3307
3308impl AnyWindowHandle {
3309 /// Get the ID of this window.
3310 pub fn window_id(&self) -> WindowId {
3311 self.id
3312 }
3313
3314 /// Attempt to convert this handle to a window handle with a specific root view type.
3315 /// If the types do not match, this will return `None`.
3316 pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
3317 if TypeId::of::<T>() == self.state_type {
3318 Some(WindowHandle {
3319 any_handle: *self,
3320 state_type: PhantomData,
3321 })
3322 } else {
3323 None
3324 }
3325 }
3326
3327 /// Update the state of the root view of this window.
3328 ///
3329 /// This will fail if the window has been closed.
3330 pub fn update<C, R>(
3331 self,
3332 cx: &mut C,
3333 update: impl FnOnce(AnyView, &mut WindowContext<'_>) -> R,
3334 ) -> Result<R>
3335 where
3336 C: Context,
3337 {
3338 cx.update_window(self, update)
3339 }
3340
3341 /// Read the state of the root view of this window.
3342 ///
3343 /// This will fail if the window has been closed.
3344 pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(View<T>, &AppContext) -> R) -> Result<R>
3345 where
3346 C: Context,
3347 T: 'static,
3348 {
3349 let view = self
3350 .downcast::<T>()
3351 .context("the type of the window's root view has changed")?;
3352
3353 cx.read_window(&view, read)
3354 }
3355}
3356
3357/// An identifier for an [`Element`](crate::Element).
3358///
3359/// Can be constructed with a string, a number, or both, as well
3360/// as other internal representations.
3361#[derive(Clone, Debug, Eq, PartialEq, Hash)]
3362pub enum ElementId {
3363 /// The ID of a View element
3364 View(EntityId),
3365 /// An integer ID.
3366 Integer(usize),
3367 /// A string based ID.
3368 Name(SharedString),
3369 /// An ID that's equated with a focus handle.
3370 FocusHandle(FocusId),
3371 /// A combination of a name and an integer.
3372 NamedInteger(SharedString, usize),
3373}
3374
3375impl ElementId {
3376 pub(crate) fn from_entity_id(entity_id: EntityId) -> Self {
3377 ElementId::View(entity_id)
3378 }
3379}
3380
3381impl TryInto<SharedString> for ElementId {
3382 type Error = anyhow::Error;
3383
3384 fn try_into(self) -> anyhow::Result<SharedString> {
3385 if let ElementId::Name(name) = self {
3386 Ok(name)
3387 } else {
3388 Err(anyhow!("element id is not string"))
3389 }
3390 }
3391}
3392
3393impl From<usize> for ElementId {
3394 fn from(id: usize) -> Self {
3395 ElementId::Integer(id)
3396 }
3397}
3398
3399impl From<i32> for ElementId {
3400 fn from(id: i32) -> Self {
3401 Self::Integer(id as usize)
3402 }
3403}
3404
3405impl From<SharedString> for ElementId {
3406 fn from(name: SharedString) -> Self {
3407 ElementId::Name(name)
3408 }
3409}
3410
3411impl From<&'static str> for ElementId {
3412 fn from(name: &'static str) -> Self {
3413 ElementId::Name(name.into())
3414 }
3415}
3416
3417impl<'a> From<&'a FocusHandle> for ElementId {
3418 fn from(handle: &'a FocusHandle) -> Self {
3419 ElementId::FocusHandle(handle.id)
3420 }
3421}
3422
3423impl From<(&'static str, EntityId)> for ElementId {
3424 fn from((name, id): (&'static str, EntityId)) -> Self {
3425 ElementId::NamedInteger(name.into(), id.as_u64() as usize)
3426 }
3427}
3428
3429impl From<(&'static str, usize)> for ElementId {
3430 fn from((name, id): (&'static str, usize)) -> Self {
3431 ElementId::NamedInteger(name.into(), id)
3432 }
3433}
3434
3435impl From<(&'static str, u64)> for ElementId {
3436 fn from((name, id): (&'static str, u64)) -> Self {
3437 ElementId::NamedInteger(name.into(), id as usize)
3438 }
3439}
3440
3441/// A rectangle to be rendered in the window at the given position and size.
3442/// Passed as an argument [`WindowContext::paint_quad`].
3443#[derive(Clone)]
3444pub struct PaintQuad {
3445 bounds: Bounds<Pixels>,
3446 corner_radii: Corners<Pixels>,
3447 background: Hsla,
3448 border_widths: Edges<Pixels>,
3449 border_color: Hsla,
3450}
3451
3452impl PaintQuad {
3453 /// Set the corner radii of the quad.
3454 pub fn corner_radii(self, corner_radii: impl Into<Corners<Pixels>>) -> Self {
3455 PaintQuad {
3456 corner_radii: corner_radii.into(),
3457 ..self
3458 }
3459 }
3460
3461 /// Set the border widths of the quad.
3462 pub fn border_widths(self, border_widths: impl Into<Edges<Pixels>>) -> Self {
3463 PaintQuad {
3464 border_widths: border_widths.into(),
3465 ..self
3466 }
3467 }
3468
3469 /// Set the border color of the quad.
3470 pub fn border_color(self, border_color: impl Into<Hsla>) -> Self {
3471 PaintQuad {
3472 border_color: border_color.into(),
3473 ..self
3474 }
3475 }
3476
3477 /// Set the background color of the quad.
3478 pub fn background(self, background: impl Into<Hsla>) -> Self {
3479 PaintQuad {
3480 background: background.into(),
3481 ..self
3482 }
3483 }
3484}
3485
3486/// Create a quad with the given parameters.
3487pub fn quad(
3488 bounds: Bounds<Pixels>,
3489 corner_radii: impl Into<Corners<Pixels>>,
3490 background: impl Into<Hsla>,
3491 border_widths: impl Into<Edges<Pixels>>,
3492 border_color: impl Into<Hsla>,
3493) -> PaintQuad {
3494 PaintQuad {
3495 bounds,
3496 corner_radii: corner_radii.into(),
3497 background: background.into(),
3498 border_widths: border_widths.into(),
3499 border_color: border_color.into(),
3500 }
3501}
3502
3503/// Create a filled quad with the given bounds and background color.
3504pub fn fill(bounds: impl Into<Bounds<Pixels>>, background: impl Into<Hsla>) -> PaintQuad {
3505 PaintQuad {
3506 bounds: bounds.into(),
3507 corner_radii: (0.).into(),
3508 background: background.into(),
3509 border_widths: (0.).into(),
3510 border_color: transparent_black(),
3511 }
3512}
3513
3514/// Create a rectangle outline with the given bounds, border color, and a 1px border width
3515pub fn outline(bounds: impl Into<Bounds<Pixels>>, border_color: impl Into<Hsla>) -> PaintQuad {
3516 PaintQuad {
3517 bounds: bounds.into(),
3518 corner_radii: (0.).into(),
3519 background: transparent_black(),
3520 border_widths: (1.).into(),
3521 border_color: border_color.into(),
3522 }
3523}