1//! Inspector dock pane: a declarative, catalog-driven Fusion 21.1 parameter editor. Pages, groups
2//! and control kinds come from `scripts/tool_catalog.json`; rows are built from the Knife `ui`
3//! sliders, screws, range sliders, color pickers and segmented controls.
4
5mod catalog;
6mod chrome;
7mod controls;
8mod dynamic;
9mod edit;
10mod layout;
11mod schemas;
12mod widgets;
13
14#[cfg(test)]
15pub use schemas::CURATED_TOOL_KINDS;
16pub use widgets::{KeyframeState, keyframe_state};
17
18use engine::EvalStats;
19use layout::{Page, ToolLayout};
20use model::{Comp, CompHistory, ExprEngine, NodeId};
21use std::collections::HashMap;
22use std::time::Duration;
23
24#[derive(Clone, Debug)]
25pub enum InspectorAction {
26 /// A parameter or node property changed; bust subtree & re-render viewers.
27 ParamEdited(NodeId),
28 /// A keyframe was added or deleted; refresh spline editor + bust subtree.
29 KeyframeEdited(NodeId),
30 /// Node was renamed.
31 NodeRenamed(NodeId),
32 /// Status notice to show in window title.
33 StatusNotice(String),
34}
35
36#[derive(Clone, Copy, Debug)]
37pub struct InspectorPalette {
38 pub bg: [f32; 4],
39 pub panel_bg: [f32; 4],
40 pub rule: [f32; 4],
41 pub text: [f32; 4],
42 pub text_dim: [f32; 4],
43 pub accent: [f32; 4],
44}
45
46impl InspectorPalette {
47 pub fn from_theme(theme: &ui::Theme) -> Self {
48 let b = theme.base;
49 let lift = |c: [f32; 4], d: f32| {
50 [
51 (c[0] + d).clamp(0.0, 1.0),
52 (c[1] + d).clamp(0.0, 1.0),
53 (c[2] + d).clamp(0.0, 1.0),
54 1.0,
55 ]
56 };
57 Self {
58 bg: b,
59 panel_bg: lift(b, 0.020),
60 rule: theme.rule,
61 text: theme.text,
62 text_dim: theme.text_dim,
63 accent: theme.accent,
64 }
65 }
66}
67
68/// Pages for the selected node's own `UserControls` and stray inputs, rebuilt when the node's
69/// shape (see [`pages_key`]) changes rather than on every value edit.
70struct NodePages {
71 node: NodeId,
72 key: u64,
73 pages: Vec<Page>,
74}
75
76pub struct InspectorState {
77 pub palette: InspectorPalette,
78 expr: ExprEngine,
79 rename: chrome::Rename,
80 edit: edit::EditState,
81 /// Active page tab per node.
82 page: HashMap<usize, usize>,
83 /// Section open/closed overrides per `(node, page, section)`.
84 sections: HashMap<(usize, usize, usize), bool>,
85 node_pages: Option<NodePages>,
86 /// Layouts of tools the catalog lacks, built from curated schemas on first sight.
87 fallback: HashMap<String, ToolLayout>,
88}
89
90impl InspectorState {
91 pub fn new(theme: &ui::Theme) -> Self {
92 // Parse the catalog off the UI thread; frames wait on it with a placeholder.
93 if catalog::ready().is_none() {
94 std::thread::spawn(|| {
95 catalog::catalog();
96 });
97 }
98 Self {
99 palette: InspectorPalette::from_theme(theme),
100 expr: ExprEngine::new(),
101 rename: chrome::Rename::default(),
102 edit: edit::EditState::default(),
103 page: HashMap::new(),
104 sections: HashMap::new(),
105 node_pages: None,
106 fallback: HashMap::new(),
107 }
108 }
109
110 pub fn background(&self) -> [f32; 4] {
111 self.palette.bg
112 }
113
114 pub fn reset(&mut self) {
115 self.rename = chrome::Rename::default();
116 self.edit = edit::EditState::default();
117 self.node_pages = None;
118 }
119
120 pub fn build_ui(
121 &mut self,
122 ui: &mut ui::Ui,
123 pane_id: ui::Id,
124 comp: &mut Comp,
125 history: &mut CompHistory,
126 selected: Option<NodeId>,
127 current_frame: f64,
128 stats: &EvalStats,
129 ) -> Vec<InspectorAction> {
130 let mut actions = Vec::new();
131 let p = self.palette;
132
133 ui.open_as(
134 pane_id,
135 ui::Spec { size: [ui::fill(), ui::fill()], axis: ui::Axis::Y, fill: Some(p.bg), ..ui::Spec::default() },
136 );
137 let Some(node_id) = selected.filter(|id| id.0 < comp.nodes.len()) else {
138 self.commit_orphans(comp, history, &mut actions);
139 chrome::empty_state(ui, p);
140 chrome::footer(ui, p, stats);
141 ui.close();
142 return actions;
143 };
144
145 let kind = comp.node(node_id).kind.clone();
146 let Some(catalog) = catalog::ready() else {
147 ui.wake_after(Duration::from_millis(50));
148 return self.loading(ui, p, stats, actions);
149 };
150 let layout = match catalog.get(&kind) {
151 Some(entry) => &entry.layout,
152 None => self
153 .fallback
154 .entry(kind.clone())
155 .or_insert_with(|| dynamic::curated_layout(&kind).unwrap_or_default()),
156 };
157
158 let key = pages_key(comp, node_id);
159 if self.node_pages.as_ref().is_none_or(|n| n.node != node_id || n.key != key) {
160 self.node_pages = Some(NodePages { node: node_id, key, pages: node_pages(comp, node_id, layout) });
161 }
162 let dynamic_pages = self.node_pages.as_ref().map_or(&[][..], |n| n.pages.as_slice());
163
164 let mut cx = edit::Cx {
165 comp,
166 history,
167 actions: &mut actions,
168 node: node_id,
169 frame: current_frame,
170 now: ui.now(),
171 p,
172 expr: &self.expr,
173 edit: &mut self.edit,
174 };
175 settle_edits(ui, &mut cx);
176
177 let mut pages = layout.pages.iter().chain(dynamic_pages);
178 if chrome::header(ui, pane_id, &mut self.rename, &mut cx) {
179 cx.reset_defaults(pages.clone().flat_map(|page| page.sections.iter()).flat_map(|s| s.controls.iter()));
180 }
181
182 let names: Vec<&str> = pages.clone().map(|page| page.name.as_str()).collect();
183 let active = self.page.get(&node_id.0).copied().unwrap_or(0).min(names.len().saturating_sub(1));
184 if let Some(next) = chrome::tabs(ui, p, &names, active) {
185 self.page.insert(node_id.0, next);
186 }
187
188 ui.open(
189 "insp-scroll",
190 ui::Spec { flags: ui::Flags::SCROLL | ui::Flags::CLIP, size: [ui::fill(), ui::fill()], axis: ui::Axis::Y, pad: [6.0, 6.0], gap: 2.0, ..ui::Spec::default() },
191 );
192 if let Some(page) = pages.nth(active) {
193 for (i, section) in page.sections.iter().enumerate() {
194 let key = (node_id.0, active, i);
195 let open = self.sections.get(&key).copied().unwrap_or(section.open);
196 let spec = ui::CompactDisclosure { body_gap: 2.0, body_pad: [0.0, 2.0], ..ui::CompactDisclosure::new(&section.title, open) };
197 let toggled = ui::compact_disclosure_with(ui, ("sec", key), spec, |ui| {
198 for def in &section.controls {
199 controls::render(ui, &mut cx, def);
200 }
201 });
202 if toggled {
203 self.sections.insert(key, !open);
204 }
205 }
206 } else {
207 ui.leaf(
208 "insp-no-controls",
209 ui::Spec { size: [ui::fill(), ui::px(20.0)], text: Some("No editable inputs"), font_size: Some(11.0), color: Some(p.text_dim), ..ui::Spec::default() },
210 );
211 }
212 if matches!(kind.as_str(), "Loader" | "Saver") {
213 chrome::clip_summary(ui, &cx);
214 }
215 ui.close(); // insp-scroll
216
217 chrome::footer(ui, p, stats);
218 ui.close(); // pane_id
219 actions
220 }
221
222 /// With nothing selected no box can keep the keys, so a typed value lands where it was typed.
223 fn commit_orphans(&mut self, comp: &mut Comp, history: &mut CompHistory, actions: &mut Vec<InspectorAction>) {
224 self.edit.text = None;
225 let Some(number) = self.edit.number.take() else { return };
226 let mut cx = edit::Cx {
227 comp,
228 history,
229 actions,
230 node: number.node,
231 frame: 0.0,
232 now: std::time::Instant::now(),
233 p: self.palette,
234 expr: &self.expr,
235 edit: &mut self.edit,
236 };
237 cx.commit_number(number);
238 }
239
240 fn loading(&self, ui: &mut ui::Ui, p: InspectorPalette, stats: &EvalStats, actions: Vec<InspectorAction>) -> Vec<InspectorAction> {
241 ui.leaf(
242 "insp-loading",
243 ui::Spec { size: [ui::fill(), ui::fill()], pad: [14.0, 18.0], text: Some("Loading tool catalog…"), font_size: Some(11.0), color: Some(p.text_dim), ..ui::Spec::default() },
244 );
245 chrome::footer(ui, p, stats);
246 ui.close();
247 actions
248 }
249}
250
251/// Commits what loses the keys and closes a rested drag's undo step.
252fn settle_edits(ui: &mut ui::Ui, cx: &mut edit::Cx) {
253 if let Some(last) = cx.edit.last_scrub {
254 if cx.now.duration_since(last) > edit::SCRUB_GRACE {
255 cx.history.break_coalescing();
256 cx.edit.last_scrub = None;
257 } else {
258 ui.wake_after(edit::SCRUB_GRACE);
259 }
260 }
261 if let Some(number) = cx.edit.number.take_if(|n| ui.focused() != Some(n.id)) {
262 cx.commit_number(number);
263 }
264 if cx.edit.text.take_if(|(id, _)| ui.focused() != Some(*id)).is_some() {
265 cx.history.break_coalescing();
266 }
267}
268
269/// What `node_pages` reads, minus values: kind, `UserControls` ids, and each input's name,
270/// value type and whether it is driven or wired. Order-independent over the input map.
271fn pages_key(comp: &Comp, node: NodeId) -> u64 {
272 use std::hash::{Hash, Hasher};
273 let hash = |item: &dyn Fn(&mut std::hash::DefaultHasher)| {
274 let mut h = std::hash::DefaultHasher::new();
275 item(&mut h);
276 h.finish()
277 };
278 let n = comp.node(node);
279 let controls = n.raw.get_table("UserControls").map_or(0, |t| {
280 t.entries.iter().fold(t.entries.len() as u64, |acc, (key, _)| match key {
281 model::LuaKey::Str(id) => acc.wrapping_add(hash(&|h| id.hash(h))),
282 _ => acc,
283 })
284 });
285 let inputs = n.inputs.iter().fold(0u64, |acc, (key, b)| {
286 let wired = b.source_op.as_deref().is_some_and(|op| comp.node_by_name.contains_key(op));
287 acc.wrapping_add(hash(&|h| {
288 key.hash(h);
289 b.value.as_ref().map(std::mem::discriminant).hash(h);
290 (b.expression.is_some(), b.source_op.is_some(), wired).hash(h);
291 }))
292 });
293 hash(&|h| (&n.kind, controls, inputs).hash(h))
294}
295
296/// The node's `UserControls` (one page per `ICS_ControlPage`) and inputs no catalog row covers.
297fn node_pages(comp: &Comp, node: NodeId, layout: &ToolLayout) -> Vec<Page> {
298 let mut by_page: Vec<(String, Vec<catalog::InputDef>)> = Vec::new();
299 for mut def in dynamic::user_defs(&comp.node(node).raw) {
300 let name = def.page.take().unwrap_or_default();
301 let name = if layout.pages.iter().any(|p| p.name == name) { "User".to_owned() } else { name };
302 match by_page.iter_mut().find(|(n, _)| *n == name) {
303 Some((_, defs)) => defs.push(def),
304 None => by_page.push((name, vec![def])),
305 }
306 }
307 let user_ids: Vec<&str> = by_page.iter().flat_map(|(_, defs)| defs.iter().map(|d| d.id.as_str())).collect();
308 let extras = dynamic::extra_defs(comp, node, |id| layout.covered.contains(id) || user_ids.contains(&id));
309 if !extras.is_empty() {
310 by_page.push(("Other".to_owned(), extras));
311 }
312 by_page.iter().map(|(name, defs)| layout::dynamic_page(name, defs)).collect()
313}
314
315#[cfg(test)]
316mod tests;