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