Skip to content

The truly free, open-source, local-first, cross-platform CapCut replacement. Scriptable through a JSON-RPC API & MCP.

updates

Jareer14751442b471
diff --git a/desktop/src-tauri/src/editor_api.rs b/desktop/src-tauri/src/editor_api.rs
index b66f2ee2..6817e324 100644
--- a/desktop/src-tauri/src/editor_api.rs
+++ b/desktop/src-tauri/src/editor_api.rs
@@ -70,6 +70,21 @@ fn view(session: &Session, created_id: Option<String>) -> EditorView {
}
}
+/// The open session's document, project folder and settings, for features
+/// that package the current edit (saving it as a template) rather than
+/// editing it.
+pub fn session_snapshot(
+ state: &EditorState,
+) -> Result<(serde_json::Value, String, DocumentSettings), String> {
+ with_session(state, |session| {
+ Ok((
+ session.editor.to_document(&session.settings),
+ session.path.clone(),
+ session.settings.clone(),
+ ))
+ })
+}
+
fn with_session<T>(
state: &EditorState,
operation: impl FnOnce(&mut Session) -> Result<T, String>,
diff --git a/desktop/src-tauri/src/lib.rs b/desktop/src-tauri/src/lib.rs
index f06f4b35..3cdcaa53 100644
--- a/desktop/src-tauri/src/lib.rs
+++ b/desktop/src-tauri/src/lib.rs
@@ -11,6 +11,7 @@ pub mod export;
mod editor_api;
mod playback;
mod projects;
+mod templates;
mod transcribe;
use serde::Serialize;
@@ -438,6 +439,62 @@ fn forget_project(app: tauri::AppHandle, path: String) -> Result<(), String> {
projects::forget(&config_dir(&app)?, &path)
}
+/// The template library, for the gallery.
+#[tauri::command]
+fn template_list(app: tauri::AppHandle) -> Result<Vec<templates::TemplateInfo>, String> {
+ Ok(templates::list(&config_dir(&app)?))
+}
+
+/// Packs the open project into a new template bundle.
+#[tauri::command]
+async fn template_save(
+ app: tauri::AppHandle,
+ state: tauri::State<'_, editor_api::EditorState>,
+ name: String,
+) -> Result<templates::TemplateInfo, String> {
+ let (document, project_path, _) = editor_api::session_snapshot(&state)?;
+ let config = config_dir(&app)?;
+ tauri::async_runtime::spawn_blocking(move || {
+ templates::save(&config, &document, &project_path, &name)
+ })
+ .await
+ .map_err(|error| format!("template save task failed: {error}"))?
+}
+
+/// Unpacks a template into a fresh project with every slot filled, and
+/// records it as recent - the caller opens it like any other project.
+#[tauri::command]
+async fn template_instantiate(
+ app: tauri::AppHandle,
+ template: String,
+ location: String,
+ name: String,
+ fills: Vec<templates::SlotFill>,
+) -> Result<projects::ProjectInfo, String> {
+ let config = config_dir(&app)?;
+ tauri::async_runtime::spawn_blocking(move || {
+ let project = templates::instantiate(&template, &location, &name, fills)?;
+ if let Err(error) = projects::remember(&config, &project) {
+ eprintln!("relay: {error}");
+ }
+ Ok(project)
+ })
+ .await
+ .map_err(|error| format!("template task failed: {error}"))?
+}
+
+/// Removes one template bundle for good.
+#[tauri::command]
+fn template_delete(app: tauri::AppHandle, path: String) -> Result<(), String> {
+ templates::delete(&config_dir(&app)?, &path)
+}
+
+/// A template's poster, or an error the UI treats as "no art".
+#[tauri::command]
+fn template_poster(path: String) -> Result<tauri::ipc::Response, String> {
+ templates::poster(&path).map(tauri::ipc::Response::new)
+}
+
fn config_dir(app: &tauri::AppHandle) -> Result<std::path::PathBuf, String> {
use tauri::Manager;
app.path()
@@ -601,6 +658,11 @@ pub fn run() {
export_project,
cancel_export,
preview_frame,
+ template_list,
+ template_save,
+ template_instantiate,
+ template_delete,
+ template_poster,
editor_api::editor_open,
editor_api::editor_apply,
editor_api::editor_undo,
diff --git a/desktop/src-tauri/src/projects.rs b/desktop/src-tauri/src/projects.rs
index 7200a7ff..0058f938 100644
--- a/desktop/src-tauri/src/projects.rs
+++ b/desktop/src-tauri/src/projects.rs
@@ -224,8 +224,9 @@ fn same_path(left: &str, right: &str) -> bool {
left.eq_ignore_ascii_case(right)
}
-/// Turns a project name into something a filesystem will accept.
-fn folder_name(name: &str) -> String {
+/// Turns a project name into something a filesystem will accept. Also used
+/// for template bundle folders and the files inside them.
+pub(crate) fn folder_name(name: &str) -> String {
let cleaned: String = name
.trim()
.chars()
diff --git a/desktop/src-tauri/src/templates.rs b/desktop/src-tauri/src/templates.rs
new file mode 100644
index 00000000..69a4d13a
--- /dev/null
+++ b/desktop/src-tauri/src/templates.rs
@@ -0,0 +1,567 @@
+//! Template bundles on disk.
+//!
+//! A template is a folder in the app config directory's `templates/`:
+//!
+//! - `template.json` - an ordinary relay document whose placeholder media
+//! (engine `placeholder: true`) have blank paths, and whose bundled media
+//! and fonts - the music, overlays and faces that are part of the design -
+//! have paths relative to the bundle (`assets/...`).
+//! - `assets/` - those bundled files, copied in at save time.
+//! - `poster.jpg` - a frame of the edit, for the gallery card.
+//!
+//! Saving packs the open project into a bundle; instantiating unpacks one
+//! into a fresh project folder and fills every slot with the user's media
+//! *through the engine* (`Command::FillSlot` in a batch), so what a fill
+//! means is defined in exactly one place - `relay-project` - and the editor
+//! never opens on a slot with a dead path.
+
+use std::path::{Path, PathBuf};
+
+use relay_project::{Command, DocumentSettings, Editor};
+use serde::{Deserialize, Serialize};
+use serde_json::Value;
+
+use crate::projects;
+
+const MANIFEST: &str = "template.json";
+const ASSETS: &str = "assets";
+const POSTER: &str = "poster.jpg";
+
+/// One template, as the gallery sees it.
+#[derive(Serialize, Clone, Debug)]
+#[serde(rename_all = "camelCase")]
+pub struct TemplateInfo {
+ /// The bundle folder.
+ pub path: String,
+ pub name: String,
+ pub width: u32,
+ pub height: u32,
+ pub rate_num: i64,
+ pub rate_den: i64,
+ /// The slots to fill, in the order they first appear on the timeline.
+ pub slots: Vec<SlotInfo>,
+ pub has_poster: bool,
+}
+
+/// One placeholder the user's media will replace.
+#[derive(Serialize, Clone, Debug)]
+#[serde(rename_all = "camelCase")]
+pub struct SlotInfo {
+ pub media_id: String,
+ pub name: String,
+ /// "video", "audio" or "image".
+ pub kind: String,
+ /// Timeline seconds this slot covers, summed over its clips.
+ pub seconds: f64,
+}
+
+/// The user's media for one slot, straight from a probe.
+#[derive(Deserialize, Clone, Debug)]
+#[serde(rename_all = "camelCase")]
+pub struct SlotFill {
+ pub media_id: String,
+ pub item: relay_project::commands::NewMedia,
+}
+
+pub fn templates_dir(config: &Path) -> PathBuf {
+ config.join("templates")
+}
+
+/// Packs the given document into a new template bundle.
+///
+/// `project_path` is where the document's media paths currently resolve; it
+/// also donates the poster frame. Refuses a name that already exists rather
+/// than overwriting someone's work.
+pub fn save(
+ config: &Path,
+ document: &Value,
+ project_path: &str,
+ name: &str,
+) -> Result<TemplateInfo, String> {
+ let root = templates_dir(config).join(projects::folder_name(name));
+ if root.join(MANIFEST).exists() {
+ return Err(format!("a template named {name:?} already exists"));
+ }
+ let assets = root.join(ASSETS);
+ std::fs::create_dir_all(&assets)
+ .map_err(|error| format!("could not create {}: {error}", assets.display()))?;
+
+ let mut document = document.clone();
+ document["name"] = Value::String(name.to_owned());
+
+ // Placeholder media loses its path - it was the creator's own footage,
+ // standing in. Everything else is part of the design and ships in the
+ // bundle, referenced relative to it.
+ if let Some(media) = document.get_mut("media").and_then(Value::as_array_mut) {
+ for item in media {
+ let placeholder =
+ item.get("placeholder").and_then(Value::as_bool).unwrap_or(false);
+ if placeholder {
+ item["path"] = Value::String(String::new());
+ continue;
+ }
+ let source = item.get("path").and_then(Value::as_str).unwrap_or("").to_owned();
+ let id = item.get("id").and_then(Value::as_str).unwrap_or("m").to_owned();
+ item["path"] = Value::String(bundle_file(&assets, &id, &source)?);
+ }
+ }
+ if let Some(fonts) = document.get_mut("fonts").and_then(Value::as_array_mut) {
+ for (index, font) in fonts.iter_mut().enumerate() {
+ let source = font.get("path").and_then(Value::as_str).unwrap_or("").to_owned();
+ font["path"] = Value::String(bundle_file(&assets, &format!("font{index}"), &source)?);
+ }
+ }
+
+ let encoded = serde_json::to_vec_pretty(&document)
+ .map_err(|error| format!("could not encode the template: {error}"))?;
+ std::fs::write(root.join(MANIFEST), encoded)
+ .map_err(|error| format!("could not write the template: {error}"))?;
+
+ // Best effort: a template without a poster is still a template.
+ if let Ok(bytes) = crate::poster_frame(project_path) {
+ let _ = std::fs::write(root.join(POSTER), bytes);
+ }
+
+ read_info(&root)
+}
+
+/// Copies one source file into `assets/` and returns its bundle-relative
+/// path. The bundle must be self-contained, so a missing source is an error,
+/// not a warning - a template that cannot find its own music is not one.
+fn bundle_file(assets: &Path, id: &str, source: &str) -> Result<String, String> {
+ if source.is_empty() {
+ return Err(
+ "a media item has no file behind it; fill or remove it before saving a template"
+ .to_owned(),
+ );
+ }
+ let base = Path::new(source)
+ .file_name()
+ .and_then(|name| name.to_str())
+ .map(projects::folder_name)
+ .unwrap_or_else(|| "file".to_owned());
+ let name = format!("{}-{base}", projects::folder_name(id));
+ let destination = assets.join(&name);
+ std::fs::copy(source, &destination)
+ .map_err(|error| format!("could not bundle {source}: {error}"))?;
+ Ok(format!("{ASSETS}/{name}"))
+}
+
+/// Every template in the library, in name order.
+///
+/// A folder that does not parse is skipped rather than sinking the whole
+/// gallery - the same grace the recents list extends to vanished projects.
+pub fn list(config: &Path) -> Vec<TemplateInfo> {
+ let Ok(entries) = std::fs::read_dir(templates_dir(config)) else {
+ return Vec::new();
+ };
+ let mut templates: Vec<TemplateInfo> = entries
+ .filter_map(|entry| entry.ok())
+ .filter_map(|entry| read_info(&entry.path()).ok())
+ .collect();
+ templates.sort_by(|left, right| left.name.cmp(&right.name));
+ templates
+}
+
+/// Reads one bundle's manifest into gallery form.
+fn read_info(root: &Path) -> Result<TemplateInfo, String> {
+ let manifest = root.join(MANIFEST);
+ let bytes = std::fs::read(&manifest)
+ .map_err(|error| format!("could not read {}: {error}", manifest.display()))?;
+ let document: Value = serde_json::from_slice(&bytes)
+ .map_err(|error| format!("{} is not a template: {error}", manifest.display()))?;
+
+ let video = document.get("video").ok_or("the template names no output format")?;
+ let dimension = |field: &str| {
+ video
+ .get(field)
+ .and_then(Value::as_u64)
+ .and_then(|value| u32::try_from(value).ok())
+ .filter(|value| *value > 0)
+ .ok_or_else(|| format!("the template has no usable {field}"))
+ };
+ let rate = |field: &str| {
+ video
+ .get(field)
+ .and_then(Value::as_i64)
+ .filter(|value| *value > 0)
+ .ok_or_else(|| format!("the template has no usable {field}"))
+ };
+
+ Ok(TemplateInfo {
+ path: root.to_string_lossy().into_owned(),
+ name: document
+ .get("name")
+ .and_then(Value::as_str)
+ .unwrap_or("Template")
+ .to_owned(),
+ width: dimension("width")?,
+ height: dimension("height")?,
+ rate_num: rate("rateNum")?,
+ rate_den: rate("rateDen")?,
+ slots: slots_of(&document),
+ has_poster: root.join(POSTER).exists(),
+ })
+}
+
+/// The placeholder media of a document, ordered by when each first appears
+/// on the active timeline - the order a user fills them in.
+fn slots_of(document: &Value) -> Vec<SlotInfo> {
+ let media = document.get("media").and_then(Value::as_array);
+ // The flat top-level clips mirror the active timeline, exactly as the
+ // poster frame reads them.
+ let clips = document.get("clips").and_then(Value::as_array);
+ let (Some(media), clips) = (media, clips.map(Vec::as_slice).unwrap_or(&[])) else {
+ return Vec::new();
+ };
+
+ let mut slots: Vec<(f64, SlotInfo)> = Vec::new();
+ for item in media {
+ if !item.get("placeholder").and_then(Value::as_bool).unwrap_or(false) {
+ continue;
+ }
+ let Some(id) = item.get("id").and_then(Value::as_str) else { continue };
+
+ let mut first = f64::MAX;
+ let mut seconds = 0.0;
+ for clip in clips {
+ if clip.get("mediaId").and_then(Value::as_str) != Some(id) {
+ continue;
+ }
+ let start = clip.get("start").and_then(Value::as_f64).unwrap_or(0.0);
+ first = first.min(start);
+ seconds += clip.get("duration").and_then(Value::as_f64).unwrap_or(0.0);
+ }
+
+ slots.push((
+ first,
+ SlotInfo {
+ media_id: id.to_owned(),
+ name: item
+ .get("name")
+ .and_then(Value::as_str)
+ .unwrap_or("Slot")
+ .to_owned(),
+ kind: item
+ .get("kind")
+ .and_then(Value::as_str)
+ .unwrap_or("video")
+ .to_owned(),
+ seconds,
+ },
+ ));
+ }
+ slots.sort_by(|(left, _), (right, _)| left.total_cmp(right));
+ slots.into_iter().map(|(_, slot)| slot).collect()
+}
+
+/// Unpacks a template into a fresh project with every slot filled.
+///
+/// The fills go through the engine as one `Batch` of `FillSlot` commands, so
+/// the semantics live in `relay-project` and a half-fillable set of media
+/// leaves no half-made project behind.
+pub fn instantiate(
+ template: &str,
+ location: &str,
+ name: &str,
+ fills: Vec<SlotFill>,
+) -> Result<projects::ProjectInfo, String> {
+ let bundle = PathBuf::from(template);
+ let manifest = bundle.join(MANIFEST);
+ let bytes = std::fs::read(&manifest)
+ .map_err(|error| format!("could not read {}: {error}", manifest.display()))?;
+ let mut document: Value = serde_json::from_slice(&bytes)
+ .map_err(|error| format!("{} is not a template: {error}", manifest.display()))?;
+ let info = read_info(&bundle)?;
+
+ let unfilled: Vec<&SlotInfo> = info
+ .slots
+ .iter()
+ .filter(|slot| !fills.iter().any(|fill| fill.media_id == slot.media_id))
+ .collect();
+ if !unfilled.is_empty() {
+ return Err(format!("{} slot(s) still need a clip", unfilled.len()));
+ }
+
+ let project =
+ projects::create(location, name, info.width, info.height, info.rate_num, info.rate_den)?;
+ let root = PathBuf::from(&project.path);
+
+ // The bundle's assets move into the project so it stands alone; the
+ // document's relative paths become project-local absolute ones.
+ copy_assets(&bundle.join(ASSETS), &root.join(ASSETS))?;
+ document["name"] = Value::String(project.name.clone());
+ for section in ["media", "fonts"] {
+ if let Some(items) = document.get_mut(section).and_then(Value::as_array_mut) {
+ for item in items {
+ let Some(path) = item.get("path").and_then(Value::as_str) else { continue };
+ if let Some(relative) = path.strip_prefix(&format!("{ASSETS}/")) {
+ let absolute = root.join(ASSETS).join(relative);
+ item["path"] = Value::String(absolute.to_string_lossy().into_owned());
+ }
+ }
+ }
+ }
+
+ let mut editor = Editor::from_document(&document)
+ .ok_or("this template holds a document this build cannot read")?;
+ if !fills.is_empty() {
+ editor
+ .apply(Command::Batch {
+ commands: fills
+ .into_iter()
+ .map(|fill| Command::FillSlot { media_id: fill.media_id, item: fill.item })
+ .collect(),
+ })
+ .map_err(|error| format!("could not fill the template: {error}"))?;
+ }
+
+ let settings = DocumentSettings {
+ name: project.name.clone(),
+ width: info.width,
+ height: info.height,
+ rate_num: info.rate_num,
+ rate_den: info.rate_den,
+ };
+ projects::save(&project.path, &editor.to_document(&settings))?;
+
+ // After the save, so the cached poster reads as fresh.
+ if bundle.join(POSTER).is_file() {
+ let cache = root.join("cache");
+ let _ = std::fs::create_dir_all(&cache);
+ let _ = std::fs::copy(bundle.join(POSTER), cache.join("preview.jpg"));
+ }
+
+ Ok(project)
+}
+
+fn copy_assets(from: &Path, to: &Path) -> Result<(), String> {
+ let Ok(entries) = std::fs::read_dir(from) else {
+ return Ok(()); // a template with no bundled assets
+ };
+ std::fs::create_dir_all(to)
+ .map_err(|error| format!("could not create {}: {error}", to.display()))?;
+ for entry in entries.filter_map(|entry| entry.ok()) {
+ let source = entry.path();
+ if source.is_file() {
+ let destination = to.join(entry.file_name());
+ std::fs::copy(&source, &destination).map_err(|error| {
+ format!("could not copy {}: {error}", source.display())
+ })?;
+ }
+ }
+ Ok(())
+}
+
+/// Removes one template bundle for good.
+///
+/// Only ever a folder inside the templates directory that actually holds a
+/// manifest - this function deletes recursively, and a stray path here would
+/// be a catastrophe, so it is checked rather than trusted.
+pub fn delete(config: &Path, path: &str) -> Result<(), String> {
+ let target = PathBuf::from(path);
+ let library = templates_dir(config);
+ let (Ok(target), Ok(library)) = (target.canonicalize(), library.canonicalize()) else {
+ return Err(format!("{path} is not a template"));
+ };
+ if !target.starts_with(&library) || target == library || !target.join(MANIFEST).is_file() {
+ return Err(format!("{path} is not a template"));
+ }
+ std::fs::remove_dir_all(&target)
+ .map_err(|error| format!("could not delete {}: {error}", target.display()))
+}
+
+/// The poster bytes for one bundle, or an error the UI treats as "no art".
+pub fn poster(path: &str) -> Result<Vec<u8>, String> {
+ std::fs::read(Path::new(path).join(POSTER))
+ .map_err(|error| format!("no poster for {path}: {error}"))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ fn template_document() -> Value {
+ json!({
+ "relay": "0.1.0", "version": 1, "name": "Beat Intro",
+ "video": { "width": 1920, "height": 1080, "rateNum": 30, "rateDen": 1 },
+ "media": [
+ { "id": "m1", "path": "", "name": "A-roll", "duration": 4.0, "kind": "video",
+ "hasAudio": true, "placeholder": true },
+ { "id": "m2", "path": "", "name": "B-roll", "duration": 2.0, "kind": "video",
+ "hasAudio": false, "placeholder": true }
+ ],
+ "tracks": [{ "id": "T1", "name": "Track 1", "visible": true, "muted": false }],
+ "clips": [
+ { "id": "c2", "trackId": "T1", "mediaId": "m2", "name": "B-roll",
+ "kind": "video", "start": 4.0, "duration": 2.0, "sourceStart": 0.0,
+ "volume": 1.0, "fadeIn": 0.0, "fadeOut": 0.0, "scale": 1.0,
+ "offsetX": 0.0, "offsetY": 0.0, "rotation": 0.0, "opacity": 1.0,
+ "speed": 1.0, "preservePitch": true, "filters": [], "videoEffects": [] },
+ { "id": "c1", "trackId": "T1", "mediaId": "m1", "name": "A-roll",
+ "kind": "video", "start": 0.0, "duration": 4.0, "sourceStart": 1.0,
+ "volume": 1.0, "fadeIn": 0.0, "fadeOut": 0.0, "scale": 1.0,
+ "offsetX": 0.0, "offsetY": 0.0, "rotation": 0.0, "opacity": 1.0,
+ "speed": 1.0, "preservePitch": true, "filters": [], "videoEffects": [] }
+ ]
+ })
+ }
+
+ #[test]
+ fn slots_come_back_in_timeline_order() {
+ // c2 is listed first but starts later; the fill order is by time.
+ let slots = slots_of(&template_document());
+ assert_eq!(slots.len(), 2);
+ assert_eq!(slots[0].media_id, "m1");
+ assert_eq!(slots[0].seconds, 4.0);
+ assert_eq!(slots[1].media_id, "m2");
+ }
+
+ #[test]
+ fn saving_packs_a_bundle_and_it_round_trips() {
+ let scratch = std::env::temp_dir().join("wolfcut-template-save-test");
+ let _ = std::fs::remove_dir_all(&scratch);
+ let config = scratch.join("config");
+ let project = scratch.join("project");
+ std::fs::create_dir_all(&project).expect("scratch dirs");
+
+ // A real file for the bundled music; the placeholder needs none.
+ let music = project.join("music.mp3");
+ std::fs::write(&music, b"not really an mp3").expect("writes");
+
+ let mut document = template_document();
+ {
+ let media = document["media"].as_array_mut().expect("media");
+ // m1 stays a placeholder; m2 becomes ordinary bundled media.
+ media[1]["placeholder"] = Value::Bool(false);
+ media[1]["path"] = Value::String(music.to_string_lossy().into_owned());
+ media[1]["kind"] = Value::String("audio".to_owned());
+ }
+
+ let info = save(&config, &document, &project.to_string_lossy(), "Beat Intro")
+ .expect("saves");
+ assert_eq!(info.name, "Beat Intro");
+ assert_eq!(info.slots.len(), 1, "only the placeholder is a slot");
+ assert_eq!(info.slots[0].media_id, "m1");
+
+ // The same name again is refused, not overwritten.
+ assert!(save(&config, &document, &project.to_string_lossy(), "Beat Intro").is_err());
+
+ let bundle = PathBuf::from(&info.path);
+ let packed: Value = serde_json::from_slice(
+ &std::fs::read(bundle.join(MANIFEST)).expect("manifest"),
+ )
+ .expect("parses");
+ let media = packed["media"].as_array().expect("media");
+ assert_eq!(media[0]["path"], "", "the placeholder's path is blanked");
+ let bundled = media[1]["path"].as_str().expect("path");
+ assert!(bundled.starts_with("assets/"), "bundled media went relative: {bundled}");
+ assert!(bundle.join(bundled).is_file(), "and the file really is in the bundle");
+
+ assert_eq!(list(&config).len(), 1, "the library sees it");
+
+ // And it instantiates: the asset lands in the project, absolute.
+ let location = scratch.join("projects");
+ std::fs::create_dir_all(&location).expect("scratch dir");
+ let made = instantiate(
+ &info.path,
+ &location.to_string_lossy(),
+ "From bundle",
+ vec![SlotFill {
+ media_id: "m1".to_owned(),
+ item: relay_project::commands::NewMedia {
+ path: "/mine/clip.mp4".to_owned(),
+ name: "clip.mp4".to_owned(),
+ duration: Some(6.0),
+ kind: relay_project::model::MediaKind::Video,
+ width: Some(1920),
+ height: Some(1080),
+ frame_rate: Some(30.0),
+ frame_rate_fraction: Some("30/1".to_owned()),
+ video_codec: Some("h264".to_owned()),
+ audio_codec: None,
+ has_audio: false,
+ },
+ }],
+ )
+ .expect("instantiates");
+
+ let opened = projects::read_document(&made.path).expect("reads back");
+ let media = opened["media"].as_array().expect("media");
+ let sound = media[1]["path"].as_str().expect("path");
+ assert!(
+ Path::new(sound).is_absolute() && Path::new(sound).is_file(),
+ "the bundled asset was copied into the project and repointed: {sound}"
+ );
+
+ let _ = std::fs::remove_dir_all(&scratch);
+ }
+
+ #[test]
+ fn instantiating_fills_through_the_engine() {
+ let scratch = std::env::temp_dir().join("wolfcut-template-test");
+ let _ = std::fs::remove_dir_all(&scratch);
+ let bundle = scratch.join("templates").join("Beat Intro");
+ std::fs::create_dir_all(&bundle).expect("scratch dir");
+ std::fs::write(
+ bundle.join(MANIFEST),
+ serde_json::to_vec(&template_document()).expect("encodes"),
+ )
+ .expect("writes");
+
+ let fill = |media_id: &str, path: &str| SlotFill {
+ media_id: media_id.to_owned(),
+ item: relay_project::commands::NewMedia {
+ path: path.to_owned(),
+ name: path.rsplit('/').next().unwrap_or(path).to_owned(),
+ duration: Some(9.0),
+ kind: relay_project::model::MediaKind::Video,
+ width: Some(1920),
+ height: Some(1080),
+ frame_rate: Some(30.0),
+ frame_rate_fraction: Some("30/1".to_owned()),
+ video_codec: Some("h264".to_owned()),
+ audio_codec: None,
+ has_audio: false,
+ },
+ };
+
+ let projects_dir = scratch.join("projects");
+ std::fs::create_dir_all(&projects_dir).expect("scratch dir");
+ let location = projects_dir.to_string_lossy().into_owned();
+
+ // Missing a slot is refused before any folder is written.
+ let refused = instantiate(
+ &bundle.to_string_lossy(),
+ &location,
+ "Missing",
+ vec![fill("m1", "/mine/a.mp4")],
+ );
+ assert!(refused.unwrap_err().contains("slot"));
+
+ let project = instantiate(
+ &bundle.to_string_lossy(),
+ &location,
+ "My edit",
+ vec![fill("m1", "/mine/a.mp4"), fill("m2", "/mine/b.mp4")],
+ )
+ .expect("instantiates");
+ assert_eq!((project.width, project.height), (1920, 1080));
+
+ let document = projects::read_document(&project.path).expect("reads back");
+ let media = document["media"].as_array().expect("media");
+ assert!(media.iter().all(|item| {
+ !item.get("placeholder").and_then(Value::as_bool).unwrap_or(false)
+ }));
+ assert_eq!(media[0]["path"], "/mine/a.mp4");
+ // The slot kept the template's timing; the in-point reset (c1 had 1.0).
+ let clips = document["clips"].as_array().expect("clips");
+ let c1 = clips.iter().find(|clip| clip["id"] == "c1").expect("c1");
+ assert_eq!(c1["start"], 0.0);
+ assert_eq!(c1["duration"], 4.0);
+ assert_eq!(c1["sourceStart"], 0.0);
+
+ let _ = std::fs::remove_dir_all(&scratch);
+ }
+}
diff --git a/desktop/src/App.tsx b/desktop/src/App.tsx
index e1b8fe7c..86cff743 100644
--- a/desktop/src/App.tsx
+++ b/desktop/src/App.tsx
@@ -13,6 +13,7 @@ import type { MenuOption } from "./components/Menu";
import { Preview, type PreviewSource, type TextOverlay } from "./components/Preview";
import { Resizer } from "./components/Resizer";
import { RightPanel, type RightTab } from "./components/RightPanel";
+import { SaveTemplateDialog } from "./components/SaveTemplateDialog";
import { SettingsDialog } from "./components/SettingsDialog";
import { StartScreen, type ProjectSession } from "./components/StartScreen";
import { TitleBar } from "./components/TitleBar";
@@ -51,11 +52,14 @@ import {
editorSave,
editorUndo,
engineVersion,
+ newMediaFromSummary,
previewFrame,
probeMedia,
readMediaBytes,
+ templateSave,
transcribeClip,
type ExportClip,
+ type TemplateInfo,
} from "./lib/engine";
import { getTranscriberLanguage, getTranscriberModel } from "./lib/settings";
import { buildChain } from "./lib/filters";
@@ -98,6 +102,9 @@ const EMPTY_PROJECT: EditorProject = {
*/
export function App() {
const [session, setSession] = useState<ProjectSession | null>(null);
+ // Choosing "use template" inside the editor closes the project and lands
+ // the launch screen straight in that template's fill mode.
+ const [pendingTemplate, setPendingTemplate] = useState<TemplateInfo | null>(null);
// Owned here rather than in the editor so the launch screen is themed too,
// and so the choice survives closing a project.
const { theme, toggle } = useTheme();
@@ -107,7 +114,13 @@ export function App() {
<div className="flex h-full flex-col overflow-hidden">
<TitleBar projectName="" menus={[]} theme={theme} onToggleTheme={toggle} />
<div className="min-h-0 flex-1">
- <StartScreen onCreate={setSession} />
+ <StartScreen
+ initialTemplate={pendingTemplate}
+ onCreate={(next) => {
+ setPendingTemplate(null);
+ setSession(next);
+ }}
+ />
</div>
</div>
);
@@ -119,6 +132,10 @@ export function App() {
theme={theme}
onToggleTheme={toggle}
onCloseProject={() => setSession(null)}
+ onUseTemplate={(template) => {
+ setPendingTemplate(template);
+ setSession(null);
+ }}
/>
);
}
@@ -138,11 +155,14 @@ function Editor({
theme,
onToggleTheme,
onCloseProject,
+ onUseTemplate,
}: {
session: ProjectSession;
theme: Theme;
onToggleTheme: () => void;
onCloseProject: () => void;
+ /** Leaves this project for the launch screen's fill flow on a template. */
+ onUseTemplate: (template: TemplateInfo) => void;
}) {
const [view, setView] = useState<EditorView | null>(null);
const [echo, setEcho] = useState<Echo | null>(null);
@@ -171,7 +191,9 @@ function Editor({
const [frame, setFrame] = useState({ width: session.width, height: session.height });
// Panel geometry.
- const [leftWidth, setLeftWidth] = useState(340);
+ // Wide enough that the library's five tabs and a row of cards breathe;
+ // the resizer still allows 220-560.
+ const [leftWidth, setLeftWidth] = useState(420);
const [rightWidth, setRightWidth] = useState(300);
const [timelineHeight, setTimelineHeight] = useState(340);
@@ -397,6 +419,9 @@ function Editor({
);
const [settingsOpen, setSettingsOpen] = useState(false);
+ // The save-as-template sheet: null closed, otherwise whether the host is
+ // packing the bundle right now.
+ const [templateDialog, setTemplateDialog] = useState<null | { busy: boolean }>(null);
const [transcribing, setTranscribing] = useState(false);
useEffect(() => {
@@ -446,22 +471,9 @@ function Editor({
for (const path of paths) {
try {
const summary = await probeMedia(path);
- const name = summary.path.split(/[\\/]/).pop() ?? summary.path;
const mediaId = await dispatch({
op: "addMedia",
- item: {
- path: summary.path,
- name,
- duration: summary.duration,
- kind: summary.kind,
- width: summary.video?.width ?? null,
- height: summary.video?.height ?? null,
- frameRate: summary.video?.frameRate ?? null,
- frameRateFraction: summary.video?.frameRateFraction ?? null,
- videoCodec: summary.video?.codec ?? null,
- audioCodec: summary.audio?.codec ?? null,
- hasAudio: summary.audio !== null,
- },
+ item: newMediaFromSummary(summary),
});
if (mediaId) {
setSelectedMediaId(mediaId);
@@ -1280,6 +1292,11 @@ function Editor({
disabled: exportClips.length === 0,
onSelect: () => setExporting(true),
},
+ {
+ label: "Save as template...",
+ icon: "slot",
+ onSelect: () => setTemplateDialog({ busy: false }),
+ },
],
[
{
@@ -1396,6 +1413,17 @@ function Editor({
onAddToTimeline={addToTimeline}
onApplyEffect={applyEffect}
onApplyTransition={applyTransition}
+ onToggleSlot={(mediaId, placeholder) =>
+ void dispatch({ op: "setMediaPlaceholder", mediaId, placeholder })
+ }
+ onSaveTemplate={() => setTemplateDialog({ busy: false })}
+ onUseTemplate={(template) => {
+ // Save what is open first: leaving for the fill flow closes
+ // this project, and the debounced autosave may not have fired.
+ void editorSave(latest.current.frame)
+ .catch(() => undefined)
+ .then(() => onUseTemplate(template));
+ }}
/>
</div>
@@ -1663,6 +1691,31 @@ function Editor({
{context && <ContextMenu target={context} onClose={() => setContext(null)} />}
{settingsOpen && <SettingsDialog onClose={() => setSettingsOpen(false)} />}
+ {templateDialog && (
+ <SaveTemplateDialog
+ defaultName={session.name}
+ slotCount={project.media.filter((item) => item.placeholder).length}
+ busy={templateDialog.busy}
+ onSave={(name) => {
+ setTemplateDialog({ busy: true });
+ templateSave(name)
+ .then((info) => {
+ setTemplateDialog(null);
+ setToast({
+ id: Date.now(),
+ message: `Saved template "${info.name}"`,
+ failed: false,
+ });
+ })
+ .catch((cause: unknown) => {
+ setTemplateDialog({ busy: false });
+ setToast({ id: Date.now(), message: String(cause), failed: true });
+ });
+ }}
+ onCancel={() => setTemplateDialog(null)}
+ />
+ )}
+
{timelineToDelete && (
<ConfirmDialog
title={`Delete "${timelineToDelete.name}"?`}
diff --git a/desktop/src/components/Icon.tsx b/desktop/src/components/Icon.tsx
index c1d9f30d..b64fb846 100644
--- a/desktop/src/components/Icon.tsx
+++ b/desktop/src/components/Icon.tsx
@@ -262,6 +262,13 @@ const GLYPHS = {
</>
),
// a four-point star with a smaller companion, for "effects"
+ // slot: a dashed placeholder box - the frame a template fills in later
+ slot: (
+ <>
+ <rect x="3.5" y="5.5" width="17" height="13" rx="2.5" strokeDasharray="3.2 2.6" />
+ <path d="M12 9.5v5M9.5 12h5" />
+ </>
+ ),
sparkles: (
<>
<path d="M10 3.5l1.7 4.3 4.3 1.7-4.3 1.7L10 15.5l-1.7-4.3L4 9.5l4.3-1.7z" />
diff --git a/desktop/src/components/MediaBin.tsx b/desktop/src/components/MediaBin.tsx
index 689f91cf..1a359cfb 100644
--- a/desktop/src/components/MediaBin.tsx
+++ b/desktop/src/components/MediaBin.tsx
@@ -13,11 +13,13 @@ import {
type TransitionCategory,
} from "../lib/effects";
import type { MediaItem } from "../lib/editor";
+import { templateDelete, templateList, type TemplateInfo } from "../lib/engine";
import { themeColor } from "../lib/theme";
import { shortDuration } from "../lib/time";
import { ErrorNotice } from "./ErrorNotice";
import { Icon } from "./Icon";
import { Empty, Panel } from "./Panel";
+import { TemplateThumb } from "./TemplateThumb";
/** Which kinds of media the bin is showing. */
export interface BinFilter {
@@ -29,13 +31,14 @@ export interface BinFilter {
export const ALL_MEDIA: BinFilter = { video: true, audio: true, image: true };
/** The pages of the library strip, in display order. */
-type LibraryTab = "media" | "text" | "transitions" | "effects";
+type LibraryTab = "media" | "text" | "transitions" | "effects" | "templates";
const TABS: { id: LibraryTab; label: string }[] = [
{ id: "media", label: "Media" },
{ id: "text", label: "Text" },
{ id: "transitions", label: "Transitions" },
{ id: "effects", label: "Effects" },
+ { id: "templates", label: "Templates" },
];
/**
@@ -72,6 +75,9 @@ export function MediaBin({
onAddToTimeline,
onApplyEffect,
onApplyTransition,
+ onToggleSlot,
+ onUseTemplate,
+ onSaveTemplate,
assets,
dropping,
}: {
@@ -98,6 +104,12 @@ export function MediaBin({
onApplyEffect: (effectId: string) => void;
/** Puts a transition on the selected clip's cut; the app validates. */
onApplyTransition: (transitionId: string) => void;
+ /** Marks or unmarks a media item as a template slot. */
+ onToggleSlot: (mediaId: string, placeholder: boolean) => void;
+ /** Takes the user to the fill flow for one template. */
+ onUseTemplate: (template: TemplateInfo) => void;
+ /** Opens the save-as-template sheet for the current project. */
+ onSaveTemplate: () => void;
}) {
const [tab, setTab] = useState<LibraryTab>("media");
const [effectCategory, setEffectCategory] = useState<EffectCategory>("basic");
@@ -120,8 +132,11 @@ export function MediaBin({
type="button"
aria-pressed={tab === entry.id}
onClick={() => setTab(entry.id)}
- className={`flex-1 cursor-pointer truncate rounded-md px-1.5 py-1 text-[11px]
- transition-colors ${
+ // flex-auto, not flex-1: extra space is shared, but each tab's
+ // base is its own label, so "Transitions" is never crammed to
+ // make room for padding around "Text".
+ className={`min-w-0 flex-auto cursor-pointer truncate rounded-md px-1.5 py-1
+ text-[11px] transition-colors ${
tab === entry.id
? "bg-panel text-primary shadow-[0_1px_2px_rgba(0,0,0,0.14)]"
: "text-secondary hover:text-primary"
@@ -166,6 +181,11 @@ export function MediaBin({
))}
</CategoryGroup>
)}
+ {tab === "templates" && (
+ <CategoryGroup title="Templates">
+ <CategoryRow label="My templates" selected onSelect={() => {}} />
+ </CategoryGroup>
+ )}
</aside>
<div className="thin-scroll min-w-0 flex-1 overflow-y-auto">
@@ -184,6 +204,7 @@ export function MediaBin({
onDismissError={onDismissError}
onBeginDrag={onBeginDrag}
onAddToTimeline={onAddToTimeline}
+ onToggleSlot={onToggleSlot}
/>
)}
{tab === "text" && <TextPage onAddText={onAddText} />}
@@ -191,6 +212,9 @@ export function MediaBin({
<TransitionsPage category={transitionCategory} onApply={onApplyTransition} />
)}
{tab === "effects" && <EffectsPage category={effectCategory} onApply={onApplyEffect} />}
+ {tab === "templates" && (
+ <TemplatesPage onUse={onUseTemplate} onSaveTemplate={onSaveTemplate} />
+ )}
</div>
</div>
</div>
@@ -315,6 +339,7 @@ function MediaPage({
onDismissError,
onBeginDrag,
onAddToTimeline,
+ onToggleSlot,
}: {
items: MediaItem[];
filter: BinFilter;
@@ -329,6 +354,7 @@ function MediaPage({
onDismissError: () => void;
onBeginDrag: (item: MediaItem, clientX: number, clientY: number) => void;
onAddToTimeline: (mediaId: string) => void;
+ onToggleSlot: (mediaId: string, placeholder: boolean) => void;
}) {
const browse = async () => {
if (busy) return;
@@ -456,6 +482,44 @@ Drag onto a track, or double-click to add at the playhead`}
{item.kind === "image" ? "still" : shortDuration(item.duration)}
</span>
+ {/* The slot state stays visible; only the controls are hover-only.
+ A template's whole point is which items are slots. */}
+ {item.placeholder && (
+ <span className="pointer-events-none absolute bottom-1 left-1 flex items-center
+ gap-1 rounded bg-accent px-1 py-px font-technical text-[10px]
+ text-on-accent">
+ <Icon name="slot" size={9} />
+ Slot
+ </span>
+ )}
+
+ <button
+ type="button"
+ aria-pressed={item.placeholder ?? false}
+ aria-label={
+ item.placeholder
+ ? `Unmark ${item.name} as a template slot`
+ : `Mark ${item.name} as a template slot`
+ }
+ title={
+ item.placeholder
+ ? "No longer a template slot"
+ : "Make this a template slot: saved templates ask for the user's own media here"
+ }
+ onClick={(event) => {
+ event.stopPropagation();
+ onToggleSlot(item.id, !item.placeholder);
+ }}
+ className={`absolute right-7 top-1 cursor-pointer rounded p-1 text-white
+ transition-colors hover:bg-accent ${
+ item.placeholder
+ ? "bg-accent"
+ : "invisible bg-black/55 group-hover:visible"
+ }`}
+ >
+ <Icon name="slot" size={10} />
+ </button>
+
<button
type="button"
aria-label={`Remove ${item.name}`}
@@ -617,6 +681,103 @@ function EffectsPage({
);
}
+// ── the templates page ───────────────────────────────────────────────────────
+
+/**
+ * The template gallery, in the library where CapCut keeps its own.
+ *
+ * Using a template means leaving this project for the fill flow on the launch
+ * screen - a template makes a *new* project - so the card's verb hands off
+ * rather than pretending to drag. Loaded fresh each time the tab opens, which
+ * is what makes a just-saved template appear without any plumbing.
+ */
+function TemplatesPage({
+ onUse,
+ onSaveTemplate,
+}: {
+ onUse: (template: TemplateInfo) => void;
+ onSaveTemplate: () => void;
+}) {
+ const [templates, setTemplates] = useState<TemplateInfo[] | null>(null);
+
+ useEffect(() => {
+ let cancelled = false;
+ void templateList()
+ .then((list) => !cancelled && setTemplates(list))
+ .catch(() => !cancelled && setTemplates([]));
+ return () => {
+ cancelled = true;
+ };
+ }, []);
+
+ const remove = async (doomed: TemplateInfo) => {
+ setTemplates((current) =>
+ current ? current.filter((entry) => entry.path !== doomed.path) : current,
+ );
+ await templateDelete(doomed.path).catch(() => undefined);
+ };
+
+ return (
+ <>
+ <div className="px-2 pb-2 pt-2">
+ <button
+ type="button"
+ onClick={onSaveTemplate}
+ className="flex w-full cursor-pointer items-center justify-center gap-2 rounded-lg
+ border border-dashed border-hairline-strong px-3 py-2.5 text-xs text-secondary
+ transition-colors hover:border-accent hover:bg-hover hover:text-primary"
+ >
+ <Icon name="slot" size={14} />
+ Save this project as a template
+ </button>
+ </div>
+
+ {templates !== null && templates.length === 0 ? (
+ <Empty icon={<Icon name="slot" size={28} strokeWidth={1.5} />}>
+ No templates yet. Mark media as slots, then save this project as a template - it will
+ ask for the user's own clips in those slots.
+ </Empty>
+ ) : (
+ <ul className={CARD_GRID}>
+ {(templates ?? []).map((template) => (
+ <li key={template.path} className="group relative select-none">
+ <button
+ type="button"
+ title={`${template.name}
+${template.slots.length} slot${template.slots.length === 1 ? "" : "s"} · ${template.width} x ${template.height}
+Click to start a new project from this template`}
+ onClick={() => onUse(template)}
+ className="w-full cursor-pointer text-left"
+ >
+ <TemplateThumb template={template} />
+ <span className="mt-1 block truncate text-[11px] leading-tight text-secondary">
+ {template.name}
+ </span>
+ <span className="block font-technical text-[10px] text-tertiary">
+ {template.slots.length} slot{template.slots.length === 1 ? "" : "s"}
+ </span>
+ </button>
+ <button
+ type="button"
+ aria-label={`Delete the template ${template.name}`}
+ title="Delete this template for good"
+ onClick={(event) => {
+ event.stopPropagation();
+ void remove(template);
+ }}
+ className="invisible absolute right-1 top-1 cursor-pointer rounded bg-black/55 p-1
+ text-white transition-colors hover:bg-danger group-hover:visible"
+ >
+ <Icon name="trash" size={10} />
+ </button>
+ </li>
+ ))}
+ </ul>
+ )}
+ </>
+ );
+}
+
// ── thumbnails ───────────────────────────────────────────────────────────────
/**
diff --git a/desktop/src/components/SaveTemplateDialog.tsx b/desktop/src/components/SaveTemplateDialog.tsx
new file mode 100644
index 00000000..5ed787af
--- /dev/null
+++ b/desktop/src/components/SaveTemplateDialog.tsx
@@ -0,0 +1,99 @@
+import { useEffect, useState } from "react";
+
+import { Icon } from "./Icon";
+
+/**
+ * Names and saves the open project as a template.
+ *
+ * The one decision it asks for is the name; the substance - which media are
+ * slots - was decided in the bin, so the dialog only reports it. Zero slots
+ * is allowed (a starter project is a legitimate template) but flagged, since
+ * forgetting to mark slots is the likelier reading, and everything that is
+ * not a slot ships inside the bundle by copy.
+ */
+export function SaveTemplateDialog({
+ defaultName,
+ slotCount,
+ busy,
+ onSave,
+ onCancel,
+}: {
+ defaultName: string;
+ /** How many media items are marked as slots right now. */
+ slotCount: number;
+ busy: boolean;
+ onSave: (name: string) => void;
+ onCancel: () => void;
+}) {
+ const [name, setName] = useState(defaultName);
+
+ useEffect(() => {
+ const onKey = (event: KeyboardEvent) => {
+ if (event.key === "Escape") onCancel();
+ };
+ window.addEventListener("keydown", onKey);
+ return () => window.removeEventListener("keydown", onKey);
+ }, [onCancel]);
+
+ const save = () => {
+ const trimmed = name.trim();
+ if (trimmed && !busy) onSave(trimmed);
+ };
+
+ return (
+ <div
+ className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-8
+ backdrop-blur-[2px]"
+ onMouseDown={(event) => {
+ if (event.target === event.currentTarget) onCancel();
+ }}
+ >
+ <div className="surface w-full max-w-sm rounded-2xl p-6">
+ <div className="mb-2 flex items-center gap-2">
+ <Icon name="slot" size={16} className="text-accent" />
+ <h2 className="text-sm font-semibold text-primary">Save as template</h2>
+ </div>
+ <p className="mb-4 text-xs leading-relaxed text-secondary">
+ {slotCount > 0
+ ? `${slotCount} slot${slotCount === 1 ? "" : "s"} will ask for the user's own media. ` +
+ "Everything else - music, overlays, titles - is copied into the template."
+ : "No media is marked as a slot, so this template opens as a ready-made project. " +
+ "Mark slots in the bin first if users should supply their own clips."}
+ </p>
+
+ <input
+ value={name}
+ autoFocus
+ spellCheck={false}
+ placeholder="Template name"
+ onChange={(event) => setName(event.target.value)}
+ onFocus={(event) => event.currentTarget.select()}
+ onKeyDown={(event) => event.key === "Enter" && save()}
+ className="mb-5 w-full rounded-lg bg-sunken px-3 py-2 text-sm text-primary outline-none
+ ring-1 ring-hairline focus:ring-accent placeholder:text-tertiary"
+ />
+
+ <div className="flex gap-1.5">
+ <button
+ type="button"
+ onClick={onCancel}
+ className="flex-1 cursor-pointer rounded-lg bg-hover px-4 py-2 text-sm text-primary
+ transition-colors hover:bg-active"
+ >
+ Cancel
+ </button>
+ <button
+ type="button"
+ disabled={busy || !name.trim()}
+ onClick={save}
+ className="flex-1 cursor-pointer rounded-lg bg-accent px-4 py-2 text-sm font-medium
+ text-on-accent transition-colors hover:bg-accent-hover
+ disabled:cursor-not-allowed disabled:opacity-40"
+ >
+ {busy ? "Saving..." : "Save template"}
+ </button>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/desktop/src/components/StartScreen.tsx b/desktop/src/components/StartScreen.tsx
index c12b3261..6c352e0d 100644
--- a/desktop/src/components/StartScreen.tsx
+++ b/desktop/src/components/StartScreen.tsx
@@ -6,14 +6,23 @@ import { desktopDir, join } from "@tauri-apps/api/path";
import {
createProject,
forgetProject,
+ newMediaFromSummary,
openProject,
+ probeMedia,
projectPreview,
recentProjects,
+ templateDelete,
+ templateInstantiate,
+ templateList,
type ProjectInfo,
+ type SlotFill,
+ type TemplateInfo,
+ type TemplateSlot,
} from "../lib/engine";
import { ErrorNotice } from "./ErrorNotice";
import { relativeTime } from "../lib/time";
import { Icon } from "./Icon";
+import { TemplateThumb } from "./TemplateThumb";
/** The settings a project is created with. Fixed for its lifetime, for now. */
export interface ProjectSession {
@@ -57,14 +66,27 @@ const FRAME_RATES = [
* frame rate, size and location are decisions the whole edit depends on, and
* choosing them after material is cut is how you end up conforming footage.
*/
-export function StartScreen({ onCreate }: { onCreate: (session: ProjectSession) => void }) {
- const [name, setName] = useState("Untitled project");
+export function StartScreen({
+ onCreate,
+ initialTemplate = null,
+}: {
+ onCreate: (session: ProjectSession) => void;
+ /** Opens straight into a template's fill mode - how "Use template" from
+ * inside the editor lands here. */
+ initialTemplate?: TemplateInfo | null;
+}) {
+ const [name, setName] = useState(initialTemplate?.name ?? "Untitled project");
const [location, setLocation] = useState("");
const [resolution, setResolution] = useState<(typeof RESOLUTIONS)[number]>(RESOLUTIONS[0]);
const [rate, setRate] = useState<(typeof FRAME_RATES)[number]>(FRAME_RATES[3]);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [recents, setRecents] = useState<ProjectInfo[]>([]);
+ const [templates, setTemplates] = useState<TemplateInfo[]>([]);
+ /** A chosen template swaps the form into fill mode. */
+ const [template, setTemplate] = useState<TemplateInfo | null>(initialTemplate);
+ /** The chosen media per slot, keyed by the slot's media id. */
+ const [fills, setFills] = useState<Record<string, SlotFill>>({});
// Default to Desktop/WolfCut. Failing to resolve it is not worth surfacing;
// the field simply starts empty and Choose still works.
@@ -79,8 +101,80 @@ export function StartScreen({ onCreate }: { onCreate: (session: ProjectSession)
void recentProjects()
.then(setRecents)
.catch(() => undefined);
+ void templateList()
+ .then(setTemplates)
+ .catch(() => undefined);
}, []);
+ const chooseTemplate = (chosen: TemplateInfo) => {
+ setTemplate(chosen);
+ setFills({});
+ setError(null);
+ setName(chosen.name);
+ };
+
+ const removeTemplate = async (doomed: TemplateInfo) => {
+ setTemplates((current) => current.filter((entry) => entry.path !== doomed.path));
+ if (template?.path === doomed.path) setTemplate(null);
+ await templateDelete(doomed.path).catch(() => undefined);
+ };
+
+ /** Asks for one slot's file and probes it into fill shape. */
+ const pickSlot = async (slot: TemplateSlot) => {
+ if (busy) return;
+ const chosen = await open({
+ multiple: false,
+ title: `Choose media for "${slot.name}"`,
+ filters: [
+ slot.kind === "audio"
+ ? { name: "Audio", extensions: ["mp3", "wav", "flac", "aac", "m4a", "ogg", "opus"] }
+ : {
+ // A photo in a video slot is fine - it freeze-frames for the
+ // slot's length - so visual slots take either.
+ name: "Video or images",
+ extensions: [
+ "mp4", "mov", "mkv", "webm", "avi", "m4v",
+ "png", "jpg", "jpeg", "webp", "bmp", "tif", "tiff", "avif", "gif",
+ ],
+ },
+ { name: "All files", extensions: ["*"] },
+ ],
+ });
+ if (typeof chosen !== "string") return;
+
+ setError(null);
+ try {
+ const summary = await probeMedia(chosen);
+ setFills((current) => ({
+ ...current,
+ [slot.mediaId]: { mediaId: slot.mediaId, item: newMediaFromSummary(summary) },
+ }));
+ } catch (cause) {
+ setError(String(cause));
+ }
+ };
+
+ const createFromTemplate = async () => {
+ if (!template || busy || !location.trim()) return;
+ const ready = template.slots.every((slot) => fills[slot.mediaId]);
+ if (!ready) return;
+
+ setBusy(true);
+ setError(null);
+ try {
+ const project = await templateInstantiate({
+ template: template.path,
+ location: location.trim(),
+ name: name.trim() || template.name,
+ fills: template.slots.map((slot) => fills[slot.mediaId]),
+ });
+ onCreate(toSession(project));
+ } catch (cause) {
+ setError(String(cause));
+ setBusy(false);
+ }
+ };
+
const reopen = async (project: ProjectInfo) => {
if (busy) return;
setBusy(true);
@@ -155,11 +249,25 @@ export function StartScreen({ onCreate }: { onCreate: (session: ProjectSession)
>
<div className="min-w-0">
<header className="mb-10">
+ {template && (
+ <button
+ type="button"
+ onClick={() => setTemplate(null)}
+ className="mb-3 flex cursor-pointer items-center gap-1 text-[12px] text-accent
+ transition-opacity hover:opacity-70"
+ >
+ <Icon name="chevronRight" size={11} className="rotate-180" />
+ All templates
+ </button>
+ )}
<h1 className="font-display text-[34px] font-semibold leading-tight tracking-[-0.03em] text-primary">
- New project
+ {template ? template.name : "New project"}
</h1>
<p className="mt-1.5 text-sm text-secondary">
- These settings apply to the whole edit and cannot be changed later.
+ {template
+ ? `Pick a clip for each slot. The template's timing, music and effects stay as designed - ` +
+ `${template.width} x ${template.height} at ${(template.rateNum / template.rateDen).toFixed(2)} fps.`
+ : "These settings apply to the whole edit and cannot be changed later."}
</p>
</header>
@@ -197,39 +305,96 @@ export function StartScreen({ onCreate }: { onCreate: (session: ProjectSession)
</div>
</Field>
- <Field label="Resolution">
- <Segmented
- options={RESOLUTIONS.map((option) => option.label)}
- value={resolution.label}
- onChange={(label) =>
- setResolution(RESOLUTIONS.find((option) => option.label === label) ?? RESOLUTIONS[0])
- }
- />
- <p className="mt-2 font-technical text-[11px] text-tertiary">
- {resolution.width} x {resolution.height}
- </p>
- </Field>
+ {!template && (
+ <>
+ <Field label="Resolution">
+ <Segmented
+ options={RESOLUTIONS.map((option) => option.label)}
+ value={resolution.label}
+ onChange={(label) =>
+ setResolution(
+ RESOLUTIONS.find((option) => option.label === label) ?? RESOLUTIONS[0],
+ )
+ }
+ />
+ <p className="mt-2 font-technical text-[11px] text-tertiary">
+ {resolution.width} x {resolution.height}
+ </p>
+ </Field>
- <Field label="Frame rate" last>
- <Segmented
- options={FRAME_RATES.map((option) => option.label)}
- value={rate.label}
- onChange={(label) =>
- setRate(FRAME_RATES.find((option) => option.label === label) ?? FRAME_RATES[3])
- }
- />
- <p className="mt-2 font-technical text-[11px] text-tertiary">
- {rate.num}/{rate.den} fps
- </p>
- </Field>
+ <Field label="Frame rate" last>
+ <Segmented
+ options={FRAME_RATES.map((option) => option.label)}
+ value={rate.label}
+ onChange={(label) =>
+ setRate(FRAME_RATES.find((option) => option.label === label) ?? FRAME_RATES[3])
+ }
+ />
+ <p className="mt-2 font-technical text-[11px] text-tertiary">
+ {rate.num}/{rate.den} fps
+ </p>
+ </Field>
+ </>
+ )}
+
+ {template && (
+ <Field label={`Slots (${template.slots.length})`} last>
+ <ul className="flex flex-col gap-1.5">
+ {template.slots.map((slot, index) => {
+ const fill = fills[slot.mediaId];
+ return (
+ <li key={slot.mediaId} className="flex items-center gap-2.5">
+ <span
+ className={`flex h-8 w-12 shrink-0 items-center justify-center rounded-md
+ ${fill ? "bg-accent-soft text-accent" : "bg-sunken text-tertiary"}`}
+ >
+ <Icon
+ name={
+ slot.kind === "audio" ? "music" : slot.kind === "image" ? "image" : "film"
+ }
+ size={13}
+ />
+ </span>
+ <span className="min-w-0 flex-1">
+ <span className="block truncate text-[13px] text-primary">
+ {fill ? fill.item.name : `${index + 1}. ${slot.name}`}
+ </span>
+ <span className="block font-technical text-[11px] text-tertiary">
+ {slot.kind} · {slot.seconds.toFixed(1)}s on the timeline
+ </span>
+ </span>
+ <button
+ type="button"
+ disabled={busy}
+ onClick={() => void pickSlot(slot)}
+ className="shrink-0 cursor-pointer text-[13px] text-accent transition-opacity
+ hover:opacity-70 disabled:cursor-not-allowed disabled:opacity-40"
+ >
+ {fill ? "Change..." : "Choose..."}
+ </button>
+ </li>
+ );
+ })}
+ {template.slots.length === 0 && (
+ <li className="text-[12px] text-tertiary">
+ This template has no slots - it opens ready-made.
+ </li>
+ )}
+ </ul>
+ </Field>
+ )}
{error && <ErrorNotice message={error} onDismiss={() => setError(null)} className="mt-6" />}
<div className="mt-10 flex items-center gap-4">
<button
type="button"
- onClick={() => void create()}
- disabled={busy || !location.trim()}
+ onClick={() => void (template ? createFromTemplate() : create())}
+ disabled={
+ busy ||
+ !location.trim() ||
+ (template !== null && !template.slots.every((slot) => fills[slot.mediaId]))
+ }
className="cursor-pointer rounded-full bg-accent px-6 py-2.5 text-[14px] font-medium
text-on-accent transition-colors hover:bg-accent-hover
disabled:cursor-not-allowed disabled:opacity-40"
@@ -238,9 +403,55 @@ export function StartScreen({ onCreate }: { onCreate: (session: ProjectSession)
</button>
<p className="flex items-center gap-1.5 text-[11px] text-tertiary">
<Icon name="info" size={12} className="shrink-0" />
- The timeline is not saved to disk yet.
+ {template
+ ? (() => {
+ const missing = template.slots.filter((slot) => !fills[slot.mediaId]).length;
+ return missing > 0
+ ? `${missing} slot${missing === 1 ? "" : "s"} still need${missing === 1 ? "s" : ""} a clip.`
+ : "Every slot is filled.";
+ })()
+ : "The timeline is not saved to disk yet."}
</p>
</div>
+
+ {!template && templates.length > 0 && (
+ <section className="mt-14 border-t border-hairline pt-7">
+ <h2 className="mb-3 text-[13px] font-semibold text-secondary">Start from a template</h2>
+ <ul className="grid grid-cols-[repeat(auto-fill,minmax(9.5rem,1fr))] gap-3">
+ {templates.map((entry) => (
+ <li key={entry.path} className="group relative">
+ <button
+ type="button"
+ disabled={busy}
+ title={entry.path}
+ onClick={() => chooseTemplate(entry)}
+ className="w-full cursor-pointer text-left disabled:cursor-not-allowed"
+ >
+ <TemplateThumb template={entry} />
+ <span className="mt-1.5 block truncate text-[13px] text-primary">
+ {entry.name}
+ </span>
+ <span className="block font-technical text-[11px] text-tertiary">
+ {entry.slots.length} slot{entry.slots.length === 1 ? "" : "s"} · {entry.width}{" "}
+ x {entry.height}
+ </span>
+ </button>
+ <button
+ type="button"
+ aria-label={`Delete the template ${entry.name}`}
+ title="Delete this template for good"
+ onClick={() => void removeTemplate(entry)}
+ className="invisible absolute right-1.5 top-1.5 cursor-pointer rounded
+ bg-black/55 p-1 text-white transition-colors hover:bg-danger
+ group-hover:visible"
+ >
+ <Icon name="trash" size={11} />
+ </button>
+ </li>
+ ))}
+ </ul>
+ </section>
+ )}
</div>
{/* No empty state: a "Recent" heading over nothing is worse than no
diff --git a/desktop/src/components/TemplateThumb.tsx b/desktop/src/components/TemplateThumb.tsx
new file mode 100644
index 00000000..d4cae49c
--- /dev/null
+++ b/desktop/src/components/TemplateThumb.tsx
@@ -0,0 +1,46 @@
+import { useEffect, useState } from "react";
+
+import { templatePoster, type TemplateInfo } from "../lib/engine";
+import { Icon } from "./Icon";
+
+/**
+ * A template's poster, saved into the bundle when the template was. Shared by
+ * the launch screen's gallery and the bin's Templates tab, so a template looks
+ * like itself everywhere. The same quiet fallback as project thumbnails: a
+ * slot icon, never an error.
+ */
+export function TemplateThumb({ template }: { template: TemplateInfo }) {
+ const [poster, setPoster] = useState<string | null>(null);
+
+ useEffect(() => {
+ if (!template.hasPoster) return;
+ let url: string | null = null;
+ let cancelled = false;
+ void templatePoster(template.path)
+ .then((bytes) => {
+ if (cancelled) return;
+ url = URL.createObjectURL(new Blob([bytes], { type: "image/jpeg" }));
+ setPoster(url);
+ })
+ .catch(() => undefined);
+ return () => {
+ cancelled = true;
+ if (url) URL.revokeObjectURL(url);
+ };
+ }, [template.path, template.hasPoster]);
+
+ return (
+ <span
+ className="relative block aspect-video w-full overflow-hidden rounded-lg bg-sunken
+ ring-1 ring-hairline transition-shadow group-hover:ring-hairline-strong"
+ >
+ {poster ? (
+ <img src={poster} alt="" draggable={false} className="h-full w-full object-cover" />
+ ) : (
+ <span className="absolute inset-0 flex items-center justify-center text-tertiary">
+ <Icon name="slot" size={18} strokeWidth={1.5} />
+ </span>
+ )}
+ </span>
+ );
+}
diff --git a/desktop/src/lib/editor.ts b/desktop/src/lib/editor.ts
index ab62fa7e..2eff3021 100644
--- a/desktop/src/lib/editor.ts
+++ b/desktop/src/lib/editor.ts
@@ -40,6 +40,9 @@ export interface MediaItem {
videoCodec: string | null;
audioCodec: string | null;
hasAudio: boolean;
+ /** True when this item is a template slot awaiting the user's own media.
+ * Absent from documents that predate templates, which means false. */
+ placeholder?: boolean;
}
export interface Track {
@@ -161,6 +164,9 @@ export interface NewMedia {
export type EditorCommand =
| { op: "addMedia"; item: NewMedia }
| { op: "removeMedia"; mediaId: string }
+ | { op: "setMediaPlaceholder"; mediaId: string; placeholder: boolean }
+ | { op: "fillSlot"; mediaId: string; item: NewMedia }
+ | { op: "batch"; commands: EditorCommand[] }
| { op: "addClip"; mediaId: string; trackId: string; start: number }
| { op: "addClipAtFirstFree"; mediaId: string; start: number }
| { op: "addTextClip"; trackId: string | null; start: number; style: TextStyle | null }
diff --git a/desktop/src/lib/engine.ts b/desktop/src/lib/engine.ts
index e107e731..dfb5886d 100644
--- a/desktop/src/lib/engine.ts
+++ b/desktop/src/lib/engine.ts
@@ -11,7 +11,7 @@
import { invoke } from "@tauri-apps/api/core";
import { listen, type UnlistenFn } from "@tauri-apps/api/event";
-import type { EditorCommand, EditorView } from "./editor";
+import type { EditorCommand, EditorView, NewMedia } from "./editor";
export interface VideoStreamInfo {
index: number;
@@ -46,6 +46,23 @@ export async function probeMedia(path: string): Promise<MediaSummary> {
return invoke<MediaSummary>("probe_media", { path });
}
+/** A probe result in the shape `addMedia` and `fillSlot` take. */
+export function newMediaFromSummary(summary: MediaSummary): NewMedia {
+ return {
+ path: summary.path,
+ name: summary.path.split(/[\\/]/).pop() ?? summary.path,
+ duration: summary.duration,
+ kind: summary.kind,
+ width: summary.video?.width ?? null,
+ height: summary.video?.height ?? null,
+ frameRate: summary.video?.frameRate ?? null,
+ frameRateFraction: summary.video?.frameRateFraction ?? null,
+ videoCodec: summary.video?.codec ?? null,
+ audioCodec: summary.audio?.codec ?? null,
+ hasAudio: summary.audio !== null,
+ };
+}
+
/** Reports the app version the UI is talking to. */
export async function engineVersion(): Promise<string> {
return invoke<string>("engine_version");
@@ -164,6 +181,74 @@ export async function projectPreview(path: string): Promise<ArrayBuffer> {
return invoke<ArrayBuffer>("project_preview", { path });
}
+// ── templates ──────────────────────────────────────────────────────────────
+// A template is a project packed into a bundle: its design media (music,
+// overlays) ship inside, its placeholder media become slots the user fills.
+// The host owns the library; see src-tauri/src/templates.rs.
+
+/** One placeholder the user's media will replace. */
+export interface TemplateSlot {
+ mediaId: string;
+ name: string;
+ kind: "video" | "audio" | "image";
+ /** Timeline seconds this slot covers, for the fill list. */
+ seconds: number;
+}
+
+/** One template, as the gallery sees it. */
+export interface TemplateInfo {
+ /** The bundle folder on disk. */
+ path: string;
+ name: string;
+ width: number;
+ height: number;
+ rateNum: number;
+ rateDen: number;
+ /** Slots in the order they first appear on the timeline. */
+ slots: TemplateSlot[];
+ hasPoster: boolean;
+}
+
+/** The user's media for one slot, straight from a probe. */
+export interface SlotFill {
+ mediaId: string;
+ item: NewMedia;
+}
+
+/** The template library, in name order. */
+export async function templateList(): Promise<TemplateInfo[]> {
+ return invoke<TemplateInfo[]>("template_list");
+}
+
+/** Packs the open project into a new template bundle. */
+export async function templateSave(name: string): Promise<TemplateInfo> {
+ return invoke<TemplateInfo>("template_save", { name });
+}
+
+/**
+ * Unpacks a template into a fresh project with every slot filled, and
+ * returns it ready to open. Every slot needs a fill; the host refuses a
+ * partial set before anything is written.
+ */
+export async function templateInstantiate(request: {
+ template: string;
+ location: string;
+ name: string;
+ fills: SlotFill[];
+}): Promise<ProjectInfo> {
+ return invoke<ProjectInfo>("template_instantiate", request);
+}
+
+/** Removes one template bundle for good. */
+export async function templateDelete(path: string): Promise<void> {
+ return invoke<void>("template_delete", { path });
+}
+
+/** A template's poster as JPEG bytes; throws when there is none. */
+export async function templatePoster(path: string): Promise<ArrayBuffer> {
+ return invoke<ArrayBuffer>("template_poster", { path });
+}
+
/** One clip, flattened for the exporter. */
export interface ExportClip {
path: string;
diff --git a/engine/crates/relay-project/src/commands.rs b/engine/crates/relay-project/src/commands.rs
index 72046f18..245d70f9 100644
--- a/engine/crates/relay-project/src/commands.rs
+++ b/engine/crates/relay-project/src/commands.rs
@@ -115,6 +115,9 @@ pub struct NewMedia {
pub enum Command {
AddMedia { item: NewMedia },
RemoveMedia { media_id: String },
+ SetMediaPlaceholder { media_id: String, placeholder: bool },
+ FillSlot { media_id: String, item: NewMedia },
+ Batch { commands: Vec<Command> },
AddClip { media_id: String, track_id: String, start: f64 },
AddClipAtFirstFree { media_id: String, start: f64 },
AddTextClip { track_id: Option<String>, start: f64, style: Option<TextStyle> },
@@ -335,10 +338,82 @@ pub fn apply(project: &mut Project, mint: &mut IdMint, command: Command) -> Resu
video_codec: item.video_codec,
audio_codec: item.audio_codec,
has_audio: item.has_audio,
+ placeholder: false,
});
Ok(Outcome { created_id: Some(id) })
}
+ Command::SetMediaPlaceholder { media_id, placeholder } => {
+ if let Some(item) = project.media.iter_mut().find(|item| item.id == media_id) {
+ item.placeholder = placeholder;
+ }
+ Ok(Outcome::default())
+ }
+
+ Command::FillSlot { media_id, item } => {
+ let media = project
+ .media
+ .iter_mut()
+ .find(|existing| existing.id == media_id)
+ .ok_or("That template slot no longer exists.")?;
+ if !media.placeholder {
+ return Err("That media is not a template slot.".to_owned());
+ }
+
+ // The slot keeps its id, so every clip that references it keeps
+ // working; only the identity behind the id changes.
+ media.path = item.path;
+ media.name = item.name.clone();
+ media.duration = item.duration;
+ media.kind = item.kind;
+ media.width = item.width;
+ media.height = item.height;
+ media.frame_rate = item.frame_rate;
+ media.frame_rate_fraction = item.frame_rate_fraction;
+ media.video_codec = item.video_codec;
+ media.audio_codec = item.audio_codec;
+ media.has_audio = item.has_audio;
+ media.placeholder = false;
+ let kind = match item.kind {
+ MediaKind::Video => ClipKind::Video,
+ MediaKind::Audio => ClipKind::Audio,
+ MediaKind::Image => ClipKind::Image,
+ };
+
+ // Slot timing is the template's: start, duration and speed stay
+ // put, which is what keeps cuts on the beat. The in-point resets
+ // because it referred to the old footage; a clip shorter than its
+ // slot freeze-frames on its last frame downstream, which is the
+ // renderer's existing behaviour for a trim past the media's end.
+ // All timelines, like RemoveMedia: slots are not per-timeline.
+ for timeline in &mut project.timelines {
+ for clip in &mut timeline.clips {
+ if clip.media_id == media_id {
+ clip.source_start = 0.0;
+ clip.kind = kind;
+ clip.name = item.name.clone();
+ }
+ }
+ }
+ Ok(Outcome::default())
+ }
+
+ Command::Batch { commands } => {
+ // All or nothing: apply to a staged copy and commit only a fully
+ // successful run, so one bad command cannot leave a half-applied
+ // batch behind (and the editor records it as one undo step).
+ let mut staged = project.clone();
+ let mut created = None;
+ for command in commands {
+ let outcome = apply(&mut staged, mint, command)?;
+ if outcome.created_id.is_some() {
+ created = outcome.created_id;
+ }
+ }
+ *project = staged;
+ Ok(Outcome { created_id: created })
+ }
+
Command::RemoveMedia { media_id } => {
// All timelines, not just the active one: a shelved clip whose
// media is gone would linger as a dead reference.
diff --git a/engine/crates/relay-project/src/doc.rs b/engine/crates/relay-project/src/doc.rs
index 18477c91..dc1e6cd9 100644
--- a/engine/crates/relay-project/src/doc.rs
+++ b/engine/crates/relay-project/src/doc.rs
@@ -63,6 +63,7 @@ fn read_media(raw: Option<&Value>) -> Vec<MediaItem> {
video_codec: opt_string(entry.get("videoCodec")),
audio_codec: opt_string(entry.get("audioCodec")),
has_audio: flag(entry.get("hasAudio"), false),
+ placeholder: flag(entry.get("placeholder"), false),
id,
path,
})
diff --git a/engine/crates/relay-project/src/lib.rs b/engine/crates/relay-project/src/lib.rs
index f67daf47..d6b35f7e 100644
--- a/engine/crates/relay-project/src/lib.rs
+++ b/engine/crates/relay-project/src/lib.rs
@@ -33,7 +33,7 @@ mod tests {
use serde_json::json;
use crate::commands::{ClipMove, ClipPatch, Command, TrimEdge};
- use crate::doc::{DocumentSettings, from_document};
+ use crate::doc::DocumentSettings;
use crate::editor::Editor;
use crate::model::{ClipKind, MediaKind, TextStyle};
@@ -301,7 +301,7 @@ mod tests {
#[test]
fn restored_ids_can_never_be_reissued() {
- let (mut editor, _, _) = fixture();
+ let (editor, _, _) = fixture();
let document = editor.to_document(&settings());
let mut restored = Editor::from_document(&document).expect("loads");
let media_id = restored
@@ -332,6 +332,27 @@ mod tests {
.expect("optional camelCase fields deserialize");
assert!(matches!(transform, Command::SetClipTransform { .. }));
+ // The template commands ride the same wire.
+ let mark: Command = serde_json::from_value(json!({
+ "op": "setMediaPlaceholder", "mediaId": "m1", "placeholder": true
+ }))
+ .expect("parses");
+ assert!(matches!(mark, Command::SetMediaPlaceholder { placeholder: true, .. }));
+
+ let batch: Command = serde_json::from_value(json!({
+ "op": "batch",
+ "commands": [{ "op": "fillSlot", "mediaId": "m1", "item": {
+ "path": "/b.mp4", "name": "b.mp4", "duration": 3.0, "kind": "video",
+ "width": null, "height": null, "frameRate": null, "frameRateFraction": null,
+ "videoCodec": null, "audioCodec": null, "hasAudio": false
+ }}]
+ }))
+ .expect("parses");
+ assert!(matches!(
+ &batch,
+ Command::Batch { commands } if matches!(commands[0], Command::FillSlot { .. })
+ ));
+
// ClipPatch double-options: absent leaves alone, null clears.
let patch: crate::commands::ClipPatch =
serde_json::from_value(json!({ "transitionIn": null })).expect("parses");
@@ -341,6 +362,137 @@ mod tests {
assert_eq!(untouched.transition_in, None);
}
+ #[test]
+ fn a_slot_fills_in_place_keeping_the_template_timing() {
+ let (mut editor, media_id, clip_id) = fixture();
+ // Shape the clip the way a template slot looks: trimmed off the front,
+ // so it has a real in-point to forget.
+ editor
+ .apply(Command::TrimClip { clip_id, edge: TrimEdge::Start, delta: 2.0 })
+ .expect("trims");
+ editor
+ .apply(Command::SetMediaPlaceholder { media_id: media_id.clone(), placeholder: true })
+ .expect("marks");
+ assert!(editor.project().media[0].placeholder);
+
+ editor
+ .apply(Command::FillSlot {
+ media_id: media_id.clone(),
+ item: crate::commands::NewMedia {
+ path: "/photo.jpg".to_owned(),
+ name: "photo.jpg".to_owned(),
+ duration: None,
+ kind: MediaKind::Image,
+ width: Some(4000),
+ height: Some(3000),
+ frame_rate: None,
+ frame_rate_fraction: None,
+ video_codec: None,
+ audio_codec: None,
+ has_audio: false,
+ },
+ })
+ .expect("fills");
+
+ let project = editor.project();
+ let media = &project.media[0];
+ assert!(!media.placeholder, "a filled slot is ordinary media again");
+ assert_eq!(media.id, media_id, "the id survives, so clips keep working");
+ assert_eq!(media.path, "/photo.jpg");
+
+ let clip = &project.active().clips[0];
+ assert_eq!(clip.start, 2.0, "slot position is the template's");
+ assert_eq!(clip.duration, 8.0, "slot length is the template's");
+ assert_eq!(clip.source_start, 0.0, "the in-point referred to the old footage");
+ assert_eq!(clip.kind, ClipKind::Image);
+ assert_eq!(clip.name, "photo.jpg");
+ }
+
+ #[test]
+ fn filling_ordinary_media_is_refused() {
+ let (mut editor, media_id, _) = fixture();
+ let refused = editor.apply(Command::FillSlot {
+ media_id,
+ item: crate::commands::NewMedia {
+ path: "/b.mp4".to_owned(),
+ name: "b.mp4".to_owned(),
+ duration: Some(3.0),
+ kind: MediaKind::Video,
+ width: None,
+ height: None,
+ frame_rate: None,
+ frame_rate_fraction: None,
+ video_codec: None,
+ audio_codec: None,
+ has_audio: false,
+ },
+ });
+ assert!(refused.unwrap_err().contains("not a template slot"));
+ }
+
+ #[test]
+ fn a_batch_is_one_undo_step() {
+ let (mut editor, _, clip_id) = fixture();
+ editor
+ .apply(Command::Batch {
+ commands: vec![
+ Command::SplitClips { clip_ids: vec![clip_id.clone()], time: 4.0 },
+ Command::SetClipSpeed { clip_id, speed: 2.0 },
+ ],
+ })
+ .expect("applies");
+ assert_eq!(editor.project().active().clips.len(), 2);
+ assert_eq!(editor.project().active().clips[0].speed, 2.0);
+
+ assert!(editor.undo());
+ let clips = &editor.project().active().clips;
+ assert_eq!(clips.len(), 1, "one undo reverses the whole batch");
+ assert_eq!(clips[0].speed, 1.0);
+ }
+
+ #[test]
+ fn a_failed_batch_changes_nothing() {
+ let (mut editor, _, clip_id) = fixture();
+ let before = editor.project().clone();
+ let refused = editor.apply(Command::Batch {
+ commands: vec![
+ Command::SplitClips { clip_ids: vec![clip_id], time: 4.0 },
+ Command::MergeClips { clip_ids: vec!["nope".to_owned()] },
+ ],
+ });
+ assert!(refused.is_err());
+ assert_eq!(editor.project(), &before, "the successful half was rolled back");
+
+ assert!(editor.undo());
+ assert!(
+ editor.project().active().clips.is_empty(),
+ "the first undo steps over the fixture's add-clip, so the batch recorded nothing"
+ );
+ }
+
+ #[test]
+ fn the_placeholder_flag_round_trips_and_defaults_off() {
+ let (mut editor, media_id, _) = fixture();
+ editor
+ .apply(Command::SetMediaPlaceholder { media_id, placeholder: true })
+ .expect("marks");
+
+ let document = editor.to_document(&settings());
+ let restored = Editor::from_document(&document).expect("loads");
+ assert!(restored.project().media[0].placeholder, "the flag survives the document");
+
+ // A document from a build that predates templates has no such field.
+ let legacy = json!({
+ "name": "Old", "version": 1,
+ "media": [{ "id": "m1", "path": "/a.mp4", "name": "a.mp4", "kind": "video",
+ "hasAudio": false }],
+ "tracks": [{ "id": "T1", "name": "Track 1", "visible": true, "muted": false }],
+ "clips": []
+ });
+ let editor = Editor::from_document(&legacy).expect("loads");
+ assert!(!editor.project().media[0].placeholder);
+ }
+
#[test]
fn a_garbage_document_is_none_not_a_panic() {
assert!(Editor::from_document(&json!("nonsense")).is_none());
diff --git a/engine/crates/relay-project/src/model.rs b/engine/crates/relay-project/src/model.rs
index 723458cb..d9ee9b0a 100644
--- a/engine/crates/relay-project/src/model.rs
+++ b/engine/crates/relay-project/src/model.rs
@@ -60,6 +60,17 @@ pub struct MediaItem {
pub video_codec: Option<String>,
pub audio_codec: Option<String>,
pub has_audio: bool,
+ /// True when this item is a template slot: a stand-in whose metadata says
+ /// what kind of media belongs here, waiting to be replaced by the user's
+ /// own file (`Command::FillSlot`). In a creator's own project the path is
+ /// still real; only a packed template bundle blanks it. Skipped when
+ /// false, so documents without templates stay byte-identical.
+ #[serde(default, skip_serializing_if = "is_false")]
+ pub placeholder: bool,
+}
+
+fn is_false(value: &bool) -> bool {
+ !value
}
/// A lane. Deliberately untyped: any media goes on any track.
diff --git a/engine/docs/decisions/0008-templates-are-documents-plus-slots.md b/engine/docs/decisions/0008-templates-are-documents-plus-slots.md
new file mode 100644
index 00000000..fe0b8c58
--- /dev/null
+++ b/engine/docs/decisions/0008-templates-are-documents-plus-slots.md
@@ -0,0 +1,49 @@
+# 0008 - A template is a document plus slots, not a new format
+
+## Decision
+A template (the CapCut-style "drop your clips into a finished edit" feature)
+is an ordinary relay document with one new fact and one new operation:
+
+- `MediaItem.placeholder: bool` marks a media item as a *slot* - a stand-in
+ whose metadata says what belongs there. Skipped when false, so documents
+ without templates stay byte-identical. In the creator's own project the
+ path stays real and everything previews; only a packed bundle blanks it.
+- `Command::FillSlot { media_id, item }` replaces the identity behind the
+ media id - path, duration, codecs, kind - and leaves every clip that
+ references it untouched, except that in-points reset (they referred to the
+ old footage) and clip kind follows the new media. Slot timing is the
+ template's: start, duration and speed stay put, which is what keeps cuts
+ on the beat. A clip shorter than its slot freeze-frames, which is the
+ renderer's existing behaviour for a trim past the media's end.
+- `Command::Batch { commands }` applies a list all-or-nothing (staged clone,
+ committed on success) as one undo step. Filling eleven slots is one edit.
+
+The *bundle* - `template.json` with `assets/` for the music and overlays
+that are part of the design, paths relative to the bundle - is host territory
+(`desktop/src-tauri/src/templates.rs`), not engine territory. The host packs
+and unpacks; instantiation opens the document in a `relay_project::Editor`
+and applies a batch of fills, so what a fill *means* lives in exactly one
+place. The editor never opens on a slot with a dead path: the launch screen
+collects every slot's media first, and instantiation refuses a partial set.
+
+## Why this shape
+- The document model, tolerant reader, undo and command wire all exist; a
+ template format that was not the document format would mean porting every
+ future feature twice, which is the exact debt decision 0007 paid off.
+- Binding fills to the media id rather than to clips means one slot can cut
+ to the beat many times and fill once - and the engine's "clips reference
+ media" indirection was already the right join point.
+- Relative asset paths stay confined to the bundle boundary. The engine
+ still never sees anything but ordinary paths, so `relay-media`,
+ `relay-render` and the exporter needed no changes at all.
+
+## What it costs
+- Slot metadata rides in every document, invisible until used.
+- A bundle copies its design media in full; big soundtracks make big
+ templates. Acceptable - a template that references files it does not own
+ breaks the moment it travels, which is the whole point of having one.
+
+## What would change our mind
+Sharing templates between machines at scale (a gallery, a marketplace) would
+want a zipped single-file form and a manifest version - packaging concerns,
+which change the host's bundle code and nothing in this crate.