1use crate::{
2 point, px, size, transparent_black, Action, AnyDrag, AnyView, AppContext, Arena,
3 AsyncWindowContext, Bounds, Context, Corners, CursorStyle, DispatchActionListener,
4 DispatchNodeId, DispatchTree, DisplayId, Edges, Effect, Entity, EntityId, EventEmitter,
5 FileDropEvent, Flatten, Global, GlobalElementId, GlobalPixels, Hsla, KeyBinding, KeyDownEvent,
6 KeyMatch, KeymatchResult, Keystroke, KeystrokeEvent, Model, ModelContext, Modifiers,
7 MouseButton, MouseMoveEvent, MouseUpEvent, Pixels, PlatformAtlas, PlatformDisplay,
8 PlatformInput, PlatformWindow, Point, PromptLevel, Render, ScaledPixels, SharedString, Size,
9 SubscriberSet, Subscription, TaffyLayoutEngine, Task, TextStyle, TextStyleRefinement, View,
10 VisualContext, WeakView, WindowAppearance, WindowOptions, WindowParams, WindowTextSystem,
11};
12use anyhow::{anyhow, Context as _, Result};
13use collections::FxHashSet;
14use derive_more::{Deref, DerefMut};
15use futures::channel::oneshot;
16use parking_lot::RwLock;
17use refineable::Refineable;
18use slotmap::SlotMap;
19use smallvec::SmallVec;
20use std::{
21 any::{Any, TypeId},
22 borrow::{Borrow, BorrowMut},
23 cell::{Cell, RefCell},
24 fmt::{Debug, Display},
25 future::Future,
26 hash::{Hash, Hasher},
27 marker::PhantomData,
28 mem,
29 rc::Rc,
30 sync::{
31 atomic::{AtomicUsize, Ordering::SeqCst},
32 Arc, Weak,
33 },
34 time::{Duration, Instant},
35};
36use util::{measure, ResultExt};
37
38mod element_cx;
39mod prompts;
40
41pub use element_cx::*;
42pub use prompts::*;
43
44/// Represents the two different phases when dispatching events.
45#[derive(Default, Copy, Clone, Debug, Eq, PartialEq)]
46pub enum DispatchPhase {
47 /// After the capture phase comes the bubble phase, in which mouse event listeners are
48 /// invoked front to back and keyboard event listeners are invoked from the focused element
49 /// to the root of the element tree. This is the phase you'll most commonly want to use when
50 /// registering event listeners.
51 #[default]
52 Bubble,
53 /// During the initial capture phase, mouse event listeners are invoked back to front, and keyboard
54 /// listeners are invoked from the root of the tree downward toward the focused element. This phase
55 /// is used for special purposes such as clearing the "pressed" state for click events. If
56 /// you stop event propagation during this phase, you need to know what you're doing. Handlers
57 /// outside of the immediate region may rely on detecting non-local events during this phase.
58 Capture,
59}
60
61impl DispatchPhase {
62 /// Returns true if this represents the "bubble" phase.
63 pub fn bubble(self) -> bool {
64 self == DispatchPhase::Bubble
65 }
66
67 /// Returns true if this represents the "capture" phase.
68 pub fn capture(self) -> bool {
69 self == DispatchPhase::Capture
70 }
71}
72
73type AnyObserver = Box<dyn FnMut(&mut WindowContext) -> bool + 'static>;
74
75type AnyWindowFocusListener = Box<dyn FnMut(&FocusEvent, &mut WindowContext) -> bool + 'static>;
76
77struct FocusEvent {
78 previous_focus_path: SmallVec<[FocusId; 8]>,
79 current_focus_path: SmallVec<[FocusId; 8]>,
80}
81
82slotmap::new_key_type! {
83 /// A globally unique identifier for a focusable element.
84 pub struct FocusId;
85}
86
87thread_local! {
88 pub(crate) static ELEMENT_ARENA: RefCell<Arena> = RefCell::new(Arena::new(8 * 1024 * 1024));
89}
90
91impl FocusId {
92 /// Obtains whether the element associated with this handle is currently focused.
93 pub fn is_focused(&self, cx: &WindowContext) -> bool {
94 cx.window.focus == Some(*self)
95 }
96
97 /// Obtains whether the element associated with this handle contains the focused
98 /// element or is itself focused.
99 pub fn contains_focused(&self, cx: &WindowContext) -> bool {
100 cx.focused()
101 .map_or(false, |focused| self.contains(focused.id, cx))
102 }
103
104 /// Obtains whether the element associated with this handle is contained within the
105 /// focused element or is itself focused.
106 pub fn within_focused(&self, cx: &WindowContext) -> bool {
107 let focused = cx.focused();
108 focused.map_or(false, |focused| focused.id.contains(*self, cx))
109 }
110
111 /// Obtains whether this handle contains the given handle in the most recently rendered frame.
112 pub(crate) fn contains(&self, other: Self, cx: &WindowContext) -> bool {
113 cx.window
114 .rendered_frame
115 .dispatch_tree
116 .focus_contains(*self, other)
117 }
118}
119
120/// A handle which can be used to track and manipulate the focused element in a window.
121pub struct FocusHandle {
122 pub(crate) id: FocusId,
123 handles: Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
124}
125
126impl std::fmt::Debug for FocusHandle {
127 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
128 f.write_fmt(format_args!("FocusHandle({:?})", self.id))
129 }
130}
131
132impl FocusHandle {
133 pub(crate) fn new(handles: &Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>) -> Self {
134 let id = handles.write().insert(AtomicUsize::new(1));
135 Self {
136 id,
137 handles: handles.clone(),
138 }
139 }
140
141 pub(crate) fn for_id(
142 id: FocusId,
143 handles: &Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
144 ) -> Option<Self> {
145 let lock = handles.read();
146 let ref_count = lock.get(id)?;
147 if ref_count.load(SeqCst) == 0 {
148 None
149 } else {
150 ref_count.fetch_add(1, SeqCst);
151 Some(Self {
152 id,
153 handles: handles.clone(),
154 })
155 }
156 }
157
158 /// Converts this focus handle into a weak variant, which does not prevent it from being released.
159 pub fn downgrade(&self) -> WeakFocusHandle {
160 WeakFocusHandle {
161 id: self.id,
162 handles: Arc::downgrade(&self.handles),
163 }
164 }
165
166 /// Moves the focus to the element associated with this handle.
167 pub fn focus(&self, cx: &mut WindowContext) {
168 cx.focus(self)
169 }
170
171 /// Obtains whether the element associated with this handle is currently focused.
172 pub fn is_focused(&self, cx: &WindowContext) -> bool {
173 self.id.is_focused(cx)
174 }
175
176 /// Obtains whether the element associated with this handle contains the focused
177 /// element or is itself focused.
178 pub fn contains_focused(&self, cx: &WindowContext) -> bool {
179 self.id.contains_focused(cx)
180 }
181
182 /// Obtains whether the element associated with this handle is contained within the
183 /// focused element or is itself focused.
184 pub fn within_focused(&self, cx: &WindowContext) -> bool {
185 self.id.within_focused(cx)
186 }
187
188 /// Obtains whether this handle contains the given handle in the most recently rendered frame.
189 pub fn contains(&self, other: &Self, cx: &WindowContext) -> bool {
190 self.id.contains(other.id, cx)
191 }
192}
193
194impl Clone for FocusHandle {
195 fn clone(&self) -> Self {
196 Self::for_id(self.id, &self.handles).unwrap()
197 }
198}
199
200impl PartialEq for FocusHandle {
201 fn eq(&self, other: &Self) -> bool {
202 self.id == other.id
203 }
204}
205
206impl Eq for FocusHandle {}
207
208impl Drop for FocusHandle {
209 fn drop(&mut self) {
210 self.handles
211 .read()
212 .get(self.id)
213 .unwrap()
214 .fetch_sub(1, SeqCst);
215 }
216}
217
218/// A weak reference to a focus handle.
219#[derive(Clone, Debug)]
220pub struct WeakFocusHandle {
221 pub(crate) id: FocusId,
222 handles: Weak<RwLock<SlotMap<FocusId, AtomicUsize>>>,
223}
224
225impl WeakFocusHandle {
226 /// Attempts to upgrade the [WeakFocusHandle] to a [FocusHandle].
227 pub fn upgrade(&self) -> Option<FocusHandle> {
228 let handles = self.handles.upgrade()?;
229 FocusHandle::for_id(self.id, &handles)
230 }
231}
232
233impl PartialEq for WeakFocusHandle {
234 fn eq(&self, other: &WeakFocusHandle) -> bool {
235 self.id == other.id
236 }
237}
238
239impl Eq for WeakFocusHandle {}
240
241impl PartialEq<FocusHandle> for WeakFocusHandle {
242 fn eq(&self, other: &FocusHandle) -> bool {
243 self.id == other.id
244 }
245}
246
247impl PartialEq<WeakFocusHandle> for FocusHandle {
248 fn eq(&self, other: &WeakFocusHandle) -> bool {
249 self.id == other.id
250 }
251}
252
253/// FocusableView allows users of your view to easily
254/// focus it (using cx.focus_view(view))
255pub trait FocusableView: 'static + Render {
256 /// Returns the focus handle associated with this view.
257 fn focus_handle(&self, cx: &AppContext) -> FocusHandle;
258}
259
260/// ManagedView is a view (like a Modal, Popover, Menu, etc.)
261/// where the lifecycle of the view is handled by another view.
262pub trait ManagedView: FocusableView + EventEmitter<DismissEvent> {}
263
264impl<M: FocusableView + EventEmitter<DismissEvent>> ManagedView for M {}
265
266/// Emitted by implementers of [`ManagedView`] to indicate the view should be dismissed, such as when a view is presented as a modal.
267pub struct DismissEvent;
268
269type FrameCallback = Box<dyn FnOnce(&mut WindowContext)>;
270
271// Holds the state for a specific window.
272#[doc(hidden)]
273pub struct Window {
274 pub(crate) handle: AnyWindowHandle,
275 pub(crate) removed: bool,
276 pub(crate) platform_window: Box<dyn PlatformWindow>,
277 display_id: DisplayId,
278 sprite_atlas: Arc<dyn PlatformAtlas>,
279 text_system: Arc<WindowTextSystem>,
280 pub(crate) rem_size: Pixels,
281 pub(crate) viewport_size: Size<Pixels>,
282 layout_engine: Option<TaffyLayoutEngine>,
283 pub(crate) root_view: Option<AnyView>,
284 pub(crate) element_id_stack: GlobalElementId,
285 pub(crate) text_style_stack: Vec<TextStyleRefinement>,
286 pub(crate) rendered_frame: Frame,
287 pub(crate) next_frame: Frame,
288 pub(crate) next_hitbox_id: HitboxId,
289 next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>>,
290 pub(crate) dirty_views: FxHashSet<EntityId>,
291 pub(crate) focus_handles: Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
292 focus_listeners: SubscriberSet<(), AnyWindowFocusListener>,
293 focus_lost_listeners: SubscriberSet<(), AnyObserver>,
294 default_prevented: bool,
295 mouse_position: Point<Pixels>,
296 mouse_hit_test: HitTest,
297 modifiers: Modifiers,
298 scale_factor: f32,
299 bounds_observers: SubscriberSet<(), AnyObserver>,
300 appearance: WindowAppearance,
301 appearance_observers: SubscriberSet<(), AnyObserver>,
302 active: Rc<Cell<bool>>,
303 pub(crate) dirty: Rc<Cell<bool>>,
304 pub(crate) needs_present: Rc<Cell<bool>>,
305 pub(crate) last_input_timestamp: Rc<Cell<Instant>>,
306 pub(crate) refreshing: bool,
307 pub(crate) draw_phase: DrawPhase,
308 activation_observers: SubscriberSet<(), AnyObserver>,
309 pub(crate) focus: Option<FocusId>,
310 focus_enabled: bool,
311 pending_input: Option<PendingInput>,
312 prompt: Option<RenderablePromptHandle>,
313}
314
315#[derive(Clone, Copy, Debug, Eq, PartialEq)]
316pub(crate) enum DrawPhase {
317 None,
318 Layout,
319 Paint,
320 Focus,
321}
322
323#[derive(Default, Debug)]
324struct PendingInput {
325 keystrokes: SmallVec<[Keystroke; 1]>,
326 bindings: SmallVec<[KeyBinding; 1]>,
327 focus: Option<FocusId>,
328 timer: Option<Task<()>>,
329}
330
331impl PendingInput {
332 fn input(&self) -> String {
333 self.keystrokes
334 .iter()
335 .flat_map(|k| k.ime_key.clone())
336 .collect::<Vec<String>>()
337 .join("")
338 }
339
340 fn used_by_binding(&self, binding: &KeyBinding) -> bool {
341 if self.keystrokes.is_empty() {
342 return true;
343 }
344 let keystroke = &self.keystrokes[0];
345 for candidate in keystroke.match_candidates() {
346 if binding.match_keystrokes(&[candidate]) == KeyMatch::Pending {
347 return true;
348 }
349 }
350 false
351 }
352}
353
354pub(crate) struct ElementStateBox {
355 pub(crate) inner: Box<dyn Any>,
356 #[cfg(debug_assertions)]
357 pub(crate) type_name: &'static str,
358}
359
360fn default_bounds(cx: &mut AppContext) -> Bounds<GlobalPixels> {
361 const DEFAULT_WINDOW_SIZE: Size<GlobalPixels> = size(GlobalPixels(1024.0), GlobalPixels(700.0));
362 const DEFAULT_WINDOW_OFFSET: Point<GlobalPixels> = point(GlobalPixels(0.0), GlobalPixels(35.0));
363
364 cx.active_window()
365 .and_then(|w| w.update(cx, |_, cx| cx.window_bounds()).ok())
366 .map(|bounds| bounds.map_origin(|origin| origin + DEFAULT_WINDOW_OFFSET))
367 .unwrap_or_else(|| {
368 cx.primary_display()
369 .map(|display| {
370 let center = display.bounds().center();
371 let offset = DEFAULT_WINDOW_SIZE / 2.0;
372 let origin = point(center.x - offset.width, center.y - offset.height);
373 Bounds::new(origin, DEFAULT_WINDOW_SIZE)
374 })
375 .unwrap_or_else(|| {
376 Bounds::new(
377 point(GlobalPixels(0.0), GlobalPixels(0.0)),
378 DEFAULT_WINDOW_SIZE,
379 )
380 })
381 })
382}
383
384impl Window {
385 pub(crate) fn new(
386 handle: AnyWindowHandle,
387 options: WindowOptions,
388 cx: &mut AppContext,
389 ) -> Self {
390 let WindowOptions {
391 bounds,
392 titlebar,
393 focus,
394 show,
395 kind,
396 is_movable,
397 display_id,
398 fullscreen,
399 } = options;
400
401 let bounds = bounds.unwrap_or_else(|| default_bounds(cx));
402 let platform_window = cx.platform.open_window(
403 handle,
404 WindowParams {
405 bounds,
406 titlebar,
407 kind,
408 is_movable,
409 focus,
410 show,
411 display_id,
412 },
413 );
414 let display_id = platform_window.display().id();
415 let sprite_atlas = platform_window.sprite_atlas();
416 let mouse_position = platform_window.mouse_position();
417 let modifiers = platform_window.modifiers();
418 let content_size = platform_window.content_size();
419 let scale_factor = platform_window.scale_factor();
420 let appearance = platform_window.appearance();
421 let text_system = Arc::new(WindowTextSystem::new(cx.text_system().clone()));
422 let dirty = Rc::new(Cell::new(true));
423 let active = Rc::new(Cell::new(false));
424 let needs_present = Rc::new(Cell::new(false));
425 let next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>> = Default::default();
426 let last_input_timestamp = Rc::new(Cell::new(Instant::now()));
427
428 if fullscreen {
429 platform_window.toggle_fullscreen();
430 }
431
432 platform_window.on_close(Box::new({
433 let mut cx = cx.to_async();
434 move || {
435 let _ = handle.update(&mut cx, |_, cx| cx.remove_window());
436 }
437 }));
438 platform_window.on_request_frame(Box::new({
439 let mut cx = cx.to_async();
440 let dirty = dirty.clone();
441 let active = active.clone();
442 let needs_present = needs_present.clone();
443 let next_frame_callbacks = next_frame_callbacks.clone();
444 let last_input_timestamp = last_input_timestamp.clone();
445 move || {
446 let next_frame_callbacks = next_frame_callbacks.take();
447 if !next_frame_callbacks.is_empty() {
448 handle
449 .update(&mut cx, |_, cx| {
450 for callback in next_frame_callbacks {
451 callback(cx);
452 }
453 })
454 .log_err();
455 }
456
457 // Keep presenting the current scene for 1 extra second since the
458 // last input to prevent the display from underclocking the refresh rate.
459 let needs_present = needs_present.get()
460 || (active.get()
461 && last_input_timestamp.get().elapsed() < Duration::from_secs(1));
462
463 if dirty.get() {
464 measure("frame duration", || {
465 handle
466 .update(&mut cx, |_, cx| {
467 cx.draw();
468 cx.present();
469 })
470 .log_err();
471 })
472 } else if needs_present {
473 handle.update(&mut cx, |_, cx| cx.present()).log_err();
474 }
475 }
476 }));
477 platform_window.on_resize(Box::new({
478 let mut cx = cx.to_async();
479 move |_, _| {
480 handle
481 .update(&mut cx, |_, cx| cx.window_bounds_changed())
482 .log_err();
483 }
484 }));
485 platform_window.on_moved(Box::new({
486 let mut cx = cx.to_async();
487 move || {
488 handle
489 .update(&mut cx, |_, cx| cx.window_bounds_changed())
490 .log_err();
491 }
492 }));
493 platform_window.on_appearance_changed(Box::new({
494 let mut cx = cx.to_async();
495 move || {
496 handle
497 .update(&mut cx, |_, cx| cx.appearance_changed())
498 .log_err();
499 }
500 }));
501 platform_window.on_active_status_change(Box::new({
502 let mut cx = cx.to_async();
503 move |active| {
504 handle
505 .update(&mut cx, |_, cx| {
506 cx.window.active.set(active);
507 cx.window
508 .activation_observers
509 .clone()
510 .retain(&(), |callback| callback(cx));
511 cx.refresh();
512 })
513 .log_err();
514 }
515 }));
516
517 platform_window.on_input({
518 let mut cx = cx.to_async();
519 Box::new(move |event| {
520 handle
521 .update(&mut cx, |_, cx| cx.dispatch_event(event))
522 .log_err()
523 .unwrap_or(DispatchEventResult::default())
524 })
525 });
526
527 Window {
528 handle,
529 removed: false,
530 platform_window,
531 display_id,
532 sprite_atlas,
533 text_system,
534 rem_size: px(16.),
535 viewport_size: content_size,
536 layout_engine: Some(TaffyLayoutEngine::new()),
537 root_view: None,
538 element_id_stack: GlobalElementId::default(),
539 text_style_stack: Vec::new(),
540 rendered_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
541 next_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
542 next_frame_callbacks,
543 next_hitbox_id: HitboxId::default(),
544 dirty_views: FxHashSet::default(),
545 focus_handles: Arc::new(RwLock::new(SlotMap::with_key())),
546 focus_listeners: SubscriberSet::new(),
547 focus_lost_listeners: SubscriberSet::new(),
548 default_prevented: true,
549 mouse_position,
550 mouse_hit_test: HitTest::default(),
551 modifiers,
552 scale_factor,
553 bounds_observers: SubscriberSet::new(),
554 appearance,
555 appearance_observers: SubscriberSet::new(),
556 active,
557 dirty,
558 needs_present,
559 last_input_timestamp,
560 refreshing: false,
561 draw_phase: DrawPhase::None,
562 activation_observers: SubscriberSet::new(),
563 focus: None,
564 focus_enabled: true,
565 pending_input: None,
566 prompt: None,
567 }
568 }
569 fn new_focus_listener(
570 &mut self,
571 value: AnyWindowFocusListener,
572 ) -> (Subscription, impl FnOnce()) {
573 self.focus_listeners.insert((), value)
574 }
575}
576
577#[derive(Clone, Debug, Default, PartialEq, Eq)]
578pub(crate) struct DispatchEventResult {
579 pub propagate: bool,
580 pub default_prevented: bool,
581}
582
583/// Indicates which region of the window is visible. Content falling outside of this mask will not be
584/// rendered. Currently, only rectangular content masks are supported, but we give the mask its own type
585/// to leave room to support more complex shapes in the future.
586#[derive(Clone, Debug, Default, PartialEq, Eq)]
587#[repr(C)]
588pub struct ContentMask<P: Clone + Default + Debug> {
589 /// The bounds
590 pub bounds: Bounds<P>,
591}
592
593impl ContentMask<Pixels> {
594 /// Scale the content mask's pixel units by the given scaling factor.
595 pub fn scale(&self, factor: f32) -> ContentMask<ScaledPixels> {
596 ContentMask {
597 bounds: self.bounds.scale(factor),
598 }
599 }
600
601 /// Intersect the content mask with the given content mask.
602 pub fn intersect(&self, other: &Self) -> Self {
603 let bounds = self.bounds.intersect(&other.bounds);
604 ContentMask { bounds }
605 }
606}
607
608/// Provides access to application state in the context of a single window. Derefs
609/// to an [`AppContext`], so you can also pass a [`WindowContext`] to any method that takes
610/// an [`AppContext`] and call any [`AppContext`] methods.
611pub struct WindowContext<'a> {
612 pub(crate) app: &'a mut AppContext,
613 pub(crate) window: &'a mut Window,
614}
615
616impl<'a> WindowContext<'a> {
617 pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window) -> Self {
618 Self { app, window }
619 }
620
621 /// Obtain a handle to the window that belongs to this context.
622 pub fn window_handle(&self) -> AnyWindowHandle {
623 self.window.handle
624 }
625
626 /// Mark the window as dirty, scheduling it to be redrawn on the next frame.
627 pub fn refresh(&mut self) {
628 if self.window.draw_phase == DrawPhase::None {
629 self.window.refreshing = true;
630 self.window.dirty.set(true);
631 }
632 }
633
634 /// Close this window.
635 pub fn remove_window(&mut self) {
636 self.window.removed = true;
637 }
638
639 /// Obtain a new [`FocusHandle`], which allows you to track and manipulate the keyboard focus
640 /// for elements rendered within this window.
641 pub fn focus_handle(&mut self) -> FocusHandle {
642 FocusHandle::new(&self.window.focus_handles)
643 }
644
645 /// Obtain the currently focused [`FocusHandle`]. If no elements are focused, returns `None`.
646 pub fn focused(&self) -> Option<FocusHandle> {
647 self.window
648 .focus
649 .and_then(|id| FocusHandle::for_id(id, &self.window.focus_handles))
650 }
651
652 /// Move focus to the element associated with the given [`FocusHandle`].
653 pub fn focus(&mut self, handle: &FocusHandle) {
654 if !self.window.focus_enabled || self.window.focus == Some(handle.id) {
655 return;
656 }
657
658 self.window.focus = Some(handle.id);
659 self.window
660 .rendered_frame
661 .dispatch_tree
662 .clear_pending_keystrokes();
663 self.refresh();
664 }
665
666 /// Remove focus from all elements within this context's window.
667 pub fn blur(&mut self) {
668 if !self.window.focus_enabled {
669 return;
670 }
671
672 self.window.focus = None;
673 self.refresh();
674 }
675
676 /// Blur the window and don't allow anything in it to be focused again.
677 pub fn disable_focus(&mut self) {
678 self.blur();
679 self.window.focus_enabled = false;
680 }
681
682 /// Accessor for the text system.
683 pub fn text_system(&self) -> &Arc<WindowTextSystem> {
684 &self.window.text_system
685 }
686
687 /// The current text style. Which is composed of all the style refinements provided to `with_text_style`.
688 pub fn text_style(&self) -> TextStyle {
689 let mut style = TextStyle::default();
690 for refinement in &self.window.text_style_stack {
691 style.refine(refinement);
692 }
693 style
694 }
695
696 /// Check if the platform window is maximized
697 /// On some platforms (namely Windows) this is different than the bounds being the size of the display
698 pub fn is_maximized(&self) -> bool {
699 self.window.platform_window.is_maximized()
700 }
701
702 /// Dispatch the given action on the currently focused element.
703 pub fn dispatch_action(&mut self, action: Box<dyn Action>) {
704 let focus_handle = self.focused();
705
706 let window = self.window.handle;
707 self.app.defer(move |cx| {
708 cx.propagate_event = true;
709 window
710 .update(cx, |_, cx| {
711 let node_id = focus_handle
712 .and_then(|handle| {
713 cx.window
714 .rendered_frame
715 .dispatch_tree
716 .focusable_node_id(handle.id)
717 })
718 .unwrap_or_else(|| cx.window.rendered_frame.dispatch_tree.root_node_id());
719
720 cx.dispatch_action_on_node(node_id, action.as_ref());
721 })
722 .log_err();
723 if cx.propagate_event {
724 cx.dispatch_global_action(action.as_ref());
725 }
726 })
727 }
728
729 pub(crate) fn dispatch_keystroke_observers(
730 &mut self,
731 event: &dyn Any,
732 action: Option<Box<dyn Action>>,
733 ) {
734 let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() else {
735 return;
736 };
737
738 self.keystroke_observers
739 .clone()
740 .retain(&(), move |callback| {
741 (callback)(
742 &KeystrokeEvent {
743 keystroke: key_down_event.keystroke.clone(),
744 action: action.as_ref().map(|action| action.boxed_clone()),
745 },
746 self,
747 );
748 true
749 });
750 }
751
752 pub(crate) fn clear_pending_keystrokes(&mut self) {
753 self.window
754 .rendered_frame
755 .dispatch_tree
756 .clear_pending_keystrokes();
757 self.window
758 .next_frame
759 .dispatch_tree
760 .clear_pending_keystrokes();
761 }
762
763 /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
764 /// that are currently on the stack to be returned to the app.
765 pub fn defer(&mut self, f: impl FnOnce(&mut WindowContext) + 'static) {
766 let handle = self.window.handle;
767 self.app.defer(move |cx| {
768 handle.update(cx, |_, cx| f(cx)).ok();
769 });
770 }
771
772 /// Subscribe to events emitted by a model or view.
773 /// The entity to which you're subscribing must implement the [`EventEmitter`] trait.
774 /// 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.
775 pub fn subscribe<Emitter, E, Evt>(
776 &mut self,
777 entity: &E,
778 mut on_event: impl FnMut(E, &Evt, &mut WindowContext<'_>) + 'static,
779 ) -> Subscription
780 where
781 Emitter: EventEmitter<Evt>,
782 E: Entity<Emitter>,
783 Evt: 'static,
784 {
785 let entity_id = entity.entity_id();
786 let entity = entity.downgrade();
787 let window_handle = self.window.handle;
788 self.app.new_subscription(
789 entity_id,
790 (
791 TypeId::of::<Evt>(),
792 Box::new(move |event, cx| {
793 window_handle
794 .update(cx, |_, cx| {
795 if let Some(handle) = E::upgrade_from(&entity) {
796 let event = event.downcast_ref().expect("invalid event type");
797 on_event(handle, event, cx);
798 true
799 } else {
800 false
801 }
802 })
803 .unwrap_or(false)
804 }),
805 ),
806 )
807 }
808
809 /// Creates an [`AsyncWindowContext`], which has a static lifetime and can be held across
810 /// await points in async code.
811 pub fn to_async(&self) -> AsyncWindowContext {
812 AsyncWindowContext::new(self.app.to_async(), self.window.handle)
813 }
814
815 /// Schedule the given closure to be run directly after the current frame is rendered.
816 pub fn on_next_frame(&mut self, callback: impl FnOnce(&mut WindowContext) + 'static) {
817 RefCell::borrow_mut(&self.window.next_frame_callbacks).push(Box::new(callback));
818 }
819
820 /// Spawn the future returned by the given closure on the application thread pool.
821 /// The closure is provided a handle to the current window and an `AsyncWindowContext` for
822 /// use within your future.
823 pub fn spawn<Fut, R>(&mut self, f: impl FnOnce(AsyncWindowContext) -> Fut) -> Task<R>
824 where
825 R: 'static,
826 Fut: Future<Output = R> + 'static,
827 {
828 self.app
829 .spawn(|app| f(AsyncWindowContext::new(app, self.window.handle)))
830 }
831
832 /// Updates the global of the given type. The given closure is given simultaneous mutable
833 /// access both to the global and the context.
834 pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
835 where
836 G: Global,
837 {
838 let mut global = self.app.lease_global::<G>();
839 let result = f(&mut global, self);
840 self.app.end_global_lease(global);
841 result
842 }
843
844 fn window_bounds_changed(&mut self) {
845 self.window.scale_factor = self.window.platform_window.scale_factor();
846 self.window.viewport_size = self.window.platform_window.content_size();
847 self.window.display_id = self.window.platform_window.display().id();
848 self.refresh();
849
850 self.window
851 .bounds_observers
852 .clone()
853 .retain(&(), |callback| callback(self));
854 }
855
856 /// Returns the bounds of the current window in the global coordinate space, which could span across multiple displays.
857 pub fn window_bounds(&self) -> Bounds<GlobalPixels> {
858 self.window.platform_window.bounds()
859 }
860
861 /// Retusn whether or not the window is currently fullscreen
862 pub fn is_fullscreen(&self) -> bool {
863 self.window.platform_window.is_fullscreen()
864 }
865
866 fn appearance_changed(&mut self) {
867 self.window.appearance = self.window.platform_window.appearance();
868
869 self.window
870 .appearance_observers
871 .clone()
872 .retain(&(), |callback| callback(self));
873 }
874
875 /// Returns the appearance of the current window.
876 pub fn appearance(&self) -> WindowAppearance {
877 self.window.appearance
878 }
879
880 /// Returns the size of the drawable area within the window.
881 pub fn viewport_size(&self) -> Size<Pixels> {
882 self.window.viewport_size
883 }
884
885 /// Returns whether this window is focused by the operating system (receiving key events).
886 pub fn is_window_active(&self) -> bool {
887 self.window.active.get()
888 }
889
890 /// Toggle zoom on the window.
891 pub fn zoom_window(&self) {
892 self.window.platform_window.zoom();
893 }
894
895 /// Updates the window's title at the platform level.
896 pub fn set_window_title(&mut self, title: &str) {
897 self.window.platform_window.set_title(title);
898 }
899
900 /// Mark the window as dirty at the platform level.
901 pub fn set_window_edited(&mut self, edited: bool) {
902 self.window.platform_window.set_edited(edited);
903 }
904
905 /// Determine the display on which the window is visible.
906 pub fn display(&self) -> Option<Rc<dyn PlatformDisplay>> {
907 self.platform
908 .displays()
909 .into_iter()
910 .find(|display| display.id() == self.window.display_id)
911 }
912
913 /// Show the platform character palette.
914 pub fn show_character_palette(&self) {
915 self.window.platform_window.show_character_palette();
916 }
917
918 /// The scale factor of the display associated with the window. For example, it could
919 /// return 2.0 for a "retina" display, indicating that each logical pixel should actually
920 /// be rendered as two pixels on screen.
921 pub fn scale_factor(&self) -> f32 {
922 self.window.scale_factor
923 }
924
925 /// The size of an em for the base font of the application. Adjusting this value allows the
926 /// UI to scale, just like zooming a web page.
927 pub fn rem_size(&self) -> Pixels {
928 self.window.rem_size
929 }
930
931 /// Sets the size of an em for the base font of the application. Adjusting this value allows the
932 /// UI to scale, just like zooming a web page.
933 pub fn set_rem_size(&mut self, rem_size: impl Into<Pixels>) {
934 self.window.rem_size = rem_size.into();
935 }
936
937 /// The line height associated with the current text style.
938 pub fn line_height(&self) -> Pixels {
939 let rem_size = self.rem_size();
940 let text_style = self.text_style();
941 text_style
942 .line_height
943 .to_pixels(text_style.font_size, rem_size)
944 }
945
946 /// Call to prevent the default action of an event. Currently only used to prevent
947 /// parent elements from becoming focused on mouse down.
948 pub fn prevent_default(&mut self) {
949 self.window.default_prevented = true;
950 }
951
952 /// Obtain whether default has been prevented for the event currently being dispatched.
953 pub fn default_prevented(&self) -> bool {
954 self.window.default_prevented
955 }
956
957 /// Determine whether the given action is available along the dispatch path to the currently focused element.
958 pub fn is_action_available(&self, action: &dyn Action) -> bool {
959 let target = self
960 .focused()
961 .and_then(|focused_handle| {
962 self.window
963 .rendered_frame
964 .dispatch_tree
965 .focusable_node_id(focused_handle.id)
966 })
967 .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
968 self.window
969 .rendered_frame
970 .dispatch_tree
971 .is_action_available(action, target)
972 }
973
974 /// The position of the mouse relative to the window.
975 pub fn mouse_position(&self) -> Point<Pixels> {
976 self.window.mouse_position
977 }
978
979 /// The current state of the keyboard's modifiers
980 pub fn modifiers(&self) -> Modifiers {
981 self.window.modifiers
982 }
983
984 /// Produces a new frame and assigns it to `rendered_frame`. To actually show
985 /// the contents of the new [Scene], use [present].
986 #[profiling::function]
987 pub fn draw(&mut self) {
988 self.window.dirty.set(false);
989
990 // Restore the previously-used input handler.
991 if let Some(input_handler) = self.window.platform_window.take_input_handler() {
992 self.window
993 .rendered_frame
994 .input_handlers
995 .push(Some(input_handler));
996 }
997
998 self.with_element_context(|cx| cx.draw_roots());
999 self.window.dirty_views.clear();
1000
1001 self.window
1002 .next_frame
1003 .dispatch_tree
1004 .preserve_pending_keystrokes(
1005 &mut self.window.rendered_frame.dispatch_tree,
1006 self.window.focus,
1007 );
1008 self.window.next_frame.focus = self.window.focus;
1009 self.window.next_frame.window_active = self.window.active.get();
1010
1011 // Register requested input handler with the platform window.
1012 if let Some(input_handler) = self.window.next_frame.input_handlers.pop() {
1013 self.window
1014 .platform_window
1015 .set_input_handler(input_handler.unwrap());
1016 }
1017
1018 self.window.layout_engine.as_mut().unwrap().clear();
1019 self.text_system().finish_frame();
1020 self.window
1021 .next_frame
1022 .finish(&mut self.window.rendered_frame);
1023 ELEMENT_ARENA.with_borrow_mut(|element_arena| {
1024 let percentage = (element_arena.len() as f32 / element_arena.capacity() as f32) * 100.;
1025 if percentage >= 80. {
1026 log::warn!("elevated element arena occupation: {}.", percentage);
1027 }
1028 element_arena.clear();
1029 });
1030
1031 self.window.draw_phase = DrawPhase::Focus;
1032 let previous_focus_path = self.window.rendered_frame.focus_path();
1033 let previous_window_active = self.window.rendered_frame.window_active;
1034 mem::swap(&mut self.window.rendered_frame, &mut self.window.next_frame);
1035 self.window.next_frame.clear();
1036 let current_focus_path = self.window.rendered_frame.focus_path();
1037 let current_window_active = self.window.rendered_frame.window_active;
1038
1039 if previous_focus_path != current_focus_path
1040 || previous_window_active != current_window_active
1041 {
1042 if !previous_focus_path.is_empty() && current_focus_path.is_empty() {
1043 self.window
1044 .focus_lost_listeners
1045 .clone()
1046 .retain(&(), |listener| listener(self));
1047 }
1048
1049 let event = FocusEvent {
1050 previous_focus_path: if previous_window_active {
1051 previous_focus_path
1052 } else {
1053 Default::default()
1054 },
1055 current_focus_path: if current_window_active {
1056 current_focus_path
1057 } else {
1058 Default::default()
1059 },
1060 };
1061 self.window
1062 .focus_listeners
1063 .clone()
1064 .retain(&(), |listener| listener(&event, self));
1065 }
1066
1067 self.reset_cursor_style();
1068 self.window.refreshing = false;
1069 self.window.draw_phase = DrawPhase::None;
1070 self.window.needs_present.set(true);
1071 }
1072
1073 #[profiling::function]
1074 fn present(&self) {
1075 self.window
1076 .platform_window
1077 .draw(&self.window.rendered_frame.scene);
1078 self.window.needs_present.set(false);
1079 profiling::finish_frame!();
1080 }
1081
1082 fn reset_cursor_style(&self) {
1083 // Set the cursor only if we're the active window.
1084 if self.is_window_active() {
1085 let style = self
1086 .window
1087 .rendered_frame
1088 .cursor_styles
1089 .iter()
1090 .rev()
1091 .find(|request| request.hitbox_id.is_hovered(self))
1092 .map(|request| request.style)
1093 .unwrap_or(CursorStyle::Arrow);
1094 self.platform.set_cursor_style(style);
1095 }
1096 }
1097
1098 /// Dispatch a given keystroke as though the user had typed it.
1099 /// You can create a keystroke with Keystroke::parse("").
1100 pub fn dispatch_keystroke(&mut self, keystroke: Keystroke) -> bool {
1101 let keystroke = keystroke.with_simulated_ime();
1102 let result = self.dispatch_event(PlatformInput::KeyDown(KeyDownEvent {
1103 keystroke: keystroke.clone(),
1104 is_held: false,
1105 }));
1106 if !result.propagate {
1107 return true;
1108 }
1109
1110 if let Some(input) = keystroke.ime_key {
1111 if let Some(mut input_handler) = self.window.platform_window.take_input_handler() {
1112 input_handler.dispatch_input(&input, self);
1113 self.window.platform_window.set_input_handler(input_handler);
1114 return true;
1115 }
1116 }
1117
1118 false
1119 }
1120
1121 /// Represent this action as a key binding string, to display in the UI.
1122 pub fn keystroke_text_for(&self, action: &dyn Action) -> String {
1123 self.bindings_for_action(action)
1124 .into_iter()
1125 .next()
1126 .map(|binding| {
1127 binding
1128 .keystrokes()
1129 .iter()
1130 .map(ToString::to_string)
1131 .collect::<Vec<_>>()
1132 .join(" ")
1133 })
1134 .unwrap_or_else(|| action.name().to_string())
1135 }
1136
1137 /// Dispatch a mouse or keyboard event on the window.
1138 #[profiling::function]
1139 pub fn dispatch_event(&mut self, event: PlatformInput) -> DispatchEventResult {
1140 self.window.last_input_timestamp.set(Instant::now());
1141 // Handlers may set this to false by calling `stop_propagation`.
1142 self.app.propagate_event = true;
1143 // Handlers may set this to true by calling `prevent_default`.
1144 self.window.default_prevented = false;
1145
1146 let event = match event {
1147 // Track the mouse position with our own state, since accessing the platform
1148 // API for the mouse position can only occur on the main thread.
1149 PlatformInput::MouseMove(mouse_move) => {
1150 self.window.mouse_position = mouse_move.position;
1151 self.window.modifiers = mouse_move.modifiers;
1152 PlatformInput::MouseMove(mouse_move)
1153 }
1154 PlatformInput::MouseDown(mouse_down) => {
1155 self.window.mouse_position = mouse_down.position;
1156 self.window.modifiers = mouse_down.modifiers;
1157 PlatformInput::MouseDown(mouse_down)
1158 }
1159 PlatformInput::MouseUp(mouse_up) => {
1160 self.window.mouse_position = mouse_up.position;
1161 self.window.modifiers = mouse_up.modifiers;
1162 PlatformInput::MouseUp(mouse_up)
1163 }
1164 PlatformInput::MouseExited(mouse_exited) => {
1165 self.window.modifiers = mouse_exited.modifiers;
1166 PlatformInput::MouseExited(mouse_exited)
1167 }
1168 PlatformInput::ModifiersChanged(modifiers_changed) => {
1169 self.window.modifiers = modifiers_changed.modifiers;
1170 PlatformInput::ModifiersChanged(modifiers_changed)
1171 }
1172 PlatformInput::ScrollWheel(scroll_wheel) => {
1173 self.window.mouse_position = scroll_wheel.position;
1174 self.window.modifiers = scroll_wheel.modifiers;
1175 PlatformInput::ScrollWheel(scroll_wheel)
1176 }
1177 // Translate dragging and dropping of external files from the operating system
1178 // to internal drag and drop events.
1179 PlatformInput::FileDrop(file_drop) => match file_drop {
1180 FileDropEvent::Entered { position, paths } => {
1181 self.window.mouse_position = position;
1182 if self.active_drag.is_none() {
1183 self.active_drag = Some(AnyDrag {
1184 value: Box::new(paths.clone()),
1185 view: self.new_view(|_| paths).into(),
1186 cursor_offset: position,
1187 });
1188 }
1189 PlatformInput::MouseMove(MouseMoveEvent {
1190 position,
1191 pressed_button: Some(MouseButton::Left),
1192 modifiers: Modifiers::default(),
1193 })
1194 }
1195 FileDropEvent::Pending { position } => {
1196 self.window.mouse_position = position;
1197 PlatformInput::MouseMove(MouseMoveEvent {
1198 position,
1199 pressed_button: Some(MouseButton::Left),
1200 modifiers: Modifiers::default(),
1201 })
1202 }
1203 FileDropEvent::Submit { position } => {
1204 self.activate(true);
1205 self.window.mouse_position = position;
1206 PlatformInput::MouseUp(MouseUpEvent {
1207 button: MouseButton::Left,
1208 position,
1209 modifiers: Modifiers::default(),
1210 click_count: 1,
1211 })
1212 }
1213 FileDropEvent::Exited => {
1214 self.active_drag.take();
1215 PlatformInput::FileDrop(FileDropEvent::Exited)
1216 }
1217 },
1218 PlatformInput::KeyDown(_) | PlatformInput::KeyUp(_) => event,
1219 };
1220
1221 if let Some(any_mouse_event) = event.mouse_event() {
1222 self.dispatch_mouse_event(any_mouse_event);
1223 } else if let Some(any_key_event) = event.keyboard_event() {
1224 self.dispatch_key_event(any_key_event);
1225 }
1226
1227 DispatchEventResult {
1228 propagate: self.app.propagate_event,
1229 default_prevented: self.window.default_prevented,
1230 }
1231 }
1232
1233 fn dispatch_mouse_event(&mut self, event: &dyn Any) {
1234 let hit_test = self.window.rendered_frame.hit_test(self.mouse_position());
1235 if hit_test != self.window.mouse_hit_test {
1236 self.window.mouse_hit_test = hit_test;
1237 self.reset_cursor_style();
1238 }
1239
1240 let mut mouse_listeners = mem::take(&mut self.window.rendered_frame.mouse_listeners);
1241 self.with_element_context(|cx| {
1242 // Capture phase, events bubble from back to front. Handlers for this phase are used for
1243 // special purposes, such as detecting events outside of a given Bounds.
1244 for listener in &mut mouse_listeners {
1245 let listener = listener.as_mut().unwrap();
1246 listener(event, DispatchPhase::Capture, cx);
1247 if !cx.app.propagate_event {
1248 break;
1249 }
1250 }
1251
1252 // Bubble phase, where most normal handlers do their work.
1253 if cx.app.propagate_event {
1254 for listener in mouse_listeners.iter_mut().rev() {
1255 let listener = listener.as_mut().unwrap();
1256 listener(event, DispatchPhase::Bubble, cx);
1257 if !cx.app.propagate_event {
1258 break;
1259 }
1260 }
1261 }
1262 });
1263 self.window.rendered_frame.mouse_listeners = mouse_listeners;
1264
1265 if self.app.propagate_event && self.has_active_drag() {
1266 if event.is::<MouseMoveEvent>() {
1267 // If this was a mouse move event, redraw the window so that the
1268 // active drag can follow the mouse cursor.
1269 self.refresh();
1270 } else if event.is::<MouseUpEvent>() {
1271 // If this was a mouse up event, cancel the active drag and redraw
1272 // the window.
1273 self.active_drag = None;
1274 self.refresh();
1275 }
1276 }
1277 }
1278
1279 fn dispatch_key_event(&mut self, event: &dyn Any) {
1280 if self.window.dirty.get() {
1281 self.draw();
1282 }
1283
1284 let node_id = self
1285 .window
1286 .focus
1287 .and_then(|focus_id| {
1288 self.window
1289 .rendered_frame
1290 .dispatch_tree
1291 .focusable_node_id(focus_id)
1292 })
1293 .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
1294
1295 let dispatch_path = self
1296 .window
1297 .rendered_frame
1298 .dispatch_tree
1299 .dispatch_path(node_id);
1300
1301 if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
1302 let KeymatchResult { bindings, pending } = self
1303 .window
1304 .rendered_frame
1305 .dispatch_tree
1306 .dispatch_key(&key_down_event.keystroke, &dispatch_path);
1307
1308 if pending {
1309 let mut currently_pending = self.window.pending_input.take().unwrap_or_default();
1310 if currently_pending.focus.is_some() && currently_pending.focus != self.window.focus
1311 {
1312 currently_pending = PendingInput::default();
1313 }
1314 currently_pending.focus = self.window.focus;
1315 currently_pending
1316 .keystrokes
1317 .push(key_down_event.keystroke.clone());
1318 for binding in bindings {
1319 currently_pending.bindings.push(binding);
1320 }
1321
1322 currently_pending.timer = Some(self.spawn(|mut cx| async move {
1323 cx.background_executor.timer(Duration::from_secs(1)).await;
1324 cx.update(move |cx| {
1325 cx.clear_pending_keystrokes();
1326 let Some(currently_pending) = cx.window.pending_input.take() else {
1327 return;
1328 };
1329 cx.replay_pending_input(currently_pending)
1330 })
1331 .log_err();
1332 }));
1333
1334 self.window.pending_input = Some(currently_pending);
1335
1336 self.propagate_event = false;
1337 return;
1338 } else if let Some(currently_pending) = self.window.pending_input.take() {
1339 if bindings
1340 .iter()
1341 .all(|binding| !currently_pending.used_by_binding(binding))
1342 {
1343 self.replay_pending_input(currently_pending)
1344 }
1345 }
1346
1347 if !bindings.is_empty() {
1348 self.clear_pending_keystrokes();
1349 }
1350
1351 self.propagate_event = true;
1352 for binding in bindings {
1353 self.dispatch_action_on_node(node_id, binding.action.as_ref());
1354 if !self.propagate_event {
1355 self.dispatch_keystroke_observers(event, Some(binding.action));
1356 return;
1357 }
1358 }
1359 }
1360
1361 self.dispatch_key_down_up_event(event, &dispatch_path);
1362 if !self.propagate_event {
1363 return;
1364 }
1365
1366 self.dispatch_keystroke_observers(event, None);
1367 }
1368
1369 fn dispatch_key_down_up_event(
1370 &mut self,
1371 event: &dyn Any,
1372 dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
1373 ) {
1374 // Capture phase
1375 for node_id in dispatch_path {
1376 let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1377
1378 for key_listener in node.key_listeners.clone() {
1379 self.with_element_context(|cx| {
1380 key_listener(event, DispatchPhase::Capture, cx);
1381 });
1382 if !self.propagate_event {
1383 return;
1384 }
1385 }
1386 }
1387
1388 // Bubble phase
1389 for node_id in dispatch_path.iter().rev() {
1390 // Handle low level key events
1391 let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1392 for key_listener in node.key_listeners.clone() {
1393 self.with_element_context(|cx| {
1394 key_listener(event, DispatchPhase::Bubble, cx);
1395 });
1396 if !self.propagate_event {
1397 return;
1398 }
1399 }
1400 }
1401 }
1402
1403 /// Determine whether a potential multi-stroke key binding is in progress on this window.
1404 pub fn has_pending_keystrokes(&self) -> bool {
1405 self.window
1406 .rendered_frame
1407 .dispatch_tree
1408 .has_pending_keystrokes()
1409 }
1410
1411 fn replay_pending_input(&mut self, currently_pending: PendingInput) {
1412 let node_id = self
1413 .window
1414 .focus
1415 .and_then(|focus_id| {
1416 self.window
1417 .rendered_frame
1418 .dispatch_tree
1419 .focusable_node_id(focus_id)
1420 })
1421 .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
1422
1423 if self.window.focus != currently_pending.focus {
1424 return;
1425 }
1426
1427 let input = currently_pending.input();
1428
1429 self.propagate_event = true;
1430 for binding in currently_pending.bindings {
1431 self.dispatch_action_on_node(node_id, binding.action.as_ref());
1432 if !self.propagate_event {
1433 return;
1434 }
1435 }
1436
1437 let dispatch_path = self
1438 .window
1439 .rendered_frame
1440 .dispatch_tree
1441 .dispatch_path(node_id);
1442
1443 for keystroke in currently_pending.keystrokes {
1444 let event = KeyDownEvent {
1445 keystroke,
1446 is_held: false,
1447 };
1448
1449 self.dispatch_key_down_up_event(&event, &dispatch_path);
1450 if !self.propagate_event {
1451 return;
1452 }
1453 }
1454
1455 if !input.is_empty() {
1456 if let Some(mut input_handler) = self.window.platform_window.take_input_handler() {
1457 input_handler.dispatch_input(&input, self);
1458 self.window.platform_window.set_input_handler(input_handler)
1459 }
1460 }
1461 }
1462
1463 fn dispatch_action_on_node(&mut self, node_id: DispatchNodeId, action: &dyn Action) {
1464 let dispatch_path = self
1465 .window
1466 .rendered_frame
1467 .dispatch_tree
1468 .dispatch_path(node_id);
1469
1470 // Capture phase
1471 for node_id in &dispatch_path {
1472 let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1473 for DispatchActionListener {
1474 action_type,
1475 listener,
1476 } in node.action_listeners.clone()
1477 {
1478 let any_action = action.as_any();
1479 if action_type == any_action.type_id() {
1480 self.with_element_context(|cx| {
1481 listener(any_action, DispatchPhase::Capture, cx);
1482 });
1483
1484 if !self.propagate_event {
1485 return;
1486 }
1487 }
1488 }
1489 }
1490 // Bubble phase
1491 for node_id in dispatch_path.iter().rev() {
1492 let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1493 for DispatchActionListener {
1494 action_type,
1495 listener,
1496 } in node.action_listeners.clone()
1497 {
1498 let any_action = action.as_any();
1499 if action_type == any_action.type_id() {
1500 self.propagate_event = false; // Actions stop propagation by default during the bubble phase
1501
1502 self.with_element_context(|cx| {
1503 listener(any_action, DispatchPhase::Bubble, cx);
1504 });
1505
1506 if !self.propagate_event {
1507 return;
1508 }
1509 }
1510 }
1511 }
1512 }
1513
1514 /// Register the given handler to be invoked whenever the global of the given type
1515 /// is updated.
1516 pub fn observe_global<G: Global>(
1517 &mut self,
1518 f: impl Fn(&mut WindowContext<'_>) + 'static,
1519 ) -> Subscription {
1520 let window_handle = self.window.handle;
1521 let (subscription, activate) = self.global_observers.insert(
1522 TypeId::of::<G>(),
1523 Box::new(move |cx| window_handle.update(cx, |_, cx| f(cx)).is_ok()),
1524 );
1525 self.app.defer(move |_| activate());
1526 subscription
1527 }
1528
1529 /// Focus the current window and bring it to the foreground at the platform level.
1530 pub fn activate_window(&self) {
1531 self.window.platform_window.activate();
1532 }
1533
1534 /// Minimize the current window at the platform level.
1535 pub fn minimize_window(&self) {
1536 self.window.platform_window.minimize();
1537 }
1538
1539 /// Toggle full screen status on the current window at the platform level.
1540 pub fn toggle_fullscreen(&self) {
1541 self.window.platform_window.toggle_fullscreen();
1542 }
1543
1544 /// Present a platform dialog.
1545 /// The provided message will be presented, along with buttons for each answer.
1546 /// When a button is clicked, the returned Receiver will receive the index of the clicked button.
1547 pub fn prompt(
1548 &mut self,
1549 level: PromptLevel,
1550 message: &str,
1551 detail: Option<&str>,
1552 answers: &[&str],
1553 ) -> oneshot::Receiver<usize> {
1554 let prompt_builder = self.app.prompt_builder.take();
1555 let Some(prompt_builder) = prompt_builder else {
1556 unreachable!("Re-entrant window prompting is not supported by GPUI");
1557 };
1558
1559 let receiver = match &prompt_builder {
1560 PromptBuilder::Default => self
1561 .window
1562 .platform_window
1563 .prompt(level, message, detail, answers)
1564 .unwrap_or_else(|| {
1565 self.build_custom_prompt(&prompt_builder, level, message, detail, answers)
1566 }),
1567 PromptBuilder::Custom(_) => {
1568 self.build_custom_prompt(&prompt_builder, level, message, detail, answers)
1569 }
1570 };
1571
1572 self.app.prompt_builder = Some(prompt_builder);
1573
1574 receiver
1575 }
1576
1577 fn build_custom_prompt(
1578 &mut self,
1579 prompt_builder: &PromptBuilder,
1580 level: PromptLevel,
1581 message: &str,
1582 detail: Option<&str>,
1583 answers: &[&str],
1584 ) -> oneshot::Receiver<usize> {
1585 let (sender, receiver) = oneshot::channel();
1586 let handle = PromptHandle::new(sender);
1587 let handle = (prompt_builder)(level, message, detail, answers, handle, self);
1588 self.window.prompt = Some(handle);
1589 receiver
1590 }
1591
1592 /// Returns all available actions for the focused element.
1593 pub fn available_actions(&self) -> Vec<Box<dyn Action>> {
1594 let node_id = self
1595 .window
1596 .focus
1597 .and_then(|focus_id| {
1598 self.window
1599 .rendered_frame
1600 .dispatch_tree
1601 .focusable_node_id(focus_id)
1602 })
1603 .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
1604
1605 let mut actions = self
1606 .window
1607 .rendered_frame
1608 .dispatch_tree
1609 .available_actions(node_id);
1610 for action_type in self.global_action_listeners.keys() {
1611 if let Err(ix) = actions.binary_search_by_key(action_type, |a| a.as_any().type_id()) {
1612 let action = self.actions.build_action_type(action_type).ok();
1613 if let Some(action) = action {
1614 actions.insert(ix, action);
1615 }
1616 }
1617 }
1618 actions
1619 }
1620
1621 /// Returns key bindings that invoke the given action on the currently focused element.
1622 pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
1623 self.window
1624 .rendered_frame
1625 .dispatch_tree
1626 .bindings_for_action(
1627 action,
1628 &self.window.rendered_frame.dispatch_tree.context_stack,
1629 )
1630 }
1631
1632 /// Returns any bindings that would invoke the given action on the given focus handle if it were focused.
1633 pub fn bindings_for_action_in(
1634 &self,
1635 action: &dyn Action,
1636 focus_handle: &FocusHandle,
1637 ) -> Vec<KeyBinding> {
1638 let dispatch_tree = &self.window.rendered_frame.dispatch_tree;
1639
1640 let Some(node_id) = dispatch_tree.focusable_node_id(focus_handle.id) else {
1641 return vec![];
1642 };
1643 let context_stack: Vec<_> = dispatch_tree
1644 .dispatch_path(node_id)
1645 .into_iter()
1646 .filter_map(|node_id| dispatch_tree.node(node_id).context.clone())
1647 .collect();
1648 dispatch_tree.bindings_for_action(action, &context_stack)
1649 }
1650
1651 /// Returns a generic event listener that invokes the given listener with the view and context associated with the given view handle.
1652 pub fn listener_for<V: Render, E>(
1653 &self,
1654 view: &View<V>,
1655 f: impl Fn(&mut V, &E, &mut ViewContext<V>) + 'static,
1656 ) -> impl Fn(&E, &mut WindowContext) + 'static {
1657 let view = view.downgrade();
1658 move |e: &E, cx: &mut WindowContext| {
1659 view.update(cx, |view, cx| f(view, e, cx)).ok();
1660 }
1661 }
1662
1663 /// Returns a generic handler that invokes the given handler with the view and context associated with the given view handle.
1664 pub fn handler_for<V: Render>(
1665 &self,
1666 view: &View<V>,
1667 f: impl Fn(&mut V, &mut ViewContext<V>) + 'static,
1668 ) -> impl Fn(&mut WindowContext) {
1669 let view = view.downgrade();
1670 move |cx: &mut WindowContext| {
1671 view.update(cx, |view, cx| f(view, cx)).ok();
1672 }
1673 }
1674
1675 /// Register a callback that can interrupt the closing of the current window based the returned boolean.
1676 /// If the callback returns false, the window won't be closed.
1677 pub fn on_window_should_close(&mut self, f: impl Fn(&mut WindowContext) -> bool + 'static) {
1678 let mut this = self.to_async();
1679 self.window
1680 .platform_window
1681 .on_should_close(Box::new(move || this.update(|cx| f(cx)).unwrap_or(true)))
1682 }
1683
1684 /// Register an action listener on the window for the next frame. The type of action
1685 /// is determined by the first parameter of the given listener. When the next frame is rendered
1686 /// the listener will be cleared.
1687 ///
1688 /// This is a fairly low-level method, so prefer using action handlers on elements unless you have
1689 /// a specific need to register a global listener.
1690 pub fn on_action(
1691 &mut self,
1692 action_type: TypeId,
1693 listener: impl Fn(&dyn Any, DispatchPhase, &mut WindowContext) + 'static,
1694 ) {
1695 self.window
1696 .next_frame
1697 .dispatch_tree
1698 .on_action(action_type, Rc::new(listener));
1699 }
1700}
1701
1702#[cfg(target_os = "windows")]
1703impl WindowContext<'_> {
1704 /// Returns the raw HWND handle for the window.
1705 pub fn get_raw_handle(&self) -> windows::Win32::Foundation::HWND {
1706 self.window.platform_window.get_raw_handle()
1707 }
1708}
1709
1710impl Context for WindowContext<'_> {
1711 type Result<T> = T;
1712
1713 fn new_model<T>(&mut self, build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T) -> Model<T>
1714 where
1715 T: 'static,
1716 {
1717 let slot = self.app.entities.reserve();
1718 let model = build_model(&mut ModelContext::new(&mut *self.app, slot.downgrade()));
1719 self.entities.insert(slot, model)
1720 }
1721
1722 fn update_model<T: 'static, R>(
1723 &mut self,
1724 model: &Model<T>,
1725 update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
1726 ) -> R {
1727 let mut entity = self.entities.lease(model);
1728 let result = update(
1729 &mut *entity,
1730 &mut ModelContext::new(&mut *self.app, model.downgrade()),
1731 );
1732 self.entities.end_lease(entity);
1733 result
1734 }
1735
1736 fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
1737 where
1738 F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
1739 {
1740 if window == self.window.handle {
1741 let root_view = self.window.root_view.clone().unwrap();
1742 Ok(update(root_view, self))
1743 } else {
1744 window.update(self.app, update)
1745 }
1746 }
1747
1748 fn read_model<T, R>(
1749 &self,
1750 handle: &Model<T>,
1751 read: impl FnOnce(&T, &AppContext) -> R,
1752 ) -> Self::Result<R>
1753 where
1754 T: 'static,
1755 {
1756 let entity = self.entities.read(handle);
1757 read(entity, &*self.app)
1758 }
1759
1760 fn read_window<T, R>(
1761 &self,
1762 window: &WindowHandle<T>,
1763 read: impl FnOnce(View<T>, &AppContext) -> R,
1764 ) -> Result<R>
1765 where
1766 T: 'static,
1767 {
1768 if window.any_handle == self.window.handle {
1769 let root_view = self
1770 .window
1771 .root_view
1772 .clone()
1773 .unwrap()
1774 .downcast::<T>()
1775 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
1776 Ok(read(root_view, self))
1777 } else {
1778 self.app.read_window(window, read)
1779 }
1780 }
1781}
1782
1783impl VisualContext for WindowContext<'_> {
1784 fn new_view<V>(
1785 &mut self,
1786 build_view_state: impl FnOnce(&mut ViewContext<'_, V>) -> V,
1787 ) -> Self::Result<View<V>>
1788 where
1789 V: 'static + Render,
1790 {
1791 let slot = self.app.entities.reserve();
1792 let view = View {
1793 model: slot.clone(),
1794 };
1795 let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1796 let entity = build_view_state(&mut cx);
1797 cx.entities.insert(slot, entity);
1798
1799 // Non-generic part to avoid leaking SubscriberSet to invokers of `new_view`.
1800 fn notify_observers(cx: &mut WindowContext, tid: TypeId, view: AnyView) {
1801 cx.new_view_observers.clone().retain(&tid, |observer| {
1802 let any_view = view.clone();
1803 (observer)(any_view, cx);
1804 true
1805 });
1806 }
1807 notify_observers(self, TypeId::of::<V>(), AnyView::from(view.clone()));
1808
1809 view
1810 }
1811
1812 /// Updates the given view. Prefer calling [`View::update`] instead, which calls this method.
1813 fn update_view<T: 'static, R>(
1814 &mut self,
1815 view: &View<T>,
1816 update: impl FnOnce(&mut T, &mut ViewContext<'_, T>) -> R,
1817 ) -> Self::Result<R> {
1818 let mut lease = self.app.entities.lease(&view.model);
1819 let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, view);
1820 let result = update(&mut *lease, &mut cx);
1821 cx.app.entities.end_lease(lease);
1822 result
1823 }
1824
1825 fn replace_root_view<V>(
1826 &mut self,
1827 build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
1828 ) -> Self::Result<View<V>>
1829 where
1830 V: 'static + Render,
1831 {
1832 let view = self.new_view(build_view);
1833 self.window.root_view = Some(view.clone().into());
1834 self.refresh();
1835 view
1836 }
1837
1838 fn focus_view<V: crate::FocusableView>(&mut self, view: &View<V>) -> Self::Result<()> {
1839 self.update_view(view, |view, cx| {
1840 view.focus_handle(cx).clone().focus(cx);
1841 })
1842 }
1843
1844 fn dismiss_view<V>(&mut self, view: &View<V>) -> Self::Result<()>
1845 where
1846 V: ManagedView,
1847 {
1848 self.update_view(view, |_, cx| cx.emit(DismissEvent))
1849 }
1850}
1851
1852impl<'a> std::ops::Deref for WindowContext<'a> {
1853 type Target = AppContext;
1854
1855 fn deref(&self) -> &Self::Target {
1856 self.app
1857 }
1858}
1859
1860impl<'a> std::ops::DerefMut for WindowContext<'a> {
1861 fn deref_mut(&mut self) -> &mut Self::Target {
1862 self.app
1863 }
1864}
1865
1866impl<'a> Borrow<AppContext> for WindowContext<'a> {
1867 fn borrow(&self) -> &AppContext {
1868 self.app
1869 }
1870}
1871
1872impl<'a> BorrowMut<AppContext> for WindowContext<'a> {
1873 fn borrow_mut(&mut self) -> &mut AppContext {
1874 self.app
1875 }
1876}
1877
1878/// This trait contains functionality that is shared across [`ViewContext`] and [`WindowContext`]
1879pub trait BorrowWindow: BorrowMut<Window> + BorrowMut<AppContext> {
1880 #[doc(hidden)]
1881 fn app_mut(&mut self) -> &mut AppContext {
1882 self.borrow_mut()
1883 }
1884
1885 #[doc(hidden)]
1886 fn app(&self) -> &AppContext {
1887 self.borrow()
1888 }
1889
1890 #[doc(hidden)]
1891 fn window(&self) -> &Window {
1892 self.borrow()
1893 }
1894
1895 #[doc(hidden)]
1896 fn window_mut(&mut self) -> &mut Window {
1897 self.borrow_mut()
1898 }
1899}
1900
1901impl Borrow<Window> for WindowContext<'_> {
1902 fn borrow(&self) -> &Window {
1903 self.window
1904 }
1905}
1906
1907impl BorrowMut<Window> for WindowContext<'_> {
1908 fn borrow_mut(&mut self) -> &mut Window {
1909 self.window
1910 }
1911}
1912
1913impl<T> BorrowWindow for T where T: BorrowMut<AppContext> + BorrowMut<Window> {}
1914
1915/// Provides access to application state that is specialized for a particular [`View`].
1916/// Allows you to interact with focus, emit events, etc.
1917/// ViewContext also derefs to [`WindowContext`], giving you access to all of its methods as well.
1918/// When you call [`View::update`], you're passed a `&mut V` and an `&mut ViewContext<V>`.
1919pub struct ViewContext<'a, V> {
1920 window_cx: WindowContext<'a>,
1921 view: &'a View<V>,
1922}
1923
1924impl<V> Borrow<AppContext> for ViewContext<'_, V> {
1925 fn borrow(&self) -> &AppContext {
1926 &*self.window_cx.app
1927 }
1928}
1929
1930impl<V> BorrowMut<AppContext> for ViewContext<'_, V> {
1931 fn borrow_mut(&mut self) -> &mut AppContext {
1932 &mut *self.window_cx.app
1933 }
1934}
1935
1936impl<V> Borrow<Window> for ViewContext<'_, V> {
1937 fn borrow(&self) -> &Window {
1938 &*self.window_cx.window
1939 }
1940}
1941
1942impl<V> BorrowMut<Window> for ViewContext<'_, V> {
1943 fn borrow_mut(&mut self) -> &mut Window {
1944 &mut *self.window_cx.window
1945 }
1946}
1947
1948impl<'a, V: 'static> ViewContext<'a, V> {
1949 pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window, view: &'a View<V>) -> Self {
1950 Self {
1951 window_cx: WindowContext::new(app, window),
1952 view,
1953 }
1954 }
1955
1956 /// Get the entity_id of this view.
1957 pub fn entity_id(&self) -> EntityId {
1958 self.view.entity_id()
1959 }
1960
1961 /// Get the view pointer underlying this context.
1962 pub fn view(&self) -> &View<V> {
1963 self.view
1964 }
1965
1966 /// Get the model underlying this view.
1967 pub fn model(&self) -> &Model<V> {
1968 &self.view.model
1969 }
1970
1971 /// Access the underlying window context.
1972 pub fn window_context(&mut self) -> &mut WindowContext<'a> {
1973 &mut self.window_cx
1974 }
1975
1976 /// Sets a given callback to be run on the next frame.
1977 pub fn on_next_frame(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static)
1978 where
1979 V: 'static,
1980 {
1981 let view = self.view().clone();
1982 self.window_cx.on_next_frame(move |cx| view.update(cx, f));
1983 }
1984
1985 /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
1986 /// that are currently on the stack to be returned to the app.
1987 pub fn defer(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static) {
1988 let view = self.view().downgrade();
1989 self.window_cx.defer(move |cx| {
1990 view.update(cx, f).ok();
1991 });
1992 }
1993
1994 /// Observe another model or view for changes to its state, as tracked by [`ModelContext::notify`].
1995 pub fn observe<V2, E>(
1996 &mut self,
1997 entity: &E,
1998 mut on_notify: impl FnMut(&mut V, E, &mut ViewContext<'_, V>) + 'static,
1999 ) -> Subscription
2000 where
2001 V2: 'static,
2002 V: 'static,
2003 E: Entity<V2>,
2004 {
2005 let view = self.view().downgrade();
2006 let entity_id = entity.entity_id();
2007 let entity = entity.downgrade();
2008 let window_handle = self.window.handle;
2009 self.app.new_observer(
2010 entity_id,
2011 Box::new(move |cx| {
2012 window_handle
2013 .update(cx, |_, cx| {
2014 if let Some(handle) = E::upgrade_from(&entity) {
2015 view.update(cx, |this, cx| on_notify(this, handle, cx))
2016 .is_ok()
2017 } else {
2018 false
2019 }
2020 })
2021 .unwrap_or(false)
2022 }),
2023 )
2024 }
2025
2026 /// Subscribe to events emitted by another model or view.
2027 /// The entity to which you're subscribing must implement the [`EventEmitter`] trait.
2028 /// 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.
2029 pub fn subscribe<V2, E, Evt>(
2030 &mut self,
2031 entity: &E,
2032 mut on_event: impl FnMut(&mut V, E, &Evt, &mut ViewContext<'_, V>) + 'static,
2033 ) -> Subscription
2034 where
2035 V2: EventEmitter<Evt>,
2036 E: Entity<V2>,
2037 Evt: 'static,
2038 {
2039 let view = self.view().downgrade();
2040 let entity_id = entity.entity_id();
2041 let handle = entity.downgrade();
2042 let window_handle = self.window.handle;
2043 self.app.new_subscription(
2044 entity_id,
2045 (
2046 TypeId::of::<Evt>(),
2047 Box::new(move |event, cx| {
2048 window_handle
2049 .update(cx, |_, cx| {
2050 if let Some(handle) = E::upgrade_from(&handle) {
2051 let event = event.downcast_ref().expect("invalid event type");
2052 view.update(cx, |this, cx| on_event(this, handle, event, cx))
2053 .is_ok()
2054 } else {
2055 false
2056 }
2057 })
2058 .unwrap_or(false)
2059 }),
2060 ),
2061 )
2062 }
2063
2064 /// Register a callback to be invoked when the view is released.
2065 ///
2066 /// The callback receives a handle to the view's window. This handle may be
2067 /// invalid, if the window was closed before the view was released.
2068 pub fn on_release(
2069 &mut self,
2070 on_release: impl FnOnce(&mut V, AnyWindowHandle, &mut AppContext) + 'static,
2071 ) -> Subscription {
2072 let window_handle = self.window.handle;
2073 let (subscription, activate) = self.app.release_listeners.insert(
2074 self.view.model.entity_id,
2075 Box::new(move |this, cx| {
2076 let this = this.downcast_mut().expect("invalid entity type");
2077 on_release(this, window_handle, cx)
2078 }),
2079 );
2080 activate();
2081 subscription
2082 }
2083
2084 /// Register a callback to be invoked when the given Model or View is released.
2085 pub fn observe_release<V2, E>(
2086 &mut self,
2087 entity: &E,
2088 mut on_release: impl FnMut(&mut V, &mut V2, &mut ViewContext<'_, V>) + 'static,
2089 ) -> Subscription
2090 where
2091 V: 'static,
2092 V2: 'static,
2093 E: Entity<V2>,
2094 {
2095 let view = self.view().downgrade();
2096 let entity_id = entity.entity_id();
2097 let window_handle = self.window.handle;
2098 let (subscription, activate) = self.app.release_listeners.insert(
2099 entity_id,
2100 Box::new(move |entity, cx| {
2101 let entity = entity.downcast_mut().expect("invalid entity type");
2102 let _ = window_handle.update(cx, |_, cx| {
2103 view.update(cx, |this, cx| on_release(this, entity, cx))
2104 });
2105 }),
2106 );
2107 activate();
2108 subscription
2109 }
2110
2111 /// Indicate that this view has changed, which will invoke any observers and also mark the window as dirty.
2112 /// If this view or any of its ancestors are *cached*, notifying it will cause it or its ancestors to be redrawn.
2113 pub fn notify(&mut self) {
2114 for view_id in self
2115 .window
2116 .rendered_frame
2117 .dispatch_tree
2118 .view_path(self.view.entity_id())
2119 .into_iter()
2120 .rev()
2121 {
2122 if !self.window.dirty_views.insert(view_id) {
2123 break;
2124 }
2125 }
2126
2127 if self.window.draw_phase == DrawPhase::None {
2128 self.window_cx.window.dirty.set(true);
2129 self.window_cx.app.push_effect(Effect::Notify {
2130 emitter: self.view.model.entity_id,
2131 });
2132 }
2133 }
2134
2135 /// Register a callback to be invoked when the window is resized.
2136 pub fn observe_window_bounds(
2137 &mut self,
2138 mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2139 ) -> Subscription {
2140 let view = self.view.downgrade();
2141 let (subscription, activate) = self.window.bounds_observers.insert(
2142 (),
2143 Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
2144 );
2145 activate();
2146 subscription
2147 }
2148
2149 /// Register a callback to be invoked when the window is activated or deactivated.
2150 pub fn observe_window_activation(
2151 &mut self,
2152 mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2153 ) -> Subscription {
2154 let view = self.view.downgrade();
2155 let (subscription, activate) = self.window.activation_observers.insert(
2156 (),
2157 Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
2158 );
2159 activate();
2160 subscription
2161 }
2162
2163 /// Registers a callback to be invoked when the window appearance changes.
2164 pub fn observe_window_appearance(
2165 &mut self,
2166 mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2167 ) -> Subscription {
2168 let view = self.view.downgrade();
2169 let (subscription, activate) = self.window.appearance_observers.insert(
2170 (),
2171 Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
2172 );
2173 activate();
2174 subscription
2175 }
2176
2177 /// Register a listener to be called when the given focus handle receives focus.
2178 /// Returns a subscription and persists until the subscription is dropped.
2179 pub fn on_focus(
2180 &mut self,
2181 handle: &FocusHandle,
2182 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2183 ) -> Subscription {
2184 let view = self.view.downgrade();
2185 let focus_id = handle.id;
2186 let (subscription, activate) =
2187 self.window.new_focus_listener(Box::new(move |event, cx| {
2188 view.update(cx, |view, cx| {
2189 if event.previous_focus_path.last() != Some(&focus_id)
2190 && event.current_focus_path.last() == Some(&focus_id)
2191 {
2192 listener(view, cx)
2193 }
2194 })
2195 .is_ok()
2196 }));
2197 self.app.defer(|_| activate());
2198 subscription
2199 }
2200
2201 /// Register a listener to be called when the given focus handle or one of its descendants receives focus.
2202 /// Returns a subscription and persists until the subscription is dropped.
2203 pub fn on_focus_in(
2204 &mut self,
2205 handle: &FocusHandle,
2206 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2207 ) -> Subscription {
2208 let view = self.view.downgrade();
2209 let focus_id = handle.id;
2210 let (subscription, activate) =
2211 self.window.new_focus_listener(Box::new(move |event, cx| {
2212 view.update(cx, |view, cx| {
2213 if !event.previous_focus_path.contains(&focus_id)
2214 && event.current_focus_path.contains(&focus_id)
2215 {
2216 listener(view, cx)
2217 }
2218 })
2219 .is_ok()
2220 }));
2221 self.app.defer(move |_| activate());
2222 subscription
2223 }
2224
2225 /// Register a listener to be called when the given focus handle loses focus.
2226 /// Returns a subscription and persists until the subscription is dropped.
2227 pub fn on_blur(
2228 &mut self,
2229 handle: &FocusHandle,
2230 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2231 ) -> Subscription {
2232 let view = self.view.downgrade();
2233 let focus_id = handle.id;
2234 let (subscription, activate) =
2235 self.window.new_focus_listener(Box::new(move |event, cx| {
2236 view.update(cx, |view, cx| {
2237 if event.previous_focus_path.last() == Some(&focus_id)
2238 && event.current_focus_path.last() != Some(&focus_id)
2239 {
2240 listener(view, cx)
2241 }
2242 })
2243 .is_ok()
2244 }));
2245 self.app.defer(move |_| activate());
2246 subscription
2247 }
2248
2249 /// Register a listener to be called when nothing in the window has focus.
2250 /// This typically happens when the node that was focused is removed from the tree,
2251 /// and this callback lets you chose a default place to restore the users focus.
2252 /// Returns a subscription and persists until the subscription is dropped.
2253 pub fn on_focus_lost(
2254 &mut self,
2255 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2256 ) -> Subscription {
2257 let view = self.view.downgrade();
2258 let (subscription, activate) = self.window.focus_lost_listeners.insert(
2259 (),
2260 Box::new(move |cx| view.update(cx, |view, cx| listener(view, cx)).is_ok()),
2261 );
2262 activate();
2263 subscription
2264 }
2265
2266 /// Register a listener to be called when the given focus handle or one of its descendants loses focus.
2267 /// Returns a subscription and persists until the subscription is dropped.
2268 pub fn on_focus_out(
2269 &mut self,
2270 handle: &FocusHandle,
2271 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2272 ) -> Subscription {
2273 let view = self.view.downgrade();
2274 let focus_id = handle.id;
2275 let (subscription, activate) =
2276 self.window.new_focus_listener(Box::new(move |event, cx| {
2277 view.update(cx, |view, cx| {
2278 if event.previous_focus_path.contains(&focus_id)
2279 && !event.current_focus_path.contains(&focus_id)
2280 {
2281 listener(view, cx)
2282 }
2283 })
2284 .is_ok()
2285 }));
2286 self.app.defer(move |_| activate());
2287 subscription
2288 }
2289
2290 /// Schedule a future to be run asynchronously.
2291 /// The given callback is invoked with a [`WeakView<V>`] to avoid leaking the view for a long-running process.
2292 /// It's also given an [`AsyncWindowContext`], which can be used to access the state of the view across await points.
2293 /// The returned future will be polled on the main thread.
2294 pub fn spawn<Fut, R>(
2295 &mut self,
2296 f: impl FnOnce(WeakView<V>, AsyncWindowContext) -> Fut,
2297 ) -> Task<R>
2298 where
2299 R: 'static,
2300 Fut: Future<Output = R> + 'static,
2301 {
2302 let view = self.view().downgrade();
2303 self.window_cx.spawn(|cx| f(view, cx))
2304 }
2305
2306 /// Updates the global state of the given type.
2307 pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
2308 where
2309 G: Global,
2310 {
2311 let mut global = self.app.lease_global::<G>();
2312 let result = f(&mut global, self);
2313 self.app.end_global_lease(global);
2314 result
2315 }
2316
2317 /// Register a callback to be invoked when the given global state changes.
2318 pub fn observe_global<G: Global>(
2319 &mut self,
2320 mut f: impl FnMut(&mut V, &mut ViewContext<'_, V>) + 'static,
2321 ) -> Subscription {
2322 let window_handle = self.window.handle;
2323 let view = self.view().downgrade();
2324 let (subscription, activate) = self.global_observers.insert(
2325 TypeId::of::<G>(),
2326 Box::new(move |cx| {
2327 window_handle
2328 .update(cx, |_, cx| view.update(cx, |view, cx| f(view, cx)).is_ok())
2329 .unwrap_or(false)
2330 }),
2331 );
2332 self.app.defer(move |_| activate());
2333 subscription
2334 }
2335
2336 /// Register a callback to be invoked when the given Action type is dispatched to the window.
2337 pub fn on_action(
2338 &mut self,
2339 action_type: TypeId,
2340 listener: impl Fn(&mut V, &dyn Any, DispatchPhase, &mut ViewContext<V>) + 'static,
2341 ) {
2342 let handle = self.view().clone();
2343 self.window_cx
2344 .on_action(action_type, move |action, phase, cx| {
2345 handle.update(cx, |view, cx| {
2346 listener(view, action, phase, cx);
2347 })
2348 });
2349 }
2350
2351 /// Emit an event to be handled any other views that have subscribed via [ViewContext::subscribe].
2352 pub fn emit<Evt>(&mut self, event: Evt)
2353 where
2354 Evt: 'static,
2355 V: EventEmitter<Evt>,
2356 {
2357 let emitter = self.view.model.entity_id;
2358 self.app.push_effect(Effect::Emit {
2359 emitter,
2360 event_type: TypeId::of::<Evt>(),
2361 event: Box::new(event),
2362 });
2363 }
2364
2365 /// Move focus to the current view, assuming it implements [`FocusableView`].
2366 pub fn focus_self(&mut self)
2367 where
2368 V: FocusableView,
2369 {
2370 self.defer(|view, cx| view.focus_handle(cx).focus(cx))
2371 }
2372
2373 /// Convenience method for accessing view state in an event callback.
2374 ///
2375 /// Many GPUI callbacks take the form of `Fn(&E, &mut WindowContext)`,
2376 /// but it's often useful to be able to access view state in these
2377 /// callbacks. This method provides a convenient way to do so.
2378 pub fn listener<E>(
2379 &self,
2380 f: impl Fn(&mut V, &E, &mut ViewContext<V>) + 'static,
2381 ) -> impl Fn(&E, &mut WindowContext) + 'static {
2382 let view = self.view().downgrade();
2383 move |e: &E, cx: &mut WindowContext| {
2384 view.update(cx, |view, cx| f(view, e, cx)).ok();
2385 }
2386 }
2387}
2388
2389impl<V> Context for ViewContext<'_, V> {
2390 type Result<U> = U;
2391
2392 fn new_model<T: 'static>(
2393 &mut self,
2394 build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
2395 ) -> Model<T> {
2396 self.window_cx.new_model(build_model)
2397 }
2398
2399 fn update_model<T: 'static, R>(
2400 &mut self,
2401 model: &Model<T>,
2402 update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
2403 ) -> R {
2404 self.window_cx.update_model(model, update)
2405 }
2406
2407 fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
2408 where
2409 F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
2410 {
2411 self.window_cx.update_window(window, update)
2412 }
2413
2414 fn read_model<T, R>(
2415 &self,
2416 handle: &Model<T>,
2417 read: impl FnOnce(&T, &AppContext) -> R,
2418 ) -> Self::Result<R>
2419 where
2420 T: 'static,
2421 {
2422 self.window_cx.read_model(handle, read)
2423 }
2424
2425 fn read_window<T, R>(
2426 &self,
2427 window: &WindowHandle<T>,
2428 read: impl FnOnce(View<T>, &AppContext) -> R,
2429 ) -> Result<R>
2430 where
2431 T: 'static,
2432 {
2433 self.window_cx.read_window(window, read)
2434 }
2435}
2436
2437impl<V: 'static> VisualContext for ViewContext<'_, V> {
2438 fn new_view<W: Render + 'static>(
2439 &mut self,
2440 build_view_state: impl FnOnce(&mut ViewContext<'_, W>) -> W,
2441 ) -> Self::Result<View<W>> {
2442 self.window_cx.new_view(build_view_state)
2443 }
2444
2445 fn update_view<V2: 'static, R>(
2446 &mut self,
2447 view: &View<V2>,
2448 update: impl FnOnce(&mut V2, &mut ViewContext<'_, V2>) -> R,
2449 ) -> Self::Result<R> {
2450 self.window_cx.update_view(view, update)
2451 }
2452
2453 fn replace_root_view<W>(
2454 &mut self,
2455 build_view: impl FnOnce(&mut ViewContext<'_, W>) -> W,
2456 ) -> Self::Result<View<W>>
2457 where
2458 W: 'static + Render,
2459 {
2460 self.window_cx.replace_root_view(build_view)
2461 }
2462
2463 fn focus_view<W: FocusableView>(&mut self, view: &View<W>) -> Self::Result<()> {
2464 self.window_cx.focus_view(view)
2465 }
2466
2467 fn dismiss_view<W: ManagedView>(&mut self, view: &View<W>) -> Self::Result<()> {
2468 self.window_cx.dismiss_view(view)
2469 }
2470}
2471
2472impl<'a, V> std::ops::Deref for ViewContext<'a, V> {
2473 type Target = WindowContext<'a>;
2474
2475 fn deref(&self) -> &Self::Target {
2476 &self.window_cx
2477 }
2478}
2479
2480impl<'a, V> std::ops::DerefMut for ViewContext<'a, V> {
2481 fn deref_mut(&mut self) -> &mut Self::Target {
2482 &mut self.window_cx
2483 }
2484}
2485
2486// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
2487slotmap::new_key_type! {
2488 /// A unique identifier for a window.
2489 pub struct WindowId;
2490}
2491
2492impl WindowId {
2493 /// Converts this window ID to a `u64`.
2494 pub fn as_u64(&self) -> u64 {
2495 self.0.as_ffi()
2496 }
2497}
2498
2499/// A handle to a window with a specific root view type.
2500/// Note that this does not keep the window alive on its own.
2501#[derive(Deref, DerefMut)]
2502pub struct WindowHandle<V> {
2503 #[deref]
2504 #[deref_mut]
2505 pub(crate) any_handle: AnyWindowHandle,
2506 state_type: PhantomData<V>,
2507}
2508
2509impl<V: 'static + Render> WindowHandle<V> {
2510 /// Creates a new handle from a window ID.
2511 /// This does not check if the root type of the window is `V`.
2512 pub fn new(id: WindowId) -> Self {
2513 WindowHandle {
2514 any_handle: AnyWindowHandle {
2515 id,
2516 state_type: TypeId::of::<V>(),
2517 },
2518 state_type: PhantomData,
2519 }
2520 }
2521
2522 /// Get the root view out of this window.
2523 ///
2524 /// This will fail if the window is closed or if the root view's type does not match `V`.
2525 pub fn root<C>(&self, cx: &mut C) -> Result<View<V>>
2526 where
2527 C: Context,
2528 {
2529 Flatten::flatten(cx.update_window(self.any_handle, |root_view, _| {
2530 root_view
2531 .downcast::<V>()
2532 .map_err(|_| anyhow!("the type of the window's root view has changed"))
2533 }))
2534 }
2535
2536 /// Updates the root view of this window.
2537 ///
2538 /// This will fail if the window has been closed or if the root view's type does not match
2539 pub fn update<C, R>(
2540 &self,
2541 cx: &mut C,
2542 update: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
2543 ) -> Result<R>
2544 where
2545 C: Context,
2546 {
2547 cx.update_window(self.any_handle, |root_view, cx| {
2548 let view = root_view
2549 .downcast::<V>()
2550 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
2551 Ok(cx.update_view(&view, update))
2552 })?
2553 }
2554
2555 /// Read the root view out of this window.
2556 ///
2557 /// This will fail if the window is closed or if the root view's type does not match `V`.
2558 pub fn read<'a>(&self, cx: &'a AppContext) -> Result<&'a V> {
2559 let x = cx
2560 .windows
2561 .get(self.id)
2562 .and_then(|window| {
2563 window
2564 .as_ref()
2565 .and_then(|window| window.root_view.clone())
2566 .map(|root_view| root_view.downcast::<V>())
2567 })
2568 .ok_or_else(|| anyhow!("window not found"))?
2569 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
2570
2571 Ok(x.read(cx))
2572 }
2573
2574 /// Read the root view out of this window, with a callback
2575 ///
2576 /// This will fail if the window is closed or if the root view's type does not match `V`.
2577 pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &AppContext) -> R) -> Result<R>
2578 where
2579 C: Context,
2580 {
2581 cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
2582 }
2583
2584 /// Read the root view pointer off of this window.
2585 ///
2586 /// This will fail if the window is closed or if the root view's type does not match `V`.
2587 pub fn root_view<C>(&self, cx: &C) -> Result<View<V>>
2588 where
2589 C: Context,
2590 {
2591 cx.read_window(self, |root_view, _cx| root_view.clone())
2592 }
2593
2594 /// Check if this window is 'active'.
2595 ///
2596 /// Will return `None` if the window is closed or currently
2597 /// borrowed.
2598 pub fn is_active(&self, cx: &mut AppContext) -> Option<bool> {
2599 cx.update_window(self.any_handle, |_, cx| cx.is_window_active())
2600 .ok()
2601 }
2602}
2603
2604impl<V> Copy for WindowHandle<V> {}
2605
2606impl<V> Clone for WindowHandle<V> {
2607 fn clone(&self) -> Self {
2608 *self
2609 }
2610}
2611
2612impl<V> PartialEq for WindowHandle<V> {
2613 fn eq(&self, other: &Self) -> bool {
2614 self.any_handle == other.any_handle
2615 }
2616}
2617
2618impl<V> Eq for WindowHandle<V> {}
2619
2620impl<V> Hash for WindowHandle<V> {
2621 fn hash<H: Hasher>(&self, state: &mut H) {
2622 self.any_handle.hash(state);
2623 }
2624}
2625
2626impl<V: 'static> From<WindowHandle<V>> for AnyWindowHandle {
2627 fn from(val: WindowHandle<V>) -> Self {
2628 val.any_handle
2629 }
2630}
2631
2632/// A handle to a window with any root view type, which can be downcast to a window with a specific root view type.
2633#[derive(Copy, Clone, PartialEq, Eq, Hash)]
2634pub struct AnyWindowHandle {
2635 pub(crate) id: WindowId,
2636 state_type: TypeId,
2637}
2638
2639impl AnyWindowHandle {
2640 /// Get the ID of this window.
2641 pub fn window_id(&self) -> WindowId {
2642 self.id
2643 }
2644
2645 /// Attempt to convert this handle to a window handle with a specific root view type.
2646 /// If the types do not match, this will return `None`.
2647 pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
2648 if TypeId::of::<T>() == self.state_type {
2649 Some(WindowHandle {
2650 any_handle: *self,
2651 state_type: PhantomData,
2652 })
2653 } else {
2654 None
2655 }
2656 }
2657
2658 /// Updates the state of the root view of this window.
2659 ///
2660 /// This will fail if the window has been closed.
2661 pub fn update<C, R>(
2662 self,
2663 cx: &mut C,
2664 update: impl FnOnce(AnyView, &mut WindowContext<'_>) -> R,
2665 ) -> Result<R>
2666 where
2667 C: Context,
2668 {
2669 cx.update_window(self, update)
2670 }
2671
2672 /// Read the state of the root view of this window.
2673 ///
2674 /// This will fail if the window has been closed.
2675 pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(View<T>, &AppContext) -> R) -> Result<R>
2676 where
2677 C: Context,
2678 T: 'static,
2679 {
2680 let view = self
2681 .downcast::<T>()
2682 .context("the type of the window's root view has changed")?;
2683
2684 cx.read_window(&view, read)
2685 }
2686}
2687
2688/// An identifier for an [`Element`](crate::Element).
2689///
2690/// Can be constructed with a string, a number, or both, as well
2691/// as other internal representations.
2692#[derive(Clone, Debug, Eq, PartialEq, Hash)]
2693pub enum ElementId {
2694 /// The ID of a View element
2695 View(EntityId),
2696 /// An integer ID.
2697 Integer(usize),
2698 /// A string based ID.
2699 Name(SharedString),
2700 /// An ID that's equated with a focus handle.
2701 FocusHandle(FocusId),
2702 /// A combination of a name and an integer.
2703 NamedInteger(SharedString, usize),
2704}
2705
2706impl Display for ElementId {
2707 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2708 match self {
2709 ElementId::View(entity_id) => write!(f, "view-{}", entity_id)?,
2710 ElementId::Integer(ix) => write!(f, "{}", ix)?,
2711 ElementId::Name(name) => write!(f, "{}", name)?,
2712 ElementId::FocusHandle(_) => write!(f, "FocusHandle")?,
2713 ElementId::NamedInteger(s, i) => write!(f, "{}-{}", s, i)?,
2714 }
2715
2716 Ok(())
2717 }
2718}
2719
2720impl TryInto<SharedString> for ElementId {
2721 type Error = anyhow::Error;
2722
2723 fn try_into(self) -> anyhow::Result<SharedString> {
2724 if let ElementId::Name(name) = self {
2725 Ok(name)
2726 } else {
2727 Err(anyhow!("element id is not string"))
2728 }
2729 }
2730}
2731
2732impl From<usize> for ElementId {
2733 fn from(id: usize) -> Self {
2734 ElementId::Integer(id)
2735 }
2736}
2737
2738impl From<i32> for ElementId {
2739 fn from(id: i32) -> Self {
2740 Self::Integer(id as usize)
2741 }
2742}
2743
2744impl From<SharedString> for ElementId {
2745 fn from(name: SharedString) -> Self {
2746 ElementId::Name(name)
2747 }
2748}
2749
2750impl From<&'static str> for ElementId {
2751 fn from(name: &'static str) -> Self {
2752 ElementId::Name(name.into())
2753 }
2754}
2755
2756impl<'a> From<&'a FocusHandle> for ElementId {
2757 fn from(handle: &'a FocusHandle) -> Self {
2758 ElementId::FocusHandle(handle.id)
2759 }
2760}
2761
2762impl From<(&'static str, EntityId)> for ElementId {
2763 fn from((name, id): (&'static str, EntityId)) -> Self {
2764 ElementId::NamedInteger(name.into(), id.as_u64() as usize)
2765 }
2766}
2767
2768impl From<(&'static str, usize)> for ElementId {
2769 fn from((name, id): (&'static str, usize)) -> Self {
2770 ElementId::NamedInteger(name.into(), id)
2771 }
2772}
2773
2774impl From<(&'static str, u64)> for ElementId {
2775 fn from((name, id): (&'static str, u64)) -> Self {
2776 ElementId::NamedInteger(name.into(), id as usize)
2777 }
2778}
2779
2780/// A rectangle to be rendered in the window at the given position and size.
2781/// Passed as an argument [`ElementContext::paint_quad`].
2782#[derive(Clone)]
2783pub struct PaintQuad {
2784 bounds: Bounds<Pixels>,
2785 corner_radii: Corners<Pixels>,
2786 background: Hsla,
2787 border_widths: Edges<Pixels>,
2788 border_color: Hsla,
2789}
2790
2791impl PaintQuad {
2792 /// Sets the corner radii of the quad.
2793 pub fn corner_radii(self, corner_radii: impl Into<Corners<Pixels>>) -> Self {
2794 PaintQuad {
2795 corner_radii: corner_radii.into(),
2796 ..self
2797 }
2798 }
2799
2800 /// Sets the border widths of the quad.
2801 pub fn border_widths(self, border_widths: impl Into<Edges<Pixels>>) -> Self {
2802 PaintQuad {
2803 border_widths: border_widths.into(),
2804 ..self
2805 }
2806 }
2807
2808 /// Sets the border color of the quad.
2809 pub fn border_color(self, border_color: impl Into<Hsla>) -> Self {
2810 PaintQuad {
2811 border_color: border_color.into(),
2812 ..self
2813 }
2814 }
2815
2816 /// Sets the background color of the quad.
2817 pub fn background(self, background: impl Into<Hsla>) -> Self {
2818 PaintQuad {
2819 background: background.into(),
2820 ..self
2821 }
2822 }
2823}
2824
2825/// Creates a quad with the given parameters.
2826pub fn quad(
2827 bounds: Bounds<Pixels>,
2828 corner_radii: impl Into<Corners<Pixels>>,
2829 background: impl Into<Hsla>,
2830 border_widths: impl Into<Edges<Pixels>>,
2831 border_color: impl Into<Hsla>,
2832) -> PaintQuad {
2833 PaintQuad {
2834 bounds,
2835 corner_radii: corner_radii.into(),
2836 background: background.into(),
2837 border_widths: border_widths.into(),
2838 border_color: border_color.into(),
2839 }
2840}
2841
2842/// Creates a filled quad with the given bounds and background color.
2843pub fn fill(bounds: impl Into<Bounds<Pixels>>, background: impl Into<Hsla>) -> PaintQuad {
2844 PaintQuad {
2845 bounds: bounds.into(),
2846 corner_radii: (0.).into(),
2847 background: background.into(),
2848 border_widths: (0.).into(),
2849 border_color: transparent_black(),
2850 }
2851}
2852
2853/// Creates a rectangle outline with the given bounds, border color, and a 1px border width
2854pub fn outline(bounds: impl Into<Bounds<Pixels>>, border_color: impl Into<Hsla>) -> PaintQuad {
2855 PaintQuad {
2856 bounds: bounds.into(),
2857 corner_radii: (0.).into(),
2858 background: transparent_black(),
2859 border_widths: (1.).into(),
2860 border_color: border_color.into(),
2861 }
2862}