From ff950de2d8df46a71fe6ad45cbb5b20c133047e2 Mon Sep 17 00:00:00 2001 From: clover caruso Date: Tue, 1 Dec 2026 03:57:41 -0800 Subject: [PATCH] inspector: catalog-driven Fusion control inspector on Knife ui primitives Pages, groups and control kinds come from scripts/tool_catalog.json (parsed once off-thread into a OnceLock). RGBA/range/toggle inputs fuse into one row; rows use Slider, ScrewControl, RangeSlider, ColorPicker, SegmentedControl and CompactDisclosure. Co-Authored-By: Claude Sonnet 5.5 --- crates/app/src/inspector/catalog.rs | 181 ++++++++ crates/app/src/inspector/chrome.rs | 271 +++++++++++ crates/app/src/inspector/controls.rs | 372 +++++++++++++++ crates/app/src/inspector/dynamic.rs | 156 +++++++ crates/app/src/inspector/edit.rs | 178 ++++++++ crates/app/src/inspector/layout.rs | 254 +++++++++++ crates/app/src/inspector/mod.rs | 650 ++++++--------------------- crates/app/src/inspector/rows.rs | 591 ------------------------ crates/app/src/inspector/schemas.rs | 33 +- crates/app/src/inspector/tests.rs | 442 ++++++++++++++++++ crates/app/src/inspector/widgets.rs | 564 +++-------------------- 11 files changed, 2063 insertions(+), 1629 deletions(-) create mode 100644 crates/app/src/inspector/catalog.rs create mode 100644 crates/app/src/inspector/chrome.rs create mode 100644 crates/app/src/inspector/controls.rs create mode 100644 crates/app/src/inspector/dynamic.rs create mode 100644 crates/app/src/inspector/edit.rs create mode 100644 crates/app/src/inspector/layout.rs delete mode 100644 crates/app/src/inspector/rows.rs create mode 100644 crates/app/src/inspector/tests.rs diff --git a/crates/app/src/inspector/catalog.rs b/crates/app/src/inspector/catalog.rs new file mode 100644 index 0000000000000000000000000000000000000000..bec2c36deaff10593b6fff1461b94ffce84df514 --- /dev/null +++ b/crates/app/src/inspector/catalog.rs @@ -0,0 +1,181 @@ +//! Fusion 21.1 `:GetInputList()` / `:GetAttrs()` catalog (`scripts/tool_catalog.json`), parsed +//! once into typed [`InputDef`]s and pre-grouped [`ToolLayout`]s. Frames only read the result. + +use super::layout::{ToolLayout, build_layout}; +use draw::trace::Value; +use std::collections::HashMap; +use std::sync::OnceLock; + +/// The Fusion `INPID_InputControl`s the Inspector can edit. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Control { + Slider, + Screw, + Range, + Color, + MultiButton, + Combo, + Checkbox, + Offset, + Text, +} + +/// One input as Fusion registers it, before grouping into rows. +#[derive(Clone, Debug)] +pub struct InputDef { + pub id: String, + pub name: String, + pub control: Control, + /// The value is a `FuID`/text string rather than a number. + pub fuid: bool, + /// `Number` default in `[0]`; `Point` default `[x, y]`. + pub default: [f64; 2], + pub default_text: String, + /// `INP_MinScale`/`INP_MaxScale`: the range a slider spans. + pub scale: [f64; 2], + /// `INP_MinAllowed`/`INP_MaxAllowed`: the hard clamp for typed values. + pub allowed: [Option; 2], + pub integer: bool, + pub page: Option, + pub entries: Vec, + /// `(IC_ControlGroup, IC_ControlID)` binding sibling inputs into one control. + pub group: Option<(i64, u32)>, +} + +impl InputDef { + pub fn new(id: &str, name: &str, control: Control) -> Self { + Self { + id: id.to_owned(), + name: name.to_owned(), + control, + fuid: false, + default: [0.0; 2], + default_text: String::new(), + scale: [0.0, 1.0], + allowed: [None; 2], + integer: false, + page: None, + entries: Vec::new(), + group: None, + } + } +} + +pub struct ToolCatalogEntry { + pub layout: ToolLayout, +} + +static CATALOG: OnceLock> = OnceLock::new(); + +/// The parsed catalog, once a worker has built it; frames use this so they never parse. +pub fn ready() -> Option<&'static HashMap> { + CATALOG.get() +} + +/// Builds the catalog on first use. Call from a worker thread, never inside a frame. +pub fn catalog() -> &'static HashMap { + CATALOG.get_or_init(|| { + let root: Value = include_str!("../../../../scripts/tool_catalog.json") + .parse() + .expect("scripts/tool_catalog.json is valid JSON"); + let tools = root["tools"].as_object().expect("catalog has a `tools` object"); + tools + .iter() + .map(|(kind, tool)| { + let raw = tool["inputs"].as_array().map_or(&[][..], Vec::as_slice); + let all_ids = raw.iter().filter_map(|i| i["id"].as_str()).map(str::to_owned).collect(); + let inputs = raw.iter().filter_map(parse_input).collect(); + (kind.clone(), ToolCatalogEntry { layout: build_layout(kind, inputs, all_ids) }) + }) + .collect() + }) +} + +fn parse_input(v: &Value) -> Option { + let id = v["id"].as_str()?; + let data_type = v["data_type"].as_str()?; + let fuid = matches!(data_type, "FuID" | "Text"); + let entries: Vec = v["combo_entries"] + .as_array() + .map(|a| a.iter().filter_map(|e| e.as_str().map(str::to_owned)).collect()) + .unwrap_or_default(); + let control = control_for(v["input_control"].as_str()?, data_type, !entries.is_empty())?; + let num = |key: &str| v[key].as_f64(); + let mut scale = [num("min_scale").unwrap_or(0.0), num("max_scale").unwrap_or(1.0)]; + if scale[1] <= scale[0] { + scale[1] = scale[0] + 1.0; + } + let default = match &v["default"] { + Value::Array(a) => [a.first().and_then(Value::as_f64).unwrap_or(0.5), a.get(1).and_then(Value::as_f64).unwrap_or(0.5)], + d => [d.as_f64().unwrap_or(0.0), 0.0], + }; + let name = v["name"].as_str().map_or_else(|| humanize(id), str::to_owned); + Some(InputDef { + fuid, + default, + default_text: v["default"].as_str().unwrap_or_default().to_owned(), + scale, + allowed: [num("min_allowed"), num("max_allowed")], + integer: v["integer"].as_bool().unwrap_or(false), + page: v["page"].as_str().map(str::to_owned), + entries, + group: v["control_group"].as_i64().map(|g| (g, v["control_id"].as_u64().unwrap_or(0) as u32)), + ..InputDef::new(id, &name, control) + }) +} + +/// Maps a Fusion control to an editable one; `None` hides inputs with no editor (images, masks, curves). +pub(super) fn control_for(name: &str, data_type: &str, has_entries: bool) -> Option { + match (name, data_type) { + ("OffsetControl", "Point") => Some(Control::Offset), + ("TextEditControl" | "FileControl" | "FontFileControl", "Text" | "FuID") => Some(Control::Text), + ("ComboControl" | "ComboIDControl", "Number" | "FuID") if has_entries => Some(Control::Combo), + ("MultiButtonControl" | "MultiButtonIDControl", "Number" | "FuID") if has_entries => Some(Control::MultiButton), + ("CheckboxControl", "Number") => Some(Control::Checkbox), + ("ColorControl", "Number") => Some(Control::Color), + ("RangeControl", "Number") => Some(Control::Range), + ("ScrewControl", "Number") => Some(Control::Screw), + (_, "Number") => Some(Control::Slider), + _ => None, + } +} + +/// `ShutterAngle` -> `Shutter Angle`; dotted ids read as their last two segments. +pub fn humanize(id: &str) -> String { + let segments: Vec<&str> = id.split('.').collect(); + let tail = &segments[segments.len().saturating_sub(2)..]; + let mut out = String::new(); + for seg in tail { + let mut prev: Option = None; + for c in seg.chars() { + let boundary = prev.is_some_and(|p| { + (p.is_lowercase() && c.is_uppercase()) || (p.is_alphabetic() && c.is_ascii_digit()) + }); + if (boundary || prev.is_none()) && !out.is_empty() { + out.push(' '); + } + out.push(c); + prev = Some(c); + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_every_tool() { + let cat = catalog(); + assert!(cat.len() > 100, "only {} tools", cat.len()); + assert!(cat.values().any(|t| !t.layout.pages.is_empty())); + } + + #[test] + fn humanizes_ids() { + assert_eq!(humanize("ShutterAngle"), "Shutter Angle"); + assert_eq!(humanize("Red1"), "Red 1"); + assert_eq!(humanize("Transform3DOp.Translate.X"), "Translate X"); + } +} diff --git a/crates/app/src/inspector/chrome.rs b/crates/app/src/inspector/chrome.rs new file mode 100644 index 0000000000000000000000000000000000000000..b7c92668860bf704cf25ad177271a20caf2a22b1 --- /dev/null +++ b/crates/app/src/inspector/chrome.rs @@ -0,0 +1,271 @@ +//! The Inspector's frame: header (bypass, name, reset), page tabs, clip summary, stats footer. + +use super::edit::Cx; +use super::{InspectorAction, InspectorPalette}; +use engine::EvalStats; +use model::is_supported_tool; +use ui::{Spec, Ui, fill, fit, px}; +use winit::keyboard::{Key, NamedKey}; + +/// The node-name edit buffer, synced with the selected node. +#[derive(Default)] +pub(super) struct Rename { + pub node: Option, + pub buf: String, +} + +pub(super) fn empty_state(ui: &mut Ui, p: InspectorPalette) { + ui.open( + "insp-empty", + Spec { size: [fill(), fill()], axis: ui::Axis::Y, pad: [14.0, 18.0], gap: 8.0, ..Spec::default() }, + ); + ui.leaf( + "empty-title", + Spec { size: [fill(), px(20.0)], text: Some("No Node Selected"), font_size: Some(12.5), medium: true, color: Some(p.text), ..Spec::default() }, + ); + ui.leaf( + "empty-hint", + Spec { + size: [fill(), fit()], + text: Some("Select a node in the Flow graph to inspect and keyframe its parameters, or press Shift+Space to add a tool."), + font_size: Some(11.0), + overflow: ui::Overflow::Wrap, + color: Some(p.text_dim), + ..Spec::default() + }, + ); + ui.close(); +} + +/// Bypass pill, name field and reset action; below them the tool badge and frame number. +/// Returns whether reset-to-defaults was clicked. +pub(super) fn header(ui: &mut Ui, pane_id: ui::Id, rename: &mut Rename, cx: &mut Cx) -> bool { + let p = cx.p; + let node_id = cx.node; + let current_name = cx.comp.node(node_id).name.clone(); + let name_field = pane_id.child(("node-name", node_id.0)); + if rename.node != Some(node_id) || (ui.focused() != Some(name_field) && rename.buf != current_name) { + rename.node = Some(node_id); + rename.buf = current_name.clone(); + } + + ui.open( + "insp-header", + Spec { size: [fill(), ui::children()], axis: ui::Axis::Y, pad: [10.0, 8.0], gap: 6.0, fill: Some(p.panel_bg), border: Some(p.rule), ..Spec::default() }, + ); + ui.open("insp-name-row", Spec { size: [fill(), px(26.0)], axis: ui::Axis::X, gap: 6.0, ..Spec::default() }); + + let bypassed = cx.comp.node(node_id).bypassed; + let (fill_c, border_c) = if bypassed { + ([0.85, 0.28, 0.28, 0.28], [0.92, 0.36, 0.36, 0.75]) + } else { + ([0.24, 0.78, 0.48, 0.18], [0.28, 0.82, 0.52, 0.55]) + }; + let pill = ui.leaf( + ("insp-pass", node_id.0), + Spec { + cursor: Some(winit::window::CursorIcon::Pointer), + flags: ui::Flags::CLICKABLE, + size: [px(64.0), px(24.0)], + text: Some(if bypassed { "Bypassed" } else { "Active" }), + font_size: Some(10.5), + medium: true, + color: Some(p.text), + fill: Some(fill_c), + border: Some(border_c), + radius: 12.0, + center: true, + ..Spec::default() + }, + ); + if pill.clicked { + cx.history.push_snapshot(cx.comp, "Toggle Passthrough"); + cx.comp.toggle_passthrough(node_id); + cx.actions.push(InspectorAction::ParamEdited(node_id)); + } + + let name_sig = ui::text_field( + ui, + name_field, + &mut rename.buf, + "Node name", + Spec { + size: [fill(), px(24.0)], + font_size: Some(12.0), + medium: true, + fill: Some(p.bg), + border: Some(p.rule), + hover_border: Some(p.accent), + radius: 4.0, + pad: [6.0, 2.0], + ..Spec::default() + }, + ); + let entered = name_sig + .events + .iter() + .any(|ev| matches!(ev, ui::Event::Key { key: Key::Named(NamedKey::Enter), .. })); + if entered && rename.buf.trim() != current_name { + let desired = rename.buf.trim().to_owned(); + cx.history.begin_group(cx.comp, "Rename Node"); + match cx.comp.rename_node(node_id, &desired) { + Ok(applied) => { + cx.history.commit_group(cx.comp); + rename.buf = applied; + cx.actions.push(InspectorAction::NodeRenamed(node_id)); + } + Err(e) => { + cx.history.cancel_group(cx.comp); + rename.buf = current_name; + cx.actions.push(InspectorAction::StatusNotice(e)); + } + } + ui.set_focus(None); + } + + let reset = ui + .leaf( + ("insp-reset", node_id.0), + Spec { + cursor: Some(winit::window::CursorIcon::Pointer), + flags: ui::Flags::CLICKABLE, + size: [px(24.0), px(24.0)], + text: Some("↺"), + font_size: Some(13.0), + color: Some(p.text_dim), + hover_fill: Some(p.bg), + radius: 4.0, + center: true, + ..Spec::default() + }, + ) + .clicked; + ui.close(); + + let kind = cx.comp.node(node_id).kind.as_str(); + ui.open("insp-meta-row", Spec { size: [fill(), px(18.0)], axis: ui::Axis::X, gap: 6.0, ..Spec::default() }); + ui.leaf( + "insp-kind-badge", + Spec { + size: [fit(), px(18.0)], + text: Some(kind), + font_size: Some(10.0), + medium: true, + color: Some(p.accent), + fill: Some([p.accent[0], p.accent[1], p.accent[2], 0.14]), + border: Some([p.accent[0], p.accent[1], p.accent[2], 0.40]), + radius: 3.0, + pad: [6.0, 0.0], + center: true, + ..Spec::default() + }, + ); + if !is_supported_tool(kind) { + ui.leaf( + "insp-preserved-badge", + Spec { + size: [fit(), px(18.0)], + text: Some("preserved"), + font_size: Some(9.5), + medium: true, + color: Some([0.98, 0.78, 0.40, 1.0]), + fill: Some([0.24, 0.16, 0.06, 0.85]), + border: Some([0.92, 0.64, 0.24, 0.60]), + radius: 3.0, + pad: [5.0, 0.0], + center: true, + ..Spec::default() + }, + ); + } + ui.leaf("insp-spacer", Spec { size: [fill(), px(18.0)], ..Spec::default() }); + ui.leaf( + "insp-frame", + Spec { size: [fit(), px(18.0)], text: Some(&format!("f{:.0}", cx.frame)), font_size: Some(10.0), color: Some(p.text_dim), center: true, ..Spec::default() }, + ); + ui.close(); + ui.close(); + reset +} + +/// Underlined page tabs; returns the tab clicked. +pub(super) fn tabs(ui: &mut Ui, p: InspectorPalette, names: &[&str], active: usize) -> Option { + ui.open( + "insp-tabs", + Spec { size: [fill(), px(28.0)], axis: ui::Axis::X, flags: ui::Flags::CLIP, pad: [6.0, 0.0], border: Some(p.rule), ..Spec::default() }, + ); + let mut clicked = None; + for (i, name) in names.iter().enumerate() { + let on = i == active; + ui.open(("tab", i), Spec { size: [ui::children(), fill()], axis: ui::Axis::Y, ..Spec::default() }); + let signal = ui.leaf( + "label", + Spec { + cursor: Some(winit::window::CursorIcon::Pointer), + flags: ui::Flags::CLICKABLE, + size: [fit(), fill()], + text: Some(name), + font_size: Some(11.0), + medium: on, + color: Some(if on { p.text } else { p.text_dim }), + hover_fill: Some(p.panel_bg), + pad: [8.0, 0.0], + center: true, + ..Spec::default() + }, + ); + ui.leaf("rule", Spec { size: [fill(), px(2.0)], fill: on.then_some(p.accent), ..Spec::default() }); + ui.close(); + if signal.clicked { + clicked = Some(i); + } + } + ui.close(); + clicked +} + +/// The Loader/Saver's first clip path. +pub(super) fn clip_summary(ui: &mut Ui, cx: &Cx) { + let node = cx.comp.node(cx.node); + let heading = if node.kind == "Saver" { "Output Filename" } else { "Clip Filename" }; + let path = node + .clips + .first() + .map(|c| c.filename.as_str()) + .or_else(|| { + node.raw + .get_table("Inputs")? + .get_table("Clip")? + .get_table("Value")? + .get_str("Filename") + }) + .unwrap_or("(no clip)"); + let p = cx.p; + ui.open( + "insp-loader-clip", + Spec { size: [fill(), ui::children()], axis: ui::Axis::Y, gap: 3.0, pad: [6.0, 5.0], fill: Some(p.panel_bg), border: Some(p.rule), radius: 4.0, ..Spec::default() }, + ); + ui.leaf("clip-lbl", Spec { size: [fill(), px(14.0)], text: Some(heading), font_size: Some(10.0), color: Some(p.text_dim), ..Spec::default() }); + ui.leaf( + "clip-path", + Spec { size: [fill(), fit()], text: Some(path), font_size: Some(10.5), overflow: ui::Overflow::Wrap, color: Some(p.text), ..Spec::default() }, + ); + ui.close(); +} + +pub(super) fn footer(ui: &mut Ui, p: InspectorPalette, stats: &EvalStats) { + let line = format!( + "Eval {:.1}ms · {} nodes · cache {}/{} · {:.0}MB", + stats.eval_ms, + stats.nodes_evaluated, + stats.cache_hits, + stats.cache_hits + stats.cache_misses, + stats.cached_vram_mb, + ); + ui.open( + "insp-footer", + Spec { size: [fill(), px(24.0)], axis: ui::Axis::X, pad: [10.0, 4.0], fill: Some(p.panel_bg), border: Some(p.rule), ..Spec::default() }, + ); + ui.leaf("insp-stats-txt", Spec { size: [fill(), fill()], text: Some(&line), font_size: Some(10.0), color: Some(p.text_dim), ..Spec::default() }); + ui.close(); +} diff --git a/crates/app/src/inspector/controls.rs b/crates/app/src/inspector/controls.rs new file mode 100644 index 0000000000000000000000000000000000000000..abc01a06d319a899c906bd1d733fc8c83785eb4b --- /dev/null +++ b/crates/app/src/inspector/controls.rs @@ -0,0 +1,372 @@ +//! Fusion's four-column parameter row — right-aligned label, control, value box(es), keyframe +//! diamond — and one renderer per control kind, built from the Knife `ui` primitives. + +use super::edit::{Cx, NumberEdit}; +use super::layout::{Channel, ControlDef, Kind}; +use super::widgets::{MARK_W, expression_badge, format_param_number, keyframe_button}; +use model::ParamValue; +use ui::{Spec, Ui, fill, fit, px}; +use winit::keyboard::{Key, NamedKey}; + +const LABEL_W: f32 = 115.0; +const ROW_H: f32 = 24.0; +const BOX_H: f32 = 20.0; + +pub(super) fn render(ui: &mut Ui, cx: &mut Cx, def: &ControlDef) { + let channels = def.channels.as_slice(); + let animatable = match def.kind { + Kind::Slider | Kind::Screw | Kind::Range | Kind::Color | Kind::Checkbox | Kind::Toggles => true, + Kind::Segmented | Kind::Combo => !def.fuid, + Kind::Point | Kind::Text => false, + }; + let marks = if animatable { channels } else { &[] }; + match def.kind { + Kind::Slider => { + let ch = &channels[0]; + let sub = sub_labels(&ch.id); + let height = px(if sub.is_some() { ROW_H + 14.0 } else { ROW_H }); + row(ui, cx, &def.label, &ch.id, marks, height, |ui, cx| { + let value = cx.number(ch); + let mut spec = ui::Slider::new(value as f32, ch.scale[0] as f32, ch.scale[1] as f32, cx.default_of(ch) as f32); + spec.step = ch.integer.then_some(1.0); + spec.sub_labels = sub; + spec.label = &def.label; + if let Some(next) = ui::slider(ui, ("sld", cx.node.0, ch.id.as_str()), spec) { + cx.write_numbers(&def.label, &[(ch, f64::from(next))], true); + } + number_box(ui, cx, ch, None, value, px(52.0)); + }); + } + Kind::Screw => { + let ch = &channels[0]; + row(ui, cx, &def.label, &ch.id, marks, px(ROW_H), |ui, cx| { + let value = cx.number(ch); + let mut spec = ui::ScrewControl::new(value as f32, cx.default_of(ch) as f32); + spec.sensitivity = ((ch.scale[1] - ch.scale[0]) / 360.0).max(0.001) as f32; + spec.bounds = ch.allowed[0].zip(ch.allowed[1]).map(|(lo, hi)| [lo as f32, hi as f32]); + spec.width = fill(); + spec.label = &def.label; + if let Some(next) = ui::screw_control(ui, ("scw", cx.node.0, ch.id.as_str()), spec) { + cx.write_numbers(&def.label, &[(ch, f64::from(next))], true); + } + number_box(ui, cx, ch, None, value, px(52.0)); + }); + } + Kind::Range => { + let [start, end] = [&channels[0], &channels[1]]; + row(ui, cx, &def.label, &start.id, marks, px(ROW_H), |ui, cx| { + let [s, e] = [cx.number(start), cx.number(end)]; + let mut spec = ui::RangeSlider::new( + s as f32, + e as f32, + start.scale[0] as f32, + start.scale[1] as f32, + [cx.default_of(start) as f32, cx.default_of(end) as f32], + ); + spec.step = start.integer.then_some(1.0); + spec.label = &def.label; + if let Some([ns, ne]) = ui::range_slider(ui, ("rng", cx.node.0, start.id.as_str()), spec) { + let moved = |old: f64, new: f32| (f64::from(new) - old).abs() > 1e-6; + let edits: Vec<_> = [(start, s, ns), (end, e, ne)] + .into_iter() + .filter(|&(_, old, new)| moved(old, new)) + .map(|(ch, _, new)| (ch, f64::from(new))) + .collect(); + cx.write_numbers(&def.label, &edits, true); + } + number_box(ui, cx, start, None, s, px(44.0)); + number_box(ui, cx, end, None, e, px(44.0)); + }); + } + Kind::Color => color(ui, cx, def), + Kind::Checkbox => { + let ch = &channels[0]; + row(ui, cx, &def.label, &ch.id, marks, px(ROW_H), |ui, cx| { + let on = cx.number(ch) >= 0.5; + if checkbox(ui, ("chk", cx.node.0, ch.id.as_str()), on, &def.label) { + cx.write_numbers(&def.label, &[(ch, f64::from(u8::from(!on)))], false); + } + spacer(ui); + }); + } + Kind::Toggles => row(ui, cx, &def.label, &channels[0].id, marks, px(ROW_H), |ui, cx| { + for (ch, name) in channels.iter().zip(&def.entries) { + let on = cx.number(ch) >= 0.5; + if toggle_button(ui, cx, ("tgl", cx.node.0, ch.id.as_str()), name, on) { + cx.write_numbers(name, &[(ch, f64::from(u8::from(!on)))], false); + } + } + spacer(ui); + }), + Kind::Segmented => { + let ch = &channels[0]; + row(ui, cx, &def.label, &ch.id, marks, px(ROW_H + 2.0), |ui, cx| { + let segments: Vec<_> = def.entries.iter().map(|e| ui::MultiSegment::text(e)).collect(); + let mut spec = ui::SegmentedControl::new(&segments, choice_index(cx, def)); + spec.width = fill(); + spec.label = &def.label; + if let Some(next) = ui::segmented_control(ui, ("seg", cx.node.0, ch.id.as_str()), spec) { + write_choice(cx, def, next); + } + }); + } + Kind::Combo => { + let ch = &channels[0]; + row(ui, cx, &def.label, &ch.id, marks, px(ROW_H + 6.0), |ui, cx| { + let current = choice_index(cx, def); + let items: Vec<_> = def + .entries + .iter() + .enumerate() + .map(|(i, e)| ui::popup::Item { text: e, current: i == current, ..Default::default() }) + .collect(); + let shown = def.entries.get(current).map_or("", String::as_str); + let part = ("cmb", cx.node.0, ch.id.as_str()); + if let Some(next) = ui::form::select(ui, part, &def.label, shown, &items, fill(), true) { + write_choice(cx, def, next); + } + }); + } + Kind::Point => { + let ch = &channels[0]; + row(ui, cx, &def.label, &ch.id, marks, px(ROW_H), |ui, cx| { + let point = cx.point(ch); + for (axis, name) in ["X", "Y"].into_iter().enumerate() { + ui.leaf(name, Spec { size: [px(10.0), fill()], text: Some(name), font_size: Some(10.0), color: Some(cx.p.text_dim), center: true, ..Spec::default() }); + number_box(ui, cx, ch, Some(axis), point[axis], fill()); + } + spacer(ui); + }); + } + Kind::Text => text(ui, cx, def), + } +} + +/// `(left, right)` words under a slider's track. +fn sub_labels(id: &str) -> Option<(&'static str, &'static str)> { + (id == "SubtractiveAdditive").then_some(("Subtractive", "Additive")) +} + +fn spacer(ui: &mut Ui) { + ui.leaf("pad", Spec { size: [px(0.0), fill()], ..Spec::default() }); +} + +/// Label column, `body`, then the expression badge and keyframe diamond of `marks`. +fn row(ui: &mut Ui, cx: &mut Cx, label: &str, key: impl std::hash::Hash, marks: &[Channel], height: ui::Extent, body: impl FnOnce(&mut Ui, &mut Cx)) { + ui.open( + ("row", cx.node.0, key), + Spec { size: [fill(), height], axis: ui::Axis::X, gap: 6.0, pad: [4.0, 1.0], ..Spec::default() }, + ); + let label_h = if height == ui::children() { px(ROW_H - 2.0) } else { fill() }; + ui.open("lbl", Spec { size: [px(LABEL_W), label_h], axis: ui::Axis::X, flags: ui::Flags::CLIP, ..Spec::default() }); + ui.leaf("fill", Spec { size: [fill(), fill()], ..Spec::default() }); + ui.leaf( + "text", + Spec { size: [fit(), label_h], text: Some(label), font_size: Some(10.5), color: Some(cx.p.text_dim), ..Spec::default() }, + ); + ui.close(); + body(ui, cx); + if cx.has_expression(marks) { + expression_badge(ui); + } + if marks.is_empty() { + ui.leaf("mark-gap", Spec { size: [px(MARK_W), fill()], ..Spec::default() }); + } else { + let state = cx.key_state(marks); + if keyframe_button(ui, cx, state) { + cx.toggle_keyframes(label, marks, state); + } + } + ui.close(); +} + +/// The numeric well beside a control; typing commits when it loses the keys. +fn number_box(ui: &mut Ui, cx: &mut Cx, ch: &Channel, axis: Option, value: f64, width: ui::Extent) { + let id = ui.id(("num", cx.node.0, ch.id.as_str(), axis)); + let focused = ui.focused() == Some(id); + if focused && cx.edit.number.as_ref().is_none_or(|e| e.id != id) { + cx.edit.number = Some(NumberEdit { id, buf: format_value(ch, value), channel: ch.clone(), axis }); + ui.focus_all(id); + } + let mut shown; + let buf = match cx.edit.number.as_mut() { + Some(edit) if focused => &mut edit.buf, + _ => { + shown = format_value(ch, value); + &mut shown + } + }; + let signal = ui::text_field( + ui, + id, + buf, + "", + Spec { + size: [width, px(BOX_H)], + font_size: Some(10.5), + fill: Some(cx.p.panel_bg), + border: Some(cx.p.rule), + hover_border: Some(cx.p.accent), + radius: 3.0, + pad: [4.0, 2.0], + ..Spec::default() + }, + ); + for event in &signal.events { + match event { + ui::Event::Key { key: Key::Named(NamedKey::Enter), .. } => ui.set_focus(None), + ui::Event::Key { key: Key::Named(NamedKey::Escape), .. } => { + cx.edit.number = None; + ui.set_focus(None); + } + _ => {} + } + } +} + +fn format_value(ch: &Channel, value: f64) -> String { + if ch.integer { format!("{}", value.round()) } else { format_param_number(value) } +} + +fn checkbox(ui: &mut Ui, part: impl std::hash::Hash, on: bool, label: &str) -> bool { + let id = ui.id(part); + let signal = ui.signal(id); + ui.open_as( + id, + Spec { + cursor: Some(winit::window::CursorIcon::Pointer), + flags: ui::Flags::CLICKABLE | ui::Flags::FOCUSABLE, + size: [px(BOX_H), px(BOX_H)], + role: Some(accesskit::Role::CheckBox), + ..Spec::default() + }, + ); + ui::check(ui, "mark", Some(on), true, signal.hovered, Some(id)); + ui.close(); + if let Some(node) = ui.access(id) { + node.set_label(label); + } + let space = signal.events.iter().any(|e| matches!(e, ui::Event::Key { key: Key::Named(NamedKey::Space), .. })); + signal.clicked || space +} + +fn toggle_button(ui: &mut Ui, cx: &Cx, part: impl std::hash::Hash, label: &str, on: bool) -> bool { + let p = cx.p; + ui.leaf( + part, + Spec { + cursor: Some(winit::window::CursorIcon::Pointer), + flags: ui::Flags::CLICKABLE, + size: [fit(), px(BOX_H)], + text: Some(label), + font_size: Some(10.5), + medium: on, + color: Some(if on { p.text } else { p.text_dim }), + fill: Some(if on { [p.accent[0], p.accent[1], p.accent[2], 0.28] } else { p.panel_bg }), + border: Some(if on { p.accent } else { p.rule }), + hover_border: Some(p.accent), + radius: 3.0, + pad: [7.0, 0.0], + center: true, + ..Spec::default() + }, + ) + .clicked +} + +fn choice_index(cx: &Cx, def: &ControlDef) -> usize { + let ch = &def.channels[0]; + if def.fuid { + let current = cx.comp.node(cx.node).static_str(&ch.id).unwrap_or(&def.default_text); + def.entries.iter().position(|e| e == current).unwrap_or(def.default_index) + } else { + cx.number(ch).round().max(0.0) as usize + } +} + +fn write_choice(cx: &mut Cx, def: &ControlDef, index: usize) { + let ch = &def.channels[0]; + if def.fuid { + cx.write_value(&def.label, &ch.id, ParamValue::FuId(def.entries[index].clone())); + } else { + cx.write_numbers(&def.label, &[(ch, index as f64)], false); + } +} + +/// Inline picker over the R/G/B(/A) channels, with a slider row per channel under it. +fn color(ui: &mut Ui, cx: &mut Cx, def: &ControlDef) { + let channels = def.channels.as_slice(); + let current: Vec = channels.iter().map(|ch| cx.number(ch)).collect(); + row(ui, cx, &def.label, ("group", &channels[0].id), channels, ui::children(), |ui, cx| { + let rgba = [0, 1, 2, 3].map(|i| current.get(i).map_or(1.0, |v| v.clamp(0.0, 1.0) as f32)); + let mut spec = ui::ColorPicker::new(rgba); + spec.width = fill(); + spec.label = &def.label; + let response = ui::color_picker(ui, ("clr", cx.node.0, channels[0].id.as_str()), spec); + if let Some(next) = response.changed { + let edits: Vec<_> = channels + .iter() + .zip(next) + .zip(rgba) + .filter(|((_, new), old)| (new - old).abs() > 1e-6) + .map(|((ch, new), _)| (ch, f64::from(new))) + .collect(); + cx.write_numbers(&def.label, &edits, true); + } + }); + for (ch, name) in channels.iter().zip(["Red", "Green", "Blue", "Alpha"]) { + row(ui, cx, name, &ch.id, &[], px(ROW_H), |ui, cx| { + let value = cx.number(ch); + let mut spec = ui::Slider::new(value as f32, 0.0, 1.0, cx.default_of(ch) as f32); + spec.label = name; + if let Some(next) = ui::slider(ui, ("clr-sld", cx.node.0, ch.id.as_str()), spec) { + cx.write_numbers(&def.label, &[(ch, f64::from(next))], true); + } + number_box(ui, cx, ch, None, value, px(52.0)); + }); + } +} + +/// A text well; edits apply live and fold into one undo step until it loses the keys. +fn text(ui: &mut Ui, cx: &mut Cx, def: &ControlDef) { + let ch = &def.channels[0]; + row(ui, cx, &def.label, &ch.id, &[], px(ROW_H), |ui, cx| { + let id = ui.id(("txt", cx.node.0, ch.id.as_str())); + let focused = ui.focused() == Some(id); + let model = cx.comp.node(cx.node).static_str(&ch.id).unwrap_or(&def.default_text).to_owned(); + if focused && cx.edit.text.as_ref().is_none_or(|(owner, _)| *owner != id) { + cx.edit.text = Some((id, model.clone())); + } + let mut shown = model; + let buf = match cx.edit.text.as_mut() { + Some((_, buf)) if focused => buf, + _ => &mut shown, + }; + let before = buf.clone(); + let signal = ui::text_field( + ui, + id, + buf, + &def.label, + Spec { + size: [fill(), px(BOX_H)], + font_size: Some(10.5), + fill: Some(cx.p.panel_bg), + border: Some(cx.p.rule), + hover_border: Some(cx.p.accent), + radius: 3.0, + pad: [6.0, 2.0], + ..Spec::default() + }, + ); + if *buf != before { + let value = if def.fuid { ParamValue::FuId(buf.clone()) } else { ParamValue::Text(buf.clone()) }; + cx.history.push_coalesced(cx.comp, format!("Edit {}", def.label), format!("text:{}:{}", cx.node.0, ch.id)); + cx.comp.set_input_value(cx.node, &ch.id, value); + cx.actions.push(super::InspectorAction::ParamEdited(cx.node)); + } + if signal.events.iter().any(|e| matches!(e, ui::Event::Key { key: Key::Named(NamedKey::Enter), .. })) { + cx.history.break_coalescing(); + } + }); +} diff --git a/crates/app/src/inspector/dynamic.rs b/crates/app/src/inspector/dynamic.rs new file mode 100644 index 0000000000000000000000000000000000000000..7dc8d9cf690a462ec22412386fa03533be923f1d --- /dev/null +++ b/crates/app/src/inspector/dynamic.rs @@ -0,0 +1,156 @@ +//! Inputs the catalog cannot describe: a node's own `UserControls`, tools Fusion's introspection +//! skipped (curated schemas), and live inputs no row covers. + +use super::catalog::{Control, InputDef, control_for, humanize}; +use super::layout::{ToolLayout, build_layout}; +use super::schemas::{ParamKind, infer_float_range, schema_for_kind}; +use model::{Comp, LuaKey, LuaTable, NodeId, ParamValue}; +use std::collections::HashSet; + +/// Rows for each `UserControls` entry of a tool/macro/group table, grouped into pages by +/// `ICS_ControlPage`. +pub fn user_defs(raw: &LuaTable) -> Vec { + let Some(controls) = raw.get_table("UserControls") else { return Vec::new() }; + controls + .entries + .iter() + .filter_map(|(key, value)| { + let LuaKey::Str(id) = key else { return None }; + user_def(id, value.as_table()?) + }) + .collect() +} + +fn user_def(id: &str, t: &LuaTable) -> Option { + let data_type = t.get_str("LINKID_DataType").unwrap_or("Number"); + let entries: Vec = t + .positional_values() + .filter_map(|v| v.as_table()) + .filter_map(|e| e.get_str("CCS_AddString").or(e.get_str("CCID_AddID")).or(e.get_str("MBTNC_AddButton"))) + .map(str::to_owned) + .collect(); + let control_name = t.get_str("INPID_InputControl").unwrap_or(match data_type { + "Point" => "OffsetControl", + "Text" | "FuID" => "TextEditControl", + _ => "SliderControl", + }); + let control = control_for(control_name, data_type, !entries.is_empty())?; + let mut scale = [t.get_f64("INP_MinScale").unwrap_or(0.0), t.get_f64("INP_MaxScale").unwrap_or(1.0)]; + if scale[1] <= scale[0] { + scale[1] = scale[0] + 1.0; + } + let name = t.get_str("LINKS_Name").map_or_else(|| humanize(id), str::to_owned); + Some(InputDef { + fuid: matches!(data_type, "FuID" | "Text"), + default: if data_type == "Point" { + [t.get_f64("INP_DefaultX").unwrap_or(0.5), t.get_f64("INP_DefaultY").unwrap_or(0.5)] + } else { + [t.get_f64("INP_Default").unwrap_or(0.0), 0.0] + }, + default_text: t.get_str("INP_Default").unwrap_or_default().to_owned(), + scale, + allowed: [t.get_f64("INP_MinAllowed"), t.get_f64("INP_MaxAllowed")], + integer: t.get_bool("INP_Integer").unwrap_or(false), + page: Some(t.get_str("ICS_ControlPage").unwrap_or("User").to_owned()), + entries, + group: t.get_f64("IC_ControlGroup").map(|g| (g as i64, t.get_f64("IC_ControlID").unwrap_or(0.0) as u32)), + ..InputDef::new(id, &name, control) + }) +} + +/// Rows for live inputs of `node` that `covered` rejects, typed by their stored value. +pub fn extra_defs(comp: &Comp, node: NodeId, covered: impl Fn(&str) -> bool) -> Vec { + let mut keys: Vec<&String> = comp + .node(node) + .inputs + .iter() + .filter(|(key, b)| { + let wired = b.source_op.as_deref().is_some_and(|op| comp.node_by_name.contains_key(op)); + !covered(key) + && !(wired && b.value.is_none()) + && (b.value.is_some() || b.expression.is_some() || b.source_op.is_some()) + }) + .map(|(key, _)| key) + .collect(); + keys.sort(); + keys.into_iter() + .map(|key| { + let value = comp.node(node).inputs[key].value.as_ref(); + let (control, fuid) = match value { + Some(ParamValue::Point(_)) => (Control::Offset, false), + Some(ParamValue::Text(_)) => (Control::Text, false), + Some(ParamValue::FuId(_)) => (Control::Text, true), + _ => (Control::Slider, false), + }; + let number = value.and_then(ParamValue::as_f64).unwrap_or(0.0); + InputDef { + fuid, + default: value.and_then(ParamValue::as_point).unwrap_or([number, 0.0]), + default_text: value.and_then(ParamValue::as_str).unwrap_or_default().to_owned(), + scale: if control == Control::Slider { infer_float_range(key, number).into() } else { [0.0, 1.0] }, + page: Some("Other".to_owned()), + ..InputDef::new(key, key, control) + } + }) + .collect() +} + +/// A layout from the curated schema, for tools the Fusion catalog skipped. +pub fn curated_layout(kind: &str) -> Option { + let schema = schema_for_kind(kind); + if schema.is_empty() { + return None; + } + let mut defs = Vec::new(); + let mut covered = HashSet::new(); + for spec in schema { + let base = |control| InputDef { page: Some("Controls".to_owned()), ..InputDef::new(spec.name, spec.label, control) }; + match spec.kind { + ParamKind::Float { min, max, default, .. } => { + defs.push(InputDef { default: [default, 0.0], scale: [min, max], ..base(Control::Slider) }); + } + ParamKind::Vec2 { default, .. } => defs.push(InputDef { default, ..base(Control::Offset) }), + ParamKind::Bool { default } => { + defs.push(InputDef { default: [f64::from(u8::from(default)), 0.0], integer: true, ..base(Control::Checkbox) }); + } + ParamKind::Enum { options, default } => defs.push(InputDef { + fuid: true, + default_text: default.to_owned(), + entries: options.iter().map(|o| (*o).to_owned()).collect(), + ..base(Control::Combo) + }), + ParamKind::IntEnum { options, default } => { + let sequential = options.iter().enumerate().all(|(i, (code, _))| *code == i as i32); + defs.push(if sequential { + InputDef { + default: [f64::from(default), 0.0], + entries: options.iter().map(|(_, label)| (*label).to_owned()).collect(), + ..base(Control::Combo) + } + } else { + let codes = options.iter().map(|(code, _)| f64::from(*code)); + let hi = codes.clone().fold(f64::MIN, f64::max); + InputDef { default: [f64::from(default), 0.0], scale: [codes.fold(f64::MAX, f64::min), hi], integer: true, ..base(Control::Slider) } + }); + } + ParamKind::Color { r, g, b, a, default } => { + for (n, id) in [Some(r), Some(g), Some(b), a].into_iter().enumerate() { + let Some(id) = id else { continue }; + covered.insert(id.to_owned()); + let name = if n == 0 { format!("{} Red", spec.label) } else { id.to_owned() }; + defs.push(InputDef { + default: [default[n], 0.0], + group: Some((0, n as u32)), + ..InputDef { page: Some("Controls".to_owned()), ..InputDef::new(id, &name, Control::Color) } + }); + } + continue; + } + ParamKind::Text { default } => { + defs.push(InputDef { fuid: false, default_text: default.to_owned(), ..base(Control::Text) }); + } + } + covered.insert(spec.name.to_owned()); + } + Some(build_layout(kind, defs, covered)) +} diff --git a/crates/app/src/inspector/edit.rs b/crates/app/src/inspector/edit.rs new file mode 100644 index 0000000000000000000000000000000000000000..b2faef93bebdb5802f1ac939a4bf49c2b1cf908d --- /dev/null +++ b/crates/app/src/inspector/edit.rs @@ -0,0 +1,178 @@ +//! Everything a row does to the comp: reading evaluated values, keyframe-aware writes with undo, +//! numeric-box edit state, and keyframe toggling for single inputs and grouped channels. + +use super::layout::{Channel, ControlDef, Kind}; +use super::widgets::{KeyframeState, keyframe_state}; +use super::{InspectorAction, InspectorPalette}; +use model::{Comp, CompHistory, ExprEngine, NodeId, ParamValue}; +use std::time::{Duration, Instant}; + +/// How long a drag rests before the undo step it coalesced into closes. +pub(super) const SCRUB_GRACE: Duration = Duration::from_millis(350); + +/// A numeric box being typed into; it commits when it loses the keys. +pub(super) struct NumberEdit { + pub id: ui::Id, + pub buf: String, + pub channel: Channel, + /// `Some(0|1)` edits one axis of a Point input. + pub axis: Option, +} + +#[derive(Default)] +pub(super) struct EditState { + pub number: Option, + pub text: Option<(ui::Id, String)>, + pub last_scrub: Option, +} + +pub(super) struct Cx<'a> { + pub comp: &'a mut Comp, + pub history: &'a mut CompHistory, + pub actions: &'a mut Vec, + pub node: NodeId, + pub frame: f64, + pub now: Instant, + pub p: InspectorPalette, + pub expr: &'a ExprEngine, + pub edit: &'a mut EditState, +} + +impl Cx<'_> { + /// A Loader without `Inputs.Loop`/`Reverse` plays whatever its clip says. + pub fn default_of(&self, ch: &Channel) -> f64 { + let node = self.comp.node(self.node); + let clip = node.clips.first().filter(|_| node.kind == "Loader"); + match (ch.id.as_str(), clip) { + ("Loop", Some(c)) => f64::from(u8::from(c.loop_clip)), + ("Reverse", Some(c)) => f64::from(u8::from(c.reverse)), + _ => ch.default[0], + } + } + + pub fn number(&self, ch: &Channel) -> f64 { + self.comp.eval_number(self.comp.node(self.node), &ch.id, self.frame, self.default_of(ch), self.expr) + } + + pub fn point(&self, ch: &Channel) -> [f64; 2] { + self.comp.eval_point(self.comp.node(self.node), &ch.id, self.frame, ch.default, self.expr) + } + + pub fn has_expression(&self, channels: &[Channel]) -> bool { + let node = self.comp.node(self.node); + channels.iter().any(|ch| node.inputs.get(&ch.id).is_some_and(|b| b.expression.is_some())) + } + + /// Every channel at a keyframe reads as on a keyframe; any animated one as animated. + pub fn key_state(&self, channels: &[Channel]) -> KeyframeState { + let mut states = channels.iter().map(|ch| keyframe_state(self.comp, self.node, &ch.id, self.frame)); + if channels.is_empty() || states.clone().all(|s| s == KeyframeState::KeyframeAtCurrent) { + return states.next().unwrap_or(KeyframeState::Static); + } + if states.any(|s| s != KeyframeState::Static) { + KeyframeState::AnimatedOtherFrame + } else { + KeyframeState::Static + } + } + + /// Writes numbers, as a keyframe where the input is animated. A `drag` folds into one undo + /// step per input until it rests; anything else is its own step. + pub fn write_numbers(&mut self, label: &str, edits: &[(&Channel, f64)], drag: bool) { + if drag { + let key = format!("scrub:{}:{}", self.node.0, edits[0].0.id); + self.history.push_coalesced(self.comp, format!("Adjust {label}"), key); + self.edit.last_scrub = Some(self.now); + } else { + self.history.push_snapshot(self.comp, format!("Set {label}")); + } + for &(ch, value) in edits { + let value = value.clamp(ch.allowed[0].unwrap_or(f64::MIN), ch.allowed[1].unwrap_or(f64::MAX)); + let animated = keyframe_state(self.comp, self.node, &ch.id, self.frame) != KeyframeState::Static; + if animated { + let _ = self.comp.set_keyframe(self.node, &ch.id, self.frame, value); + self.actions.push(InspectorAction::KeyframeEdited(self.node)); + } else { + self.comp.set_input_value(self.node, &ch.id, ParamValue::Number(value)); + self.actions.push(InspectorAction::ParamEdited(self.node)); + } + } + } + + pub fn write_value(&mut self, label: &str, id: &str, value: ParamValue) { + self.history.push_snapshot(self.comp, format!("Set {label}")); + self.comp.set_input_value(self.node, id, value); + self.actions.push(InspectorAction::ParamEdited(self.node)); + } + + /// Commits a numeric box once it has lost the keys. + pub fn commit_number(&mut self, edit: NumberEdit) { + let Ok(value) = edit.buf.trim().parse::() else { return }; + if !value.is_finite() { + return; + } + let ch = &edit.channel; + match edit.axis { + Some(axis) => { + let mut point = self.point(ch); + point[axis] = value; + self.write_value(&ch.id, &ch.id, ParamValue::Point(point)); + } + None => self.write_numbers(&ch.id, &[(ch, value)], false), + } + } + + /// Keys every channel at the current frame, or removes those keys when all already have one. + pub fn toggle_keyframes(&mut self, label: &str, channels: &[Channel], state: KeyframeState) { + self.history.begin_group(self.comp, format!("Keyframe {label}")); + let mut notice = None; + for ch in channels { + if state == KeyframeState::KeyframeAtCurrent { + let spline = self.comp.node(self.node).inputs.get(&ch.id).and_then(|b| b.source_op.clone()); + if spline.is_some_and(|sp| self.comp.delete_keyframe(&sp, self.frame)) { + notice = Some(format!("Deleted keyframe on {label} @ f{:.0}", self.frame)); + } + } else { + let value = self.number(ch); + match self.comp.set_keyframe(self.node, &ch.id, self.frame, value) { + Ok(_) => notice = Some(format!("Keyframed {label} @ f{:.0}", self.frame)), + Err(e) => notice = Some(e), + } + } + } + self.history.commit_group(self.comp); + if let Some(notice) = notice { + self.actions.push(InspectorAction::KeyframeEdited(self.node)); + self.actions.push(InspectorAction::StatusNotice(notice)); + } + } + + /// Puts every static input of `controls` back to its default; animated and expression inputs + /// keep their drivers. + pub fn reset_defaults<'d>(&mut self, controls: impl Iterator) { + self.history.begin_group(self.comp, "Reset to Defaults"); + for def in controls { + for ch in &def.channels { + let binding = self.comp.node(self.node).inputs.get(&ch.id); + if binding.is_some_and(|b| b.source_op.is_some() || b.expression.is_some()) { + continue; + } + let Some(current) = binding.and_then(|b| b.value.clone()) else { continue }; + let default = match def.kind { + Kind::Point => ParamValue::Point(ch.default), + Kind::Text if def.fuid => ParamValue::FuId(def.default_text.clone()), + Kind::Text => ParamValue::Text(def.default_text.clone()), + Kind::Segmented | Kind::Combo if def.fuid => ParamValue::FuId(def.entries[def.default_index].clone()), + _ => ParamValue::Number(self.default_of(ch)), + }; + if current != default { + self.comp.set_input_value(self.node, &ch.id, default); + } + } + } + if self.history.commit_group(self.comp) { + self.actions.push(InspectorAction::ParamEdited(self.node)); + self.actions.push(InspectorAction::StatusNotice("Reset to defaults".to_owned())); + } + } +} diff --git a/crates/app/src/inspector/layout.rs b/crates/app/src/inspector/layout.rs new file mode 100644 index 0000000000000000000000000000000000000000..78a960062a854325bc6003bf0211a44dc20a1b2d --- /dev/null +++ b/crates/app/src/inspector/layout.rs @@ -0,0 +1,254 @@ +//! Turns a flat [`InputDef`] list into the Inspector's pages, sections and rows: sibling +//! RGBA/range/toggle inputs fuse into one [`ControlDef`], pages follow Fusion's tab order. + +use super::catalog::{Control, InputDef}; +use std::collections::HashSet; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Kind { + Slider, + Screw, + Range, + Color, + Toggles, + Segmented, + Combo, + Checkbox, + Point, + Text, +} + +/// One input a row reads and writes. +#[derive(Clone, Debug)] +pub struct Channel { + pub id: String, + /// Number default in `[0]`; Point default `[x, y]`. + pub default: [f64; 2], + pub scale: [f64; 2], + pub allowed: [Option; 2], + pub integer: bool, +} + +/// One Inspector row. +#[derive(Clone, Debug)] +pub struct ControlDef { + pub label: String, + pub kind: Kind, + /// Range: start, end. Color: r, g, b[, a]. Toggles: one per button. + pub channels: Vec, + /// Segmented/Combo choices, or one label per toggle button. + pub entries: Vec, + /// Segmented/Combo/Text values are strings; choices default to `default_index`. + pub fuid: bool, + pub default_index: usize, + pub default_text: String, +} + +#[derive(Clone, Debug)] +pub struct Section { + pub title: String, + pub open: bool, + pub controls: Vec, +} + +#[derive(Clone, Debug)] +pub struct Page { + pub name: String, + pub sections: Vec
, +} + +#[derive(Clone, Debug, Default)] +pub struct ToolLayout { + pub pages: Vec, + /// Every input id the tool registers, including image and mask ports with no row. + pub covered: HashSet, +} + +const SETTINGS: &str = "Settings"; + +/// Fusion tab order where `:GetInputList()` registration order differs. +const PAGE_ORDER: &[(&str, &[&str])] = &[ + ("TextPlus", &["Text", "Layout", "Transform", "Shading", "Image", SETTINGS]), + ("Text3D", &["Text", "Layout", "Transform", "Shading", "3D", SETTINGS]), +]; + +/// Subsections Fusion draws inside a page, which the input list doesn't report: +/// `(tools, first input id, title, open)`. No tools matches every tool. +pub(super) const SECTIONS: &[(&[&str], &str, &str, bool)] = &[ + (&["Merge", "Transform"], "Width", "Reference Size", false), + (&[], "MotionBlur", "Motion Blur", true), + (&["Text3D"], "ExtrusionStyle", "Extrusion", true), +]; + +const MAX_SEGMENTS: usize = 5; +const MAX_SEGMENT_CHARS: usize = 18; + +pub fn build_layout(kind: &str, defs: Vec, covered: HashSet) -> ToolLayout { + let mut pages: Vec<(String, Vec)> = Vec::new(); + for def in defs { + let name = match def.page.as_deref() { + None | Some("Common") => SETTINGS, + Some(page) => page, + }; + match pages.iter_mut().find(|(n, _)| n == name) { + Some((_, list)) => list.push(def), + None => pages.push((name.to_owned(), vec![def])), + } + } + let order = PAGE_ORDER.iter().find(|(k, _)| *k == kind).map(|(_, o)| *o); + let rank = |name: &str| match order { + Some(order) => order.iter().position(|o| *o == name), + None => Some(match name { + SETTINGS => 2, + "Image" => 1, + _ => 0, + }), + }; + pages.sort_by_key(|(name, _)| rank(name).unwrap_or(usize::MAX)); + + let pages = pages + .into_iter() + .map(|(name, defs)| { + let title = if name == SETTINGS { "Common Controls" } else { &name }; + Page { sections: sections(kind, title, controls(&defs)), name } + }) + .collect(); + ToolLayout { pages, covered } +} + +/// A single-section page for controls that are not in the catalog (user controls, stray inputs). +pub fn dynamic_page(name: &str, defs: &[InputDef]) -> Page { + Page { name: name.to_owned(), sections: sections("", name, controls(defs)) } +} + +fn sections(kind: &str, first_title: &str, controls: Vec) -> Vec
{ + let mut out = vec![Section { title: first_title.to_owned(), open: true, controls: Vec::new() }]; + for control in controls { + let marker = SECTIONS.iter().find(|(tools, id, ..)| { + (tools.is_empty() || tools.contains(&kind)) && control.channels.first().is_some_and(|c| c.id == *id) + }); + if let Some(&(_, _, title, open)) = marker { + out.push(Section { title: title.to_owned(), open, controls: Vec::new() }); + } + out.last_mut().expect("starts non-empty").controls.push(control); + } + out.retain(|s| !s.controls.is_empty()); + out +} + +/// How many defs from `i` form one group: same control and `IC_ControlGroup`, ascending `IC_ControlID`. +fn group_len(defs: &[InputDef], i: usize) -> usize { + let head = &defs[i]; + let Some((group, first)) = head.group else { return 1 }; + 1 + defs[i + 1..] + .iter() + .zip(first + 1..) + .take_while(|(d, id)| d.control == head.control && d.group == Some((group, *id))) + .count() +} + +fn controls(defs: &[InputDef]) -> Vec { + let mut out = Vec::new(); + let mut i = 0; + while i < defs.len() { + let head = &defs[i]; + let run = group_len(defs, i); + let starts_group = head.group.is_some_and(|(_, id)| id == 0); + let take = match head.control { + Control::Color if run >= 3 && starts_group => run.min(4), + Control::Range if run >= 2 && starts_group => 2, + Control::MultiButton if head.entries.len() == 1 => run, + _ => 1, + }; + out.push(control(&defs[i..i + take])); + i += take; + } + out +} + +fn channel(d: &InputDef) -> Channel { + Channel { id: d.id.clone(), default: d.default, scale: d.scale, allowed: d.allowed, integer: d.integer } +} + +fn control(group: &[InputDef]) -> ControlDef { + let d = &group[0]; + let (kind, label, entries) = match d.control { + Control::Color if group.len() >= 3 => (Kind::Color, color_label(&d.name), Vec::new()), + Control::Range if group.len() == 2 => (Kind::Range, range_label(&group[0].name, &group[1].name), Vec::new()), + Control::MultiButton if d.entries.len() == 1 => { + let names: Vec<&str> = group.iter().map(|g| g.name.as_str()).collect(); + (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()) + } + Control::MultiButton | Control::Combo => { + let chars: usize = d.entries.iter().map(String::len).sum(); + let segmented = d.control == Control::MultiButton && d.entries.len() <= MAX_SEGMENTS && chars <= MAX_SEGMENT_CHARS; + (if segmented { Kind::Segmented } else { Kind::Combo }, d.name.clone(), d.entries.clone()) + } + Control::Screw => (Kind::Screw, d.name.clone(), Vec::new()), + Control::Checkbox => (Kind::Checkbox, d.name.clone(), Vec::new()), + Control::Offset => (Kind::Point, d.name.clone(), Vec::new()), + Control::Text => (Kind::Text, d.name.clone(), Vec::new()), + Control::Slider | Control::Color | Control::Range => (Kind::Slider, d.name.clone(), Vec::new()), + }; + let default_index = if d.fuid { + entries.iter().position(|e| *e == d.default_text).unwrap_or(0) + } else { + (d.default[0].max(0.0) as usize).min(entries.len().saturating_sub(1)) + }; + ControlDef { + label, + kind, + channels: group.iter().map(channel).collect(), + entries, + fuid: d.fuid, + default_index, + default_text: d.default_text.clone(), + } +} + +/// `Top Left Red` -> `Top Left`; a bare channel name is just `Color`. +fn color_label(first: &str) -> String { + let rest: Vec<&str> = first.split_whitespace().filter(|w| *w != "Red").collect(); + match rest.first() { + None => "Color".to_owned(), + Some(w) if w.starts_with(|c: char| c.is_ascii_digit()) => format!("Color {}", rest.join(" ")), + Some(_) => rest.join(" "), + } +} + +/// `Write On Start`, `Write On End` -> `Write On Start / End`; `Low`, `High` -> `Low / High`. +fn range_label(start: &str, end: &str) -> String { + let (a, b): (Vec<&str>, Vec<&str>) = (start.split_whitespace().collect(), end.split_whitespace().collect()); + let shared = a.iter().zip(&b).take_while(|(x, y)| x == y).count(); + if shared == 0 || shared == a.len().min(b.len()) { + return format!("{start} / {end}"); + } + format!("{} / {}", start, b[shared..].join(" ")) +} + +/// The words every name starts with, or `None` when they share none. +fn common_prefix(names: &[&str]) -> Option { + let first: Vec<&str> = names.first()?.split_whitespace().collect(); + let shared = names + .iter() + .map(|n| n.split_whitespace().zip(&first).take_while(|(a, b)| a == *b).count()) + .min()?; + (shared > 0).then(|| first[..shared].join(" ")) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn labels() { + assert_eq!(color_label("Top Left Red"), "Top Left"); + assert_eq!(color_label("Red 1"), "Color 1"); + assert_eq!(color_label("Red"), "Color"); + assert_eq!(range_label("Write On Start", "Write On End"), "Write On Start / End"); + assert_eq!(range_label("Low", "High"), "Low / High"); + assert_eq!(common_prefix(&["Process Red", "Process Green"]).as_deref(), Some("Process")); + assert_eq!(common_prefix(&["Flip Horizontal", "Flip Vertical"]).as_deref(), Some("Flip")); + assert_eq!(common_prefix(&["Red", "Green"]), None); + } +} diff --git a/crates/app/src/inspector/mod.rs b/crates/app/src/inspector/mod.rs index be56416bbc8080c99ebef59081a609c9cf2be9db..1b9083f8ddad666e0dc172e4a87c6bfbcada3acd 100644 --- a/crates/app/src/inspector/mod.rs +++ b/crates/app/src/inspector/mod.rs @@ -1,24 +1,25 @@ -//! Inspector dock pane — Fusion 21.1 parameter editor with scrub sliders, Vec2, RGBA color groups, -//! booleans, FuID enum cyclers, text fields, expression badges, and keyframe diamonds (`◆`). +//! Inspector dock pane: a declarative, catalog-driven Fusion 21.1 parameter editor. Pages, groups +//! and control kinds come from `scripts/tool_catalog.json`; rows are built from the Knife `ui` +//! sliders, screws, range sliders, color pickers and segmented controls. +mod catalog; +mod chrome; +mod controls; +mod dynamic; +mod edit; +mod layout; mod schemas; mod widgets; #[cfg(test)] pub use schemas::CURATED_TOOL_KINDS; -#[allow(unused_imports)] -pub use schemas::{ParamKind, ParamSpec, infer_float_range, schema_for_kind}; -#[allow(unused_imports)] -pub use widgets::{ - KeyframeState, compute_scrub_value, format_param_number, keyframe_state, - normalize_slider_fraction, -}; +pub use widgets::{KeyframeState, keyframe_state}; use engine::EvalStats; -use model::{Comp, CompHistory, ExprEngine, NodeId, is_supported_tool}; -use std::collections::{HashMap, HashSet}; -use std::time::Instant; -use widgets::DragState; +use layout::{Page, ToolLayout}; +use model::{Comp, CompHistory, ExprEngine, NodeId}; +use std::collections::HashMap; +use std::time::Duration; #[derive(Clone, Debug)] pub enum InspectorAction { @@ -64,33 +65,43 @@ impl InspectorPalette { } } +/// Pages for the selected node's own `UserControls` and stray inputs, rebuilt when the comp +/// revision moves. +struct NodePages { + node: NodeId, + revision: u64, + pages: Vec, +} + pub struct InspectorState { pub palette: InspectorPalette, expr: ExprEngine, - /// Node name edit buffer synced with the currently selected node. - name_node: Option, - name_buf: String, - /// Text parameter edit buffers keyed by `(node_id, param_name)`. - text_bufs: HashMap<(usize, String), String>, - /// Active scrub slider drag. - drag: Option, - /// Text field that had the keys last frame, so losing them ends its coalesced undo step. - text_focus: Option, - /// Last click timestamp per slider key for double-click reset. - last_click: HashMap, + rename: chrome::Rename, + edit: edit::EditState, + /// Active page tab per node. + page: HashMap, + /// Section open/closed overrides per `(node, page, section)`. + sections: HashMap<(usize, usize, usize), bool>, + node_pages: Option, + /// Layouts of tools the catalog lacks, built from curated schemas on first sight. + fallback: HashMap, } impl InspectorState { pub fn new(theme: &ui::Theme) -> Self { + // Parse the catalog off the UI thread; frames wait on it with a placeholder. + std::thread::spawn(|| { + catalog::catalog(); + }); Self { palette: InspectorPalette::from_theme(theme), expr: ExprEngine::new(), - name_node: None, - name_buf: String::new(), - text_bufs: HashMap::new(), - drag: None, - text_focus: None, - last_click: HashMap::new(), + rename: chrome::Rename::default(), + edit: edit::EditState::default(), + page: HashMap::new(), + sections: HashMap::new(), + node_pages: None, + fallback: HashMap::new(), } } @@ -99,11 +110,9 @@ impl InspectorState { } pub fn reset(&mut self) { - self.name_node = None; - self.name_buf.clear(); - self.text_bufs.clear(); - self.drag = None; - self.text_focus = None; + self.rename = chrome::Rename::default(); + self.edit = edit::EditState::default(); + self.node_pages = None; } pub fn build_ui( @@ -121,501 +130,138 @@ impl InspectorState { ui.open_as( pane_id, - ui::Spec { - size: [ui::fill(), ui::fill()], - axis: ui::Axis::Y, - fill: Some(p.bg), - ..ui::Spec::default() - }, + ui::Spec { size: [ui::fill(), ui::fill()], axis: ui::Axis::Y, fill: Some(p.bg), ..ui::Spec::default() }, ); - let Some(node_id) = selected.filter(|id| id.0 < comp.nodes.len()) else { - // Empty state - ui.open( - "insp-empty", - ui::Spec { - size: [ui::fill(), ui::fill()], - axis: ui::Axis::Y, - pad: [14.0, 18.0], - gap: 8.0, - ..ui::Spec::default() - }, - ); - ui.leaf( - "empty-title", - ui::Spec { - size: [ui::fill(), ui::px(20.0)], - text: Some("No Node Selected"), - font_size: Some(12.5), - medium: true, - color: Some(p.text), - ..ui::Spec::default() - }, - ); - ui.leaf( - "empty-hint", - ui::Spec { - size: [ui::fill(), ui::fit()], - text: Some("Select a node in the Flow graph to inspect and keyframe its parameters, or press Shift+Space to add a tool."), - font_size: Some(11.0), - overflow: ui::Overflow::Wrap, - color: Some(p.text_dim), - ..ui::Spec::default() - }, - ); - self.render_stats_footer(ui, stats); - ui.close(); + chrome::empty_state(ui, p); + chrome::footer(ui, p, stats); ui.close(); return actions; }; - // Sync editable name buffer when selection changes or node was renamed externally (e.g. undo) - let current_name = comp.node(node_id).name.clone(); - let name_field_id = pane_id.child(("node-name", node_id.0)); - if self.name_node != Some(node_id) - || (ui.focused() != Some(name_field_id) && self.name_buf != current_name) - { - self.name_node = Some(node_id); - self.name_buf = current_name.clone(); - } - - // 1. Header: Node name + Class badge + Bypass toggle - ui.open( - "insp-header", - ui::Spec { - size: [ui::fill(), ui::children()], - axis: ui::Axis::Y, - pad: [10.0, 8.0], - gap: 6.0, - fill: Some(p.panel_bg), - border: Some(p.rule), - ..ui::Spec::default() - }, - ); + let kind = comp.node(node_id).kind.clone(); + let Some(catalog) = catalog::ready() else { + ui.wake_after(Duration::from_millis(50)); + return self.loading(ui, p, stats, actions); + }; + let layout = match catalog.get(&kind) { + Some(entry) => &entry.layout, + None => self + .fallback + .entry(kind.clone()) + .or_insert_with(|| dynamic::curated_layout(&kind).unwrap_or_default()), + }; - // Row 1: Editable name + Bypass button - ui.open( - "insp-name-row", - ui::Spec { - size: [ui::fill(), ui::px(26.0)], - axis: ui::Axis::X, - gap: 6.0, - ..ui::Spec::default() - }, - ); - let name_sig = ui::text_field( - ui, - name_field_id, - &mut self.name_buf, - "Node name", - ui::Spec { - size: [ui::fill(), ui::px(24.0)], - font_size: Some(12.0), - medium: true, - fill: Some(p.bg), - border: Some(p.rule), - hover_border: Some(p.accent), - radius: 4.0, - pad: [6.0, 2.0], - ..ui::Spec::default() - }, - ); - let enter_pressed = name_sig.events.iter().any(|ev| { - matches!( - ev, - ui::Event::Key { key: winit::keyboard::Key::Named(winit::keyboard::NamedKey::Enter), .. } - ) - }); - if enter_pressed && self.name_buf.trim() != current_name { - let desired = self.name_buf.trim().to_owned(); - history.begin_group(comp, "Rename Node"); - match comp.rename_node(node_id, &desired) { - Ok(applied) => { - history.commit_group(comp); - self.name_buf = applied; - actions.push(InspectorAction::NodeRenamed(node_id)); - } - Err(e) => { - history.cancel_group(comp); - self.name_buf = current_name.clone(); - actions.push(InspectorAction::StatusNotice(e)); - } - } - ui.set_focus(None); + if self.node_pages.as_ref().is_none_or(|n| n.node != node_id || n.revision != comp.revision) { + self.node_pages = Some(NodePages { node: node_id, revision: comp.revision, pages: node_pages(comp, node_id, layout) }); } + let dynamic_pages = self.node_pages.as_ref().map_or(&[][..], |n| n.pages.as_slice()); - let bypassed = comp.node(node_id).bypassed; - let pass_lbl = if bypassed { "Bypassed" } else { "Active" }; - let pass_fill = if bypassed { - [0.85, 0.28, 0.28, 0.28] - } else { - [0.24, 0.78, 0.48, 0.18] - }; - let pass_border = if bypassed { - [0.92, 0.36, 0.36, 0.75] - } else { - [0.28, 0.82, 0.52, 0.55] + let mut cx = edit::Cx { + comp, + history, + actions: &mut actions, + node: node_id, + frame: current_frame, + now: ui.now(), + p, + expr: &self.expr, + edit: &mut self.edit, }; - let pass_sig = ui.leaf( - ("insp-pass", node_id.0), - ui::Spec { - cursor: Some(winit::window::CursorIcon::Pointer), - flags: ui::Flags::CLICKABLE, - size: [ui::fit(), ui::px(24.0)], - text: Some(pass_lbl), - font_size: Some(10.5), - medium: true, - color: Some(p.text), - fill: Some(pass_fill), - border: Some(pass_border), - radius: 4.0, - pad: [8.0, 0.0], - center: true, - ..ui::Spec::default() - }, - ); - if pass_sig.clicked { - history.push_snapshot(comp, "Toggle Passthrough"); - comp.toggle_passthrough(node_id); - actions.push(InspectorAction::ParamEdited(node_id)); + settle_edits(ui, &mut cx); + + let mut pages = layout.pages.iter().chain(dynamic_pages); + if chrome::header(ui, pane_id, &mut self.rename, &mut cx) { + cx.reset_defaults(pages.clone().flat_map(|page| page.sections.iter()).flat_map(|s| s.controls.iter())); } - ui.close(); // insp-name-row - // Row 2: Tool class badge + supported/preserved indicator + frame badge - let node_kind = comp.node(node_id).kind.clone(); - let supported = is_supported_tool(&node_kind); - let frame_str = format!("f{:.0}", current_frame); - ui.open( - "insp-meta-row", - ui::Spec { - size: [ui::fill(), ui::px(18.0)], - axis: ui::Axis::X, - gap: 6.0, - ..ui::Spec::default() - }, - ); - ui.leaf( - "insp-kind-badge", - ui::Spec { - size: [ui::fit(), ui::px(18.0)], - text: Some(&node_kind), - font_size: Some(10.0), - medium: true, - color: Some(p.accent), - fill: Some([p.accent[0], p.accent[1], p.accent[2], 0.14]), - border: Some([p.accent[0], p.accent[1], p.accent[2], 0.40]), - radius: 3.0, - pad: [6.0, 0.0], - center: true, - ..ui::Spec::default() - }, - ); - if !supported { - ui.leaf( - "insp-preserved-badge", - ui::Spec { - size: [ui::fit(), ui::px(18.0)], - text: Some("preserved"), - font_size: Some(9.5), - medium: true, - color: Some([0.98, 0.78, 0.40, 1.0]), - fill: Some([0.24, 0.16, 0.06, 0.85]), - border: Some([0.92, 0.64, 0.24, 0.60]), - radius: 3.0, - pad: [5.0, 0.0], - center: true, - ..ui::Spec::default() - }, - ); + let names: Vec<&str> = pages.clone().map(|page| page.name.as_str()).collect(); + let active = self.page.get(&node_id.0).copied().unwrap_or(0).min(names.len().saturating_sub(1)); + if let Some(next) = chrome::tabs(ui, p, &names, active) { + self.page.insert(node_id.0, next); } - ui.leaf( - "insp-spacer", - ui::Spec { - size: [ui::fill(), ui::px(18.0)], - ..ui::Spec::default() - }, - ); - ui.leaf( - "insp-frame", - ui::Spec { - size: [ui::fit(), ui::px(18.0)], - text: Some(&frame_str), - font_size: Some(10.0), - color: Some(p.text_dim), - center: true, - ..ui::Spec::default() - }, - ); - ui.close(); // insp-meta-row - ui.close(); // insp-header - // 2. Scrollable Parameter List ui.open( "insp-scroll", - ui::Spec { - flags: ui::Flags::SCROLL | ui::Flags::CLIP, - size: [ui::fill(), ui::fill()], - axis: ui::Axis::Y, - pad: [10.0, 8.0], - gap: 6.0, - ..ui::Spec::default() - }, + 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() }, ); - - let schema = schema_for_kind(&node_kind); - let mut covered: HashSet<&str> = HashSet::new(); - - for spec in schema { - covered.insert(spec.name); - if let ParamKind::Color { r, g, b, a, .. } = spec.kind { - covered.insert(r); - covered.insert(g); - covered.insert(b); - if let Some(alpha_k) = a { - covered.insert(alpha_k); + if let Some(page) = pages.nth(active) { + for (i, section) in page.sections.iter().enumerate() { + let key = (node_id.0, active, i); + let open = self.sections.get(&key).copied().unwrap_or(section.open); + let spec = ui::CompactDisclosure { body_gap: 2.0, body_pad: [0.0, 2.0], ..ui::CompactDisclosure::new(§ion.title, open) }; + let toggled = ui::compact_disclosure_with(ui, ("sec", key), spec, |ui| { + for def in §ion.controls { + controls::render(ui, &mut cx, def); + } + }); + if toggled { + self.sections.insert(key, !open); } } - self.render_param_spec(ui, pane_id, comp, history, node_id, spec, current_frame, &mut actions); - } - - // Fallback: list all remaining present non-image inputs on the node! - let extra_keys = schemas::extra_input_keys(comp, node_id, &covered); - if !extra_keys.is_empty() { + } else { ui.leaf( - "insp-extra-hdr", - ui::Spec { - size: [ui::fill(), ui::px(18.0)], - text: Some("OTHER INPUTS"), - font_size: Some(9.5), - medium: true, - color: Some(p.text_dim), - ..ui::Spec::default() - }, + "insp-no-controls", + 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() }, ); - for key in extra_keys { - self.render_fallback_input(ui, pane_id, comp, history, node_id, &key, current_frame, &mut actions); - } } - - // Loader / Saver clip filename summary - if matches!(node_kind.as_str(), "Loader" | "Saver") { - let clip_hdr = if node_kind == "Saver" { - "Output Filename" - } else { - "Clip Filename" - }; - let node_ref = comp.node(node_id); - let clip_summary = node_ref - .clips - .first() - .map(|c| c.filename.clone()) - .or_else(|| { - node_ref - .raw - .get_table("Inputs") - .and_then(|i| i.get_table("Clip")) - .and_then(|c| c.get_table("Value")) - .and_then(|v| v.get_str("Filename")) - .map(str::to_owned) - }) - .unwrap_or_else(|| "(no clip)".to_owned()); - ui.open( - "insp-loader-clip", - ui::Spec { - size: [ui::fill(), ui::children()], - axis: ui::Axis::Y, - gap: 3.0, - pad: [6.0, 5.0], - fill: Some(p.panel_bg), - border: Some(p.rule), - radius: 4.0, - ..ui::Spec::default() - }, - ); - ui.leaf( - "clip-lbl", - ui::Spec { - size: [ui::fill(), ui::px(14.0)], - text: Some(clip_hdr), - font_size: Some(10.0), - color: Some(p.text_dim), - ..ui::Spec::default() - }, - ); - ui.leaf( - "clip-path", - ui::Spec { - size: [ui::fill(), ui::fit()], - text: Some(&clip_summary), - font_size: Some(10.5), - overflow: ui::Overflow::Wrap, - color: Some(p.text), - ..ui::Spec::default() - }, - ); - ui.close(); + if matches!(kind.as_str(), "Loader" | "Saver") { + chrome::clip_summary(ui, &cx); } - ui.close(); // insp-scroll - // 3. Footer: EvalStats summary - self.render_stats_footer(ui, stats); - + chrome::footer(ui, p, stats); ui.close(); // pane_id actions } + + fn loading(&self, ui: &mut ui::Ui, p: InspectorPalette, stats: &EvalStats, actions: Vec) -> Vec { + ui.leaf( + "insp-loading", + 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() }, + ); + chrome::footer(ui, p, stats); + ui.close(); + actions + } +} + +/// Commits what loses the keys and closes a rested drag's undo step. +fn settle_edits(ui: &mut ui::Ui, cx: &mut edit::Cx) { + if let Some(last) = cx.edit.last_scrub { + if cx.now.duration_since(last) > edit::SCRUB_GRACE { + cx.history.break_coalescing(); + cx.edit.last_scrub = None; + } else { + ui.wake_after(edit::SCRUB_GRACE); + } + } + if let Some(number) = cx.edit.number.take_if(|n| ui.focused() != Some(n.id)) { + cx.commit_number(number); + } + if cx.edit.text.take_if(|(id, _)| ui.focused() != Some(*id)).is_some() { + cx.history.break_coalescing(); + } +} + +/// The node's `UserControls` (one page per `ICS_ControlPage`) and inputs no catalog row covers. +fn node_pages(comp: &Comp, node: NodeId, layout: &ToolLayout) -> Vec { + let mut by_page: Vec<(String, Vec)> = Vec::new(); + for mut def in dynamic::user_defs(&comp.node(node).raw) { + let name = def.page.take().unwrap_or_default(); + let name = if layout.pages.iter().any(|p| p.name == name) { "User".to_owned() } else { name }; + match by_page.iter_mut().find(|(n, _)| *n == name) { + Some((_, defs)) => defs.push(def), + None => by_page.push((name, vec![def])), + } + } + let user_ids: Vec<&str> = by_page.iter().flat_map(|(_, defs)| defs.iter().map(|d| d.id.as_str())).collect(); + let extras = dynamic::extra_defs(comp, node, |id| layout.covered.contains(id) || user_ids.contains(&id)); + if !extras.is_empty() { + by_page.push(("Other".to_owned(), extras)); + } + by_page.iter().map(|(name, defs)| layout::dynamic_page(name, defs)).collect() } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn curated_schemas_cover_all_major_tools() { - let required = [ - // Original 18 - "Merge", "Transform", "Blur", "Glow", "SoftGlow", "BrightnessContrast", - "ColorCorrector", "Background", "TextPlus", "EllipseMask", "RectangleMask", - "Displace", "Vortex", "FastNoise", "UltraKeyer", "Loader", "Camera3D", "Shape3D", - // Wave 9E additions - "Dissolve", "ChannelBoolean", "Saver", "Switch", "Fuse.Switch", - "TimeStretcher", "TimeSpeed", - "Paint", "PaintMask", "WandMask", "BitmapMask", - "Drip", "Dent", "DaySky", "GridWarp", "PerspectivePositioner", - "sRender", "sEllipse", "sRectangle", "sNGon", "sBoolean", "sTransform", "sOutline", "sGrid", - "MtlBlinn", "MtlPhong", "MtlCookTorrance", - "LightPoint", "LightSpot", "LightDirectional", "LightAmbient", - "Cube3D", "SurfaceFBXMesh", "Custom", - "ErodeDilate", "DirectionalBlur", "VariBlur", "Sharpen", "Shadow", - "ColorGain", "HueCurves", "GamutConvert", "FilmGrain", - ]; - for tool in required { - assert!( - CURATED_TOOL_KINDS.contains(&tool), - "{tool} missing from CURATED_TOOL_KINDS" - ); - let s = schema_for_kind(tool); - assert!(!s.is_empty(), "expected non-empty curated schema for {tool}"); - } - for &tool in CURATED_TOOL_KINDS { - assert!( - !schema_for_kind(tool).is_empty(), - "CURATED_TOOL_KINDS entry {tool} has empty schema" - ); - } - assert!(schema_for_kind("UnknownCustomTool").is_empty()); - } - - #[test] - fn curated_schemas_have_unique_params_and_valid_bounds() { - let mut seen_tools = HashSet::new(); - for &tool in CURATED_TOOL_KINDS { - assert!(seen_tools.insert(tool), "duplicate tool in CURATED_TOOL_KINDS: {tool}"); - let schema = schema_for_kind(tool); - let mut names = HashSet::new(); - for spec in schema { - assert!( - names.insert(spec.name), - "duplicate parameter `{}` in schema for `{tool}`", - spec.name - ); - match spec.kind { - ParamKind::Float { min, max, default, step } => { - assert!(min.is_finite() && max.is_finite() && default.is_finite() && step.is_finite()); - assert!(min <= max, "{tool}.{}: min ({min}) > max ({max})", spec.name); - assert!(step > 0.0, "{tool}.{}: step ({step}) <= 0", spec.name); - assert!( - (min..=max).contains(&default), - "{tool}.{}: default ({default}) outside [{min}, {max}]", - spec.name - ); - } - ParamKind::Vec2 { min, max, default } => { - assert!(min.is_finite() && max.is_finite()); - assert!(min <= max, "{tool}.{}: min ({min}) > max ({max})", spec.name); - for (axis, d) in default.iter().enumerate() { - assert!( - d.is_finite() && (min..=max).contains(d), - "{tool}.{}[{axis}]: default ({d}) outside [{min}, {max}]", - spec.name - ); - } - } - ParamKind::Enum { options, default } => { - assert!(!options.is_empty(), "{tool}.{}: empty Enum options", spec.name); - assert!( - options.contains(&default), - "{tool}.{}: default `{default}` not in options {options:?}", - spec.name - ); - } - ParamKind::IntEnum { options, default } => { - assert!(!options.is_empty(), "{tool}.{}: empty IntEnum options", spec.name); - let mut codes = HashSet::new(); - for &(code, _) in options { - assert!( - codes.insert(code), - "{tool}.{}: duplicate IntEnum code {code}", - spec.name - ); - } - assert!( - codes.contains(&default), - "{tool}.{}: default {default} not in IntEnum options", - spec.name - ); - } - ParamKind::Color { r, g, b, a, default } => { - for ch in [r, g, b].into_iter().chain(a) { - assert!( - names.insert(ch), - "duplicate color channel `{ch}` in schema for `{tool}`" - ); - } - for (idx, c) in default.iter().enumerate() { - assert!( - c.is_finite() && (0.0..=1.0).contains(c), - "{tool}.{}[{idx}]: color default ({c}) outside [0, 1]", - spec.name - ); - } - } - ParamKind::Bool { .. } | ParamKind::Text { .. } => {} - } - } - } - } - - #[test] - fn slider_math_and_clamping() { - assert!((normalize_slider_fraction(0.5, 0.0, 1.0) - 0.5).abs() < 1e-6); - assert!((normalize_slider_fraction(-5.0, 0.0, 1.0) - 0.0).abs() < 1e-6); - assert!((normalize_slider_fraction(10.0, 0.0, 1.0) - 1.0).abs() < 1e-6); - - let v = compute_scrub_value(0.5, 50.0, 100.0, 0.0, 1.0, 1.0); - assert!((v - 1.0).abs() < 1e-6); - let v_fine = compute_scrub_value(0.5, 50.0, 100.0, 0.0, 1.0, 0.1); - assert!((v_fine - 0.55).abs() < 1e-6); - } - - #[test] - fn keyframe_state_transitions() { - let src = r#"Composition { - Tools = ordered() { - BC1 = BrightnessContrast { - Inputs = { Gain = Input { Value = 1.0 } }, - }, - }, - }"#; - let mut comp = Comp::from_fusion_str(src).unwrap(); - let bc = comp.find_node("BC1").unwrap(); - assert_eq!(keyframe_state(&comp, bc, "Gain", 10.0), KeyframeState::Static); - - let sp = comp.set_keyframe(bc, "Gain", 10.0, 1.5).unwrap(); - assert_eq!(keyframe_state(&comp, bc, "Gain", 10.0), KeyframeState::KeyframeAtCurrent); - assert_eq!(keyframe_state(&comp, bc, "Gain", 20.0), KeyframeState::AnimatedOtherFrame); - - assert!(comp.delete_keyframe(&sp, 10.0)); - assert_eq!(keyframe_state(&comp, bc, "Gain", 10.0), KeyframeState::Static); - } -} +mod tests; diff --git a/crates/app/src/inspector/rows.rs b/crates/app/src/inspector/rows.rs deleted file mode 100644 index 5f573ad66f35289baf7d0551be693f7553532e3d..0000000000000000000000000000000000000000 --- a/crates/app/src/inspector/rows.rs +++ /dev/null @@ -1,591 +0,0 @@ -//! Parameter row renderers for [`InspectorState`]: float, vec2, bool, enum, int-enum, -//! combo, RGBA color group, and text rows. - -use super::super::{InspectorAction, InspectorState}; -use super::{ - KeyframeState, combo_cycle_index, enum_option_index, int_enum_lookup, keyframe_state, -}; -use model::{Comp, CompHistory, NodeId, ParamValue}; - -impl InspectorState { - #[allow(clippy::too_many_arguments)] - pub(super) fn render_float_row( - &mut self, - ui: &mut ui::Ui, - pane_id: ui::Id, - comp: &mut Comp, - history: &mut CompHistory, - node_id: NodeId, - input_name: &str, - label: &str, - min: f64, - max: f64, - default: f64, - current_frame: f64, - actions: &mut Vec, - ) { - let cur_val = comp.eval_number(comp.node(node_id), input_name, current_frame, default, &self.expr); - let has_expr = comp - .node(node_id) - .inputs - .get(input_name) - .and_then(|b| b.expression.as_ref()) - .is_some(); - let kf_state = keyframe_state(comp, node_id, input_name, current_frame); - let p = self.palette; - - ui.open( - ("row-f", node_id.0, input_name), - ui::Spec { - size: [ui::fill(), ui::px(22.0)], - axis: ui::Axis::X, - gap: 4.0, - ..ui::Spec::default() - }, - ); - - // Label - ui.leaf( - "lbl", - ui::Spec { - size: [ui::px(86.0), ui::fill()], - text: Some(label), - font_size: Some(10.5), - overflow: ui::Overflow::Ellipsis, - color: Some(p.text_dim), - ..ui::Spec::default() - }, - ); - - // Expression `=` badge if present - if has_expr { - render_expr_badge(ui); - } - - // Scrub slider - let slider_id = pane_id.child(("sld", node_id.0, input_name)); - let drag_key = format!("{}:{input_name}", node_id.0); - if let Some(new_val) = self.scrub_slider( - ui, - slider_id, - &drag_key, - node_id, - cur_val, - min, - max, - default, - history, - comp, - input_name, - ) { - if kf_state != KeyframeState::Static { - let _ = comp.set_keyframe(node_id, input_name, current_frame, new_val); - actions.push(InspectorAction::KeyframeEdited(node_id)); - } else { - comp.set_input_value(node_id, input_name, ParamValue::Number(new_val)); - actions.push(InspectorAction::ParamEdited(node_id)); - } - } - - // Reset button (small dot/arrow when non-default) - let is_default = (cur_val - default).abs() < 1e-4; - if !is_default { - let rst = ui.leaf( - ("rst", node_id.0, input_name), - ui::Spec { - cursor: Some(winit::window::CursorIcon::Pointer), - flags: ui::Flags::CLICKABLE, - size: [ui::px(18.0), ui::px(20.0)], - text: Some("↺"), - font_size: Some(10.5), - color: Some(p.text_dim), - hover_fill: Some(p.panel_bg), - radius: 3.0, - center: true, - ..ui::Spec::default() - }, - ); - if rst.clicked { - history.push_snapshot(comp, format!("Reset {label}")); - if kf_state != KeyframeState::Static { - let _ = comp.set_keyframe(node_id, input_name, current_frame, default); - actions.push(InspectorAction::KeyframeEdited(node_id)); - } else { - comp.set_input_value(node_id, input_name, ParamValue::Number(default)); - actions.push(InspectorAction::ParamEdited(node_id)); - } - } - } - - // Keyframe diamond button (`◆`) - if self.keyframe_button(ui, ("kf", node_id.0, input_name), kf_state) { - self.toggle_keyframe(comp, history, node_id, input_name, current_frame, cur_val, kf_state, actions); - } - - ui.close(); - } - - #[allow(clippy::too_many_arguments)] - pub(super) fn render_vec2_row( - &mut self, - ui: &mut ui::Ui, - pane_id: ui::Id, - comp: &mut Comp, - history: &mut CompHistory, - node_id: NodeId, - input_name: &str, - label: &str, - min: f64, - max: f64, - default: [f64; 2], - current_frame: f64, - actions: &mut Vec, - ) { - let cur = comp.eval_point(comp.node(node_id), input_name, current_frame, default, &self.expr); - let has_expr = comp - .node(node_id) - .inputs - .get(input_name) - .and_then(|b| b.expression.as_ref()) - .is_some(); - - ui.open( - ("row-v2", node_id.0, input_name), - ui::Spec { - size: [ui::fill(), ui::px(22.0)], - axis: ui::Axis::X, - gap: 4.0, - ..ui::Spec::default() - }, - ); - ui.leaf( - "lbl", - ui::Spec { - size: [ui::px(86.0), ui::fill()], - text: Some(label), - font_size: Some(10.5), - overflow: ui::Overflow::Ellipsis, - color: Some(self.palette.text_dim), - ..ui::Spec::default() - }, - ); - if has_expr { - render_expr_badge(ui); - } - - let x_id = pane_id.child(("v2x", node_id.0, input_name)); - let x_key = format!("{}:{input_name}:x", node_id.0); - if let Some(nx) = self.scrub_slider( - ui, - x_id, - &x_key, - node_id, - cur[0], - min, - max, - default[0], - history, - comp, - input_name, - ) { - comp.set_input_value(node_id, input_name, ParamValue::Point([nx, cur[1]])); - actions.push(InspectorAction::ParamEdited(node_id)); - } - - let y_id = pane_id.child(("v2y", node_id.0, input_name)); - let y_key = format!("{}:{input_name}:y", node_id.0); - if let Some(ny) = self.scrub_slider( - ui, - y_id, - &y_key, - node_id, - cur[1], - min, - max, - default[1], - history, - comp, - input_name, - ) { - comp.set_input_value(node_id, input_name, ParamValue::Point([cur[0], ny])); - actions.push(InspectorAction::ParamEdited(node_id)); - } - - ui.close(); - } - - #[allow(clippy::too_many_arguments)] - pub(super) fn render_bool_row( - &mut self, - ui: &mut ui::Ui, - comp: &mut Comp, - history: &mut CompHistory, - node_id: NodeId, - input_name: &str, - label: &str, - default: bool, - actions: &mut Vec, - ) { - let checked = comp - .node(node_id) - .static_number(input_name) - .map(|v| v >= 0.5) - .unwrap_or(default); - let p = self.palette; - - ui.open( - ("row-b", node_id.0, input_name), - ui::Spec { - size: [ui::fill(), ui::px(22.0)], - axis: ui::Axis::X, - gap: 6.0, - ..ui::Spec::default() - }, - ); - ui.leaf( - "lbl", - ui::Spec { - size: [ui::px(86.0), ui::fill()], - text: Some(label), - font_size: Some(10.5), - overflow: ui::Overflow::Ellipsis, - color: Some(p.text_dim), - ..ui::Spec::default() - }, - ); - let fill = if checked { - [p.accent[0], p.accent[1], p.accent[2], 0.28] - } else { - p.panel_bg - }; - let border = if checked { p.accent } else { p.rule }; - let sig = ui.leaf( - ("chk", node_id.0, input_name), - ui::Spec { - cursor: Some(winit::window::CursorIcon::Pointer), - flags: ui::Flags::CLICKABLE, - size: [ui::px(54.0), ui::px(20.0)], - text: Some(if checked { "✓ On" } else { "Off" }), - font_size: Some(10.5), - medium: checked, - color: Some(if checked { p.text } else { p.text_dim }), - fill: Some(fill), - border: Some(border), - radius: 4.0, - center: true, - ..ui::Spec::default() - }, - ); - if sig.clicked { - history.push_snapshot(comp, format!("Toggle {label}")); - let next = if checked { 0.0 } else { 1.0 }; - comp.set_input_value(node_id, input_name, ParamValue::Number(next)); - actions.push(InspectorAction::ParamEdited(node_id)); - } - ui.close(); - } - - #[allow(clippy::too_many_arguments)] - pub(super) fn render_enum_row( - &mut self, - ui: &mut ui::Ui, - comp: &mut Comp, - history: &mut CompHistory, - node_id: NodeId, - input_name: &str, - label: &str, - options: &'static [&'static str], - default: &'static str, - actions: &mut Vec, - ) { - let cur = comp - .node(node_id) - .static_str(input_name) - .unwrap_or(default) - .to_owned(); - let idx = enum_option_index(options, &cur); - if let Some(next_idx) = self.render_combo_row(ui, node_id, input_name, label, &cur, idx, options.len()) { - history.push_snapshot(comp, format!("Set {label}")); - comp.set_input_value(node_id, input_name, ParamValue::FuId(options[next_idx].to_owned())); - actions.push(InspectorAction::ParamEdited(node_id)); - } - } - - #[allow(clippy::too_many_arguments)] - pub(super) fn render_int_enum_row( - &mut self, - ui: &mut ui::Ui, - comp: &mut Comp, - history: &mut CompHistory, - node_id: NodeId, - input_name: &str, - label: &str, - options: &'static [(i32, &'static str)], - default: i32, - actions: &mut Vec, - ) { - let cur_val = comp - .node(node_id) - .static_number(input_name) - .map(|v| v.round() as i32) - .unwrap_or(default); - let (idx, cur_label) = int_enum_lookup(options, cur_val); - if let Some(next_idx) = self.render_combo_row(ui, node_id, input_name, label, &cur_label, idx, options.len()) { - history.push_snapshot(comp, format!("Set {label}")); - comp.set_input_value(node_id, input_name, ParamValue::Number(f64::from(options[next_idx].0))); - actions.push(InspectorAction::ParamEdited(node_id)); - } - } - - #[allow(clippy::too_many_arguments)] - fn render_combo_row( - &self, - ui: &mut ui::Ui, - node_id: NodeId, - input_name: &str, - label: &str, - cur_label: &str, - cur_idx: usize, - option_count: usize, - ) -> Option { - let p = self.palette; - - ui.open( - ("row-e", node_id.0, input_name), - ui::Spec { - size: [ui::fill(), ui::px(22.0)], - axis: ui::Axis::X, - gap: 6.0, - ..ui::Spec::default() - }, - ); - ui.leaf( - "lbl", - ui::Spec { - size: [ui::px(86.0), ui::fill()], - text: Some(label), - font_size: Some(10.5), - overflow: ui::Overflow::Ellipsis, - color: Some(p.text_dim), - ..ui::Spec::default() - }, - ); - let btn_lbl = format!("{cur_label} ▾"); - let sig = ui.leaf( - ("enum", node_id.0, input_name), - ui::Spec { - cursor: Some(winit::window::CursorIcon::Pointer), - flags: ui::Flags::CLICKABLE, - size: [ui::fill(), ui::px(20.0)], - text: Some(&btn_lbl), - font_size: Some(10.5), - color: Some(p.text), - fill: Some(p.panel_bg), - border: Some(p.rule), - hover_border: Some(p.accent), - radius: 4.0, - pad: [6.0, 0.0], - ..ui::Spec::default() - }, - ); - let next = if sig.clicked { - combo_cycle_index(cur_idx, option_count, ui.modifiers().shift_key()) - } else { - None - }; - ui.close(); - next - } - - #[allow(clippy::too_many_arguments)] - pub(super) fn render_color_group( - &mut self, - ui: &mut ui::Ui, - pane_id: ui::Id, - comp: &mut Comp, - history: &mut CompHistory, - node_id: NodeId, - label: &str, - r_key: &'static str, - g_key: &'static str, - b_key: &'static str, - a_key: Option<&'static str>, - default: [f64; 4], - current_frame: f64, - actions: &mut Vec, - ) { - let rv = comp.eval_number(comp.node(node_id), r_key, current_frame, default[0], &self.expr); - let gv = comp.eval_number(comp.node(node_id), g_key, current_frame, default[1], &self.expr); - let bv = comp.eval_number(comp.node(node_id), b_key, current_frame, default[2], &self.expr); - let _av = a_key - .map(|ak| comp.eval_number(comp.node(node_id), ak, current_frame, default[3], &self.expr)) - .unwrap_or(default[3]); - let swatch = [ - rv.clamp(0.0, 1.0) as f32, - gv.clamp(0.0, 1.0) as f32, - bv.clamp(0.0, 1.0) as f32, - 1.0, - ]; - let p = self.palette; - - ui.open( - ("grp-col", node_id.0, label), - ui::Spec { - size: [ui::fill(), ui::children()], - axis: ui::Axis::Y, - gap: 4.0, - pad: [6.0, 5.0], - fill: Some(p.panel_bg), - border: Some(p.rule), - radius: 4.0, - ..ui::Spec::default() - }, - ); - // Swatch header - ui.open( - "col-hdr", - ui::Spec { - size: [ui::fill(), ui::px(18.0)], - axis: ui::Axis::X, - gap: 6.0, - ..ui::Spec::default() - }, - ); - ui.leaf( - "col-lbl", - ui::Spec { - size: [ui::px(80.0), ui::fill()], - text: Some(label), - font_size: Some(10.5), - medium: true, - color: Some(p.text), - ..ui::Spec::default() - }, - ); - ui.leaf( - "col-swatch", - ui::Spec { - size: [ui::fill(), ui::px(16.0)], - fill: Some(swatch), - border: Some(p.rule), - radius: 3.0, - ..ui::Spec::default() - }, - ); - ui.close(); - - self.render_float_row(ui, pane_id, comp, history, node_id, r_key, "Red", 0.0, 1.0, default[0], current_frame, actions); - self.render_float_row(ui, pane_id, comp, history, node_id, g_key, "Green", 0.0, 1.0, default[1], current_frame, actions); - self.render_float_row(ui, pane_id, comp, history, node_id, b_key, "Blue", 0.0, 1.0, default[2], current_frame, actions); - if let Some(ak) = a_key { - self.render_float_row(ui, pane_id, comp, history, node_id, ak, "Alpha", 0.0, 1.0, default[3], current_frame, actions); - } - ui.close(); - } - - #[allow(clippy::too_many_arguments)] - pub(super) fn render_text_row( - &mut self, - ui: &mut ui::Ui, - pane_id: ui::Id, - comp: &mut Comp, - history: &mut CompHistory, - node_id: NodeId, - input_name: &str, - label: &str, - default: &str, - actions: &mut Vec, - ) { - let field_id = pane_id.child(("txt", node_id.0, input_name)); - if self.text_focus == Some(field_id) && ui.focused() != Some(field_id) { - self.text_focus = None; - history.break_coalescing(); - } - let key = (node_id.0, input_name.to_owned()); - let model_val = comp - .node(node_id) - .static_str(input_name) - .unwrap_or(default) - .to_owned(); - let p = self.palette; - let buf = self.text_bufs.entry(key).or_insert_with(|| model_val.clone()); - if ui.focused() != Some(field_id) && *buf != model_val { - *buf = model_val.clone(); - } - let prev = buf.clone(); - - ui.open( - ("row-t", node_id.0, input_name), - ui::Spec { - size: [ui::fill(), ui::px(24.0)], - axis: ui::Axis::X, - gap: 6.0, - ..ui::Spec::default() - }, - ); - ui.leaf( - "lbl", - ui::Spec { - size: [ui::px(86.0), ui::fill()], - text: Some(label), - font_size: Some(10.5), - overflow: ui::Overflow::Ellipsis, - color: Some(p.text_dim), - ..ui::Spec::default() - }, - ); - let sig = ui::text_field( - ui, - field_id, - buf, - label, - ui::Spec { - size: [ui::fill(), ui::px(22.0)], - font_size: Some(11.0), - fill: Some(p.panel_bg), - border: Some(p.rule), - hover_border: Some(p.accent), - radius: 4.0, - pad: [6.0, 2.0], - ..ui::Spec::default() - }, - ); - if ui.focused() == Some(field_id) { - self.text_focus = Some(field_id); - } - let committed = sig.events.iter().any(|ev| { - matches!(ev, ui::Event::Key { key: winit::keyboard::Key::Named(winit::keyboard::NamedKey::Enter), .. }) - }); - if *buf != prev { - history.push_coalesced( - comp, - format!("Edit {label}"), - format!("text:{}:{input_name}", node_id.0), - ); - comp.set_input_value(node_id, input_name, ParamValue::Text(buf.clone())); - actions.push(InspectorAction::ParamEdited(node_id)); - } - if committed { - history.break_coalescing(); - } - ui.close(); - } -} - -fn render_expr_badge(ui: &mut ui::Ui) { - ui.leaf( - "expr-badge", - ui::Spec { - size: [ui::px(16.0), ui::px(18.0)], - text: Some("="), - font_size: Some(10.5), - bold: true, - color: Some([0.36, 0.88, 0.92, 1.0]), - fill: Some([0.10, 0.24, 0.28, 0.85]), - border: Some([0.32, 0.78, 0.86, 0.65]), - radius: 3.0, - center: true, - ..ui::Spec::default() - }, - ); -} diff --git a/crates/app/src/inspector/schemas.rs b/crates/app/src/inspector/schemas.rs index 99fe52a490c16df6198f0943287f363fe5d1a926..2dfd29cf33e2661fc776c86c7629c4f23d4e1c44 100644 --- a/crates/app/src/inspector/schemas.rs +++ b/crates/app/src/inspector/schemas.rs @@ -1,7 +1,4 @@ -//! Curated Fusion 21.1 parameter schemas and fallback input discovery for the Inspector. - -use model::{Comp, NodeId}; -use std::collections::HashSet; +//! Curated Fusion 21.1 parameter schemas: the layout for tools the introspected catalog lacks. #[derive(Clone, Copy, Debug, PartialEq)] pub enum ParamKind { @@ -27,34 +24,6 @@ pub struct ParamSpec { pub kind: ParamKind, } -/// Collects and sorts remaining non-image inputs on `node_id` not covered by its curated schema. -pub(super) fn extra_input_keys(comp: &Comp, node_id: NodeId, covered: &HashSet<&str>) -> Vec { - let mut extra_keys: Vec = comp - .node(node_id) - .inputs - .iter() - .filter_map(|(k, b)| { - if covered.contains(k.as_str()) { - return None; - } - // Skip image/node connections unless they also have a value or spline - let is_node_conn = b - .source_op - .as_deref() - .is_some_and(|op| comp.node_by_name.contains_key(op)); - if is_node_conn && b.value.is_none() { - return None; - } - if b.value.is_none() && b.expression.is_none() && b.source_op.is_none() { - return None; - } - Some(k.clone()) - }) - .collect(); - extra_keys.sort(); - extra_keys -} - pub fn infer_float_range(name: &str, val: f64) -> (f64, f64) { let lower = name.to_ascii_lowercase(); if lower.contains("angle") || lower.contains("rotate") { diff --git a/crates/app/src/inspector/tests.rs b/crates/app/src/inspector/tests.rs new file mode 100644 index 0000000000000000000000000000000000000000..3787179fa1471cedb1c6c01fb4401b90ac75b8c9 --- /dev/null +++ b/crates/app/src/inspector/tests.rs @@ -0,0 +1,442 @@ +//! Registry consistency: curated schemas, the parsed Fusion catalog and its grouping. + +use super::schemas::{ParamKind, schema_for_kind}; +use super::CURATED_TOOL_KINDS; +use std::collections::HashSet; + +#[test] +fn curated_schemas_cover_all_major_tools() { + let required = [ + // Original 18 + "Merge", "Transform", "Blur", "Glow", "SoftGlow", "BrightnessContrast", + "ColorCorrector", "Background", "TextPlus", "EllipseMask", "RectangleMask", + "Displace", "Vortex", "FastNoise", "UltraKeyer", "Loader", "Camera3D", "Shape3D", + // Wave 9E additions + "Dissolve", "ChannelBoolean", "Saver", "Switch", "Fuse.Switch", + "TimeStretcher", "TimeSpeed", + "Paint", "PaintMask", "WandMask", "BitmapMask", + "Drip", "Dent", "DaySky", "GridWarp", "PerspectivePositioner", + "sRender", "sEllipse", "sRectangle", "sNGon", "sBoolean", "sTransform", "sOutline", "sGrid", + "MtlBlinn", "MtlPhong", "MtlCookTorrance", + "LightPoint", "LightSpot", "LightDirectional", "LightAmbient", + "Cube3D", "SurfaceFBXMesh", "Custom", + "ErodeDilate", "DirectionalBlur", "VariBlur", "Sharpen", "Shadow", + "ColorGain", "HueCurves", "GamutConvert", "FilmGrain", + ]; + for tool in required { + assert!( + CURATED_TOOL_KINDS.contains(&tool), + "{tool} missing from CURATED_TOOL_KINDS" + ); + let s = schema_for_kind(tool); + assert!(!s.is_empty(), "expected non-empty curated schema for {tool}"); + } + for &tool in CURATED_TOOL_KINDS { + assert!( + !schema_for_kind(tool).is_empty(), + "CURATED_TOOL_KINDS entry {tool} has empty schema" + ); + } + assert!(schema_for_kind("UnknownCustomTool").is_empty()); +} + +#[test] +fn curated_schemas_have_unique_params_and_valid_bounds() { + let mut seen_tools = HashSet::new(); + for &tool in CURATED_TOOL_KINDS { + assert!(seen_tools.insert(tool), "duplicate tool in CURATED_TOOL_KINDS: {tool}"); + let schema = schema_for_kind(tool); + let mut names = HashSet::new(); + for spec in schema { + assert!( + names.insert(spec.name), + "duplicate parameter `{}` in schema for `{tool}`", + spec.name + ); + match spec.kind { + ParamKind::Float { min, max, default, step } => { + assert!(min.is_finite() && max.is_finite() && default.is_finite() && step.is_finite()); + assert!(min <= max, "{tool}.{}: min ({min}) > max ({max})", spec.name); + assert!(step > 0.0, "{tool}.{}: step ({step}) <= 0", spec.name); + assert!( + (min..=max).contains(&default), + "{tool}.{}: default ({default}) outside [{min}, {max}]", + spec.name + ); + } + ParamKind::Vec2 { min, max, default } => { + assert!(min.is_finite() && max.is_finite()); + assert!(min <= max, "{tool}.{}: min ({min}) > max ({max})", spec.name); + for (axis, d) in default.iter().enumerate() { + assert!( + d.is_finite() && (min..=max).contains(d), + "{tool}.{}[{axis}]: default ({d}) outside [{min}, {max}]", + spec.name + ); + } + } + ParamKind::Enum { options, default } => { + assert!(!options.is_empty(), "{tool}.{}: empty Enum options", spec.name); + assert!( + options.contains(&default), + "{tool}.{}: default `{default}` not in options {options:?}", + spec.name + ); + } + ParamKind::IntEnum { options, default } => { + assert!(!options.is_empty(), "{tool}.{}: empty IntEnum options", spec.name); + let mut codes = HashSet::new(); + for &(code, _) in options { + assert!( + codes.insert(code), + "{tool}.{}: duplicate IntEnum code {code}", + spec.name + ); + } + assert!( + codes.contains(&default), + "{tool}.{}: default {default} not in IntEnum options", + spec.name + ); + } + ParamKind::Color { r, g, b, a, default } => { + for ch in [r, g, b].into_iter().chain(a) { + assert!( + names.insert(ch), + "duplicate color channel `{ch}` in schema for `{tool}`" + ); + } + for (idx, c) in default.iter().enumerate() { + assert!( + c.is_finite() && (0.0..=1.0).contains(c), + "{tool}.{}[{idx}]: color default ({c}) outside [0, 1]", + spec.name + ); + } + } + ParamKind::Bool { .. } | ParamKind::Text { .. } => {} + } + } + } +} + +mod catalog_layout { + use super::super::catalog::{self, catalog}; + use super::super::layout::{ControlDef, Kind, SECTIONS, ToolLayout}; + use super::super::{InspectorState, dynamic}; + use super::{CURATED_TOOL_KINDS, HashSet, schema_for_kind}; + use model::{Comp, CompHistory}; + use std::time::Instant; + + fn controls(layout: &ToolLayout) -> impl Iterator { + layout.pages.iter().flat_map(|p| &p.sections).flat_map(|s| &s.controls) + } + + fn find<'a>(tool: &str, first_id: &str) -> &'a ControlDef { + let layout = &catalog()[tool].layout; + let found = controls(layout).find(|c| c.channels[0].id == first_id); + found.unwrap_or_else(|| panic!("{tool} has no row starting at {first_id}")) + } + + fn ids(def: &ControlDef) -> Vec<&str> { + def.channels.iter().map(|c| c.id.as_str()).collect() + } + + #[test] + fn catalog_has_every_introspected_tool() { + let cat = catalog(); + assert!(cat.len() > 100, "only {} tools", cat.len()); + for tool in ["Merge", "Transform", "Background", "TextPlus", "Blur", "MacroOperator", "GroupOperator"] { + assert!(cat.contains_key(tool), "{tool} missing from catalog"); + } + assert!(catalog::ready().is_some()); + } + + #[test] + fn rgba_color_inputs_fuse_into_one_row() { + let def = find("Background", "TopLeftRed"); + assert_eq!((def.kind, def.label.as_str()), (Kind::Color, "Top Left")); + assert_eq!(ids(def), ["TopLeftRed", "TopLeftGreen", "TopLeftBlue", "TopLeftAlpha"]); + assert_eq!(def.channels[3].default[0], 1.0); + + let def = find("TextPlus", "Red1"); + assert_eq!((def.kind, ids(def)), (Kind::Color, vec!["Red1", "Green1", "Blue1", "Alpha1"])); + + // Object/Material IDs share a color group but are lone ids, not RGB. + assert_eq!(find("Merge", "ObjectID").kind, Kind::Slider); + } + + #[test] + fn range_inputs_fuse_into_one_row() { + let def = find("TextPlus", "Start"); + assert_eq!((def.kind, ids(def)), (Kind::Range, vec!["Start", "End"])); + assert_eq!(def.label, "Write On Start / End"); + assert_eq!(ids(find("Merge", "MaskLow")), ["MaskLow", "MaskHigh"]); + // Two Solid/Garbage ranges in one group stay two rows. + let keyer = controls(&catalog()["UltraKeyer"].layout).filter(|c| c.kind == Kind::Range && c.channels[0].id.contains(".MaskLow")); + assert_eq!(keyer.count(), 2); + } + + #[test] + fn angles_are_screws_and_toggles_group() { + assert_eq!(find("Merge", "Angle").kind, Kind::Screw); + assert_eq!(find("Transform", "Angle").kind, Kind::Screw); + let process = find("Merge", "ProcessRed"); + assert_eq!((process.kind, process.label.as_str()), (Kind::Toggles, "Process")); + assert_eq!(process.entries, ["Red", "Green", "Blue", "Alpha"]); + assert_eq!(find("Merge", "Center").kind, Kind::Point); + assert_eq!(find("Merge", "ApplyMode").kind, Kind::Combo); + assert!(find("Merge", "ApplyMode").fuid); + assert_eq!(find("Background", "UseGPU").kind, Kind::Segmented); + } + + #[test] + fn pages_follow_fusion_tab_order() { + let names = |tool: &str| -> Vec<&str> { catalog()[tool].layout.pages.iter().map(|p| p.name.as_str()).collect() }; + assert_eq!(names("Merge"), ["Merge", "Channels", "Settings"]); + assert_eq!(names("Transform"), ["Controls", "Settings"]); + assert_eq!(names("TextPlus"), ["Text", "Layout", "Transform", "Shading", "Image", "Settings"]); + let merge = &catalog()["Merge"].layout.pages[0]; + assert_eq!(merge.sections.iter().map(|s| s.title.as_str()).collect::>(), ["Merge", "Reference Size"]); + assert!(!merge.sections[1].open); + } + + #[test] + fn section_markers_name_real_inputs() { + for (tools, id, title, _) in SECTIONS { + let hits = |tool: &str| controls(&catalog()[tool].layout).any(|c| c.channels[0].id == *id); + if tools.is_empty() { + assert!(catalog().keys().any(|t| hits(t)), "no tool has `{id}` for section `{title}`"); + } + for tool in *tools { + assert!(hits(tool), "{tool} has no `{id}` row for section `{title}`"); + } + } + } + + #[test] + fn every_layout_is_well_formed() { + for (tool, entry) in catalog() { + let mut seen = HashSet::new(); + for def in controls(&entry.layout) { + for ch in &def.channels { + assert!(seen.insert(ch.id.as_str()), "{tool}: `{}` appears in two rows", ch.id); + assert!(entry.layout.covered.contains(&ch.id), "{tool}: `{}` not covered", ch.id); + assert!(ch.scale[0] < ch.scale[1] && ch.scale.iter().all(|v| v.is_finite()), "{tool}.{} scale {:?}", ch.id, ch.scale); + } + if matches!(def.kind, Kind::Segmented | Kind::Combo) { + assert!(def.default_index < def.entries.len(), "{tool}.{}: default index out of range", def.label); + } + let n = def.channels.len(); + let ok = match def.kind { + Kind::Range => n == 2, + Kind::Color => (3..=4).contains(&n), + Kind::Toggles => n == def.entries.len(), + _ => n == 1, + }; + assert!(ok, "{tool}.{}: {n} channels", def.label); + } + } + } + + #[test] + fn curated_kinds_have_pages_in_catalog_or_fallback() { + for &tool in CURATED_TOOL_KINDS { + let layout = match catalog().get(tool) { + Some(entry) => &entry.layout, + None => &dynamic::curated_layout(tool).unwrap_or_else(|| panic!("{tool}: no catalog entry and no curated layout")), + }; + assert!(controls(layout).next().is_some(), "{tool} has no rows"); + } + let fallback = dynamic::curated_layout("Fuse.Switch").expect("curated fallback"); + assert!(fallback.covered.contains(schema_for_kind("Fuse.Switch")[0].name)); + } + + #[test] + fn user_controls_become_rows() { + let comp = Comp::from_fusion_str( + r#"Composition { + Tools = ordered() { + Mac = MacroOperator { + UserControls = ordered() { + Gain = { LINKS_Name = "Gain", LINKID_DataType = "Number", INPID_InputControl = "SliderControl", INP_Default = 0.5, INP_MaxScale = 4, ICS_ControlPage = "Look" }, + Mode = { LINKID_DataType = "Number", INPID_InputControl = "ComboControl", INP_Default = 1, { CCS_AddString = "Off" }, { CCS_AddString = "On" } }, + Spot = { LINKID_DataType = "Point", INPID_InputControl = "OffsetControl", INP_DefaultX = 0.25, INP_DefaultY = 0.75 }, + }, + }, + }, + }"#, + ) + .expect("comp"); + let defs = dynamic::user_defs(&comp.node(comp.find_node("Mac").unwrap()).raw); + assert_eq!(defs.len(), 3); + assert_eq!((defs[0].page.as_deref(), defs[0].scale), (Some("Look"), [0.0, 4.0])); + assert_eq!((defs[1].entries.len(), defs[1].default[0]), (2, 1.0)); + assert_eq!(defs[2].default, [0.25, 0.75]); + let page = super::super::layout::dynamic_page("Look", &defs); + let kinds: Vec<_> = page.sections[0].controls.iter().map(|c| c.kind).collect(); + assert_eq!(kinds, [Kind::Slider, Kind::Combo, Kind::Point]); + } + + /// Every tool, every page, builds under the frame guard without panicking. + #[test] + fn builds_every_page_of_every_tool() { + catalog(); + let theme = ui::Theme::dark(); + let mut state = InspectorState::new(&theme); + let mut ui = ui::Ui::new(theme); + let (mut history, stats) = (CompHistory::default(), engine::EvalStats::default()); + for (tool, entry) in catalog() { + let mut comp = Comp::from_fusion_str(&format!("Composition {{ Tools = ordered() {{ N = {tool} {{}}, }}, }}")).expect("comp"); + let node = comp.find_node("N").expect("node"); + for page in 0..entry.layout.pages.len().max(1) { + state.page.insert(node.0, page); + ui.begin([360.0, 900.0], 1.0, Instant::now()); + state.build_ui(&mut ui, ui::Id::ROOT.child("pane"), &mut comp, &mut history, Some(node), 0.0, &stats); + ui.end(); + } + } + } + + struct Harness { + ui: ui::Ui, + state: InspectorState, + comp: Comp, + history: CompHistory, + node: model::NodeId, + at: Instant, + } + + const PANE: &str = "pane"; + + impl Harness { + fn new(tool: &str, page: usize) -> Self { + catalog(); + let theme = ui::Theme::dark(); + let mut ui = ui::Ui::new(theme.clone()); + ui.set_reduce_motion(true); + let mut state = InspectorState::new(&theme); + let comp = Comp::from_fusion_str(&format!("Composition {{ Tools = ordered() {{ N = {tool} {{}}, }}, }}")).expect("comp"); + let node = comp.find_node("N").expect("node"); + state.page.insert(node.0, page); + let mut h = Self { ui, state, comp, history: CompHistory::default(), node, at: Instant::now() }; + h.frame(0); + h + } + + fn frame(&mut self, advance_ms: u64) { + self.at += std::time::Duration::from_millis(advance_ms); + self.ui.begin([360.0, 900.0], 1.0, self.at); + let pane = ui::Id::ROOT.child(PANE); + self.state.build_ui(&mut self.ui, pane, &mut self.comp, &mut self.history, Some(self.node), 0.0, &engine::EvalStats::default()); + self.ui.end(); + } + + /// Where the row `key`'s child `part` sits: the first section of the active page. + fn rect(&self, page: usize, key: &str, part: impl std::hash::Hash) -> [f32; 4] { + let section = ui::Id::ROOT.child(PANE).child("insp-scroll").child(("sec", (self.node.0, page, 0usize))); + let row = section.child("body").child(("row", self.node.0, key)); + self.ui.laid_out(row.child(part)).unwrap_or_else(|| panic!("no `{key}` row in page {page}")) + } + + fn click(&mut self, at: [f32; 2]) { + use winit::event::MouseButton::Left; + self.ui.event(ui::Event::PointerMoved(at)); + self.ui.event(ui::Event::Button { button: Left, pressed: true, at: self.at }); + self.frame(16); + self.ui.event(ui::Event::Button { button: Left, pressed: false, at: self.at }); + self.frame(16); + self.frame(16); + } + + fn number(&self, id: &str) -> Option { + self.comp.node(self.node).static_number(id) + } + } + + fn center(r: [f32; 4]) -> [f32; 2] { + [(r[0] + r[2]) / 2.0, (r[1] + r[3]) / 2.0] + } + + #[test] + fn slider_drag_edits_and_undoes_as_one_step() { + let mut h = Harness::new("Merge", 2); + let track = h.rect(2, "Blend", ("sld", h.node.0, "Blend")); + h.click([track[0] + (track[2] - track[0]) * 0.25, (track[1] + track[3]) / 2.0]); + let value = h.number("Blend").expect("slider wrote Blend"); + assert!(value < 0.5, "clicking a quarter along the track set {value}"); + + h.frame(600); + assert!(h.history.undo(&mut h.comp)); + assert_eq!(h.number("Blend"), None); + } + + #[test] + fn checkbox_and_keyframe_diamond_edit_with_undo() { + let mut h = Harness::new("Merge", 2); + let check = h.rect(2, "ProcessWhenBlendIs00", ("chk", h.node.0, "ProcessWhenBlendIs00")); + h.click(center(check)); + assert_eq!(h.number("ProcessWhenBlendIs00"), Some(1.0)); + + let diamond = h.rect(2, "Blend", "kf"); + h.click(center(diamond)); + let state = |h: &Harness| super::super::keyframe_state(&h.comp, h.node, "Blend", 0.0); + assert_eq!(state(&h), super::super::KeyframeState::KeyframeAtCurrent); + h.click(center(diamond)); + assert_eq!(state(&h), super::super::KeyframeState::Static); + assert!(h.history.undo(&mut h.comp)); + assert_eq!(state(&h), super::super::KeyframeState::KeyframeAtCurrent); + } + + #[test] + fn color_channel_slider_and_typed_number_commit() { + let mut h = Harness::new("Background", 0); + let track = h.rect(0, "TopLeftRed", ("clr-sld", h.node.0, "TopLeftRed")); + h.click([track[0] + (track[2] - track[0]) * 0.75, (track[1] + track[3]) / 2.0]); + let slid = h.number("TopLeftRed").expect("channel slider wrote the red channel"); + assert!(slid > 0.5, "clicking three quarters along the track set {slid}"); + + let well = h.rect(0, "TopLeftGreen", ("num", h.node.0, "TopLeftGreen", None::)); + h.click(center(well)); + for ch in "0.3".chars() { + let key = winit::keyboard::Key::Character(ch.to_string().into()); + h.ui.event(ui::Event::Key { key, text: Some(ch.to_string()), modifiers: Default::default() }); + h.frame(16); + } + let enter = winit::keyboard::Key::Named(winit::keyboard::NamedKey::Enter); + h.ui.event(ui::Event::Key { key: enter, text: None, modifiers: Default::default() }); + h.frame(16); + h.frame(16); + let typed = h.number("TopLeftGreen").expect("typed value committed"); + assert!((typed - 0.3).abs() < 1e-9, "typed 0.3, got {typed}"); + } + + #[test] + fn reset_restores_defaults_but_keeps_animation() { + let mut h = Harness::new("Merge", 2); + h.comp.set_input_value(h.node, "Blend", model::ParamValue::Number(0.2)); + h.comp.set_keyframe(h.node, "Gain", 0.0, 0.4).expect("keyframe"); + h.comp.set_input_value(h.node, "ProcessWhenBlendIs00", model::ParamValue::Number(1.0)); + let node = h.node; + let pages = &catalog()["Merge"].layout.pages; + let mut actions = Vec::new(); + let mut edit = super::super::edit::EditState::default(); + let mut cx = super::super::edit::Cx { + comp: &mut h.comp, + history: &mut h.history, + actions: &mut actions, + node, + frame: 0.0, + now: h.at, + p: h.state.palette, + expr: &h.state.expr, + edit: &mut edit, + }; + cx.reset_defaults(pages.iter().flat_map(|p| &p.sections).flat_map(|s| &s.controls)); + assert_eq!(h.number("Blend"), Some(1.0)); + assert_eq!(h.number("ProcessWhenBlendIs00"), Some(0.0)); + assert_eq!(super::super::keyframe_state(&h.comp, node, "Gain", 0.0), super::super::KeyframeState::KeyframeAtCurrent); + assert!(h.history.undo(&mut h.comp)); + assert_eq!(h.number("Blend"), Some(0.2)); + } +} diff --git a/crates/app/src/inspector/widgets.rs b/crates/app/src/inspector/widgets.rs index a5f063c5215be8405e30e54458a5734ced49f863..e9cc723963b74a3d65f5b55b16cb2433c4ea655c 100644 --- a/crates/app/src/inspector/widgets.rs +++ b/crates/app/src/inspector/widgets.rs @@ -1,26 +1,8 @@ -//! Reusable Inspector UI control builders: scrub sliders, keyframe diamonds (`◆`), -//! value formatting/scrubbing math, and parameter row dispatch. +//! Small Inspector widgets: the keyframe diamond (`◆`), the expression badge, and the keyframe +//! state / number formatting they share. -#[path = "rows.rs"] -mod rows; - -use super::schemas::{ParamKind, ParamSpec, infer_float_range}; -use super::{InspectorAction, InspectorState}; -use engine::EvalStats; -use model::{Comp, CompHistory, NodeId, ParamValue}; -use std::borrow::Cow; -use std::time::{Duration, Instant}; - -#[derive(Clone, Debug)] -pub(super) struct DragState { - pub node_id: NodeId, - pub key: String, - pub start_x: f32, - pub start_val: f64, - pub min: f64, - pub max: f64, - pub width: f32, -} +use super::edit::Cx; +use model::{Comp, NodeId}; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum KeyframeState { @@ -29,418 +11,6 @@ pub enum KeyframeState { KeyframeAtCurrent, } -impl InspectorState { - pub(super) fn render_stats_footer(&self, ui: &mut ui::Ui, stats: &EvalStats) { - let p = self.palette; - let line = format!( - "Eval {:.1}ms · {} nodes · cache {}/{} · {:.0}MB", - stats.eval_ms, - stats.nodes_evaluated, - stats.cache_hits, - stats.cache_hits + stats.cache_misses, - stats.cached_vram_mb, - ); - ui.open( - "insp-footer", - ui::Spec { - size: [ui::fill(), ui::px(24.0)], - axis: ui::Axis::X, - pad: [10.0, 4.0], - fill: Some(p.panel_bg), - border: Some(p.rule), - ..ui::Spec::default() - }, - ); - ui.leaf( - "insp-stats-txt", - ui::Spec { - size: [ui::fill(), ui::fill()], - text: Some(&line), - font_size: Some(10.0), - color: Some(p.text_dim), - ..ui::Spec::default() - }, - ); - ui.close(); - } - - #[allow(clippy::too_many_arguments)] - pub(super) fn render_param_spec( - &mut self, - ui: &mut ui::Ui, - pane_id: ui::Id, - comp: &mut Comp, - history: &mut CompHistory, - node_id: NodeId, - spec: &ParamSpec, - current_frame: f64, - actions: &mut Vec, - ) { - match spec.kind { - ParamKind::Float { min, max, default, step: _ } => { - self.render_float_row( - ui, - pane_id, - comp, - history, - node_id, - spec.name, - spec.label, - min, - max, - default, - current_frame, - actions, - ); - } - ParamKind::Vec2 { min, max, default } => { - self.render_vec2_row( - ui, - pane_id, - comp, - history, - node_id, - spec.name, - spec.label, - min, - max, - default, - current_frame, - actions, - ); - } - ParamKind::Bool { default } => { - // A Loader without `Inputs.Loop`/`Reverse` plays whatever its clip says. - let node = comp.node(node_id); - let clip = node.clips.first().filter(|_| node.kind == "Loader"); - let default = match spec.name { - "Loop" => clip.map_or(default, |c| c.loop_clip), - "Reverse" => clip.map_or(default, |c| c.reverse), - _ => default, - }; - self.render_bool_row(ui, comp, history, node_id, spec.name, spec.label, default, actions); - } - ParamKind::Enum { options, default } => { - self.render_enum_row(ui, comp, history, node_id, spec.name, spec.label, options, default, actions); - } - ParamKind::IntEnum { options, default } => { - self.render_int_enum_row(ui, comp, history, node_id, spec.name, spec.label, options, default, actions); - } - ParamKind::Color { r, g, b, a, default } => { - self.render_color_group( - ui, - pane_id, - comp, - history, - node_id, - spec.label, - r, - g, - b, - a, - default, - current_frame, - actions, - ); - } - ParamKind::Text { default } => { - self.render_text_row(ui, pane_id, comp, history, node_id, spec.name, spec.label, default, actions); - } - } - } - - #[allow(clippy::too_many_arguments)] - pub(super) fn render_fallback_input( - &mut self, - ui: &mut ui::Ui, - pane_id: ui::Id, - comp: &mut Comp, - history: &mut CompHistory, - node_id: NodeId, - key: &str, - current_frame: f64, - actions: &mut Vec, - ) { - let val = comp.node(node_id).inputs.get(key).and_then(|b| b.value.clone()); - match val { - Some(ParamValue::Point(pt)) => { - self.render_vec2_row(ui, pane_id, comp, history, node_id, key, key, -1.0, 2.0, pt, current_frame, actions); - } - Some(ParamValue::Text(_)) => { - self.render_text_row(ui, pane_id, comp, history, node_id, key, key, "", actions); - } - Some(ParamValue::FuId(cur)) => { - let p = self.palette; - ui.open( - ("fb-fuid", node_id.0, key), - ui::Spec { - size: [ui::fill(), ui::px(22.0)], - axis: ui::Axis::X, - gap: 6.0, - ..ui::Spec::default() - }, - ); - ui.leaf( - "lbl", - ui::Spec { - size: [ui::px(92.0), ui::fill()], - text: Some(key), - font_size: Some(10.5), - overflow: ui::Overflow::Ellipsis, - color: Some(p.text_dim), - ..ui::Spec::default() - }, - ); - ui.leaf( - "val", - ui::Spec { - size: [ui::fill(), ui::fill()], - text: Some(&cur), - font_size: Some(10.5), - color: Some(p.text), - fill: Some(p.panel_bg), - border: Some(p.rule), - radius: 4.0, - pad: [6.0, 0.0], - ..ui::Spec::default() - }, - ); - ui.close(); - } - Some(ParamValue::Number(v)) => { - let (min, max) = infer_float_range(key, v); - self.render_float_row(ui, pane_id, comp, history, node_id, key, key, min, max, v, current_frame, actions); - } - None => { - // Animated spline or expression-only scalar input - let cur = comp.eval_number(comp.node(node_id), key, current_frame, 0.0, &self.expr); - let (min, max) = infer_float_range(key, cur); - self.render_float_row(ui, pane_id, comp, history, node_id, key, key, min, max, 0.0, current_frame, actions); - } - _ => {} - } - } - - #[allow(clippy::too_many_arguments)] - pub(super) fn scrub_slider( - &mut self, - ui: &mut ui::Ui, - slider_id: ui::Id, - drag_key: &str, - node_id: NodeId, - value: f64, - min: f64, - max: f64, - default: f64, - history: &mut CompHistory, - comp: &Comp, - input_name: &str, - ) -> Option { - let sig = ui.signal(slider_id); - let rect = ui.laid_out(slider_id); - let width = rect.map(|r| (r[2] - r[0]).max(40.0)).unwrap_or(110.0); - let mut updated: Option = None; - - if let Some(press) = sig.press { - let now = Instant::now(); - let is_double = self - .last_click - .get(drag_key) - .is_some_and(|prev| now.duration_since(*prev) < Duration::from_millis(320)); - self.last_click.insert(drag_key.to_owned(), now); - if is_double { - history.push_snapshot(comp, format!("Reset {input_name}")); - self.drag = None; - updated = Some(default); - } else { - self.drag = Some(DragState { - node_id, - key: drag_key.to_owned(), - start_x: press[0], - start_val: value, - min, - max, - width, - }); - } - } else if sig.dragging { - if let (Some(d), Some(ptr)) = (&self.drag, ui.pointer()) { - if d.key == drag_key && d.node_id == node_id { - let fine = if ui.modifiers().shift_key() { 0.15 } else { 1.0 }; - let next = compute_scrub_value(d.start_val, ptr[0] - d.start_x, d.width, d.min, d.max, fine); - if (next - value).abs() > 1e-6 { - history.push_coalesced( - comp, - format!("Adjust {input_name}"), - format!("scrub:{drag_key}"), - ); - updated = Some(next); - } - } - } - } else if self.drag.as_ref().is_some_and(|d| d.key == drag_key) { - self.drag = None; - history.break_coalescing(); - } - - let display_val = updated.unwrap_or(value); - let frac = normalize_slider_fraction(display_val, min, max); - let val_text = format_param_number(display_val); - let fill_w = (width * frac).clamp(0.0, width); - let active_drag = self.drag.as_ref().is_some_and(|d| d.key == drag_key); - let p = self.palette; - - ui.open_as( - slider_id, - ui::Spec { - cursor: Some(winit::window::CursorIcon::EwResize), - flags: ui::Flags::CLICKABLE | ui::Flags::CLIP, - size: [ui::fill(), ui::px(20.0)], - fill: Some(p.panel_bg), - border: Some(if active_drag || sig.hovered { p.accent } else { p.rule }), - radius: 4.0, - ..ui::Spec::default() - }, - ); - if fill_w > 0.5 { - ui.leaf( - "fill", - ui::Spec { - flags: ui::Flags::FLOAT | ui::Flags::INERT, - position: [0.0, 0.0], - size: [ui::px(fill_w), ui::px(20.0)], - fill: Some([p.accent[0], p.accent[1], p.accent[2], if active_drag { 0.34 } else { 0.22 }]), - radius: 3.0, - ..ui::Spec::default() - }, - ); - } - ui.leaf( - "txt", - ui::Spec { - flags: ui::Flags::INERT, - size: [ui::fill(), ui::fill()], - text: Some(&val_text), - font_size: Some(10.5), - color: Some(p.text), - center: true, - ..ui::Spec::default() - }, - ); - ui.close(); - - updated - } - - pub(super) fn keyframe_button(&self, ui: &mut ui::Ui, part: impl std::hash::Hash, state: KeyframeState) -> bool { - let (ink, fill, border) = match state { - KeyframeState::KeyframeAtCurrent => ( - [1.0, 0.80, 0.22, 1.0], - Some([0.98, 0.72, 0.18, 0.24]), - Some([0.98, 0.76, 0.20, 0.85]), - ), - KeyframeState::AnimatedOtherFrame => ( - [0.92, 0.64, 0.24, 0.90], - Some([0.92, 0.64, 0.24, 0.12]), - Some([0.92, 0.64, 0.24, 0.45]), - ), - KeyframeState::Static => (self.palette.text_dim, None, None), - }; - let sig = ui.leaf( - part, - ui::Spec { - cursor: Some(winit::window::CursorIcon::Pointer), - flags: ui::Flags::CLICKABLE, - size: [ui::px(20.0), ui::px(20.0)], - text: Some("◆"), - font_size: Some(10.5), - color: Some(ink), - fill, - border, - hover_fill: Some([0.98, 0.76, 0.22, 0.18]), - radius: 4.0, - center: true, - ..ui::Spec::default() - }, - ); - sig.clicked - } - - #[allow(clippy::too_many_arguments)] - pub(super) fn toggle_keyframe( - &self, - comp: &mut Comp, - history: &mut CompHistory, - node_id: NodeId, - input_name: &str, - current_frame: f64, - cur_val: f64, - state: KeyframeState, - actions: &mut Vec, - ) { - match state { - KeyframeState::KeyframeAtCurrent => { - if let Some(sp_name) = comp - .node(node_id) - .inputs - .get(input_name) - .and_then(|b| b.source_op.clone()) - { - history.begin_group(comp, format!("Delete Keyframe {input_name}")); - if comp.delete_keyframe(&sp_name, current_frame) { - actions.push(InspectorAction::KeyframeEdited(node_id)); - actions.push(InspectorAction::StatusNotice(format!( - "Deleted keyframe on {input_name} @ f{current_frame:.0}" - ))); - } - history.commit_group(comp); - } - } - KeyframeState::Static | KeyframeState::AnimatedOtherFrame => { - history.begin_group(comp, format!("Set Keyframe {input_name}")); - let result = comp.set_keyframe(node_id, input_name, current_frame, cur_val); - if result.is_ok() { - history.commit_group(comp); - } else { - history.cancel_group(comp); - } - match result { - Ok(_) => { - actions.push(InspectorAction::KeyframeEdited(node_id)); - actions.push(InspectorAction::StatusNotice(format!( - "Keyframed {input_name} = {:.3} @ f{current_frame:.0}", - cur_val - ))); - } - Err(e) => actions.push(InspectorAction::StatusNotice(e)), - } - } - } - } -} - -pub(crate) fn enum_option_index(options: &[&str], current: &str) -> usize { - options.iter().position(|&o| o == current).unwrap_or(0) -} - -pub(crate) fn int_enum_lookup<'a>(options: &[(i32, &'a str)], val: i32) -> (usize, Cow<'a, str>) { - match options.iter().position(|&(v, _)| v == val) { - Some(idx) => (idx, Cow::Borrowed(options[idx].1)), - None => (0, Cow::Owned(val.to_string())), - } -} - -pub(crate) fn combo_cycle_index(cur_idx: usize, option_count: usize, reverse: bool) -> Option { - if option_count == 0 { - return None; - } - Some(if reverse { - (cur_idx + option_count - 1) % option_count - } else { - (cur_idx + 1) % option_count - }) -} - /// Computes whether an input is static, animated on another frame, or has a keyframe at `frame`. pub fn keyframe_state(comp: &Comp, node_id: NodeId, input_name: &str, frame: f64) -> KeyframeState { let Some(sp_name) = comp @@ -463,17 +33,6 @@ pub fn keyframe_state(comp: &Comp, node_id: NodeId, input_name: &str, frame: f64 } } -pub fn normalize_slider_fraction(value: f64, min: f64, max: f64) -> f32 { - let span = (max - min).abs().max(1e-6); - ((value - min) / span).clamp(0.0, 1.0) as f32 -} - -pub fn compute_scrub_value(start_val: f64, dx: f32, width: f32, min: f64, max: f64, fine_scale: f64) -> f64 { - let span = (max - min).max(1e-4); - let delta = (f64::from(dx) / f64::from(width.max(40.0))) * span * fine_scale; - (start_val + delta).clamp(min, max) -} - pub fn format_param_number(v: f64) -> String { if v.abs() >= 100.0 { format!("{v:.1}") @@ -484,46 +43,67 @@ pub fn format_param_number(v: f64) -> String { } } +/// The diamond column's width, kept by rows with nothing to animate so controls line up. +pub(super) const MARK_W: f32 = 18.0; + +/// Whether the diamond was clicked. +pub(super) fn keyframe_button(ui: &mut ui::Ui, cx: &Cx, state: KeyframeState) -> bool { + let (ink, fill, border) = match state { + KeyframeState::KeyframeAtCurrent => ( + [1.0, 0.80, 0.22, 1.0], + Some([0.98, 0.72, 0.18, 0.24]), + Some([0.98, 0.76, 0.20, 0.85]), + ), + KeyframeState::AnimatedOtherFrame => ( + [0.92, 0.64, 0.24, 0.90], + Some([0.92, 0.64, 0.24, 0.12]), + Some([0.92, 0.64, 0.24, 0.45]), + ), + KeyframeState::Static => (cx.p.text_dim, None, None), + }; + ui.leaf( + "kf", + ui::Spec { + cursor: Some(winit::window::CursorIcon::Pointer), + flags: ui::Flags::CLICKABLE, + size: [ui::px(MARK_W), ui::px(20.0)], + text: Some("◆"), + font_size: Some(10.0), + color: Some(ink), + fill, + border, + hover_fill: Some([0.98, 0.76, 0.22, 0.18]), + radius: 4.0, + center: true, + ..ui::Spec::default() + }, + ) + .clicked +} + +pub(super) fn expression_badge(ui: &mut ui::Ui) { + ui.leaf( + "expr", + ui::Spec { + size: [ui::px(16.0), ui::px(18.0)], + text: Some("="), + font_size: Some(10.5), + bold: true, + color: Some([0.36, 0.88, 0.92, 1.0]), + fill: Some([0.10, 0.24, 0.28, 0.85]), + border: Some([0.32, 0.78, 0.86, 0.65]), + radius: 3.0, + center: true, + ..ui::Spec::default() + }, + ); +} + #[cfg(test)] mod tests { use super::*; use model::{BezierSpline, Comp, Keyframe}; - #[test] - fn int_enum_lookup_and_cycling_with_unknown_fallback() { - const OPTS: &[(i32, &str)] = &[(0, "Normal"), (2, "Screen"), (5, "Multiply")]; - - let (idx, lbl) = int_enum_lookup(OPTS, 2); - assert_eq!(idx, 1); - assert_eq!(lbl.as_ref(), "Screen"); - - // Forward and reverse cycling wrap around - assert_eq!(combo_cycle_index(idx, OPTS.len(), false), Some(2)); - assert_eq!(combo_cycle_index(idx, OPTS.len(), true), Some(0)); - assert_eq!(combo_cycle_index(0, OPTS.len(), true), Some(2)); - assert_eq!(combo_cycle_index(2, OPTS.len(), false), Some(0)); - - // Unknown integer code falls back to index 0 and stringified code - let (idx, lbl) = int_enum_lookup(OPTS, 99); - assert_eq!(idx, 0); - assert_eq!(lbl.as_ref(), "99"); - assert_eq!(combo_cycle_index(idx, OPTS.len(), false), Some(1)); - } - - #[test] - fn combo_option_lookup_and_cycling() { - const OPTS: &[&str] = &["Nearest", "Linear", "Cubic"]; - - assert_eq!(enum_option_index(OPTS, "Linear"), 1); - assert_eq!(enum_option_index(OPTS, "Missing"), 0); - - assert_eq!(combo_cycle_index(0, OPTS.len(), false), Some(1)); - assert_eq!(combo_cycle_index(2, OPTS.len(), false), Some(0)); - assert_eq!(combo_cycle_index(0, OPTS.len(), true), Some(2)); - assert_eq!(combo_cycle_index(1, OPTS.len(), true), Some(0)); - assert_eq!(combo_cycle_index(0, 0, false), None); - } - #[test] fn format_param_number_uses_magnitude_precision() { assert_eq!(format_param_number(0.12345), "0.123"); @@ -534,30 +114,6 @@ mod tests { assert_eq!(format_param_number(-1234.56), "-1234.6"); } - #[test] - fn compute_scrub_value_normal_and_fine_shift_precision() { - // Full width drag of 100px over [0, 10] adds 10.0 normally, 1.5 with Shift (0.15) - let normal = compute_scrub_value(2.0, 50.0, 100.0, 0.0, 10.0, 1.0); - assert!((normal - 7.0).abs() < 1e-9); - - let fine = compute_scrub_value(2.0, 50.0, 100.0, 0.0, 10.0, 0.15); - assert!((fine - 2.75).abs() < 1e-9); - - // Clamps to [min, max] and enforces minimum 40px width denominator - assert_eq!(compute_scrub_value(8.0, 200.0, 100.0, 0.0, 10.0, 1.0), 10.0); - assert_eq!(compute_scrub_value(1.0, -200.0, 100.0, 0.0, 10.0, 1.0), 0.0); - let narrow = compute_scrub_value(0.0, 20.0, 10.0, 0.0, 10.0, 1.0); - assert!((narrow - 5.0).abs() < 1e-9); - } - - #[test] - fn normalize_slider_fraction_clamps_and_handles_degenerate_span() { - assert_eq!(normalize_slider_fraction(5.0, 0.0, 10.0), 0.5); - assert_eq!(normalize_slider_fraction(-5.0, 0.0, 10.0), 0.0); - assert_eq!(normalize_slider_fraction(25.0, 0.0, 10.0), 1.0); - assert_eq!(normalize_slider_fraction(0.0, 1.0, 1.0), 0.0); - } - #[test] fn keyframe_state_respects_epsilon() { let mut comp = Comp::from_fusion_str( -- 2.54.1