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