Skip to content

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

graphics: document shape placement params; placement errors name their command

Tommaso Maccagni28cde3168d89
diff --git a/crates/engine/src/graphic_templates.rs b/crates/engine/src/graphic_templates.rs
index db00d6ee2..0b9941e29 100644
--- a/crates/engine/src/graphic_templates.rs
+++ b/crates/engine/src/graphic_templates.rs
@@ -316,7 +316,7 @@ fn apply_template(s: &mut Session, p: &Value) -> Result<Value> {
let (layers, meta) = t.instantiate((w, h));
let before = s.history.undo.len();
let dur = t.duration;
- let clip = place_video_clip(s, &t.name, p, "Apply Graphics Template", layers, move |pr, (w, h, rate)| {
+ let clip = place_video_clip(s, "graphics.template.apply", &t.name, p, "Apply Graphics Template", layers, move |pr, (w, h, rate)| {
let src = crate::graphics::graphic_source(pr, w, h, rate);
(src, rate.snap_nearest(dur))
})?;
@@ -911,7 +911,7 @@ fn upgrade_caption(s: &mut Session, p: &Value) -> Result<Value> {
let name = text.lines().next().unwrap_or("Caption").chars().take(40).collect::<String>();
let dur = c.duration;
let q = json!({"time": c.start.0});
- let clip = place_video_clip(s, &name, &q, "Upgrade Caption to Graphic", vec![layer], move |pr, (w, h, rate)| {
+ let clip = place_video_clip(s, "graphics.upgradeCaption", &name, &q, "Upgrade Caption to Graphic", vec![layer], move |pr, (w, h, rate)| {
(crate::graphics::graphic_source(pr, w, h, rate), dur)
})?;
clips.push(clip.0);
diff --git a/crates/engine/src/graphics.rs b/crates/engine/src/graphics.rs
index fea4922a9..d3ad695ad 100644
--- a/crates/engine/src/graphics.rs
+++ b/crates/engine/src/graphics.rs
@@ -96,23 +96,25 @@ pub(crate) fn graphic_source(p: &mut filmcraft_project::Project, w: u32, h: u32,
/// Place a new graphic clip holding `layer` at the playhead: on the first video track above the
/// topmost clip at the playhead that is free for the duration (a track is added if needed).
-fn new_graphic_clip(s: &mut Session, layer: filmcraft_project::EffectInstance, name: &str, p: &Value) -> Result<ClipId> {
+fn new_graphic_clip(s: &mut Session, cmd: &str, layer: filmcraft_project::EffectInstance, name: &str, p: &Value) -> Result<ClipId> {
let seconds = f64_p(p, "seconds").unwrap_or(5.0).max(0.01);
// Here `seconds` is duration, not the generic time parser's placement alias.
let mut placement = p.clone();
if let Some(params) = placement.as_object_mut() {
params.remove("seconds");
}
- place_video_clip(s, name, &placement, "New Graphic", vec![layer], move |pr, (w, h, rate)| {
+ place_video_clip(s, cmd, name, &placement, "New Graphic", vec![layer], move |pr, (w, h, rate)| {
let src = graphic_source(pr, w, h, rate);
(src, rate.snap_nearest(Tick::from_seconds_f64(seconds)).max(rate.frame_duration()))
})
}
/// Place a video clip of the item `source` returns (with its duration) at the playhead (or
-/// `time`), above the clips there, as one undo step; selects it.
+/// `time`), above the clips there, as one undo step; selects it. `cmd` is the command that asked,
+/// for its errors.
pub(crate) fn place_video_clip(
s: &mut Session,
+ cmd: &str,
name: &str,
p: &Value,
label: &str,
@@ -133,7 +135,7 @@ pub(crate) fn place_video_clip(
let src_size = pr.source_size(src).unwrap_or((w, h));
let t = rate.snap(t);
let dur = dur.max(rate.frame_duration());
- let mut ti = pr.make_track_item(src, TrackKind::Video, t, TimeRange::new(Tick::ZERO, dur), rate).ok_or_else(|| bad("graphics.newText", "bad item"))?;
+ let mut ti = pr.make_track_item(src, TrackKind::Video, t, TimeRange::new(Tick::ZERO, dur), rate).ok_or_else(|| bad(cmd, "bad item"))?;
ti.name = name;
ti.effects.extend(extra);
for e in &mut ti.effects {
@@ -146,7 +148,7 @@ pub(crate) fn place_video_clip(
let free = |tr: &filmcraft_project::Track| !tr.items.iter().any(|i| i.range().overlaps(&range));
let idx = match want_track {
Some(i) if i < q.video_tracks.len() && free(&q.video_tracks[i]) => i,
- Some(i) if i < q.video_tracks.len() => return Err(bad("graphics.newText", format!("V{} is not free here", i + 1))),
+ Some(i) if i < q.video_tracks.len() => return Err(bad(cmd, format!("V{} is not free here", i + 1))),
_ => {
let top = q.video_tracks.iter().rposition(|tr| tr.item_at(t).is_some()).map_or(0, |k| k + 1);
match (top..q.video_tracks.len()).find(|&i| free(&q.video_tracks[i]) && !q.video_tracks[i].locked) {
@@ -703,7 +705,7 @@ fn menu_commands() -> Vec<CommandSpec> {
"Rectangle",
&["Graphics and Titles", "New Layer"],
Some("Cmd+Alt+R"),
- r#"{"position":[x,y]?,"size":[w,h]=[400,200],"clip":id?}"#,
+ r#"{"position":[x,y]?,"size":[w,h]=[400,200],"clip":id?,"seconds":f64=5,"track":index?,"time":ticks?}"#,
has_seq,
|s, p| new_shape_cmd(s, p, "rectangle"),
),
@@ -712,7 +714,7 @@ fn menu_commands() -> Vec<CommandSpec> {
"Ellipse",
&["Graphics and Titles", "New Layer"],
Some("Cmd+Alt+E"),
- r#"{"position":[x,y]?,"size":[w,h]=[400,200],"clip":id?}"#,
+ r#"{"position":[x,y]?,"size":[w,h]=[400,200],"clip":id?,"seconds":f64=5,"track":index?,"time":ticks?}"#,
has_seq,
|s, p| new_shape_cmd(s, p, "ellipse"),
),
@@ -721,7 +723,7 @@ fn menu_commands() -> Vec<CommandSpec> {
"Polygon",
&["Graphics and Titles", "New Layer"],
None,
- r#"{"position":[x,y]?,"size":[w,h]=[300,300],"sides":n=6,"clip":id?}"#,
+ r#"{"position":[x,y]?,"size":[w,h]=[300,300],"sides":n=6,"clip":id?,"seconds":f64=5,"track":index?,"time":ticks?}"#,
has_seq,
|s, p| {
let mut q = if p.is_object() { p.clone() } else { json!({}) };
@@ -766,7 +768,7 @@ fn menu_commands() -> Vec<CommandSpec> {
return Err(bad("graphics.newFromFile", "the file has no picture"));
}
let (name, dur) = (pi.name.clone(), pi.duration());
- let clip = place_video_clip(s, &name, p, "New Layer from File", Vec::new(), move |_, _| (item, dur))?;
+ let clip = place_video_clip(s, "graphics.newFromFile", &name, p, "New Layer from File", Vec::new(), move |_, _| (item, dur))?;
s.state.graphic_layers.clear();
Ok(json!({"clip": clip.0, "item": item.0}))
},
@@ -902,7 +904,7 @@ pub fn commands() -> Vec<CommandSpec> {
Some(c) => (c, add_layer(s, c, layer)?),
None => {
let name = text.lines().next().filter(|l| !l.trim().is_empty()).unwrap_or("Graphic").to_string();
- (new_graphic_clip(s, layer, &name, p)?, 0)
+ (new_graphic_clip(s, "graphics.newText", layer, &name, p)?, 0)
}
};
Ok(json!({"clip": clip.0, "layer": layer_i}))
@@ -913,7 +915,7 @@ pub fn commands() -> Vec<CommandSpec> {
"Shape",
&[],
None,
- r#"{"shape":"rectangle|ellipse|polygon|path","position":[x,y]?,"size":[w,h]=[400,200],"points":[[x,y],…]?,"clip":id?,"seconds":f64=5}"#,
+ r#"{"shape":"rectangle|ellipse|polygon|path","position":[x,y]? (the shape's centre),"size":[w,h]=[400,200],"points":[[x,y],…]?,"clip":id? (add the shape to this graphic),"seconds":f64=5,"track":index?,"time":ticks?}"#,
has_seq,
|s, p| {
let shape = str_p(p, "shape").unwrap_or("rectangle").to_ascii_lowercase();
@@ -936,7 +938,7 @@ pub fn commands() -> Vec<CommandSpec> {
let into = u64_p(p, "clip").map(ClipId).filter(|c| s.active_sequence().is_some_and(|q| is_graphic(s, q, *c)));
let (clip, layer_i) = match into {
Some(c) => (c, add_layer(s, c, layer)?),
- None => (new_graphic_clip(s, layer, "Shape", p)?, 0),
+ None => (new_graphic_clip(s, "graphics.newShape", layer, "Shape", p)?, 0),
};
Ok(json!({"clip": clip.0, "layer": layer_i}))
},
diff --git a/crates/engine/src/graphics_tests.rs b/crates/engine/src/graphics_tests.rs
index 0c7cc4cb7..e907bf345 100644
--- a/crates/engine/src/graphics_tests.rs
+++ b/crates/engine/src/graphics_tests.rs
@@ -65,6 +65,36 @@ fn graphic_duration_keeps_explicit_time_frame_and_timecode_placement() {
}
}
+/// A new graphic goes on the track and at the time it is given, for a shape as for text; a track
+/// that is not free there is an error named after the command that asked.
+#[test]
+fn graphic_placement_takes_a_track_and_a_time() {
+ let commands =
+ [("graphics.newText", json!({})), ("graphics.newShape", json!({})), ("graphics.newRectangle", json!({})), ("graphics.newPolygon", json!({"sides": 5}))];
+ for (command, mut params) in commands {
+ let mut s = Session::default();
+ s.execute("file.newSequence", json!({"name": "Placement", "fps": 24, "width": 128, "height": 128, "video": 3, "audio": 1})).unwrap();
+ s.execute("playhead.set", json!({"frame": 72})).unwrap();
+ params["track"] = json!(2);
+ params["frame"] = json!(24);
+ params["seconds"] = json!(1);
+ let r = s.execute(command, params.clone()).unwrap();
+ let clip = ClipId(r["clip"].as_u64().unwrap());
+ let q = s.active_sequence().unwrap();
+ let (track, it) = q.find_item(clip).unwrap();
+ assert_eq!(track, q.video_tracks[2].id, "{command}");
+ assert_eq!((it.start, it.duration), (Tick::from_seconds_f64(1.0), Tick::from_seconds_f64(1.0)), "{command}");
+ // the same place again is taken
+ let e = s.execute(command, params).unwrap_err().to_string();
+ assert!(e.contains("V3 is not free here"), "{command}: {e}");
+ let named = if command == "graphics.newText" { "graphics.newText" } else { "graphics.newShape" };
+ assert!(e.contains(named), "{command}: {e}");
+ assert_eq!(s.active_sequence().unwrap().video_tracks[2].items.len(), 1, "{command}");
+ s.execute("edit.undo", json!({})).unwrap();
+ assert!(s.active_sequence().unwrap().find_item(clip).is_none(), "{command}");
+ }
+}
+
#[test]
fn new_text_makes_a_graphic_clip_above_the_footage() {
let mut s = demo();
diff --git a/docs/graphics.md b/docs/graphics.md
index 6d935e82c..6bdf9f363 100644
--- a/docs/graphics.md
+++ b/docs/graphics.md
@@ -84,9 +84,9 @@ Timecode and Clip Name effects also draw with the text engine.
|---|---|---|
| `graphics.newText` | Graphics and Titles ▸ New Layer ▸ Text (⌘T) | `text`, `position`, `box` (`[w, h]`: paragraph text in a box, `position` is its top-left corner), `clip` (add to this graphic), `vertical`, `size`, `font`, `fontStyle`, `seconds` (5), `track`, `time` |
| `graphics.newVerticalText` | New Layer ▸ Vertical Text | as `graphics.newText`; characters stack top to bottom, paragraphs are columns right to left |
-| `graphics.newRectangle`, `graphics.newEllipse`, `graphics.newPolygon` | New Layer ▸ Rectangle (⌥⌘R), Ellipse (⌥⌘E), Polygon | `position`, `size`, `clip`; polygon `sides` (6) |
+| `graphics.newRectangle`, `graphics.newEllipse`, `graphics.newPolygon` | New Layer ▸ Rectangle (⌥⌘R), Ellipse (⌥⌘E), Polygon | `position` (the shape's centre), `size`, `clip`, `seconds` (5), `track`, `time`; polygon `sides` (6) |
| `graphics.newFromFile` | New Layer ▸ From file… | `path` — imports the image or video and places it above the clips at the playhead (a separate clip; graphics have no media layers yet) |
-| `graphics.newShape` | (agents) | `shape` (rectangle/ellipse/polygon/path), `position`, `size`, `points`, `clip` |
+| `graphics.newShape` | (agents) | `shape` (rectangle/ellipse/polygon/path), `position` (the shape's centre), `size`, `points`, `clip` (add to this graphic), `seconds` (5), `track`, `time` |
| `graphics.setTextType` | Text Properties ▸ Text Layer Type | `clip`, `layer`, `type` (`point` / `paragraph`); the text stays where it is |
| `graphics.setText` | typing on the monitor | `clip`, `layer`, `text`, `merge` (coalesce one typing session into one undo step) |
| `graphics.set` | Properties panel | `clip`, `layer`, `props` {parameter id or camelCase alias: value; choices by index or name}, `time` |