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