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