FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust
NEST14: a project reopens with its sequence tabs and their views
justjohn12345eeec77267112
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rsindex 2fe4a3d22..c9989330a 100644--- a/crates/engine/src/commands.rs+++ b/crates/engine/src/commands.rs@@ -3061,7 +3061,9 @@ fn write_project(s: &mut Session, path: &str, adopt: bool) -> Result<Value> {{name_project(std::sync::Arc::make_mut(&mut s.project), name);}- let bytes = filmcraft_format::encode(&s.project, false);+ // what is open (sequence tabs, how each is shown) goes into the file beside the project+ let view = s.project_view();+ let bytes = filmcraft_format::encode_with_view(&s.project, Some(&view), false);let mut backup = None;if adopt && s.path.as_deref() == Some(path) && s.loaded_schema < filmcraft_format::SCHEMA_VERSION {let b = schema_backup_path(path, s.loaded_schema);@@ -3119,6 +3121,13 @@ fn open_project(s: &mut Session, path: &str) -> Result<Value> {let loaded = filmcraft_format::decode(&bytes).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;let (from, migrated) = (loaded.schema_version, loaded.migrated());install_project(s, loaded.project, Some(path.to_string()), true);+ if let Some(view) = loaded.view.filter(|_| s.prefs.timeline.restore_open_sequences) {+ s.restore_project_view(view);+ }+ // the frontend shows the project's active sequence (with its own view, when one was restored)+ if let Some(seq) = s.state.active_sequence {+ s.events.push(crate::Event::OpenSequence(seq));+ }s.note_recent_project();s.loaded_schema = from;if migrated {@@ -3139,6 +3148,9 @@ fn recover(s: &mut Session, id: Option<&str>) -> Result<Value> {let saved_at = per.local_time(c.meta.saved_unix);let loaded = crate::autosave::load_candidate(&c).map_err(EngineError::Other)?;install_project(s, loaded.project, c.meta.project_path.clone(), false);+ if let Some(seq) = s.state.active_sequence {+ s.events.push(crate::Event::OpenSequence(seq));+ }crate::relink::on_open(s);// Our own journal must hold the recovered state before the old one is deleted.s.sync_persistence();diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsindex c8c913bb7..c50ca5c08 100644--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@ -697,6 +697,36 @@ impl Session {commands::find(id).is_some_and(|c| (c.enabled)(self).is_ok())}+ /// What is open, to store beside the project when it is saved.+ pub fn project_view(&self) -> filmcraft_project::ProjectView {+ let is_seq = |id: &ItemId| self.project.sequence(*id).is_some();+ filmcraft_project::ProjectView {+ open_sequences: self.state.open_sequences.iter().copied().filter(is_seq).collect(),+ active_sequence: self.state.active_sequence.filter(is_seq),+ sequences: self.state.timeline_views.iter().filter(|(id, _)| is_seq(id)).map(|(id, v)| (*id, *v)).collect(),+ }+ }++ /// Open what was open when the project was saved. Nothing in `view` is trusted: ids that are+ /// not sequences of this project are dropped (also a second mention of the same sequence),+ /// and numbers are brought into range. A view without any open sequence leaves the project+ /// on its first sequence: a project saved by a session that never showed one (a script, the+ /// CLI) should not open on an empty Timeline.+ pub fn restore_project_view(&mut self, view: filmcraft_project::ProjectView) {+ let mut open: Vec<ItemId> = Vec::new();+ for id in view.open_sequences {+ if self.project.sequence(id).is_some() && !open.contains(&id) {+ open.push(id);+ }+ }+ if !open.is_empty() {+ self.state.active_sequence = view.active_sequence.filter(|id| open.contains(id)).or(open.first().copied());+ self.state.open_sequences = open;+ }+ self.state.timeline_views =+ view.sequences.into_iter().filter(|(id, _)| self.project.sequence(*id).is_some()).filter_map(|(id, v)| Some((id, v.checked()?))).collect();+ }+/// Every edit passes through here: one that would put a sequence inside itself (directly or/// through another nested sequence) is refused, whichever command asked for it. A project that/// was opened with such a sequence already in it can still be edited (and repaired).diff --git a/crates/engine/src/sequence_tabs_tests.rs b/crates/engine/src/sequence_tabs_tests.rsindex c0c7b12d0..d8d6cd487 100644--- a/crates/engine/src/sequence_tabs_tests.rs+++ b/crates/engine/src/sequence_tabs_tests.rs@@ -1,5 +1,6 @@-//! The Timeline's sequence tabs: every sequence has its own view (zoom, scroll, track heights);-//! closing the other tabs; reordering. Premiere's behaviour was observed in Premiere Pro 26.5.2.+//! The Timeline's sequence tabs: closing the others, reordering, and what a project file keeps of+//! them (the open tabs in order, the active one, and each sequence's zoom, scroll and track+//! heights). Premiere's behaviour was observed in Premiere Pro 26.5.2.use super::*;use filmcraft_project::SequenceView;@@ -21,6 +22,13 @@ fn view(pps: f64, scroll: f64) -> SequenceView {SequenceView { pps, scroll, v_scroll: 12.0, a_scroll: 7.0, video_track_h: 90.0, audio_track_h: 40.0 }}+fn temp_dir(name: &str) -> std::path::PathBuf {+ let dir = std::env::temp_dir().join(format!("filmcraft-tabs-{name}-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).unwrap();+ dir+}+#[test]fn close_others_keeps_one_tab_and_shows_it() {let (mut s, [main, b, c]) = three_tabs();@@ -57,6 +65,91 @@ fn a_tab_moves_to_another_place_among_the_tabs() {assert!(s.execute("sequence.moveTab", json!({"item": c.0})).is_err());}+#[test]+fn a_saved_project_reopens_with_its_tabs_and_their_views() {+ let (mut s, [main, b, c]) = three_tabs();+ s.execute("sequence.moveTab", json!({"item": c.0, "index": 0})).unwrap();+ s.execute("sequence.open", json!({"item": b.0})).unwrap();+ s.state.timeline_views.insert(main, view(12.5, 3.0));+ s.state.timeline_views.insert(b, view(400.0, 0.25));+ let dir = temp_dir("reopen");+ let path = dir.join("tabs.fcproj").to_string_lossy().to_string();+ s.execute("file.saveAs", json!({"path": path})).unwrap();++ let mut t = Session::default();+ t.execute("file.open", json!({"path": path})).unwrap();+ assert_eq!(t.state.open_sequences, [c, main, b]);+ assert_eq!(t.state.active_sequence, Some(b));+ assert_eq!(t.state.timeline_views.get(&main), Some(&view(12.5, 3.0)));+ assert_eq!(t.state.timeline_views.get(&b), Some(&view(400.0, 0.25)));+ assert_eq!(t.state.timeline_views.get(&c), None, "a sequence that was never shown has no view");+ assert!(t.drain_events().contains(&Event::OpenSequence(b)));+ assert!(!t.is_dirty());++ // with the preference off, a project opens on its first sequence as before+ let mut u = Session::default();+ u.prefs.timeline.restore_open_sequences = false;+ u.execute("file.open", json!({"path": path})).unwrap();+ assert_eq!(u.state.open_sequences, [main]);+ assert_eq!(u.state.active_sequence, Some(main));+ assert!(u.state.timeline_views.is_empty());++ // saved with every tab closed (or by a session that never showed a sequence): the project+ // opens on its first sequence, not on an empty Timeline, and still knows the views+ s.execute("sequence.closeOthers", json!({})).unwrap();+ s.execute("sequence.close", json!({})).unwrap();+ s.execute("file.save", json!({})).unwrap();+ let mut w = Session::default();+ w.execute("file.open", json!({"path": path})).unwrap();+ assert_eq!((w.state.open_sequences.clone(), w.state.active_sequence), (vec![main], Some(main)));+ assert_eq!(w.state.timeline_views.get(&b), Some(&view(400.0, 0.25)));+ let _ = std::fs::remove_dir_all(&dir);+}++/// The view in a project file is not trusted: ids of things that are not sequences, repeats and+/// numbers out of range are dropped or brought into range, and a view that cannot be read at all+/// does not stop the project from opening.+#[test]+fn a_damaged_view_in_a_project_file_is_cleaned_up_or_ignored() {+ let (mut s, [main, b, c]) = three_tabs();+ let footage = s.project.sequence(main).unwrap().video_tracks[0].items[0].item;+ let dir = temp_dir("damaged");+ let path = dir.join("tabs.fcproj").to_string_lossy().to_string();+ s.execute("file.saveAs", json!({"path": path})).unwrap();+ let saved: serde_json::Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();+ let with_view = |view: serde_json::Value| {+ let mut doc = saved.clone();+ doc["view"] = view;+ std::fs::write(&path, serde_json::to_vec(&doc).unwrap()).unwrap();+ let mut t = Session::default();+ t.execute("file.open", json!({"path": path})).unwrap();+ t+ };++ let t = with_view(json!({+ "open_sequences": [c.0, 999_999, footage.0, c.0, b.0],+ "active_sequence": 999_999,+ "sequences": {+ b.0.to_string(): {"pps": 1e300, "scroll": -5.0, "v_scroll": 1e30, "a_scroll": -1.0, "video_track_h": 0.0, "audio_track_h": 1e9},+ "999999": {"pps": 40.0, "scroll": 0.0, "video_track_h": 60.0, "audio_track_h": 56.0},+ footage.0.to_string(): {"pps": 40.0, "scroll": 0.0, "video_track_h": 60.0, "audio_track_h": 56.0},+ },+ }));+ assert_eq!(t.state.open_sequences, [c, b]);+ assert_eq!(t.state.active_sequence, Some(c), "an active tab that is not open: the first tab");+ assert_eq!(t.state.timeline_views.len(), 1);+ let v = t.state.timeline_views[&b];+ assert!(v.pps <= 1e5 && v.scroll == 0.0 && v.v_scroll <= 1e6 && v.a_scroll == 0.0);+ assert!(v.video_track_h >= 8.0 && v.audio_track_h <= 600.0);++ // not a view at all: the project opens as it does without one+ for junk in [json!("tabs"), json!([1, 2, 3]), json!({"open_sequences": "all"}), json!({"sequences": {"x": 1}}), json!(null)] {+ let t = with_view(junk.clone());+ assert_eq!((t.state.open_sequences.clone(), t.state.active_sequence), (vec![main], Some(main)), "{junk}");+ }+ let _ = std::fs::remove_dir_all(&dir);+}+#[test]fn the_view_of_a_deleted_sequence_is_forgotten() {let (mut s, [main, b, c]) = three_tabs();@@ -66,4 +159,6 @@ fn the_view_of_a_deleted_sequence_is_forgotten() {s.execute("project.delete", json!({"items": [b.0]})).unwrap();assert_eq!(s.state.timeline_views.keys().copied().collect::<Vec<_>>(), [main, c]);assert_eq!(s.state.open_sequences, [main, c]);+ // the saved view never names it either+ assert_eq!(s.project_view().open_sequences, [main, c]);}diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rsindex 39e0aaa5e..2cb7f1cda 100644--- a/crates/format/src/lib.rs+++ b/crates/format/src/lib.rs@@ -39,7 +39,7 @@pub mod atomic;pub mod autosave;-use filmcraft_project::Project;+use filmcraft_project::{Project, ProjectView};use serde::{Deserialize, Serialize};use serde_json::Value;@@ -85,6 +85,9 @@ pub struct Loaded {pub schema_version: u32,/// The `generator` string of the writer, if recorded.pub generator: Option<String>,+ /// What was open when the file was saved (sequence tabs and how each was shown), when the+ /// file records it and it can be read.+ pub view: Option<ProjectView>,}impl Loaded {@@ -105,6 +108,8 @@ struct EnvelopeOut<'a> {schema_version: u32,generator: String,project: &'a Project,+ #[serde(skip_serializing_if = "Option::is_none")]+ view: Option<&'a ProjectView>,}#[derive(Deserialize)]@@ -112,6 +117,17 @@ struct EnvelopeIn {#[serde(default)]generator: Option<String>,project: Project,+ /// Kept as JSON until the project itself has loaded: a view that cannot be read is dropped,+ /// it never stops a project from opening.+ #[serde(default)]+ view: Option<Value>,+}++impl EnvelopeIn {+ fn loaded(self, schema_version: u32) -> Loaded {+ let view = self.view.and_then(|v| serde_json::from_value(v).ok());+ Loaded { project: self.project, schema_version, generator: self.generator, view }+ }}/// Just enough of a document to know which schema it is.@@ -133,7 +149,14 @@ struct Probe {/// Serialize a project in the current schema. `pretty` = indented (human-diffable; used for the/// project file itself), compact otherwise (recovery snapshots).pub fn encode(project: &Project, pretty: bool) -> Vec<u8> {- let env = EnvelopeOut { format: FORMAT_ID, schema_version: SCHEMA_VERSION, generator: generator(), project };+ encode_with_view(project, None, pretty)+}++/// [`encode`], with what is open in the editor (`view`) stored beside the project. The view is+/// outside the schema's promises: builds that do not know it ignore it, and it is dropped rather+/// than migrated when it cannot be read.+pub fn encode_with_view(project: &Project, view: Option<&ProjectView>, pretty: bool) -> Vec<u8> {+ let env = EnvelopeOut { format: FORMAT_ID, schema_version: SCHEMA_VERSION, generator: generator(), project, view };let r = if pretty { serde_json::to_vec_pretty(&env) } else { serde_json::to_vec(&env) };// Serializing plain data (string keys, finite numbers or null) cannot fail.r.unwrap_or_default()@@ -175,12 +198,12 @@ pub fn decode(bytes: &[u8]) -> Result<Loaded, FormatError> {if found == SCHEMA_VERSION {// Fast path: deserialize straight into the model.let env: EnvelopeIn = serde_json::from_slice(bytes).map_err(|e| FormatError::Corrupt(e.to_string()))?;- return Ok(Loaded { project: env.project, schema_version: found, generator: env.generator });+ return Ok(env.loaded(found));}let doc: Value = serde_json::from_slice(bytes).map_err(|e| FormatError::Corrupt(e.to_string()))?;let doc = migrate_with(MIGRATIONS, doc, found)?;let env: EnvelopeIn = serde_json::from_value(doc).map_err(|e| FormatError::Corrupt(format!("after upgrading from schema v{found}: {e}")))?;- Ok(Loaded { project: env.project, schema_version: found, generator: env.generator })+ Ok(env.loaded(found))}fn check_supported(found: u32) -> Result<(), FormatError> {@@ -303,6 +326,37 @@ mod tests {}}+ /// What is open is stored beside the project. A file without it, or with one that cannot be+ /// read, opens all the same.+ #[test]+ fn the_view_is_kept_beside_the_project_and_never_stops_a_file_from_opening() {+ use filmcraft_project::{ItemId, SequenceSettings, SequenceView};+ let mut p = Project::new("Tabs");+ let seq = p.new_sequence("Sequence 01", SequenceSettings::default(), 1, 1, None);+ let view = ProjectView {+ open_sequences: vec![seq],+ active_sequence: Some(seq),+ sequences: [(seq, SequenceView { pps: 80.0, scroll: 1.5, v_scroll: 0.0, a_scroll: 4.0, video_track_h: 60.0, audio_track_h: 56.0 })].into(),+ };+ for pretty in [true, false] {+ let l = decode(&encode_with_view(&p, Some(&view), pretty)).unwrap();+ assert_eq!((l.view.as_ref(), &l.project), (Some(&view), &p));+ assert_eq!(decode(&encode(&p, pretty)).unwrap().view, None);+ }+ // the project is the same bytes with or without a view beside it+ let mut doc: Value = serde_json::from_slice(&encode_with_view(&p, Some(&view), false)).unwrap();+ assert_eq!(doc["project"], serde_json::from_slice::<Value>(&encode(&p, false)).unwrap()["project"]);+ // a view that is not one: dropped, the project loads+ for junk in [serde_json::json!(7), serde_json::json!({"open_sequences": {"a": 1}}), serde_json::json!({"sequences": [1]}), Value::Null] {+ doc["view"] = junk;+ let l = decode(&serde_json::to_vec(&doc).unwrap()).unwrap();+ assert_eq!((l.view, &l.project), (None, &p));+ }+ // unknown ids are not this crate's business (the editor checks them against the project)+ doc["view"] = serde_json::json!({"open_sequences": [424242]});+ assert_eq!(decode(&serde_json::to_vec(&doc).unwrap()).unwrap().view.unwrap().open_sequences, [ItemId(424242)]);+ }+/// A clip with unresolved "auto" points (NaN) is written with `null` coordinates. Such a file/// used to be refused as damaged; it opens, and the points are still "auto".#[test]diff --git a/crates/project/src/lib.rs b/crates/project/src/lib.rsindex 66154ecd7..3c2b02408 100644--- a/crates/project/src/lib.rs+++ b/crates/project/src/lib.rs@@ -1136,6 +1136,19 @@ impl SequenceView {}}+/// What was open when a project was saved: the Timeline's sequence tabs in order, the active one+/// and how each sequence was shown. Stored beside the project in its file, not in it: it is not+/// part of the edit and never an undo step.+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]+pub struct ProjectView {+ #[serde(default)]+ pub open_sequences: Vec<ItemId>,+ #[serde(default)]+ pub active_sequence: Option<ItemId>,+ #[serde(default)]+ pub sequences: BTreeMap<ItemId, SequenceView>,+}+/// A LUT imported into the project (`lut.import`). Lumetri refers to it as `lib:<id>`.#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]pub struct ProjectLut {diff --git a/crates/ui-egui/tests/timeline_tabs_ui.rs b/crates/ui-egui/tests/timeline_tabs_ui.rsindex 1c02ed527..d2c5be614 100644--- a/crates/ui-egui/tests/timeline_tabs_ui.rs+++ b/crates/ui-egui/tests/timeline_tabs_ui.rs@@ -1,6 +1,7 @@//! Headless UI tests of the Timeline's sequence tabs: every sequence keeps its own zoom, scroll//! and track heights; a right-click on a tab opens its menu; tabs are reordered by dragging; tabs-//! that do not fit are in a list. Premiere's behaviour was observed in Premiere Pro 26.5.2.+//! that do not fit are in a list; a project reopens with its tabs. Premiere's behaviour was+//! observed in Premiere Pro 26.5.2.use std::path::PathBuf;use std::sync::mpsc::{Sender, channel};@@ -232,3 +233,33 @@ fn tabs_that_do_not_fit_are_reached_through_a_list() {d.click("panel.Program");assert!(!d.has(&format!("timeline.tabs.list.{last}")));}++#[test]+fn a_reopened_project_shows_its_tabs_as_they_were_left() {+ let dir = std::env::temp_dir().join(format!("filmcraft-tabs-ui-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).unwrap();+ let path = dir.join("tabs.fcproj").to_string_lossy().to_string();++ let mut d = Driver::new();+ let main = d.active();+ d.ok("ui.set", json!({"timeline": {"pps": 250.0, "scroll": 2.0, "videoTrackHeight": 80.0}}));+ d.frames(3);+ let other = d.new_sequence("Other");+ d.ok("ui.set", json!({"timeline": {"pps": 15.0, "scroll": 0.5}}));+ d.frames(3);+ d.exec("sequence.moveTab", json!({"item": other, "index": 0}));+ d.exec("file.saveAs", json!({"path": path}));++ // another window of the app opens the file+ let mut e = Driver::new();+ e.ok("ui.set", json!({"timeline": {"pps": 77.0, "scroll": 9.0}}));+ e.frames(3);+ e.exec("file.open", json!({"path": path}));+ e.frames(3);+ assert_eq!((e.open(), e.active()), (vec![other, main], other));+ assert_eq!(e.view(), (15.0, 0.5, 60.0));+ e.click(&format!("timeline.tab.{main}"));+ assert_eq!(e.view(), (250.0, 2.0, 80.0));+ let _ = std::fs::remove_dir_all(&dir);+}diff --git a/docs/project-files.md b/docs/project-files.mdindex fb68cd367..68980cea8 100644--- a/docs/project-files.md+++ b/docs/project-files.md@@ -10,7 +10,8 @@ writing them is `crates/format` (`filmcraft-format`); the engine's `file.*` comm"format": "filmcraft.project","schema_version": 12,"generator": "FilmCraft 0.1.0",- "project": { "name": "…", "settings": { … }, "root": { … }, "items": { … }, "next_id": 48 }+ "project": { "name": "…", "settings": { … }, "root": { … }, "items": { … }, "next_id": 48 },+ "view": { "open_sequences": [21, 50], "active_sequence": 50, "sequences": { "21": { "pps": 40.0, "scroll": 0.0, … } } }}```@@ -19,6 +20,14 @@ writing them is `crates/format` (`filmcraft-format`); the engine's `file.*` comm- `project` is the serialized `filmcraft_project::Project` (bins, media clips, sequences, tracks,clips, effects, keyframes, markers). Media is referenced by path, never embedded.- Files are written compact (no indentation). A 2,000-clip project is about 1.4 MB.+- `view` (optional) is what was open when the project was saved: the Timeline's sequence tabs in+ order, the active one, and each sequence's zoom, scroll and track heights+ (`filmcraft_project::ProjectView`). It is beside the project, not in it: it is not part of the+ edit, never an undo step, and changing it does not mark the project as changed. Opening a+ project restores it when the Timeline preference "Restore open sequences when opening projects"+ is on. It is outside the schema version: older builds ignore it, ids that are not sequences and+ numbers out of range are dropped or clamped, and a `view` that cannot be read is ignored (the+ project opens on its first sequence, as it does without one or with no open sequence in it).- A coordinate of an effect's point parameter may be `null`. Point parameters use NaN for "auto"(the frame centre, or the source centre for `anchor`), and JSON writes NaN as `null`; it reads backas "auto". Placing a clip resolves these points at once. An interchange import resolves them