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