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