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 reserve_model<T: 'static>(&mut self) -> Self::Result<crate::Reservation<T>> {
1834 self.app.reserve_model()
1835 }
1836
1837 fn insert_model<T: 'static>(
1838 &mut self,
1839 reservation: crate::Reservation<T>,
1840 build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
1841 ) -> Self::Result<Model<T>> {
1842 self.app.insert_model(reservation, build_model)
1843 }
1844
1845 fn update_model<T: 'static, R>(
1846 &mut self,
1847 model: &Model<T>,
1848 update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
1849 ) -> R {
1850 let mut entity = self.entities.lease(model);
1851 let result = update(
1852 &mut *entity,
1853 &mut ModelContext::new(&mut *self.app, model.downgrade()),
1854 );
1855 self.entities.end_lease(entity);
1856 result
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 update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
1872 where
1873 F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
1874 {
1875 if window == self.window.handle {
1876 let root_view = self.window.root_view.clone().unwrap();
1877 Ok(update(root_view, self))
1878 } else {
1879 window.update(self.app, update)
1880 }
1881 }
1882
1883 fn read_window<T, R>(
1884 &self,
1885 window: &WindowHandle<T>,
1886 read: impl FnOnce(View<T>, &AppContext) -> R,
1887 ) -> Result<R>
1888 where
1889 T: 'static,
1890 {
1891 if window.any_handle == self.window.handle {
1892 let root_view = self
1893 .window
1894 .root_view
1895 .clone()
1896 .unwrap()
1897 .downcast::<T>()
1898 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
1899 Ok(read(root_view, self))
1900 } else {
1901 self.app.read_window(window, read)
1902 }
1903 }
1904}
1905
1906impl VisualContext for WindowContext<'_> {
1907 fn new_view<V>(
1908 &mut self,
1909 build_view_state: impl FnOnce(&mut ViewContext<'_, V>) -> V,
1910 ) -> Self::Result<View<V>>
1911 where
1912 V: 'static + Render,
1913 {
1914 let slot = self.app.entities.reserve();
1915 let view = View {
1916 model: slot.clone(),
1917 };
1918 let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1919 let entity = build_view_state(&mut cx);
1920 cx.entities.insert(slot, entity);
1921
1922 // Non-generic part to avoid leaking SubscriberSet to invokers of `new_view`.
1923 fn notify_observers(cx: &mut WindowContext, tid: TypeId, view: AnyView) {
1924 cx.new_view_observers.clone().retain(&tid, |observer| {
1925 let any_view = view.clone();
1926 (observer)(any_view, cx);
1927 true
1928 });
1929 }
1930 notify_observers(self, TypeId::of::<V>(), AnyView::from(view.clone()));
1931
1932 view
1933 }
1934
1935 /// Updates the given view. Prefer calling [`View::update`] instead, which calls this method.
1936 fn update_view<T: 'static, R>(
1937 &mut self,
1938 view: &View<T>,
1939 update: impl FnOnce(&mut T, &mut ViewContext<'_, T>) -> R,
1940 ) -> Self::Result<R> {
1941 let mut lease = self.app.entities.lease(&view.model);
1942 let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, view);
1943 let result = update(&mut *lease, &mut cx);
1944 cx.app.entities.end_lease(lease);
1945 result
1946 }
1947
1948 fn replace_root_view<V>(
1949 &mut self,
1950 build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
1951 ) -> Self::Result<View<V>>
1952 where
1953 V: 'static + Render,
1954 {
1955 let view = self.new_view(build_view);
1956 self.window.root_view = Some(view.clone().into());
1957 self.refresh();
1958 view
1959 }
1960
1961 fn focus_view<V: crate::FocusableView>(&mut self, view: &View<V>) -> Self::Result<()> {
1962 self.update_view(view, |view, cx| {
1963 view.focus_handle(cx).clone().focus(cx);
1964 })
1965 }
1966
1967 fn dismiss_view<V>(&mut self, view: &View<V>) -> Self::Result<()>
1968 where
1969 V: ManagedView,
1970 {
1971 self.update_view(view, |_, cx| cx.emit(DismissEvent))
1972 }
1973}
1974
1975impl<'a> std::ops::Deref for WindowContext<'a> {
1976 type Target = AppContext;
1977
1978 fn deref(&self) -> &Self::Target {
1979 self.app
1980 }
1981}
1982
1983impl<'a> std::ops::DerefMut for WindowContext<'a> {
1984 fn deref_mut(&mut self) -> &mut Self::Target {
1985 self.app
1986 }
1987}
1988
1989impl<'a> Borrow<AppContext> for WindowContext<'a> {
1990 fn borrow(&self) -> &AppContext {
1991 self.app
1992 }
1993}
1994
1995impl<'a> BorrowMut<AppContext> for WindowContext<'a> {
1996 fn borrow_mut(&mut self) -> &mut AppContext {
1997 self.app
1998 }
1999}
2000
2001/// This trait contains functionality that is shared across [`ViewContext`] and [`WindowContext`]
2002pub trait BorrowWindow: BorrowMut<Window> + BorrowMut<AppContext> {
2003 #[doc(hidden)]
2004 fn app_mut(&mut self) -> &mut AppContext {
2005 self.borrow_mut()
2006 }
2007
2008 #[doc(hidden)]
2009 fn app(&self) -> &AppContext {
2010 self.borrow()
2011 }
2012
2013 #[doc(hidden)]
2014 fn window(&self) -> &Window {
2015 self.borrow()
2016 }
2017
2018 #[doc(hidden)]
2019 fn window_mut(&mut self) -> &mut Window {
2020 self.borrow_mut()
2021 }
2022}
2023
2024impl Borrow<Window> for WindowContext<'_> {
2025 fn borrow(&self) -> &Window {
2026 self.window
2027 }
2028}
2029
2030impl BorrowMut<Window> for WindowContext<'_> {
2031 fn borrow_mut(&mut self) -> &mut Window {
2032 self.window
2033 }
2034}
2035
2036impl<T> BorrowWindow for T where T: BorrowMut<AppContext> + BorrowMut<Window> {}
2037
2038/// Provides access to application state that is specialized for a particular [`View`].
2039/// Allows you to interact with focus, emit events, etc.
2040/// ViewContext also derefs to [`WindowContext`], giving you access to all of its methods as well.
2041/// When you call [`View::update`], you're passed a `&mut V` and an `&mut ViewContext<V>`.
2042pub struct ViewContext<'a, V> {
2043 window_cx: WindowContext<'a>,
2044 view: &'a View<V>,
2045}
2046
2047impl<V> Borrow<AppContext> for ViewContext<'_, V> {
2048 fn borrow(&self) -> &AppContext {
2049 &*self.window_cx.app
2050 }
2051}
2052
2053impl<V> BorrowMut<AppContext> for ViewContext<'_, V> {
2054 fn borrow_mut(&mut self) -> &mut AppContext {
2055 &mut *self.window_cx.app
2056 }
2057}
2058
2059impl<V> Borrow<Window> for ViewContext<'_, V> {
2060 fn borrow(&self) -> &Window {
2061 &*self.window_cx.window
2062 }
2063}
2064
2065impl<V> BorrowMut<Window> for ViewContext<'_, V> {
2066 fn borrow_mut(&mut self) -> &mut Window {
2067 &mut *self.window_cx.window
2068 }
2069}
2070
2071impl<'a, V: 'static> ViewContext<'a, V> {
2072 pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window, view: &'a View<V>) -> Self {
2073 Self {
2074 window_cx: WindowContext::new(app, window),
2075 view,
2076 }
2077 }
2078
2079 /// Get the entity_id of this view.
2080 pub fn entity_id(&self) -> EntityId {
2081 self.view.entity_id()
2082 }
2083
2084 /// Get the view pointer underlying this context.
2085 pub fn view(&self) -> &View<V> {
2086 self.view
2087 }
2088
2089 /// Get the model underlying this view.
2090 pub fn model(&self) -> &Model<V> {
2091 &self.view.model
2092 }
2093
2094 /// Access the underlying window context.
2095 pub fn window_context(&mut self) -> &mut WindowContext<'a> {
2096 &mut self.window_cx
2097 }
2098
2099 /// Sets a given callback to be run on the next frame.
2100 pub fn on_next_frame(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static)
2101 where
2102 V: 'static,
2103 {
2104 let view = self.view().clone();
2105 self.window_cx.on_next_frame(move |cx| view.update(cx, f));
2106 }
2107
2108 /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
2109 /// that are currently on the stack to be returned to the app.
2110 pub fn defer(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static) {
2111 let view = self.view().downgrade();
2112 self.window_cx.defer(move |cx| {
2113 view.update(cx, f).ok();
2114 });
2115 }
2116
2117 /// Observe another model or view for changes to its state, as tracked by [`ModelContext::notify`].
2118 pub fn observe<V2, E>(
2119 &mut self,
2120 entity: &E,
2121 mut on_notify: impl FnMut(&mut V, E, &mut ViewContext<'_, V>) + 'static,
2122 ) -> Subscription
2123 where
2124 V2: 'static,
2125 V: 'static,
2126 E: Entity<V2>,
2127 {
2128 let view = self.view().downgrade();
2129 let entity_id = entity.entity_id();
2130 let entity = entity.downgrade();
2131 let window_handle = self.window.handle;
2132 self.app.new_observer(
2133 entity_id,
2134 Box::new(move |cx| {
2135 window_handle
2136 .update(cx, |_, cx| {
2137 if let Some(handle) = E::upgrade_from(&entity) {
2138 view.update(cx, |this, cx| on_notify(this, handle, cx))
2139 .is_ok()
2140 } else {
2141 false
2142 }
2143 })
2144 .unwrap_or(false)
2145 }),
2146 )
2147 }
2148
2149 /// Subscribe to events emitted by another model or view.
2150 /// The entity to which you're subscribing must implement the [`EventEmitter`] trait.
2151 /// 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.
2152 pub fn subscribe<V2, E, Evt>(
2153 &mut self,
2154 entity: &E,
2155 mut on_event: impl FnMut(&mut V, E, &Evt, &mut ViewContext<'_, V>) + 'static,
2156 ) -> Subscription
2157 where
2158 V2: EventEmitter<Evt>,
2159 E: Entity<V2>,
2160 Evt: 'static,
2161 {
2162 let view = self.view().downgrade();
2163 let entity_id = entity.entity_id();
2164 let handle = entity.downgrade();
2165 let window_handle = self.window.handle;
2166 self.app.new_subscription(
2167 entity_id,
2168 (
2169 TypeId::of::<Evt>(),
2170 Box::new(move |event, cx| {
2171 window_handle
2172 .update(cx, |_, cx| {
2173 if let Some(handle) = E::upgrade_from(&handle) {
2174 let event = event.downcast_ref().expect("invalid event type");
2175 view.update(cx, |this, cx| on_event(this, handle, event, cx))
2176 .is_ok()
2177 } else {
2178 false
2179 }
2180 })
2181 .unwrap_or(false)
2182 }),
2183 ),
2184 )
2185 }
2186
2187 /// Register a callback to be invoked when the view is released.
2188 ///
2189 /// The callback receives a handle to the view's window. This handle may be
2190 /// invalid, if the window was closed before the view was released.
2191 pub fn on_release(
2192 &mut self,
2193 on_release: impl FnOnce(&mut V, AnyWindowHandle, &mut AppContext) + 'static,
2194 ) -> Subscription {
2195 let window_handle = self.window.handle;
2196 let (subscription, activate) = self.app.release_listeners.insert(
2197 self.view.model.entity_id,
2198 Box::new(move |this, cx| {
2199 let this = this.downcast_mut().expect("invalid entity type");
2200 on_release(this, window_handle, cx)
2201 }),
2202 );
2203 activate();
2204 subscription
2205 }
2206
2207 /// Register a callback to be invoked when the given Model or View is released.
2208 pub fn observe_release<V2, E>(
2209 &mut self,
2210 entity: &E,
2211 mut on_release: impl FnMut(&mut V, &mut V2, &mut ViewContext<'_, V>) + 'static,
2212 ) -> Subscription
2213 where
2214 V: 'static,
2215 V2: 'static,
2216 E: Entity<V2>,
2217 {
2218 let view = self.view().downgrade();
2219 let entity_id = entity.entity_id();
2220 let window_handle = self.window.handle;
2221 let (subscription, activate) = self.app.release_listeners.insert(
2222 entity_id,
2223 Box::new(move |entity, cx| {
2224 let entity = entity.downcast_mut().expect("invalid entity type");
2225 let _ = window_handle.update(cx, |_, cx| {
2226 view.update(cx, |this, cx| on_release(this, entity, cx))
2227 });
2228 }),
2229 );
2230 activate();
2231 subscription
2232 }
2233
2234 /// Indicate that this view has changed, which will invoke any observers and also mark the window as dirty.
2235 /// If this view or any of its ancestors are *cached*, notifying it will cause it or its ancestors to be redrawn.
2236 pub fn notify(&mut self) {
2237 self.window_cx.notify(self.view.entity_id());
2238 }
2239
2240 /// Register a callback to be invoked when the window is resized.
2241 pub fn observe_window_bounds(
2242 &mut self,
2243 mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2244 ) -> Subscription {
2245 let view = self.view.downgrade();
2246 let (subscription, activate) = self.window.bounds_observers.insert(
2247 (),
2248 Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
2249 );
2250 activate();
2251 subscription
2252 }
2253
2254 /// Register a callback to be invoked when the window is activated or deactivated.
2255 pub fn observe_window_activation(
2256 &mut self,
2257 mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2258 ) -> Subscription {
2259 let view = self.view.downgrade();
2260 let (subscription, activate) = self.window.activation_observers.insert(
2261 (),
2262 Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
2263 );
2264 activate();
2265 subscription
2266 }
2267
2268 /// Registers a callback to be invoked when the window appearance changes.
2269 pub fn observe_window_appearance(
2270 &mut self,
2271 mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2272 ) -> Subscription {
2273 let view = self.view.downgrade();
2274 let (subscription, activate) = self.window.appearance_observers.insert(
2275 (),
2276 Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
2277 );
2278 activate();
2279 subscription
2280 }
2281
2282 /// Register a listener to be called when the given focus handle receives focus.
2283 /// Returns a subscription and persists until the subscription is dropped.
2284 pub fn on_focus(
2285 &mut self,
2286 handle: &FocusHandle,
2287 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2288 ) -> Subscription {
2289 let view = self.view.downgrade();
2290 let focus_id = handle.id;
2291 let (subscription, activate) =
2292 self.window.new_focus_listener(Box::new(move |event, cx| {
2293 view.update(cx, |view, cx| {
2294 if event.previous_focus_path.last() != Some(&focus_id)
2295 && event.current_focus_path.last() == Some(&focus_id)
2296 {
2297 listener(view, cx)
2298 }
2299 })
2300 .is_ok()
2301 }));
2302 self.app.defer(|_| activate());
2303 subscription
2304 }
2305
2306 /// Register a listener to be called when the given focus handle or one of its descendants receives focus.
2307 /// Returns a subscription and persists until the subscription is dropped.
2308 pub fn on_focus_in(
2309 &mut self,
2310 handle: &FocusHandle,
2311 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2312 ) -> Subscription {
2313 let view = self.view.downgrade();
2314 let focus_id = handle.id;
2315 let (subscription, activate) =
2316 self.window.new_focus_listener(Box::new(move |event, cx| {
2317 view.update(cx, |view, cx| {
2318 if !event.previous_focus_path.contains(&focus_id)
2319 && event.current_focus_path.contains(&focus_id)
2320 {
2321 listener(view, cx)
2322 }
2323 })
2324 .is_ok()
2325 }));
2326 self.app.defer(move |_| activate());
2327 subscription
2328 }
2329
2330 /// Register a listener to be called when the given focus handle loses focus.
2331 /// Returns a subscription and persists until the subscription is dropped.
2332 pub fn on_blur(
2333 &mut self,
2334 handle: &FocusHandle,
2335 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2336 ) -> Subscription {
2337 let view = self.view.downgrade();
2338 let focus_id = handle.id;
2339 let (subscription, activate) =
2340 self.window.new_focus_listener(Box::new(move |event, cx| {
2341 view.update(cx, |view, cx| {
2342 if event.previous_focus_path.last() == Some(&focus_id)
2343 && event.current_focus_path.last() != Some(&focus_id)
2344 {
2345 listener(view, cx)
2346 }
2347 })
2348 .is_ok()
2349 }));
2350 self.app.defer(move |_| activate());
2351 subscription
2352 }
2353
2354 /// Register a listener to be called when nothing in the window has focus.
2355 /// This typically happens when the node that was focused is removed from the tree,
2356 /// and this callback lets you chose a default place to restore the users focus.
2357 /// Returns a subscription and persists until the subscription is dropped.
2358 pub fn on_focus_lost(
2359 &mut self,
2360 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2361 ) -> Subscription {
2362 let view = self.view.downgrade();
2363 let (subscription, activate) = self.window.focus_lost_listeners.insert(
2364 (),
2365 Box::new(move |cx| view.update(cx, |view, cx| listener(view, cx)).is_ok()),
2366 );
2367 activate();
2368 subscription
2369 }
2370
2371 /// Register a listener to be called when the given focus handle or one of its descendants loses focus.
2372 /// Returns a subscription and persists until the subscription is dropped.
2373 pub fn on_focus_out(
2374 &mut self,
2375 handle: &FocusHandle,
2376 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2377 ) -> Subscription {
2378 let view = self.view.downgrade();
2379 let focus_id = handle.id;
2380 let (subscription, activate) =
2381 self.window.new_focus_listener(Box::new(move |event, cx| {
2382 view.update(cx, |view, cx| {
2383 if event.previous_focus_path.contains(&focus_id)
2384 && !event.current_focus_path.contains(&focus_id)
2385 {
2386 listener(view, cx)
2387 }
2388 })
2389 .is_ok()
2390 }));
2391 self.app.defer(move |_| activate());
2392 subscription
2393 }
2394
2395 /// Schedule a future to be run asynchronously.
2396 /// The given callback is invoked with a [`WeakView<V>`] to avoid leaking the view for a long-running process.
2397 /// It's also given an [`AsyncWindowContext`], which can be used to access the state of the view across await points.
2398 /// The returned future will be polled on the main thread.
2399 pub fn spawn<Fut, R>(
2400 &mut self,
2401 f: impl FnOnce(WeakView<V>, AsyncWindowContext) -> Fut,
2402 ) -> Task<R>
2403 where
2404 R: 'static,
2405 Fut: Future<Output = R> + 'static,
2406 {
2407 let view = self.view().downgrade();
2408 self.window_cx.spawn(|cx| f(view, cx))
2409 }
2410
2411 /// Register a callback to be invoked when the given global state changes.
2412 pub fn observe_global<G: Global>(
2413 &mut self,
2414 mut f: impl FnMut(&mut V, &mut ViewContext<'_, V>) + 'static,
2415 ) -> Subscription {
2416 let window_handle = self.window.handle;
2417 let view = self.view().downgrade();
2418 let (subscription, activate) = self.global_observers.insert(
2419 TypeId::of::<G>(),
2420 Box::new(move |cx| {
2421 window_handle
2422 .update(cx, |_, cx| view.update(cx, |view, cx| f(view, cx)).is_ok())
2423 .unwrap_or(false)
2424 }),
2425 );
2426 self.app.defer(move |_| activate());
2427 subscription
2428 }
2429
2430 /// Register a callback to be invoked when the given Action type is dispatched to the window.
2431 pub fn on_action(
2432 &mut self,
2433 action_type: TypeId,
2434 listener: impl Fn(&mut V, &dyn Any, DispatchPhase, &mut ViewContext<V>) + 'static,
2435 ) {
2436 let handle = self.view().clone();
2437 self.window_cx
2438 .on_action(action_type, move |action, phase, cx| {
2439 handle.update(cx, |view, cx| {
2440 listener(view, action, phase, cx);
2441 })
2442 });
2443 }
2444
2445 /// Emit an event to be handled any other views that have subscribed via [ViewContext::subscribe].
2446 pub fn emit<Evt>(&mut self, event: Evt)
2447 where
2448 Evt: 'static,
2449 V: EventEmitter<Evt>,
2450 {
2451 let emitter = self.view.model.entity_id;
2452 self.app.push_effect(Effect::Emit {
2453 emitter,
2454 event_type: TypeId::of::<Evt>(),
2455 event: Box::new(event),
2456 });
2457 }
2458
2459 /// Move focus to the current view, assuming it implements [`FocusableView`].
2460 pub fn focus_self(&mut self)
2461 where
2462 V: FocusableView,
2463 {
2464 self.defer(|view, cx| view.focus_handle(cx).focus(cx))
2465 }
2466
2467 /// Convenience method for accessing view state in an event callback.
2468 ///
2469 /// Many GPUI callbacks take the form of `Fn(&E, &mut WindowContext)`,
2470 /// but it's often useful to be able to access view state in these
2471 /// callbacks. This method provides a convenient way to do so.
2472 pub fn listener<E>(
2473 &self,
2474 f: impl Fn(&mut V, &E, &mut ViewContext<V>) + 'static,
2475 ) -> impl Fn(&E, &mut WindowContext) + 'static {
2476 let view = self.view().downgrade();
2477 move |e: &E, cx: &mut WindowContext| {
2478 view.update(cx, |view, cx| f(view, e, cx)).ok();
2479 }
2480 }
2481}
2482
2483impl<V> Context for ViewContext<'_, V> {
2484 type Result<U> = U;
2485
2486 fn new_model<T: 'static>(
2487 &mut self,
2488 build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
2489 ) -> Model<T> {
2490 self.window_cx.new_model(build_model)
2491 }
2492
2493 fn reserve_model<T: 'static>(&mut self) -> Self::Result<crate::Reservation<T>> {
2494 self.window_cx.reserve_model()
2495 }
2496
2497 fn insert_model<T: 'static>(
2498 &mut self,
2499 reservation: crate::Reservation<T>,
2500 build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
2501 ) -> Self::Result<Model<T>> {
2502 self.window_cx.insert_model(reservation, build_model)
2503 }
2504
2505 fn update_model<T: 'static, R>(
2506 &mut self,
2507 model: &Model<T>,
2508 update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
2509 ) -> R {
2510 self.window_cx.update_model(model, update)
2511 }
2512
2513 fn read_model<T, R>(
2514 &self,
2515 handle: &Model<T>,
2516 read: impl FnOnce(&T, &AppContext) -> R,
2517 ) -> Self::Result<R>
2518 where
2519 T: 'static,
2520 {
2521 self.window_cx.read_model(handle, read)
2522 }
2523
2524 fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
2525 where
2526 F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
2527 {
2528 self.window_cx.update_window(window, update)
2529 }
2530
2531 fn read_window<T, R>(
2532 &self,
2533 window: &WindowHandle<T>,
2534 read: impl FnOnce(View<T>, &AppContext) -> R,
2535 ) -> Result<R>
2536 where
2537 T: 'static,
2538 {
2539 self.window_cx.read_window(window, read)
2540 }
2541}
2542
2543impl<V: 'static> VisualContext for ViewContext<'_, V> {
2544 fn new_view<W: Render + 'static>(
2545 &mut self,
2546 build_view_state: impl FnOnce(&mut ViewContext<'_, W>) -> W,
2547 ) -> Self::Result<View<W>> {
2548 self.window_cx.new_view(build_view_state)
2549 }
2550
2551 fn update_view<V2: 'static, R>(
2552 &mut self,
2553 view: &View<V2>,
2554 update: impl FnOnce(&mut V2, &mut ViewContext<'_, V2>) -> R,
2555 ) -> Self::Result<R> {
2556 self.window_cx.update_view(view, update)
2557 }
2558
2559 fn replace_root_view<W>(
2560 &mut self,
2561 build_view: impl FnOnce(&mut ViewContext<'_, W>) -> W,
2562 ) -> Self::Result<View<W>>
2563 where
2564 W: 'static + Render,
2565 {
2566 self.window_cx.replace_root_view(build_view)
2567 }
2568
2569 fn focus_view<W: FocusableView>(&mut self, view: &View<W>) -> Self::Result<()> {
2570 self.window_cx.focus_view(view)
2571 }
2572
2573 fn dismiss_view<W: ManagedView>(&mut self, view: &View<W>) -> Self::Result<()> {
2574 self.window_cx.dismiss_view(view)
2575 }
2576}
2577
2578impl<'a, V> std::ops::Deref for ViewContext<'a, V> {
2579 type Target = WindowContext<'a>;
2580
2581 fn deref(&self) -> &Self::Target {
2582 &self.window_cx
2583 }
2584}
2585
2586impl<'a, V> std::ops::DerefMut for ViewContext<'a, V> {
2587 fn deref_mut(&mut self) -> &mut Self::Target {
2588 &mut self.window_cx
2589 }
2590}
2591
2592// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
2593slotmap::new_key_type! {
2594 /// A unique identifier for a window.
2595 pub struct WindowId;
2596}
2597
2598impl WindowId {
2599 /// Converts this window ID to a `u64`.
2600 pub fn as_u64(&self) -> u64 {
2601 self.0.as_ffi()
2602 }
2603}
2604
2605/// A handle to a window with a specific root view type.
2606/// Note that this does not keep the window alive on its own.
2607#[derive(Deref, DerefMut)]
2608pub struct WindowHandle<V> {
2609 #[deref]
2610 #[deref_mut]
2611 pub(crate) any_handle: AnyWindowHandle,
2612 state_type: PhantomData<V>,
2613}
2614
2615impl<V: 'static + Render> WindowHandle<V> {
2616 /// Creates a new handle from a window ID.
2617 /// This does not check if the root type of the window is `V`.
2618 pub fn new(id: WindowId) -> Self {
2619 WindowHandle {
2620 any_handle: AnyWindowHandle {
2621 id,
2622 state_type: TypeId::of::<V>(),
2623 },
2624 state_type: PhantomData,
2625 }
2626 }
2627
2628 /// Get the root view out of this window.
2629 ///
2630 /// This will fail if the window is closed or if the root view's type does not match `V`.
2631 pub fn root<C>(&self, cx: &mut C) -> Result<View<V>>
2632 where
2633 C: Context,
2634 {
2635 Flatten::flatten(cx.update_window(self.any_handle, |root_view, _| {
2636 root_view
2637 .downcast::<V>()
2638 .map_err(|_| anyhow!("the type of the window's root view has changed"))
2639 }))
2640 }
2641
2642 /// Updates the root view of this window.
2643 ///
2644 /// This will fail if the window has been closed or if the root view's type does not match
2645 pub fn update<C, R>(
2646 &self,
2647 cx: &mut C,
2648 update: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
2649 ) -> Result<R>
2650 where
2651 C: Context,
2652 {
2653 cx.update_window(self.any_handle, |root_view, cx| {
2654 let view = root_view
2655 .downcast::<V>()
2656 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
2657 Ok(cx.update_view(&view, update))
2658 })?
2659 }
2660
2661 /// Read the root view out of this window.
2662 ///
2663 /// This will fail if the window is closed or if the root view's type does not match `V`.
2664 pub fn read<'a>(&self, cx: &'a AppContext) -> Result<&'a V> {
2665 let x = cx
2666 .windows
2667 .get(self.id)
2668 .and_then(|window| {
2669 window
2670 .as_ref()
2671 .and_then(|window| window.root_view.clone())
2672 .map(|root_view| root_view.downcast::<V>())
2673 })
2674 .ok_or_else(|| anyhow!("window not found"))?
2675 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
2676
2677 Ok(x.read(cx))
2678 }
2679
2680 /// Read the root view out of this window, with a callback
2681 ///
2682 /// This will fail if the window is closed or if the root view's type does not match `V`.
2683 pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &AppContext) -> R) -> Result<R>
2684 where
2685 C: Context,
2686 {
2687 cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
2688 }
2689
2690 /// Read the root view pointer off of this window.
2691 ///
2692 /// This will fail if the window is closed or if the root view's type does not match `V`.
2693 pub fn root_view<C>(&self, cx: &C) -> Result<View<V>>
2694 where
2695 C: Context,
2696 {
2697 cx.read_window(self, |root_view, _cx| root_view.clone())
2698 }
2699
2700 /// Check if this window is 'active'.
2701 ///
2702 /// Will return `None` if the window is closed or currently
2703 /// borrowed.
2704 pub fn is_active(&self, cx: &mut AppContext) -> Option<bool> {
2705 cx.update_window(self.any_handle, |_, cx| cx.is_window_active())
2706 .ok()
2707 }
2708}
2709
2710impl<V> Copy for WindowHandle<V> {}
2711
2712impl<V> Clone for WindowHandle<V> {
2713 fn clone(&self) -> Self {
2714 *self
2715 }
2716}
2717
2718impl<V> PartialEq for WindowHandle<V> {
2719 fn eq(&self, other: &Self) -> bool {
2720 self.any_handle == other.any_handle
2721 }
2722}
2723
2724impl<V> Eq for WindowHandle<V> {}
2725
2726impl<V> Hash for WindowHandle<V> {
2727 fn hash<H: Hasher>(&self, state: &mut H) {
2728 self.any_handle.hash(state);
2729 }
2730}
2731
2732impl<V: 'static> From<WindowHandle<V>> for AnyWindowHandle {
2733 fn from(val: WindowHandle<V>) -> Self {
2734 val.any_handle
2735 }
2736}
2737
2738/// A handle to a window with any root view type, which can be downcast to a window with a specific root view type.
2739#[derive(Copy, Clone, PartialEq, Eq, Hash)]
2740pub struct AnyWindowHandle {
2741 pub(crate) id: WindowId,
2742 state_type: TypeId,
2743}
2744
2745impl AnyWindowHandle {
2746 /// Get the ID of this window.
2747 pub fn window_id(&self) -> WindowId {
2748 self.id
2749 }
2750
2751 /// Attempt to convert this handle to a window handle with a specific root view type.
2752 /// If the types do not match, this will return `None`.
2753 pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
2754 if TypeId::of::<T>() == self.state_type {
2755 Some(WindowHandle {
2756 any_handle: *self,
2757 state_type: PhantomData,
2758 })
2759 } else {
2760 None
2761 }
2762 }
2763
2764 /// Updates the state of the root view of this window.
2765 ///
2766 /// This will fail if the window has been closed.
2767 pub fn update<C, R>(
2768 self,
2769 cx: &mut C,
2770 update: impl FnOnce(AnyView, &mut WindowContext<'_>) -> R,
2771 ) -> Result<R>
2772 where
2773 C: Context,
2774 {
2775 cx.update_window(self, update)
2776 }
2777
2778 /// Read the state of the root view of this window.
2779 ///
2780 /// This will fail if the window has been closed.
2781 pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(View<T>, &AppContext) -> R) -> Result<R>
2782 where
2783 C: Context,
2784 T: 'static,
2785 {
2786 let view = self
2787 .downcast::<T>()
2788 .context("the type of the window's root view has changed")?;
2789
2790 cx.read_window(&view, read)
2791 }
2792}
2793
2794/// An identifier for an [`Element`](crate::Element).
2795///
2796/// Can be constructed with a string, a number, or both, as well
2797/// as other internal representations.
2798#[derive(Clone, Debug, Eq, PartialEq, Hash)]
2799pub enum ElementId {
2800 /// The ID of a View element
2801 View(EntityId),
2802 /// An integer ID.
2803 Integer(usize),
2804 /// A string based ID.
2805 Name(SharedString),
2806 /// An ID that's equated with a focus handle.
2807 FocusHandle(FocusId),
2808 /// A combination of a name and an integer.
2809 NamedInteger(SharedString, usize),
2810}
2811
2812impl Display for ElementId {
2813 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2814 match self {
2815 ElementId::View(entity_id) => write!(f, "view-{}", entity_id)?,
2816 ElementId::Integer(ix) => write!(f, "{}", ix)?,
2817 ElementId::Name(name) => write!(f, "{}", name)?,
2818 ElementId::FocusHandle(_) => write!(f, "FocusHandle")?,
2819 ElementId::NamedInteger(s, i) => write!(f, "{}-{}", s, i)?,
2820 }
2821
2822 Ok(())
2823 }
2824}
2825
2826impl TryInto<SharedString> for ElementId {
2827 type Error = anyhow::Error;
2828
2829 fn try_into(self) -> anyhow::Result<SharedString> {
2830 if let ElementId::Name(name) = self {
2831 Ok(name)
2832 } else {
2833 Err(anyhow!("element id is not string"))
2834 }
2835 }
2836}
2837
2838impl From<usize> for ElementId {
2839 fn from(id: usize) -> Self {
2840 ElementId::Integer(id)
2841 }
2842}
2843
2844impl From<i32> for ElementId {
2845 fn from(id: i32) -> Self {
2846 Self::Integer(id as usize)
2847 }
2848}
2849
2850impl From<SharedString> for ElementId {
2851 fn from(name: SharedString) -> Self {
2852 ElementId::Name(name)
2853 }
2854}
2855
2856impl From<&'static str> for ElementId {
2857 fn from(name: &'static str) -> Self {
2858 ElementId::Name(name.into())
2859 }
2860}
2861
2862impl<'a> From<&'a FocusHandle> for ElementId {
2863 fn from(handle: &'a FocusHandle) -> Self {
2864 ElementId::FocusHandle(handle.id)
2865 }
2866}
2867
2868impl From<(&'static str, EntityId)> for ElementId {
2869 fn from((name, id): (&'static str, EntityId)) -> Self {
2870 ElementId::NamedInteger(name.into(), id.as_u64() as usize)
2871 }
2872}
2873
2874impl From<(&'static str, usize)> for ElementId {
2875 fn from((name, id): (&'static str, usize)) -> Self {
2876 ElementId::NamedInteger(name.into(), id)
2877 }
2878}
2879
2880impl From<(&'static str, u64)> for ElementId {
2881 fn from((name, id): (&'static str, u64)) -> Self {
2882 ElementId::NamedInteger(name.into(), id as usize)
2883 }
2884}
2885
2886/// A rectangle to be rendered in the window at the given position and size.
2887/// Passed as an argument [`ElementContext::paint_quad`].
2888#[derive(Clone)]
2889pub struct PaintQuad {
2890 /// The bounds of the quad within the window.
2891 pub bounds: Bounds<Pixels>,
2892 /// The radii of the quad's corners.
2893 pub corner_radii: Corners<Pixels>,
2894 /// The background color of the quad.
2895 pub background: Hsla,
2896 /// The widths of the quad's borders.
2897 pub border_widths: Edges<Pixels>,
2898 /// The color of the quad's borders.
2899 pub border_color: Hsla,
2900}
2901
2902impl PaintQuad {
2903 /// Sets the corner radii of the quad.
2904 pub fn corner_radii(self, corner_radii: impl Into<Corners<Pixels>>) -> Self {
2905 PaintQuad {
2906 corner_radii: corner_radii.into(),
2907 ..self
2908 }
2909 }
2910
2911 /// Sets the border widths of the quad.
2912 pub fn border_widths(self, border_widths: impl Into<Edges<Pixels>>) -> Self {
2913 PaintQuad {
2914 border_widths: border_widths.into(),
2915 ..self
2916 }
2917 }
2918
2919 /// Sets the border color of the quad.
2920 pub fn border_color(self, border_color: impl Into<Hsla>) -> Self {
2921 PaintQuad {
2922 border_color: border_color.into(),
2923 ..self
2924 }
2925 }
2926
2927 /// Sets the background color of the quad.
2928 pub fn background(self, background: impl Into<Hsla>) -> Self {
2929 PaintQuad {
2930 background: background.into(),
2931 ..self
2932 }
2933 }
2934}
2935
2936/// Creates a quad with the given parameters.
2937pub fn quad(
2938 bounds: Bounds<Pixels>,
2939 corner_radii: impl Into<Corners<Pixels>>,
2940 background: impl Into<Hsla>,
2941 border_widths: impl Into<Edges<Pixels>>,
2942 border_color: impl Into<Hsla>,
2943) -> PaintQuad {
2944 PaintQuad {
2945 bounds,
2946 corner_radii: corner_radii.into(),
2947 background: background.into(),
2948 border_widths: border_widths.into(),
2949 border_color: border_color.into(),
2950 }
2951}
2952
2953/// Creates a filled quad with the given bounds and background color.
2954pub fn fill(bounds: impl Into<Bounds<Pixels>>, background: impl Into<Hsla>) -> PaintQuad {
2955 PaintQuad {
2956 bounds: bounds.into(),
2957 corner_radii: (0.).into(),
2958 background: background.into(),
2959 border_widths: (0.).into(),
2960 border_color: transparent_black(),
2961 }
2962}
2963
2964/// Creates a rectangle outline with the given bounds, border color, and a 1px border width
2965pub fn outline(bounds: impl Into<Bounds<Pixels>>, border_color: impl Into<Hsla>) -> PaintQuad {
2966 PaintQuad {
2967 bounds: bounds.into(),
2968 corner_radii: (0.).into(),
2969 background: transparent_black(),
2970 border_widths: (1.).into(),
2971 border_color: border_color.into(),
2972 }
2973}