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