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