1//! Turns a flat [`InputDef`] list into the Inspector's pages, sections and rows: sibling
2//! RGBA/range/toggle inputs fuse into one [`ControlDef`], pages follow Fusion's tab order.
3
4use super::catalog::{Control, InputDef};
5use std::collections::HashSet;
6
7#[derive(Clone, Copy, Debug, PartialEq, Eq)]
8pub enum Kind {
9 Slider,
10 Screw,
11 Range,
12 Color,
13 Toggles,
14 Segmented,
15 Combo,
16 Checkbox,
17 Point,
18 Text,
19}
20
21/// One input a row reads and writes.
22#[derive(Clone, Debug)]
23pub struct Channel {
24 pub id: String,
25 /// Number default in `[0]`; Point default `[x, y]`.
26 pub default: [f64; 2],
27 pub scale: [f64; 2],
28 pub allowed: [Option<f64>; 2],
29 pub integer: bool,
30}
31
32/// One Inspector row.
33#[derive(Clone, Debug)]
34pub struct ControlDef {
35 pub label: String,
36 pub kind: Kind,
37 /// Range: start, end. Color: r, g, b[, a]. Toggles: one per button.
38 pub channels: Vec<Channel>,
39 /// Segmented/Combo choices, or one label per toggle button.
40 pub entries: Vec<String>,
41 /// Segmented/Combo/Text values are strings; choices default to `default_index`.
42 pub fuid: bool,
43 pub default_index: usize,
44 pub default_text: String,
45}
46
47#[derive(Clone, Debug)]
48pub struct Section {
49 pub title: String,
50 pub open: bool,
51 pub controls: Vec<ControlDef>,
52}
53
54#[derive(Clone, Debug)]
55pub struct Page {
56 pub name: String,
57 pub sections: Vec<Section>,
58}
59
60#[derive(Clone, Debug, Default)]
61pub struct ToolLayout {
62 pub pages: Vec<Page>,
63 /// Every input id the tool registers, including image and mask ports with no row.
64 pub covered: HashSet<String>,
65}
66
67const SETTINGS: &str = "Settings";
68
69/// Fusion tab order where `:GetInputList()` registration order differs.
70const PAGE_ORDER: &[(&str, &[&str])] = &[
71 ("TextPlus", &["Text", "Layout", "Transform", "Shading", "Image", SETTINGS]),
72 ("Text3D", &["Text", "Layout", "Transform", "Shading", "3D", SETTINGS]),
73];
74
75/// Subsections Fusion draws inside a page, which the input list doesn't report:
76/// `(tools, first input id, title, open)`. No tools matches every tool.
77pub(super) const SECTIONS: &[(&[&str], &str, &str, bool)] = &[
78 (&["Merge", "Transform"], "Width", "Reference Size", false),
79 (&[], "MotionBlur", "Motion Blur", true),
80 (&["Text3D"], "ExtrusionStyle", "Extrusion", true),
81];
82
83const MAX_SEGMENTS: usize = 5;
84const MAX_SEGMENT_CHARS: usize = 18;
85
86pub fn build_layout(kind: &str, defs: Vec<InputDef>, covered: HashSet<String>) -> ToolLayout {
87 let mut pages: Vec<(String, Vec<InputDef>)> = Vec::new();
88 for def in defs {
89 let name = match def.page.as_deref() {
90 None | Some("Common") => SETTINGS,
91 Some(page) => page,
92 };
93 match pages.iter_mut().find(|(n, _)| n == name) {
94 Some((_, list)) => list.push(def),
95 None => pages.push((name.to_owned(), vec![def])),
96 }
97 }
98 let order = PAGE_ORDER.iter().find(|(k, _)| *k == kind).map(|(_, o)| *o);
99 let rank = |name: &str| match order {
100 Some(order) => order.iter().position(|o| *o == name),
101 None => Some(match name {
102 SETTINGS => 2,
103 "Image" => 1,
104 _ => 0,
105 }),
106 };
107 pages.sort_by_key(|(name, _)| rank(name).unwrap_or(usize::MAX));
108
109 let pages = pages
110 .into_iter()
111 .map(|(name, defs)| {
112 let title = if name == SETTINGS { "Common Controls" } else { &name };
113 Page { sections: sections(kind, title, controls(&defs)), name }
114 })
115 .collect();
116 ToolLayout { pages, covered }
117}
118
119/// A single-section page for controls that are not in the catalog (user controls, stray inputs).
120pub fn dynamic_page(name: &str, defs: &[InputDef]) -> Page {
121 Page { name: name.to_owned(), sections: sections("", name, controls(defs)) }
122}
123
124fn sections(kind: &str, first_title: &str, controls: Vec<ControlDef>) -> Vec<Section> {
125 let mut out = vec![Section { title: first_title.to_owned(), open: true, controls: Vec::new() }];
126 for control in controls {
127 let marker = SECTIONS.iter().find(|(tools, id, ..)| {
128 (tools.is_empty() || tools.contains(&kind)) && control.channels.first().is_some_and(|c| c.id == *id)
129 });
130 if let Some(&(_, _, title, open)) = marker {
131 out.push(Section { title: title.to_owned(), open, controls: Vec::new() });
132 }
133 out.last_mut().expect("starts non-empty").controls.push(control);
134 }
135 out.retain(|s| !s.controls.is_empty());
136 out
137}
138
139/// How many defs from `i` form one group: same control and `IC_ControlGroup`, ascending `IC_ControlID`.
140fn group_len(defs: &[InputDef], i: usize) -> usize {
141 let head = &defs[i];
142 let Some((group, first)) = head.group else { return 1 };
143 let Some(next) = first.checked_add(1) else { return 1 };
144 1 + defs[i + 1..]
145 .iter()
146 .zip(next..)
147 .take_while(|(d, id)| d.control == head.control && d.group == Some((group, *id)))
148 .count()
149}
150
151fn controls(defs: &[InputDef]) -> Vec<ControlDef> {
152 let mut out = Vec::new();
153 let mut i = 0;
154 while i < defs.len() {
155 let head = &defs[i];
156 let run = group_len(defs, i);
157 let starts_group = head.group.is_some_and(|(_, id)| id == 0);
158 let take = match head.control {
159 Control::Color if run >= 3 && starts_group => run.min(4),
160 Control::Range if run >= 2 && starts_group => 2,
161 Control::MultiButton if head.entries.len() == 1 => run,
162 _ => 1,
163 };
164 out.push(control(&defs[i..i + take]));
165 i += take;
166 }
167 out
168}
169
170fn channel(d: &InputDef) -> Channel {
171 Channel { id: d.id.clone(), default: d.default, scale: d.scale, allowed: d.allowed, integer: d.integer }
172}
173
174fn control(group: &[InputDef]) -> ControlDef {
175 let d = &group[0];
176 let (kind, label, entries) = match d.control {
177 Control::Color if group.len() >= 3 => (Kind::Color, color_label(&d.name), Vec::new()),
178 Control::Range if group.len() == 2 => (Kind::Range, range_label(&group[0].name, &group[1].name), Vec::new()),
179 Control::MultiButton if d.entries.len() == 1 => {
180 let names: Vec<&str> = group.iter().map(|g| g.name.as_str()).collect();
181 (Kind::Toggles, common_prefix(&names).unwrap_or_else(|| if group.len() > 1 { "Channels".to_owned() } else { d.name.clone() }), group.iter().map(|g| g.entries[0].clone()).collect())
182 }
183 Control::MultiButton | Control::Combo => {
184 let chars: usize = d.entries.iter().map(String::len).sum();
185 let segmented = d.control == Control::MultiButton && d.entries.len() <= MAX_SEGMENTS && chars <= MAX_SEGMENT_CHARS;
186 (if segmented { Kind::Segmented } else { Kind::Combo }, d.name.clone(), d.entries.clone())
187 }
188 Control::Screw => (Kind::Screw, d.name.clone(), Vec::new()),
189 Control::Checkbox => (Kind::Checkbox, d.name.clone(), Vec::new()),
190 Control::Offset => (Kind::Point, d.name.clone(), Vec::new()),
191 Control::Text => (Kind::Text, d.name.clone(), Vec::new()),
192 Control::Slider | Control::Color | Control::Range => (Kind::Slider, d.name.clone(), Vec::new()),
193 };
194 let default_index = if d.fuid {
195 entries.iter().position(|e| *e == d.default_text).unwrap_or(0)
196 } else {
197 (d.default[0].max(0.0) as usize).min(entries.len().saturating_sub(1))
198 };
199 ControlDef {
200 label,
201 kind,
202 channels: group.iter().map(channel).collect(),
203 entries,
204 fuid: d.fuid,
205 default_index,
206 default_text: d.default_text.clone(),
207 }
208}
209
210/// `Top Left Red` -> `Top Left`; a bare channel name is just `Color`.
211fn color_label(first: &str) -> String {
212 let rest: Vec<&str> = first.split_whitespace().filter(|w| *w != "Red").collect();
213 match rest.first() {
214 None => "Color".to_owned(),
215 Some(w) if w.starts_with(|c: char| c.is_ascii_digit()) => format!("Color {}", rest.join(" ")),
216 Some(_) => rest.join(" "),
217 }
218}
219
220/// `Write On Start`, `Write On End` -> `Write On Start / End`; `Low`, `High` -> `Low / High`.
221fn range_label(start: &str, end: &str) -> String {
222 let (a, b): (Vec<&str>, Vec<&str>) = (start.split_whitespace().collect(), end.split_whitespace().collect());
223 let shared = a.iter().zip(&b).take_while(|(x, y)| x == y).count();
224 if shared == 0 || shared == a.len().min(b.len()) {
225 return format!("{start} / {end}");
226 }
227 format!("{} / {}", start, b[shared..].join(" "))
228}
229
230/// The words every name starts with, or `None` when they share none.
231fn common_prefix(names: &[&str]) -> Option<String> {
232 let first: Vec<&str> = names.first()?.split_whitespace().collect();
233 let shared = names
234 .iter()
235 .map(|n| n.split_whitespace().zip(&first).take_while(|(a, b)| a == *b).count())
236 .min()?;
237 (shared > 0).then(|| first[..shared].join(" "))
238}
239
240#[cfg(test)]
241mod tests {
242 use super::*;
243
244 #[test]
245 fn labels() {
246 assert_eq!(color_label("Top Left Red"), "Top Left");
247 assert_eq!(color_label("Red 1"), "Color 1");
248 assert_eq!(color_label("Red"), "Color");
249 assert_eq!(range_label("Write On Start", "Write On End"), "Write On Start / End");
250 assert_eq!(range_label("Low", "High"), "Low / High");
251 assert_eq!(common_prefix(&["Process Red", "Process Green"]).as_deref(), Some("Process"));
252 assert_eq!(common_prefix(&["Flip Horizontal", "Flip Vertical"]).as_deref(), Some("Flip"));
253 assert_eq!(common_prefix(&["Red", "Green"]), None);
254 }
255}