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 {
2765 if !self.window.dirty_views.insert(view_id) {
2766 break;
2767 }
2768 }
2769
2770 if !self.window.drawing {
2771 self.window_cx.window.dirty = true;
2772 self.window_cx.app.push_effect(Effect::Notify {
2773 emitter: self.view.model.entity_id,
2774 });
2775 }
2776 }
2777
2778 /// Register a callback to be invoked when the window is resized.
2779 pub fn observe_window_bounds(
2780 &mut self,
2781 mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2782 ) -> Subscription {
2783 let view = self.view.downgrade();
2784 let (subscription, activate) = self.window.bounds_observers.insert(
2785 (),
2786 Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
2787 );
2788 activate();
2789 subscription
2790 }
2791
2792 /// Register a callback to be invoked when the window is activated or deactivated.
2793 pub fn observe_window_activation(
2794 &mut self,
2795 mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2796 ) -> Subscription {
2797 let view = self.view.downgrade();
2798 let (subscription, activate) = self.window.activation_observers.insert(
2799 (),
2800 Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
2801 );
2802 activate();
2803 subscription
2804 }
2805
2806 /// Register a listener to be called when the given focus handle receives focus.
2807 /// Returns a subscription and persists until the subscription is dropped.
2808 pub fn on_focus(
2809 &mut self,
2810 handle: &FocusHandle,
2811 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2812 ) -> Subscription {
2813 let view = self.view.downgrade();
2814 let focus_id = handle.id;
2815 let (subscription, activate) = self.window.focus_listeners.insert(
2816 (),
2817 Box::new(move |event, cx| {
2818 view.update(cx, |view, cx| {
2819 if event.previous_focus_path.last() != Some(&focus_id)
2820 && event.current_focus_path.last() == Some(&focus_id)
2821 {
2822 listener(view, cx)
2823 }
2824 })
2825 .is_ok()
2826 }),
2827 );
2828 self.app.defer(move |_| activate());
2829 subscription
2830 }
2831
2832 /// Register a listener to be called when the given focus handle or one of its descendants receives focus.
2833 /// Returns a subscription and persists until the subscription is dropped.
2834 pub fn on_focus_in(
2835 &mut self,
2836 handle: &FocusHandle,
2837 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2838 ) -> Subscription {
2839 let view = self.view.downgrade();
2840 let focus_id = handle.id;
2841 let (subscription, activate) = self.window.focus_listeners.insert(
2842 (),
2843 Box::new(move |event, cx| {
2844 view.update(cx, |view, cx| {
2845 if !event.previous_focus_path.contains(&focus_id)
2846 && event.current_focus_path.contains(&focus_id)
2847 {
2848 listener(view, cx)
2849 }
2850 })
2851 .is_ok()
2852 }),
2853 );
2854 self.app.defer(move |_| activate());
2855 subscription
2856 }
2857
2858 /// Register a listener to be called when the given focus handle loses focus.
2859 /// Returns a subscription and persists until the subscription is dropped.
2860 pub fn on_blur(
2861 &mut self,
2862 handle: &FocusHandle,
2863 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2864 ) -> Subscription {
2865 let view = self.view.downgrade();
2866 let focus_id = handle.id;
2867 let (subscription, activate) = self.window.focus_listeners.insert(
2868 (),
2869 Box::new(move |event, cx| {
2870 view.update(cx, |view, cx| {
2871 if event.previous_focus_path.last() == Some(&focus_id)
2872 && event.current_focus_path.last() != Some(&focus_id)
2873 {
2874 listener(view, cx)
2875 }
2876 })
2877 .is_ok()
2878 }),
2879 );
2880 self.app.defer(move |_| activate());
2881 subscription
2882 }
2883
2884 /// Register a listener to be called when nothing in the window has focus.
2885 /// This typically happens when the node that was focused is removed from the tree,
2886 /// and this callback lets you chose a default place to restore the users focus.
2887 /// Returns a subscription and persists until the subscription is dropped.
2888 pub fn on_focus_lost(
2889 &mut self,
2890 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2891 ) -> Subscription {
2892 let view = self.view.downgrade();
2893 let (subscription, activate) = self.window.focus_lost_listeners.insert(
2894 (),
2895 Box::new(move |cx| view.update(cx, |view, cx| listener(view, cx)).is_ok()),
2896 );
2897 activate();
2898 subscription
2899 }
2900
2901 /// Register a listener to be called when the given focus handle or one of its descendants loses focus.
2902 /// Returns a subscription and persists until the subscription is dropped.
2903 pub fn on_focus_out(
2904 &mut self,
2905 handle: &FocusHandle,
2906 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2907 ) -> Subscription {
2908 let view = self.view.downgrade();
2909 let focus_id = handle.id;
2910 let (subscription, activate) = self.window.focus_listeners.insert(
2911 (),
2912 Box::new(move |event, cx| {
2913 view.update(cx, |view, cx| {
2914 if event.previous_focus_path.contains(&focus_id)
2915 && !event.current_focus_path.contains(&focus_id)
2916 {
2917 listener(view, cx)
2918 }
2919 })
2920 .is_ok()
2921 }),
2922 );
2923 self.app.defer(move |_| activate());
2924 subscription
2925 }
2926
2927 /// Schedule a future to be run asynchronously.
2928 /// The given callback is invoked with a [`WeakView<V>`] to avoid leaking the view for a long-running process.
2929 /// It's also given an [`AsyncWindowContext`], which can be used to access the state of the view across await points.
2930 /// The returned future will be polled on the main thread.
2931 pub fn spawn<Fut, R>(
2932 &mut self,
2933 f: impl FnOnce(WeakView<V>, AsyncWindowContext) -> Fut,
2934 ) -> Task<R>
2935 where
2936 R: 'static,
2937 Fut: Future<Output = R> + 'static,
2938 {
2939 let view = self.view().downgrade();
2940 self.window_cx.spawn(|cx| f(view, cx))
2941 }
2942
2943 /// Update the global state of the given type.
2944 pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
2945 where
2946 G: 'static,
2947 {
2948 let mut global = self.app.lease_global::<G>();
2949 let result = f(&mut global, self);
2950 self.app.end_global_lease(global);
2951 result
2952 }
2953
2954 /// Register a callback to be invoked when the given global state changes.
2955 pub fn observe_global<G: 'static>(
2956 &mut self,
2957 mut f: impl FnMut(&mut V, &mut ViewContext<'_, V>) + 'static,
2958 ) -> Subscription {
2959 let window_handle = self.window.handle;
2960 let view = self.view().downgrade();
2961 let (subscription, activate) = self.global_observers.insert(
2962 TypeId::of::<G>(),
2963 Box::new(move |cx| {
2964 window_handle
2965 .update(cx, |_, cx| view.update(cx, |view, cx| f(view, cx)).is_ok())
2966 .unwrap_or(false)
2967 }),
2968 );
2969 self.app.defer(move |_| activate());
2970 subscription
2971 }
2972
2973 /// Add a listener for any mouse event that occurs in the window.
2974 /// This is a fairly low level method.
2975 /// Typically, you'll want to use methods on UI elements, which perform bounds checking etc.
2976 pub fn on_mouse_event<Event: 'static>(
2977 &mut self,
2978 handler: impl Fn(&mut V, &Event, DispatchPhase, &mut ViewContext<V>) + 'static,
2979 ) {
2980 let handle = self.view().clone();
2981 self.window_cx.on_mouse_event(move |event, phase, cx| {
2982 handle.update(cx, |view, cx| {
2983 handler(view, event, phase, cx);
2984 })
2985 });
2986 }
2987
2988 /// Register a callback to be invoked when the given Key Event is dispatched to the window.
2989 pub fn on_key_event<Event: 'static>(
2990 &mut self,
2991 handler: impl Fn(&mut V, &Event, DispatchPhase, &mut ViewContext<V>) + 'static,
2992 ) {
2993 let handle = self.view().clone();
2994 self.window_cx.on_key_event(move |event, phase, cx| {
2995 handle.update(cx, |view, cx| {
2996 handler(view, event, phase, cx);
2997 })
2998 });
2999 }
3000
3001 /// Register a callback to be invoked when the given Action type is dispatched to the window.
3002 pub fn on_action(
3003 &mut self,
3004 action_type: TypeId,
3005 listener: impl Fn(&mut V, &dyn Any, DispatchPhase, &mut ViewContext<V>) + 'static,
3006 ) {
3007 let handle = self.view().clone();
3008 self.window_cx
3009 .on_action(action_type, move |action, phase, cx| {
3010 handle.update(cx, |view, cx| {
3011 listener(view, action, phase, cx);
3012 })
3013 });
3014 }
3015
3016 /// Emit an event to be handled any other views that have subscribed via [ViewContext::subscribe].
3017 pub fn emit<Evt>(&mut self, event: Evt)
3018 where
3019 Evt: 'static,
3020 V: EventEmitter<Evt>,
3021 {
3022 let emitter = self.view.model.entity_id;
3023 self.app.push_effect(Effect::Emit {
3024 emitter,
3025 event_type: TypeId::of::<Evt>(),
3026 event: Box::new(event),
3027 });
3028 }
3029
3030 /// Move focus to the current view, assuming it implements [`FocusableView`].
3031 pub fn focus_self(&mut self)
3032 where
3033 V: FocusableView,
3034 {
3035 self.defer(|view, cx| view.focus_handle(cx).focus(cx))
3036 }
3037
3038 /// Convenience method for accessing view state in an event callback.
3039 ///
3040 /// Many GPUI callbacks take the form of `Fn(&E, &mut WindowContext)`,
3041 /// but it's often useful to be able to access view state in these
3042 /// callbacks. This method provides a convenient way to do so.
3043 pub fn listener<E>(
3044 &self,
3045 f: impl Fn(&mut V, &E, &mut ViewContext<V>) + 'static,
3046 ) -> impl Fn(&E, &mut WindowContext) + 'static {
3047 let view = self.view().downgrade();
3048 move |e: &E, cx: &mut WindowContext| {
3049 view.update(cx, |view, cx| f(view, e, cx)).ok();
3050 }
3051 }
3052}
3053
3054impl<V> Context for ViewContext<'_, V> {
3055 type Result<U> = U;
3056
3057 fn new_model<T: 'static>(
3058 &mut self,
3059 build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
3060 ) -> Model<T> {
3061 self.window_cx.new_model(build_model)
3062 }
3063
3064 fn update_model<T: 'static, R>(
3065 &mut self,
3066 model: &Model<T>,
3067 update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
3068 ) -> R {
3069 self.window_cx.update_model(model, update)
3070 }
3071
3072 fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
3073 where
3074 F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
3075 {
3076 self.window_cx.update_window(window, update)
3077 }
3078
3079 fn read_model<T, R>(
3080 &self,
3081 handle: &Model<T>,
3082 read: impl FnOnce(&T, &AppContext) -> R,
3083 ) -> Self::Result<R>
3084 where
3085 T: 'static,
3086 {
3087 self.window_cx.read_model(handle, read)
3088 }
3089
3090 fn read_window<T, R>(
3091 &self,
3092 window: &WindowHandle<T>,
3093 read: impl FnOnce(View<T>, &AppContext) -> R,
3094 ) -> Result<R>
3095 where
3096 T: 'static,
3097 {
3098 self.window_cx.read_window(window, read)
3099 }
3100}
3101
3102impl<V: 'static> VisualContext for ViewContext<'_, V> {
3103 fn new_view<W: Render + 'static>(
3104 &mut self,
3105 build_view_state: impl FnOnce(&mut ViewContext<'_, W>) -> W,
3106 ) -> Self::Result<View<W>> {
3107 self.window_cx.new_view(build_view_state)
3108 }
3109
3110 fn update_view<V2: 'static, R>(
3111 &mut self,
3112 view: &View<V2>,
3113 update: impl FnOnce(&mut V2, &mut ViewContext<'_, V2>) -> R,
3114 ) -> Self::Result<R> {
3115 self.window_cx.update_view(view, update)
3116 }
3117
3118 fn replace_root_view<W>(
3119 &mut self,
3120 build_view: impl FnOnce(&mut ViewContext<'_, W>) -> W,
3121 ) -> Self::Result<View<W>>
3122 where
3123 W: 'static + Render,
3124 {
3125 self.window_cx.replace_root_view(build_view)
3126 }
3127
3128 fn focus_view<W: FocusableView>(&mut self, view: &View<W>) -> Self::Result<()> {
3129 self.window_cx.focus_view(view)
3130 }
3131
3132 fn dismiss_view<W: ManagedView>(&mut self, view: &View<W>) -> Self::Result<()> {
3133 self.window_cx.dismiss_view(view)
3134 }
3135}
3136
3137impl<'a, V> std::ops::Deref for ViewContext<'a, V> {
3138 type Target = WindowContext<'a>;
3139
3140 fn deref(&self) -> &Self::Target {
3141 &self.window_cx
3142 }
3143}
3144
3145impl<'a, V> std::ops::DerefMut for ViewContext<'a, V> {
3146 fn deref_mut(&mut self) -> &mut Self::Target {
3147 &mut self.window_cx
3148 }
3149}
3150
3151// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
3152slotmap::new_key_type! {
3153 /// A unique identifier for a window.
3154 pub struct WindowId;
3155}
3156
3157impl WindowId {
3158 /// Converts this window ID to a `u64`.
3159 pub fn as_u64(&self) -> u64 {
3160 self.0.as_ffi()
3161 }
3162}
3163
3164/// A handle to a window with a specific root view type.
3165/// Note that this does not keep the window alive on its own.
3166#[derive(Deref, DerefMut)]
3167pub struct WindowHandle<V> {
3168 #[deref]
3169 #[deref_mut]
3170 pub(crate) any_handle: AnyWindowHandle,
3171 state_type: PhantomData<V>,
3172}
3173
3174impl<V: 'static + Render> WindowHandle<V> {
3175 /// Create a new handle from a window ID.
3176 /// This does not check if the root type of the window is `V`.
3177 pub fn new(id: WindowId) -> Self {
3178 WindowHandle {
3179 any_handle: AnyWindowHandle {
3180 id,
3181 state_type: TypeId::of::<V>(),
3182 },
3183 state_type: PhantomData,
3184 }
3185 }
3186
3187 /// Get the root view out of this window.
3188 ///
3189 /// This will fail if the window is closed or if the root view's type does not match `V`.
3190 pub fn root<C>(&self, cx: &mut C) -> Result<View<V>>
3191 where
3192 C: Context,
3193 {
3194 Flatten::flatten(cx.update_window(self.any_handle, |root_view, _| {
3195 root_view
3196 .downcast::<V>()
3197 .map_err(|_| anyhow!("the type of the window's root view has changed"))
3198 }))
3199 }
3200
3201 /// Update the root view of this window.
3202 ///
3203 /// This will fail if the window has been closed or if the root view's type does not match
3204 pub fn update<C, R>(
3205 &self,
3206 cx: &mut C,
3207 update: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
3208 ) -> Result<R>
3209 where
3210 C: Context,
3211 {
3212 cx.update_window(self.any_handle, |root_view, cx| {
3213 let view = root_view
3214 .downcast::<V>()
3215 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
3216 Ok(cx.update_view(&view, update))
3217 })?
3218 }
3219
3220 /// Read the root view out of this window.
3221 ///
3222 /// This will fail if the window is closed or if the root view's type does not match `V`.
3223 pub fn read<'a>(&self, cx: &'a AppContext) -> Result<&'a V> {
3224 let x = cx
3225 .windows
3226 .get(self.id)
3227 .and_then(|window| {
3228 window
3229 .as_ref()
3230 .and_then(|window| window.root_view.clone())
3231 .map(|root_view| root_view.downcast::<V>())
3232 })
3233 .ok_or_else(|| anyhow!("window not found"))?
3234 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
3235
3236 Ok(x.read(cx))
3237 }
3238
3239 /// Read the root view out of this window, with a callback
3240 ///
3241 /// This will fail if the window is closed or if the root view's type does not match `V`.
3242 pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &AppContext) -> R) -> Result<R>
3243 where
3244 C: Context,
3245 {
3246 cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
3247 }
3248
3249 /// Read the root view pointer off of this window.
3250 ///
3251 /// This will fail if the window is closed or if the root view's type does not match `V`.
3252 pub fn root_view<C>(&self, cx: &C) -> Result<View<V>>
3253 where
3254 C: Context,
3255 {
3256 cx.read_window(self, |root_view, _cx| root_view.clone())
3257 }
3258
3259 /// Check if this window is 'active'.
3260 ///
3261 /// Will return `None` if the window is closed.
3262 pub fn is_active(&self, cx: &AppContext) -> Option<bool> {
3263 cx.windows
3264 .get(self.id)
3265 .and_then(|window| window.as_ref().map(|window| window.active))
3266 }
3267}
3268
3269impl<V> Copy for WindowHandle<V> {}
3270
3271impl<V> Clone for WindowHandle<V> {
3272 fn clone(&self) -> Self {
3273 *self
3274 }
3275}
3276
3277impl<V> PartialEq for WindowHandle<V> {
3278 fn eq(&self, other: &Self) -> bool {
3279 self.any_handle == other.any_handle
3280 }
3281}
3282
3283impl<V> Eq for WindowHandle<V> {}
3284
3285impl<V> Hash for WindowHandle<V> {
3286 fn hash<H: Hasher>(&self, state: &mut H) {
3287 self.any_handle.hash(state);
3288 }
3289}
3290
3291impl<V: 'static> From<WindowHandle<V>> for AnyWindowHandle {
3292 fn from(val: WindowHandle<V>) -> Self {
3293 val.any_handle
3294 }
3295}
3296
3297/// A handle to a window with any root view type, which can be downcast to a window with a specific root view type.
3298#[derive(Copy, Clone, PartialEq, Eq, Hash)]
3299pub struct AnyWindowHandle {
3300 pub(crate) id: WindowId,
3301 state_type: TypeId,
3302}
3303
3304impl AnyWindowHandle {
3305 /// Get the ID of this window.
3306 pub fn window_id(&self) -> WindowId {
3307 self.id
3308 }
3309
3310 /// Attempt to convert this handle to a window handle with a specific root view type.
3311 /// If the types do not match, this will return `None`.
3312 pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
3313 if TypeId::of::<T>() == self.state_type {
3314 Some(WindowHandle {
3315 any_handle: *self,
3316 state_type: PhantomData,
3317 })
3318 } else {
3319 None
3320 }
3321 }
3322
3323 /// Update the state of the root view of this window.
3324 ///
3325 /// This will fail if the window has been closed.
3326 pub fn update<C, R>(
3327 self,
3328 cx: &mut C,
3329 update: impl FnOnce(AnyView, &mut WindowContext<'_>) -> R,
3330 ) -> Result<R>
3331 where
3332 C: Context,
3333 {
3334 cx.update_window(self, update)
3335 }
3336
3337 /// Read the state of the root view of this window.
3338 ///
3339 /// This will fail if the window has been closed.
3340 pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(View<T>, &AppContext) -> R) -> Result<R>
3341 where
3342 C: Context,
3343 T: 'static,
3344 {
3345 let view = self
3346 .downcast::<T>()
3347 .context("the type of the window's root view has changed")?;
3348
3349 cx.read_window(&view, read)
3350 }
3351}
3352
3353/// An identifier for an [`Element`](crate::Element).
3354///
3355/// Can be constructed with a string, a number, or both, as well
3356/// as other internal representations.
3357#[derive(Clone, Debug, Eq, PartialEq, Hash)]
3358pub enum ElementId {
3359 /// The ID of a View element
3360 View(EntityId),
3361 /// An integer ID.
3362 Integer(usize),
3363 /// A string based ID.
3364 Name(SharedString),
3365 /// An ID that's equated with a focus handle.
3366 FocusHandle(FocusId),
3367 /// A combination of a name and an integer.
3368 NamedInteger(SharedString, usize),
3369}
3370
3371impl ElementId {
3372 pub(crate) fn from_entity_id(entity_id: EntityId) -> Self {
3373 ElementId::View(entity_id)
3374 }
3375}
3376
3377impl TryInto<SharedString> for ElementId {
3378 type Error = anyhow::Error;
3379
3380 fn try_into(self) -> anyhow::Result<SharedString> {
3381 if let ElementId::Name(name) = self {
3382 Ok(name)
3383 } else {
3384 Err(anyhow!("element id is not string"))
3385 }
3386 }
3387}
3388
3389impl From<usize> for ElementId {
3390 fn from(id: usize) -> Self {
3391 ElementId::Integer(id)
3392 }
3393}
3394
3395impl From<i32> for ElementId {
3396 fn from(id: i32) -> Self {
3397 Self::Integer(id as usize)
3398 }
3399}
3400
3401impl From<SharedString> for ElementId {
3402 fn from(name: SharedString) -> Self {
3403 ElementId::Name(name)
3404 }
3405}
3406
3407impl From<&'static str> for ElementId {
3408 fn from(name: &'static str) -> Self {
3409 ElementId::Name(name.into())
3410 }
3411}
3412
3413impl<'a> From<&'a FocusHandle> for ElementId {
3414 fn from(handle: &'a FocusHandle) -> Self {
3415 ElementId::FocusHandle(handle.id)
3416 }
3417}
3418
3419impl From<(&'static str, EntityId)> for ElementId {
3420 fn from((name, id): (&'static str, EntityId)) -> Self {
3421 ElementId::NamedInteger(name.into(), id.as_u64() as usize)
3422 }
3423}
3424
3425impl From<(&'static str, usize)> for ElementId {
3426 fn from((name, id): (&'static str, usize)) -> Self {
3427 ElementId::NamedInteger(name.into(), id)
3428 }
3429}
3430
3431impl From<(&'static str, u64)> for ElementId {
3432 fn from((name, id): (&'static str, u64)) -> Self {
3433 ElementId::NamedInteger(name.into(), id as usize)
3434 }
3435}
3436
3437/// A rectangle to be rendered in the window at the given position and size.
3438/// Passed as an argument [`WindowContext::paint_quad`].
3439#[derive(Clone)]
3440pub struct PaintQuad {
3441 bounds: Bounds<Pixels>,
3442 corner_radii: Corners<Pixels>,
3443 background: Hsla,
3444 border_widths: Edges<Pixels>,
3445 border_color: Hsla,
3446}
3447
3448impl PaintQuad {
3449 /// Set the corner radii of the quad.
3450 pub fn corner_radii(self, corner_radii: impl Into<Corners<Pixels>>) -> Self {
3451 PaintQuad {
3452 corner_radii: corner_radii.into(),
3453 ..self
3454 }
3455 }
3456
3457 /// Set the border widths of the quad.
3458 pub fn border_widths(self, border_widths: impl Into<Edges<Pixels>>) -> Self {
3459 PaintQuad {
3460 border_widths: border_widths.into(),
3461 ..self
3462 }
3463 }
3464
3465 /// Set the border color of the quad.
3466 pub fn border_color(self, border_color: impl Into<Hsla>) -> Self {
3467 PaintQuad {
3468 border_color: border_color.into(),
3469 ..self
3470 }
3471 }
3472
3473 /// Set the background color of the quad.
3474 pub fn background(self, background: impl Into<Hsla>) -> Self {
3475 PaintQuad {
3476 background: background.into(),
3477 ..self
3478 }
3479 }
3480}
3481
3482/// Create a quad with the given parameters.
3483pub fn quad(
3484 bounds: Bounds<Pixels>,
3485 corner_radii: impl Into<Corners<Pixels>>,
3486 background: impl Into<Hsla>,
3487 border_widths: impl Into<Edges<Pixels>>,
3488 border_color: impl Into<Hsla>,
3489) -> PaintQuad {
3490 PaintQuad {
3491 bounds,
3492 corner_radii: corner_radii.into(),
3493 background: background.into(),
3494 border_widths: border_widths.into(),
3495 border_color: border_color.into(),
3496 }
3497}
3498
3499/// Create a filled quad with the given bounds and background color.
3500pub fn fill(bounds: impl Into<Bounds<Pixels>>, background: impl Into<Hsla>) -> PaintQuad {
3501 PaintQuad {
3502 bounds: bounds.into(),
3503 corner_radii: (0.).into(),
3504 background: background.into(),
3505 border_widths: (0.).into(),
3506 border_color: transparent_black(),
3507 }
3508}
3509
3510/// Create a rectangle outline with the given bounds, border color, and a 1px border width
3511pub fn outline(bounds: impl Into<Bounds<Pixels>>, border_color: impl Into<Hsla>) -> PaintQuad {
3512 PaintQuad {
3513 bounds: bounds.into(),
3514 corner_radii: (0.).into(),
3515 background: transparent_black(),
3516 border_widths: (1.).into(),
3517 border_color: border_color.into(),
3518 }
3519}