From 81057428d1e251d90415eb15f620d5cb3b866fa1 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 18:41:32 +0000 Subject: [PATCH] Add shared FilmCraft project envelope and migrations --- Cargo.lock | 9 ++ Cargo.toml | 1 + crates/fcproj-format/Cargo.toml | 16 ++ crates/fcproj-format/src/lib.rs | 260 ++++++++++++++++++++++++++++++++ 4 files changed, 286 insertions(+) create mode 100644 crates/fcproj-format/Cargo.toml create mode 100644 crates/fcproj-format/src/lib.rs diff --git a/Cargo.lock b/Cargo.lock index b3325f790..3b008d6eb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1671,6 +1671,15 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-fcproj-format" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "craft-fig" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 0c9729e00..9e664024f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -68,6 +68,7 @@ craft-doc = { path = "crates/doc" } craft-docpath = { path = "crates/docpath" } craft-dpx = { path = "crates/dpx" } craft-dwg = { path = "crates/dwg" } +craft-fcproj-format = { path = "crates/fcproj-format" } craft-ecproj-format = { path = "crates/ecproj-format" } craft-figma-rest = { path = "crates/figma-rest" } craft-exr = { path = "crates/exr" } diff --git a/crates/fcproj-format/Cargo.toml b/crates/fcproj-format/Cargo.toml new file mode 100644 index 000000000..aa210187d --- /dev/null +++ b/crates/fcproj-format/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "craft-fcproj-format" +description = "FilmCraft project envelope and schema migrations" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[dependencies] +serde = { workspace = true } +serde_json = { workspace = true } +thiserror = { workspace = true } diff --git a/crates/fcproj-format/src/lib.rs b/crates/fcproj-format/src/lib.rs new file mode 100644 index 000000000..877b79765 --- /dev/null +++ b/crates/fcproj-format/src/lib.rs @@ -0,0 +1,260 @@ +//! FilmCraft `.fcproj` JSON envelope, version detection and historical migrations. +//! Project and editor-view types are supplied by the caller. +use serde::{Deserialize, Serialize}; +use serde_json::Value; +/// The `format` tag written in every envelope. +pub const FORMAT_ID: &str = "filmcraft.project"; + +/// A migration upgrades a whole document from schema `n` to `n + 1`. +pub type Migration = fn(Value) -> Result; + +/// `MIGRATIONS[i]` upgrades schema `i + 1` to `i + 2`. Append one function per schema bump; never +/// edit a shipped one. +pub const MIGRATIONS: &[Migration] = &[ + v1_to_v2, v2_to_v3, v3_to_v4, v4_to_v5, v5_to_v6, v6_to_v7, v7_to_v8, v8_to_v9, v9_to_v10, v10_to_v11, v11_to_v12, v12_to_v13, v13_to_v14, + v14_to_v15, v15_to_v16, v16_to_v17, +]; + +/// The schema version this build writes (and the newest it reads). +pub const SCHEMA_VERSION: u32 = MIGRATIONS.len() as u32 + 1; + +/// Oldest schema this build can still upgrade. +pub const OLDEST_SCHEMA: u32 = 1; + +#[derive(Debug, thiserror::Error)] +pub enum FormatError { + #[error("not a FilmCraft project: {0}")] + NotAProject(String), + #[error( + "this project was saved by a newer version of FilmCraft (project schema v{found}); this build reads up to v{supported}. Update FilmCraft to open it." + )] + TooNew { found: u32, supported: u32 }, + #[error("project schema v{found} is too old for this build (oldest supported: v{oldest})")] + TooOld { found: u32, oldest: u32 }, + #[error("upgrading project from schema v{from} to v{}: {msg}", from + 1)] + Migration { from: u32, msg: String }, + #[error("project file is damaged: {0}")] + Corrupt(String), +} + +/// Serialized current-schema envelope. +#[derive(Serialize)] +pub struct EnvelopeOut<'a, P, V> { + pub format: &'static str, + pub schema_version: u32, + pub generator: String, + pub project: &'a P, + #[serde(skip_serializing_if = "Option::is_none")] + pub view: Option<&'a V>, +} +/// Parsed envelope. View parsing remains optional to preserve forward compatibility. +#[derive(Deserialize)] +pub struct EnvelopeIn

