1//! Fusion 21.1 `:GetInputList()` / `:GetAttrs()` catalog (`scripts/tool_catalog.json`), parsed
2//! once into typed [`InputDef`]s and pre-grouped [`ToolLayout`]s. Frames only read the result.
3
4use super::layout::{ToolLayout, build_layout};
5use draw::trace::Value;
6use std::collections::HashMap;
7use std::sync::OnceLock;
8
9/// The Fusion `INPID_InputControl`s the Inspector can edit.
10#[derive(Clone, Copy, Debug, PartialEq, Eq)]
11pub enum Control {
12 Slider,
13 Screw,
14 Range,
15 Color,
16 MultiButton,
17 Combo,
18 Checkbox,
19 Offset,
20 Text,
21}
22
23/// One input as Fusion registers it, before grouping into rows.
24#[derive(Clone, Debug)]
25pub struct InputDef {
26 pub id: String,
27 pub name: String,
28 pub control: Control,
29 /// The value is a `FuID`/text string rather than a number.
30 pub fuid: bool,
31 /// `Number` default in `[0]`; `Point` default `[x, y]`.
32 pub default: [f64; 2],
33 pub default_text: String,
34 /// `INP_MinScale`/`INP_MaxScale`: the range a slider spans.
35 pub scale: [f64; 2],
36 /// `INP_MinAllowed`/`INP_MaxAllowed`: the hard clamp for typed values.
37 pub allowed: [Option<f64>; 2],
38 pub integer: bool,
39 pub page: Option<String>,
40 pub entries: Vec<String>,
41 /// `(IC_ControlGroup, IC_ControlID)` binding sibling inputs into one control.
42 pub group: Option<(i64, u32)>,
43}
44
45impl InputDef {
46 pub fn new(id: &str, name: &str, control: Control) -> Self {
47 Self {
48 id: id.to_owned(),
49 name: name.to_owned(),
50 control,
51 fuid: false,
52 default: [0.0; 2],
53 default_text: String::new(),
54 scale: [0.0, 1.0],
55 allowed: [None; 2],
56 integer: false,
57 page: None,
58 entries: Vec::new(),
59 group: None,
60 }
61 }
62}
63
64pub struct ToolCatalogEntry {
65 pub layout: ToolLayout,
66}
67
68static CATALOG: OnceLock<HashMap<String, ToolCatalogEntry>> = OnceLock::new();
69
70/// The parsed catalog, once a worker has built it; frames use this so they never parse.
71pub fn ready() -> Option<&'static HashMap<String, ToolCatalogEntry>> {
72 CATALOG.get()
73}
74
75/// Builds the catalog on first use. Call from a worker thread, never inside a frame.
76pub fn catalog() -> &'static HashMap<String, ToolCatalogEntry> {
77 CATALOG.get_or_init(|| {
78 let root: Value = include_str!("../../../../scripts/tool_catalog.json")
79 .parse()
80 .expect("scripts/tool_catalog.json is valid JSON");
81 let tools = root["tools"].as_object().expect("catalog has a `tools` object");
82 tools
83 .iter()
84 .map(|(kind, tool)| {
85 let raw = tool["inputs"].as_array().map_or(&[][..], Vec::as_slice);
86 let all_ids = raw.iter().filter_map(|i| i["id"].as_str()).map(str::to_owned).collect();
87 let inputs = raw.iter().filter_map(parse_input).collect();
88 (kind.clone(), ToolCatalogEntry { layout: build_layout(kind, inputs, all_ids) })
89 })
90 .collect()
91 })
92}
93
94fn parse_input(v: &Value) -> Option<InputDef> {
95 let id = v["id"].as_str()?;
96 let data_type = v["data_type"].as_str()?;
97 let fuid = matches!(data_type, "FuID" | "Text");
98 let entries: Vec<String> = v["combo_entries"]
99 .as_array()
100 .map(|a| a.iter().filter_map(|e| e.as_str().map(str::to_owned)).collect())
101 .unwrap_or_default();
102 let control = control_for(v["input_control"].as_str()?, data_type, !entries.is_empty())?;
103 let num = |key: &str| v[key].as_f64();
104 let scale = sanitize_scale(num("min_scale"), num("max_scale"));
105 let allowed = sanitize_allowed(num("min_allowed"), num("max_allowed"));
106 let default = match &v["default"] {
107 Value::Array(a) => [
108 finite_or(a.first().and_then(Value::as_f64), 0.5),
109 finite_or(a.get(1).and_then(Value::as_f64), 0.5),
110 ],
111 d => [finite_or(d.as_f64(), 0.0), 0.0],
112 };
113 let name = v["name"].as_str().map_or_else(|| humanize(id), str::to_owned);
114 Some(InputDef {
115 fuid,
116 default,
117 default_text: v["default"].as_str().unwrap_or_default().to_owned(),
118 scale,
119 allowed,
120 integer: v["integer"].as_bool().unwrap_or(false),
121 page: v["page"].as_str().map(str::to_owned),
122 entries,
123 group: v["control_group"].as_i64().map(|g| (g, v["control_id"].as_u64().unwrap_or(0) as u32)),
124 ..InputDef::new(id, &name, control)
125 })
126}
127
128pub(super) fn finite_or(v: Option<f64>, fallback: f64) -> f64 {
129 v.filter(|n| n.is_finite()).unwrap_or(fallback)
130}
131
132pub(super) fn sanitize_scale(min: Option<f64>, max: Option<f64>) -> [f64; 2] {
133 let lo = finite_or(min, 0.0);
134 let hi = finite_or(max, lo + 1.0);
135 if !lo.is_finite() || !hi.is_finite() {
136 return [0.0, 1.0];
137 }
138 if hi <= lo {
139 let next = lo + 1.0;
140 if next.is_finite() && next > lo { [lo, next] } else { [0.0, 1.0] }
141 } else {
142 [lo, hi]
143 }
144}
145
146pub(super) fn sanitize_allowed(min: Option<f64>, max: Option<f64>) -> [Option<f64>; 2] {
147 let lo = min.filter(|v| v.is_finite());
148 let hi = max.filter(|v| v.is_finite());
149 match (lo, hi) {
150 (Some(a), Some(b)) if a > b => [Some(b), Some(a)],
151 other => [other.0, other.1],
152 }
153}
154
155/// Maps a Fusion control to an editable one; `None` hides inputs with no editor (images, masks, curves).
156pub(super) fn control_for(name: &str, data_type: &str, has_entries: bool) -> Option<Control> {
157 match (name, data_type) {
158 ("OffsetControl", "Point") => Some(Control::Offset),
159 ("TextEditControl" | "FileControl" | "FontFileControl", "Text" | "FuID") => Some(Control::Text),
160 ("ComboControl" | "ComboIDControl", "Number" | "FuID") if has_entries => Some(Control::Combo),
161 ("MultiButtonControl" | "MultiButtonIDControl", "Number" | "FuID") if has_entries => Some(Control::MultiButton),
162 ("CheckboxControl", "Number") => Some(Control::Checkbox),
163 ("ColorControl", "Number") => Some(Control::Color),
164 ("RangeControl", "Number") => Some(Control::Range),
165 ("ScrewControl", "Number") => Some(Control::Screw),
166 (_, "Number") => Some(Control::Slider),
167 _ => None,
168 }
169}
170
171/// `ShutterAngle` -> `Shutter Angle`; dotted ids read as their last two segments.
172pub fn humanize(id: &str) -> String {
173 let segments: Vec<&str> = id.split('.').collect();
174 let tail = &segments[segments.len().saturating_sub(2)..];
175 let mut out = String::new();
176 for seg in tail {
177 let mut prev: Option<char> = None;
178 for c in seg.chars() {
179 let boundary = prev.is_some_and(|p| {
180 (p.is_lowercase() && c.is_uppercase()) || (p.is_alphabetic() && c.is_ascii_digit())
181 });
182 if (boundary || prev.is_none()) && !out.is_empty() {
183 out.push(' ');
184 }
185 out.push(c);
186 prev = Some(c);
187 }
188 }
189 out
190}
191
192#[cfg(test)]
193mod tests {
194 use super::*;
195
196 #[test]
197 fn parses_every_tool() {
198 let cat = catalog();
199 assert!(cat.len() > 100, "only {} tools", cat.len());
200 assert!(cat.values().any(|t| !t.layout.pages.is_empty()));
201 }
202
203 #[test]
204 fn humanizes_ids() {
205 assert_eq!(humanize("ShutterAngle"), "Shutter Angle");
206 assert_eq!(humanize("Red1"), "Red 1");
207 assert_eq!(humanize("Transform3DOp.Translate.X"), "Translate X");
208 }
209}