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