{ + #[serde(default)] + pub generator: Option, + pub project: P, + #[serde(default)] + pub view: Option, +} +/// Probe and validate the schema directly from bytes without building a JSON tree. +pub fn detect_bytes(bytes: &[u8]) -> Result { + let probe: Probe = serde_json::from_slice(bytes) + .map_err(|e| if e.is_syntax() || e.is_eof() { FormatError::Corrupt(e.to_string()) } else { FormatError::NotAProject(e.to_string()) })?; + let found = probe_version(&probe)?; + check_supported(found)?; + Ok(found) +} +/// Just enough of a document to know which schema it is. +#[derive(Deserialize)] +struct Probe { + #[serde(default)] + format: Option, + #[serde(default)] + schema_version: Option, + /// Bare (pre-envelope) project: its `version` field. + #[serde(default)] + version: Option, + #[serde(default)] + items: Option, + #[serde(default)] + root: Option, +} + +/// Detect the schema version of a parsed document. +pub fn detect_version(doc: &Value) -> Result { + let probe: Probe = serde_json::from_value(doc.clone()).map_err(|e| FormatError::NotAProject(e.to_string()))?; + probe_version(&probe) +} + +fn probe_version(p: &Probe) -> Result { + if let Some(v) = p.schema_version { + if let Some(f) = &p.format + && f != FORMAT_ID + { + return Err(FormatError::NotAProject(format!("format is `{f}`, expected `{FORMAT_ID}`"))); + } + return Ok(v); + } + // Before the envelope (v1) a file was the bare Project object with `version`. + // Its `version` was 1, or 2 on builds that briefly bumped it when caption tracks were added + // (same shape; the new field loads with its default). Anything higher is from the future. + if p.items.is_some() && p.root.is_some() { + return Ok(match p.version.unwrap_or(1) { + 0..=2 => 1, + v => v, + }); + } + Err(FormatError::NotAProject("no `schema_version` and not a legacy project".into())) +} + +pub fn check_supported(found: u32) -> Result<(), FormatError> { + if found > SCHEMA_VERSION { + return Err(FormatError::TooNew { found, supported: SCHEMA_VERSION }); + } + if found < OLDEST_SCHEMA { + return Err(FormatError::TooOld { found, oldest: OLDEST_SCHEMA }); + } + Ok(()) +} + +/// Run `table` from schema `from` up to `table.len() + 1`, stamping `schema_version` after each step. +pub fn migrate_with(table: &[Migration], mut doc: Value, from: u32) -> Result { + let target = table.len() as u32 + 1; + if from > target { + return Err(FormatError::TooNew { found: from, supported: target }); + } + if from == 0 { + return Err(FormatError::TooOld { found: 0, oldest: 1 }); + } + for v in from..target { + let step = table[(v - 1) as usize]; + doc = step(doc).map_err(|msg| FormatError::Migration { from: v, msg })?; + match doc.as_object_mut() { + Some(o) => { + o.insert("schema_version".into(), Value::from(v + 1)); + } + None => return Err(FormatError::Migration { from: v, msg: "migration produced a non-object document".into() }), + } + } + Ok(doc) +} + +/// v1 → v2: wrap the bare project in the envelope and drop the per-project `version` field. +fn v1_to_v2(doc: Value) -> Result { + let Value::Object(mut project) = doc else { return Err("expected a JSON object".into()) }; + project.remove("version"); + Ok(serde_json::json!({ + "format": FORMAT_ID, + "schema_version": 2, + "generator": "FilmCraft (schema v1)", + "project": Value::Object(project), + })) +} + +/// v2 → v3: graphic clips added; existing data needs no change. +fn v2_to_v3(doc: Value) -> Result { + Ok(doc) +} + +/// v3 → v4: Essential Sound fields added; existing data needs no change. +fn v3_to_v4(doc: Value) -> Result { + Ok(doc) +} + +/// v4 → v5: colour-management fields added; existing data needs no change. +fn v4_to_v5(doc: Value) -> Result { + Ok(doc) +} + +/// v5 → v6: media identity and ingest settings added; existing data needs no change. +fn v5_to_v6(doc: Value) -> Result { + Ok(doc) +} + +/// v6 → v7: effect masks (Bézier mask paths as keyframable parameters); existing data needs no change. +fn v6_to_v7(doc: Value) -> Result { + Ok(doc) +} + +/// v7 → v8: multi-camera source sequences / clips and merged clips added; existing data needs no +/// change. +fn v7_to_v8(doc: Value) -> Result { + Ok(doc) +} + +/// v8 → v9: per-media-item transcripts (`project.transcripts`) added; existing data needs no change. +fn v8_to_v9(doc: Value) -> Result { + Ok(doc) +} + +/// v9 → v10: clip time interpolation, Hold Filters, Field Options and audio source channels; the +/// Modify ▸ Audio Channels map; subclips' Restrict Trims flag. Existing data needs no change. +fn v9_to_v10(doc: Value) -> Result { + Ok(doc) +} + +/// v10 → v11: search bins (`project.search_bins`), Flash Cue markers, Project Settings safe areas, +/// capture format and scratch disks. Existing data needs no change. +fn v10_to_v11(doc: Value) -> Result { + Ok(doc) +} + +/// v11 → v12: graphics templates, rolls / crawls, responsive design and per-character text styles +/// on graphic clips, and source graphics. Existing data needs no change. +fn v11_to_v12(doc: Value) -> Result { + Ok(doc) +} + +/// v12 → v13: container audio streams and per-clip stream selection. `MediaInfo` reads the old +/// `audio` field as stream zero; `TrackItem::audio_stream` defaults to zero. +fn v12_to_v13(doc: Value) -> Result { + Ok(doc) +} + +/// v13 → v14: narrations (Text to Speech). Existing data needs no change. +fn v13_to_v14(doc: Value) -> Result { + Ok(doc) +} + +/// v14 → v15: project notes. Existing data needs no change. +fn v14_to_v15(doc: Value) -> Result { + Ok(doc) +} + +/// v15 → v16: existing colors remain presets; authors and the named custom palette default empty. +fn v15_to_v16(doc: Value) -> Result { + Ok(doc) +} + +/// v16 → v17: marker URLs default empty. Older builds must not silently drop saved URLs. +fn v16_to_v17(doc: Value) -> Result { + Ok(doc) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn legacy_and_current_envelopes_preserve_values() { + let bare = json!({"version": 2, "items": {}, "root": {}, "extra": [1, 2]}); + assert_eq!(detect_version(&bare).unwrap(), 1); + let migrated = migrate_with(MIGRATIONS, bare, 1).unwrap(); + assert_eq!(migrated["schema_version"], 17); + assert_eq!(migrated["project"]["extra"], json!([1, 2])); + assert_eq!(migrated["generator"], "FilmCraft (schema v1)"); + assert_eq!(detect_bytes(serde_json::to_string(&migrated).unwrap().as_bytes()).unwrap(), 17); + let parsed: EnvelopeIn = serde_json::from_value(migrated).unwrap(); + assert!(parsed.view.is_none()); + assert_eq!(parsed.project["extra"], json!([1, 2])); + } + #[test] + fn rejects_wrong_future_and_damaged_envelopes() { + assert!(matches!(detect_bytes(br#"{"format":"other","schema_version":1}"#), Err(FormatError::NotAProject(_)))); + assert!(matches!(detect_bytes(br#"{"schema_version":18}"#), Err(FormatError::TooNew { found: 18, supported: 17 }))); + assert!(matches!(detect_bytes(br#"{"schema_version":0}"#), Err(FormatError::TooOld { found: 0, oldest: 1 }))); + assert!(matches!(detect_bytes(b"{"), Err(FormatError::Corrupt(_)))); + assert!(matches!(migrate_with(MIGRATIONS, json!([]), 1), Err(FormatError::Migration { from: 1, .. }))); + } +}