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