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 window
709 .update(cx, |_, cx| {
710 let node_id = focus_handle
711 .and_then(|handle| {
712 cx.window
713 .rendered_frame
714 .dispatch_tree
715 .focusable_node_id(handle.id)
716 })
717 .unwrap_or_else(|| cx.window.rendered_frame.dispatch_tree.root_node_id());
718
719 cx.dispatch_action_on_node(node_id, action.as_ref());
720 })
721 .log_err();
722 })
723 }
724
725 pub(crate) fn dispatch_keystroke_observers(
726 &mut self,
727 event: &dyn Any,
728 action: Option<Box<dyn Action>>,
729 ) {
730 let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() else {
731 return;
732 };
733
734 self.keystroke_observers
735 .clone()
736 .retain(&(), move |callback| {
737 (callback)(
738 &KeystrokeEvent {
739 keystroke: key_down_event.keystroke.clone(),
740 action: action.as_ref().map(|action| action.boxed_clone()),
741 },
742 self,
743 );
744 true
745 });
746 }
747
748 pub(crate) fn clear_pending_keystrokes(&mut self) {
749 self.window
750 .rendered_frame
751 .dispatch_tree
752 .clear_pending_keystrokes();
753 self.window
754 .next_frame
755 .dispatch_tree
756 .clear_pending_keystrokes();
757 }
758
759 /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
760 /// that are currently on the stack to be returned to the app.
761 pub fn defer(&mut self, f: impl FnOnce(&mut WindowContext) + 'static) {
762 let handle = self.window.handle;
763 self.app.defer(move |cx| {
764 handle.update(cx, |_, cx| f(cx)).ok();
765 });
766 }
767
768 /// Subscribe to events emitted by a model or view.
769 /// The entity to which you're subscribing must implement the [`EventEmitter`] trait.
770 /// 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.
771 pub fn subscribe<Emitter, E, Evt>(
772 &mut self,
773 entity: &E,
774 mut on_event: impl FnMut(E, &Evt, &mut WindowContext<'_>) + 'static,
775 ) -> Subscription
776 where
777 Emitter: EventEmitter<Evt>,
778 E: Entity<Emitter>,
779 Evt: 'static,
780 {
781 let entity_id = entity.entity_id();
782 let entity = entity.downgrade();
783 let window_handle = self.window.handle;
784 self.app.new_subscription(
785 entity_id,
786 (
787 TypeId::of::<Evt>(),
788 Box::new(move |event, cx| {
789 window_handle
790 .update(cx, |_, cx| {
791 if let Some(handle) = E::upgrade_from(&entity) {
792 let event = event.downcast_ref().expect("invalid event type");
793 on_event(handle, event, cx);
794 true
795 } else {
796 false
797 }
798 })
799 .unwrap_or(false)
800 }),
801 ),
802 )
803 }
804
805 /// Creates an [`AsyncWindowContext`], which has a static lifetime and can be held across
806 /// await points in async code.
807 pub fn to_async(&self) -> AsyncWindowContext {
808 AsyncWindowContext::new(self.app.to_async(), self.window.handle)
809 }
810
811 /// Schedule the given closure to be run directly after the current frame is rendered.
812 pub fn on_next_frame(&mut self, callback: impl FnOnce(&mut WindowContext) + 'static) {
813 RefCell::borrow_mut(&self.window.next_frame_callbacks).push(Box::new(callback));
814 }
815
816 /// Spawn the future returned by the given closure on the application thread pool.
817 /// The closure is provided a handle to the current window and an `AsyncWindowContext` for
818 /// use within your future.
819 pub fn spawn<Fut, R>(&mut self, f: impl FnOnce(AsyncWindowContext) -> Fut) -> Task<R>
820 where
821 R: 'static,
822 Fut: Future<Output = R> + 'static,
823 {
824 self.app
825 .spawn(|app| f(AsyncWindowContext::new(app, self.window.handle)))
826 }
827
828 /// Updates the global of the given type. The given closure is given simultaneous mutable
829 /// access both to the global and the context.
830 pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
831 where
832 G: Global,
833 {
834 let mut global = self.app.lease_global::<G>();
835 let result = f(&mut global, self);
836 self.app.end_global_lease(global);
837 result
838 }
839
840 fn window_bounds_changed(&mut self) {
841 self.window.scale_factor = self.window.platform_window.scale_factor();
842 self.window.viewport_size = self.window.platform_window.content_size();
843 self.window.display_id = self.window.platform_window.display().id();
844 self.refresh();
845
846 self.window
847 .bounds_observers
848 .clone()
849 .retain(&(), |callback| callback(self));
850 }
851
852 /// Returns the bounds of the current window in the global coordinate space, which could span across multiple displays.
853 pub fn window_bounds(&self) -> Bounds<GlobalPixels> {
854 self.window.platform_window.bounds()
855 }
856
857 /// Retusn whether or not the window is currently fullscreen
858 pub fn is_fullscreen(&self) -> bool {
859 self.window.platform_window.is_fullscreen()
860 }
861
862 fn appearance_changed(&mut self) {
863 self.window.appearance = self.window.platform_window.appearance();
864
865 self.window
866 .appearance_observers
867 .clone()
868 .retain(&(), |callback| callback(self));
869 }
870
871 /// Returns the appearance of the current window.
872 pub fn appearance(&self) -> WindowAppearance {
873 self.window.appearance
874 }
875
876 /// Returns the size of the drawable area within the window.
877 pub fn viewport_size(&self) -> Size<Pixels> {
878 self.window.viewport_size
879 }
880
881 /// Returns whether this window is focused by the operating system (receiving key events).
882 pub fn is_window_active(&self) -> bool {
883 self.window.active.get()
884 }
885
886 /// Toggle zoom on the window.
887 pub fn zoom_window(&self) {
888 self.window.platform_window.zoom();
889 }
890
891 /// Updates the window's title at the platform level.
892 pub fn set_window_title(&mut self, title: &str) {
893 self.window.platform_window.set_title(title);
894 }
895
896 /// Mark the window as dirty at the platform level.
897 pub fn set_window_edited(&mut self, edited: bool) {
898 self.window.platform_window.set_edited(edited);
899 }
900
901 /// Determine the display on which the window is visible.
902 pub fn display(&self) -> Option<Rc<dyn PlatformDisplay>> {
903 self.platform
904 .displays()
905 .into_iter()
906 .find(|display| display.id() == self.window.display_id)
907 }
908
909 /// Show the platform character palette.
910 pub fn show_character_palette(&self) {
911 self.window.platform_window.show_character_palette();
912 }
913
914 /// The scale factor of the display associated with the window. For example, it could
915 /// return 2.0 for a "retina" display, indicating that each logical pixel should actually
916 /// be rendered as two pixels on screen.
917 pub fn scale_factor(&self) -> f32 {
918 self.window.scale_factor
919 }
920
921 /// The size of an em for the base font of the application. Adjusting this value allows the
922 /// UI to scale, just like zooming a web page.
923 pub fn rem_size(&self) -> Pixels {
924 self.window.rem_size
925 }
926
927 /// Sets the size of an em for the base font of the application. Adjusting this value allows the
928 /// UI to scale, just like zooming a web page.
929 pub fn set_rem_size(&mut self, rem_size: impl Into<Pixels>) {
930 self.window.rem_size = rem_size.into();
931 }
932
933 /// The line height associated with the current text style.
934 pub fn line_height(&self) -> Pixels {
935 let rem_size = self.rem_size();
936 let text_style = self.text_style();
937 text_style
938 .line_height
939 .to_pixels(text_style.font_size, rem_size)
940 }
941
942 /// Call to prevent the default action of an event. Currently only used to prevent
943 /// parent elements from becoming focused on mouse down.
944 pub fn prevent_default(&mut self) {
945 self.window.default_prevented = true;
946 }
947
948 /// Obtain whether default has been prevented for the event currently being dispatched.
949 pub fn default_prevented(&self) -> bool {
950 self.window.default_prevented
951 }
952
953 /// Determine whether the given action is available along the dispatch path to the currently focused element.
954 pub fn is_action_available(&self, action: &dyn Action) -> bool {
955 let target = self
956 .focused()
957 .and_then(|focused_handle| {
958 self.window
959 .rendered_frame
960 .dispatch_tree
961 .focusable_node_id(focused_handle.id)
962 })
963 .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
964 self.window
965 .rendered_frame
966 .dispatch_tree
967 .is_action_available(action, target)
968 }
969
970 /// The position of the mouse relative to the window.
971 pub fn mouse_position(&self) -> Point<Pixels> {
972 self.window.mouse_position
973 }
974
975 /// The current state of the keyboard's modifiers
976 pub fn modifiers(&self) -> Modifiers {
977 self.window.modifiers
978 }
979
980 /// Produces a new frame and assigns it to `rendered_frame`. To actually show
981 /// the contents of the new [Scene], use [present].
982 #[profiling::function]
983 pub fn draw(&mut self) {
984 self.window.dirty.set(false);
985
986 // Restore the previously-used input handler.
987 if let Some(input_handler) = self.window.platform_window.take_input_handler() {
988 self.window
989 .rendered_frame
990 .input_handlers
991 .push(Some(input_handler));
992 }
993
994 self.with_element_context(|cx| cx.draw_roots());
995 self.window.dirty_views.clear();
996
997 self.window
998 .next_frame
999 .dispatch_tree
1000 .preserve_pending_keystrokes(
1001 &mut self.window.rendered_frame.dispatch_tree,
1002 self.window.focus,
1003 );
1004 self.window.next_frame.focus = self.window.focus;
1005 self.window.next_frame.window_active = self.window.active.get();
1006
1007 // Register requested input handler with the platform window.
1008 if let Some(input_handler) = self.window.next_frame.input_handlers.pop() {
1009 self.window
1010 .platform_window
1011 .set_input_handler(input_handler.unwrap());
1012 }
1013
1014 self.window.layout_engine.as_mut().unwrap().clear();
1015 self.text_system().finish_frame();
1016 self.window
1017 .next_frame
1018 .finish(&mut self.window.rendered_frame);
1019 ELEMENT_ARENA.with_borrow_mut(|element_arena| {
1020 let percentage = (element_arena.len() as f32 / element_arena.capacity() as f32) * 100.;
1021 if percentage >= 80. {
1022 log::warn!("elevated element arena occupation: {}.", percentage);
1023 }
1024 element_arena.clear();
1025 });
1026
1027 self.window.draw_phase = DrawPhase::Focus;
1028 let previous_focus_path = self.window.rendered_frame.focus_path();
1029 let previous_window_active = self.window.rendered_frame.window_active;
1030 mem::swap(&mut self.window.rendered_frame, &mut self.window.next_frame);
1031 self.window.next_frame.clear();
1032 let current_focus_path = self.window.rendered_frame.focus_path();
1033 let current_window_active = self.window.rendered_frame.window_active;
1034
1035 if previous_focus_path != current_focus_path
1036 || previous_window_active != current_window_active
1037 {
1038 if !previous_focus_path.is_empty() && current_focus_path.is_empty() {
1039 self.window
1040 .focus_lost_listeners
1041 .clone()
1042 .retain(&(), |listener| listener(self));
1043 }
1044
1045 let event = FocusEvent {
1046 previous_focus_path: if previous_window_active {
1047 previous_focus_path
1048 } else {
1049 Default::default()
1050 },
1051 current_focus_path: if current_window_active {
1052 current_focus_path
1053 } else {
1054 Default::default()
1055 },
1056 };
1057 self.window
1058 .focus_listeners
1059 .clone()
1060 .retain(&(), |listener| listener(&event, self));
1061 }
1062
1063 self.reset_cursor_style();
1064 self.window.refreshing = false;
1065 self.window.draw_phase = DrawPhase::None;
1066 self.window.needs_present.set(true);
1067 }
1068
1069 #[profiling::function]
1070 fn present(&self) {
1071 self.window
1072 .platform_window
1073 .draw(&self.window.rendered_frame.scene);
1074 self.window.needs_present.set(false);
1075 profiling::finish_frame!();
1076 }
1077
1078 fn reset_cursor_style(&self) {
1079 // Set the cursor only if we're the active window.
1080 if self.is_window_active() {
1081 let style = self
1082 .window
1083 .rendered_frame
1084 .cursor_styles
1085 .iter()
1086 .rev()
1087 .find(|request| request.hitbox_id.is_hovered(self))
1088 .map(|request| request.style)
1089 .unwrap_or(CursorStyle::Arrow);
1090 self.platform.set_cursor_style(style);
1091 }
1092 }
1093
1094 /// Dispatch a given keystroke as though the user had typed it.
1095 /// You can create a keystroke with Keystroke::parse("").
1096 pub fn dispatch_keystroke(&mut self, keystroke: Keystroke) -> bool {
1097 let keystroke = keystroke.with_simulated_ime();
1098 let result = self.dispatch_event(PlatformInput::KeyDown(KeyDownEvent {
1099 keystroke: keystroke.clone(),
1100 is_held: false,
1101 }));
1102 if !result.propagate {
1103 return true;
1104 }
1105
1106 if let Some(input) = keystroke.ime_key {
1107 if let Some(mut input_handler) = self.window.platform_window.take_input_handler() {
1108 input_handler.dispatch_input(&input, self);
1109 self.window.platform_window.set_input_handler(input_handler);
1110 return true;
1111 }
1112 }
1113
1114 false
1115 }
1116
1117 /// Represent this action as a key binding string, to display in the UI.
1118 pub fn keystroke_text_for(&self, action: &dyn Action) -> String {
1119 self.bindings_for_action(action)
1120 .into_iter()
1121 .next()
1122 .map(|binding| {
1123 binding
1124 .keystrokes()
1125 .iter()
1126 .map(ToString::to_string)
1127 .collect::<Vec<_>>()
1128 .join(" ")
1129 })
1130 .unwrap_or_else(|| action.name().to_string())
1131 }
1132
1133 /// Dispatch a mouse or keyboard event on the window.
1134 #[profiling::function]
1135 pub fn dispatch_event(&mut self, event: PlatformInput) -> DispatchEventResult {
1136 self.window.last_input_timestamp.set(Instant::now());
1137 // Handlers may set this to false by calling `stop_propagation`.
1138 self.app.propagate_event = true;
1139 // Handlers may set this to true by calling `prevent_default`.
1140 self.window.default_prevented = false;
1141
1142 let event = match event {
1143 // Track the mouse position with our own state, since accessing the platform
1144 // API for the mouse position can only occur on the main thread.
1145 PlatformInput::MouseMove(mouse_move) => {
1146 self.window.mouse_position = mouse_move.position;
1147 self.window.modifiers = mouse_move.modifiers;
1148 PlatformInput::MouseMove(mouse_move)
1149 }
1150 PlatformInput::MouseDown(mouse_down) => {
1151 self.window.mouse_position = mouse_down.position;
1152 self.window.modifiers = mouse_down.modifiers;
1153 PlatformInput::MouseDown(mouse_down)
1154 }
1155 PlatformInput::MouseUp(mouse_up) => {
1156 self.window.mouse_position = mouse_up.position;
1157 self.window.modifiers = mouse_up.modifiers;
1158 PlatformInput::MouseUp(mouse_up)
1159 }
1160 PlatformInput::MouseExited(mouse_exited) => {
1161 self.window.modifiers = mouse_exited.modifiers;
1162 PlatformInput::MouseExited(mouse_exited)
1163 }
1164 PlatformInput::ModifiersChanged(modifiers_changed) => {
1165 self.window.modifiers = modifiers_changed.modifiers;
1166 PlatformInput::ModifiersChanged(modifiers_changed)
1167 }
1168 PlatformInput::ScrollWheel(scroll_wheel) => {
1169 self.window.mouse_position = scroll_wheel.position;
1170 self.window.modifiers = scroll_wheel.modifiers;
1171 PlatformInput::ScrollWheel(scroll_wheel)
1172 }
1173 // Translate dragging and dropping of external files from the operating system
1174 // to internal drag and drop events.
1175 PlatformInput::FileDrop(file_drop) => match file_drop {
1176 FileDropEvent::Entered { position, paths } => {
1177 self.window.mouse_position = position;
1178 if self.active_drag.is_none() {
1179 self.active_drag = Some(AnyDrag {
1180 value: Box::new(paths.clone()),
1181 view: self.new_view(|_| paths).into(),
1182 cursor_offset: position,
1183 });
1184 }
1185 PlatformInput::MouseMove(MouseMoveEvent {
1186 position,
1187 pressed_button: Some(MouseButton::Left),
1188 modifiers: Modifiers::default(),
1189 })
1190 }
1191 FileDropEvent::Pending { position } => {
1192 self.window.mouse_position = position;
1193 PlatformInput::MouseMove(MouseMoveEvent {
1194 position,
1195 pressed_button: Some(MouseButton::Left),
1196 modifiers: Modifiers::default(),
1197 })
1198 }
1199 FileDropEvent::Submit { position } => {
1200 self.activate(true);
1201 self.window.mouse_position = position;
1202 PlatformInput::MouseUp(MouseUpEvent {
1203 button: MouseButton::Left,
1204 position,
1205 modifiers: Modifiers::default(),
1206 click_count: 1,
1207 })
1208 }
1209 FileDropEvent::Exited => {
1210 self.active_drag.take();
1211 PlatformInput::FileDrop(FileDropEvent::Exited)
1212 }
1213 },
1214 PlatformInput::KeyDown(_) | PlatformInput::KeyUp(_) => event,
1215 };
1216
1217 if let Some(any_mouse_event) = event.mouse_event() {
1218 self.dispatch_mouse_event(any_mouse_event);
1219 } else if let Some(any_key_event) = event.keyboard_event() {
1220 self.dispatch_key_event(any_key_event);
1221 }
1222
1223 DispatchEventResult {
1224 propagate: self.app.propagate_event,
1225 default_prevented: self.window.default_prevented,
1226 }
1227 }
1228
1229 fn dispatch_mouse_event(&mut self, event: &dyn Any) {
1230 let hit_test = self.window.rendered_frame.hit_test(self.mouse_position());
1231 if hit_test != self.window.mouse_hit_test {
1232 self.window.mouse_hit_test = hit_test;
1233 self.reset_cursor_style();
1234 }
1235
1236 let mut mouse_listeners = mem::take(&mut self.window.rendered_frame.mouse_listeners);
1237 self.with_element_context(|cx| {
1238 // Capture phase, events bubble from back to front. Handlers for this phase are used for
1239 // special purposes, such as detecting events outside of a given Bounds.
1240 for listener in &mut mouse_listeners {
1241 let listener = listener.as_mut().unwrap();
1242 listener(event, DispatchPhase::Capture, cx);
1243 if !cx.app.propagate_event {
1244 break;
1245 }
1246 }
1247
1248 // Bubble phase, where most normal handlers do their work.
1249 if cx.app.propagate_event {
1250 for listener in mouse_listeners.iter_mut().rev() {
1251 let listener = listener.as_mut().unwrap();
1252 listener(event, DispatchPhase::Bubble, cx);
1253 if !cx.app.propagate_event {
1254 break;
1255 }
1256 }
1257 }
1258 });
1259 self.window.rendered_frame.mouse_listeners = mouse_listeners;
1260
1261 if self.app.propagate_event && self.has_active_drag() {
1262 if event.is::<MouseMoveEvent>() {
1263 // If this was a mouse move event, redraw the window so that the
1264 // active drag can follow the mouse cursor.
1265 self.refresh();
1266 } else if event.is::<MouseUpEvent>() {
1267 // If this was a mouse up event, cancel the active drag and redraw
1268 // the window.
1269 self.active_drag = None;
1270 self.refresh();
1271 }
1272 }
1273 }
1274
1275 fn dispatch_key_event(&mut self, event: &dyn Any) {
1276 if self.window.dirty.get() {
1277 self.draw();
1278 }
1279
1280 let node_id = self
1281 .window
1282 .focus
1283 .and_then(|focus_id| {
1284 self.window
1285 .rendered_frame
1286 .dispatch_tree
1287 .focusable_node_id(focus_id)
1288 })
1289 .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
1290
1291 let dispatch_path = self
1292 .window
1293 .rendered_frame
1294 .dispatch_tree
1295 .dispatch_path(node_id);
1296
1297 if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
1298 let KeymatchResult { bindings, pending } = self
1299 .window
1300 .rendered_frame
1301 .dispatch_tree
1302 .dispatch_key(&key_down_event.keystroke, &dispatch_path);
1303
1304 if pending {
1305 let mut currently_pending = self.window.pending_input.take().unwrap_or_default();
1306 if currently_pending.focus.is_some() && currently_pending.focus != self.window.focus
1307 {
1308 currently_pending = PendingInput::default();
1309 }
1310 currently_pending.focus = self.window.focus;
1311 currently_pending
1312 .keystrokes
1313 .push(key_down_event.keystroke.clone());
1314 for binding in bindings {
1315 currently_pending.bindings.push(binding);
1316 }
1317
1318 currently_pending.timer = Some(self.spawn(|mut cx| async move {
1319 cx.background_executor.timer(Duration::from_secs(1)).await;
1320 cx.update(move |cx| {
1321 cx.clear_pending_keystrokes();
1322 let Some(currently_pending) = cx.window.pending_input.take() else {
1323 return;
1324 };
1325 cx.replay_pending_input(currently_pending)
1326 })
1327 .log_err();
1328 }));
1329
1330 self.window.pending_input = Some(currently_pending);
1331
1332 self.propagate_event = false;
1333 return;
1334 } else if let Some(currently_pending) = self.window.pending_input.take() {
1335 if bindings
1336 .iter()
1337 .all(|binding| !currently_pending.used_by_binding(binding))
1338 {
1339 self.replay_pending_input(currently_pending)
1340 }
1341 }
1342
1343 if !bindings.is_empty() {
1344 self.clear_pending_keystrokes();
1345 }
1346
1347 self.propagate_event = true;
1348 for binding in bindings {
1349 self.dispatch_action_on_node(node_id, binding.action.as_ref());
1350 if !self.propagate_event {
1351 self.dispatch_keystroke_observers(event, Some(binding.action));
1352 return;
1353 }
1354 }
1355 }
1356
1357 self.dispatch_key_down_up_event(event, &dispatch_path);
1358 if !self.propagate_event {
1359 return;
1360 }
1361
1362 self.dispatch_keystroke_observers(event, None);
1363 }
1364
1365 fn dispatch_key_down_up_event(
1366 &mut self,
1367 event: &dyn Any,
1368 dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
1369 ) {
1370 // Capture phase
1371 for node_id in dispatch_path {
1372 let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1373
1374 for key_listener in node.key_listeners.clone() {
1375 self.with_element_context(|cx| {
1376 key_listener(event, DispatchPhase::Capture, cx);
1377 });
1378 if !self.propagate_event {
1379 return;
1380 }
1381 }
1382 }
1383
1384 // Bubble phase
1385 for node_id in dispatch_path.iter().rev() {
1386 // Handle low level key events
1387 let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1388 for key_listener in node.key_listeners.clone() {
1389 self.with_element_context(|cx| {
1390 key_listener(event, DispatchPhase::Bubble, cx);
1391 });
1392 if !self.propagate_event {
1393 return;
1394 }
1395 }
1396 }
1397 }
1398
1399 /// Determine whether a potential multi-stroke key binding is in progress on this window.
1400 pub fn has_pending_keystrokes(&self) -> bool {
1401 self.window
1402 .rendered_frame
1403 .dispatch_tree
1404 .has_pending_keystrokes()
1405 }
1406
1407 fn replay_pending_input(&mut self, currently_pending: PendingInput) {
1408 let node_id = self
1409 .window
1410 .focus
1411 .and_then(|focus_id| {
1412 self.window
1413 .rendered_frame
1414 .dispatch_tree
1415 .focusable_node_id(focus_id)
1416 })
1417 .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
1418
1419 if self.window.focus != currently_pending.focus {
1420 return;
1421 }
1422
1423 let input = currently_pending.input();
1424
1425 self.propagate_event = true;
1426 for binding in currently_pending.bindings {
1427 self.dispatch_action_on_node(node_id, binding.action.as_ref());
1428 if !self.propagate_event {
1429 return;
1430 }
1431 }
1432
1433 let dispatch_path = self
1434 .window
1435 .rendered_frame
1436 .dispatch_tree
1437 .dispatch_path(node_id);
1438
1439 for keystroke in currently_pending.keystrokes {
1440 let event = KeyDownEvent {
1441 keystroke,
1442 is_held: false,
1443 };
1444
1445 self.dispatch_key_down_up_event(&event, &dispatch_path);
1446 if !self.propagate_event {
1447 return;
1448 }
1449 }
1450
1451 if !input.is_empty() {
1452 if let Some(mut input_handler) = self.window.platform_window.take_input_handler() {
1453 input_handler.dispatch_input(&input, self);
1454 self.window.platform_window.set_input_handler(input_handler)
1455 }
1456 }
1457 }
1458
1459 fn dispatch_action_on_node(&mut self, node_id: DispatchNodeId, action: &dyn Action) {
1460 let dispatch_path = self
1461 .window
1462 .rendered_frame
1463 .dispatch_tree
1464 .dispatch_path(node_id);
1465
1466 // Capture phase for global actions.
1467 self.propagate_event = true;
1468 if let Some(mut global_listeners) = self
1469 .global_action_listeners
1470 .remove(&action.as_any().type_id())
1471 {
1472 for listener in &global_listeners {
1473 listener(action.as_any(), DispatchPhase::Capture, self);
1474 if !self.propagate_event {
1475 break;
1476 }
1477 }
1478
1479 global_listeners.extend(
1480 self.global_action_listeners
1481 .remove(&action.as_any().type_id())
1482 .unwrap_or_default(),
1483 );
1484
1485 self.global_action_listeners
1486 .insert(action.as_any().type_id(), global_listeners);
1487 }
1488
1489 if !self.propagate_event {
1490 return;
1491 }
1492
1493 // Capture phase for window actions.
1494 for node_id in &dispatch_path {
1495 let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1496 for DispatchActionListener {
1497 action_type,
1498 listener,
1499 } in node.action_listeners.clone()
1500 {
1501 let any_action = action.as_any();
1502 if action_type == any_action.type_id() {
1503 self.with_element_context(|cx| {
1504 listener(any_action, DispatchPhase::Capture, cx);
1505 });
1506
1507 if !self.propagate_event {
1508 return;
1509 }
1510 }
1511 }
1512 }
1513
1514 // Bubble phase for window actions.
1515 for node_id in dispatch_path.iter().rev() {
1516 let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1517 for DispatchActionListener {
1518 action_type,
1519 listener,
1520 } in node.action_listeners.clone()
1521 {
1522 let any_action = action.as_any();
1523 if action_type == any_action.type_id() {
1524 self.propagate_event = false; // Actions stop propagation by default during the bubble phase
1525
1526 self.with_element_context(|cx| {
1527 listener(any_action, DispatchPhase::Bubble, cx);
1528 });
1529
1530 if !self.propagate_event {
1531 return;
1532 }
1533 }
1534 }
1535 }
1536
1537 // Bubble phase for global actions.
1538 if let Some(mut global_listeners) = self
1539 .global_action_listeners
1540 .remove(&action.as_any().type_id())
1541 {
1542 for listener in global_listeners.iter().rev() {
1543 self.propagate_event = false; // Actions stop propagation by default during the bubble phase
1544
1545 listener(action.as_any(), DispatchPhase::Bubble, self);
1546 if !self.propagate_event {
1547 break;
1548 }
1549 }
1550
1551 global_listeners.extend(
1552 self.global_action_listeners
1553 .remove(&action.as_any().type_id())
1554 .unwrap_or_default(),
1555 );
1556
1557 self.global_action_listeners
1558 .insert(action.as_any().type_id(), global_listeners);
1559 }
1560 }
1561
1562 /// Register the given handler to be invoked whenever the global of the given type
1563 /// is updated.
1564 pub fn observe_global<G: Global>(
1565 &mut self,
1566 f: impl Fn(&mut WindowContext<'_>) + 'static,
1567 ) -> Subscription {
1568 let window_handle = self.window.handle;
1569 let (subscription, activate) = self.global_observers.insert(
1570 TypeId::of::<G>(),
1571 Box::new(move |cx| window_handle.update(cx, |_, cx| f(cx)).is_ok()),
1572 );
1573 self.app.defer(move |_| activate());
1574 subscription
1575 }
1576
1577 /// Focus the current window and bring it to the foreground at the platform level.
1578 pub fn activate_window(&self) {
1579 self.window.platform_window.activate();
1580 }
1581
1582 /// Minimize the current window at the platform level.
1583 pub fn minimize_window(&self) {
1584 self.window.platform_window.minimize();
1585 }
1586
1587 /// Toggle full screen status on the current window at the platform level.
1588 pub fn toggle_fullscreen(&self) {
1589 self.window.platform_window.toggle_fullscreen();
1590 }
1591
1592 /// Present a platform dialog.
1593 /// The provided message will be presented, along with buttons for each answer.
1594 /// When a button is clicked, the returned Receiver will receive the index of the clicked button.
1595 pub fn prompt(
1596 &mut self,
1597 level: PromptLevel,
1598 message: &str,
1599 detail: Option<&str>,
1600 answers: &[&str],
1601 ) -> oneshot::Receiver<usize> {
1602 let prompt_builder = self.app.prompt_builder.take();
1603 let Some(prompt_builder) = prompt_builder else {
1604 unreachable!("Re-entrant window prompting is not supported by GPUI");
1605 };
1606
1607 let receiver = match &prompt_builder {
1608 PromptBuilder::Default => self
1609 .window
1610 .platform_window
1611 .prompt(level, message, detail, answers)
1612 .unwrap_or_else(|| {
1613 self.build_custom_prompt(&prompt_builder, level, message, detail, answers)
1614 }),
1615 PromptBuilder::Custom(_) => {
1616 self.build_custom_prompt(&prompt_builder, level, message, detail, answers)
1617 }
1618 };
1619
1620 self.app.prompt_builder = Some(prompt_builder);
1621
1622 receiver
1623 }
1624
1625 fn build_custom_prompt(
1626 &mut self,
1627 prompt_builder: &PromptBuilder,
1628 level: PromptLevel,
1629 message: &str,
1630 detail: Option<&str>,
1631 answers: &[&str],
1632 ) -> oneshot::Receiver<usize> {
1633 let (sender, receiver) = oneshot::channel();
1634 let handle = PromptHandle::new(sender);
1635 let handle = (prompt_builder)(level, message, detail, answers, handle, self);
1636 self.window.prompt = Some(handle);
1637 receiver
1638 }
1639
1640 /// Returns all available actions for the focused element.
1641 pub fn available_actions(&self) -> Vec<Box<dyn Action>> {
1642 let node_id = self
1643 .window
1644 .focus
1645 .and_then(|focus_id| {
1646 self.window
1647 .rendered_frame
1648 .dispatch_tree
1649 .focusable_node_id(focus_id)
1650 })
1651 .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
1652
1653 let mut actions = self
1654 .window
1655 .rendered_frame
1656 .dispatch_tree
1657 .available_actions(node_id);
1658 for action_type in self.global_action_listeners.keys() {
1659 if let Err(ix) = actions.binary_search_by_key(action_type, |a| a.as_any().type_id()) {
1660 let action = self.actions.build_action_type(action_type).ok();
1661 if let Some(action) = action {
1662 actions.insert(ix, action);
1663 }
1664 }
1665 }
1666 actions
1667 }
1668
1669 /// Returns key bindings that invoke the given action on the currently focused element.
1670 pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
1671 self.window
1672 .rendered_frame
1673 .dispatch_tree
1674 .bindings_for_action(
1675 action,
1676 &self.window.rendered_frame.dispatch_tree.context_stack,
1677 )
1678 }
1679
1680 /// Returns any bindings that would invoke the given action on the given focus handle if it were focused.
1681 pub fn bindings_for_action_in(
1682 &self,
1683 action: &dyn Action,
1684 focus_handle: &FocusHandle,
1685 ) -> Vec<KeyBinding> {
1686 let dispatch_tree = &self.window.rendered_frame.dispatch_tree;
1687
1688 let Some(node_id) = dispatch_tree.focusable_node_id(focus_handle.id) else {
1689 return vec![];
1690 };
1691 let context_stack: Vec<_> = dispatch_tree
1692 .dispatch_path(node_id)
1693 .into_iter()
1694 .filter_map(|node_id| dispatch_tree.node(node_id).context.clone())
1695 .collect();
1696 dispatch_tree.bindings_for_action(action, &context_stack)
1697 }
1698
1699 /// Returns a generic event listener that invokes the given listener with the view and context associated with the given view handle.
1700 pub fn listener_for<V: Render, E>(
1701 &self,
1702 view: &View<V>,
1703 f: impl Fn(&mut V, &E, &mut ViewContext<V>) + 'static,
1704 ) -> impl Fn(&E, &mut WindowContext) + 'static {
1705 let view = view.downgrade();
1706 move |e: &E, cx: &mut WindowContext| {
1707 view.update(cx, |view, cx| f(view, e, cx)).ok();
1708 }
1709 }
1710
1711 /// Returns a generic handler that invokes the given handler with the view and context associated with the given view handle.
1712 pub fn handler_for<V: Render>(
1713 &self,
1714 view: &View<V>,
1715 f: impl Fn(&mut V, &mut ViewContext<V>) + 'static,
1716 ) -> impl Fn(&mut WindowContext) {
1717 let view = view.downgrade();
1718 move |cx: &mut WindowContext| {
1719 view.update(cx, |view, cx| f(view, cx)).ok();
1720 }
1721 }
1722
1723 /// Register a callback that can interrupt the closing of the current window based the returned boolean.
1724 /// If the callback returns false, the window won't be closed.
1725 pub fn on_window_should_close(&mut self, f: impl Fn(&mut WindowContext) -> bool + 'static) {
1726 let mut this = self.to_async();
1727 self.window
1728 .platform_window
1729 .on_should_close(Box::new(move || this.update(|cx| f(cx)).unwrap_or(true)))
1730 }
1731
1732 /// Register an action listener on the window for the next frame. The type of action
1733 /// is determined by the first parameter of the given listener. When the next frame is rendered
1734 /// the listener will be cleared.
1735 ///
1736 /// This is a fairly low-level method, so prefer using action handlers on elements unless you have
1737 /// a specific need to register a global listener.
1738 pub fn on_action(
1739 &mut self,
1740 action_type: TypeId,
1741 listener: impl Fn(&dyn Any, DispatchPhase, &mut WindowContext) + 'static,
1742 ) {
1743 self.window
1744 .next_frame
1745 .dispatch_tree
1746 .on_action(action_type, Rc::new(listener));
1747 }
1748}
1749
1750#[cfg(target_os = "windows")]
1751impl WindowContext<'_> {
1752 /// Returns the raw HWND handle for the window.
1753 pub fn get_raw_handle(&self) -> windows::Win32::Foundation::HWND {
1754 self.window.platform_window.get_raw_handle()
1755 }
1756}
1757
1758impl Context for WindowContext<'_> {
1759 type Result<T> = T;
1760
1761 fn new_model<T>(&mut self, build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T) -> Model<T>
1762 where
1763 T: 'static,
1764 {
1765 let slot = self.app.entities.reserve();
1766 let model = build_model(&mut ModelContext::new(&mut *self.app, slot.downgrade()));
1767 self.entities.insert(slot, model)
1768 }
1769
1770 fn update_model<T: 'static, R>(
1771 &mut self,
1772 model: &Model<T>,
1773 update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
1774 ) -> R {
1775 let mut entity = self.entities.lease(model);
1776 let result = update(
1777 &mut *entity,
1778 &mut ModelContext::new(&mut *self.app, model.downgrade()),
1779 );
1780 self.entities.end_lease(entity);
1781 result
1782 }
1783
1784 fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
1785 where
1786 F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
1787 {
1788 if window == self.window.handle {
1789 let root_view = self.window.root_view.clone().unwrap();
1790 Ok(update(root_view, self))
1791 } else {
1792 window.update(self.app, update)
1793 }
1794 }
1795
1796 fn read_model<T, R>(
1797 &self,
1798 handle: &Model<T>,
1799 read: impl FnOnce(&T, &AppContext) -> R,
1800 ) -> Self::Result<R>
1801 where
1802 T: 'static,
1803 {
1804 let entity = self.entities.read(handle);
1805 read(entity, &*self.app)
1806 }
1807
1808 fn read_window<T, R>(
1809 &self,
1810 window: &WindowHandle<T>,
1811 read: impl FnOnce(View<T>, &AppContext) -> R,
1812 ) -> Result<R>
1813 where
1814 T: 'static,
1815 {
1816 if window.any_handle == self.window.handle {
1817 let root_view = self
1818 .window
1819 .root_view
1820 .clone()
1821 .unwrap()
1822 .downcast::<T>()
1823 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
1824 Ok(read(root_view, self))
1825 } else {
1826 self.app.read_window(window, read)
1827 }
1828 }
1829}
1830
1831impl VisualContext for WindowContext<'_> {
1832 fn new_view<V>(
1833 &mut self,
1834 build_view_state: impl FnOnce(&mut ViewContext<'_, V>) -> V,
1835 ) -> Self::Result<View<V>>
1836 where
1837 V: 'static + Render,
1838 {
1839 let slot = self.app.entities.reserve();
1840 let view = View {
1841 model: slot.clone(),
1842 };
1843 let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1844 let entity = build_view_state(&mut cx);
1845 cx.entities.insert(slot, entity);
1846
1847 // Non-generic part to avoid leaking SubscriberSet to invokers of `new_view`.
1848 fn notify_observers(cx: &mut WindowContext, tid: TypeId, view: AnyView) {
1849 cx.new_view_observers.clone().retain(&tid, |observer| {
1850 let any_view = view.clone();
1851 (observer)(any_view, cx);
1852 true
1853 });
1854 }
1855 notify_observers(self, TypeId::of::<V>(), AnyView::from(view.clone()));
1856
1857 view
1858 }
1859
1860 /// Updates the given view. Prefer calling [`View::update`] instead, which calls this method.
1861 fn update_view<T: 'static, R>(
1862 &mut self,
1863 view: &View<T>,
1864 update: impl FnOnce(&mut T, &mut ViewContext<'_, T>) -> R,
1865 ) -> Self::Result<R> {
1866 let mut lease = self.app.entities.lease(&view.model);
1867 let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, view);
1868 let result = update(&mut *lease, &mut cx);
1869 cx.app.entities.end_lease(lease);
1870 result
1871 }
1872
1873 fn replace_root_view<V>(
1874 &mut self,
1875 build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
1876 ) -> Self::Result<View<V>>
1877 where
1878 V: 'static + Render,
1879 {
1880 let view = self.new_view(build_view);
1881 self.window.root_view = Some(view.clone().into());
1882 self.refresh();
1883 view
1884 }
1885
1886 fn focus_view<V: crate::FocusableView>(&mut self, view: &View<V>) -> Self::Result<()> {
1887 self.update_view(view, |view, cx| {
1888 view.focus_handle(cx).clone().focus(cx);
1889 })
1890 }
1891
1892 fn dismiss_view<V>(&mut self, view: &View<V>) -> Self::Result<()>
1893 where
1894 V: ManagedView,
1895 {
1896 self.update_view(view, |_, cx| cx.emit(DismissEvent))
1897 }
1898}
1899
1900impl<'a> std::ops::Deref for WindowContext<'a> {
1901 type Target = AppContext;
1902
1903 fn deref(&self) -> &Self::Target {
1904 self.app
1905 }
1906}
1907
1908impl<'a> std::ops::DerefMut for WindowContext<'a> {
1909 fn deref_mut(&mut self) -> &mut Self::Target {
1910 self.app
1911 }
1912}
1913
1914impl<'a> Borrow<AppContext> for WindowContext<'a> {
1915 fn borrow(&self) -> &AppContext {
1916 self.app
1917 }
1918}
1919
1920impl<'a> BorrowMut<AppContext> for WindowContext<'a> {
1921 fn borrow_mut(&mut self) -> &mut AppContext {
1922 self.app
1923 }
1924}
1925
1926/// This trait contains functionality that is shared across [`ViewContext`] and [`WindowContext`]
1927pub trait BorrowWindow: BorrowMut<Window> + BorrowMut<AppContext> {
1928 #[doc(hidden)]
1929 fn app_mut(&mut self) -> &mut AppContext {
1930 self.borrow_mut()
1931 }
1932
1933 #[doc(hidden)]
1934 fn app(&self) -> &AppContext {
1935 self.borrow()
1936 }
1937
1938 #[doc(hidden)]
1939 fn window(&self) -> &Window {
1940 self.borrow()
1941 }
1942
1943 #[doc(hidden)]
1944 fn window_mut(&mut self) -> &mut Window {
1945 self.borrow_mut()
1946 }
1947}
1948
1949impl Borrow<Window> for WindowContext<'_> {
1950 fn borrow(&self) -> &Window {
1951 self.window
1952 }
1953}
1954
1955impl BorrowMut<Window> for WindowContext<'_> {
1956 fn borrow_mut(&mut self) -> &mut Window {
1957 self.window
1958 }
1959}
1960
1961impl<T> BorrowWindow for T where T: BorrowMut<AppContext> + BorrowMut<Window> {}
1962
1963/// Provides access to application state that is specialized for a particular [`View`].
1964/// Allows you to interact with focus, emit events, etc.
1965/// ViewContext also derefs to [`WindowContext`], giving you access to all of its methods as well.
1966/// When you call [`View::update`], you're passed a `&mut V` and an `&mut ViewContext<V>`.
1967pub struct ViewContext<'a, V> {
1968 window_cx: WindowContext<'a>,
1969 view: &'a View<V>,
1970}
1971
1972impl<V> Borrow<AppContext> for ViewContext<'_, V> {
1973 fn borrow(&self) -> &AppContext {
1974 &*self.window_cx.app
1975 }
1976}
1977
1978impl<V> BorrowMut<AppContext> for ViewContext<'_, V> {
1979 fn borrow_mut(&mut self) -> &mut AppContext {
1980 &mut *self.window_cx.app
1981 }
1982}
1983
1984impl<V> Borrow<Window> for ViewContext<'_, V> {
1985 fn borrow(&self) -> &Window {
1986 &*self.window_cx.window
1987 }
1988}
1989
1990impl<V> BorrowMut<Window> for ViewContext<'_, V> {
1991 fn borrow_mut(&mut self) -> &mut Window {
1992 &mut *self.window_cx.window
1993 }
1994}
1995
1996impl<'a, V: 'static> ViewContext<'a, V> {
1997 pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window, view: &'a View<V>) -> Self {
1998 Self {
1999 window_cx: WindowContext::new(app, window),
2000 view,
2001 }
2002 }
2003
2004 /// Get the entity_id of this view.
2005 pub fn entity_id(&self) -> EntityId {
2006 self.view.entity_id()
2007 }
2008
2009 /// Get the view pointer underlying this context.
2010 pub fn view(&self) -> &View<V> {
2011 self.view
2012 }
2013
2014 /// Get the model underlying this view.
2015 pub fn model(&self) -> &Model<V> {
2016 &self.view.model
2017 }
2018
2019 /// Access the underlying window context.
2020 pub fn window_context(&mut self) -> &mut WindowContext<'a> {
2021 &mut self.window_cx
2022 }
2023
2024 /// Sets a given callback to be run on the next frame.
2025 pub fn on_next_frame(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static)
2026 where
2027 V: 'static,
2028 {
2029 let view = self.view().clone();
2030 self.window_cx.on_next_frame(move |cx| view.update(cx, f));
2031 }
2032
2033 /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
2034 /// that are currently on the stack to be returned to the app.
2035 pub fn defer(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static) {
2036 let view = self.view().downgrade();
2037 self.window_cx.defer(move |cx| {
2038 view.update(cx, f).ok();
2039 });
2040 }
2041
2042 /// Observe another model or view for changes to its state, as tracked by [`ModelContext::notify`].
2043 pub fn observe<V2, E>(
2044 &mut self,
2045 entity: &E,
2046 mut on_notify: impl FnMut(&mut V, E, &mut ViewContext<'_, V>) + 'static,
2047 ) -> Subscription
2048 where
2049 V2: 'static,
2050 V: 'static,
2051 E: Entity<V2>,
2052 {
2053 let view = self.view().downgrade();
2054 let entity_id = entity.entity_id();
2055 let entity = entity.downgrade();
2056 let window_handle = self.window.handle;
2057 self.app.new_observer(
2058 entity_id,
2059 Box::new(move |cx| {
2060 window_handle
2061 .update(cx, |_, cx| {
2062 if let Some(handle) = E::upgrade_from(&entity) {
2063 view.update(cx, |this, cx| on_notify(this, handle, cx))
2064 .is_ok()
2065 } else {
2066 false
2067 }
2068 })
2069 .unwrap_or(false)
2070 }),
2071 )
2072 }
2073
2074 /// Subscribe to events emitted by another model or view.
2075 /// The entity to which you're subscribing must implement the [`EventEmitter`] trait.
2076 /// 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.
2077 pub fn subscribe<V2, E, Evt>(
2078 &mut self,
2079 entity: &E,
2080 mut on_event: impl FnMut(&mut V, E, &Evt, &mut ViewContext<'_, V>) + 'static,
2081 ) -> Subscription
2082 where
2083 V2: EventEmitter<Evt>,
2084 E: Entity<V2>,
2085 Evt: 'static,
2086 {
2087 let view = self.view().downgrade();
2088 let entity_id = entity.entity_id();
2089 let handle = entity.downgrade();
2090 let window_handle = self.window.handle;
2091 self.app.new_subscription(
2092 entity_id,
2093 (
2094 TypeId::of::<Evt>(),
2095 Box::new(move |event, cx| {
2096 window_handle
2097 .update(cx, |_, cx| {
2098 if let Some(handle) = E::upgrade_from(&handle) {
2099 let event = event.downcast_ref().expect("invalid event type");
2100 view.update(cx, |this, cx| on_event(this, handle, event, cx))
2101 .is_ok()
2102 } else {
2103 false
2104 }
2105 })
2106 .unwrap_or(false)
2107 }),
2108 ),
2109 )
2110 }
2111
2112 /// Register a callback to be invoked when the view is released.
2113 ///
2114 /// The callback receives a handle to the view's window. This handle may be
2115 /// invalid, if the window was closed before the view was released.
2116 pub fn on_release(
2117 &mut self,
2118 on_release: impl FnOnce(&mut V, AnyWindowHandle, &mut AppContext) + 'static,
2119 ) -> Subscription {
2120 let window_handle = self.window.handle;
2121 let (subscription, activate) = self.app.release_listeners.insert(
2122 self.view.model.entity_id,
2123 Box::new(move |this, cx| {
2124 let this = this.downcast_mut().expect("invalid entity type");
2125 on_release(this, window_handle, cx)
2126 }),
2127 );
2128 activate();
2129 subscription
2130 }
2131
2132 /// Register a callback to be invoked when the given Model or View is released.
2133 pub fn observe_release<V2, E>(
2134 &mut self,
2135 entity: &E,
2136 mut on_release: impl FnMut(&mut V, &mut V2, &mut ViewContext<'_, V>) + 'static,
2137 ) -> Subscription
2138 where
2139 V: 'static,
2140 V2: 'static,
2141 E: Entity<V2>,
2142 {
2143 let view = self.view().downgrade();
2144 let entity_id = entity.entity_id();
2145 let window_handle = self.window.handle;
2146 let (subscription, activate) = self.app.release_listeners.insert(
2147 entity_id,
2148 Box::new(move |entity, cx| {
2149 let entity = entity.downcast_mut().expect("invalid entity type");
2150 let _ = window_handle.update(cx, |_, cx| {
2151 view.update(cx, |this, cx| on_release(this, entity, cx))
2152 });
2153 }),
2154 );
2155 activate();
2156 subscription
2157 }
2158
2159 /// Indicate that this view has changed, which will invoke any observers and also mark the window as dirty.
2160 /// If this view or any of its ancestors are *cached*, notifying it will cause it or its ancestors to be redrawn.
2161 pub fn notify(&mut self) {
2162 for view_id in self
2163 .window
2164 .rendered_frame
2165 .dispatch_tree
2166 .view_path(self.view.entity_id())
2167 .into_iter()
2168 .rev()
2169 {
2170 if !self.window.dirty_views.insert(view_id) {
2171 break;
2172 }
2173 }
2174
2175 if self.window.draw_phase == DrawPhase::None {
2176 self.window_cx.window.dirty.set(true);
2177 self.window_cx.app.push_effect(Effect::Notify {
2178 emitter: self.view.model.entity_id,
2179 });
2180 }
2181 }
2182
2183 /// Register a callback to be invoked when the window is resized.
2184 pub fn observe_window_bounds(
2185 &mut self,
2186 mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2187 ) -> Subscription {
2188 let view = self.view.downgrade();
2189 let (subscription, activate) = self.window.bounds_observers.insert(
2190 (),
2191 Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
2192 );
2193 activate();
2194 subscription
2195 }
2196
2197 /// Register a callback to be invoked when the window is activated or deactivated.
2198 pub fn observe_window_activation(
2199 &mut self,
2200 mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2201 ) -> Subscription {
2202 let view = self.view.downgrade();
2203 let (subscription, activate) = self.window.activation_observers.insert(
2204 (),
2205 Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
2206 );
2207 activate();
2208 subscription
2209 }
2210
2211 /// Registers a callback to be invoked when the window appearance changes.
2212 pub fn observe_window_appearance(
2213 &mut self,
2214 mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2215 ) -> Subscription {
2216 let view = self.view.downgrade();
2217 let (subscription, activate) = self.window.appearance_observers.insert(
2218 (),
2219 Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
2220 );
2221 activate();
2222 subscription
2223 }
2224
2225 /// Register a listener to be called when the given focus handle receives focus.
2226 /// Returns a subscription and persists until the subscription is dropped.
2227 pub fn on_focus(
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(|_| activate());
2246 subscription
2247 }
2248
2249 /// Register a listener to be called when the given focus handle or one of its descendants receives focus.
2250 /// Returns a subscription and persists until the subscription is dropped.
2251 pub fn on_focus_in(
2252 &mut self,
2253 handle: &FocusHandle,
2254 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2255 ) -> Subscription {
2256 let view = self.view.downgrade();
2257 let focus_id = handle.id;
2258 let (subscription, activate) =
2259 self.window.new_focus_listener(Box::new(move |event, cx| {
2260 view.update(cx, |view, cx| {
2261 if !event.previous_focus_path.contains(&focus_id)
2262 && event.current_focus_path.contains(&focus_id)
2263 {
2264 listener(view, cx)
2265 }
2266 })
2267 .is_ok()
2268 }));
2269 self.app.defer(move |_| activate());
2270 subscription
2271 }
2272
2273 /// Register a listener to be called when the given focus handle loses focus.
2274 /// Returns a subscription and persists until the subscription is dropped.
2275 pub fn on_blur(
2276 &mut self,
2277 handle: &FocusHandle,
2278 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2279 ) -> Subscription {
2280 let view = self.view.downgrade();
2281 let focus_id = handle.id;
2282 let (subscription, activate) =
2283 self.window.new_focus_listener(Box::new(move |event, cx| {
2284 view.update(cx, |view, cx| {
2285 if event.previous_focus_path.last() == Some(&focus_id)
2286 && event.current_focus_path.last() != Some(&focus_id)
2287 {
2288 listener(view, cx)
2289 }
2290 })
2291 .is_ok()
2292 }));
2293 self.app.defer(move |_| activate());
2294 subscription
2295 }
2296
2297 /// Register a listener to be called when nothing in the window has focus.
2298 /// This typically happens when the node that was focused is removed from the tree,
2299 /// and this callback lets you chose a default place to restore the users focus.
2300 /// Returns a subscription and persists until the subscription is dropped.
2301 pub fn on_focus_lost(
2302 &mut self,
2303 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2304 ) -> Subscription {
2305 let view = self.view.downgrade();
2306 let (subscription, activate) = self.window.focus_lost_listeners.insert(
2307 (),
2308 Box::new(move |cx| view.update(cx, |view, cx| listener(view, cx)).is_ok()),
2309 );
2310 activate();
2311 subscription
2312 }
2313
2314 /// Register a listener to be called when the given focus handle or one of its descendants loses focus.
2315 /// Returns a subscription and persists until the subscription is dropped.
2316 pub fn on_focus_out(
2317 &mut self,
2318 handle: &FocusHandle,
2319 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2320 ) -> Subscription {
2321 let view = self.view.downgrade();
2322 let focus_id = handle.id;
2323 let (subscription, activate) =
2324 self.window.new_focus_listener(Box::new(move |event, cx| {
2325 view.update(cx, |view, cx| {
2326 if event.previous_focus_path.contains(&focus_id)
2327 && !event.current_focus_path.contains(&focus_id)
2328 {
2329 listener(view, cx)
2330 }
2331 })
2332 .is_ok()
2333 }));
2334 self.app.defer(move |_| activate());
2335 subscription
2336 }
2337
2338 /// Schedule a future to be run asynchronously.
2339 /// The given callback is invoked with a [`WeakView<V>`] to avoid leaking the view for a long-running process.
2340 /// It's also given an [`AsyncWindowContext`], which can be used to access the state of the view across await points.
2341 /// The returned future will be polled on the main thread.
2342 pub fn spawn<Fut, R>(
2343 &mut self,
2344 f: impl FnOnce(WeakView<V>, AsyncWindowContext) -> Fut,
2345 ) -> Task<R>
2346 where
2347 R: 'static,
2348 Fut: Future<Output = R> + 'static,
2349 {
2350 let view = self.view().downgrade();
2351 self.window_cx.spawn(|cx| f(view, cx))
2352 }
2353
2354 /// Updates the global state of the given type.
2355 pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
2356 where
2357 G: Global,
2358 {
2359 let mut global = self.app.lease_global::<G>();
2360 let result = f(&mut global, self);
2361 self.app.end_global_lease(global);
2362 result
2363 }
2364
2365 /// Register a callback to be invoked when the given global state changes.
2366 pub fn observe_global<G: Global>(
2367 &mut self,
2368 mut f: impl FnMut(&mut V, &mut ViewContext<'_, V>) + 'static,
2369 ) -> Subscription {
2370 let window_handle = self.window.handle;
2371 let view = self.view().downgrade();
2372 let (subscription, activate) = self.global_observers.insert(
2373 TypeId::of::<G>(),
2374 Box::new(move |cx| {
2375 window_handle
2376 .update(cx, |_, cx| view.update(cx, |view, cx| f(view, cx)).is_ok())
2377 .unwrap_or(false)
2378 }),
2379 );
2380 self.app.defer(move |_| activate());
2381 subscription
2382 }
2383
2384 /// Register a callback to be invoked when the given Action type is dispatched to the window.
2385 pub fn on_action(
2386 &mut self,
2387 action_type: TypeId,
2388 listener: impl Fn(&mut V, &dyn Any, DispatchPhase, &mut ViewContext<V>) + 'static,
2389 ) {
2390 let handle = self.view().clone();
2391 self.window_cx
2392 .on_action(action_type, move |action, phase, cx| {
2393 handle.update(cx, |view, cx| {
2394 listener(view, action, phase, cx);
2395 })
2396 });
2397 }
2398
2399 /// Emit an event to be handled any other views that have subscribed via [ViewContext::subscribe].
2400 pub fn emit<Evt>(&mut self, event: Evt)
2401 where
2402 Evt: 'static,
2403 V: EventEmitter<Evt>,
2404 {
2405 let emitter = self.view.model.entity_id;
2406 self.app.push_effect(Effect::Emit {
2407 emitter,
2408 event_type: TypeId::of::<Evt>(),
2409 event: Box::new(event),
2410 });
2411 }
2412
2413 /// Move focus to the current view, assuming it implements [`FocusableView`].
2414 pub fn focus_self(&mut self)
2415 where
2416 V: FocusableView,
2417 {
2418 self.defer(|view, cx| view.focus_handle(cx).focus(cx))
2419 }
2420
2421 /// Convenience method for accessing view state in an event callback.
2422 ///
2423 /// Many GPUI callbacks take the form of `Fn(&E, &mut WindowContext)`,
2424 /// but it's often useful to be able to access view state in these
2425 /// callbacks. This method provides a convenient way to do so.
2426 pub fn listener<E>(
2427 &self,
2428 f: impl Fn(&mut V, &E, &mut ViewContext<V>) + 'static,
2429 ) -> impl Fn(&E, &mut WindowContext) + 'static {
2430 let view = self.view().downgrade();
2431 move |e: &E, cx: &mut WindowContext| {
2432 view.update(cx, |view, cx| f(view, e, cx)).ok();
2433 }
2434 }
2435}
2436
2437impl<V> Context for ViewContext<'_, V> {
2438 type Result<U> = U;
2439
2440 fn new_model<T: 'static>(
2441 &mut self,
2442 build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
2443 ) -> Model<T> {
2444 self.window_cx.new_model(build_model)
2445 }
2446
2447 fn update_model<T: 'static, R>(
2448 &mut self,
2449 model: &Model<T>,
2450 update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
2451 ) -> R {
2452 self.window_cx.update_model(model, update)
2453 }
2454
2455 fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
2456 where
2457 F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
2458 {
2459 self.window_cx.update_window(window, update)
2460 }
2461
2462 fn read_model<T, R>(
2463 &self,
2464 handle: &Model<T>,
2465 read: impl FnOnce(&T, &AppContext) -> R,
2466 ) -> Self::Result<R>
2467 where
2468 T: 'static,
2469 {
2470 self.window_cx.read_model(handle, read)
2471 }
2472
2473 fn read_window<T, R>(
2474 &self,
2475 window: &WindowHandle<T>,
2476 read: impl FnOnce(View<T>, &AppContext) -> R,
2477 ) -> Result<R>
2478 where
2479 T: 'static,
2480 {
2481 self.window_cx.read_window(window, read)
2482 }
2483}
2484
2485impl<V: 'static> VisualContext for ViewContext<'_, V> {
2486 fn new_view<W: Render + 'static>(
2487 &mut self,
2488 build_view_state: impl FnOnce(&mut ViewContext<'_, W>) -> W,
2489 ) -> Self::Result<View<W>> {
2490 self.window_cx.new_view(build_view_state)
2491 }
2492
2493 fn update_view<V2: 'static, R>(
2494 &mut self,
2495 view: &View<V2>,
2496 update: impl FnOnce(&mut V2, &mut ViewContext<'_, V2>) -> R,
2497 ) -> Self::Result<R> {
2498 self.window_cx.update_view(view, update)
2499 }
2500
2501 fn replace_root_view<W>(
2502 &mut self,
2503 build_view: impl FnOnce(&mut ViewContext<'_, W>) -> W,
2504 ) -> Self::Result<View<W>>
2505 where
2506 W: 'static + Render,
2507 {
2508 self.window_cx.replace_root_view(build_view)
2509 }
2510
2511 fn focus_view<W: FocusableView>(&mut self, view: &View<W>) -> Self::Result<()> {
2512 self.window_cx.focus_view(view)
2513 }
2514
2515 fn dismiss_view<W: ManagedView>(&mut self, view: &View<W>) -> Self::Result<()> {
2516 self.window_cx.dismiss_view(view)
2517 }
2518}
2519
2520impl<'a, V> std::ops::Deref for ViewContext<'a, V> {
2521 type Target = WindowContext<'a>;
2522
2523 fn deref(&self) -> &Self::Target {
2524 &self.window_cx
2525 }
2526}
2527
2528impl<'a, V> std::ops::DerefMut for ViewContext<'a, V> {
2529 fn deref_mut(&mut self) -> &mut Self::Target {
2530 &mut self.window_cx
2531 }
2532}
2533
2534// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
2535slotmap::new_key_type! {
2536 /// A unique identifier for a window.
2537 pub struct WindowId;
2538}
2539
2540impl WindowId {
2541 /// Converts this window ID to a `u64`.
2542 pub fn as_u64(&self) -> u64 {
2543 self.0.as_ffi()
2544 }
2545}
2546
2547/// A handle to a window with a specific root view type.
2548/// Note that this does not keep the window alive on its own.
2549#[derive(Deref, DerefMut)]
2550pub struct WindowHandle<V> {
2551 #[deref]
2552 #[deref_mut]
2553 pub(crate) any_handle: AnyWindowHandle,
2554 state_type: PhantomData<V>,
2555}
2556
2557impl<V: 'static + Render> WindowHandle<V> {
2558 /// Creates a new handle from a window ID.
2559 /// This does not check if the root type of the window is `V`.
2560 pub fn new(id: WindowId) -> Self {
2561 WindowHandle {
2562 any_handle: AnyWindowHandle {
2563 id,
2564 state_type: TypeId::of::<V>(),
2565 },
2566 state_type: PhantomData,
2567 }
2568 }
2569
2570 /// Get the root view out of this window.
2571 ///
2572 /// This will fail if the window is closed or if the root view's type does not match `V`.
2573 pub fn root<C>(&self, cx: &mut C) -> Result<View<V>>
2574 where
2575 C: Context,
2576 {
2577 Flatten::flatten(cx.update_window(self.any_handle, |root_view, _| {
2578 root_view
2579 .downcast::<V>()
2580 .map_err(|_| anyhow!("the type of the window's root view has changed"))
2581 }))
2582 }
2583
2584 /// Updates the root view of this window.
2585 ///
2586 /// This will fail if the window has been closed or if the root view's type does not match
2587 pub fn update<C, R>(
2588 &self,
2589 cx: &mut C,
2590 update: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
2591 ) -> Result<R>
2592 where
2593 C: Context,
2594 {
2595 cx.update_window(self.any_handle, |root_view, cx| {
2596 let view = root_view
2597 .downcast::<V>()
2598 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
2599 Ok(cx.update_view(&view, update))
2600 })?
2601 }
2602
2603 /// Read the root view out of this window.
2604 ///
2605 /// This will fail if the window is closed or if the root view's type does not match `V`.
2606 pub fn read<'a>(&self, cx: &'a AppContext) -> Result<&'a V> {
2607 let x = cx
2608 .windows
2609 .get(self.id)
2610 .and_then(|window| {
2611 window
2612 .as_ref()
2613 .and_then(|window| window.root_view.clone())
2614 .map(|root_view| root_view.downcast::<V>())
2615 })
2616 .ok_or_else(|| anyhow!("window not found"))?
2617 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
2618
2619 Ok(x.read(cx))
2620 }
2621
2622 /// Read the root view out of this window, with a callback
2623 ///
2624 /// This will fail if the window is closed or if the root view's type does not match `V`.
2625 pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &AppContext) -> R) -> Result<R>
2626 where
2627 C: Context,
2628 {
2629 cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
2630 }
2631
2632 /// Read the root view pointer off of this window.
2633 ///
2634 /// This will fail if the window is closed or if the root view's type does not match `V`.
2635 pub fn root_view<C>(&self, cx: &C) -> Result<View<V>>
2636 where
2637 C: Context,
2638 {
2639 cx.read_window(self, |root_view, _cx| root_view.clone())
2640 }
2641
2642 /// Check if this window is 'active'.
2643 ///
2644 /// Will return `None` if the window is closed or currently
2645 /// borrowed.
2646 pub fn is_active(&self, cx: &mut AppContext) -> Option<bool> {
2647 cx.update_window(self.any_handle, |_, cx| cx.is_window_active())
2648 .ok()
2649 }
2650}
2651
2652impl<V> Copy for WindowHandle<V> {}
2653
2654impl<V> Clone for WindowHandle<V> {
2655 fn clone(&self) -> Self {
2656 *self
2657 }
2658}
2659
2660impl<V> PartialEq for WindowHandle<V> {
2661 fn eq(&self, other: &Self) -> bool {
2662 self.any_handle == other.any_handle
2663 }
2664}
2665
2666impl<V> Eq for WindowHandle<V> {}
2667
2668impl<V> Hash for WindowHandle<V> {
2669 fn hash<H: Hasher>(&self, state: &mut H) {
2670 self.any_handle.hash(state);
2671 }
2672}
2673
2674impl<V: 'static> From<WindowHandle<V>> for AnyWindowHandle {
2675 fn from(val: WindowHandle<V>) -> Self {
2676 val.any_handle
2677 }
2678}
2679
2680/// A handle to a window with any root view type, which can be downcast to a window with a specific root view type.
2681#[derive(Copy, Clone, PartialEq, Eq, Hash)]
2682pub struct AnyWindowHandle {
2683 pub(crate) id: WindowId,
2684 state_type: TypeId,
2685}
2686
2687impl AnyWindowHandle {
2688 /// Get the ID of this window.
2689 pub fn window_id(&self) -> WindowId {
2690 self.id
2691 }
2692
2693 /// Attempt to convert this handle to a window handle with a specific root view type.
2694 /// If the types do not match, this will return `None`.
2695 pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
2696 if TypeId::of::<T>() == self.state_type {
2697 Some(WindowHandle {
2698 any_handle: *self,
2699 state_type: PhantomData,
2700 })
2701 } else {
2702 None
2703 }
2704 }
2705
2706 /// Updates the state of the root view of this window.
2707 ///
2708 /// This will fail if the window has been closed.
2709 pub fn update<C, R>(
2710 self,
2711 cx: &mut C,
2712 update: impl FnOnce(AnyView, &mut WindowContext<'_>) -> R,
2713 ) -> Result<R>
2714 where
2715 C: Context,
2716 {
2717 cx.update_window(self, update)
2718 }
2719
2720 /// Read the state of the root view of this window.
2721 ///
2722 /// This will fail if the window has been closed.
2723 pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(View<T>, &AppContext) -> R) -> Result<R>
2724 where
2725 C: Context,
2726 T: 'static,
2727 {
2728 let view = self
2729 .downcast::<T>()
2730 .context("the type of the window's root view has changed")?;
2731
2732 cx.read_window(&view, read)
2733 }
2734}
2735
2736/// An identifier for an [`Element`](crate::Element).
2737///
2738/// Can be constructed with a string, a number, or both, as well
2739/// as other internal representations.
2740#[derive(Clone, Debug, Eq, PartialEq, Hash)]
2741pub enum ElementId {
2742 /// The ID of a View element
2743 View(EntityId),
2744 /// An integer ID.
2745 Integer(usize),
2746 /// A string based ID.
2747 Name(SharedString),
2748 /// An ID that's equated with a focus handle.
2749 FocusHandle(FocusId),
2750 /// A combination of a name and an integer.
2751 NamedInteger(SharedString, usize),
2752}
2753
2754impl Display for ElementId {
2755 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2756 match self {
2757 ElementId::View(entity_id) => write!(f, "view-{}", entity_id)?,
2758 ElementId::Integer(ix) => write!(f, "{}", ix)?,
2759 ElementId::Name(name) => write!(f, "{}", name)?,
2760 ElementId::FocusHandle(_) => write!(f, "FocusHandle")?,
2761 ElementId::NamedInteger(s, i) => write!(f, "{}-{}", s, i)?,
2762 }
2763
2764 Ok(())
2765 }
2766}
2767
2768impl TryInto<SharedString> for ElementId {
2769 type Error = anyhow::Error;
2770
2771 fn try_into(self) -> anyhow::Result<SharedString> {
2772 if let ElementId::Name(name) = self {
2773 Ok(name)
2774 } else {
2775 Err(anyhow!("element id is not string"))
2776 }
2777 }
2778}
2779
2780impl From<usize> for ElementId {
2781 fn from(id: usize) -> Self {
2782 ElementId::Integer(id)
2783 }
2784}
2785
2786impl From<i32> for ElementId {
2787 fn from(id: i32) -> Self {
2788 Self::Integer(id as usize)
2789 }
2790}
2791
2792impl From<SharedString> for ElementId {
2793 fn from(name: SharedString) -> Self {
2794 ElementId::Name(name)
2795 }
2796}
2797
2798impl From<&'static str> for ElementId {
2799 fn from(name: &'static str) -> Self {
2800 ElementId::Name(name.into())
2801 }
2802}
2803
2804impl<'a> From<&'a FocusHandle> for ElementId {
2805 fn from(handle: &'a FocusHandle) -> Self {
2806 ElementId::FocusHandle(handle.id)
2807 }
2808}
2809
2810impl From<(&'static str, EntityId)> for ElementId {
2811 fn from((name, id): (&'static str, EntityId)) -> Self {
2812 ElementId::NamedInteger(name.into(), id.as_u64() as usize)
2813 }
2814}
2815
2816impl From<(&'static str, usize)> for ElementId {
2817 fn from((name, id): (&'static str, usize)) -> Self {
2818 ElementId::NamedInteger(name.into(), id)
2819 }
2820}
2821
2822impl From<(&'static str, u64)> for ElementId {
2823 fn from((name, id): (&'static str, u64)) -> Self {
2824 ElementId::NamedInteger(name.into(), id as usize)
2825 }
2826}
2827
2828/// A rectangle to be rendered in the window at the given position and size.
2829/// Passed as an argument [`ElementContext::paint_quad`].
2830#[derive(Clone)]
2831pub struct PaintQuad {
2832 bounds: Bounds<Pixels>,
2833 corner_radii: Corners<Pixels>,
2834 background: Hsla,
2835 border_widths: Edges<Pixels>,
2836 border_color: Hsla,
2837}
2838
2839impl PaintQuad {
2840 /// Sets the corner radii of the quad.
2841 pub fn corner_radii(self, corner_radii: impl Into<Corners<Pixels>>) -> Self {
2842 PaintQuad {
2843 corner_radii: corner_radii.into(),
2844 ..self
2845 }
2846 }
2847
2848 /// Sets the border widths of the quad.
2849 pub fn border_widths(self, border_widths: impl Into<Edges<Pixels>>) -> Self {
2850 PaintQuad {
2851 border_widths: border_widths.into(),
2852 ..self
2853 }
2854 }
2855
2856 /// Sets the border color of the quad.
2857 pub fn border_color(self, border_color: impl Into<Hsla>) -> Self {
2858 PaintQuad {
2859 border_color: border_color.into(),
2860 ..self
2861 }
2862 }
2863
2864 /// Sets the background color of the quad.
2865 pub fn background(self, background: impl Into<Hsla>) -> Self {
2866 PaintQuad {
2867 background: background.into(),
2868 ..self
2869 }
2870 }
2871}
2872
2873/// Creates a quad with the given parameters.
2874pub fn quad(
2875 bounds: Bounds<Pixels>,
2876 corner_radii: impl Into<Corners<Pixels>>,
2877 background: impl Into<Hsla>,
2878 border_widths: impl Into<Edges<Pixels>>,
2879 border_color: impl Into<Hsla>,
2880) -> PaintQuad {
2881 PaintQuad {
2882 bounds,
2883 corner_radii: corner_radii.into(),
2884 background: background.into(),
2885 border_widths: border_widths.into(),
2886 border_color: border_color.into(),
2887 }
2888}
2889
2890/// Creates a filled quad with the given bounds and background color.
2891pub fn fill(bounds: impl Into<Bounds<Pixels>>, background: impl Into<Hsla>) -> PaintQuad {
2892 PaintQuad {
2893 bounds: bounds.into(),
2894 corner_radii: (0.).into(),
2895 background: background.into(),
2896 border_widths: (0.).into(),
2897 border_color: transparent_black(),
2898 }
2899}
2900
2901/// Creates a rectangle outline with the given bounds, border color, and a 1px border width
2902pub fn outline(bounds: impl Into<Bounds<Pixels>>, border_color: impl Into<Hsla>) -> PaintQuad {
2903 PaintQuad {
2904 bounds: bounds.into(),
2905 corner_radii: (0.).into(),
2906 background: transparent_black(),
2907 border_widths: (1.).into(),
2908 border_color: border_color.into(),
2909 }
2910}