1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
//! Pick an element in a window, then inspect its details and state.
//!
//! The inspector is available with the `inspector` feature and in debug builds
//! (`debug_assertions`). In other builds, [`InspectorElementId`] remains available without
//! fields, but `Inspector`, its renderer and reflection types are omitted.
//! [`Window::is_inspector_picking`] always returns `false` in those builds.
/// Identifies one element so the inspector can select it and describe its state.
///
/// The `path` and `instance_id` fields exist only in builds with the `inspector` feature or with
/// `debug_assertions`. In other builds the type has no identifying data, so every two IDs compare
/// equal; do not use it there as a stable key.
#[derive(Debug, Eq, PartialEq, Hash, Clone)]
pub struct InspectorElementId {
/// The element's stable path. It is reference counted, so cloning the ID does not copy it.
#[cfg(any(feature = "inspector", debug_assertions))]
pub path: std::rc::Rc<InspectorElementPath>,
/// Distinguishes elements that share a `path`, such as two rows built at the same call site.
#[cfg(any(feature = "inspector", debug_assertions))]
pub instance_id: usize,
}
impl Into<InspectorElementId> for &InspectorElementId {
fn into(self) -> InspectorElementId {
self.clone()
}
}
#[cfg(any(feature = "inspector", debug_assertions))]
pub use conditional::*;
#[cfg(any(feature = "inspector", debug_assertions))]
mod conditional {
use super::*;
use crate::{AnyElement, App, Context, Empty, IntoElement, Render, Window};
use collections::{FxHashMap, TypeIdHashMap, hash_map::Entry};
use std::any::{Any, TypeId};
/// A [`GlobalElementId`](crate::GlobalElementId) plus the source location where the element was built.
///
/// Two elements built at different call sites get different paths even when they
/// have the same ID, so the inspector can tell them apart.
#[derive(Debug, Eq, PartialEq, Hash)]
pub struct InspectorElementPath {
/// The global ID of this element: the chain of `ElementId`s from the root down to it,
/// including the element itself when it has an `ElementId`.
#[cfg(any(feature = "inspector", debug_assertions))]
pub global_id: crate::GlobalElementId,
/// Where the element was constructed in source code.
#[cfg(any(feature = "inspector", debug_assertions))]
pub source_location: &'static std::panic::Location<'static>,
}
impl Clone for InspectorElementPath {
fn clone(&self) -> Self {
Self {
global_id: self.global_id.clone(),
source_location: self.source_location,
}
}
}
impl Into<InspectorElementPath> for &InspectorElementPath {
fn into(self) -> InspectorElementPath {
self.clone()
}
}
/// The function that builds the inspector panel. Install it with
/// [`App::set_inspector_renderer`].
///
/// GPUI passes the [`Inspector`], window and inspector context to the renderer. It returns
/// the panel's element, and GPUI calls it on each draw of the inspector view.
pub type InspectorRenderer =
Box<dyn Fn(&mut Inspector, &mut Window, &mut Context<Inspector>) -> AnyElement>;
/// Tracks the element selected or hovered in the inspector, and whether picking is active.
///
/// Each window owns one while its inspector is open. Use [`Window::toggle_inspector`] to open
/// or close it, and [`Inspector::is_picking`] to query the mode.
pub struct Inspector {
active_element: Option<InspectedElement>,
pub(crate) pick_depth: Option<f32>,
renderers: TypeIdHashMap<InspectorElementRenderer>,
}
struct InspectedElement {
id: InspectorElementId,
states: TypeIdHashMap<Box<dyn Any>>,
}
impl InspectedElement {
fn new(id: InspectorElementId) -> Self {
InspectedElement {
id,
states: Default::default(),
}
}
}
impl Inspector {
pub(crate) fn new() -> Self {
Self {
active_element: None,
pick_depth: Some(0.0),
renderers: TypeIdHashMap::default(),
}
}
pub(crate) fn select(&mut self, id: InspectorElementId, window: &mut Window) {
self.set_active_element_id(id, window);
self.pick_depth = None;
}
pub(crate) fn hover(&mut self, id: InspectorElementId, window: &mut Window) {
if self.is_picking() {
let changed = self.set_active_element_id(id, window);
if changed {
self.pick_depth = Some(0.0);
}
}
}
pub(crate) fn set_active_element_id(
&mut self,
id: InspectorElementId,
window: &mut Window,
) -> bool {
let changed = Some(&id) != self.active_element_id();
if changed {
self.active_element = Some(InspectedElement::new(id));
window.refresh();
}
changed
}
/// Returns the ID of the element that is hovered while picking, or the element
/// that was selected, or `None` if no element is active.
pub fn active_element_id(&self) -> Option<&InspectorElementId> {
self.active_element.as_ref().map(|e| &e.id)
}
pub(crate) fn with_active_element_state<T: 'static, R>(
&mut self,
window: &mut Window,
f: impl FnOnce(&mut Option<T>, &mut Window) -> R,
) -> R {
let Some(active_element) = &mut self.active_element else {
return f(&mut None, window);
};
let type_id = TypeId::of::<T>();
let mut inspector_state = active_element
.states
.remove(&type_id)
.map(|state| *state.downcast().unwrap());
let result = f(&mut inspector_state, window);
if let Some(inspector_state) = inspector_state {
active_element
.states
.insert(type_id, Box::new(inspector_state));
}
result
}
/// Enters picking mode. While picking, moving the pointer over an element makes it
/// the active element, and a click selects it and leaves picking mode.
pub fn start_picking(&mut self) {
self.pick_depth = Some(0.0);
}
/// Returns `true` while the inspector is in picking mode.
pub fn is_picking(&self) -> bool {
self.pick_depth.is_some()
}
/// Returns one element for each state type held by the active element when that type has
/// a renderer registered with [`App::register_inspector_element`]. Returns an empty list
/// when no element is active.
///
/// Call this from your inspector renderer to show per-element details.
pub fn render_inspector_states(
&mut self,
window: &mut Window,
cx: &mut Context<Self>,
) -> Vec<AnyElement> {
let mut elements = Vec::new();
if let Some(active_element) = self.active_element.take() {
for (type_id, state) in &active_element.states {
let renderer = match self.renderers.entry(*type_id) {
Entry::Occupied(entry) => entry.into_mut(),
Entry::Vacant(entry) => {
let Some(factory) = cx
.inspector_element_registry
.factories_by_type_id
.remove(type_id)
else {
continue;
};
let renderer = factory(window, cx);
cx.inspector_element_registry
.factories_by_type_id
.insert(*type_id, factory);
entry.insert(renderer)
}
};
elements.push(renderer(
active_element.id.clone(),
state.as_ref(),
window,
cx,
));
}
self.active_element = Some(active_element);
}
elements
}
}
impl Render for Inspector {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
if let Some(inspector_renderer) = cx.inspector_renderer.take() {
let result = inspector_renderer(self, window, cx);
cx.inspector_renderer = Some(inspector_renderer);
result
} else {
Empty.into_any_element()
}
}
}
#[derive(Default)]
pub(crate) struct InspectorElementRegistry {
factories_by_type_id:
FxHashMap<TypeId, Box<dyn Fn(&mut Window, &mut App) -> InspectorElementRenderer>>,
}
impl InspectorElementRegistry {
/// Stores the renderer for state type `T`, replacing any earlier one.
pub fn register<T: 'static, R: IntoElement, F>(
&mut self,
factory: impl 'static + Fn(&mut Window, &mut App) -> F,
) where
F: 'static + FnMut(InspectorElementId, &T, &mut Window, &mut App) -> R,
{
self.factories_by_type_id.insert(
TypeId::of::<T>(),
Box::new(move |window, cx| {
let mut renderer = factory(window, cx);
Box::new(move |id, value, window, cx| {
let value = value
.downcast_ref()
.expect("registered inspector state type");
renderer(id, value, window, cx).into_any_element()
})
}),
);
}
}
type InspectorElementRenderer =
Box<dyn FnMut(InspectorElementId, &dyn Any, &mut Window, &mut App) -> AnyElement>;
}
/// Runtime descriptions of trait methods, generated by `#[derive_inspector_reflection]`.
///
/// Available only with the `inspector` feature or in debug builds.
#[cfg(any(feature = "inspector", debug_assertions))]
pub mod inspector_reflection {
use std::any::Any;
/// A method with the signature `fn some_fn(T) -> T`, described at runtime.
///
/// Gives you the method's name and doc comment, and a way to call it. The
/// `derive_inspector_reflection` attribute on a trait generates one for each method
/// of the form `fn method(self) -> Self`, so tools can list and call those methods by
/// name.
#[derive(Clone, Copy)]
pub struct FunctionReflection<T> {
/// The method's name.
pub name: &'static str,
/// Calls the method. Takes and returns a boxed `T`.
pub function: fn(Box<dyn Any>) -> Box<dyn Any>,
/// The method's doc comment, if it has one.
pub documentation: Option<&'static str>,
/// Ties the reflection to `T`. Not used at runtime.
pub _type: std::marker::PhantomData<T>,
}
impl<T: 'static> FunctionReflection<T> {
/// Calls the method on `value` and returns its result.
///
/// # Panics
///
/// Panics if the method returns a value that isn't a `T`. Generated reflections
/// always return `T`, so this indicates a bug in the generated code.
pub fn invoke(&self, value: T) -> T {
let boxed = Box::new(value) as Box<dyn Any>;
let result = (self.function)(boxed);
*result
.downcast::<T>()
.expect("Type mismatch in reflection invoke")
}
}
}