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