1//! Everything a row does to the comp: reading evaluated values, keyframe-aware writes with undo,
2//! numeric-box edit state, and keyframe toggling for single inputs and grouped channels.
3
4use super::layout::{Channel, ControlDef, Kind};
5use super::widgets::{KeyframeState, keyframe_state};
6use super::{InspectorAction, InspectorPalette};
7use model::{Comp, CompHistory, ExprEngine, NodeId, ParamValue};
8use std::time::{Duration, Instant};
9
10/// How long a drag rests before the undo step it coalesced into closes.
11pub(super) const SCRUB_GRACE: Duration = Duration::from_millis(350);
12
13/// A numeric box being typed into; it commits when it loses the keys.
14pub(super) struct NumberEdit {
15 pub id: ui::Id,
16 /// The node the box was focused on; selection may move on before the commit.
17 pub node: NodeId,
18 pub buf: String,
19 pub channel: Channel,
20 /// `Some(0|1)` edits one axis of a Point input.
21 pub axis: Option<usize>,
22}
23
24#[derive(Default)]
25pub(super) struct EditState {
26 pub number: Option<NumberEdit>,
27 pub text: Option<(ui::Id, String)>,
28 pub last_scrub: Option<Instant>,
29}
30
31pub(super) struct Cx<'a> {
32 pub comp: &'a mut Comp,
33 pub history: &'a mut CompHistory,
34 pub actions: &'a mut Vec<InspectorAction>,
35 pub node: NodeId,
36 pub frame: f64,
37 pub now: Instant,
38 pub p: InspectorPalette,
39 pub expr: &'a ExprEngine,
40 pub edit: &'a mut EditState,
41}
42
43impl Cx<'_> {
44 /// A Loader without `Inputs.Loop`/`Reverse` plays whatever its clip says.
45 pub fn default_of(&self, ch: &Channel) -> f64 {
46 let node = self.comp.node(self.node);
47 let clip = node.clips.first().filter(|_| node.kind == "Loader");
48 match (ch.id.as_str(), clip) {
49 ("Loop", Some(c)) => f64::from(u8::from(c.loop_clip)),
50 ("Reverse", Some(c)) => f64::from(u8::from(c.reverse)),
51 _ => ch.default[0],
52 }
53 }
54
55 pub fn number(&self, ch: &Channel) -> f64 {
56 self.comp.eval_number(self.comp.node(self.node), &ch.id, self.frame, self.default_of(ch), self.expr)
57 }
58
59 pub fn point(&self, ch: &Channel) -> [f64; 2] {
60 self.comp.eval_point(self.comp.node(self.node), &ch.id, self.frame, ch.default, self.expr)
61 }
62
63 pub fn has_expression(&self, channels: &[Channel]) -> bool {
64 let node = self.comp.node(self.node);
65 channels.iter().any(|ch| node.inputs.get(&ch.id).is_some_and(|b| b.expression.is_some()))
66 }
67
68 /// Every channel at a keyframe reads as on a keyframe; any animated one as animated.
69 pub fn key_state(&self, channels: &[Channel]) -> KeyframeState {
70 let mut states = channels.iter().map(|ch| keyframe_state(self.comp, self.node, &ch.id, self.frame));
71 if channels.is_empty() || states.clone().all(|s| s == KeyframeState::KeyframeAtCurrent) {
72 return states.next().unwrap_or(KeyframeState::Static);
73 }
74 if states.any(|s| s != KeyframeState::Static) {
75 KeyframeState::AnimatedOtherFrame
76 } else {
77 KeyframeState::Static
78 }
79 }
80
81 /// Writes numbers, as a keyframe where the input is animated. A drag, named by its control's
82 /// primary channel, folds into one undo step until it rests; anything else is its own step.
83 pub fn write_numbers(&mut self, label: &str, edits: &[(&Channel, f64)], drag: Option<&str>) {
84 if edits.is_empty() {
85 return;
86 }
87 if let Some(primary) = drag {
88 let key = format!("scrub:{}:{primary}", self.node.0);
89 self.history.push_coalesced(self.comp, format!("Adjust {label}"), key);
90 self.edit.last_scrub = Some(self.now);
91 } else {
92 self.history.push_snapshot(self.comp, format!("Set {label}"));
93 }
94 for &(ch, value) in edits {
95 if !value.is_finite() {
96 continue;
97 }
98 let lo = ch.allowed[0].filter(|v| v.is_finite()).unwrap_or(f64::MIN);
99 let hi = ch.allowed[1].filter(|v| v.is_finite()).unwrap_or(f64::MAX);
100 let value = if lo <= hi { value.clamp(lo, hi) } else { value };
101 let animated = keyframe_state(self.comp, self.node, &ch.id, self.frame) != KeyframeState::Static;
102 if animated {
103 let _ = self.comp.set_keyframe(self.node, &ch.id, self.frame, value);
104 self.actions.push(InspectorAction::KeyframeEdited(self.node));
105 } else {
106 self.comp.set_input_value(self.node, &ch.id, ParamValue::Number(value));
107 self.actions.push(InspectorAction::ParamEdited(self.node));
108 }
109 }
110 }
111
112 pub fn write_value(&mut self, label: &str, id: &str, value: ParamValue) {
113 self.history.push_snapshot(self.comp, format!("Set {label}"));
114 self.comp.set_input_value(self.node, id, value);
115 self.actions.push(InspectorAction::ParamEdited(self.node));
116 }
117
118 /// Commits a numeric box once it has lost the keys, onto the node it was typed into.
119 pub fn commit_number(&mut self, edit: NumberEdit) {
120 let Ok(value) = edit.buf.trim().parse::<f64>() else { return };
121 if !value.is_finite() || edit.node.0 >= self.comp.nodes.len() {
122 return;
123 }
124 let selected = std::mem::replace(&mut self.node, edit.node);
125 let ch = &edit.channel;
126 match edit.axis {
127 Some(axis) => {
128 let mut point = self.point(ch);
129 point[axis] = value;
130 self.write_value(&ch.id, &ch.id, ParamValue::Point(point));
131 }
132 None => self.write_numbers(&ch.id, &[(ch, value)], None),
133 }
134 self.node = selected;
135 }
136
137 /// Keys every channel at the current frame, or removes those keys when all already have one.
138 pub fn toggle_keyframes(&mut self, label: &str, channels: &[Channel], state: KeyframeState) {
139 self.history.begin_group(self.comp, format!("Keyframe {label}"));
140 let mut notice = None;
141 for ch in channels {
142 if state == KeyframeState::KeyframeAtCurrent {
143 let spline = self.comp.node(self.node).inputs.get(&ch.id).and_then(|b| b.source_op.clone());
144 if spline.is_some_and(|sp| self.comp.delete_keyframe(&sp, self.frame)) {
145 notice = Some(format!("Deleted keyframe on {label} @ f{:.0}", self.frame));
146 }
147 } else {
148 let value = self.number(ch);
149 match self.comp.set_keyframe(self.node, &ch.id, self.frame, value) {
150 Ok(_) => notice = Some(format!("Keyframed {label} @ f{:.0}", self.frame)),
151 Err(e) => notice = Some(e),
152 }
153 }
154 }
155 self.history.commit_group(self.comp);
156 if let Some(notice) = notice {
157 self.actions.push(InspectorAction::KeyframeEdited(self.node));
158 self.actions.push(InspectorAction::StatusNotice(notice));
159 }
160 }
161
162 /// Puts every static input of `controls` back to its default; animated and expression inputs
163 /// keep their drivers.
164 pub fn reset_defaults<'d>(&mut self, controls: impl Iterator<Item = &'d ControlDef>) {
165 self.history.begin_group(self.comp, "Reset to Defaults");
166 for def in controls {
167 for ch in &def.channels {
168 let binding = self.comp.node(self.node).inputs.get(&ch.id);
169 if binding.is_some_and(|b| b.source_op.is_some() || b.expression.is_some()) {
170 continue;
171 }
172 let Some(current) = binding.and_then(|b| b.value.clone()) else { continue };
173 let default = match def.kind {
174 Kind::Point => ParamValue::Point(ch.default),
175 Kind::Text if def.fuid => ParamValue::FuId(def.default_text.clone()),
176 Kind::Text => ParamValue::Text(def.default_text.clone()),
177 Kind::Segmented | Kind::Combo if def.fuid => {
178 let s = def.entries.get(def.default_index).cloned().unwrap_or_else(|| def.default_text.clone());
179 ParamValue::FuId(s)
180 }
181 _ => ParamValue::Number(self.default_of(ch)),
182 };
183 if current != default {
184 self.comp.set_input_value(self.node, &ch.id, default);
185 }
186 }
187 }
188 if self.history.commit_group(self.comp) {
189 self.actions.push(InspectorAction::ParamEdited(self.node));
190 self.actions.push(InspectorAction::StatusNotice("Reset to defaults".to_owned()));
191 }
192 }
193}