Skip to content

FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust

engine: a command whose targets are named in the parameters does not need a selection

punkhop6de389c75a9b
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs
index e5cde54e5..c00aa1409 100644
--- a/crates/engine/src/commands.rs
+++ b/crates/engine/src/commands.rs
@@ -110,6 +110,33 @@ fn has_clipboard(s: &Session) -> std::result::Result<(), String> {
if s.state.clipboard.is_empty() { Err("clipboard is empty".into()) } else { Ok(()) }
}
+/// The ids a caller named under `many` (a list) or `one` (a single id), when the command documents
+/// that key as ids (`"clips":[id]`, `"item":id`); `None` when it named none.
+fn named_ids(spec: &CommandSpec, p: &Value, many: &str, one: &str) -> Option<Vec<u64>> {
+ let ids: Vec<u64> = if spec.params.contains(&format!("\"{many}\":[id]"))
+ && let Some(a) = p.get(many).and_then(Value::as_array)
+ {
+ a.iter().filter_map(Value::as_u64).collect()
+ } else if spec.params.contains(&format!("\"{one}\":id")) {
+ u64_p(p, one).into_iter().collect()
+ } else {
+ Vec::new()
+ };
+ (!ids.is_empty()).then_some(ids)
+}
+/// Timeline clips named explicitly in `clips` / `clip` (see [`Session::execute`]): only clips of
+/// the active sequence count, so an id of nothing does not stand in for a selection.
+pub(crate) fn named_clips(s: &Session, spec: &CommandSpec, p: &Value) -> Option<Vec<ClipId>> {
+ let seq = s.active_sequence()?;
+ let clips: Vec<ClipId> = named_ids(spec, p, "clips", "clip")?.into_iter().map(ClipId).filter(|c| seq.find_item(*c).is_some()).collect();
+ (!clips.is_empty()).then_some(clips)
+}
+/// Project items named explicitly in `items` / `item`, likewise.
+pub(crate) fn named_items(s: &Session, spec: &CommandSpec, p: &Value) -> Option<Vec<ItemId>> {
+ let items: Vec<ItemId> = named_ids(spec, p, "items", "item")?.into_iter().map(ItemId).filter(|i| s.project.item(*i).is_some()).collect();
+ (!items.is_empty()).then_some(items)
+}
+
// ---------- param helpers ----------
pub(crate) fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {
@@ -1114,7 +1141,7 @@ fn build() -> Vec<CommandSpec> {
"Audio Gain…",
["Clip", "Audio Options"],
Some("G"),
- r#"{"mode":"set|adjust|normalizeMax|normalizeAll"?,"db":f64,"relative":bool?}"#,
+ r#"{"clips":[id]?,"mode":"set|adjust|normalizeMax|normalizeAll"?,"db":f64,"relative":bool?}"#,
has_selection,
|s, p| crate::mixer::audio_gain(s, p)
),
diff --git a/crates/engine/src/explicit_targets_tests.rs b/crates/engine/src/explicit_targets_tests.rs
new file mode 100644
index 000000000..164d03983
--- /dev/null
+++ b/crates/engine/src/explicit_targets_tests.rs
@@ -0,0 +1,177 @@
+//! A caller that names its targets in the parameters (`clips`, `clip`, `item`, `items`) does not
+//! need a selection: enablement is checked against the named targets. Without such parameters
+//! (the menus, shortcuts and `engine.commands`) enablement is the selection's, as before.
+
+use filmcraft_project::{ClipId, ItemId, TrackItem};
+use serde_json::json;
+
+use crate::{EngineError, Session};
+
+fn demo() -> Session {
+ let mut s = Session::default();
+ s.execute("file.openDemoProject", json!({})).unwrap();
+ s.execute("sequence.linkedSelection", json!({"on": false})).unwrap();
+ s.state.selection.clear();
+ s.state.project_selection.clear();
+ s
+}
+
+fn item_named(s: &Session, name: &str) -> ItemId {
+ s.project.items.values().find(|i| i.name == name).map(|i| i.id).unwrap_or_else(|| panic!("no item {name}"))
+}
+
+fn v1(s: &Session) -> Vec<TrackItem> {
+ s.active_sequence().unwrap().video_tracks[0].items.clone()
+}
+
+fn a1(s: &Session) -> Vec<TrackItem> {
+ s.active_sequence().unwrap().audio_tracks[0].items.clone()
+}
+
+fn clip(s: &Session, id: ClipId) -> Option<TrackItem> {
+ s.active_sequence().unwrap().find_item(id).map(|(_, i)| i.clone())
+}
+
+fn disabled(r: crate::Result<serde_json::Value>) -> String {
+ match r {
+ Err(EngineError::Disabled(_, why)) => why,
+ other => panic!("expected a disabled command, got {other:?}"),
+ }
+}
+
+#[test]
+fn replace_from_bin_takes_an_explicit_item_and_clips_without_any_selection() {
+ let mut s = demo();
+ let c = v1(&s)[0].clone();
+ let dunes = item_named(&s, "Desert_Dunes.mp4");
+ assert_ne!(c.item, dunes);
+ // nothing named, nothing selected: disabled, for the menus and for a caller alike
+ assert!(!s.is_enabled("clip.replaceFromBin"));
+ assert_eq!(disabled(s.execute("clip.replaceFromBin", json!({}))), "no clips selected");
+ // the clip is named but the replacement is not: still the Project panel's call
+ assert_eq!(disabled(s.execute("clip.replaceFromBin", json!({"clips": [c.id.0]}))), "select a clip in the Project panel");
+ // both named: runs with no timeline and no Project-panel selection
+ s.execute("clip.replaceFromBin", json!({"clips": [c.id.0], "item": dunes.0})).unwrap();
+ assert_eq!(clip(&s, c.id).unwrap().item, dunes);
+ assert!(s.state.selection.is_empty() && s.state.project_selection.is_empty(), "the selections are left as they were");
+ assert!(!s.is_enabled("clip.replaceFromBin"), "menu enablement still follows the selection");
+ s.execute("edit.undo", json!({})).unwrap();
+ assert_eq!(clip(&s, c.id).unwrap().item, c.item);
+ // a timeline selection plus an explicit item (no Project-panel selection)
+ s.execute("timeline.select", json!({"clips": [c.id.0]})).unwrap();
+ s.execute("clip.replaceFromBin", json!({"item": dunes.0})).unwrap();
+ assert_eq!(clip(&s, c.id).unwrap().item, dunes);
+}
+
+#[test]
+fn clip_commands_take_explicit_clips_without_a_selection() {
+ let mut s = demo();
+ let (a, b) = (v1(&s)[0].clone(), v1(&s)[1].clone());
+ for id in ["edit.clear", "edit.rippleDelete", "clip.audioGain", "edit.pasteAttributes", "clip.enable"] {
+ assert!(!s.is_enabled(id), "{id} is disabled without a selection");
+ assert!(matches!(s.execute(id, json!({})), Err(EngineError::Disabled(..))), "{id} with no parameters stays disabled");
+ }
+ // Clear
+ s.execute("edit.clear", json!({"clips": [a.id.0]})).unwrap();
+ assert!(clip(&s, a.id).is_none() && clip(&s, b.id).is_some());
+ s.execute("edit.undo", json!({})).unwrap();
+ assert!(clip(&s, a.id).is_some());
+ // Ripple Delete
+ let a_and_its_audio: Vec<u64> = s
+ .active_sequence()
+ .unwrap()
+ .all_tracks()
+ .flat_map(|t| &t.items)
+ .filter(|i| i.id == a.id || (i.link.is_some() && i.link == a.link))
+ .map(|i| i.id.0)
+ .collect();
+ s.execute("timeline.setTrack", json!({"track": "A2", "syncLock": false})).unwrap(); // the music on A2 would block the ripple
+ s.execute("edit.rippleDelete", json!({"clips": a_and_its_audio})).unwrap();
+ assert!(clip(&s, a.id).is_none());
+ assert_eq!(clip(&s, b.id).unwrap().start, a.start, "the next clip closes the gap");
+ s.execute("edit.undo", json!({})).unwrap();
+ // Audio Gain
+ let au = a1(&s)[0].clone();
+ s.execute("clip.audioGain", json!({"clips": [au.id.0], "mode": "set", "db": -6.0})).unwrap();
+ assert_eq!(clip(&s, au.id).unwrap().gain_db, -6.0);
+ // Enable
+ s.execute("clip.enable", json!({"clips": [a.id.0]})).unwrap();
+ assert!(!clip(&s, a.id).unwrap().enabled);
+ s.execute("edit.undo", json!({})).unwrap();
+ assert!(clip(&s, a.id).unwrap().enabled);
+ s.execute("edit.redo", json!({})).unwrap();
+ assert!(!clip(&s, a.id).unwrap().enabled);
+ // `clip.enable` documents `clips` only: a key it does not document is not a named target
+ assert_eq!(disabled(s.execute("clip.enable", json!({"clip": a.id.0}))), "no clips selected");
+ // Paste Attributes: naming the clips lifts only the selection condition, not the clipboard one
+ assert_eq!(disabled(s.execute("edit.pasteAttributes", json!({"clips": [b.id.0]}))), "copy a clip first");
+ s.execute("timeline.select", json!({"clips": [a.id.0]})).unwrap();
+ s.execute("edit.copy", json!({})).unwrap();
+ s.state.selection.clear();
+ s.execute("edit.pasteAttributes", json!({"clips": [b.id.0]})).unwrap();
+ assert!(s.state.selection.is_empty(), "the selection is left as it was");
+ for id in ["edit.clear", "edit.rippleDelete", "clip.audioGain", "edit.pasteAttributes"] {
+ assert!(!s.is_enabled(id), "menu enablement of {id} still follows the selection");
+ }
+}
+
+#[test]
+fn naming_nothing_usable_does_not_enable_a_command() {
+ let mut s = demo();
+ let before = s.project.clone();
+ // no ids, ids of no clip, the wrong type, and a key the command does not take
+ for p in [json!({"clips": []}), json!({"clips": [987_654_321u64]}), json!({"clips": "all"}), json!({"clips": [-1, 1.5, null]}), json!({"items": [1]})] {
+ assert_eq!(disabled(s.execute("edit.rippleDelete", p.clone())), "nothing selected", "{p}");
+ }
+ assert_eq!(disabled(s.execute("clip.replaceFromBin", json!({"clips": [v1(&s)[0].id.0], "item": 987_654_321u64}))), "select a clip in the Project panel");
+ // `edit.cut` takes no `clips`: it works on the selection only
+ assert_eq!(disabled(s.execute("edit.cut", json!({"clips": [v1(&s)[0].id.0]}))), "no clips selected");
+ assert!(std::sync::Arc::ptr_eq(&before, &s.project), "nothing was edited");
+}
+
+#[test]
+fn link_and_speed_take_explicit_clips_without_a_selection() {
+ let mut s = demo();
+ let (v, au) = (v1(&s)[0].clone(), a1(&s)[0].clone());
+ for id in ["clip.link", "clip.speedDuration"] {
+ assert!(!s.is_enabled(id));
+ assert_eq!(disabled(s.execute(id, json!({}))), "no clips selected");
+ }
+ // Link toggles the named pair
+ let was = v.link.is_some() && v.link == au.link;
+ let r = s.execute("clip.link", json!({"clips": [v.id.0, au.id.0]})).unwrap();
+ assert_eq!(r["linked"], !was);
+ assert_eq!(clip(&s, v.id).unwrap().link.is_some(), !was);
+ s.execute("edit.undo", json!({})).unwrap();
+ assert_eq!(clip(&s, v.id).unwrap().link, v.link);
+ s.execute("edit.redo", json!({})).unwrap();
+ assert_eq!(clip(&s, v.id).unwrap().link.is_some(), !was);
+ s.execute("edit.undo", json!({})).unwrap();
+ // Speed/Duration on the last clip of V1 (nothing after it to run into)
+ let last = v1(&s).last().unwrap().clone();
+ s.execute("clip.speedDuration", json!({"clips": [last.id.0], "speed": 200})).unwrap();
+ let fast = clip(&s, last.id).unwrap();
+ assert!(fast.duration < last.duration, "{:?} -> {:?}", last.duration, fast.duration);
+ s.execute("edit.undo", json!({})).unwrap();
+ assert_eq!(clip(&s, last.id).unwrap().duration, last.duration);
+ s.execute("edit.redo", json!({})).unwrap();
+ assert_eq!(clip(&s, last.id).unwrap().duration, fast.duration);
+ assert!(s.state.selection.is_empty() && !s.is_enabled("clip.speedDuration"), "menu enablement still follows the selection");
+}
+
+#[test]
+fn naming_targets_lifts_only_the_selection_condition() {
+ // no sequence: named clips cannot stand in for one
+ let mut empty = Session::default();
+ assert_eq!(disabled(empty.execute("edit.clear", json!({"clips": [1]}))), "no sequence is open");
+ assert_eq!(disabled(empty.execute("clip.speedDuration", json!({"clips": [1], "speed": 50}))), "no sequence is open");
+
+ let mut s = demo();
+ let a = v1(&s)[0].clone();
+ // the wrong kind of target: a video clip is not a graphic
+ assert_eq!(disabled(s.execute("graphics.setText", json!({"clip": a.id.0, "text": "x"}))), "select a graphic clip");
+ // a locked track is still the edit's own business: named or selected, the clip stays
+ s.execute("timeline.setTrack", json!({"track": "V1", "locked": true})).unwrap();
+ let _ = s.execute("edit.clear", json!({"clips": [a.id.0]}));
+ assert!(clip(&s, a.id).is_some(), "a clip on a locked track is not removed");
+}
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index a5f34e61d..2be97102d 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -595,7 +595,7 @@ impl Session {
if self.exec_depth == 0 && spec.journal && self.trim_play.active() {
self.settle_trim_playback(id);
}
- if let Err(why) = (spec.enabled)(self) {
+ if let Err(why) = self.enabled_for(spec, &params) {
let e = EngineError::Disabled(id.to_string(), why);
if self.exec_depth == 0 {
self.log.push(panels::Level::Warning, id, e.to_string());
@@ -645,6 +645,33 @@ impl Session {
}
}
+ /// Enablement of `spec` for one call. `enabled()` reads the selection, which is right for the
+ /// menus and for a call without targets. A caller that names its targets in `params`, under a
+ /// key the command documents (`clips` / `clip`: timeline clips, `items` / `item`: project
+ /// items), is asked the same question about those targets instead: the check runs again with
+ /// them standing in for the selection, so every other condition (an open sequence, a filled
+ /// clipboard, the kind of item…) still applies. The selections are put back before returning.
+ fn enabled_for(&mut self, spec: &CommandSpec, params: &Value) -> std::result::Result<(), String> {
+ let by_selection = (spec.enabled)(self);
+ if by_selection.is_ok() {
+ return by_selection;
+ }
+ let clips = commands::named_clips(self, spec, params);
+ let items = commands::named_items(self, spec, params);
+ if clips.is_none() && items.is_none() {
+ return by_selection;
+ }
+ let mut clips = clips.unwrap_or_else(|| self.state.selection.clone());
+ let mut items = items.unwrap_or_else(|| self.state.project_selection.clone());
+ std::mem::swap(&mut self.state.selection, &mut clips);
+ std::mem::swap(&mut self.state.project_selection, &mut items);
+ let by_params = (spec.enabled)(self);
+ self.state.selection = clips;
+ self.state.project_selection = items;
+ by_params
+ }
+
+ /// Whether the command can run on the current selection (what the menus show).
pub fn is_enabled(&self, id: &str) -> bool {
commands::find(id).is_some_and(|c| (c.enabled)(self).is_ok())
}
@@ -880,6 +907,8 @@ mod color_tests;
#[cfg(test)]
mod essential_sound_tests;
#[cfg(test)]
+mod explicit_targets_tests;
+#[cfg(test)]
mod export_tests;
#[cfg(test)]
mod file_tests;
diff --git a/docs/agents.md b/docs/agents.md
index 50ce3bcf3..b97b6eb7c 100644
--- a/docs/agents.md
+++ b/docs/agents.md
@@ -91,6 +91,13 @@ Notes:
`timecode`.
- `engine.execute` also runs UI-only commands (`tool.razor`, `playback.toggle`,
`window.workspace.color`, `window.panel.<name>`).
+- A command that works on the selection is disabled ("no clips selected", "select a clip in the
+ Project panel") until something is selected, unless the call names its targets under a key the
+ command documents (`clips` / `clip` for timeline clips, `items` / `item` for project items):
+ `clip.replaceFromBin {"clips":[12],"item":4}` runs with nothing selected and leaves the
+ selection alone. Only the selection condition is answered by the named targets; every other
+ one (an open sequence, a filled clipboard, the right kind of clip) still applies, and ids of
+ nothing do not count. `command_list` / `engine.commands` keep reporting the selection's state.
- Element ids come from the previous frame. If an element is missing right after a layout change,
the app retries on later frames before giving up.
- Without a window, `filmcraft-cli run script.jsonl` (lines of `{"id":"…","params":{…}}`) runs the
diff --git a/docs/control-protocol.md b/docs/control-protocol.md
index b473892b1..037443f48 100644
--- a/docs/control-protocol.md
+++ b/docs/control-protocol.md
@@ -31,6 +31,12 @@ Methods (handlers in `crates/ui-egui/src/control.rs`):
| `ui.resize`, `ui.focus`, `app.quit` | | `ui.focus` is the only request that activates the app and takes keyboard focus |
| `perf.stats` | – | performance counters (also the command `perf.stats`, so `engine.execute` and MCP `command_run` reach it; headless sessions return the engine part). `decode`: GOP-cache requests / hits / `cacheHitRate`, decoder seeks, samples decoded and skipped while catching up, `draftFrames` (decoded in draft mode), `h264Threads` (frame-threading workers per H.264 decoder), decoder ms (total and per sample), `framesDecoded`, `hardware` (Settings ▸ Playback ▸ Hardware decoding: `enabled`, pictures from hardware decoders `frames` vs `softwareFrames`, `sessions`, `declined` streams, mid-stream `fallbacks`); `playback`: playing, shown / dropped frames and `dropRate` of the current or last play, resolution, `draftDecode` (Settings ▸ Playback ▸ Draft decoding); `frames`: frame-worker jobs, cancelled, `requestHitRate`, `decodeMs` / `renderMs` (mean, p50, p95 of the last 256 jobs), queue, render-cost estimate, cache use; `ui`: fps and frame ms; `process`: CPU seconds; `media`, `jobs`. Counters are cumulative: diff two readings to measure an interval ([performance.md](performance.md)) |
+**Selection or explicit targets.** A command that acts on the selection is "not available right now" when
+nothing is selected. When `params` name the targets under a key the command documents (`clips` /
+`clip`: timeline clips of the active sequence, `items` / `item`: project items), enablement is
+checked against those instead and the selection is left as it is; the command's other conditions
+still apply. `engine.commands` and the menus always show the selection's enablement.
+
**Focus.** Driving the app never steals the user's keyboard. Started with `--control`, the app opens
without activating itself. UI requests and screenshots that need a rendered frame bring the window
forward without making it key (macOS `orderFrontRegardless`), so the user's typing keeps going to
@@ -46,7 +52,7 @@ solo, record arm, solo safe, mode Off/Read/Latch/Touch/Write, output, input map,
`mixer.recordStart` / `mixer.recordStop` (playback runs them), `mixer.addSubmix`, `mixer.deleteSubmix`,
`mixer.addInsert` / `removeInsert` / `setInsert`, `mixer.addSend` / `setSend` / `removeSend`,
`mixer.setKeyframe` / `deleteKeyframe` / `moveKeyframe` / `clearLane`, `mixer.writeAutomation`;
-`clipMixer.set`; `clip.audioGain {mode: set|adjust|normalizeMax|normalizeAll, db}`, `clip.audioPeak`;
+`clipMixer.set`; `clip.audioGain {clips?, mode: set|adjust|normalizeMax|normalizeAll, db}`, `clip.audioPeak`;
`effects.setDefaultTransition`. UI ids: `mixer.<A1|S1|Mix>.<fader|value|pan|panValue|mode|mute|solo|
record|soloSafe|output|input|fx.<n>|send.<n>|meter|name>` (popup entries below them, e.g.
`mixer.A1.mode.Touch`, `mixer.A1.fx.0.studio_reverb`), `mixer.showEffects`, `mixer.transport.<cmd>`,