edith
Clone
https://git.tahinli.com/Tahinli/edith.git
0 watching·0 forks·Rust·18.3 MiB·ff99ad6·Tahinli·6 days ago·1055 commits
| 1 | //! Project tools: new, open, save, status, settings. |
| 2 | //! |
| 3 | //! The undo ledger: `server.ledger` holds one entry per agent-visible undo step, |
| 4 | //! the number of engine snapshots that step pushed. Any tool that may change the |
| 5 | //! engine's push count (`history_pushes`, which keeps rising at the undo cap) |
| 6 | //! measures it before and after and calls [`note_pushes`]. |
| 7 | //! The project is dirty when the undo depth differs from `saved_depth`, the ledger's top |
| 8 | //! entry is not the one it was at the save (`saved_top`), or a source came or went. |
| 9 | use std::collections::{BTreeMap, HashMap}; |
| 10 | use std::path::{Path, PathBuf}; |
| 11 | use std::time::{Duration, SystemTime}; |
| 12 | |
| 13 | use engine::limiter::Limiter; |
| 14 | use engine::project::{Lane, LaneKind, Rate, STILL_MAX_SECS, STILL_MIN_SECS}; |
| 15 | use engine::speech::{DeviceChoice, MODELS}; |
| 16 | use engine::tonemap::Preset; |
| 17 | use engine::export::EncoderSeat; |
| 18 | use engine::PlaybackSession; |
| 19 | use serde_json::{json, Map, Value}; |
| 20 | |
| 21 | use crate::parse; |
| 22 | use crate::server::{arg_str, opt_bool, opt_f64, opt_str, tri, Reply, Server, Tool}; |
| 23 | use crate::tools::media::{not_a_file, not_found}; |
| 24 | |
| 25 | pub fn tools() -> Vec<Tool> { |
| 26 | vec![ |
| 27 | Tool { |
| 28 | name: "project_new", |
| 29 | description: "Start an empty project at a new path. Nothing is written until project_save. Refused, before anything is created, when an earlier session's unsaved edits sit in the path's autosave: the reply names them and offers project_open {recover:true} to continue from them, or overwrite:true to start fresh (the autosave is set aside as a dated copy; the newest 3 dated copies and any from the last 7 days are kept; older ones are deleted).", |
| 30 | schema: || { |
| 31 | schema( |
| 32 | json!({ |
| 33 | "path": {"type": "string", "description": "Where the .edith file will be saved. Must not exist yet."}, |
| 34 | "resolution": {"type": "string", "description": "Canvas size as WIDTHxHEIGHT, e.g. 1920x1080. Default 1920x1080."}, |
| 35 | "fps": {"type": "number", "description": "Frame rate of the timeline. Default 30."}, |
| 36 | "template": {"type": "string", "examples": ["Vertical 1080×1920 30"], "description": "Start from a template by name: a built-in (YouTube 1080p 30, Vertical 1080×1920 30, Square 1080 30) or one saved with File > Save as template (see templates). Sets the canvas size, rate, lanes, lane names and caption style; resolution and fps are then refused."}, |
| 37 | "discard": {"type": "boolean", "description": "Replace the open project even if it has unsaved changes."}, |
| 38 | "overwrite": {"type": "boolean", "description": "Let path name an existing file, or a path with an earlier session's unsaved autosave. The autosave is set aside as a dated copy at once. The file is replaced by project_save (which needs its own force:true if the file changed on disk after this call). Without overwrite, an existing path, or one with such an autosave, is refused."} |
| 39 | }), |
| 40 | &["path"], |
| 41 | ) |
| 42 | }, |
| 43 | run: project_new, |
| 44 | }, |
| 45 | Tool { |
| 46 | name: "templates", |
| 47 | description: "The project templates: the built-ins and the ones saved with File > Save as template, each with whether it keeps clips. Pass a name as project_new's template. With save: {name, with_clips?} it saves the open project as a template of that name (replacing one of the same name, and refusing a built-in's name): its settings always, its clips and their sources when with_clips is true and the project has sources. The project does not change.", |
| 48 | schema: || { |
| 49 | schema( |
| 50 | json!({ |
| 51 | "save": { |
| 52 | "type": "object", |
| 53 | "description": "Save the open project as a template.", |
| 54 | "properties": { |
| 55 | "name": {"type": "string", "description": "The template's name: 1 to 40 characters, no slashes, not a built-in's name."}, |
| 56 | "with_clips": {"type": "boolean", "description": "Keep the clips and their sources too. Default false: settings only."} |
| 57 | }, |
| 58 | "required": ["name"], |
| 59 | "additionalProperties": false |
| 60 | } |
| 61 | }), |
| 62 | &[], |
| 63 | ) |
| 64 | }, |
| 65 | run: templates_list, |
| 66 | }, |
| 67 | Tool { |
| 68 | name: "project_open", |
| 69 | description: "Open a .edith project, or a media file as a new project (its project is <stem>.edith next to it, unsaved). When an autosave beside the project holds unsaved edits from an earlier session, the open is refused before anything is loaded or written, and says what those edits are. Choose up front: recover: true continues from them: they open on the saved file as one undo step, so undo takes them back to the saved timeline (the project stays unsaved until project_save; a never-saved project has nothing for undo to return to), discard_autosave: true opens the saved file and sets the autosave aside as a dated copy (the newest 3 dated copies and any from the last 7 days are kept; older ones are deleted). Older dated autosaves are listed in the reply; recover: \"<file name or time stamp>\" loads one of those. Returns the status.", |
| 70 | schema: || { |
| 71 | schema( |
| 72 | json!({ |
| 73 | "path": {"type": "string", "description": "A .edith file, or a video/audio file to start a project from."}, |
| 74 | "discard": {"type": "boolean", "description": "Replace the open project even if it has unsaved changes."}, |
| 75 | "recover": {"type": ["boolean", "string"], "description": "true: continue from the autosave (<name>.autosave.edith) beside the project: the saved file opens and the autosave's edits go on top as one undo step; required when that autosave holds an earlier session's unsaved edits. A string: the dated autosave with that file name or time stamp (as listed in the reply, local time). The project stays unsaved until project_save. When this session has unsaved edits, recover is refused unless discard: true, which drops those edits (or project_save {discard_autosave:true} keeps them first)."}, |
| 76 | "discard_autosave": {"type": "boolean", "description": "Open the saved file and set the autosave beside it aside without loading it: it is renamed to a dated copy (<stem>.autosave-<stamp>.edith, listed in the reply), so its edits are not loaded and the copy is kept (the newest 3 dated copies and any from the last 7 days are kept; older ones are deleted). Required, with recover, to open past an earlier session's autosave."}, |
| 77 | "search": {"type": "array", "items": {"type": "string"}, "description": "Folders searched (recursively) for the files of offline sources, matched by file name. A name found exactly once is relinked; the reply says which."} |
| 78 | }), |
| 79 | &["path"], |
| 80 | ) |
| 81 | }, |
| 82 | run: project_open, |
| 83 | }, |
| 84 | Tool { |
| 85 | name: "project_save", |
| 86 | description: "Save the project. With a different path it is save-as. Refuses to overwrite a file this session did not open or save, or one that changed on disk since, unless force: true. Refuses while an autosave beside the project that this session did not load holds edits, unless discard_autosave: true: that saves this session's edits and sets the autosave aside as a dated copy (the newest 3 dated copies and any from the last 7 days are kept; older ones are deleted). project_open settles an earlier session's autosave before it opens the project, so this refusal is for one that appeared while this session ran.", |
| 87 | schema: || { |
| 88 | schema( |
| 89 | json!({ |
| 90 | "path": {"type": "string", "description": "Target .edith path. Default: the current project path."}, |
| 91 | "force": {"type": "boolean", "description": "Replace the target even if it is not this project's file or changed on disk since it was last opened or saved here."}, |
| 92 | "discard_autosave": {"type": "boolean", "description": "Save this session's edits anyway: the autosave that appeared beside the project holds edits this save does not have, so it is set aside as a dated copy (the newest 3 dated copies and any from the last 7 days are kept; older ones are deleted). Use it when project_save refuses over that autosave."} |
| 93 | }), |
| 94 | &[], |
| 95 | ) |
| 96 | }, |
| 97 | run: project_save, |
| 98 | }, |
| 99 | Tool { |
| 100 | name: "project_collect", |
| 101 | description: "Copy every file the project plays into one folder and point the project at the copies, so the folder and the project can be moved or archived together. Default folder: <project stem>_media next to the project file. Generated sources (solids, bars, adjustment layers) are skipped, a source whose file is missing is skipped and named, one already in the folder stays, and a name already taken by another file gets -2, -3. The same bytes already in the folder are reused. The relink is one undo step and the project is unsaved until project_save. Nothing changes if a copy fails.", |
| 102 | schema: || { |
| 103 | schema( |
| 104 | json!({ |
| 105 | "folder": {"type": "string", "description": "Where the copies go (made if missing). Default: <project stem>_media beside the project file."} |
| 106 | }), |
| 107 | &[], |
| 108 | ) |
| 109 | }, |
| 110 | run: project_collect, |
| 111 | }, |
| 112 | Tool { |
| 113 | name: "project_export_timeline", |
| 114 | description: "Write the active sequence for another editor. format \"otio\" writes OpenTimelineIO (.otio): tracks, clips with their file paths, gaps, transitions and markers. \"fcpxml\" writes Final Cut Pro XML 1.10, which Final Cut Pro, DaVinci Resolve and Premiere read. \"edl\" writes a CMX3600 EDL: V1, and audio on A1 and A2. Subtitles are left out, and the reply says what else was left out. Default path: beside the project file, named after it with the format's extension. Only the file is written; the project does not change.", |
| 115 | schema: || { |
| 116 | schema( |
| 117 | json!({ |
| 118 | "format": {"type": "string", "enum": ["otio", "fcpxml", "edl"], "description": "Which format to write."}, |
| 119 | "path": {"type": "string", "description": "Where the file goes. Default: beside the project file, named after it."} |
| 120 | }), |
| 121 | &["format"], |
| 122 | ) |
| 123 | }, |
| 124 | run: project_export_timeline, |
| 125 | }, |
| 126 | Tool { |
| 127 | name: "project_import_timeline", |
| 128 | description: "Read an OpenTimelineIO (.otio) file as a new sequence of this project and switch to it. Each clip is relinked by its file path; a file that is missing becomes an offline clip. One undo step; unsaved until project_save.", |
| 129 | schema: || { |
| 130 | schema( |
| 131 | json!({ |
| 132 | "path": {"type": "string", "description": "The .otio file to read."} |
| 133 | }), |
| 134 | &["path"], |
| 135 | ) |
| 136 | }, |
| 137 | run: project_import_timeline, |
| 138 | }, |
| 139 | Tool { |
| 140 | name: "project_status", |
| 141 | description: "Project path, saved or dirty, canvas size, frame rate, duration, lanes with clip counts, sources, undo and redo steps, running exports, the colour looks (built-in and saved, by name, for the look op), and settings. history: true also lists every undo step and every redo step, newest first, each with the number undo {steps} or redo {steps} takes to reach it (1 is the newest undo step, and undo {steps: N} takes back the N newest).", |
| 142 | schema: || { |
| 143 | schema( |
| 144 | json!({ |
| 145 | "history": {"type": "boolean", "description": "List every undo and redo step with its index, so undo {steps} can target any point. Default false."} |
| 146 | }), |
| 147 | &[], |
| 148 | ) |
| 149 | }, |
| 150 | run: project_status, |
| 151 | }, |
| 152 | Tool { |
| 153 | name: "project_settings", |
| 154 | description: "Change project-wide settings: canvas resolution, frame rate, tone mapping, proxies, encoder seat, limiter, caption style, notes, still length. Reports each change and each refusal.", |
| 155 | schema: || { |
| 156 | schema( |
| 157 | json!({ |
| 158 | "resolution": {"type": "string", "description": "Canvas size as WIDTHxHEIGHT, e.g. 1280x720."}, |
| 159 | "fps": {"type": "number", "description": "Timeline frame rate, e.g. 25 or 29.97. Refused while a locked lane has clips the retime would move, unless force is true."}, |
| 160 | "force": {"type": "boolean", "description": "With fps: move the clips of locked lanes too."}, |
| 161 | "tonemap": {"type": "string", "enum": ["reference", "standard", "vivid"], "description": "HDR to SDR rendition."}, |
| 162 | "notes": {"type": "string", "examples": ["Cut the intro to 30 s"], "description": "The project's notes: free text, several lines allowed (a newline is \\n in JSON). An empty string clears them. Saved with the project; one undo step."}, |
| 163 | "still_secs": {"type": "number", "description": "How long a still image is placed for, in seconds: 0.5 to 600 (default 5). Stills placed after this change take it; clips already placed keep theirs. Saved with the project; one undo step."}, |
| 164 | "speech_model": {"type": "string", "enum": MODELS.iter().copied().chain(["auto"]).collect::<Vec<_>>(), "description": "The Whisper model transcript, find_words and auto_captions run on; auto (default) picks the first installed. Saved with the project; one undo step."}, |
| 165 | "speech_device": {"type": "string", "enum": ["auto", "cpu", "gpu"], "description": "Where that model runs: auto (gpu when usable and that model is installed, else cpu), cpu or gpu. Saved with the project; one undo step."}, |
| 166 | "sample_rate": {"type": ["string", "integer"], "description": "The project's sound mix rate: \"source\" (the default: the highest rate among the sources, 48 kHz when all are below 44.1 kHz), or 44100, 48000 or 96000 in Hz. Saved with the project; one undo step.", "enum": ["source", 44100, 48000, 96000]}, |
| 167 | "proxies": {"type": "boolean", "description": "Play and edit through proxy files."}, |
| 168 | "auto_proxies": {"type": "boolean", "description": "Make proxies automatically for heavy sources."}, |
| 169 | "encoder": {"type": "string", "enum": ["auto", "hardware", "software"], "description": "Which encoder export uses."}, |
| 170 | "captions": { |
| 171 | "type": "object", |
| 172 | "description": "The project's caption style, the default for burn_captions (which can override each key): animation (none, karaoke, pop, bounce, word), highlight (#rrggbb), box (highlight as a rounded box), uppercase, words_per_line (0 to 12). Saved with the project; one undo step.", |
| 173 | "properties": { |
| 174 | "animation": {"type": "string", "enum": ["none", "karaoke", "pop", "bounce", "word"]}, |
| 175 | "highlight": {"type": "string", "description": "#rrggbb"}, |
| 176 | "box": {"type": "boolean"}, |
| 177 | "uppercase": {"type": "boolean"}, |
| 178 | "words_per_line": {"type": "integer", "minimum": 0, "maximum": 12} |
| 179 | }, |
| 180 | "additionalProperties": false |
| 181 | }, |
| 182 | "limiter": { |
| 183 | "type": "object", |
| 184 | "description": "Master limiter.", |
| 185 | "properties": { |
| 186 | "on": {"type": "boolean", "description": "Turn the limiter on or off."}, |
| 187 | "ceiling_db": {"type": "number", "description": "Ceiling in dBTP, -24 to 0: the highest true peak the output may reach, between samples included."} |
| 188 | } |
| 189 | } |
| 190 | }), |
| 191 | &[], |
| 192 | ) |
| 193 | }, |
| 194 | run: project_settings, |
| 195 | }, |
| 196 | ] |
| 197 | } |
| 198 | |
| 199 | /// `project_collect {folder?}`: [`engine::collect`] over the open project's sources. |
| 200 | fn project_collect(server: &mut Server, args: &Value) -> Reply { |
| 201 | let folder = match opt_str(args, "folder") { |
| 202 | Some(f) => expand_home(f.trim()), |
| 203 | None => match server.path.as_deref() { |
| 204 | Some(p) => engine::collect::default_folder(p), |
| 205 | None => return Reply::err("the project has no path yet: project_save it first, or give `folder`"), |
| 206 | }, |
| 207 | }; |
| 208 | let s = tri!(server.session()); |
| 209 | let plan = engine::collect::plan(s.sources(), &folder); |
| 210 | let cancel = std::sync::atomic::AtomicBool::new(false); |
| 211 | let done = match engine::collect::copy_all(&plan, &cancel, &mut |_, _| {}) { |
| 212 | Ok(done) => done, |
| 213 | Err(e) => return Reply::err(format!("project_collect failed, nothing changed: {e:?}")), |
| 214 | }; |
| 215 | let before = s.history_pushes(); |
| 216 | let moved = s.relink_all(&done.pairs); |
| 217 | let steps = s.history_pushes().saturating_sub(before); |
| 218 | let mut lines = vec![format!( |
| 219 | "collected into {}: {} file(s) copied, {}; {moved} source(s) relinked", |
| 220 | folder.display(), |
| 221 | done.files, |
| 222 | engine::collect::size_text(done.bytes) |
| 223 | )]; |
| 224 | let reused = plan.items.iter().filter(|i| i.present).count(); |
| 225 | if reused > 0 { |
| 226 | lines.push(format!("{reused} file(s) were already in the folder with the same bytes and were reused")); |
| 227 | } |
| 228 | if plan.already > 0 { |
| 229 | lines.push(format!("{} source(s) were already in the folder", plan.already)); |
| 230 | } |
| 231 | if plan.generated > 0 { |
| 232 | lines.push(format!("{} generated source(s) skipped (they are not files)", plan.generated)); |
| 233 | } |
| 234 | for p in &plan.offline { |
| 235 | lines.push(format!("warning: skipped, file missing: {}", p.display())); |
| 236 | } |
| 237 | if steps > 0 { |
| 238 | server.saved_sources = None; |
| 239 | crate::tools::project::note_pushes_as(server, before, "project_collect"); |
| 240 | crate::tools::media::remember_sources(server); |
| 241 | lines.push("undo takes the relink back".to_string()); |
| 242 | } |
| 243 | lines.push("unsaved until project_save".to_string()); |
| 244 | Reply::ok(lines.join("\n")).with(json!({ |
| 245 | "folder": folder.display().to_string(), |
| 246 | "copied": done.files, |
| 247 | "bytes": done.bytes, |
| 248 | "relinked": moved, |
| 249 | "generated_skipped": plan.generated, |
| 250 | "missing": plan.offline.iter().map(|p| p.display().to_string()).collect::<Vec<_>>() |
| 251 | })) |
| 252 | } |
| 253 | |
| 254 | /// `project_export_timeline {format, path?}`: [`engine::interchange`] of the active sequence, written to a file. |
| 255 | fn project_export_timeline(server: &mut Server, args: &Value) -> Reply { |
| 256 | let format = tri!(arg_str(args, "format")); |
| 257 | let ext = match format { |
| 258 | "otio" | "fcpxml" | "edl" => format, |
| 259 | other => return Reply::err(format!("format `{other}` is not one of otio, fcpxml, edl")), |
| 260 | }; |
| 261 | let path = match opt_str(args, "path") { |
| 262 | Some(raw) => expand_home(raw.trim()), |
| 263 | None => match server.path.as_deref() { |
| 264 | Some(p) => p.with_extension(ext), |
| 265 | None => return Reply::err("the project has no path yet: give `path`, or project_save first"), |
| 266 | }, |
| 267 | }; |
| 268 | let s = tri!(server.session_ref()); |
| 269 | let t = s.timeline_snapshot(); |
| 270 | let text = match format { |
| 271 | "otio" => engine::interchange::otio::write(&t), |
| 272 | "fcpxml" => engine::interchange::fcpxml::write(&t), |
| 273 | _ => engine::interchange::edl::write(&t), |
| 274 | }; |
| 275 | if let Err(e) = std::fs::write(&path, text) { |
| 276 | return Reply::err(format!("could not write {}: {e}", path.display())); |
| 277 | } |
| 278 | let mut lines = vec![format!("wrote {} ({} track(s), {} marker(s))", path.display(), t.tracks.len(), t.markers.len())]; |
| 279 | lines.extend(t.notes.iter().cloned()); |
| 280 | Reply::ok(lines.join("\n")).with(json!({ |
| 281 | "path": path.display().to_string(), |
| 282 | "format": format, |
| 283 | "tracks": t.tracks.len(), |
| 284 | "markers": t.markers.len(), |
| 285 | "notes": t.notes, |
| 286 | })) |
| 287 | } |
| 288 | |
| 289 | /// `project_import_timeline {path}`: an OpenTimelineIO file becomes a new sequence, one undo step. |
| 290 | fn project_import_timeline(server: &mut Server, args: &Value) -> Reply { |
| 291 | let path = tri!(path_arg(args, "path")); |
| 292 | let text = match std::fs::read_to_string(&path) { |
| 293 | Ok(text) => text, |
| 294 | Err(e) => return Reply::err(format!("could not read {}: {e}", path.display())), |
| 295 | }; |
| 296 | let s = tri!(server.session()); |
| 297 | let fps = s.timeline_frame_rate(); |
| 298 | let t = match engine::interchange::otio::read(&text, fps) { |
| 299 | Ok(t) => t, |
| 300 | Err(e) => return Reply::err(format!("project_import_timeline failed, nothing changed: {e}")), |
| 301 | }; |
| 302 | let before = s.history_pushes(); |
| 303 | let id = match s.import_timeline(&t) { |
| 304 | Ok(id) => id, |
| 305 | Err(e) => return Reply::err(format!("project_import_timeline failed, nothing changed: {e}")), |
| 306 | }; |
| 307 | let steps = s.history_pushes().saturating_sub(before); |
| 308 | let clips: usize = t |
| 309 | .tracks |
| 310 | .iter() |
| 311 | .map(|tr| tr.items.iter().filter(|i| matches!(i, engine::interchange::Item::Clip(_))).count()) |
| 312 | .sum(); |
| 313 | let mut lines = vec![format!( |
| 314 | "imported {} as sequence {id}: {} track(s), {clips} clip(s), {} marker(s); it is the active sequence", |
| 315 | t.name, |
| 316 | t.tracks.len(), |
| 317 | t.markers.len() |
| 318 | )]; |
| 319 | lines.extend(t.notes.iter().cloned()); |
| 320 | if steps > 0 { |
| 321 | server.saved_sources = None; |
| 322 | crate::tools::project::note_pushes_as(server, before, "project_import_timeline"); |
| 323 | crate::tools::media::remember_sources(server); |
| 324 | lines.push("undo takes the import back".to_string()); |
| 325 | } |
| 326 | lines.push("unsaved until project_save".to_string()); |
| 327 | Reply::ok(lines.join("\n")).with(json!({"sequence": id, "name": t.name, "tracks": t.tracks.len(), "clips": clips, "markers": t.markers.len()})) |
| 328 | } |
| 329 | |
| 330 | fn schema(properties: Value, required: &[&str]) -> Value { |
| 331 | json!({ |
| 332 | "type": "object", |
| 333 | "properties": properties, |
| 334 | "required": required, |
| 335 | "additionalProperties": false |
| 336 | }) |
| 337 | } |
| 338 | |
| 339 | // ---- shared helpers (also used by the media tools) ------------------------- |
| 340 | |
| 341 | /// Expands a leading `~` or `~/` to the home directory. |
| 342 | pub fn expand_home(raw: &str) -> PathBuf { |
| 343 | if (raw == "~" || raw.starts_with("~/")) |
| 344 | && let Some(home) = std::env::var_os("HOME") |
| 345 | { |
| 346 | let mut p = PathBuf::from(home); |
| 347 | if let Some(rest) = raw.strip_prefix("~/") { |
| 348 | p.push(rest); |
| 349 | } |
| 350 | return p; |
| 351 | } |
| 352 | PathBuf::from(raw) |
| 353 | } |
| 354 | |
| 355 | /// Whether the open project has changes since it was last saved or opened. |
| 356 | /// A project never saved (`saved_depth` is `None`) is dirty. Undo and redo move the ledger's |
| 357 | /// top entry, so back at the saved position the project is clean again; the engine's push |
| 358 | /// count is not used, since undo leaves it raised. |
| 359 | pub fn dirty(server: &Server) -> bool { |
| 360 | match &server.session { |
| 361 | None => false, |
| 362 | Some(s) => { |
| 363 | Some(s.undo_depth()) != server.saved_depth |
| 364 | || server.ledger_top() != server.saved_top |
| 365 | || Some(s.sources().len()) != server.saved_sources |
| 366 | || !server.load_fixes.is_empty() |
| 367 | } |
| 368 | } |
| 369 | } |
| 370 | |
| 371 | /// Whether this session changed the project since it opened it, saved it, or (for a media file |
| 372 | /// started as a project) since that start: an engine snapshot pushed, a source added or removed, |
| 373 | /// or the undo depth moved. Loads that only fixed or relinked what was on disk do not count, and |
| 374 | /// neither does a recovery, whose edits are already in an autosave. A session that made no edit |
| 375 | /// never writes an autosave. |
| 376 | fn edited_this_session(server: &Server, session: &PlaybackSession) -> bool { |
| 377 | if let Some((depth, pushes, sources)) = server.media_open { |
| 378 | return (session.undo_depth(), session.history_pushes(), session.sources().len()) != (depth, pushes, sources); |
| 379 | } |
| 380 | match (server.saved_pushes, server.saved_sources) { |
| 381 | (Some(pushes), Some(sources)) => { |
| 382 | session.history_pushes() != pushes |
| 383 | || session.sources().len() != sources |
| 384 | || server.saved_depth.is_some_and(|d| session.undo_depth() != d) |
| 385 | } |
| 386 | // A project never saved: whatever it holds was made in this session. |
| 387 | _ => true, |
| 388 | } |
| 389 | } |
| 390 | |
| 391 | /// Records the snapshots an engine call pushed since `before` (an engine |
| 392 | /// `history_pushes` reading taken before the change), as one ledger entry. |
| 393 | /// Exact at the undo cap, where the depth no longer grows. |
| 394 | pub fn note_pushes(server: &mut Server, before: u64) { |
| 395 | note_pushes_as(server, before, "edit"); |
| 396 | } |
| 397 | |
| 398 | /// `note_pushes` with the ledger label `label`, which undo and redo report. |
| 399 | pub fn note_pushes_as(server: &mut Server, before: u64, label: &str) { |
| 400 | let after = match &server.session { |
| 401 | Some(s) => s.history_pushes(), |
| 402 | None => return, |
| 403 | }; |
| 404 | if after > before { |
| 405 | record(server, (after - before) as usize, label); |
| 406 | } |
| 407 | } |
| 408 | |
| 409 | fn record(server: &mut Server, steps: usize, label: &str) { |
| 410 | server.ledger.push(crate::server::Entry::new(steps, label)); |
| 411 | server.history_lost_on_open = false; |
| 412 | server.redo_ledger.clear(); |
| 413 | server.trim_ledger(); |
| 414 | } |
| 415 | |
| 416 | fn path_arg(args: &Value, name: &str) -> Result<PathBuf, Reply> { |
| 417 | Ok(absolute(&expand_home(arg_str(args, name)?))) |
| 418 | } |
| 419 | |
| 420 | /// `path` as an absolute path: a relative one is resolved against the server's working |
| 421 | /// directory, so every reply can name the file it used. Nothing is canonicalized, since the |
| 422 | /// file may not exist yet. |
| 423 | pub fn absolute(path: &Path) -> PathBuf { |
| 424 | if path.is_absolute() { |
| 425 | return path.to_path_buf(); |
| 426 | } |
| 427 | std::env::current_dir().map_or_else(|_| path.to_path_buf(), |cwd| cwd.join(path)) |
| 428 | } |
| 429 | |
| 430 | /// How many dated autosave copies (`<stem>.autosave-<stamp>.edith`) a project keeps. Older |
| 431 | /// ones are deleted when a newer one is set aside. |
| 432 | const DATED_KEEP: usize = 3; |
| 433 | |
| 434 | /// A dated copy written this recently is never deleted, however many newer copies there are: its |
| 435 | /// edits may be the only copy of work a person has not yet looked at again. |
| 436 | const DATED_RECENT: Duration = Duration::from_secs(7 * 24 * 60 * 60); |
| 437 | |
| 438 | fn mtime(path: &Path) -> Option<SystemTime> { |
| 439 | std::fs::metadata(path).and_then(|m| m.modified()).ok() |
| 440 | } |
| 441 | |
| 442 | fn canon(path: &Path) -> PathBuf { |
| 443 | std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()) |
| 444 | } |
| 445 | |
| 446 | /// Records that this session opened or saved `path`, with the mtime it has now. |
| 447 | fn note_own(server: &mut Server, path: &Path) { |
| 448 | let c = canon(path); |
| 449 | let mt = mtime(path); |
| 450 | server.own_files.retain(|(p, _)| *p != c); |
| 451 | server.own_files.push((c, mt)); |
| 452 | } |
| 453 | |
| 454 | /// The mtime this session last left `path` with, when the session opened or saved it. |
| 455 | fn own_mtime(server: &Server, path: &Path) -> Option<Option<SystemTime>> { |
| 456 | let c = canon(path); |
| 457 | server.own_files.iter().find(|(p, _)| *p == c).map(|(_, mt)| *mt) |
| 458 | } |
| 459 | |
| 460 | fn guard_dirty(server: &Server, discard: bool, what: &str) -> Result<Option<String>, Reply> { |
| 461 | if !dirty(server) { |
| 462 | return Ok(None); |
| 463 | } |
| 464 | if !discard { |
| 465 | let at = server |
| 466 | .path |
| 467 | .as_ref() |
| 468 | .map_or_else(|| "the open project".to_string(), |p| p.display().to_string()); |
| 469 | return Err(Reply::err(format!( |
| 470 | "{at} has unsaved changes; project_save it first, or pass discard: true to {what} anyway" |
| 471 | ))); |
| 472 | } |
| 473 | Ok(Some(discarded_note(server))) |
| 474 | } |
| 475 | |
| 476 | /// What a discard says: which unsaved edits it drops, and the autosave they were written to |
| 477 | /// first, so they can still be recovered. |
| 478 | fn discarded_note(server: &Server) -> String { |
| 479 | let old = server |
| 480 | .path |
| 481 | .as_ref() |
| 482 | .map_or_else(|| "the open project".to_string(), |p| p.display().to_string()); |
| 483 | match write_autosave(server) { |
| 484 | Ok(Some(auto)) => format!("discarded unsaved edits in {old} (still in its autosave {})", auto.display()), |
| 485 | // Nothing written: the autosave beside the project already holds these edits, or they match the file. |
| 486 | Ok(None) => match server.path.as_deref().map(autosave_path).filter(|a| a.is_file()) { |
| 487 | Some(auto) => format!("discarded unsaved edits in {old} (its autosave {} is the last written copy)", auto.display()), |
| 488 | None => format!("discarded unsaved edits in {old} (nothing was written beside it)"), |
| 489 | }, |
| 490 | Err(why) => { |
| 491 | eprintln!("autosave FAILED: {why}; the discarded edits are NOT on disk"); |
| 492 | format!("discarded unsaved edits in {old}: autosave FAILED ({why}), so those edits are gone") |
| 493 | } |
| 494 | } |
| 495 | } |
| 496 | |
| 497 | /// The reply line for a path the person typed relative: the absolute path the call used. |
| 498 | fn relative_note(args: &Value, name: &str, used: &Path) -> Option<String> { |
| 499 | let raw = arg_str(args, name).ok()?; |
| 500 | (!expand_home(raw).is_absolute()).then(|| format!("{raw} is a relative path; the file used is {}", used.display())) |
| 501 | } |
| 502 | |
| 503 | /// Installs a session as the open project, with a fresh ledger. |
| 504 | fn install(server: &mut Server, session: PlaybackSession, path: PathBuf, saved: Option<(Option<SystemTime>, usize)>) { |
| 505 | let (mt, depth) = match saved { |
| 506 | Some((mt, depth)) => (mt, Some(depth)), |
| 507 | None => (None, None), |
| 508 | }; |
| 509 | server.saved_pushes = depth.map(|_| session.history_pushes()); |
| 510 | server.saved_sources = depth.map(|_| session.sources().len()); |
| 511 | server.session = Some(session); |
| 512 | server.saved_body = if depth.is_some() { server.session.as_ref().and_then(session_body) } else { None }; |
| 513 | note_own(server, &path); |
| 514 | server.path = Some(path); |
| 515 | server.saved_mtime = mt; |
| 516 | server.saved_depth = depth; |
| 517 | server.history_lost_on_open = !server.ledger.is_empty(); |
| 518 | server.ledger.clear(); |
| 519 | server.redo_ledger.clear(); |
| 520 | server.saved_top = server.ledger_top(); |
| 521 | server.history_capped = false; |
| 522 | server.unrecovered_autosave = false; |
| 523 | server.recovered_autosave = None; |
| 524 | server.media_open = None; |
| 525 | // What the open had to fix to load: unsaved until a save writes it (see `dirty`). |
| 526 | server.load_fixes = session_fixes(server.session.as_ref()); |
| 527 | crate::tools::media::remember_sources(server); |
| 528 | } |
| 529 | |
| 530 | /// The open's load fixes as the engine reports them, empty for no session. |
| 531 | fn session_fixes(session: Option<&PlaybackSession>) -> Vec<String> { |
| 532 | session.map_or_else(Vec::new, |s| s.load_warnings().to_vec()) |
| 533 | } |
| 534 | |
| 535 | fn parse_resolution(raw: &str) -> Result<(u32, u32), Reply> { |
| 536 | let bad = || Reply::err(format!("`{raw}` is not a resolution: write WIDTHxHEIGHT, e.g. 1920x1080")); |
| 537 | let lower = raw.trim().to_ascii_lowercase(); |
| 538 | let (w, h) = lower.split_once('x').ok_or_else(bad)?; |
| 539 | let w: u32 = w.trim().parse().map_err(|_| bad())?; |
| 540 | let h: u32 = h.trim().parse().map_err(|_| bad())?; |
| 541 | if !(16..=8192).contains(&w) || !(16..=8192).contains(&h) { |
| 542 | return Err(Reply::err(format!("{w}x{h}: each side must be 16 to 8192 pixels"))); |
| 543 | } |
| 544 | if !w.is_multiple_of(2) || !h.is_multiple_of(2) { |
| 545 | return Err(Reply::err(format!("{w}x{h}: width and height must both be even"))); |
| 546 | } |
| 547 | if !engine::is_resolution(w, h) { |
| 548 | return Err(Reply::err(format!("{w}x{h} is not a resolution the engine accepts"))); |
| 549 | } |
| 550 | Ok((w, h)) |
| 551 | } |
| 552 | |
| 553 | fn fps_arg(args: &Value) -> Result<Option<f64>, Reply> { |
| 554 | match opt_f64(args, "fps") { |
| 555 | None => match args.get("fps") { |
| 556 | None | Some(Value::Null) => Ok(None), |
| 557 | Some(_) => Err(Reply::err("argument `fps` must be a number, e.g. 30")), |
| 558 | }, |
| 559 | Some(f) if f.is_finite() && (1.0..=240.0).contains(&f) => Ok(Some(f)), |
| 560 | Some(f) => Err(Reply::err(format!("fps {f} is out of range: use a frame rate from 1 to 240"))), |
| 561 | } |
| 562 | } |
| 563 | |
| 564 | fn fmt_fps(f: f64) -> String { |
| 565 | let s = format!("{f:.3}"); |
| 566 | s.trim_end_matches('0').trim_end_matches('.').to_string() |
| 567 | } |
| 568 | |
| 569 | /// Every clip's start and end frame on every lane, in lane order. A rate change retimes each one. |
| 570 | fn clip_edges(s: &PlaybackSession) -> Vec<u32> { |
| 571 | let mut edges = Vec::new(); |
| 572 | for lane in s.lanes() { |
| 573 | for clip in s.lane_clips(lane) { |
| 574 | edges.push(clip.start); |
| 575 | edges.push(clip.end()); |
| 576 | } |
| 577 | } |
| 578 | edges |
| 579 | } |
| 580 | |
| 581 | /// How many edges sit at a different time after a change from `old_fps` to `new_fps`: each |
| 582 | /// frame number is compared as the seconds it names before and after the change. |
| 583 | fn moved_edges(before: &[u32], after: &[u32], old_fps: f64, new_fps: f64) -> usize { |
| 584 | before |
| 585 | .iter() |
| 586 | .zip(after) |
| 587 | .filter(|(b, a)| (f64::from(**b) / old_fps - f64::from(**a) / new_fps).abs() > 1e-9) |
| 588 | .count() |
| 589 | } |
| 590 | |
| 591 | /// The locked lanes whose clip edges an fps change from `old` to `new` would move, with how many |
| 592 | /// edges move on each. The engine's own rate map says where each edge lands, the one the retime uses. |
| 593 | fn locked_lanes_moved(s: &PlaybackSession, old: f64, new: f64) -> Vec<(String, usize)> { |
| 594 | let Ok(k) = Rate::from_fps(old, new) else { |
| 595 | return Vec::new(); |
| 596 | }; |
| 597 | s.lanes() |
| 598 | .into_iter() |
| 599 | .filter(|&l| s.lane_locked(l)) |
| 600 | .filter_map(|l| { |
| 601 | let edges: Vec<u32> = s.lane_clips(l).iter().flat_map(|c| [c.start, c.end()]).collect(); |
| 602 | let after: Vec<u32> = edges.iter().map(|&e| k.timeline_nearest(e)).collect(); |
| 603 | let moved = moved_edges(&edges, &after, old, new); |
| 604 | (moved > 0).then(|| (parse::lane_name(l), moved)) |
| 605 | }) |
| 606 | .collect() |
| 607 | } |
| 608 | |
| 609 | /// The start frame of every clip on a locked lane, in lane order. An fps change keeps such a clip's |
| 610 | /// seconds and rescales its frame number, so its address (`V1@100`) moves with the rate. |
| 611 | fn locked_starts(s: &PlaybackSession) -> Vec<(Lane, u32)> { |
| 612 | let mut out = Vec::new(); |
| 613 | for l in s.lanes() { |
| 614 | if s.lane_locked(l) { |
| 615 | for c in s.lane_clips(l) { |
| 616 | out.push((l, c.start)); |
| 617 | } |
| 618 | } |
| 619 | } |
| 620 | out |
| 621 | } |
| 622 | |
| 623 | /// How many moved addresses an fps note names before it says `… (N more)`. |
| 624 | const ADDRESSES_SHOWN: usize = 8; |
| 625 | |
| 626 | /// The note an fps change owes when it keeps a locked lane's times but moves its frame addresses: |
| 627 | /// `locked lane V1 keeps its times; its frame addresses change: V1@100→V1@120`. `before` and `after` |
| 628 | /// are `locked_starts` read either side of the change. `moved` names the lanes whose times moved |
| 629 | /// (the force warning covers those). None when no other locked clip's address changes. |
| 630 | fn locked_address_note(before: &[(Lane, u32)], after: &[(Lane, u32)], moved: &[String]) -> Option<String> { |
| 631 | let mut lanes: Vec<String> = Vec::new(); |
| 632 | let mut pairs: Vec<String> = Vec::new(); |
| 633 | for (&(lane, b), &(_, a)) in before.iter().zip(after) { |
| 634 | let name = parse::lane_name(lane); |
| 635 | if b == a || moved.contains(&name) { |
| 636 | continue; |
| 637 | } |
| 638 | if !lanes.contains(&name) { |
| 639 | lanes.push(name); |
| 640 | } |
| 641 | pairs.push(format!("{}→{}", parse::addr(lane, b), parse::addr(lane, a))); |
| 642 | } |
| 643 | if pairs.is_empty() { |
| 644 | return None; |
| 645 | } |
| 646 | let (one, shown) = (lanes.len() == 1, pairs.len().min(ADDRESSES_SHOWN)); |
| 647 | let more = if pairs.len() > shown { format!(", … ({} more)", pairs.len() - shown) } else { String::new() }; |
| 648 | let (who, keep, pronoun) = if one { ("lane", "keeps its", "its") } else { ("lanes", "keep their", "their") }; |
| 649 | Some(format!( |
| 650 | "locked {who} {} {keep} times; {pronoun} frame addresses change: {}{more}", |
| 651 | lanes.join(", "), |
| 652 | pairs[..shown].join(", ") |
| 653 | )) |
| 654 | } |
| 655 | |
| 656 | // ---- tools ----------------------------------------------------------------- |
| 657 | |
| 658 | /// The refusal `project_new` gives for a path with an earlier session's unsaved edits in its |
| 659 | /// autosave, unless `overwrite` is set. It names the autosave and what it holds, and the two ways |
| 660 | /// on: continue from it, or start fresh (overwrite sets the autosave aside as a dated copy). |
| 661 | fn new_over_autosave_refusal(path: &Path, overwrite: bool) -> Option<String> { |
| 662 | if overwrite { |
| 663 | return None; |
| 664 | } |
| 665 | let auto = unloaded_autosave(path)?; |
| 666 | let when = mtime(&auto).map_or_else(|| "an unknown time".to_string(), local_text); |
| 667 | // Compared with the saved project beside the path when there is one, else with an empty |
| 668 | // project. The reply names which, so the difference is read against the right thing. |
| 669 | let p = path.display(); |
| 670 | let (summary, against) = if path.is_file() { |
| 671 | let disk = std::fs::read_to_string(path).unwrap_or_default(); |
| 672 | let summary = match PlaybackSession::open_project(path) { |
| 673 | Ok(saved) => describe_autosave(&saved, &disk, &auto), |
| 674 | Err(e) => format!("the saved project could not be read: {e}"), |
| 675 | }; |
| 676 | (summary, "the saved project".to_string()) |
| 677 | } else { |
| 678 | let summary = match PlaybackSession::empty(1920, 1080, 30.0) { |
| 679 | // No file to read settings from: the autosave's own settings then count as unchanged. |
| 680 | Ok(empty) => { |
| 681 | let auto_text = std::fs::read_to_string(&auto).unwrap_or_default(); |
| 682 | describe_autosave(&empty, &auto_text, &auto) |
| 683 | } |
| 684 | Err(e) => format!("could not be read: {e}"), |
| 685 | }; |
| 686 | (summary, format!("an empty project, since {p} is not saved yet")) |
| 687 | }; |
| 688 | Some(format!( |
| 689 | "the autosave at {} from {when} differs from {against} by {summary}; it holds an earlier session's unsaved edits. Continue from it with project_open {{\"path\": \"{p}\", \"recover\": true}}, or start fresh with project_new {{\"path\": \"{p}\", \"overwrite\": true}}, which sets the autosave aside as a dated copy. Nothing was created.", |
| 690 | auto.display() |
| 691 | )) |
| 692 | } |
| 693 | |
| 694 | /// `templates`: every template, the built-ins first. |
| 695 | fn templates_list(server: &mut Server, args: &Value) -> Reply { |
| 696 | if let Some(spec) = args.get("save") { |
| 697 | return templates_save(server, spec); |
| 698 | } |
| 699 | let Some(dir) = server.templates_dir() else { |
| 700 | return Reply::err("there is no data folder to keep templates in"); |
| 701 | }; |
| 702 | let rows = engine::templates::list(&dir); |
| 703 | let text = rows |
| 704 | .iter() |
| 705 | .map(|r| { |
| 706 | let kind = if r.builtin { "built-in" } else { "saved" }; |
| 707 | let clips = if r.clips { ", keeps clips" } else { "" }; |
| 708 | format!("{} ({kind}{clips})", r.name) |
| 709 | }) |
| 710 | .collect::<Vec<_>>() |
| 711 | .join("\n"); |
| 712 | let items: Vec<Value> = rows.iter().map(|r| json!({"name": r.name, "builtin": r.builtin, "clips": r.clips})).collect(); |
| 713 | Reply::ok(text).with(json!({"templates": items})) |
| 714 | } |
| 715 | |
| 716 | /// `templates {save: {name, with_clips?}}`: the open project saved as a template, the same |
| 717 | /// `engine::templates::save` call File > Save as template makes, with no export preset kept. |
| 718 | fn templates_save(server: &mut Server, spec: &Value) -> Reply { |
| 719 | let Some(name) = opt_str(spec, "name") else { |
| 720 | return Reply::err("templates save needs `name`: 1 to 40 characters, no slashes, not a built-in's name"); |
| 721 | }; |
| 722 | let with_clips = opt_bool(spec, "with_clips").unwrap_or(false); |
| 723 | let Some(dir) = server.templates_dir() else { |
| 724 | return Reply::err("there is no data folder to keep templates in"); |
| 725 | }; |
| 726 | let s = tri!(server.session_ref()); |
| 727 | let clips = with_clips && !s.sources().is_empty(); |
| 728 | match engine::templates::save(&dir, s, name, with_clips, None) { |
| 729 | Ok(replaced) => { |
| 730 | let verb = if replaced { "Replaced" } else { "Saved" }; |
| 731 | let kept = if clips { " with its clips and sources" } else { " (settings only)" }; |
| 732 | Reply::ok(format!("{verb} template {}{kept}", name.trim())).with(json!({"template": name.trim(), "replaced": replaced, "clips": clips})) |
| 733 | } |
| 734 | Err(e) => Reply::err(format!("not saved: {e}")), |
| 735 | } |
| 736 | } |
| 737 | |
| 738 | fn project_new(server: &mut Server, args: &Value) -> Reply { |
| 739 | let path = tri!(path_arg(args, "path")); |
| 740 | let discard = opt_bool(args, "discard").unwrap_or(false); |
| 741 | let overwrite = opt_bool(args, "overwrite").unwrap_or(false); |
| 742 | // An earlier session's unsaved edits beside this path: the person chooses before anything is |
| 743 | // created, whether or not the file exists. |
| 744 | if let Some(why) = new_over_autosave_refusal(&path, overwrite) { |
| 745 | return Reply::err(why); |
| 746 | } |
| 747 | let existed = path.exists(); |
| 748 | if existed && !overwrite { |
| 749 | return Reply::err(format!( |
| 750 | "{} already exists; use project_open {{\"path\": \"{}\"}} to continue it, or overwrite:true to replace it on project_save", |
| 751 | path.display(), |
| 752 | path.display() |
| 753 | )); |
| 754 | } |
| 755 | let discarded = tri!(guard_dirty(server, discard, "start a new project")); |
| 756 | // A template sets the canvas, the rate, the lanes and the caption style; a size or rate typed |
| 757 | // as well would be one of two answers, so it is refused. |
| 758 | let (session, from) = match opt_str(args, "template") { |
| 759 | Some(name) => { |
| 760 | if opt_str(args, "resolution").is_some() || args.get("fps").is_some() { |
| 761 | return Reply::err("a template sets the canvas size and frame rate: leave out resolution and fps, or leave out template"); |
| 762 | } |
| 763 | let Some(dir) = server.templates_dir() else { |
| 764 | return Reply::err("there is no data folder to read templates from"); |
| 765 | }; |
| 766 | match engine::templates::open(&dir, name) { |
| 767 | Ok(o) => (o.session, Some((name.to_string(), o.export))), |
| 768 | Err(e) => return Reply::err(e.to_string()), |
| 769 | } |
| 770 | } |
| 771 | None => { |
| 772 | let (w, h) = match opt_str(args, "resolution") { |
| 773 | Some(r) => tri!(parse_resolution(r)), |
| 774 | None => (1920, 1080), |
| 775 | }; |
| 776 | let fps = tri!(fps_arg(args)).unwrap_or(30.0); |
| 777 | match PlaybackSession::empty(w, h, fps) { |
| 778 | Ok(s) => (s, None), |
| 779 | Err(e) => return Reply::err(format!("could not start an empty project: {e}")), |
| 780 | } |
| 781 | } |
| 782 | }; |
| 783 | let (w, h) = session.resolution(); |
| 784 | let fps = session.meta().frame_rate; |
| 785 | // The folder the project will be saved into is made now, so project_save does not later fail |
| 786 | // on a folder that is not there. Made only once the project has started, so a refusal leaves nothing. |
| 787 | let folder = path.parent().filter(|d| !d.as_os_str().is_empty() && !d.is_dir()); |
| 788 | if let Some(dir) = folder |
| 789 | && let Err(e) = std::fs::create_dir_all(dir) |
| 790 | { |
| 791 | return Reply::err(format!("could not create the folder {} for the project: {e}", dir.display())); |
| 792 | } |
| 793 | install(server, session, path.clone(), None); |
| 794 | // overwrite:true: the file that exists is the one project_save may replace (its mtime is |
| 795 | // the one this project was started against), so the save is not refused as a change on disk. |
| 796 | if existed { |
| 797 | server.saved_mtime = mtime(&path); |
| 798 | } |
| 799 | let mut text = format!( |
| 800 | "new project {} ({w}x{h} @{}); the project file is written only by project_save, which needs at least one source (media_import first). Unsaved work is autosaved beside it when this session ends", |
| 801 | path.display(), |
| 802 | fmt_fps(fps) |
| 803 | ); |
| 804 | if let Some((name, export)) = &from { |
| 805 | text.push_str(&format!("\nstarted from template {name}")); |
| 806 | if let Some(id) = export { |
| 807 | text.push_str(&format!("; its export preset is {id}")); |
| 808 | } |
| 809 | } |
| 810 | if let Some(note) = relative_note(args, "path", &path) { |
| 811 | text.push_str(&format!("\n{note}")); |
| 812 | } |
| 813 | if let Some(dir) = folder { |
| 814 | text.push_str(&format!("\ncreated the folder {} for the project (with any folders missing above it)", dir.display())); |
| 815 | } |
| 816 | if existed { |
| 817 | text.push_str(&format!("\n{} exists and project_save will replace it", path.display())); |
| 818 | } |
| 819 | // An autosave an earlier session left beside this path is never overwritten by this one. |
| 820 | // overwrite:true replaces that project, so its autosave is set aside (dated, kept) instead, |
| 821 | // and the next save is not refused over it. |
| 822 | let auto = autosave_path(&path); |
| 823 | if auto.is_file() { |
| 824 | let aside = if overwrite { set_aside_dated(&auto, &path).ok() } else { None }; |
| 825 | match aside { |
| 826 | Some((kept, pruned)) => { |
| 827 | text.push_str(&format!( |
| 828 | "\nset the earlier autosave {} aside as {} (overwrite: its unsaved edits are not loaded; the copy is kept (the newest 3 dated copies and any from the last 7 days are kept; older ones are deleted))", |
| 829 | auto.display(), |
| 830 | kept.display() |
| 831 | )); |
| 832 | if let Some(note) = pruned_note(&pruned) { |
| 833 | text.push_str(&format!("\n{note}")); |
| 834 | } |
| 835 | } |
| 836 | None => { |
| 837 | server.unrecovered_autosave = true; |
| 838 | text.push_str(&format!("\nan autosave from an earlier session is at {}; this session's autosave is kept apart from it", auto.display())); |
| 839 | } |
| 840 | } |
| 841 | } |
| 842 | if let Some(note) = discarded { |
| 843 | text = format!("{note}\n{text}"); |
| 844 | } |
| 845 | Reply::ok(text) |
| 846 | } |
| 847 | |
| 848 | fn project_open(server: &mut Server, args: &Value) -> Reply { |
| 849 | let path = tri!(path_arg(args, "path")); |
| 850 | let discard = opt_bool(args, "discard").unwrap_or(false); |
| 851 | let discard_autosave = opt_bool(args, "discard_autosave").unwrap_or(false); |
| 852 | // A media file's project is <stem>.edith beside it: recovering it must install that project, |
| 853 | // never the media file, or a save would write project data over the media. |
| 854 | match args.get("recover") { |
| 855 | Some(Value::Bool(true)) => return recover_open(server, &project_file(&path), discard, None), |
| 856 | Some(Value::String(name)) => return recover_open(server, &project_file(&path), discard, Some(name.trim())), |
| 857 | _ => {} |
| 858 | } |
| 859 | if !path.exists() { |
| 860 | // project_new names a path that is written only by project_save, so the open |
| 861 | // project can have a path no file has yet. |
| 862 | if server.session.is_some() && server.path.as_deref() == Some(path.as_path()) { |
| 863 | let mut text = format!( |
| 864 | "{} is the open project, not yet saved — it's already open; call project_save to write it", |
| 865 | path.display() |
| 866 | ); |
| 867 | // An earlier session's autosave makes that save refuse: say how to get past it. |
| 868 | let auto = autosave_path(&path); |
| 869 | if auto.is_file() && server.recovered_autosave.as_deref() != Some(auto.as_path()) { |
| 870 | text.push_str(&format!("\n{}", unrecovered_choices(&path))); |
| 871 | } |
| 872 | return Reply::err(text); |
| 873 | } |
| 874 | return Reply::err(match unsaved_autosave_note(&path) { |
| 875 | Some(note) => format!("{}\n{note}", not_found(&path)), |
| 876 | None => not_found(&path), |
| 877 | }); |
| 878 | } |
| 879 | // Checked before the unsaved guard: a refusal names this file, not the open project. |
| 880 | if let Some(why) = not_a_file(&path) { |
| 881 | return Reply::err(why); |
| 882 | } |
| 883 | let is_edith = path |
| 884 | .extension() |
| 885 | .and_then(|e| e.to_str()) |
| 886 | .is_some_and(|e| e.eq_ignore_ascii_case("edith")); |
| 887 | if let Err(e) = std::fs::File::open(&path) { |
| 888 | return Reply::err(format!("cannot read {}: {e}", path.display())); |
| 889 | } |
| 890 | if !is_edith && !is_media(&path) { |
| 891 | // The reason a named refusal gives for a media file the engine will not open (a display matrix |
| 892 | // that is not a quarter turn), so the refusal says why; anything else is not media. |
| 893 | return Reply::err(match named_media_refusal(&path) { |
| 894 | Some(why) => format!("{} is media edith cannot open: {why}", path.display()), |
| 895 | None => format!("{} is not an edith project or a media file", path.display()), |
| 896 | }); |
| 897 | } |
| 898 | // Read the project first, so the autosave decision is made before anything is written. A |
| 899 | // media file's project is <stem>.edith beside it. |
| 900 | let project = project_file(&path); |
| 901 | let (session, relinks, notes) = if is_edith { |
| 902 | let (relinks, notes) = relink_by_name(&path, &search_dirs(args)); |
| 903 | match PlaybackSession::open_project_relinked(&path, &relinks) { |
| 904 | Ok(s) => (s, relinks, notes), |
| 905 | Err(e) => return Reply::err(open_failure(&path, &e.to_string())), |
| 906 | } |
| 907 | } else { |
| 908 | match PlaybackSession::open(&path) { |
| 909 | Ok(s) => (s, Vec::new(), Vec::new()), |
| 910 | Err(e) => return Reply::err(format!("could not open {} as a project: {e}", path.display())), |
| 911 | } |
| 912 | }; |
| 913 | // An earlier session's unsaved edits beside the project: the person chooses how to open, and |
| 914 | // nothing is loaded, written or set aside until they do. |
| 915 | if let Some(why) = unloaded_autosave_refusal(&project, &session, discard_autosave) { |
| 916 | return Reply::err(why); |
| 917 | } |
| 918 | let discarded = tri!(guard_dirty(server, discard, "open another file")); |
| 919 | // The lines the reply starts with, in order: unloaded edits first, then what a discard dropped. |
| 920 | let mut lead: Vec<String> = Vec::new(); |
| 921 | let settled = match settle_autosave_on_open(&project, discard_autosave) { |
| 922 | Ok(note) => note, |
| 923 | Err(why) => return Reply::err(why), |
| 924 | }; |
| 925 | if is_edith { |
| 926 | let depth = session.undo_depth(); |
| 927 | let mt = mtime(&path); |
| 928 | let offline = session.offline_sources(); |
| 929 | let fixes = load_fix_lines(&session); |
| 930 | let older = older_autosave_lines(&path, &session); |
| 931 | install(server, session, path, Some((mt, depth))); |
| 932 | // Relinked paths are written by the next save, so the project is unsaved until then. |
| 933 | if !relinks.is_empty() { |
| 934 | server.load_fixes.push(format!("relinked {} source(s) by name", relinks.len())); |
| 935 | lead.push(format!("relinked {} source(s); save to keep the new paths", relinks.len())); |
| 936 | } |
| 937 | lead.extend(fixes); |
| 938 | lead.extend(settled); |
| 939 | lead.extend(notes); |
| 940 | lead.extend(offline_lines(&offline)); |
| 941 | lead.extend(older); |
| 942 | } else { |
| 943 | let base = (session.undo_depth(), session.history_pushes(), session.sources().len()); |
| 944 | install(server, session, project, None); |
| 945 | server.media_open = Some(base); |
| 946 | lead.extend(settled); |
| 947 | } |
| 948 | lead.extend(discarded); |
| 949 | let mut reply = status_reply(server); |
| 950 | if !lead.is_empty() { |
| 951 | reply.text = format!("{}\n{}", lead.join("\n"), reply.text); |
| 952 | } |
| 953 | reply.text.push_str(UNDO_OPEN_NOTE); |
| 954 | reply |
| 955 | } |
| 956 | |
| 957 | /// The project file `project_open` loads for `path`: the path itself for a .edith file, else the |
| 958 | /// <stem>.edith beside a media file. |
| 959 | fn project_file(path: &Path) -> PathBuf { |
| 960 | if path.extension().and_then(|e| e.to_str()).is_some_and(|e| e.eq_ignore_ascii_case("edith")) { |
| 961 | path.to_path_buf() |
| 962 | } else { |
| 963 | path.with_extension("edith") |
| 964 | } |
| 965 | } |
| 966 | |
| 967 | /// The folders `project_open {search}` names, expanded. |
| 968 | fn search_dirs(args: &Value) -> Vec<PathBuf> { |
| 969 | args.get("search") |
| 970 | .and_then(Value::as_array) |
| 971 | .map(|a| a.iter().filter_map(Value::as_str).map(|s| expand_home(s.trim())).collect()) |
| 972 | .unwrap_or_default() |
| 973 | } |
| 974 | |
| 975 | /// Finds each offline source of the project at `path` by file name under `dirs`. A name found |
| 976 | /// exactly once is relinked; several matches are listed and left offline. Returns the pairs to |
| 977 | /// open with and the lines that say what was done. |
| 978 | fn relink_by_name(path: &Path, dirs: &[PathBuf]) -> (Vec<(PathBuf, PathBuf)>, Vec<String>) { |
| 979 | let (mut relinks, mut notes) = (Vec::new(), Vec::new()); |
| 980 | if dirs.is_empty() { |
| 981 | return (relinks, notes); |
| 982 | } |
| 983 | let Ok(doc) = engine::edith::load(path) else { |
| 984 | return (relinks, notes); |
| 985 | }; |
| 986 | for (i, source) in doc.sources.iter().enumerate() { |
| 987 | if engine::source_present(&source.path) { |
| 988 | continue; |
| 989 | } |
| 990 | let Some(name) = source.path.file_name() else { |
| 991 | continue; |
| 992 | }; |
| 993 | let mut found = Vec::new(); |
| 994 | for dir in dirs { |
| 995 | find_named(dir, name, 6, &mut found); |
| 996 | } |
| 997 | match found.len() { |
| 998 | 0 => notes.push(format!("src:{i} {} is not under the search folders", source.path.display())), |
| 999 | 1 => { |
| 1000 | let new = found.remove(0); |
| 1001 | notes.push(format!("src:{i} relinked: {} -> {}", source.path.display(), new.display())); |
| 1002 | relinks.push((source.path.clone(), new)); |
| 1003 | } |
| 1004 | n => { |
| 1005 | let all: Vec<String> = found.iter().map(|p| p.display().to_string()).collect(); |
| 1006 | notes.push(format!( |
| 1007 | "src:{i} {}: {n} files named {} under the search folders ({}); not relinked, pick one with media_relink", |
| 1008 | source.path.display(), |
| 1009 | name.to_string_lossy(), |
| 1010 | all.join(", ") |
| 1011 | )); |
| 1012 | } |
| 1013 | } |
| 1014 | } |
| 1015 | (relinks, notes) |
| 1016 | } |
| 1017 | |
| 1018 | /// Every file named `name` under `dir`, down `depth` folder levels. |
| 1019 | fn find_named(dir: &Path, name: &std::ffi::OsStr, depth: usize, out: &mut Vec<PathBuf>) { |
| 1020 | let Ok(entries) = std::fs::read_dir(dir) else { |
| 1021 | return; |
| 1022 | }; |
| 1023 | for entry in entries.flatten() { |
| 1024 | let p = entry.path(); |
| 1025 | if p.is_dir() { |
| 1026 | if depth > 0 { |
| 1027 | find_named(&p, name, depth - 1, out); |
| 1028 | } |
| 1029 | } else if p.file_name() == Some(name) { |
| 1030 | out.push(p); |
| 1031 | } |
| 1032 | } |
| 1033 | } |
| 1034 | |
| 1035 | /// The LUT report `project_open` gives: each `.cube` file clips name that cannot be used. |
| 1036 | pub(crate) fn lut_lines(problems: &[(PathBuf, String)]) -> Vec<String> { |
| 1037 | problems |
| 1038 | .iter() |
| 1039 | .map(|(p, why)| { |
| 1040 | format!( |
| 1041 | "LUT not applied: {} ({why}); its clips play without it until you relink it: edit {{ops:[{{op:\"lut\", relink:\"{}\", path:\"<new path>\"}}]}}", |
| 1042 | p.display(), |
| 1043 | p.display() |
| 1044 | ) |
| 1045 | }) |
| 1046 | .collect() |
| 1047 | } |
| 1048 | |
| 1049 | /// The offline report `project_open` gives: which sources are missing and how to fix them. |
| 1050 | fn offline_lines(offline: &[(usize, PathBuf)]) -> Vec<String> { |
| 1051 | if offline.is_empty() { |
| 1052 | return Vec::new(); |
| 1053 | } |
| 1054 | let mut lines = vec![format!( |
| 1055 | "{} source(s) offline (moved or deleted): their clips stay, and frames or exports that need them are refused", |
| 1056 | offline.len() |
| 1057 | )]; |
| 1058 | for (i, p) in offline { |
| 1059 | lines.push(format!(" src:{i} {}", p.display())); |
| 1060 | } |
| 1061 | lines.push( |
| 1062 | "fix: media_relink {\"source\": \"src:N\", \"path\": \"<file>\"} for each, or project_open {\"path\": \"<project>\", \"search\": [\"<folder>\"]} to find them by name".to_string(), |
| 1063 | ); |
| 1064 | lines |
| 1065 | } |
| 1066 | |
| 1067 | /// What `project_open` adds: the undo ledger is in-memory, so a reopened project starts |
| 1068 | /// with no steps to undo. Checkpoints are the points that survive. |
| 1069 | const UNDO_OPEN_NOTE: &str = |
| 1070 | "\nundo history starts empty in this session; use checkpoint/restore for points that survive"; |
| 1071 | |
| 1072 | /// Makes the project's own autosave `own` hold the state of the dated autosave `chosen` that a |
| 1073 | /// recovery loads. The autosave it replaces is moved to a dated copy first, so none of its edits |
| 1074 | /// are lost, and the copies beside `path` are pruned as a dated copy always is. Returns the copy |
| 1075 | /// (when one was made) and the older copies deleted to make room. Nothing is changed when `own` |
| 1076 | /// already says what `chosen` says. |
| 1077 | fn rewrite_autosave_from(chosen: &Path, own: &Path, path: &Path) -> Result<(Option<PathBuf>, Vec<PathBuf>), String> { |
| 1078 | if own.is_file() && same_project(chosen, own) { |
| 1079 | return Ok((None, Vec::new())); |
| 1080 | } |
| 1081 | // Copied beside the autosave, then moved into place, so a failed copy leaves `own` as it was. |
| 1082 | let staged = own.with_extension("recover.edith"); |
| 1083 | std::fs::copy(chosen, &staged).map_err(|e| format!("could not write the autosave {} ({e})", own.display()))?; |
| 1084 | let aside = if own.is_file() { |
| 1085 | match set_aside_dated(own, path) { |
| 1086 | Ok(done) => Some(done), |
| 1087 | Err(e) => { |
| 1088 | let _ = std::fs::remove_file(&staged); |
| 1089 | return Err(format!("could not move the autosave {} aside ({e}), so nothing was opened", own.display())); |
| 1090 | } |
| 1091 | } |
| 1092 | } else { |
| 1093 | None |
| 1094 | }; |
| 1095 | if let Err(e) = std::fs::rename(&staged, own) { |
| 1096 | let _ = std::fs::remove_file(&staged); |
| 1097 | return Err(format!("could not move the autosave into place at {} ({e})", own.display())); |
| 1098 | } |
| 1099 | Ok(match aside { |
| 1100 | Some((kept, pruned)) => (Some(kept), pruned), |
| 1101 | None => (None, Vec::new()), |
| 1102 | }) |
| 1103 | } |
| 1104 | |
| 1105 | /// How many lines of the project file the autosave changes: the larger of the two sides of the line |
| 1106 | /// difference, so a clip that moved counts once. Read from the files, since an autosave keeps no count. |
| 1107 | fn recovered_edits(saved: &Path, auto: &Path) -> usize { |
| 1108 | let read = |p: &Path| std::fs::read_to_string(p).unwrap_or_default(); |
| 1109 | let (saved, auto) = (read(saved), read(auto)); |
| 1110 | let (sl, al) = (body_lines(&saved), body_lines(&auto)); |
| 1111 | minus(&al, &sl).len().max(minus(&sl, &al).len()) |
| 1112 | } |
| 1113 | |
| 1114 | /// `project_open {recover: true}`: the saved project is opened as it is and the autosave's edits |
| 1115 | /// go on top of it as one undo step, so undo takes them back to the saved timeline. At the |
| 1116 | /// project's own path, so a later save writes the recovered work there, and left unsaved until |
| 1117 | /// project_save. With no readable saved file the autosave is the project itself, and undo has |
| 1118 | /// nothing earlier to return to. |
| 1119 | fn recover_open(server: &mut Server, path: &Path, discard: bool, chosen: Option<&str>) -> Reply { |
| 1120 | let own = autosave_path(path); |
| 1121 | // `chosen` names a dated autosave (its file name or its stamp); none means the project's own. |
| 1122 | let auto = match chosen { |
| 1123 | None => own.clone(), |
| 1124 | Some(name) => match dated_autosaves(path).into_iter().find(|(_, p)| autosave_matches(p, name)) { |
| 1125 | Some((_, p)) => p, |
| 1126 | None => { |
| 1127 | let listed: Vec<String> = dated_autosaves(path) |
| 1128 | .iter() |
| 1129 | .map(|(_, p)| p.file_name().map_or_else(String::new, |n| n.to_string_lossy().into_owned())) |
| 1130 | .collect(); |
| 1131 | let have = if listed.is_empty() { "there are no dated autosaves beside it".to_string() } else { format!("dated autosaves: {}", listed.join(", ")) }; |
| 1132 | return Reply::err(format!("no dated autosave named {name} beside {}; {have}", path.display())); |
| 1133 | } |
| 1134 | }, |
| 1135 | }; |
| 1136 | if !auto.is_file() { |
| 1137 | return Reply::err(format!("nothing to recover: no autosave at {}", auto.display())); |
| 1138 | } |
| 1139 | // Unsaved edits in this session would be replaced by the recovered state. Refused unless |
| 1140 | // `discard` says they are dropped. Not written to an autosave first: that would overwrite the |
| 1141 | // very autosave being recovered. |
| 1142 | let discarded = if dirty(server) { |
| 1143 | if !discard { |
| 1144 | return Reply::err(format!( |
| 1145 | "{} has unsaved edits in this session, and recovering would replace them. Keep them: project_save {{discard_autosave:true}} saves them and sets the autosave aside as a dated copy. Or drop them: project_open {{\"path\": \"{}\", \"recover\": true, \"discard\": true}} loads the autosave and the unsaved edits of this session are lost.", |
| 1146 | path.display(), |
| 1147 | path.display() |
| 1148 | )); |
| 1149 | } |
| 1150 | let old = server.path.as_ref().map_or_else(|| "the open project".to_string(), |p| p.display().to_string()); |
| 1151 | Some(format!("dropped the unsaved edits in {old} (they were not saved or autosaved)")) |
| 1152 | } else { |
| 1153 | None |
| 1154 | }; |
| 1155 | let recovered = match PlaybackSession::open_project(&auto) { |
| 1156 | Ok(s) => s, |
| 1157 | Err(e) => return Reply::err(format!("could not open the autosave {}: {e}", auto.display())), |
| 1158 | }; |
| 1159 | // The saved project, opened as it is, when there is one. The recovered edits go on top of it |
| 1160 | // as one undo step, so undo takes them back to the saved file's timeline. Checked before |
| 1161 | // anything is written: a refusal changes nothing. Without a readable saved file the autosave |
| 1162 | // is the project, and undo has nothing earlier to return to. |
| 1163 | let mut layer = if path.is_file() { PlaybackSession::open_project(path).ok() } else { None }; |
| 1164 | let unreadable = path.is_file() && layer.is_none(); |
| 1165 | let steps = match layer.as_mut() { |
| 1166 | Some(base) => { |
| 1167 | let before = base.history_pushes(); |
| 1168 | if !base.adopt_as_step(&recovered) { |
| 1169 | return Reply::err(format!( |
| 1170 | "could not recover {}: the autosave's effect settings do not fit beside the saved project's; nothing was changed", |
| 1171 | path.display() |
| 1172 | )); |
| 1173 | } |
| 1174 | Some(base.history_pushes().saturating_sub(before) as usize) |
| 1175 | } |
| 1176 | None => None, |
| 1177 | }; |
| 1178 | // A dated recovery makes the project's own autosave hold the recovered state, so the autosave |
| 1179 | // a later recover or save reads is this session's state. The one it replaces is kept dated. |
| 1180 | let rewritten = if auto == own { |
| 1181 | Ok((None, Vec::new())) |
| 1182 | } else { |
| 1183 | rewrite_autosave_from(&auto, &own, path) |
| 1184 | }; |
| 1185 | let (replaced, pruned) = match rewritten { |
| 1186 | Ok(done) => done, |
| 1187 | Err(why) => return Reply::err(why), |
| 1188 | }; |
| 1189 | let session = layer.unwrap_or(recovered); |
| 1190 | let fixes = load_fix_lines(&session); |
| 1191 | let older = older_autosave_lines(path, &session); |
| 1192 | install(server, session, path.to_path_buf(), Some((mtime(path), 0))); |
| 1193 | if let Some(n) = steps { |
| 1194 | let when = mtime(&auto).map_or_else(|| "an unknown time".to_string(), local_hhmm); |
| 1195 | let edits = recovered_edits(path, &auto); |
| 1196 | record(server, n, &format!("recover autosave ({edits} edits from {when})")); |
| 1197 | } |
| 1198 | // The project's own autosave now holds the recovered state, so it is this session's to replace. |
| 1199 | server.recovered_autosave = Some(own.clone()); |
| 1200 | // Dirty by definition: the work lives in the autosave, not in the project file. |
| 1201 | server.saved_depth = None; |
| 1202 | let mut reply = status_reply(server); |
| 1203 | let after = if auto == own { |
| 1204 | "and removes the autosave" |
| 1205 | } else { |
| 1206 | "and removes the autosave (the dated copy stays beside it)" |
| 1207 | }; |
| 1208 | reply.text.push_str(&format!( |
| 1209 | "\nrecovered the unsaved edits from {}; project_save writes them to {} {after}", |
| 1210 | auto.display(), |
| 1211 | path.display() |
| 1212 | )); |
| 1213 | if auto != own { |
| 1214 | reply.text.push_str(&format!("\nthe autosave {} now holds the recovered state, so a later recover or save reads the same edits", own.display())); |
| 1215 | } |
| 1216 | if let Some(kept) = replaced { |
| 1217 | reply.text.push_str(&format!( |
| 1218 | "\nthe earlier autosave {} was set aside as {} (its unsaved edits are not loaded; the copy is kept (the newest 3 dated copies and any from the last 7 days are kept; older ones are deleted))", |
| 1219 | own.display(), |
| 1220 | kept.display() |
| 1221 | )); |
| 1222 | if let Some(note) = pruned_note(&pruned) { |
| 1223 | reply.text.push_str(&format!("\n{note}")); |
| 1224 | } |
| 1225 | } |
| 1226 | if steps.is_some() { |
| 1227 | reply.text.push_str("\nundo takes the recovered edits back as one step, to the saved file's timeline"); |
| 1228 | } else { |
| 1229 | let why = if unreadable { "the saved file could not be opened" } else { "the project was never saved" }; |
| 1230 | reply.text.push_str(&format!( |
| 1231 | "\nundo has nothing earlier to return to: {why}, so undo starts empty here and reaches only edits made after this open. To drop the recovered edits, project_open {{discard_autosave:true}} sets the autosave aside as a dated copy" |
| 1232 | )); |
| 1233 | } |
| 1234 | for line in older { |
| 1235 | reply.text.push_str(&format!("\n{line}")); |
| 1236 | } |
| 1237 | if let Some(note) = discarded { |
| 1238 | reply.text = format!("{note}\n{}", reply.text); |
| 1239 | } |
| 1240 | if !fixes.is_empty() { |
| 1241 | reply.text = format!("{}\n{}", fixes.join("\n"), reply.text); |
| 1242 | } |
| 1243 | reply |
| 1244 | } |
| 1245 | |
| 1246 | /// One line per change a load made to open the file (a clip that ran past its source is |
| 1247 | /// clamped, not refused). They come first in a reply, since the file on disk still has the |
| 1248 | /// problem until it is saved again. |
| 1249 | fn load_fix_lines(session: &PlaybackSession) -> Vec<String> { |
| 1250 | session |
| 1251 | .load_warnings() |
| 1252 | .iter() |
| 1253 | .map(|w| format!("warning: the file needed fixing to open: {w} — save to keep the fix")) |
| 1254 | .collect() |
| 1255 | } |
| 1256 | |
| 1257 | fn project_save(server: &mut Server, args: &Value) -> Reply { |
| 1258 | let force = opt_bool(args, "force").unwrap_or(false); |
| 1259 | // Checked first: with nothing open there is no project to save, whatever path was given. |
| 1260 | if server.session.is_none() { |
| 1261 | return Reply::err( |
| 1262 | "no project is open, so there is nothing to save. Start one with project_new {path:\"/abs/new.edith\"} (then media_import), or open an existing file with project_open {path:\"/abs/file.edith\"}", |
| 1263 | ); |
| 1264 | } |
| 1265 | let target = match opt_str(args, "path") { |
| 1266 | Some(p) => absolute(&expand_home(p)), |
| 1267 | None => match &server.path { |
| 1268 | Some(p) => p.clone(), |
| 1269 | None => return Reply::err("no project path to save to: project_save {path:\"/abs/file.edith\"} first"), |
| 1270 | }, |
| 1271 | }; |
| 1272 | let session = tri!(server.session_ref()); |
| 1273 | // The engine refuses a source-less project; say why here, before any folder is blamed. |
| 1274 | if session.sources().is_empty() { |
| 1275 | return Reply::err(format!( |
| 1276 | "nothing to save yet: {} would name no sources, and a project file names its sources. Import media first (media_import), then project_save", |
| 1277 | target.display() |
| 1278 | )); |
| 1279 | } |
| 1280 | if let Some(dir) = target.parent().filter(|d| !d.as_os_str().is_empty()) |
| 1281 | && !dir.is_dir() |
| 1282 | { |
| 1283 | return Reply::err(format!("folder does not exist: {}", dir.display())); |
| 1284 | } |
| 1285 | // A file this session opened or saved (at any point, so a save-as and a save back are both |
| 1286 | // this project's) is overwritten without force, unless it changed on disk since. |
| 1287 | let known = own_mtime(server, &target); |
| 1288 | if !force && target.exists() { |
| 1289 | let Some(left) = known else { |
| 1290 | return Reply::err(format!( |
| 1291 | "{} already exists and is not this project's file; pass force: true to overwrite it", |
| 1292 | target.display() |
| 1293 | )); |
| 1294 | }; |
| 1295 | if mtime(&target) != left { |
| 1296 | return Reply::err(format!( |
| 1297 | "{} changed on disk since it was last opened or saved (the GUI may have written it); pass force: true to overwrite", |
| 1298 | target.display() |
| 1299 | )); |
| 1300 | } |
| 1301 | } |
| 1302 | // An autosave beside the open project, newer than the file, that this session did not load |
| 1303 | // holds edits this save would leave out: refused unless the person says to set it aside (the |
| 1304 | // save keeps it dated). project_open settles an earlier session's autosave first, so this is |
| 1305 | // one that appeared while this session ran. |
| 1306 | let discard_autosave = opt_bool(args, "discard_autosave").unwrap_or(false); |
| 1307 | let open_path = server.path.clone().unwrap_or_else(|| target.clone()); |
| 1308 | let open_auto = autosave_path(&open_path); |
| 1309 | let loaded_here = server.recovered_autosave.as_deref() == Some(open_auto.as_path()); |
| 1310 | if !loaded_here && !discard_autosave && unloaded_autosave(&open_path).is_some() { |
| 1311 | let when = mtime(&open_auto).map_or_else(|| "an unknown time".to_string(), local_text); |
| 1312 | let disk = std::fs::read_to_string(&open_path).unwrap_or_default(); |
| 1313 | let summary = describe_autosave(session, &disk, &open_auto); |
| 1314 | return Reply::err(format!( |
| 1315 | "an autosave from {when}, not loaded by this session, holds unsaved edits ({summary}) that are not in this project. {}", |
| 1316 | unrecovered_choices(&open_path) |
| 1317 | )); |
| 1318 | } |
| 1319 | let unchanged = !dirty(server) && server.path.as_deref() == Some(target.as_path()) && target.is_file(); |
| 1320 | // Judged against the file as it is now: the save below makes the file newer than any autosave. |
| 1321 | let stale_newer = unloaded_autosave(&target).is_some(); |
| 1322 | if let Err(e) = session.save_project(&target) { |
| 1323 | return Reply::err(write_failure(&target, &e.to_string())); |
| 1324 | } |
| 1325 | let depth = session.undo_depth(); |
| 1326 | let pushes = session.history_pushes(); |
| 1327 | let sources = session.sources().len(); |
| 1328 | let body = session_body(session); |
| 1329 | let mt = mtime(&target); |
| 1330 | server.saved_body = body; |
| 1331 | note_own(server, &target); |
| 1332 | server.path = Some(target.clone()); |
| 1333 | server.saved_mtime = mt; |
| 1334 | server.saved_depth = Some(depth); |
| 1335 | server.saved_pushes = Some(pushes); |
| 1336 | server.saved_top = server.ledger_top(); |
| 1337 | server.saved_sources = Some(sources); |
| 1338 | // The fixes the open made to load are in this save from now on. |
| 1339 | let fixed = std::mem::take(&mut server.load_fixes); |
| 1340 | let mut text = if unchanged { |
| 1341 | format!("saved {}: nothing changed since the last save (saved anyway)", target.display()) |
| 1342 | } else { |
| 1343 | format!("saved {}", target.display()) |
| 1344 | }; |
| 1345 | if let Some(note) = relative_note(args, "path", &target) { |
| 1346 | text.push_str(&format!("\n{note}")); |
| 1347 | } |
| 1348 | if !fixed.is_empty() { |
| 1349 | text.push_str(&format!("\nwritten with the {} fix(es) made to open it: {}", fixed.len(), fixed.join("; "))); |
| 1350 | } |
| 1351 | // This save wrote the session's whole state, so the autosave this session recovered is |
| 1352 | // superseded and removed, and so is one no newer than the file (it holds nothing the file |
| 1353 | // lacks). Any other autosave beside the target, newer than the file, holds edits this save |
| 1354 | // does not have: it is kept under a dated name. |
| 1355 | let stale = autosave_path(&target); |
| 1356 | if stale.is_file() { |
| 1357 | if server.recovered_autosave.as_deref() == Some(stale.as_path()) || !stale_newer { |
| 1358 | match std::fs::remove_file(&stale) { |
| 1359 | Ok(()) => text.push_str(&format!("\nremoved the autosave {}: this save replaces it", stale.display())), |
| 1360 | Err(e) => text.push_str(&format!("\ncould not remove the autosave {}: {e}", stale.display())), |
| 1361 | } |
| 1362 | } else { |
| 1363 | match set_aside_dated(&stale, &target) { |
| 1364 | Ok((kept, pruned)) => { |
| 1365 | text = format!("kept the unrecovered autosave as {} (its edits are not in this save)\n{text}", kept.display()); |
| 1366 | if let Some(note) = pruned_note(&pruned) { |
| 1367 | text.push_str(&format!("\n{note}")); |
| 1368 | } |
| 1369 | } |
| 1370 | Err(e) => text.push_str(&format!("\ncould not keep the unrecovered autosave {}: {e}", stale.display())), |
| 1371 | } |
| 1372 | } |
| 1373 | } |
| 1374 | server.unrecovered_autosave = false; |
| 1375 | server.media_open = None; |
| 1376 | Reply::ok(text) |
| 1377 | } |
| 1378 | |
| 1379 | /// Where an unrecovered autosave is kept: `<stem>.autosave-<YYYYmmdd-HHMMSS>.edith` beside the |
| 1380 | /// project, in local time. A name already taken gets `-2`, `-3`, ... so nothing is overwritten. |
| 1381 | fn kept_autosave_path(target: &Path, now: SystemTime) -> PathBuf { |
| 1382 | let stem = target.file_stem().map_or_else(|| "untitled".to_string(), |s| s.to_string_lossy().into_owned()); |
| 1383 | let stamp = local_stamp(now); |
| 1384 | let mut p = target.with_file_name(format!("{stem}.autosave-{stamp}.edith")); |
| 1385 | let mut n = 2; |
| 1386 | while p.exists() { |
| 1387 | p = target.with_file_name(format!("{stem}.autosave-{stamp}-{n}.edith")); |
| 1388 | n += 1; |
| 1389 | } |
| 1390 | p |
| 1391 | } |
| 1392 | |
| 1393 | /// Moves `from` to a new dated copy beside `target`, then keeps only the |
| 1394 | /// newest `DATED_KEEP` dated copies (the newest 3 dated copies and any from the last 7 days are kept; older ones are deleted). Returns the copy and the older copies deleted to make room. |
| 1395 | fn set_aside_dated(from: &Path, target: &Path) -> std::io::Result<(PathBuf, Vec<PathBuf>)> { |
| 1396 | let kept = kept_autosave_path(target, SystemTime::now()); |
| 1397 | std::fs::rename(from, &kept)?; |
| 1398 | let pruned = prune_dated(target, &kept); |
| 1399 | Ok((kept, pruned)) |
| 1400 | } |
| 1401 | |
| 1402 | /// Deletes the dated copies beside `target` beyond the newest `DATED_KEEP`, except those written |
| 1403 | /// within `DATED_RECENT`. `keep` (the copy just made) is never deleted and takes one of those places. |
| 1404 | /// Returns the paths deleted. What is deleted is named in the reply, and its edits are gone. |
| 1405 | fn prune_dated(target: &Path, keep: &Path) -> Vec<PathBuf> { |
| 1406 | let others: Vec<(SystemTime, PathBuf)> = dated_autosaves(target).into_iter().filter(|(_, p)| p != keep).collect(); |
| 1407 | let now = SystemTime::now(); |
| 1408 | let mut deleted = Vec::new(); |
| 1409 | // Newest first: the first `DATED_KEEP - 1` sit beside `keep`. A copy in the future counts as recent. |
| 1410 | for (i, (written, p)) in others.into_iter().enumerate() { |
| 1411 | let recent = match now.duration_since(written) { |
| 1412 | Ok(age) => age < DATED_RECENT, |
| 1413 | Err(_) => true, |
| 1414 | }; |
| 1415 | if i < DATED_KEEP - 1 || recent { |
| 1416 | continue; |
| 1417 | } |
| 1418 | if std::fs::remove_file(&p).is_ok() { |
| 1419 | deleted.push(p); |
| 1420 | } |
| 1421 | } |
| 1422 | deleted |
| 1423 | } |
| 1424 | |
| 1425 | /// The reply line for dated copies `prune_dated` deleted, if any. |
| 1426 | fn pruned_note(pruned: &[PathBuf]) -> Option<String> { |
| 1427 | if pruned.is_empty() { |
| 1428 | return None; |
| 1429 | } |
| 1430 | let names: Vec<String> = pruned.iter().filter_map(|p| p.file_name()).map(|n| n.to_string_lossy().into_owned()).collect(); |
| 1431 | Some(format!( |
| 1432 | "deleted {} older dated autosave(s) beyond the newest {DATED_KEEP} kept beside the project and older than 7 days: {}. Their unsaved edits are gone: they are in neither the project file nor any autosave now", |
| 1433 | pruned.len(), |
| 1434 | names.join(", ") |
| 1435 | )) |
| 1436 | } |
| 1437 | |
| 1438 | /// The local time of `t`, or `None` before the epoch. |
| 1439 | fn local_time(t: SystemTime) -> Option<chrono::DateTime<chrono::Local>> { |
| 1440 | t.duration_since(SystemTime::UNIX_EPOCH).ok()?; |
| 1441 | Some(chrono::DateTime::<chrono::Local>::from(t)) |
| 1442 | } |
| 1443 | |
| 1444 | /// `YYYYmmdd-HHMMSS` in local time, the stamp dated autosave names carry. |
| 1445 | fn local_stamp(t: SystemTime) -> String { |
| 1446 | match local_time(t) { |
| 1447 | Some(tm) => tm.format("%Y%m%d-%H%M%S").to_string(), |
| 1448 | None => "00000000-000000".to_string(), |
| 1449 | } |
| 1450 | } |
| 1451 | |
| 1452 | /// `HH:MM` in local time, for a ledger label. |
| 1453 | fn local_hhmm(t: SystemTime) -> String { |
| 1454 | match local_time(t) { |
| 1455 | Some(tm) => tm.format("%H:%M").to_string(), |
| 1456 | None => "an unknown time".to_string(), |
| 1457 | } |
| 1458 | } |
| 1459 | |
| 1460 | /// `YYYY-mm-dd HH:MM:SS` in local time, for replies. |
| 1461 | fn local_text(t: SystemTime) -> String { |
| 1462 | match local_time(t) { |
| 1463 | Some(tm) => tm.format("%Y-%m-%d %H:%M:%S").to_string(), |
| 1464 | None => "an unknown time".to_string(), |
| 1465 | } |
| 1466 | } |
| 1467 | |
| 1468 | /// The dated autosaves (`<stem>.autosave-<stamp>.edith`) beside `path`, newest first. Nothing is |
| 1469 | /// deleted: a dated autosave may hold unrecovered edits, so the person decides. The project's own |
| 1470 | /// `<stem>.autosave.edith` is not among them: `settle_autosave_on_open` owns it. |
| 1471 | fn dated_autosaves(path: &Path) -> Vec<(SystemTime, PathBuf)> { |
| 1472 | let dir = path.parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or(Path::new(".")); |
| 1473 | let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else { |
| 1474 | return Vec::new(); |
| 1475 | }; |
| 1476 | let prefix = format!("{stem}.autosave-"); |
| 1477 | let Ok(entries) = std::fs::read_dir(dir) else { |
| 1478 | return Vec::new(); |
| 1479 | }; |
| 1480 | let mut found: Vec<(SystemTime, PathBuf)> = entries |
| 1481 | .filter_map(Result::ok) |
| 1482 | .map(|e| e.path()) |
| 1483 | .filter(|p| { |
| 1484 | p.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with(&prefix) && n.ends_with(".edith")) |
| 1485 | && p.is_file() |
| 1486 | }) |
| 1487 | .map(|p| (mtime(&p).unwrap_or(SystemTime::UNIX_EPOCH), p)) |
| 1488 | .collect(); |
| 1489 | found.sort_by_key(|b| std::cmp::Reverse(b.0)); |
| 1490 | found |
| 1491 | } |
| 1492 | |
| 1493 | /// Whether a dated autosave is named `name`: its file name, or its stamp (`20261016-223636`, |
| 1494 | /// local time, with any `-2` suffix a name collision added). |
| 1495 | fn autosave_matches(auto: &Path, name: &str) -> bool { |
| 1496 | let Some(file) = auto.file_name().and_then(|n| n.to_str()) else { |
| 1497 | return false; |
| 1498 | }; |
| 1499 | if file == name { |
| 1500 | return true; |
| 1501 | } |
| 1502 | file.split_once(".autosave-") |
| 1503 | .and_then(|(_, rest)| rest.strip_suffix(".edith")) |
| 1504 | .is_some_and(|stamp| stamp == name) |
| 1505 | } |
| 1506 | |
| 1507 | /// The lines `project_open` lists for the dated autosaves beside `path`: each one's file name, |
| 1508 | /// local time and what it differs by from the open project. Empty when there are none. |
| 1509 | fn older_autosave_lines(path: &Path, open: &PlaybackSession) -> Vec<String> { |
| 1510 | let found = dated_autosaves(path); |
| 1511 | if found.is_empty() { |
| 1512 | return Vec::new(); |
| 1513 | } |
| 1514 | let text = std::fs::read_to_string(path).unwrap_or_default(); |
| 1515 | let mut lines = vec![format!( |
| 1516 | "older autosaves ({}; recover one with project_open {{path:\"{}\", recover:\"<name or stamp>\"}}):", |
| 1517 | found.len(), |
| 1518 | path.display() |
| 1519 | )]; |
| 1520 | for (t, p) in &found { |
| 1521 | let name = p.file_name().map_or_else(String::new, |n| n.to_string_lossy().into_owned()); |
| 1522 | let diff = describe_autosave(open, &text, p); |
| 1523 | // The name carries the set-aside stamp (what recover accepts); the time is when the edits were made. |
| 1524 | lines.push(format!(" {name} (edits from {}: {diff})", local_text(*t))); |
| 1525 | } |
| 1526 | lines |
| 1527 | } |
| 1528 | |
| 1529 | /// What an autosave's edits change against `against` (a session, with the project file's text |
| 1530 | /// for the settings), in the words the warnings use. |
| 1531 | fn describe_autosave(against: &PlaybackSession, against_text: &str, auto: &Path) -> String { |
| 1532 | let auto_text = std::fs::read_to_string(auto).unwrap_or_default(); |
| 1533 | let settings = settings_differences(against_text, &auto_text); |
| 1534 | match PlaybackSession::open_project(auto) { |
| 1535 | Ok(saved) => autosave_summary(against, &saved, &settings), |
| 1536 | Err(e) => format!("could not be read: {e}"), |
| 1537 | } |
| 1538 | } |
| 1539 | |
| 1540 | /// Where the autosave of the project at `path` goes: the same folder, named |
| 1541 | /// `<name>.autosave.edith`. Never the project's own file, so an autosave cannot |
| 1542 | /// overwrite the work it is protecting. |
| 1543 | pub fn autosave_path(path: &Path) -> PathBuf { |
| 1544 | let stem = path.file_stem().map_or_else(|| "untitled".to_string(), |s| s.to_string_lossy().into_owned()); |
| 1545 | path.with_file_name(format!("{stem}.autosave.edith")) |
| 1546 | } |
| 1547 | |
| 1548 | /// Where an autosave of a project that was never given a path goes: the editor's |
| 1549 | /// own cache, one file per process so two runs do not share one. |
| 1550 | fn untitled_autosave_path() -> Option<PathBuf> { |
| 1551 | let home = std::env::var_os("HOME")?; |
| 1552 | let dir = PathBuf::from(home).join(".cache").join("edith").join("autosave"); |
| 1553 | let stamp = std::time::SystemTime::now() |
| 1554 | .duration_since(std::time::UNIX_EPOCH) |
| 1555 | .map_or(0, |d| d.as_secs()); |
| 1556 | Some(dir.join(format!("untitled-{}-{stamp}.autosave.edith", std::process::id()))) |
| 1557 | } |
| 1558 | |
| 1559 | /// The session's whole project as the engine writes it, the `playhead` line left out. It is |
| 1560 | /// written through a scratch file in the cache folder, so nothing lands beside the project. |
| 1561 | fn session_body(session: &PlaybackSession) -> Option<Vec<u8>> { |
| 1562 | // One scratch file per call: calls in one process (parallel test threads, or a |
| 1563 | // session checked while another is written) must not write and read the same file. |
| 1564 | static NEXT_BODY: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); |
| 1565 | let dir = scratch_dir()?; |
| 1566 | std::fs::create_dir_all(&dir).ok()?; |
| 1567 | let n = NEXT_BODY.fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 1568 | let tmp = dir.join(format!("body-{}-{n}.edith", std::process::id())); |
| 1569 | let bytes = session.save_project(&tmp).ok().and_then(|()| std::fs::read(&tmp).ok()); |
| 1570 | let _ = std::fs::remove_file(&tmp); |
| 1571 | bytes.map(|b| b.split(|&c| c == b'\n').filter(|l| !l.starts_with(b"playhead ")).collect::<Vec<_>>().join(&b'\n')) |
| 1572 | } |
| 1573 | |
| 1574 | /// The folder for the editor's own scratch files, under the user's cache. |
| 1575 | fn scratch_dir() -> Option<PathBuf> { |
| 1576 | let home = std::env::var_os("HOME")?; |
| 1577 | Some(PathBuf::from(home).join(".cache").join("edith").join("autosave")) |
| 1578 | } |
| 1579 | |
| 1580 | /// The lines of a project file the playhead line does not make. |
| 1581 | fn body_lines(text: &str) -> Vec<&str> { |
| 1582 | text.lines().filter(|l| !l.starts_with("playhead ")).collect() |
| 1583 | } |
| 1584 | |
| 1585 | /// `a` without the lines of `b`, counting each line as many times as it appears. |
| 1586 | fn minus<'a>(a: &[&'a str], b: &[&str]) -> Vec<&'a str> { |
| 1587 | let mut left: HashMap<&str, usize> = HashMap::new(); |
| 1588 | for l in b { |
| 1589 | *left.entry(l).or_default() += 1; |
| 1590 | } |
| 1591 | a.iter() |
| 1592 | .filter(|l| match left.get_mut(**l) { |
| 1593 | Some(n) if *n > 0 => { |
| 1594 | *n -= 1; |
| 1595 | false |
| 1596 | } |
| 1597 | _ => true, |
| 1598 | }) |
| 1599 | .copied() |
| 1600 | .collect() |
| 1601 | } |
| 1602 | |
| 1603 | /// A clip line's fields that the settings diff reads: `video <lane> <start> ... eq color ... transform`. |
| 1604 | struct ClipLine<'a> { |
| 1605 | lane: String, |
| 1606 | start: &'a str, |
| 1607 | eq: &'a str, |
| 1608 | color: &'a str, |
| 1609 | transform: &'a str, |
| 1610 | line: &'a str, |
| 1611 | } |
| 1612 | |
| 1613 | fn clip_lines<'a>(lines: &[&'a str]) -> Vec<ClipLine<'a>> { |
| 1614 | lines |
| 1615 | .iter() |
| 1616 | .filter_map(|&l| { |
| 1617 | let t: Vec<&str> = l.split(' ').collect(); |
| 1618 | (matches!(t.first(), Some(&"video" | &"audio")) && t.len() >= 15).then(|| ClipLine { |
| 1619 | lane: format!("{}{}", if t[0] == "video" { "V" } else { "A" }, t[1]), |
| 1620 | start: t[2], |
| 1621 | eq: t[7], |
| 1622 | color: t[8], |
| 1623 | transform: t[14], |
| 1624 | line: l, |
| 1625 | }) |
| 1626 | }) |
| 1627 | .collect() |
| 1628 | } |
| 1629 | |
| 1630 | /// What differs between the file as opened and the autosave beside it, read from the two |
| 1631 | /// texts: lane gains and flags, the colour, eq and transform of named clips, and the |
| 1632 | /// project's own settings. Clip counts and sources are the caller's business. |
| 1633 | fn settings_differences(file: &str, auto: &str) -> Vec<String> { |
| 1634 | let (f, a) = (body_lines(file), body_lines(auto)); |
| 1635 | let (only_auto, only_file) = (minus(&a, &f), minus(&f, &a)); |
| 1636 | let mut out: Vec<String> = Vec::new(); |
| 1637 | let mut add = |s: String| { |
| 1638 | if !out.contains(&s) { |
| 1639 | out.push(s); |
| 1640 | } |
| 1641 | }; |
| 1642 | let (fc, ac) = (clip_lines(&f), clip_lines(&a)); |
| 1643 | // A clip whose line changed: which of its colour, eq or transform moved, else the clip itself. |
| 1644 | for c in ac.iter().filter(|c| only_auto.contains(&c.line)) { |
| 1645 | let Some(old) = fc.iter().find(|o| o.lane == c.lane && o.start == c.start) else { |
| 1646 | continue; |
| 1647 | }; |
| 1648 | let mut named = false; |
| 1649 | for (kind, now, was) in [("eq", c.eq, old.eq), ("color", c.color, old.color), ("transform", c.transform, old.transform)] { |
| 1650 | if now != was { |
| 1651 | add(format!("{kind} on {}@{}", c.lane, c.start)); |
| 1652 | named = true; |
| 1653 | } |
| 1654 | } |
| 1655 | if !named { |
| 1656 | add(format!("clip {}@{} changed", c.lane, c.start)); |
| 1657 | } |
| 1658 | } |
| 1659 | // The colour, eq and transform tables: a changed entry is the clips that point at it. |
| 1660 | for (kind, field) in [("eq", 7), ("color", 8), ("transform", 14)] { |
| 1661 | let entries: Vec<(usize, &str)> = a.iter().filter(|l| l.split(' ').next() == Some(kind)).copied().enumerate().collect(); |
| 1662 | for (i, entry) in entries { |
| 1663 | if !only_auto.contains(&entry) { |
| 1664 | continue; |
| 1665 | } |
| 1666 | let users: Vec<String> = ac |
| 1667 | .iter() |
| 1668 | .filter(|c| { |
| 1669 | let v = match field { |
| 1670 | 7 => c.eq, |
| 1671 | 8 => c.color, |
| 1672 | _ => c.transform, |
| 1673 | }; |
| 1674 | v == i.to_string() |
| 1675 | }) |
| 1676 | .map(|c| format!("{}@{}", c.lane, c.start)) |
| 1677 | .collect(); |
| 1678 | if users.is_empty() { |
| 1679 | add(format!("{kind} table entry changed")); |
| 1680 | } else { |
| 1681 | for u in users.iter().take(3) { |
| 1682 | add(format!("{kind} on {u}")); |
| 1683 | } |
| 1684 | if users.len() > 3 { |
| 1685 | add(format!("{kind} on {} more clips", users.len() - 3)); |
| 1686 | } |
| 1687 | } |
| 1688 | } |
| 1689 | } |
| 1690 | for l in &only_auto { |
| 1691 | let t: Vec<&str> = l.split(' ').collect(); |
| 1692 | let described = match t[0] { |
| 1693 | "gain" if t.len() >= 4 => format!("lane {}{} gain {} dB", lane_letter(t[1]), t[2], db_text(t[3])), |
| 1694 | "flags" if t.len() >= 4 => format!("lane {}{} {}", lane_letter(t[1]), t[2], t[3..].join(" ")), |
| 1695 | "tonemap" | "proxy" | "autoproxy" | "encoder" => format!("{} {}", t[0], t.get(1).unwrap_or(&"")), |
| 1696 | "resolution" if t.len() >= 3 => format!("resolution {}x{}", t[1], t[2]), |
| 1697 | "fps" | "samplerate" => format!("{} {}", t[0], t.get(1).unwrap_or(&"")), |
| 1698 | "limiter" => format!("limiter {}", t[1..].join(" ")), |
| 1699 | "sub" | "subtitle" | "cue" | "source" | "video" | "audio" | "eq" | "color" | "transform" => continue, |
| 1700 | other => format!("{other} changed"), |
| 1701 | }; |
| 1702 | add(described); |
| 1703 | } |
| 1704 | // A gain or flag line the file had and the autosave drops is a setting put back. |
| 1705 | for l in &only_file { |
| 1706 | let t: Vec<&str> = l.split(' ').collect(); |
| 1707 | let lane = |t: &[&str]| format!("{}{}", lane_letter(t[1]), t[2]); |
| 1708 | if t[0] == "gain" && t.len() >= 4 && !only_auto.iter().any(|x| x.starts_with("gain ") && x.split(' ').nth(2) == Some(t[2]) && x.split(' ').nth(1) == Some(t[1])) { |
| 1709 | add(format!("lane {} gain reset", lane(&t))); |
| 1710 | } else if t[0] == "flags" && t.len() >= 4 && !only_auto.iter().any(|x| x.starts_with("flags ") && x.split(' ').nth(2) == Some(t[2]) && x.split(' ').nth(1) == Some(t[1])) { |
| 1711 | add(format!("lane {} flags cleared", lane(&t))); |
| 1712 | } |
| 1713 | } |
| 1714 | out |
| 1715 | } |
| 1716 | |
| 1717 | /// A dB figure as a person writes it: `-6` for `-6.0`, `-1.5` as it is. |
| 1718 | fn db_text(raw: &str) -> String { |
| 1719 | match raw.parse::<f64>() { |
| 1720 | Ok(v) if v.fract() == 0.0 => format!("{v:.0}"), |
| 1721 | _ => raw.to_string(), |
| 1722 | } |
| 1723 | } |
| 1724 | |
| 1725 | fn lane_letter(kind: &str) -> &'static str { |
| 1726 | match kind { |
| 1727 | "video" => "V", |
| 1728 | "audio" => "A", |
| 1729 | _ => "S", |
| 1730 | } |
| 1731 | } |
| 1732 | |
| 1733 | /// Whether two project files say the same thing. The `playhead` line is where the view |
| 1734 | /// rests, not an edit, so it is left out of the comparison. |
| 1735 | fn same_project(a: &Path, b: &Path) -> bool { |
| 1736 | let (Ok(x), Ok(y)) = (std::fs::read(a), std::fs::read(b)) else { |
| 1737 | return false; |
| 1738 | }; |
| 1739 | let body = |d: &[u8]| d.split(|&c| c == b'\n').filter(|l| !l.starts_with(b"playhead ")).map(<[u8]>::to_vec).collect::<Vec<_>>(); |
| 1740 | body(&x) == body(&y) |
| 1741 | } |
| 1742 | |
| 1743 | /// At stdin EOF: a dirty project is written beside its file (or to the cache, if it |
| 1744 | /// has none), so the work a client walked away from survives the server. Nothing is |
| 1745 | /// written when the session says what the autosave or the file already says, so a |
| 1746 | /// read-only run leaves no trace. Logged to stderr. Returns the path written, if any. |
| 1747 | /// A write that fails is logged as FAILED with its reason: the edits it held are then |
| 1748 | /// not on disk anywhere. |
| 1749 | pub fn autosave_at_eof(server: &Server) -> Option<PathBuf> { |
| 1750 | match write_autosave(server) { |
| 1751 | Ok(path) => path, |
| 1752 | Err(why) => { |
| 1753 | eprintln!("autosave FAILED: {why}; this session's unsaved edits are NOT on disk"); |
| 1754 | None |
| 1755 | } |
| 1756 | } |
| 1757 | } |
| 1758 | |
| 1759 | /// The write behind `autosave_at_eof`; also used when a discard keeps the edits it drops. |
| 1760 | /// `Err` carries the reason the write failed. |
| 1761 | fn write_autosave(server: &Server) -> Result<Option<PathBuf>, String> { |
| 1762 | if !dirty(server) { |
| 1763 | return Ok(None); |
| 1764 | } |
| 1765 | let Some(session) = server.session.as_ref() else { |
| 1766 | return Ok(None); |
| 1767 | }; |
| 1768 | if session.sources().is_empty() { |
| 1769 | return Ok(None); |
| 1770 | } |
| 1771 | // A session that made no edit writes nothing: whatever it opened (a load fix, a relink, a |
| 1772 | // recovered autosave) is still on disk where it was, and the reply already said so. |
| 1773 | if !edited_this_session(server, session) { |
| 1774 | return Ok(None); |
| 1775 | } |
| 1776 | // The whole project, not its clips: a session that says what the file as opened (or saved) |
| 1777 | // says has nothing unsaved. A library row no clip plays from is not in the file's words, |
| 1778 | // so the source count is checked as well. |
| 1779 | if let Some(base) = &server.saved_body |
| 1780 | && server.saved_sources == Some(session.sources().len()) |
| 1781 | && session_body(session).is_some_and(|b| b == *base) |
| 1782 | { |
| 1783 | return Ok(None); |
| 1784 | } |
| 1785 | // A media file opened as a project has no project file of its own: its autosave never goes |
| 1786 | // beside the file it came from, and nothing is written until an edit moves it off the open. |
| 1787 | let beside = server.path.as_deref().filter(|_| server.media_open.is_none()); |
| 1788 | if let Some(base) = server.media_open |
| 1789 | && (session.undo_depth(), session.history_pushes(), session.sources().len()) == base |
| 1790 | { |
| 1791 | return Ok(None); |
| 1792 | } |
| 1793 | let auto = match beside { |
| 1794 | Some(p) => autosave_path(p), |
| 1795 | None => untitled_autosave_path().ok_or("no home folder for an autosave")?, |
| 1796 | }; |
| 1797 | let dir = auto.parent().ok_or_else(|| format!("no folder for {}", auto.display()))?; |
| 1798 | if std::fs::create_dir_all(dir).is_err() { |
| 1799 | return Err(format!("cannot create the folder {}", dir.display())); |
| 1800 | } |
| 1801 | // Written beside the autosave first, then compared: the bytes say whether anything changed. |
| 1802 | let check = auto.with_extension("check.edith"); |
| 1803 | // The autosave write never refuses a project the engine would refuse to save (a clip past |
| 1804 | // its source, say); the only refusal left is a project that names no file at all. |
| 1805 | if let Err(e) = session.save_autosave(&check) { |
| 1806 | let _ = std::fs::remove_file(&check); |
| 1807 | return Err(format!("the engine would not write {} ({e})", auto.display())); |
| 1808 | } |
| 1809 | let same_as_autosave = auto.is_file() && same_project(&check, &auto); |
| 1810 | let same_as_file = server.path.as_deref().is_some_and(|p| p.is_file() && same_project(&check, p)); |
| 1811 | if same_as_autosave || same_as_file { |
| 1812 | let _ = std::fs::remove_file(&check); |
| 1813 | return Ok(None); |
| 1814 | } |
| 1815 | // An autosave this session did not recover is never overwritten: whatever it holds was |
| 1816 | // written by an earlier run (or another client) and was not loaded here, so it is moved to |
| 1817 | // a dated name first. A recovered autosave is this session's own and is replaced in place. |
| 1818 | // One dated copy per collision, not a fresh copy of the same unrecovered file on every run. |
| 1819 | let mut moved_aside = None; |
| 1820 | if let Some(p) = beside.filter(|_| auto.is_file() && server.recovered_autosave.as_deref() != Some(auto.as_path())) { |
| 1821 | let (kept, pruned) = match set_aside_dated(&auto, p) { |
| 1822 | Ok(done) => done, |
| 1823 | Err(e) => { |
| 1824 | let _ = std::fs::remove_file(&check); |
| 1825 | return Err(format!("could not move the older autosave {} aside ({e})", auto.display())); |
| 1826 | } |
| 1827 | }; |
| 1828 | eprintln!("autosave: an earlier session's autosave was kept as {}", kept.display()); |
| 1829 | if let Some(note) = pruned_note(&pruned) { |
| 1830 | eprintln!("autosave: {note}"); |
| 1831 | } |
| 1832 | moved_aside = Some(kept); |
| 1833 | } |
| 1834 | match std::fs::rename(&check, &auto) { |
| 1835 | Ok(()) => { |
| 1836 | // This session's own write: an earlier session's autosave is named as moved, not as written. |
| 1837 | match moved_aside { |
| 1838 | Some(kept) => eprintln!("autosave: this session's unsaved changes written to {} (the earlier autosave is {})", auto.display(), kept.display()), |
| 1839 | None => eprintln!("autosave: unsaved changes written to {}", auto.display()), |
| 1840 | } |
| 1841 | Ok(Some(auto)) |
| 1842 | } |
| 1843 | Err(e) => { |
| 1844 | let _ = std::fs::remove_file(&check); |
| 1845 | Err(format!("could not move the autosave into place at {} ({e})", auto.display())) |
| 1846 | } |
| 1847 | } |
| 1848 | } |
| 1849 | |
| 1850 | /// The note for a project path with no file of its own that has an autosave beside it: |
| 1851 | /// the project was never saved, and the autosave is the only copy of its work. |
| 1852 | fn unsaved_autosave_note(path: &Path) -> Option<String> { |
| 1853 | let auto = autosave_path(path); |
| 1854 | auto.is_file().then(|| { |
| 1855 | let when = mtime(&auto).map_or_else(|| "at an unknown time".to_string(), ago); |
| 1856 | format!( |
| 1857 | "the project was never saved; unsaved changes from the last session are in its autosave {} (written {when}): project_open {{\"path\": \"{}\", \"recover\": true}} to load them", |
| 1858 | auto.display(), |
| 1859 | path.display() |
| 1860 | ) |
| 1861 | }) |
| 1862 | } |
| 1863 | |
| 1864 | /// The two ways out of an unrecovered autosave while this session has the project open: keep |
| 1865 | /// this session's edits (the autosave is set aside as a dated copy), or load the autosave and |
| 1866 | /// drop this session's edits. Both are named, so neither refusal points back at the other alone. |
| 1867 | fn unrecovered_choices(path: &Path) -> String { |
| 1868 | let p = path.display(); |
| 1869 | format!( |
| 1870 | "project_save {{discard_autosave:true}} keeps THIS session's edits and sets the earlier autosave aside as a dated copy (the newest 3 dated copies and any from the last 7 days are kept; older ones are deleted). project_open {{\"path\": \"{p}\", \"recover\": true, \"discard\": true}} loads the earlier autosave and drops THIS session's unsaved edits." |
| 1871 | ) |
| 1872 | } |
| 1873 | |
| 1874 | /// The reply when a project file will not open. An unsupported version names the versions this |
| 1875 | /// build reads; the way out is the autosave or the dated copies beside the file, or else its |
| 1876 | /// checkpoints, each named with the call that restores it. |
| 1877 | fn open_failure(path: &Path, engine_error: &str) -> String { |
| 1878 | let mut why = engine_error.to_string(); |
| 1879 | if why.contains("unsupported version") { |
| 1880 | why.push_str(&format!("; this edith reads project versions up to {}", engine::edith::NEWEST_VERSION)); |
| 1881 | } |
| 1882 | let p = path.display(); |
| 1883 | let mut outs = Vec::new(); |
| 1884 | if autosave_path(path).is_file() { |
| 1885 | outs.push(format!("the autosave {} (project_open {{\"path\": \"{p}\", \"recover\": true}})", autosave_path(path).display())); |
| 1886 | } |
| 1887 | let dated: Vec<String> = dated_autosaves(path) |
| 1888 | .iter() |
| 1889 | .filter_map(|(_, d)| d.file_name().map(|n| n.to_string_lossy().into_owned())) |
| 1890 | .collect(); |
| 1891 | if !dated.is_empty() { |
| 1892 | outs.push(format!("the dated autosaves {} (project_open {{\"path\": \"{p}\", \"recover\": \"<name>\"}})", dated.join(", "))); |
| 1893 | } |
| 1894 | if outs.is_empty() { |
| 1895 | let cps = checkpoints_beside(path); |
| 1896 | if !cps.is_empty() { |
| 1897 | outs.push(format!("the checkpoints {} (restore {{\"name\": \"<name>\"}} after opening a project that opens)", cps.join(", "))); |
| 1898 | } |
| 1899 | } |
| 1900 | let way_out = if outs.is_empty() { |
| 1901 | "no autosave, dated copy or checkpoint was found beside it".to_string() |
| 1902 | } else { |
| 1903 | format!("the way out is {}", outs.join("; or ")) |
| 1904 | }; |
| 1905 | format!("could not open {p}: {why}; {way_out}") |
| 1906 | } |
| 1907 | |
| 1908 | /// The checkpoint names (`<name>.edith`) saved for the project at `path`, in |
| 1909 | /// `<project dir>/checkpoints/<stem>/`, sorted. Empty when there are none. |
| 1910 | fn checkpoints_beside(path: &Path) -> Vec<String> { |
| 1911 | let Some(stem) = path.file_stem().map(|s| s.to_string_lossy().into_owned()) else { |
| 1912 | return Vec::new(); |
| 1913 | }; |
| 1914 | let dir = path.parent().unwrap_or(Path::new(".")).join("checkpoints").join(stem); |
| 1915 | let Ok(entries) = std::fs::read_dir(dir) else { |
| 1916 | return Vec::new(); |
| 1917 | }; |
| 1918 | let mut names: Vec<String> = entries |
| 1919 | .filter_map(Result::ok) |
| 1920 | .filter_map(|e| e.file_name().to_str().and_then(|n| n.strip_suffix(".edith")).map(str::to_string)) |
| 1921 | .collect(); |
| 1922 | names.sort(); |
| 1923 | names |
| 1924 | } |
| 1925 | |
| 1926 | /// The reply when a save cannot write its file. A permission refusal says which folder to pick. |
| 1927 | fn write_failure(target: &Path, engine_error: &str) -> String { |
| 1928 | if engine_error.contains("ermission denied") { |
| 1929 | return format!("cannot write {}: permission denied; choose a folder you can write to", target.display()); |
| 1930 | } |
| 1931 | format!("save failed: could not write {} ({engine_error})", target.display()) |
| 1932 | } |
| 1933 | |
| 1934 | /// The reason a named refusal (an unsupported rotation or display size) gives for a recognised media |
| 1935 | /// file. A file the demuxer cannot parse at all, such as plain text, has no such reason: None. |
| 1936 | fn named_media_refusal(path: &Path) -> Option<String> { |
| 1937 | if engine::is_audio(path) || engine::is_image(path) { |
| 1938 | return None; |
| 1939 | } |
| 1940 | let e = engine::demux::Demuxer::open(path).err()?; |
| 1941 | let named = engine::demux::UnsupportedRotation::is_it(&e) || engine::demux::UnsupportedDisplaySize::is_it(&e); |
| 1942 | named.then(|| e.to_string()) |
| 1943 | } |
| 1944 | |
| 1945 | /// Whether project_open can start a project from `path`: a picture, a sound, or a |
| 1946 | /// file whose header gives a picture or a playing time. Anything else is refused by name. |
| 1947 | fn is_media(path: &Path) -> bool { |
| 1948 | if engine::is_audio(path) || engine::is_image(path) { |
| 1949 | return true; |
| 1950 | } |
| 1951 | let facts = engine::probe_media(path); |
| 1952 | facts.video.is_some() || facts.duration_secs.is_some() |
| 1953 | } |
| 1954 | |
| 1955 | /// How long a span is, in the largest whole unit: `12 s`, `5 min`, `3 h`, `2 d`. |
| 1956 | fn span(d: Duration) -> String { |
| 1957 | let s = d.as_secs(); |
| 1958 | match s { |
| 1959 | 0..=119 => format!("{s} s"), |
| 1960 | 120..=7199 => format!("{} min", s / 60), |
| 1961 | 7200..=172_799 => format!("{} h", s / 3600), |
| 1962 | _ => format!("{} d", s / 86_400), |
| 1963 | } |
| 1964 | } |
| 1965 | |
| 1966 | /// `5 min ago` for a time in the past. |
| 1967 | fn ago(t: SystemTime) -> String { |
| 1968 | match SystemTime::now().duration_since(t) { |
| 1969 | Ok(d) => format!("{} ago", span(d)), |
| 1970 | Err(_) => "in the future".to_string(), |
| 1971 | } |
| 1972 | } |
| 1973 | |
| 1974 | /// The refusal `project_open` gives for an autosave beside the project that holds an earlier |
| 1975 | /// session's unsaved edits, unless the person chose: `recover` continues from it, and |
| 1976 | /// `discard_autosave` opens the saved file and sets the autosave aside. None when there is |
| 1977 | /// nothing to choose about (no autosave, or a stale one that is removed without a word). |
| 1978 | fn unloaded_autosave_refusal(project: &Path, file: &PlaybackSession, discard_autosave: bool) -> Option<String> { |
| 1979 | let auto = unloaded_autosave(project)?; |
| 1980 | if discard_autosave { |
| 1981 | return None; |
| 1982 | } |
| 1983 | let when = mtime(&auto).map_or_else(|| "an unknown time".to_string(), local_text); |
| 1984 | let disk = std::fs::read_to_string(project).unwrap_or_default(); |
| 1985 | let summary = describe_autosave(file, &disk, &auto); |
| 1986 | Some(format!( |
| 1987 | "{} has an autosave from {when} (an earlier session's unsaved edits: {summary}). Open with recover:true to continue from it, or discard_autosave:true to open the saved file and set the autosave aside (dated copy). Nothing was loaded.", |
| 1988 | project.display() |
| 1989 | )) |
| 1990 | } |
| 1991 | |
| 1992 | /// The autosave beside `project` that holds edits the project file does not: newer than it, and |
| 1993 | /// not the same project. A project file that is missing counts as older than any autosave. |
| 1994 | fn unloaded_autosave(project: &Path) -> Option<PathBuf> { |
| 1995 | let auto = autosave_path(project); |
| 1996 | if !auto.is_file() { |
| 1997 | return None; |
| 1998 | } |
| 1999 | let newer = match (mtime(&auto), mtime(project)) { |
| 2000 | (Some(a), Some(f)) => a > f, |
| 2001 | (Some(_), None) => true, |
| 2002 | _ => false, |
| 2003 | }; |
| 2004 | (newer && !same_project(&auto, project)).then_some(auto) |
| 2005 | } |
| 2006 | |
| 2007 | /// Settles the autosave beside `project` once an open is going ahead. An unloaded one is set |
| 2008 | /// aside as a dated copy when the person said `discard_autosave` (its edits are not loaded, and |
| 2009 | /// they stay on disk until that copy is deleted); without it the open was refused before this. |
| 2010 | /// A stale one (same as the file, or older) is removed. `Err` when the set-aside fails. |
| 2011 | fn settle_autosave_on_open(project: &Path, discard_autosave: bool) -> Result<Option<String>, String> { |
| 2012 | let auto = autosave_path(project); |
| 2013 | if !auto.is_file() { |
| 2014 | return Ok(None); |
| 2015 | } |
| 2016 | if unloaded_autosave(project).is_none() { |
| 2017 | let _ = std::fs::remove_file(&auto); |
| 2018 | return Ok(None); |
| 2019 | } |
| 2020 | if !discard_autosave { |
| 2021 | return Ok(None); |
| 2022 | } |
| 2023 | match set_aside_dated(&auto, project) { |
| 2024 | Ok((kept, pruned)) => { |
| 2025 | let mut note = format!( |
| 2026 | "set the autosave aside as {} (its unsaved edits are not loaded; the copy is kept (the newest 3 dated copies and any from the last 7 days are kept; older ones are deleted))", |
| 2027 | kept.display() |
| 2028 | ); |
| 2029 | if let Some(extra) = pruned_note(&pruned) { |
| 2030 | note.push_str(&format!("\n{extra}")); |
| 2031 | } |
| 2032 | Ok(Some(note)) |
| 2033 | } |
| 2034 | Err(e) => Err(format!("could not set the autosave {} aside ({e}), so nothing was opened", auto.display())), |
| 2035 | } |
| 2036 | } |
| 2037 | |
| 2038 | /// Clip, cue and lane counts by lane name. |
| 2039 | fn lane_counts(s: &PlaybackSession) -> BTreeMap<String, usize> { |
| 2040 | s.lanes() |
| 2041 | .into_iter() |
| 2042 | .map(|l| { |
| 2043 | let n = match l.kind { |
| 2044 | LaneKind::Subtitle => s.sub_lane_cues(l).len(), |
| 2045 | _ => s.lane_clips(l).len(), |
| 2046 | }; |
| 2047 | (parse::lane_name(l), n) |
| 2048 | }) |
| 2049 | .collect() |
| 2050 | } |
| 2051 | |
| 2052 | /// What the autosave's edits change against the file, in a few words: `+3 clips on A2`, |
| 2053 | /// `new lane A3 with 2 clips`, `+1 source(s)`, `length 00:05.000 -> 00:09.000`. |
| 2054 | fn autosave_summary(file: &PlaybackSession, auto: &PlaybackSession, settings: &[String]) -> String { |
| 2055 | let (before, after) = (lane_counts(file), lane_counts(auto)); |
| 2056 | let mut parts: Vec<String> = Vec::new(); |
| 2057 | for (name, &n) in &after { |
| 2058 | let unit = if name.starts_with('S') { "cue(s)" } else { "clip(s)" }; |
| 2059 | match before.get(name) { |
| 2060 | None => parts.push(format!("new lane {name} with {n} {unit}")), |
| 2061 | Some(&b) if b != n => parts.push(format!("{:+} {unit} on {name}", n as i64 - b as i64)), |
| 2062 | Some(_) => {} |
| 2063 | } |
| 2064 | } |
| 2065 | for name in before.keys().filter(|k| !after.contains_key(*k)) { |
| 2066 | parts.push(format!("lane {name} removed")); |
| 2067 | } |
| 2068 | // Sources: a changed path is named by its index and both file names; an added or removed |
| 2069 | // source is named by its file. Kept apart from the content parts, so an import-only change |
| 2070 | // can say that no clip, lane or setting changed. |
| 2071 | let name = |p: &Path| p.file_name().map_or_else(|| p.display().to_string(), |n| n.to_string_lossy().into_owned()); |
| 2072 | let (fsrc, asrc) = (file.sources(), auto.sources()); |
| 2073 | let mut src_parts: Vec<String> = Vec::new(); |
| 2074 | for (i, (f, a)) in fsrc.iter().zip(asrc.iter()).enumerate() { |
| 2075 | if f.path != a.path { |
| 2076 | src_parts.push(format!("src:{i} {} -> {}", name(&f.path), name(&a.path))); |
| 2077 | } |
| 2078 | } |
| 2079 | let (sb, sa) = (fsrc.len(), asrc.len()); |
| 2080 | if sa > sb { |
| 2081 | let added: Vec<String> = asrc[sb..].iter().enumerate().map(|(k, s)| format!("src:{} {}", sb + k, name(&s.path))).collect(); |
| 2082 | src_parts.push(format!("+{} source(s): {}", sa - sb, added.join(", "))); |
| 2083 | } else if sb > sa { |
| 2084 | let gone: Vec<String> = fsrc[sa..].iter().enumerate().map(|(k, s)| format!("src:{} {}", sa + k, name(&s.path))).collect(); |
| 2085 | src_parts.push(format!("{} source(s) removed: {}", sb - sa, gone.join(", "))); |
| 2086 | } |
| 2087 | let (eb, ea) = (parse::session_end(file), parse::session_end(auto)); |
| 2088 | if eb != ea { |
| 2089 | let fps = parse::session_fps(auto); |
| 2090 | parts.push(format!("length {} -> {}", parse::clock(eb, fps), parse::clock(ea, fps))); |
| 2091 | } |
| 2092 | parts.extend(settings.iter().cloned()); |
| 2093 | if parts.is_empty() && src_parts.is_empty() { |
| 2094 | "no clip, lane, setting or source differs".to_string() |
| 2095 | } else if parts.is_empty() { |
| 2096 | format!("{} (no clip, lane or setting changed)", src_parts.join(", ")) |
| 2097 | } else { |
| 2098 | parts.extend(src_parts); |
| 2099 | parts.join(", ") |
| 2100 | } |
| 2101 | } |
| 2102 | |
| 2103 | /// The caption style as `project_status` reports it. |
| 2104 | fn caption_json(cs: engine::captionanim::CaptionStyle) -> Value { |
| 2105 | json!({ |
| 2106 | "animation": cs.anim.name(), |
| 2107 | "highlight": format!("#{:02x}{:02x}{:02x}", cs.highlight[0], cs.highlight[1], cs.highlight[2]), |
| 2108 | "box": cs.hl_box, |
| 2109 | "uppercase": cs.uppercase, |
| 2110 | "words_per_line": cs.words_per_line, |
| 2111 | }) |
| 2112 | } |
| 2113 | |
| 2114 | fn project_status(server: &mut Server, args: &Value) -> Reply { |
| 2115 | if opt_bool(args, "history") != Some(true) { |
| 2116 | return status_reply(server); |
| 2117 | } |
| 2118 | // Trimmed first, as undo trims before it reads the ledger, so the list is the one undo would use. |
| 2119 | server.trim_ledger(); |
| 2120 | let reply = status_reply(server); |
| 2121 | history_reply(server, reply) |
| 2122 | } |
| 2123 | |
| 2124 | /// Adds every undo and redo label to a status reply, each with the `steps` count that reaches it. |
| 2125 | fn history_reply(server: &Server, reply: Reply) -> Reply { |
| 2126 | let undo: Vec<(usize, String)> = server.ledger.iter().rev().enumerate().map(|(i, e)| (i + 1, e.label.clone())).collect(); |
| 2127 | let redo: Vec<(usize, String)> = server.redo_ledger.iter().rev().enumerate().map(|(i, e)| (i + 1, e.label.clone())).collect(); |
| 2128 | let mut text = reply.text.clone(); |
| 2129 | text.push_str("\nundo history, newest first (undo {steps: N} takes back the N newest):"); |
| 2130 | if undo.is_empty() { |
| 2131 | text.push_str("\n (none)"); |
| 2132 | } |
| 2133 | for (n, label) in &undo { |
| 2134 | text.push_str(&format!("\n {n}: {label}")); |
| 2135 | } |
| 2136 | text.push_str("\nredo history, next first (redo {steps: N} brings back the N next):"); |
| 2137 | if redo.is_empty() { |
| 2138 | text.push_str("\n (none)"); |
| 2139 | } |
| 2140 | for (n, label) in &redo { |
| 2141 | text.push_str(&format!("\n {n}: {label}")); |
| 2142 | } |
| 2143 | let undo_json: Vec<Value> = undo.iter().map(|(n, label)| json!({"steps": n, "label": label})).collect(); |
| 2144 | let redo_json: Vec<Value> = redo.iter().map(|(n, label)| json!({"steps": n, "label": label})).collect(); |
| 2145 | let mut structured = reply.structured.as_deref().cloned().unwrap_or_else(|| json!({})); |
| 2146 | if let Some(obj) = structured.as_object_mut() { |
| 2147 | obj.insert("undo_history".into(), Value::Array(undo_json)); |
| 2148 | obj.insert("redo_history".into(), Value::Array(redo_json)); |
| 2149 | } |
| 2150 | Reply { text, structured: Some(Box::new(structured)), is_error: reply.is_error, images: reply.images } |
| 2151 | } |
| 2152 | |
| 2153 | fn status_reply(server: &Server) -> Reply { |
| 2154 | let s = tri!(server.session_ref()); |
| 2155 | let fps = parse::session_fps(s); |
| 2156 | let (w, h) = s.resolution(); |
| 2157 | let end = parse::session_end(s); |
| 2158 | // Not "saved" while a newer autosave of unrecovered edits sits beside the file: what is |
| 2159 | // open is the file on disk, which is older than those edits. |
| 2160 | let state = if dirty(server) { |
| 2161 | "dirty" |
| 2162 | } else if server.unrecovered_autosave { |
| 2163 | "on disk, older than the autosave" |
| 2164 | } else { |
| 2165 | "saved" |
| 2166 | }; |
| 2167 | let path = server |
| 2168 | .path |
| 2169 | .as_ref() |
| 2170 | .map_or_else(|| "(unsaved)".to_string(), |p| p.display().to_string()); |
| 2171 | let undo = server.ledger.len(); |
| 2172 | let redo = server.redo_ledger.len(); |
| 2173 | // The newest five undo steps, newest first, so a status read says where the edit history stands. |
| 2174 | let recent_steps: Vec<String> = server.ledger.iter().rev().take(5).map(|e| e.label.clone()).collect(); |
| 2175 | let recent_text = match recent_steps.is_empty() { |
| 2176 | true => String::new(), |
| 2177 | false => format!("last steps: {}\n", recent_steps.join(" · ")), |
| 2178 | }; |
| 2179 | let running = server.jobs.iter().filter(|j| j.outcome.is_none()).count(); |
| 2180 | |
| 2181 | let lanes: Vec<(String, usize)> = s |
| 2182 | .lanes() |
| 2183 | .into_iter() |
| 2184 | .map(|l| { |
| 2185 | let n = match l.kind { |
| 2186 | LaneKind::Subtitle => s.sub_lane_cues(l).len(), |
| 2187 | _ => s.lane_clips(l).len(), |
| 2188 | }; |
| 2189 | (parse::lane_name(l), n) |
| 2190 | }) |
| 2191 | .collect(); |
| 2192 | let lane_text = if lanes.is_empty() { |
| 2193 | "no lanes".to_string() |
| 2194 | } else { |
| 2195 | lanes |
| 2196 | .iter() |
| 2197 | .map(|(name, n)| { |
| 2198 | if name.starts_with('S') { |
| 2199 | format!("{name} {n} cue(s)") |
| 2200 | } else { |
| 2201 | format!("{name} {n} clip(s)") |
| 2202 | } |
| 2203 | }) |
| 2204 | .collect::<Vec<_>>() |
| 2205 | .join(" · ") |
| 2206 | }; |
| 2207 | |
| 2208 | // Every duck on an audio lane: the lane it dips, the key lane it listens to, and its depth. |
| 2209 | let ducks: Vec<(String, engine::duck::Duck)> = s |
| 2210 | .lanes() |
| 2211 | .into_iter() |
| 2212 | .filter(|l| l.kind == LaneKind::Audio) |
| 2213 | .flat_map(|l| s.lane_duck_list(l).into_iter().map(move |d| (parse::lane_name(l), d))) |
| 2214 | .collect(); |
| 2215 | let duck_key = |d: &engine::duck::Duck| parse::lane_name(Lane::new(LaneKind::Audio, d.under)); |
| 2216 | let ducks_text = if ducks.is_empty() { |
| 2217 | String::new() |
| 2218 | } else { |
| 2219 | format!( |
| 2220 | "\nducks: {}", |
| 2221 | ducks |
| 2222 | .iter() |
| 2223 | .map(|(lane, d)| format!("{lane} under {} {}dB", duck_key(d), d.depth_db)) |
| 2224 | .collect::<Vec<_>>() |
| 2225 | .join(" · ") |
| 2226 | ) |
| 2227 | }; |
| 2228 | |
| 2229 | // Every audio lane with voice processors on, and which. |
| 2230 | let voiced: Vec<String> = s |
| 2231 | .lanes() |
| 2232 | .into_iter() |
| 2233 | .filter(|l| l.kind == LaneKind::Audio) |
| 2234 | .filter_map(|l| { |
| 2235 | let v = s.lane_voice(l); |
| 2236 | v.is_active().then(|| format!("{} {}", parse::lane_name(l), v.summary())) |
| 2237 | }) |
| 2238 | .collect(); |
| 2239 | let voice_text = if voiced.is_empty() { String::new() } else { format!("\nvoice: {}", voiced.join(" · ")) }; |
| 2240 | |
| 2241 | let sources = s.sources(); |
| 2242 | let source_names: Vec<String> = sources |
| 2243 | .iter() |
| 2244 | .enumerate() |
| 2245 | .map(|(i, src)| { |
| 2246 | let name = src |
| 2247 | .path |
| 2248 | .file_name() |
| 2249 | .map_or_else(|| src.path.display().to_string(), |n| n.to_string_lossy().into_owned()); |
| 2250 | format!("src:{i} {name}") |
| 2251 | }) |
| 2252 | .collect(); |
| 2253 | |
| 2254 | let limiter = s.limiter(); |
| 2255 | let sample_rate = match s.sample_rate() { |
| 2256 | Some(r) => format!("{r} Hz"), |
| 2257 | None => "derived from the sources: the highest rate among them, 48 kHz when all are below 44.1 kHz".to_string(), |
| 2258 | }; |
| 2259 | let limiter_text = if limiter.on { |
| 2260 | format!("on at {:.1} dBTP true peak", limiter.ceiling_db) |
| 2261 | } else { |
| 2262 | "off".to_string() |
| 2263 | }; |
| 2264 | let tone = s.tone().name(); |
| 2265 | let encoder = s.encoder_seat().name(); |
| 2266 | // The colour looks the look op takes by name: the built-in ones and the saved ones, A to Z. |
| 2267 | let builtin_looks: Vec<&str> = engine::looks::builtins().iter().map(|(n, _)| *n).collect(); |
| 2268 | let saved_looks = engine::looks::saved_names(); |
| 2269 | let looks_text = format!( |
| 2270 | "\nlooks: built-in {} · saved {}", |
| 2271 | builtin_looks.join(", "), |
| 2272 | if saved_looks.is_empty() { "none".to_string() } else { saved_looks.join(", ") } |
| 2273 | ); |
| 2274 | |
| 2275 | // Each offline source is named on its own line, with the fix; a clip on it is still on the timeline. |
| 2276 | let offline = s.offline_sources(); |
| 2277 | let offline_text: String = offline |
| 2278 | .iter() |
| 2279 | .map(|(i, p)| format!("\nOFFLINE: src:{i} {} (relink with media_relink)", p.display())) |
| 2280 | .collect(); |
| 2281 | // A LUT a clip names that cannot be read: the clip plays without it until it is relinked. |
| 2282 | let luts = s.lut_problems(); |
| 2283 | let offline_text: String = offline_text + &lut_lines(&luts).iter().map(|l| format!("\n{l}")).collect::<String>(); |
| 2284 | // What the open clamped to load: the file on disk still has it, so the project reads unsaved. |
| 2285 | let fix_text = if server.load_fixes.is_empty() { |
| 2286 | String::new() |
| 2287 | } else { |
| 2288 | format!( |
| 2289 | "\nunsaved: the open fixed {} thing(s) to load ({}); project_save writes the fix", |
| 2290 | server.load_fixes.len(), |
| 2291 | server.load_fixes.join("; ") |
| 2292 | ) |
| 2293 | }; |
| 2294 | // The notes, in full, after the settings, when there are any. |
| 2295 | let notes_text = match s.notes().is_empty() { |
| 2296 | true => String::new(), |
| 2297 | false => format!("\nnotes: {}", s.notes()), |
| 2298 | }; |
| 2299 | let render_text = crate::tools::render::status_line(server).map_or_else(String::new, |l| format!("\n{l}")); |
| 2300 | let speech_text = format!("{} on {}", s.speech_model().unwrap_or("auto"), s.speech_device().as_str()); |
| 2301 | let text = format!( |
| 2302 | "{path} · {state} · {w}x{h} @{} · {} ({end}f) · undo {undo} · redo {redo} · {running} export job(s) running\n\ |
| 2303 | lanes: {lane_text}{ducks_text}{voice_text}\n\ |
| 2304 | {recent_text}sources: {} {}{looks_text}\n\ |
| 2305 | settings: tonemap {tone} · proxies {} · auto proxies {} · encoder {encoder} · limiter {limiter_text} · sample rate {sample_rate} · still {:.1} s · speech {speech_text}{offline_text}{fix_text}{notes_text}{render_text}", |
| 2306 | fmt_fps(fps), |
| 2307 | parse::clock(end, fps), |
| 2308 | sources.len(), |
| 2309 | if source_names.is_empty() { String::new() } else { format!("({})", source_names.join(", ")) }, |
| 2310 | on_off(s.proxies()), |
| 2311 | on_off(s.auto_proxies()), |
| 2312 | s.still_secs(), |
| 2313 | ); |
| 2314 | |
| 2315 | let unrecovered = server |
| 2316 | .path |
| 2317 | .as_deref() |
| 2318 | .filter(|_| server.unrecovered_autosave) |
| 2319 | .map(|p| autosave_path(p).display().to_string()); |
| 2320 | let structured = json!({ |
| 2321 | "path": server.path.as_ref().map(|p| p.display().to_string()), |
| 2322 | "saved": !dirty(server), |
| 2323 | "dirty": dirty(server), |
| 2324 | "resolution": {"width": w, "height": h}, |
| 2325 | "fps": fps, |
| 2326 | "duration_frames": end, |
| 2327 | "duration_secs": parse::secs(end, fps), |
| 2328 | "lanes": lanes.iter().map(|(name, n)| json!({"lane": name, "count": n})).collect::<Vec<_>>(), |
| 2329 | "ducks": ducks.iter().map(|(lane, d)| json!({ |
| 2330 | "lane": lane, |
| 2331 | "under": duck_key(d), |
| 2332 | "depth_db": d.depth_db, |
| 2333 | "threshold_db": d.threshold_db, |
| 2334 | })).collect::<Vec<_>>(), |
| 2335 | "sources": sources.len(), |
| 2336 | "offline": offline.iter().map(|(i, p)| json!({"src": i, "path": p.display().to_string()})).collect::<Vec<_>>(), |
| 2337 | "lut_problems": luts.iter().map(|(p, e)| json!({"path": p.display().to_string(), "problem": e})).collect::<Vec<_>>(), |
| 2338 | "load_fixes": server.load_fixes, |
| 2339 | "undo_steps": undo, |
| 2340 | "redo_steps": redo, |
| 2341 | "recent_steps": recent_steps, |
| 2342 | "jobs_running": running, |
| 2343 | "looks": {"builtin": builtin_looks, "saved": saved_looks}, |
| 2344 | "unrecovered_autosave": unrecovered, |
| 2345 | "settings": { |
| 2346 | "captions": caption_json(s.caption_style()), |
| 2347 | "tonemap": tone, |
| 2348 | "proxies": s.proxies(), |
| 2349 | "auto_proxies": s.auto_proxies(), |
| 2350 | "encoder": encoder, |
| 2351 | "limiter": {"on": limiter.on, "ceiling_db": limiter.ceiling_db}, |
| 2352 | "sample_rate": s.sample_rate(), |
| 2353 | "still_secs": s.still_secs(), |
| 2354 | "speech_model": s.speech_model(), |
| 2355 | "speech_device": s.speech_device().as_str(), |
| 2356 | "notes": s.notes(), |
| 2357 | } |
| 2358 | }); |
| 2359 | Reply::ok(text).with(structured) |
| 2360 | } |
| 2361 | |
| 2362 | fn on_off(on: bool) -> &'static str { |
| 2363 | if on { "on" } else { "off" } |
| 2364 | } |
| 2365 | |
| 2366 | /// `sample_rate`: "source" for no pick (`None`), or one of the rates the GUI offers |
| 2367 | /// (`engine::playback::SAMPLE_RATES`), as a number or a numeric string. |
| 2368 | fn parse_sample_rate(v: &Value) -> Result<Option<u32>, String> { |
| 2369 | let offered = || engine::playback::SAMPLE_RATES.iter().map(|r| r.to_string()).collect::<Vec<_>>().join(", "); |
| 2370 | match v { |
| 2371 | Value::String(word) if word == "source" => Ok(None), |
| 2372 | Value::Number(n) => match n.as_u64().and_then(|r| u32::try_from(r).ok()) { |
| 2373 | Some(r) if engine::playback::SAMPLE_RATES.contains(&r) => Ok(Some(r)), |
| 2374 | _ => Err(format!("use source, {}", offered())), |
| 2375 | }, |
| 2376 | Value::String(word) => match word.parse::<u32>() { |
| 2377 | Ok(r) if engine::playback::SAMPLE_RATES.contains(&r) => Ok(Some(r)), |
| 2378 | _ => Err(format!("`{word}` is not a rate; use source, {}", offered())), |
| 2379 | }, |
| 2380 | _ => Err(format!("use source, {}", offered())), |
| 2381 | } |
| 2382 | } |
| 2383 | |
| 2384 | pub(crate) fn project_settings(server: &mut Server, args: &Value) -> Reply { |
| 2385 | let before = tri!(server.session_ref()).history_pushes(); |
| 2386 | let force = opt_bool(args, "force").unwrap_or(false); |
| 2387 | let mut lines: Vec<String> = Vec::new(); |
| 2388 | let mut changed = 0usize; |
| 2389 | let mut refused = 0usize; |
| 2390 | let mut asked = 0usize; |
| 2391 | // What each change was, for the ledger label: `project_settings fps 30→5`. |
| 2392 | let mut named: Vec<String> = Vec::new(); |
| 2393 | { |
| 2394 | let s = tri!(server.session()); |
| 2395 | |
| 2396 | if let Some(raw) = opt_str(args, "resolution") { |
| 2397 | asked += 1; |
| 2398 | match parse_resolution(raw) { |
| 2399 | Err(r) => { |
| 2400 | refused += 1; |
| 2401 | lines.push(format!("resolution: refused ({})", r.text)); |
| 2402 | } |
| 2403 | Ok((w, h)) => { |
| 2404 | let (cw, ch) = s.resolution(); |
| 2405 | if (cw, ch) == (w, h) { |
| 2406 | lines.push(format!("resolution already {w}x{h}")); |
| 2407 | } else if s.set_resolution(w, h) { |
| 2408 | changed += 1; |
| 2409 | named.push(format!("resolution {cw}x{ch}→{w}x{h}")); |
| 2410 | lines.push(format!( |
| 2411 | "resolution {cw}x{ch} -> {w}x{h}: clips keep their fit mode and refit to the new canvas; transforms are canvas fractions, so their positions scale with it; titles keep their placement (top, bottom or centre) and their size is a share of the frame height" |
| 2412 | )); |
| 2413 | } else { |
| 2414 | refused += 1; |
| 2415 | lines.push(format!("resolution {w}x{h}: refused by the engine")); |
| 2416 | } |
| 2417 | } |
| 2418 | } |
| 2419 | } |
| 2420 | |
| 2421 | match fps_arg(args) { |
| 2422 | Err(r) => { |
| 2423 | asked += 1; |
| 2424 | refused += 1; |
| 2425 | lines.push(format!("fps: refused ({})", r.text)); |
| 2426 | } |
| 2427 | Ok(None) => {} |
| 2428 | Ok(Some(f)) => { |
| 2429 | asked += 1; |
| 2430 | let cur = s.meta().frame_rate; |
| 2431 | let edges_before = clip_edges(s); |
| 2432 | let locked_before = locked_starts(s); |
| 2433 | let locked = locked_lanes_moved(s, cur, f); |
| 2434 | let locked_list = locked.iter().map(|(name, n)| format!("{name} ({n} {})", if *n == 1 { "clip edge" } else { "clip edges" })).collect::<Vec<_>>().join(", "); |
| 2435 | if (cur - f).abs() < 1e-9 { |
| 2436 | lines.push(format!("fps already {}", fmt_fps(f))); |
| 2437 | } else if !locked.is_empty() && !force { |
| 2438 | refused += 1; |
| 2439 | lines.push(format!( |
| 2440 | "fps {} -> {}: refused: locked lane {locked_list} would have clips moved by the retime. Unlock the lane first (edit lane_flags {{lane, locked:false}}), or pass force:true to move them anyway", |
| 2441 | fmt_fps(cur), |
| 2442 | fmt_fps(f) |
| 2443 | )); |
| 2444 | } else if s.set_frame_rate(f) { |
| 2445 | changed += 1; |
| 2446 | named.push(format!("fps {}→{}", fmt_fps(cur), fmt_fps(f))); |
| 2447 | lines.push(format!("fps {} -> {}", fmt_fps(cur), fmt_fps(f))); |
| 2448 | if !locked.is_empty() { |
| 2449 | lines.push(format!("warning: force:true moved the clips of locked lane {locked_list}")); |
| 2450 | } |
| 2451 | // A locked lane whose times stay put still takes new frame numbers: say which. |
| 2452 | let moved_names: Vec<String> = locked.iter().map(|(name, _)| name.clone()).collect(); |
| 2453 | if let Some(note) = locked_address_note(&locked_before, &locked_starts(s), &moved_names) { |
| 2454 | lines.push(note); |
| 2455 | } |
| 2456 | // A rate that is not a whole multiple of the old one puts some edges between |
| 2457 | // frames; the retime rounds each to the nearest frame, and says how many moved. |
| 2458 | let moved = moved_edges(&edges_before, &clip_edges(s), cur, f); |
| 2459 | if moved > 0 { |
| 2460 | lines.push(format!( |
| 2461 | "warning: {moved} clip {} moved to the nearest frame at {} fps; undo restores them. An fps change is not reversible by changing back: setting {} again does not restore the exact frames, only undo does", |
| 2462 | if moved == 1 { "edge" } else { "edges" }, |
| 2463 | fmt_fps(f), |
| 2464 | fmt_fps(cur) |
| 2465 | )); |
| 2466 | } |
| 2467 | } else { |
| 2468 | refused += 1; |
| 2469 | lines.push(if s.rate_locked() { |
| 2470 | format!("fps {}: refused: the project has several sequences or a compound clip, which are made at one frame rate; keep {} fps", fmt_fps(f), fmt_fps(cur)) |
| 2471 | } else { |
| 2472 | format!("fps {}: refused by the engine", fmt_fps(f)) |
| 2473 | }); |
| 2474 | } |
| 2475 | } |
| 2476 | } |
| 2477 | |
| 2478 | if let Some(raw) = opt_str(args, "tonemap") { |
| 2479 | asked += 1; |
| 2480 | match Preset::from_name(raw.as_bytes()) { |
| 2481 | None => { |
| 2482 | refused += 1; |
| 2483 | lines.push(format!("tonemap `{raw}`: refused; use reference, standard or vivid")); |
| 2484 | } |
| 2485 | Some(p) => { |
| 2486 | let cur = s.tone(); |
| 2487 | if cur == p { |
| 2488 | lines.push(format!("tonemap already {}", p.name())); |
| 2489 | } else if s.set_tone(p) { |
| 2490 | changed += 1; |
| 2491 | named.push(format!("tonemap {}→{}", cur.name(), p.name())); |
| 2492 | lines.push(format!("tonemap {} -> {}", cur.name(), p.name())); |
| 2493 | } else { |
| 2494 | refused += 1; |
| 2495 | lines.push(format!("tonemap {}: refused by the engine", p.name())); |
| 2496 | } |
| 2497 | } |
| 2498 | } |
| 2499 | } |
| 2500 | |
| 2501 | if let Some(raw) = opt_str(args, "notes") { |
| 2502 | asked += 1; |
| 2503 | if s.set_notes(raw) { |
| 2504 | changed += 1; |
| 2505 | named.push("notes".to_string()); |
| 2506 | lines.push(match raw.is_empty() { |
| 2507 | true => "notes cleared".to_string(), |
| 2508 | false => format!("notes set ({} characters)", raw.chars().count()), |
| 2509 | }); |
| 2510 | } else { |
| 2511 | lines.push("notes already set to that".to_string()); |
| 2512 | } |
| 2513 | } |
| 2514 | |
| 2515 | if let Some(raw) = opt_str(args, "speech_model") { |
| 2516 | asked += 1; |
| 2517 | let v = raw.trim().to_ascii_lowercase(); |
| 2518 | if v != "auto" && !MODELS.contains(&v.as_str()) { |
| 2519 | refused += 1; |
| 2520 | lines.push(format!("speech_model {raw}: refused; use one of {}, or auto", MODELS.join(", "))); |
| 2521 | } else { |
| 2522 | let cur = s.speech_model().unwrap_or("auto").to_string(); |
| 2523 | let want = (v != "auto").then_some(v.as_str()); |
| 2524 | if s.set_speech_model(want) { |
| 2525 | changed += 1; |
| 2526 | named.push(format!("speech_model {cur}→{v}")); |
| 2527 | lines.push(format!("speech model {cur} -> {v}")); |
| 2528 | } else { |
| 2529 | lines.push(format!("speech model already {cur}")); |
| 2530 | } |
| 2531 | } |
| 2532 | } |
| 2533 | |
| 2534 | if let Some(raw) = opt_str(args, "speech_device") { |
| 2535 | asked += 1; |
| 2536 | match DeviceChoice::parse(raw.trim()) { |
| 2537 | Some(d) => { |
| 2538 | let cur = s.speech_device(); |
| 2539 | if s.set_speech_device(d) { |
| 2540 | changed += 1; |
| 2541 | named.push(format!("speech_device {}→{}", cur.as_str(), d.as_str())); |
| 2542 | lines.push(format!("speech device {} -> {}", cur.as_str(), d.as_str())); |
| 2543 | } else { |
| 2544 | lines.push(format!("speech device already {}", d.as_str())); |
| 2545 | } |
| 2546 | } |
| 2547 | None => { |
| 2548 | refused += 1; |
| 2549 | lines.push(format!("speech_device {raw}: refused; use auto, cpu or gpu")); |
| 2550 | } |
| 2551 | } |
| 2552 | } |
| 2553 | |
| 2554 | if let Some(v) = args.get("still_secs") { |
| 2555 | asked += 1; |
| 2556 | match v.as_f64() { |
| 2557 | Some(secs) if (STILL_MIN_SECS..=STILL_MAX_SECS).contains(&secs) => { |
| 2558 | let cur = s.still_secs(); |
| 2559 | if s.set_still_secs(secs) { |
| 2560 | changed += 1; |
| 2561 | named.push(format!("still {cur:.1}s→{secs:.1}s")); |
| 2562 | lines.push(format!("still length {cur:.1} s -> {secs:.1} s")); |
| 2563 | } else { |
| 2564 | lines.push(format!("still length already {cur:.1} s")); |
| 2565 | } |
| 2566 | } |
| 2567 | _ => { |
| 2568 | refused += 1; |
| 2569 | lines.push(format!("still_secs {v}: refused; use a length from {STILL_MIN_SECS} to {STILL_MAX_SECS} seconds")); |
| 2570 | } |
| 2571 | } |
| 2572 | } |
| 2573 | |
| 2574 | for (key, get, set) in [ |
| 2575 | ("proxies", s.proxies(), true), |
| 2576 | ("auto_proxies", s.auto_proxies(), false), |
| 2577 | ] { |
| 2578 | if let Some(want) = opt_bool(args, key) { |
| 2579 | asked += 1; |
| 2580 | if want == get { |
| 2581 | lines.push(format!("{key} already {}", on_off(want))); |
| 2582 | } else { |
| 2583 | if set { |
| 2584 | s.set_proxies(want); |
| 2585 | } else { |
| 2586 | s.set_auto_proxies(want); |
| 2587 | } |
| 2588 | changed += 1; |
| 2589 | named.push(format!("{key} {}→{}", on_off(get), on_off(want))); |
| 2590 | lines.push(format!("{key} {} -> {}", on_off(get), on_off(want))); |
| 2591 | } |
| 2592 | } |
| 2593 | } |
| 2594 | |
| 2595 | if let Some(v) = args.get("sample_rate") { |
| 2596 | asked += 1; |
| 2597 | match parse_sample_rate(v) { |
| 2598 | Err(why) => { |
| 2599 | refused += 1; |
| 2600 | lines.push(format!("sample_rate: refused ({why})")); |
| 2601 | } |
| 2602 | Ok(want) => { |
| 2603 | let cur = s.sample_rate(); |
| 2604 | let label = |r: Option<u32>| r.map_or("source".to_string(), |r| format!("{r} Hz")); |
| 2605 | if cur == want { |
| 2606 | lines.push(format!("sample rate already {}", label(want))); |
| 2607 | } else { |
| 2608 | s.set_sample_rate(want); |
| 2609 | changed += 1; |
| 2610 | named.push(format!("sample rate {}→{}", label(cur), label(want))); |
| 2611 | lines.push(format!("sample rate {} -> {}", label(cur), label(want))); |
| 2612 | } |
| 2613 | } |
| 2614 | } |
| 2615 | } |
| 2616 | |
| 2617 | if let Some(raw) = opt_str(args, "encoder") { |
| 2618 | asked += 1; |
| 2619 | match EncoderSeat::from_name(raw.as_bytes()) { |
| 2620 | None => { |
| 2621 | refused += 1; |
| 2622 | lines.push(format!("encoder `{raw}`: refused; use auto, hardware or software")); |
| 2623 | } |
| 2624 | Some(seat) => { |
| 2625 | let cur = s.encoder_seat(); |
| 2626 | if cur == seat { |
| 2627 | lines.push(format!("encoder already {}", seat.name())); |
| 2628 | } else { |
| 2629 | s.set_encoder_seat(seat); |
| 2630 | changed += 1; |
| 2631 | named.push(format!("encoder {}→{}", cur.name(), seat.name())); |
| 2632 | lines.push(format!("encoder {} -> {}", cur.name(), seat.name())); |
| 2633 | } |
| 2634 | } |
| 2635 | } |
| 2636 | } |
| 2637 | |
| 2638 | if let Some(caps) = args.get("captions") { |
| 2639 | asked += 1; |
| 2640 | let cur = s.caption_style(); |
| 2641 | let want = match caps.as_object() { |
| 2642 | None => Err("give an object such as {\"animation\": \"karaoke\", \"words_per_line\": 3}".to_string()), |
| 2643 | Some(obj) => match obj.keys().find(|k| !["animation", "highlight", "box", "uppercase", "words_per_line"].contains(&k.as_str())) { |
| 2644 | Some(k) => Err(format!("unknown key `{k}`")), |
| 2645 | None => super::export::caption_from(obj, cur), |
| 2646 | }, |
| 2647 | }; |
| 2648 | match want { |
| 2649 | Err(msg) => { |
| 2650 | refused += 1; |
| 2651 | lines.push(format!("captions: refused ({msg})")); |
| 2652 | } |
| 2653 | Ok(want) if want.clamped() == cur => lines.push("captions already set so".into()), |
| 2654 | Ok(want) => { |
| 2655 | s.set_caption_style(want); |
| 2656 | changed += 1; |
| 2657 | named.push(format!("captions {}→{}", cur.anim.name(), want.anim.name())); |
| 2658 | lines.push(format!( |
| 2659 | "captions {} -> {} (highlight #{:02x}{:02x}{:02x}{}{}, {} words per line)", |
| 2660 | cur.anim.name(), |
| 2661 | want.anim.name(), |
| 2662 | want.highlight[0], |
| 2663 | want.highlight[1], |
| 2664 | want.highlight[2], |
| 2665 | if want.hl_box { ", box" } else { "" }, |
| 2666 | if want.uppercase { ", uppercase" } else { "" }, |
| 2667 | want.words_per_line |
| 2668 | )); |
| 2669 | } |
| 2670 | } |
| 2671 | } |
| 2672 | |
| 2673 | if let Some(lim) = args.get("limiter") { |
| 2674 | asked += 1; |
| 2675 | match lim.as_object() { |
| 2676 | None => { |
| 2677 | refused += 1; |
| 2678 | lines.push("limiter: refused; give an object such as {\"on\": true, \"ceiling_db\": -1.0}".into()); |
| 2679 | } |
| 2680 | Some(obj) => match limiter_from(obj, s.limiter()) { |
| 2681 | Err(msg) => { |
| 2682 | refused += 1; |
| 2683 | lines.push(format!("limiter: refused ({msg})")); |
| 2684 | } |
| 2685 | Ok(want) => { |
| 2686 | let cur = s.limiter(); |
| 2687 | if cur.on == want.on && cur.ceiling_db == want.ceiling_db { |
| 2688 | lines.push("limiter already set so".into()); |
| 2689 | } else if s.set_limiter(want) { |
| 2690 | changed += 1; |
| 2691 | named.push(format!("limiter {}→{}", on_off(cur.on), on_off(want.on))); |
| 2692 | lines.push(format!( |
| 2693 | "limiter {} at {:.1} -> {} at {:.1} dBTP", |
| 2694 | on_off(cur.on), |
| 2695 | cur.ceiling_db, |
| 2696 | on_off(want.on), |
| 2697 | want.ceiling_db |
| 2698 | )); |
| 2699 | } else { |
| 2700 | refused += 1; |
| 2701 | lines.push("limiter: refused by the engine".into()); |
| 2702 | } |
| 2703 | } |
| 2704 | }, |
| 2705 | } |
| 2706 | } |
| 2707 | } |
| 2708 | if named.is_empty() { |
| 2709 | note_pushes(server, before); |
| 2710 | } else { |
| 2711 | note_pushes_as(server, before, &format!("project_settings {}", named.join(", "))); |
| 2712 | } |
| 2713 | |
| 2714 | if asked == 0 { |
| 2715 | return Reply::err( |
| 2716 | "no setting given; pass one of resolution, fps, tonemap, notes, still_secs, speech_model, speech_device, proxies, auto_proxies, encoder, limiter, captions", |
| 2717 | ); |
| 2718 | } |
| 2719 | let mut out = Map::new(); |
| 2720 | out.insert("changed".into(), json!(changed)); |
| 2721 | out.insert("refused".into(), json!(refused)); |
| 2722 | let text = lines.join("\n"); |
| 2723 | let reply = if refused > 0 && changed == 0 { |
| 2724 | Reply::err(text) |
| 2725 | } else { |
| 2726 | Reply::ok(text) |
| 2727 | }; |
| 2728 | reply.with(Value::Object(out)) |
| 2729 | } |
| 2730 | |
| 2731 | /// Applies the `on` and `ceiling_db` keys over the current limiter. |
| 2732 | fn limiter_from(obj: &Map<String, Value>, cur: Limiter) -> Result<Limiter, String> { |
| 2733 | let on = match obj.get("on") { |
| 2734 | None | Some(Value::Null) => cur.on, |
| 2735 | Some(Value::Bool(b)) => *b, |
| 2736 | Some(_) => return Err("`on` must be true or false".into()), |
| 2737 | }; |
| 2738 | let ceiling_db = match obj.get("ceiling_db") { |
| 2739 | None | Some(Value::Null) => cur.ceiling_db, |
| 2740 | Some(v) => match v.as_f64() { |
| 2741 | Some(c) if c.is_finite() && (f64::from(Limiter::MIN_DB)..=f64::from(Limiter::MAX_DB)).contains(&c) => c as f32, |
| 2742 | _ => return Err("`ceiling_db` must be a number from -24 to 0 dBTP (a true-peak ceiling)".into()), |
| 2743 | }, |
| 2744 | }; |
| 2745 | Ok(Limiter { on, ceiling_db }) |
| 2746 | } |
| 2747 | |
| 2748 | #[cfg(test)] |
| 2749 | mod tests { |
| 2750 | use super::*; |
| 2751 | use crate::testutil::TestDir; |
| 2752 | use std::fs::File; |
| 2753 | use std::time::Duration; |
| 2754 | |
| 2755 | #[test] |
| 2756 | fn fps_and_resolution_are_range_checked() { |
| 2757 | assert!(fps_arg(&json!({"fps": 1000})).is_err()); |
| 2758 | assert!(fps_arg(&json!({"fps": 0.5})).is_err()); |
| 2759 | assert!(fps_arg(&json!({"fps": 240})).is_ok_and(|f| f == Some(240.0))); |
| 2760 | assert!(parse_resolution("1921x1080").is_err(), "odd width"); |
| 2761 | assert!(parse_resolution("8x8").is_err(), "below 16"); |
| 2762 | assert!(parse_resolution("16000x9000").is_err(), "above 8192"); |
| 2763 | assert!(parse_resolution("1920x1080").is_ok()); |
| 2764 | } |
| 2765 | |
| 2766 | #[test] |
| 2767 | fn dated_autosaves_are_found_newest_first_and_none_is_deleted() { |
| 2768 | let td = TestDir::new("dated-autosaves"); |
| 2769 | let project = td.path().join("p1.edith"); |
| 2770 | std::fs::write(&project, b"x").unwrap(); |
| 2771 | for (i, day) in [3u64, 1, 2].iter().enumerate() { |
| 2772 | let p = td.path().join(format!("p1.autosave-2026010{i}-120000.edith")); |
| 2773 | std::fs::write(&p, b"x").unwrap(); |
| 2774 | let t = SystemTime::UNIX_EPOCH + Duration::from_secs(1_767_225_600 + day * 86_400); |
| 2775 | std::fs::File::options().write(true).open(&p).unwrap().set_modified(t).unwrap(); |
| 2776 | } |
| 2777 | std::fs::write(td.path().join("p1.autosave.edith"), b"x").unwrap(); |
| 2778 | let found: Vec<String> = dated_autosaves(&project) |
| 2779 | .iter() |
| 2780 | .map(|(_, p)| p.file_name().unwrap().to_string_lossy().into_owned()) |
| 2781 | .collect(); |
| 2782 | assert_eq!( |
| 2783 | found, |
| 2784 | vec!["p1.autosave-20260100-120000.edith", "p1.autosave-20260102-120000.edith", "p1.autosave-20260101-120000.edith"], |
| 2785 | "newest first by modification time" |
| 2786 | ); |
| 2787 | assert!(td.path().join("p1.autosave.edith").is_file(), "the project's own autosave is not listed or touched"); |
| 2788 | assert_eq!(std::fs::read_dir(td.path()).unwrap().count(), 5, "nothing is deleted"); |
| 2789 | assert!(dated_autosaves(&td.path().join("nothere.edith")).is_empty()); |
| 2790 | } |
| 2791 | |
| 2792 | #[test] |
| 2793 | fn a_media_file_the_probe_refuses_says_why_it_cannot_open() { |
| 2794 | // A 45-degree display matrix: the probe refuses it, so project_open gives the probe's reason. |
| 2795 | let mut server = Server::new(); |
| 2796 | let path = asset("test_rotation45.mp4"); |
| 2797 | let r = project_open(&mut server, &json!({"path": path, "discard": true})); |
| 2798 | assert!(r.is_error, "{}", r.text); |
| 2799 | assert!(r.text.contains("test_rotation45.mp4 is media edith cannot open: "), "{}", r.text); |
| 2800 | assert!(r.text.contains("quarter turn"), "{}", r.text); |
| 2801 | assert!(!r.text.contains("is not an edith project or a media file"), "{}", r.text); |
| 2802 | assert!(server.session.is_none(), "a refused file opens nothing"); |
| 2803 | // A text file is not media, so it keeps the plain refusal, not the demuxer's parse error. |
| 2804 | let dir = TestDir::new("project-plain-text-refusal"); |
| 2805 | let notes = dir.join("notes.txt"); |
| 2806 | std::fs::write(¬es, b"plain text, not media").unwrap(); |
| 2807 | assert!(named_media_refusal(¬es).is_none()); |
| 2808 | } |
| 2809 | |
| 2810 | #[test] |
| 2811 | fn autosave_is_matched_by_file_name_or_stamp() { |
| 2812 | let p = Path::new("/x/p1.autosave-20261016-223636-2.edith"); |
| 2813 | assert!(autosave_matches(p, "p1.autosave-20261016-223636-2.edith")); |
| 2814 | assert!(autosave_matches(p, "20261016-223636-2")); |
| 2815 | assert!(!autosave_matches(p, "20261016-223636"), "a collision suffix is part of the stamp"); |
| 2816 | assert!(!autosave_matches(p, "p1.autosave.edith")); |
| 2817 | } |
| 2818 | |
| 2819 | fn asset(name: &str) -> PathBuf { |
| 2820 | Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets").join(name) |
| 2821 | } |
| 2822 | |
| 2823 | fn quiet() { |
| 2824 | engine::ao::set_silent_output(); |
| 2825 | } |
| 2826 | |
| 2827 | /// A project path that does not exist yet, unique per test. The guard owns the folder, |
| 2828 | /// so it is removed when the test ends, panic or not. |
| 2829 | fn scratch(test: &str) -> (TestDir, PathBuf) { |
| 2830 | let dir = TestDir::new(&format!("project-{test}")); |
| 2831 | let path = dir.join("proj.edith"); |
| 2832 | (dir, path) |
| 2833 | } |
| 2834 | |
| 2835 | fn call(f: fn(&mut Server, &Value) -> Reply, server: &mut Server, args: Value) -> Reply { |
| 2836 | f(server, &args) |
| 2837 | } |
| 2838 | |
| 2839 | fn import_av(server: &mut Server) { |
| 2840 | let before = server.session.as_ref().unwrap().history_pushes(); |
| 2841 | server |
| 2842 | .session |
| 2843 | .as_mut() |
| 2844 | .unwrap() |
| 2845 | .import(&asset("test_av.mp4")) |
| 2846 | .expect("import test asset"); |
| 2847 | note_pushes(server, before); |
| 2848 | } |
| 2849 | |
| 2850 | #[test] |
| 2851 | fn new_import_save_open_roundtrip() { |
| 2852 | quiet(); |
| 2853 | let (_dir, path) = scratch("roundtrip"); |
| 2854 | let mut server = Server::new(); |
| 2855 | let r = call(project_new, &mut server, json!({"path": path, "resolution": "1280x720"})); |
| 2856 | assert!(!r.is_error, "{}", r.text); |
| 2857 | assert!(!path.exists(), "new must not write the file"); |
| 2858 | assert!(dirty(&server)); |
| 2859 | |
| 2860 | import_av(&mut server); |
| 2861 | let r = call(project_save, &mut server, json!({})); |
| 2862 | assert!(!r.is_error, "{}", r.text); |
| 2863 | assert!(path.exists()); |
| 2864 | assert!(!dirty(&server)); |
| 2865 | |
| 2866 | let mut fresh = Server::new(); |
| 2867 | let r = call(project_open, &mut fresh, json!({"path": path})); |
| 2868 | assert!(!r.is_error, "{}", r.text); |
| 2869 | assert!(r.text.contains("1280x720"), "{}", r.text); |
| 2870 | assert_eq!(fresh.session.as_ref().unwrap().sources().len(), 1); |
| 2871 | assert!(!dirty(&fresh)); |
| 2872 | assert!(fresh.ledger.is_empty()); |
| 2873 | } |
| 2874 | |
| 2875 | #[test] |
| 2876 | fn open_media_file_names_project_beside_it() { |
| 2877 | quiet(); |
| 2878 | let mut server = Server::new(); |
| 2879 | let r = call(project_open, &mut server, json!({"path": asset("test_av.mp4")})); |
| 2880 | assert!(!r.is_error, "{}", r.text); |
| 2881 | assert_eq!(server.path.as_ref().unwrap().file_name().unwrap(), "test_av.edith"); |
| 2882 | assert!(!server.path.as_ref().unwrap().exists()); |
| 2883 | assert!(dirty(&server), "a media-started project is unsaved"); |
| 2884 | } |
| 2885 | |
| 2886 | #[test] |
| 2887 | fn dirty_project_refuses_open_unless_discard() { |
| 2888 | quiet(); |
| 2889 | let (_dir, path) = scratch("dirty"); |
| 2890 | let mut server = Server::new(); |
| 2891 | assert!(!call(project_new, &mut server, json!({"path": path})).is_error); |
| 2892 | import_av(&mut server); |
| 2893 | assert!(!call(project_save, &mut server, json!({})).is_error); |
| 2894 | |
| 2895 | // A settings change is an undo step, so the project is now dirty. |
| 2896 | let r = call(project_settings, &mut server, json!({"tonemap": "vivid"})); |
| 2897 | assert!(!r.is_error, "{}", r.text); |
| 2898 | assert_eq!(server.ledger.len(), 1); |
| 2899 | assert!(dirty(&server)); |
| 2900 | |
| 2901 | let other = asset("test_av.mp4"); |
| 2902 | let refused = call(project_open, &mut server, json!({"path": other})); |
| 2903 | assert!(refused.is_error); |
| 2904 | assert!(refused.text.contains("unsaved changes"), "{}", refused.text); |
| 2905 | assert_eq!(server.ledger.len(), 1, "a refusal changes nothing"); |
| 2906 | |
| 2907 | let ok = call(project_open, &mut server, json!({"path": other, "discard": true})); |
| 2908 | assert!(!ok.is_error, "{}", ok.text); |
| 2909 | assert!(server.ledger.is_empty()); |
| 2910 | } |
| 2911 | |
| 2912 | /// Undo back to the saved content is clean, redo away from it is dirty, and a new edit |
| 2913 | /// made after undoing past the save is dirty even though undo then reaches its depth. |
| 2914 | #[test] |
| 2915 | fn undo_back_to_the_saved_content_is_clean() { |
| 2916 | quiet(); |
| 2917 | let (_dir, path) = scratch("clean-undo"); |
| 2918 | let mut server = Server::new(); |
| 2919 | let run = |server: &mut Server, name: &str| { |
| 2920 | let t = crate::server::tools().into_iter().find(|t| t.name == name).expect("tool"); |
| 2921 | (t.run)(server, &json!({})) |
| 2922 | }; |
| 2923 | assert!(!call(project_new, &mut server, json!({"path": path})).is_error); |
| 2924 | import_av(&mut server); |
| 2925 | assert!(!call(project_settings, &mut server, json!({"tonemap": "vivid"})).is_error); |
| 2926 | assert!(!call(project_save, &mut server, json!({})).is_error); |
| 2927 | assert!(!dirty(&server)); |
| 2928 | |
| 2929 | assert!(!call(project_settings, &mut server, json!({"tonemap": "reference"})).is_error); |
| 2930 | assert!(dirty(&server)); |
| 2931 | assert!(!run(&mut server, "undo").is_error); |
| 2932 | assert!(!dirty(&server), "undo back to the save is clean: {}", status_reply(&server).text); |
| 2933 | assert!(!status_reply(&server).text.contains("dirty"), "{}", status_reply(&server).text); |
| 2934 | |
| 2935 | assert!(!run(&mut server, "redo").is_error); |
| 2936 | assert!(dirty(&server), "redo away from the save is dirty"); |
| 2937 | assert!(!run(&mut server, "undo").is_error); |
| 2938 | assert!(!dirty(&server), "redo then undo is clean again"); |
| 2939 | |
| 2940 | // Past the save, the saved entry is still reachable by undo; a new edit there drops it. |
| 2941 | assert!(!run(&mut server, "undo").is_error); |
| 2942 | assert!(dirty(&server), "undo past the save is dirty"); |
| 2943 | assert!(!call(project_settings, &mut server, json!({"tonemap": "standard"})).is_error); |
| 2944 | assert!(dirty(&server)); |
| 2945 | assert!(!run(&mut server, "undo").is_error); |
| 2946 | assert!(dirty(&server), "the saved content left the ledger with the new edit"); |
| 2947 | } |
| 2948 | |
| 2949 | /// `undo` blames the reopen only when the open dropped steps, and a new edit clears the blame. |
| 2950 | #[test] |
| 2951 | fn undo_names_the_reopen_only_when_the_open_dropped_steps() { |
| 2952 | quiet(); |
| 2953 | let (_dir, path) = scratch("undo-reopen"); |
| 2954 | let mut server = Server::new(); |
| 2955 | let run = |server: &mut Server, name: &str| { |
| 2956 | let t = crate::server::tools().into_iter().find(|t| t.name == name).expect("tool"); |
| 2957 | (t.run)(server, &json!({})) |
| 2958 | }; |
| 2959 | assert!(!call(project_new, &mut server, json!({"path": path})).is_error); |
| 2960 | import_av(&mut server); |
| 2961 | assert!(!call(project_settings, &mut server, json!({"tonemap": "reference"})).is_error); |
| 2962 | assert!(!call(project_save, &mut server, json!({})).is_error); |
| 2963 | // An edit after the save is a step the reopen will drop. |
| 2964 | assert!(!call(project_settings, &mut server, json!({"tonemap": "vivid"})).is_error); |
| 2965 | assert!(!call(project_open, &mut server, json!({"path": path, "discard": true})).is_error); |
| 2966 | assert!(server.ledger.is_empty()); |
| 2967 | let r = run(&mut server, "undo"); |
| 2968 | assert!(r.is_error && r.text.starts_with("nothing to undo yet (history does not survive project_open); "), "{}", r.text); |
| 2969 | |
| 2970 | // A new edit lands on the reopened project, so the next undo of it names no reopen. |
| 2971 | assert!(!call(project_settings, &mut server, json!({"tonemap": "standard"})).is_error); |
| 2972 | assert!(!server.history_lost_on_open, "a new edit clears the reopen note"); |
| 2973 | assert!(!run(&mut server, "undo").is_error); |
| 2974 | let r = run(&mut server, "undo"); |
| 2975 | assert!(r.is_error && !r.text.contains("project_open"), "{}", r.text); |
| 2976 | } |
| 2977 | |
| 2978 | #[test] |
| 2979 | fn save_with_no_project_open_says_so_and_how_to_start() { |
| 2980 | quiet(); |
| 2981 | let mut server = Server::new(); |
| 2982 | let r = call(project_save, &mut server, json!({})); |
| 2983 | assert!(r.is_error); |
| 2984 | assert!(r.text.contains("no project is open"), "{}", r.text); |
| 2985 | assert!(r.text.contains("project_new") && r.text.contains("project_open"), "{}", r.text); |
| 2986 | assert!(!r.text.contains("no project path"), "{}", r.text); |
| 2987 | } |
| 2988 | |
| 2989 | /// The notes and the still length through `project_settings`: each is one undo step, `project_status` |
| 2990 | /// shows the notes when there are any and the still length always, and a length out of range is refused. |
| 2991 | #[test] |
| 2992 | fn notes_and_still_length_go_through_project_settings() { |
| 2993 | quiet(); |
| 2994 | let (_dir, path) = scratch("notes_settings"); |
| 2995 | let mut server = Server::new(); |
| 2996 | assert!(!call(project_new, &mut server, json!({"path": path, "resolution": "1280x720"})).is_error); |
| 2997 | import_av(&mut server); |
| 2998 | |
| 2999 | let r = call(project_settings, &mut server, json!({"notes": "Line one\nLine two"})); |
| 3000 | assert!(!r.is_error, "{}", r.text); |
| 3001 | assert!(r.text.contains("notes set (17 characters)"), "{}", r.text); |
| 3002 | let status = call(project_status, &mut server, json!({})); |
| 3003 | assert!(status.text.contains("\nnotes: Line one\nLine two"), "{}", status.text); |
| 3004 | assert!(status.text.contains("still 5.0 s"), "{}", status.text); |
| 3005 | assert_eq!(status.structured.as_ref().unwrap()["settings"]["notes"], "Line one\nLine two"); |
| 3006 | |
| 3007 | let r = call(project_settings, &mut server, json!({"still_secs": 2.5})); |
| 3008 | assert!(!r.is_error, "{}", r.text); |
| 3009 | assert!(r.text.contains("still length 5.0 s -> 2.5 s"), "{}", r.text); |
| 3010 | assert!(call(project_status, &mut server, json!({})).text.contains("still 2.5 s")); |
| 3011 | |
| 3012 | // Out of range is refused, and nothing changes. |
| 3013 | let r = call(project_settings, &mut server, json!({"still_secs": 0.1})); |
| 3014 | assert!(r.is_error, "{}", r.text); |
| 3015 | assert!(r.text.contains("refused"), "{}", r.text); |
| 3016 | assert_eq!(server.session.as_ref().unwrap().still_secs(), 2.5); |
| 3017 | |
| 3018 | // Each change is an undo step. |
| 3019 | let session = server.session.as_mut().unwrap(); |
| 3020 | assert!(session.undo()); |
| 3021 | assert_eq!(session.still_secs(), 5.0); |
| 3022 | assert!(session.undo()); |
| 3023 | assert_eq!(session.notes(), ""); |
| 3024 | |
| 3025 | // Clearing the notes says so, and project_status stops showing them. |
| 3026 | assert!(!call(project_settings, &mut server, json!({"notes": "x"})).is_error); |
| 3027 | let r = call(project_settings, &mut server, json!({"notes": ""})); |
| 3028 | assert!(r.text.contains("notes cleared"), "{}", r.text); |
| 3029 | assert!(!call(project_status, &mut server, json!({})).text.contains("notes:")); |
| 3030 | } |
| 3031 | |
| 3032 | #[test] |
| 3033 | fn save_refuses_when_file_changed_on_disk() { |
| 3034 | quiet(); |
| 3035 | let (_dir, path) = scratch("conflict"); |
| 3036 | let mut server = Server::new(); |
| 3037 | assert!(!call(project_new, &mut server, json!({"path": path})).is_error); |
| 3038 | import_av(&mut server); |
| 3039 | assert!(!call(project_save, &mut server, json!({})).is_error); |
| 3040 | |
| 3041 | // Pretend the GUI wrote the file after we loaded it. |
| 3042 | let later = SystemTime::now() + Duration::from_secs(3600); |
| 3043 | File::options().write(true).open(&path).unwrap().set_modified(later).unwrap(); |
| 3044 | |
| 3045 | // Change the project so there is something to save. |
| 3046 | assert!(!call(project_settings, &mut server, json!({"fps": 25})).is_error); |
| 3047 | let refused = call(project_save, &mut server, json!({})); |
| 3048 | assert!(refused.is_error); |
| 3049 | assert!(refused.text.contains("changed on disk"), "{}", refused.text); |
| 3050 | |
| 3051 | let forced = call(project_save, &mut server, json!({"force": true})); |
| 3052 | assert!(!forced.is_error, "{}", forced.text); |
| 3053 | assert!(!dirty(&server)); |
| 3054 | } |
| 3055 | |
| 3056 | #[test] |
| 3057 | fn new_refuses_existing_path_and_status_reports_lanes() { |
| 3058 | quiet(); |
| 3059 | let (_dir, path) = scratch("exists"); |
| 3060 | std::fs::write(&path, b"x").unwrap(); |
| 3061 | let mut server = Server::new(); |
| 3062 | let r = call(project_new, &mut server, json!({"path": path})); |
| 3063 | assert!(r.is_error); |
| 3064 | assert!(r.text.contains("project_open"), "{}", r.text); |
| 3065 | |
| 3066 | let (_fresh_dir, fresh) = scratch("status"); |
| 3067 | let mut s = Server::new(); |
| 3068 | assert!(!call(project_new, &mut s, json!({"path": fresh})).is_error); |
| 3069 | import_av(&mut s); |
| 3070 | let st = call(project_status, &mut s, json!({})); |
| 3071 | assert!(!st.is_error); |
| 3072 | assert!(st.text.contains("V1"), "{}", st.text); |
| 3073 | assert_eq!(st.structured.as_ref().unwrap()["sources"], json!(1)); |
| 3074 | } |
| 3075 | |
| 3076 | #[test] |
| 3077 | fn settings_report_refusals_and_bad_input() { |
| 3078 | quiet(); |
| 3079 | let mut server = Server::new(); |
| 3080 | let (_dir, settings) = scratch("settings"); |
| 3081 | assert!(!call(project_new, &mut server, json!({"path": settings})).is_error); |
| 3082 | let bad_res = call(project_settings, &mut server, json!({"resolution": "wide"})); |
| 3083 | assert!(bad_res.is_error); |
| 3084 | let bad_tone = call(project_settings, &mut server, json!({"tonemap": "neon"})); |
| 3085 | assert!(bad_tone.is_error); |
| 3086 | assert!(bad_tone.text.contains("refused"), "{}", bad_tone.text); |
| 3087 | let none = call(project_settings, &mut server, json!({})); |
| 3088 | assert!(none.is_error); |
| 3089 | assert!(server.ledger.is_empty(), "refused settings push no undo step"); |
| 3090 | let lim = call(project_settings, &mut server, json!({"limiter": {"on": true, "ceiling_db": -1.5}})); |
| 3091 | assert!(!lim.is_error, "{}", lim.text); |
| 3092 | assert_eq!(server.ledger.len(), 1); |
| 3093 | } |
| 3094 | |
| 3095 | /// An fps change that puts a clip edge between frames says how many moved and that undo restores |
| 3096 | /// them, and its ledger step names the setting. An edge on a frame the new rate keeps does not count. |
| 3097 | #[test] |
| 3098 | fn an_fps_change_that_rounds_clip_edges_warns_and_names_the_step() { |
| 3099 | quiet(); |
| 3100 | let by_name = |server: &mut Server, name: &str, args: Value| { |
| 3101 | let t = crate::server::tools().into_iter().find(|t| t.name == name).expect("tool"); |
| 3102 | (t.run)(server, &args) |
| 3103 | }; |
| 3104 | let mut server = Server::new(); |
| 3105 | let (_dir, path) = scratch("fps-edges"); |
| 3106 | assert!(!call(project_new, &mut server, json!({"path": path})).is_error); |
| 3107 | let imported = by_name(&mut server, "media_import", json!({"paths": [asset("test_av.mp4").display().to_string()]})); |
| 3108 | assert!(!imported.is_error, "{}", imported.text); |
| 3109 | let cut = by_name(&mut server, "edit", json!({"ops": [{"op": "keep", "source": "src:0", "ranges": [["0s", "1.1s"]], "lane": "V1"}]})); |
| 3110 | assert!(!cut.is_error, "{}", cut.text); |
| 3111 | |
| 3112 | let fps = by_name(&mut server, "project_settings", json!({"fps": 5})); |
| 3113 | assert!(!fps.is_error, "{}", fps.text); |
| 3114 | assert!(fps.text.contains("clip edge") && fps.text.contains("moved to the nearest frame at 5 fps; undo restores them"), "{}", fps.text); |
| 3115 | assert!(fps.text.contains("not reversible by changing back"), "{}", fps.text); |
| 3116 | assert_eq!(server.ledger.last().map(|e| e.label.as_str()), Some("project_settings fps 30→5")); |
| 3117 | } |
| 3118 | |
| 3119 | /// Two frame numbers compare as the seconds they name at each rate: a frame kept by the new rate is |
| 3120 | /// not a move, and one landing between frames is. |
| 3121 | #[test] |
| 3122 | fn moved_edges_counts_the_edges_whose_time_changes() { |
| 3123 | // 30 -> 5: frame 60 is 2.0 s both before and after; frame 33 (1.1 s) becomes frame 6 (1.2 s). |
| 3124 | assert_eq!(moved_edges(&[60, 33], &[10, 6], 30.0, 5.0), 1); |
| 3125 | // 30 -> 29.97 moves every edge after the first frame. |
| 3126 | assert_eq!(moved_edges(&[0, 1200], &[0, 1200], 30.0, 29.97), 1); |
| 3127 | assert_eq!(moved_edges(&[0, 30], &[0, 30], 30.0, 30.0), 0); |
| 3128 | } |
| 3129 | |
| 3130 | /// The sample rate argument takes "source" or one of the rates the GUI offers, and refuses the rest. |
| 3131 | #[test] |
| 3132 | fn sample_rate_takes_source_or_a_gui_rate() { |
| 3133 | assert_eq!(parse_sample_rate(&json!("source")), Ok(None)); |
| 3134 | assert_eq!(parse_sample_rate(&json!(48000)), Ok(Some(48_000))); |
| 3135 | assert_eq!(parse_sample_rate(&json!("96000")), Ok(Some(96_000))); |
| 3136 | assert!(parse_sample_rate(&json!(22050)).is_err()); |
| 3137 | assert!(parse_sample_rate(&json!("fast")).is_err()); |
| 3138 | } |
| 3139 | |
| 3140 | #[test] |
| 3141 | fn status_formats_the_duration_once_and_counts_ledger_steps() { |
| 3142 | quiet(); |
| 3143 | let mut server = Server::new(); |
| 3144 | server.session = Some(PlaybackSession::empty(1280, 720, 30.0).unwrap()); |
| 3145 | server.ledger = vec![crate::server::Entry::new(1, "a"), crate::server::Entry::new(2, "b")]; |
| 3146 | let r = status_reply(&server); |
| 3147 | assert!(!r.text.contains("(("), "{}", r.text); |
| 3148 | assert!(r.text.contains("00:00.000 (0f)"), "{}", r.text); |
| 3149 | assert!(r.text.contains("undo 2 · redo 0"), "{}", r.text); |
| 3150 | } |
| 3151 | |
| 3152 | #[test] |
| 3153 | fn save_names_a_missing_folder() { |
| 3154 | quiet(); |
| 3155 | let (dir, _) = scratch("nofolder"); |
| 3156 | let missing = dir.join("no-such-folder-xyz").join("p.edith"); |
| 3157 | let mut server = Server::new(); |
| 3158 | server.session = Some(PlaybackSession::empty(1280, 720, 30.0).unwrap()); |
| 3159 | import_av(&mut server); |
| 3160 | let r = project_save(&mut server, &json!({"path": missing.display().to_string()})); |
| 3161 | assert!(r.is_error); |
| 3162 | assert!( |
| 3163 | r.text.contains(&format!("folder does not exist: {}", missing.parent().unwrap().display())), |
| 3164 | "{}", |
| 3165 | r.text |
| 3166 | ); |
| 3167 | } |
| 3168 | |
| 3169 | #[test] |
| 3170 | fn save_keeps_imported_sources_that_are_not_on_the_timeline() { |
| 3171 | quiet(); |
| 3172 | let (_dir, file) = scratch("unplaced"); |
| 3173 | let mut server = Server::new(); |
| 3174 | server.session = Some(PlaybackSession::empty(1280, 720, 30.0).unwrap()); |
| 3175 | server.session.as_mut().unwrap().import(&asset("test_tone.wav")).expect("import wav"); |
| 3176 | let r = project_save(&mut server, &json!({"path": file.display().to_string()})); |
| 3177 | assert!(!r.is_error, "{}", r.text); |
| 3178 | assert!(!r.text.contains("not saved"), "every imported source is saved now: {}", r.text); |
| 3179 | let text = std::fs::read_to_string(&file).expect("read the save"); |
| 3180 | assert!(text.contains("test_tone.wav"), "the unplaced source reached the file:\n{text}"); |
| 3181 | } |
| 3182 | |
| 3183 | #[test] |
| 3184 | fn open_names_a_missing_file_as_not_found() { |
| 3185 | let mut server = Server::new(); |
| 3186 | let r = project_open(&mut server, &json!({"path": "/definitely/not/here.edith"})); |
| 3187 | assert_eq!(r.text, "not found: /definitely/not/here.edith"); |
| 3188 | } |
| 3189 | |
| 3190 | #[test] |
| 3191 | fn open_names_the_unsaved_open_project() { |
| 3192 | quiet(); |
| 3193 | let (_dir, path) = scratch("unsaved-open"); |
| 3194 | let mut server = Server::new(); |
| 3195 | assert!(!call(project_new, &mut server, json!({"path": path})).is_error); |
| 3196 | let r = call(project_open, &mut server, json!({"path": path})); |
| 3197 | assert!(r.is_error); |
| 3198 | assert!(r.text.contains("not yet saved") && r.text.contains("already open"), "{}", r.text); |
| 3199 | assert!(r.text.contains("call project_save to write it"), "{}", r.text); |
| 3200 | } |
| 3201 | |
| 3202 | /// A project saved past its source (hand-written here: a clip that runs to frame 10000 of |
| 3203 | /// a 150-frame file) opens, and the reply starts with the fix it needed, naming the clamp. |
| 3204 | #[test] |
| 3205 | fn open_reports_a_clamped_clip_first_and_says_to_save() { |
| 3206 | quiet(); |
| 3207 | let (_dir, path) = scratch("open-clamped"); |
| 3208 | let asset = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/test_av.mp4").canonicalize().unwrap(); |
| 3209 | std::fs::write( |
| 3210 | &path, |
| 3211 | format!("edith 1\nplayhead 0\nsource {}\nclip 0 30 0\nclip 30 10000 0\n", asset.display()), |
| 3212 | ) |
| 3213 | .unwrap(); |
| 3214 | let mut server = Server::new(); |
| 3215 | let r = call(project_open, &mut server, json!({"path": path})); |
| 3216 | assert!(!r.is_error, "{}", r.text); |
| 3217 | assert!(r.text.starts_with("warning: the file needed fixing to open: clip "), "{}", r.text); |
| 3218 | assert!(r.text.contains("clamped to") && r.text.contains("save to keep the fix"), "{}", r.text); |
| 3219 | } |
| 3220 | |
| 3221 | #[test] |
| 3222 | fn open_refuses_a_device_or_a_non_media_file_before_the_unsaved_guard() { |
| 3223 | quiet(); |
| 3224 | let (dir, _path) = scratch("open-validate"); |
| 3225 | let notes = dir.join("notes.txt"); |
| 3226 | std::fs::write(¬es, b"plain text, not media").unwrap(); |
| 3227 | let mut server = Server::new(); |
| 3228 | server.session = Some(PlaybackSession::empty(1280, 720, 30.0).unwrap()); |
| 3229 | assert!(dirty(&server), "the open project is unsaved"); |
| 3230 | let dev = call(project_open, &mut server, json!({"path": "/dev/zero"})); |
| 3231 | assert!(dev.is_error); |
| 3232 | assert!(dev.text.contains("is not a regular file: /dev/zero"), "{}", dev.text); |
| 3233 | let text = call(project_open, &mut server, json!({"path": notes})); |
| 3234 | assert!(text.is_error); |
| 3235 | assert!(text.text.contains("is not an edith project or a media file"), "{}", text.text); |
| 3236 | assert!(!text.text.contains("unsaved"), "{}", text.text); |
| 3237 | } |
| 3238 | |
| 3239 | #[test] |
| 3240 | fn limiter_ceiling_outside_the_engine_range_is_refused_by_name() { |
| 3241 | quiet(); |
| 3242 | let mut server = Server::new(); |
| 3243 | server.session = Some(PlaybackSession::empty(1280, 720, 30.0).unwrap()); |
| 3244 | let low = call(project_settings, &mut server, json!({"limiter": {"on": true, "ceiling_db": -30.0}})); |
| 3245 | assert!(low.text.contains("from -24 to 0 dBTP"), "{}", low.text); |
| 3246 | assert!(call(project_status, &mut server, json!({})).text.contains("limiter off")); |
| 3247 | let ok = call(project_settings, &mut server, json!({"limiter": {"on": true, "ceiling_db": -1.5}})); |
| 3248 | assert!(!ok.is_error, "{}", ok.text); |
| 3249 | assert!(call(project_status, &mut server, json!({})).text.contains("limiter on at -1.5 dBTP true peak")); |
| 3250 | } |
| 3251 | |
| 3252 | #[test] |
| 3253 | fn save_names_an_unwritable_folder() { |
| 3254 | quiet(); |
| 3255 | let mut server = Server::new(); |
| 3256 | server.session = Some(PlaybackSession::empty(1280, 720, 30.0).unwrap()); |
| 3257 | import_av(&mut server); |
| 3258 | let r = call(project_save, &mut server, json!({"path": "/proc/forbidden.edith"})); |
| 3259 | assert!(r.is_error); |
| 3260 | assert!(r.text.contains("save failed: could not write /proc/forbidden.edith"), "{}", r.text); |
| 3261 | } |
| 3262 | } |
| 3263 | |
| 3264 | #[cfg(test)] |
| 3265 | mod autosave_tests { |
| 3266 | use super::*; |
| 3267 | use std::fs::File; |
| 3268 | |
| 3269 | fn asset(name: &str) -> PathBuf { |
| 3270 | Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets").join(name) |
| 3271 | } |
| 3272 | |
| 3273 | /// A project that was never saved leaves only its autosave: `project_open` of its |
| 3274 | /// path names that autosave, and opening the autosave recovers the work. |
| 3275 | #[test] |
| 3276 | fn open_of_a_never_saved_project_names_its_autosave() { |
| 3277 | engine::ao::set_silent_output(); |
| 3278 | let td = crate::testutil::TestDir::new("autosave-never-saved"); |
| 3279 | let path = td.path().join("proj.edith"); |
| 3280 | let mut server = Server::new(); |
| 3281 | let r = project_new(&mut server, &json!({"path": path, "resolution": "1280x720"})); |
| 3282 | assert!(!r.is_error, "{}", r.text); |
| 3283 | server.session.as_mut().unwrap().import(&asset("test_av.mp4")).expect("import"); |
| 3284 | let auto = autosave_at_eof(&server).expect("a dirty project autosaves"); |
| 3285 | assert!(!path.exists(), "the project was never saved"); |
| 3286 | |
| 3287 | let mut fresh = Server::new(); |
| 3288 | let missing = project_open(&mut fresh, &json!({"path": path})); |
| 3289 | assert!(missing.is_error, "{}", missing.text); |
| 3290 | assert!(missing.text.starts_with("not found:"), "{}", missing.text); |
| 3291 | assert!(missing.text.contains("never saved"), "{}", missing.text); |
| 3292 | assert!(missing.text.contains(&auto.display().to_string()), "{}", missing.text); |
| 3293 | assert!(missing.text.contains("\"recover\": true"), "{}", missing.text); |
| 3294 | |
| 3295 | let recovered = project_open(&mut fresh, &json!({"path": path, "recover": true})); |
| 3296 | assert!(!recovered.is_error, "{}", recovered.text); |
| 3297 | assert!(recovered.text.contains("src:0 test_av.mp4") || recovered.text.contains("sources: 1"), "{}", recovered.text); |
| 3298 | assert!(recovered.text.contains("recovered the unsaved edits"), "{}", recovered.text); |
| 3299 | // A never-saved project has no saved timeline under the recovered state: undo says so. |
| 3300 | assert!(recovered.text.contains("undo has nothing earlier to return to: the project was never saved"), "{}", recovered.text); |
| 3301 | assert!(recovered.text.contains("project_open {discard_autosave:true}"), "{}", recovered.text); |
| 3302 | assert!(!recovered.text.contains("use checkpoint/restore"), "{}", recovered.text); |
| 3303 | assert!(dirty(&fresh), "a recovered project is unsaved"); |
| 3304 | // Saving the recovered work writes the project file and retires the autosave. |
| 3305 | let saved = project_save(&mut fresh, &json!({})); |
| 3306 | assert!(!saved.is_error, "{}", saved.text); |
| 3307 | assert!(path.is_file(), "the recovered project is now a file"); |
| 3308 | assert!(!auto.exists(), "the save replaced the autosave"); |
| 3309 | } |
| 3310 | |
| 3311 | /// `recover` with no autosave to load is refused by name, and writes nothing. |
| 3312 | #[test] |
| 3313 | fn recover_without_an_autosave_is_refused() { |
| 3314 | engine::ao::set_silent_output(); |
| 3315 | let td = crate::testutil::TestDir::new("autosave-no-recover"); |
| 3316 | let path = td.path().join("none.edith"); |
| 3317 | let mut server = Server::new(); |
| 3318 | let r = project_open(&mut server, &json!({"path": path, "recover": true})); |
| 3319 | assert!(r.is_error, "{}", r.text); |
| 3320 | assert!(r.text.contains("nothing to recover"), "{}", r.text); |
| 3321 | assert!(server.session.is_none()); |
| 3322 | } |
| 3323 | |
| 3324 | /// The timeline as `(start, in, out)` per clip on every lane: what a recovery's undo must give back. |
| 3325 | fn timeline(s: &PlaybackSession) -> Vec<Vec<(u32, u32, u32)>> { |
| 3326 | s.lanes() |
| 3327 | .into_iter() |
| 3328 | .map(|l| s.lane_clips(l).iter().map(|c| (c.start, c.in_frame, c.out_frame)).collect()) |
| 3329 | .collect() |
| 3330 | } |
| 3331 | |
| 3332 | fn tool(server: &mut Server, name: &str, args: Value) -> Reply { |
| 3333 | let t = crate::server::tools().into_iter().find(|t| t.name == name).expect("tool"); |
| 3334 | (t.run)(server, &args) |
| 3335 | } |
| 3336 | |
| 3337 | /// A recovery on a saved project is one undo step: undo gives the saved file's timeline back, |
| 3338 | /// redo the recovered one, and the ledger holds the entry the reply names. |
| 3339 | #[test] |
| 3340 | fn recover_is_one_undo_step_that_undo_and_redo_walk() { |
| 3341 | engine::ao::set_silent_output(); |
| 3342 | let td = crate::testutil::TestDir::new("autosave-undo-recover"); |
| 3343 | let path = td.path().join("proj.edith"); |
| 3344 | let mut server = Server::new(); |
| 3345 | assert!(!project_new(&mut server, &json!({"path": path, "resolution": "1280x720"})).is_error); |
| 3346 | server.session.as_mut().unwrap().import(&asset("test_av.mp4")).expect("import"); |
| 3347 | let placed = tool(&mut server, "edit", json!({"ops": [{"op": "place", "source": "src:0", "lane": "V1", "at": "0s"}]})); |
| 3348 | assert!(!placed.is_error, "{}", placed.text); |
| 3349 | let cut = tool(&mut server, "edit", json!({"ops": [{"op": "split", "at": "1s"}]})); |
| 3350 | assert!(!cut.is_error, "{}", cut.text); |
| 3351 | assert!(project_save(&mut server, &json!({})).text.starts_with("saved")); |
| 3352 | let saved = timeline(server.session.as_ref().unwrap()); |
| 3353 | |
| 3354 | // Unsaved edits after the save, then the client walks away. |
| 3355 | let more = tool(&mut server, "edit", json!({"ops": [{"op": "split", "at": "2s"}]})); |
| 3356 | assert!(!more.is_error, "{}", more.text); |
| 3357 | let recovered = timeline(server.session.as_ref().unwrap()); |
| 3358 | assert_ne!(recovered, saved, "the edit changed the timeline"); |
| 3359 | let auto = autosave_at_eof(&server).expect("a dirty project autosaves"); |
| 3360 | drop(server); |
| 3361 | |
| 3362 | let mut fresh = Server::new(); |
| 3363 | let opened = project_open(&mut fresh, &json!({"path": path, "recover": true})); |
| 3364 | assert!(!opened.is_error, "{}", opened.text); |
| 3365 | assert_eq!(timeline(fresh.session.as_ref().unwrap()), recovered, "the recovered timeline"); |
| 3366 | assert_eq!(fresh.ledger.len(), 1, "one entry for the recovery"); |
| 3367 | let label = fresh.ledger[0].label.clone(); |
| 3368 | assert!(label.starts_with("recover autosave (") && label.contains(" edits from "), "{label}"); |
| 3369 | assert!(dirty(&fresh), "a recovered project is unsaved"); |
| 3370 | |
| 3371 | let undone = tool(&mut fresh, "undo", json!({})); |
| 3372 | assert!(!undone.is_error, "{}", undone.text); |
| 3373 | assert_eq!(timeline(fresh.session.as_ref().unwrap()), saved, "undo gives the saved file's timeline"); |
| 3374 | let redone = tool(&mut fresh, "redo", json!({})); |
| 3375 | assert!(!redone.is_error, "{}", redone.text); |
| 3376 | assert_eq!(timeline(fresh.session.as_ref().unwrap()), recovered, "redo gives the recovered timeline"); |
| 3377 | assert!(auto.is_file(), "the autosave stays until a save retires it"); |
| 3378 | } |
| 3379 | |
| 3380 | /// A save of a project with no sources says so, rather than blaming the folder; once a |
| 3381 | /// source is imported the same save works. |
| 3382 | #[test] |
| 3383 | fn save_of_a_project_with_no_sources_names_the_missing_source() { |
| 3384 | engine::ao::set_silent_output(); |
| 3385 | let td = crate::testutil::TestDir::new("save-empty"); |
| 3386 | let path = td.path().join("empty.edith"); |
| 3387 | let mut server = Server::new(); |
| 3388 | assert!(!project_new(&mut server, &json!({"path": path, "resolution": "1280x720"})).is_error); |
| 3389 | let early = project_save(&mut server, &json!({})); |
| 3390 | assert!(early.is_error, "{}", early.text); |
| 3391 | assert!(early.text.contains("nothing to save yet"), "{}", early.text); |
| 3392 | assert!(!early.text.contains("folder"), "{}", early.text); |
| 3393 | assert!(!path.exists()); |
| 3394 | |
| 3395 | server.session.as_mut().unwrap().import(&asset("test_av.mp4")).expect("import"); |
| 3396 | let saved = project_save(&mut server, &json!({})); |
| 3397 | assert!(!saved.is_error, "{}", saved.text); |
| 3398 | assert!(path.is_file()); |
| 3399 | } |
| 3400 | |
| 3401 | /// Unsaved work at EOF goes beside the project, the project file is left as it was, |
| 3402 | /// `project_open` says a newer autosave exists, and `project_save` clears it. |
| 3403 | #[test] |
| 3404 | fn unsaved_work_is_autosaved_beside_the_file_and_offered_on_open() { |
| 3405 | engine::ao::set_silent_output(); |
| 3406 | let td = crate::testutil::TestDir::new("autosave-eof"); |
| 3407 | let d = td.path().to_path_buf(); |
| 3408 | let path = d.join("proj.edith"); |
| 3409 | let mut server = Server::new(); |
| 3410 | let r = project_new(&mut server, &json!({"path": path, "resolution": "1280x720"})); |
| 3411 | assert!(!r.is_error, "{}", r.text); |
| 3412 | server.session.as_mut().unwrap().import(&asset("test_av.mp4")).expect("import"); |
| 3413 | assert!(project_save(&mut server, &json!({})).text.starts_with("saved")); |
| 3414 | let before = std::fs::read(&path).expect("read the saved project"); |
| 3415 | |
| 3416 | // A change after the save, then the client walks away. |
| 3417 | server.session.as_mut().unwrap().import(&asset("test_av2.mp4")).expect("import"); |
| 3418 | assert!(dirty(&server)); |
| 3419 | let auto = autosave_at_eof(&server).expect("a dirty project autosaves"); |
| 3420 | assert_eq!(auto, autosave_path(&path)); |
| 3421 | assert!(auto.is_file(), "the autosave exists"); |
| 3422 | assert_eq!(std::fs::read(&path).expect("reread"), before, "the real file is never overwritten"); |
| 3423 | |
| 3424 | // The open is refused before anything loads, and names both ways on. |
| 3425 | let mut fresh = Server::new(); |
| 3426 | let refused = project_open(&mut fresh, &json!({"path": path})); |
| 3427 | assert!(refused.is_error, "{}", refused.text); |
| 3428 | assert!(refused.text.starts_with(&format!("{} has an autosave from ", path.display())), "{}", refused.text); |
| 3429 | assert!(refused.text.contains("recover:true") && refused.text.contains("discard_autosave:true"), "{}", refused.text); |
| 3430 | assert!(refused.text.ends_with("Nothing was loaded."), "{}", refused.text); |
| 3431 | assert!(fresh.session.is_none(), "nothing is loaded by a refused open"); |
| 3432 | assert!(auto.is_file(), "nothing is set aside by a refused open"); |
| 3433 | |
| 3434 | // recover:true continues from the autosave; the save then retires it. |
| 3435 | let opened = project_open(&mut fresh, &json!({"path": path, "recover": true})); |
| 3436 | assert!(!opened.is_error, "{}", opened.text); |
| 3437 | assert!(opened.text.contains("recovered the unsaved edits from "), "{}", opened.text); |
| 3438 | assert!(opened.text.contains("undo takes the recovered edits back as one step"), "{}", opened.text); |
| 3439 | |
| 3440 | // A save writes the session's state and retires the autosave, and says so once. |
| 3441 | let saved = project_save(&mut fresh, &json!({})); |
| 3442 | assert!(!saved.is_error, "{}", saved.text); |
| 3443 | assert!(saved.text.contains("removed the autosave"), "{}", saved.text); |
| 3444 | assert!(!saved.text.contains("kept"), "{}", saved.text); |
| 3445 | assert!(!auto.exists(), "the save replaced the autosave"); |
| 3446 | } |
| 3447 | |
| 3448 | /// A project saved once, then given more work and left to autosave: returns the test dir, |
| 3449 | /// the project path and its autosave path. |
| 3450 | fn unrecovered_project(name: &str) -> (crate::testutil::TestDir, PathBuf, PathBuf) { |
| 3451 | engine::ao::set_silent_output(); |
| 3452 | let td = crate::testutil::TestDir::new(name); |
| 3453 | let path = td.path().join("proj.edith"); |
| 3454 | let mut server = Server::new(); |
| 3455 | assert!(!project_new(&mut server, &json!({"path": path, "resolution": "1280x720"})).is_error); |
| 3456 | server.session.as_mut().unwrap().import(&asset("test_av.mp4")).expect("import"); |
| 3457 | assert!(project_save(&mut server, &json!({})).text.starts_with("saved")); |
| 3458 | server.session.as_mut().unwrap().import(&asset("test_av2.mp4")).expect("import"); |
| 3459 | let auto = autosave_at_eof(&server).expect("a dirty project autosaves"); |
| 3460 | (td, path, auto) |
| 3461 | } |
| 3462 | |
| 3463 | /// An open over an unloaded autosave is refused, and the refusal loads and writes nothing. |
| 3464 | /// `discard_autosave` opens the saved file and sets the autosave aside; the save then succeeds. |
| 3465 | #[test] |
| 3466 | fn unloaded_autosave_refuses_the_open_and_discard_then_saves() { |
| 3467 | let (td, path, auto) = unrecovered_project("autosave-refuse-open"); |
| 3468 | let mut fresh = Server::new(); |
| 3469 | let refused = project_open(&mut fresh, &json!({"path": path})); |
| 3470 | assert!(refused.is_error, "{}", refused.text); |
| 3471 | assert!(refused.text.contains("(an earlier session's unsaved edits: +1 source(s)"), "{}", refused.text); |
| 3472 | assert!(fresh.session.is_none(), "nothing is loaded"); |
| 3473 | assert!(auto.is_file(), "nothing is written or moved"); |
| 3474 | |
| 3475 | // discard_autosave opens the saved file (one source) and sets the autosave aside. |
| 3476 | let opened = project_open(&mut fresh, &json!({"path": path, "discard_autosave": true})); |
| 3477 | assert!(!opened.is_error, "{}", opened.text); |
| 3478 | assert!(opened.text.starts_with("set the autosave aside as "), "{}", opened.text); |
| 3479 | assert!(opened.text.contains("(its unsaved edits are not loaded; the copy is kept (the newest 3 dated copies and any from the last 7 days are kept; older ones are deleted))"), "{}", opened.text); |
| 3480 | assert!(!opened.text.contains('⚠'), "{}", opened.text); |
| 3481 | assert_eq!(fresh.session.as_ref().unwrap().sources().len(), 1, "the autosave is not loaded"); |
| 3482 | assert!(opened.structured.as_ref().unwrap()["unrecovered_autosave"].is_null()); |
| 3483 | assert!(!auto.exists(), "the autosave moved aside"); |
| 3484 | let kept: Vec<_> = std::fs::read_dir(td.path()) |
| 3485 | .unwrap() |
| 3486 | .filter_map(|e| e.ok().map(|e| e.file_name().to_string_lossy().into_owned())) |
| 3487 | .filter(|n| n.starts_with("proj.autosave-")) |
| 3488 | .collect(); |
| 3489 | assert_eq!(kept.len(), 1, "{kept:?}"); |
| 3490 | |
| 3491 | // The save after a discard open succeeds: nothing unloaded is left beside the project. |
| 3492 | let saved = project_save(&mut fresh, &json!({})); |
| 3493 | assert!(!saved.is_error, "{}", saved.text); |
| 3494 | assert!(saved.text.starts_with("saved "), "{}", saved.text); |
| 3495 | assert!(!saved.text.contains("kept"), "{}", saved.text); |
| 3496 | let status = project_status(&mut fresh, &json!({})); |
| 3497 | assert!(status.structured.as_ref().unwrap()["unrecovered_autosave"].is_null()); |
| 3498 | } |
| 3499 | |
| 3500 | /// `discard_autosave` sets the unloaded edits aside as a dated copy (the newest 3 dated copies and any from the last 7 days are kept; older ones are deleted), and |
| 3501 | /// the reply says so first with no warning. |
| 3502 | #[test] |
| 3503 | fn discard_autosave_keeps_a_dated_copy_of_the_unloaded_edits() { |
| 3504 | let (_td, path, auto) = unrecovered_project("autosave-discard"); |
| 3505 | let bytes = std::fs::read(&auto).expect("the autosave to set aside"); |
| 3506 | let mut fresh = Server::new(); |
| 3507 | let opened = project_open(&mut fresh, &json!({"path": path, "discard_autosave": true})); |
| 3508 | assert!(!opened.is_error, "{}", opened.text); |
| 3509 | assert!(opened.text.starts_with("set the autosave aside as "), "{}", opened.text); |
| 3510 | assert!(opened.text.contains("the copy is kept (the newest 3 dated copies and any from the last 7 days are kept; older ones are deleted)"), "{}", opened.text); |
| 3511 | assert!(!opened.text.contains('⚠'), "{}", opened.text); |
| 3512 | assert!(!auto.exists(), "the autosave itself is moved"); |
| 3513 | let dated = dated_autosaves(&path); |
| 3514 | assert_eq!(dated.len(), 1, "one dated copy: {:?}", dated); |
| 3515 | assert!(opened.text.contains(&dated[0].1.display().to_string()), "the reply names the copy: {}", opened.text); |
| 3516 | assert_eq!(std::fs::read(&dated[0].1).expect("read the copy"), bytes, "the copy holds the same edits"); |
| 3517 | assert!(opened.structured.as_ref().unwrap()["unrecovered_autosave"].is_null()); |
| 3518 | // Nothing was edited since: the session writes no autosave at exit. |
| 3519 | assert!(autosave_at_eof(&fresh).is_none()); |
| 3520 | assert!(!auto.exists()); |
| 3521 | } |
| 3522 | |
| 3523 | /// Over an unloaded autosave, the choice still needs the unsaved-edits guard to pass: with |
| 3524 | /// another project dirty, `discard_autosave` alone is refused and nothing is set aside; with |
| 3525 | /// `discard` as well, both happen and the reply names each. |
| 3526 | #[test] |
| 3527 | fn discard_autosave_still_respects_the_unsaved_guard_of_another_project() { |
| 3528 | let (td, path, auto) = unrecovered_project("autosave-other-dirty"); |
| 3529 | let mut server = Server::new(); |
| 3530 | let other = td.path().join("other.edith"); |
| 3531 | assert!(!project_new(&mut server, &json!({"path": other, "resolution": "1280x720"})).is_error); |
| 3532 | let refused = project_open(&mut server, &json!({"path": path, "discard_autosave": true})); |
| 3533 | assert!(refused.is_error, "{}", refused.text); |
| 3534 | assert!(refused.text.contains("has unsaved changes"), "{}", refused.text); |
| 3535 | assert!(auto.is_file(), "a refused open sets nothing aside"); |
| 3536 | assert_eq!(server.path.as_deref(), Some(other.as_path()), "the other project is still open"); |
| 3537 | |
| 3538 | let opened = project_open(&mut server, &json!({"path": path, "discard_autosave": true, "discard": true})); |
| 3539 | assert!(!opened.is_error, "{}", opened.text); |
| 3540 | assert!(opened.text.contains("discarded unsaved edits in "), "{}", opened.text); |
| 3541 | assert!(opened.text.contains("set the autosave aside as "), "{}", opened.text); |
| 3542 | assert!(!auto.exists()); |
| 3543 | } |
| 3544 | |
| 3545 | /// A media file started as a project: its project is <stem>.edith beside it. Over that |
| 3546 | /// project's unloaded autosave the open is refused and names the .edith, and recover installs |
| 3547 | /// the .edith as the project, so a save writes the project and never the media file. |
| 3548 | #[test] |
| 3549 | fn media_start_recovers_its_own_project_and_never_the_media_file() { |
| 3550 | engine::ao::set_silent_output(); |
| 3551 | let td = crate::testutil::TestDir::new("autosave-media"); |
| 3552 | let clip = td.path().join("clip.mp4"); |
| 3553 | std::fs::copy(asset("test_av.mp4"), &clip).expect("copy the clip"); |
| 3554 | let media_bytes = std::fs::read(&clip).expect("read the clip"); |
| 3555 | let project = td.path().join("clip.edith"); |
| 3556 | let mut first = Server::new(); |
| 3557 | assert!(!project_new(&mut first, &json!({"path": project, "resolution": "1280x720"})).is_error); |
| 3558 | first.session.as_mut().unwrap().import(&clip).expect("import"); |
| 3559 | let auto = autosave_at_eof(&first).expect("a dirty project autosaves"); |
| 3560 | assert_eq!(auto, td.path().join("clip.autosave.edith")); |
| 3561 | |
| 3562 | let mut fresh = Server::new(); |
| 3563 | let refused = project_open(&mut fresh, &json!({"path": clip})); |
| 3564 | assert!(refused.is_error, "{}", refused.text); |
| 3565 | assert!(refused.text.starts_with(&format!("{} has an autosave from ", project.display())), "{}", refused.text); |
| 3566 | let rec = project_open(&mut fresh, &json!({"path": clip, "recover": true})); |
| 3567 | assert!(!rec.is_error, "{}", rec.text); |
| 3568 | assert_eq!(fresh.path.as_deref(), Some(project.as_path()), "the project file is the one recovered"); |
| 3569 | let saved = project_save(&mut fresh, &json!({})); |
| 3570 | assert!(!saved.is_error, "{}", saved.text); |
| 3571 | assert_eq!(std::fs::read(&clip).expect("reread the clip"), media_bytes, "the media file is never written"); |
| 3572 | } |
| 3573 | |
| 3574 | /// A session that opens a project and makes no edit writes no autosave at exit, whatever |
| 3575 | /// it found beside the project: an unrecovered autosave, a recovered one, a file that needed |
| 3576 | /// a load fix. An edit made in such a session is still autosaved. |
| 3577 | #[test] |
| 3578 | fn a_session_that_made_no_edit_writes_no_autosave_at_exit() { |
| 3579 | let (td, path, auto) = unrecovered_project("autosave-no-edit"); |
| 3580 | let before = std::fs::read(&auto).expect("the unrecovered autosave"); |
| 3581 | let listing = |d: &Path| { |
| 3582 | let mut v: Vec<String> = std::fs::read_dir(d).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect(); |
| 3583 | v.sort(); |
| 3584 | v |
| 3585 | }; |
| 3586 | let files_before = listing(td.path()); |
| 3587 | |
| 3588 | // Refused over the unloaded autosave: nothing opens, so nothing is written at exit. |
| 3589 | let mut fresh = Server::new(); |
| 3590 | assert!(project_open(&mut fresh, &json!({"path": path})).is_error); |
| 3591 | assert!(autosave_at_eof(&fresh).is_none(), "a refused open leaves the autosave alone at exit"); |
| 3592 | assert_eq!(std::fs::read(&auto).expect("still there"), before); |
| 3593 | assert_eq!(listing(td.path()), files_before, "no file was written, moved or copied"); |
| 3594 | |
| 3595 | let mut rec = Server::new(); |
| 3596 | assert!(!project_open(&mut rec, &json!({"path": path, "recover": true})).is_error); |
| 3597 | assert!(autosave_at_eof(&rec).is_none(), "a recovered session with no edit writes nothing"); |
| 3598 | assert_eq!(listing(td.path()), files_before); |
| 3599 | |
| 3600 | // An edit in the recovered session is still autosaved, in place of the recovered one. |
| 3601 | rec.session.as_mut().unwrap().import(&asset("test_tone.wav")).expect("import"); |
| 3602 | assert!(autosave_at_eof(&rec).is_some(), "an edit is autosaved at exit"); |
| 3603 | } |
| 3604 | |
| 3605 | /// A file that needed a fix to open (a clip past its source, clamped) is not an edit: the |
| 3606 | /// session that only opens it writes no autosave, and the reply still says what was fixed. |
| 3607 | #[test] |
| 3608 | fn a_load_fix_alone_is_not_an_edit() { |
| 3609 | engine::ao::set_silent_output(); |
| 3610 | let td = crate::testutil::TestDir::new("autosave-load-fix"); |
| 3611 | let path = td.path().join("proj.edith"); |
| 3612 | let mut server = Server::new(); |
| 3613 | assert!(!project_new(&mut server, &json!({"path": path, "resolution": "1280x720"})).is_error); |
| 3614 | let s = server.session.as_mut().unwrap(); |
| 3615 | s.import(&asset("test_av.mp4")).expect("import"); |
| 3616 | s.place_stream_at(0.0, &asset("test_av.mp4"), 0, Some(Lane::V1)).expect("place the picture"); |
| 3617 | assert!(project_save(&mut server, &json!({})).text.starts_with("saved")); |
| 3618 | // Make a clip run past its source, as a file a GUI or an older engine wrote can. |
| 3619 | let text = std::fs::read_to_string(&path).expect("read the project"); |
| 3620 | let mut out = String::new(); |
| 3621 | let mut changed = false; |
| 3622 | for line in text.lines() { |
| 3623 | if !changed && line.starts_with("video ") { |
| 3624 | let mut t: Vec<&str> = line.split(' ').collect(); |
| 3625 | if t.len() > 4 { |
| 3626 | t[4] = "9999"; |
| 3627 | changed = true; |
| 3628 | } |
| 3629 | out.push_str(&t.join(" ")); |
| 3630 | } else { |
| 3631 | out.push_str(line); |
| 3632 | } |
| 3633 | out.push('\n'); |
| 3634 | } |
| 3635 | assert!(changed, "the file has a video clip to stretch"); |
| 3636 | std::fs::write(&path, out).expect("write the stretched project"); |
| 3637 | let mut fresh = Server::new(); |
| 3638 | let opened = project_open(&mut fresh, &json!({"path": path})); |
| 3639 | assert!(!opened.is_error, "{}", opened.text); |
| 3640 | assert!(opened.text.contains("needed fixing to open"), "{}", opened.text); |
| 3641 | assert!(dirty(&fresh), "the fix is unsaved"); |
| 3642 | assert!(autosave_at_eof(&fresh).is_none(), "a fix alone writes no autosave"); |
| 3643 | assert!(!autosave_path(&path).exists()); |
| 3644 | let _ = td; |
| 3645 | } |
| 3646 | |
| 3647 | /// Recover, then save: the save removes the autosave, as the recover reply promised. |
| 3648 | #[test] |
| 3649 | fn recover_then_save_removes_the_autosave() { |
| 3650 | let (_td, path, auto) = unrecovered_project("autosave-recover-save"); |
| 3651 | let mut fresh = Server::new(); |
| 3652 | let first = project_open(&mut fresh, &json!({"path": path})); |
| 3653 | assert!(first.is_error && first.text.contains("has an autosave from"), "{}", first.text); |
| 3654 | let rec = project_open(&mut fresh, &json!({"path": path, "recover": true})); |
| 3655 | assert!(!rec.is_error, "{}", rec.text); |
| 3656 | assert!(!rec.text.contains('⚠'), "{}", rec.text); |
| 3657 | assert!(rec.text.contains("removes the autosave"), "{}", rec.text); |
| 3658 | assert!(rec.structured.as_ref().unwrap()["unrecovered_autosave"].is_null()); |
| 3659 | let saved = project_save(&mut fresh, &json!({})); |
| 3660 | assert!(!saved.is_error, "{}", saved.text); |
| 3661 | assert!(saved.text.starts_with("saved "), "{}", saved.text); |
| 3662 | assert!(saved.text.contains("removed the autosave"), "{}", saved.text); |
| 3663 | assert!(!saved.text.contains("kept"), "{}", saved.text); |
| 3664 | assert!(!auto.exists()); |
| 3665 | } |
| 3666 | |
| 3667 | /// A discard names the unsaved edits it drops and the autosave they were written to. |
| 3668 | #[test] |
| 3669 | fn discarding_unsaved_edits_names_where_they_are() { |
| 3670 | engine::ao::set_silent_output(); |
| 3671 | let td = crate::testutil::TestDir::new("discard-note"); |
| 3672 | let path = td.path().join("proj.edith"); |
| 3673 | let other = td.path().join("other.edith"); |
| 3674 | let mut server = Server::new(); |
| 3675 | assert!(!project_new(&mut server, &json!({"path": path, "resolution": "1280x720"})).is_error); |
| 3676 | server.session.as_mut().unwrap().import(&asset("test_av.mp4")).expect("import"); |
| 3677 | assert!(project_save(&mut server, &json!({})).text.starts_with("saved")); |
| 3678 | server.session.as_mut().unwrap().import(&asset("test_av2.mp4")).expect("import"); |
| 3679 | let r = project_new(&mut server, &json!({"path": other, "resolution": "1280x720", "discard": true})); |
| 3680 | assert!(!r.is_error, "{}", r.text); |
| 3681 | let auto = autosave_path(&path); |
| 3682 | let want = format!("discarded unsaved edits in {} (still in its autosave {})", path.display(), auto.display()); |
| 3683 | assert!(r.text.starts_with(&want), "{}", r.text); |
| 3684 | assert!(auto.is_file(), "the discarded edits are in the autosave"); |
| 3685 | } |
| 3686 | |
| 3687 | /// An autosave no newer than the file the session last saved is stale, and the save removes it. |
| 3688 | #[test] |
| 3689 | fn save_removes_an_autosave_no_newer_than_the_file() { |
| 3690 | engine::ao::set_silent_output(); |
| 3691 | let td = crate::testutil::TestDir::new("autosave-stale"); |
| 3692 | let path = td.path().join("stale.edith"); |
| 3693 | let mut server = Server::new(); |
| 3694 | assert!(!project_new(&mut server, &json!({"path": path, "resolution": "1280x720"})).is_error); |
| 3695 | server.session.as_mut().unwrap().import(&asset("test_av.mp4")).expect("import"); |
| 3696 | assert!(project_save(&mut server, &json!({})).text.starts_with("saved")); |
| 3697 | server.session.as_mut().unwrap().import(&asset("test_av2.mp4")).expect("import"); |
| 3698 | let auto = autosave_at_eof(&server).expect("a dirty project autosaves"); |
| 3699 | File::options() |
| 3700 | .write(true) |
| 3701 | .open(&auto) |
| 3702 | .unwrap() |
| 3703 | .set_modified(SystemTime::now() - Duration::from_secs(3600)) |
| 3704 | .unwrap(); |
| 3705 | let saved = project_save(&mut server, &json!({})); |
| 3706 | assert!(!saved.is_error, "{}", saved.text); |
| 3707 | assert!(saved.text.contains("removed the autosave"), "{}", saved.text); |
| 3708 | assert!(!auto.exists()); |
| 3709 | } |
| 3710 | |
| 3711 | /// A project opened over a newer autosave the session did not recover: a save keeps the |
| 3712 | /// autosave under a dated name, byte for byte, and never deletes it. |
| 3713 | #[test] |
| 3714 | fn save_after_an_unrecovered_open_keeps_the_autosave_dated() { |
| 3715 | engine::ao::set_silent_output(); |
| 3716 | let td = crate::testutil::TestDir::new("autosave-keep"); |
| 3717 | let path = td.path().join("keep.edith"); |
| 3718 | let mut server = Server::new(); |
| 3719 | assert!(!project_new(&mut server, &json!({"path": path, "resolution": "1280x720"})).is_error); |
| 3720 | server.session.as_mut().unwrap().import(&asset("test_av.mp4")).expect("import"); |
| 3721 | assert!(project_save(&mut server, &json!({})).text.starts_with("saved")); |
| 3722 | server.session.as_mut().unwrap().import(&asset("test_av2.mp4")).expect("import"); |
| 3723 | let auto = autosave_at_eof(&server).expect("a dirty project autosaves"); |
| 3724 | let auto_bytes = std::fs::read(&auto).expect("read the autosave"); |
| 3725 | |
| 3726 | // The open happens with no autosave beside the project; another session's autosave then |
| 3727 | // appears while this one runs. |
| 3728 | std::fs::remove_file(&auto).expect("take the autosave away before the open"); |
| 3729 | let mut fresh = Server::new(); |
| 3730 | let opened = project_open(&mut fresh, &json!({"path": path})); |
| 3731 | assert!(!opened.is_error, "{}", opened.text); |
| 3732 | std::fs::write(&auto, &auto_bytes).expect("the autosave appears after the open"); |
| 3733 | |
| 3734 | let refused = project_save(&mut fresh, &json!({})); |
| 3735 | assert!(refused.is_error, "{}", refused.text); |
| 3736 | assert!(refused.text.contains("not loaded by this session"), "{}", refused.text); |
| 3737 | assert!(auto.is_file(), "a refused save moves nothing"); |
| 3738 | |
| 3739 | let saved = project_save(&mut fresh, &json!({"discard_autosave": true})); |
| 3740 | assert!(!saved.is_error, "{}", saved.text); |
| 3741 | assert!(saved.text.contains("kept the unrecovered autosave as "), "{}", saved.text); |
| 3742 | assert!(!saved.text.contains("removed"), "{}", saved.text); |
| 3743 | assert!(!auto.exists(), "the autosave moved out of the way"); |
| 3744 | |
| 3745 | let kept: Vec<PathBuf> = std::fs::read_dir(td.path()) |
| 3746 | .expect("list the folder") |
| 3747 | .filter_map(|e| e.ok().map(|e| e.path())) |
| 3748 | .filter(|p| p.file_name().is_some_and(|n| { |
| 3749 | let n = n.to_string_lossy(); |
| 3750 | n.starts_with("keep.autosave-") && n.ends_with(".edith") |
| 3751 | })) |
| 3752 | .collect(); |
| 3753 | assert_eq!(kept.len(), 1, "exactly one dated autosave: {kept:?}"); |
| 3754 | let name = kept[0].file_name().unwrap().to_string_lossy().into_owned(); |
| 3755 | let stamp = &name["keep.autosave-".len()..name.len() - ".edith".len()]; |
| 3756 | assert_eq!(stamp.len(), 15, "YYYYmmdd-HHMMSS: {stamp}"); |
| 3757 | assert_eq!(stamp.as_bytes()[8], b'-', "{stamp}"); |
| 3758 | assert!(saved.text.contains(&kept[0].display().to_string()), "{}", saved.text); |
| 3759 | assert_eq!(std::fs::read(&kept[0]).expect("read the kept autosave"), auto_bytes, "kept byte for byte"); |
| 3760 | } |
| 3761 | |
| 3762 | /// The stamp is the UTC calendar time, with no clock crate: checked at known instants. |
| 3763 | #[test] |
| 3764 | fn local_stamp_and_text_are_the_same_local_time() { |
| 3765 | // The stamp in a dated autosave name and the reply's time are both local: they agree. |
| 3766 | for secs in [0u64, 1_700_000_000, 951_782_400] { |
| 3767 | let t = SystemTime::UNIX_EPOCH + Duration::from_secs(secs); |
| 3768 | let (stamp, text) = (local_stamp(t), local_text(t)); |
| 3769 | assert_eq!(stamp.len(), 15, "{stamp}"); |
| 3770 | assert_eq!(text.len(), 19, "{text}"); |
| 3771 | let digits: String = text.chars().filter(char::is_ascii_digit).collect(); |
| 3772 | assert_eq!(stamp.replace('-', ""), digits, "{stamp} vs {text}"); |
| 3773 | } |
| 3774 | let t = SystemTime::UNIX_EPOCH + Duration::from_secs(1_700_000_000); |
| 3775 | let tm = local_time(t).expect("local time"); |
| 3776 | assert_eq!(chrono::Datelike::year(&tm), 2023); |
| 3777 | assert_eq!(local_stamp(t).get(..8), Some(tm.format("%Y%m%d").to_string().as_str())); |
| 3778 | } |
| 3779 | |
| 3780 | /// A clean project writes nothing at EOF. |
| 3781 | #[test] |
| 3782 | fn a_clean_project_is_not_autosaved() { |
| 3783 | engine::ao::set_silent_output(); |
| 3784 | let td = crate::testutil::TestDir::new("autosave-clean"); |
| 3785 | let d = td.path().to_path_buf(); |
| 3786 | let path = d.join("clean.edith"); |
| 3787 | let mut server = Server::new(); |
| 3788 | project_new(&mut server, &json!({"path": path, "resolution": "1280x720"})); |
| 3789 | server.session.as_mut().unwrap().import(&asset("test_av.mp4")).expect("import"); |
| 3790 | project_save(&mut server, &json!({})); |
| 3791 | assert!(autosave_at_eof(&server).is_none()); |
| 3792 | assert!(!autosave_path(&path).exists()); |
| 3793 | } |
| 3794 | |
| 3795 | /// Sources imported but not placed on the timeline are in the autosave, so a recovered |
| 3796 | /// session still has every `src:<n>` the last one had. |
| 3797 | #[test] |
| 3798 | fn recovered_autosave_keeps_every_imported_source() { |
| 3799 | engine::ao::set_silent_output(); |
| 3800 | let td = crate::testutil::TestDir::new("autosave-sources"); |
| 3801 | let path = td.path().join("keep.edith"); |
| 3802 | let mut server = Server::new(); |
| 3803 | assert!(!project_new(&mut server, &json!({"path": path, "resolution": "1280x720"})).is_error); |
| 3804 | let s = server.session.as_mut().unwrap(); |
| 3805 | s.import(&asset("test_av.mp4")).expect("import"); |
| 3806 | s.import(&asset("test_tone.wav")).expect("import"); |
| 3807 | s.import(&asset("test_hevc.mkv")).expect("import"); |
| 3808 | let auto = autosave_at_eof(&server).expect("a dirty project autosaves"); |
| 3809 | |
| 3810 | let mut fresh = Server::new(); |
| 3811 | let r = project_open(&mut fresh, &json!({"path": path, "recover": true})); |
| 3812 | assert!(!r.is_error, "{}", r.text); |
| 3813 | assert_eq!(fresh.session.as_ref().unwrap().sources().len(), 3, "every import is recovered"); |
| 3814 | assert!(auto.is_file()); |
| 3815 | } |
| 3816 | |
| 3817 | /// A read-only run on a saved project, and a run that recovers an autosave and changes |
| 3818 | /// nothing, write no autosave and print nothing. |
| 3819 | #[test] |
| 3820 | fn read_only_runs_write_no_autosave() { |
| 3821 | engine::ao::set_silent_output(); |
| 3822 | let td = crate::testutil::TestDir::new("autosave-read-only"); |
| 3823 | let path = td.path().join("ro.edith"); |
| 3824 | let mut server = Server::new(); |
| 3825 | assert!(!project_new(&mut server, &json!({"path": path, "resolution": "1280x720"})).is_error); |
| 3826 | server.session.as_mut().unwrap().import(&asset("test_av.mp4")).expect("import"); |
| 3827 | assert!(project_save(&mut server, &json!({})).text.starts_with("saved")); |
| 3828 | |
| 3829 | let mut clean = Server::new(); |
| 3830 | assert!(!project_open(&mut clean, &json!({"path": path})).is_error); |
| 3831 | assert!(autosave_at_eof(&clean).is_none(), "a saved project that is unchanged writes nothing"); |
| 3832 | assert!(!autosave_path(&path).exists()); |
| 3833 | |
| 3834 | // An unsaved change makes one autosave; a later run that only reads it writes nothing. |
| 3835 | clean.session.as_mut().unwrap().import(&asset("test_av2.mp4")).expect("import"); |
| 3836 | assert!(autosave_at_eof(&clean).is_some()); |
| 3837 | let mut recovered = Server::new(); |
| 3838 | assert!(!project_open(&mut recovered, &json!({"path": path, "recover": true})).is_error); |
| 3839 | assert!(autosave_at_eof(&recovered).is_none(), "the recovered work is already in the autosave"); |
| 3840 | } |
| 3841 | |
| 3842 | /// An autosave that matches the file, or is older than it, is stale: `project_open` |
| 3843 | /// removes it without offering recovery. Only a newer one that differs is offered. |
| 3844 | #[test] |
| 3845 | fn open_removes_a_stale_autosave_silently() { |
| 3846 | engine::ao::set_silent_output(); |
| 3847 | let td = crate::testutil::TestDir::new("autosave-open-stale"); |
| 3848 | let path = td.path().join("stale2.edith"); |
| 3849 | let mut server = Server::new(); |
| 3850 | assert!(!project_new(&mut server, &json!({"path": path, "resolution": "1280x720"})).is_error); |
| 3851 | server.session.as_mut().unwrap().import(&asset("test_av.mp4")).expect("import"); |
| 3852 | assert!(project_save(&mut server, &json!({})).text.starts_with("saved")); |
| 3853 | let auto = autosave_path(&path); |
| 3854 | |
| 3855 | // Identical content, newer than the file: stale. |
| 3856 | std::fs::copy(&path, &auto).expect("copy"); |
| 3857 | std::fs::File::options().write(true).open(&auto).expect("open").set_modified(SystemTime::now() + Duration::from_secs(60)).expect("mtime"); |
| 3858 | let mut a = Server::new(); |
| 3859 | let r = project_open(&mut a, &json!({"path": path})); |
| 3860 | assert!(!r.is_error, "{}", r.text); |
| 3861 | assert!(!r.text.contains("unsaved edits"), "{}", r.text); |
| 3862 | assert!(!auto.exists(), "the identical autosave is removed"); |
| 3863 | |
| 3864 | // Different content, but older than the file: stale too. |
| 3865 | let mut b = Server::new(); |
| 3866 | assert!(!project_open(&mut b, &json!({"path": path, "discard": true})).is_error); |
| 3867 | b.session.as_mut().unwrap().import(&asset("test_av2.mp4")).expect("import"); |
| 3868 | assert!(autosave_at_eof(&b).is_some()); |
| 3869 | std::fs::File::options().write(true).open(&path).expect("open").set_modified(SystemTime::now() + Duration::from_secs(120)).expect("mtime"); |
| 3870 | let mut c = Server::new(); |
| 3871 | let r = project_open(&mut c, &json!({"path": path})); |
| 3872 | assert!(!r.text.contains("unsaved edits"), "{}", r.text); |
| 3873 | assert!(!auto.exists(), "an older autosave is removed"); |
| 3874 | } |
| 3875 | |
| 3876 | /// Parallel checks of one session's body all read back the whole project: none of them |
| 3877 | /// reads a scratch file another thread wrote or removed (the flake this guards against). |
| 3878 | #[test] |
| 3879 | fn session_body_is_stable_under_parallel_calls() { |
| 3880 | engine::ao::set_silent_output(); |
| 3881 | let base_session = PlaybackSession::open(asset("test_av.mp4")).expect("open test asset"); |
| 3882 | let base = session_body(&base_session).expect("a body"); |
| 3883 | let path = asset("test_av.mp4"); |
| 3884 | std::thread::scope(|s| { |
| 3885 | let handles: Vec<_> = (0..16) |
| 3886 | .map(|_| { |
| 3887 | let path = path.clone(); |
| 3888 | s.spawn(move || session_body(&PlaybackSession::open(path).expect("open"))) |
| 3889 | }) |
| 3890 | .collect(); |
| 3891 | for h in handles { |
| 3892 | assert_eq!(h.join().expect("thread").as_deref(), Some(base.as_slice())); |
| 3893 | } |
| 3894 | }); |
| 3895 | } |
| 3896 | |
| 3897 | fn call(server: &mut Server, name: &str, args: Value) -> Reply { |
| 3898 | let t = crate::server::tools().into_iter().find(|t| t.name == name).expect("tool"); |
| 3899 | (t.run)(server, &args) |
| 3900 | } |
| 3901 | |
| 3902 | /// A project opened and left unchanged writes no autosave at exit, and a setting edit |
| 3903 | /// that is undone again leaves the session saying what the file says. |
| 3904 | #[test] |
| 3905 | fn unchanged_project_writes_no_autosave_at_exit() { |
| 3906 | engine::ao::set_silent_output(); |
| 3907 | let td = crate::testutil::TestDir::new("autosave-unchanged"); |
| 3908 | let path = td.path().join("unchanged.edith"); |
| 3909 | let mut server = Server::new(); |
| 3910 | assert!(!project_new(&mut server, &json!({"path": path, "resolution": "1280x720"})).is_error); |
| 3911 | server.session.as_mut().unwrap().import(&asset("test_av.mp4")).expect("import"); |
| 3912 | assert!(project_save(&mut server, &json!({})).text.starts_with("saved")); |
| 3913 | |
| 3914 | let mut opened = Server::new(); |
| 3915 | assert!(!project_open(&mut opened, &json!({"path": path})).is_error); |
| 3916 | assert!(autosave_at_eof(&opened).is_none(), "an unchanged project is not autosaved"); |
| 3917 | |
| 3918 | let r = call(&mut opened, "edit", json!({"ops": [{"op": "lane_gain", "lane": "A1", "db": -6}]})); |
| 3919 | assert!(!r.is_error, "{}", r.text); |
| 3920 | assert!(autosave_at_eof(&opened).is_some(), "a setting edit is autosaved"); |
| 3921 | let r = call(&mut opened, "undo", json!({})); |
| 3922 | assert!(!r.is_error, "{}", r.text); |
| 3923 | assert!(autosave_at_eof(&opened).is_none(), "undone back to the file: nothing to autosave"); |
| 3924 | } |
| 3925 | |
| 3926 | /// The open warning reads settings from the two files: a gain, and the colour of the |
| 3927 | /// clip that points at a changed colour entry. Identical texts differ in nothing. |
| 3928 | #[test] |
| 3929 | fn settings_differences_name_gains_and_clip_colours() { |
| 3930 | let file = "edith 29\nplayhead 0\nresolution 1280 720\nfps 25\nsource 0 a.mp4\nvideo 1 0 0 50 0 - - - fit 1000 0 0 0 - 0 0\naudio 1 0 0 50 0 - - - fit 1000 0 0 0 - 0 0\n"; |
| 3931 | let auto = "edith 29\nplayhead 40\nresolution 1280 720\nfps 25\nsource 0 a.mp4\nvideo 1 0 0 50 0 - - 0 fit 1000 0 0 0 - 0 0\naudio 1 0 0 50 0 - - - fit 1000 0 0 0 - 0 0\ncolor 0.1:1.2:0.9:-0.3\ngain audio 1 -6.0\n"; |
| 3932 | assert!(settings_differences(file, file).is_empty()); |
| 3933 | let got = settings_differences(file, auto); |
| 3934 | assert!(got.contains(&"color on V1@0".to_string()), "{got:?}"); |
| 3935 | assert!(got.contains(&"lane A1 gain -6 dB".to_string()), "{got:?}"); |
| 3936 | assert!(!got.iter().any(|g| g.starts_with("clip")), "{got:?}"); |
| 3937 | } |
| 3938 | /// Gives the clip on A1 at 0 a gain of `db`, as one edit step. |
| 3939 | fn set_gain(server: &mut Server, db: f64) { |
| 3940 | let r = crate::tools::edit::run_edit(server, &json!({"ops": [{"op": "gain", "clip": "A1@0", "db": db}]})); |
| 3941 | assert!(!r.is_error, "{}", r.text); |
| 3942 | } |
| 3943 | |
| 3944 | /// The gain (dB) the autosave at `path` holds for its A1 clip. |
| 3945 | fn autosave_gain(path: &Path) -> String { |
| 3946 | let text = std::fs::read_to_string(path).expect("read the autosave"); |
| 3947 | text.lines().find(|l| l.starts_with("clipgain audio")).unwrap_or("no clipgain").to_string() |
| 3948 | } |
| 3949 | |
| 3950 | /// The two-session sequence from the dogfood: run 1 leaves the -7 edit in the autosave; |
| 3951 | /// run 2 opens without recovering it, edits, and exits. The -7 autosave must survive under a |
| 3952 | /// dated name, and run 2's own autosave holds run 2's edit. |
| 3953 | #[test] |
| 3954 | fn unrecovered_autosave_survives_a_second_session_that_edits() { |
| 3955 | engine::ao::set_silent_output(); |
| 3956 | let td = crate::testutil::TestDir::new("autosave-two-sessions"); |
| 3957 | let path = td.path().join("au.edith"); |
| 3958 | let mut first = Server::new(); |
| 3959 | assert!(!project_new(&mut first, &json!({"path": path, "resolution": "1280x720"})).is_error); |
| 3960 | first.session.as_mut().unwrap().import(&asset("test_av.mp4")).expect("import"); |
| 3961 | let placed = crate::tools::edit::run_edit(&mut first, &json!({"ops": [{"op": "place", "source": "src:0", "at": 0}]})); |
| 3962 | assert!(!placed.is_error, "{}", placed.text); |
| 3963 | assert!(project_save(&mut first, &json!({})).text.starts_with("saved")); |
| 3964 | // Run 1: gain -7, exit. |
| 3965 | let mut run1 = Server::new(); |
| 3966 | assert!(!project_open(&mut run1, &json!({"path": path})).is_error); |
| 3967 | set_gain(&mut run1, -7.0); |
| 3968 | let auto = autosave_at_eof(&run1).expect("run 1 autosaves its -7"); |
| 3969 | assert_eq!(autosave_gain(&auto), "clipgain audio 1 0 -7"); |
| 3970 | |
| 3971 | // Run 2: a plain open is refused over run 1's autosave, so it opens with discard_autosave |
| 3972 | // (run 1's edits are set aside), edits, exits. |
| 3973 | let mut run2 = Server::new(); |
| 3974 | assert!(project_open(&mut run2, &json!({"path": path})).is_error); |
| 3975 | let opened = project_open(&mut run2, &json!({"path": path, "discard_autosave": true})); |
| 3976 | assert!(opened.text.contains("set the autosave aside as"), "{}", opened.text); |
| 3977 | set_gain(&mut run2, -2.0); |
| 3978 | assert_eq!(autosave_at_eof(&run2).as_deref(), Some(auto.as_path())); |
| 3979 | |
| 3980 | // The -7 edits are kept, byte for byte, under a dated name; run 2's edit is the autosave. |
| 3981 | let kept: Vec<PathBuf> = std::fs::read_dir(td.path()) |
| 3982 | .unwrap() |
| 3983 | .filter_map(|e| e.ok().map(|e| e.path())) |
| 3984 | .filter(|p| p.file_name().unwrap().to_string_lossy().starts_with("au.autosave-")) |
| 3985 | .collect(); |
| 3986 | assert_eq!(kept.len(), 1, "exactly one dated copy: {kept:?}"); |
| 3987 | assert_eq!(autosave_gain(&kept[0]), "clipgain audio 1 0 -7", "the -7 edit survives"); |
| 3988 | assert_eq!(autosave_gain(&auto), "clipgain audio 1 0 -2"); |
| 3989 | |
| 3990 | // Run 3 recovers run 2's autosave and exits with no change: nothing is moved or added. |
| 3991 | let mut run3 = Server::new(); |
| 3992 | assert!(!project_open(&mut run3, &json!({"path": path, "recover": true})).is_error); |
| 3993 | assert_eq!(autosave_at_eof(&run3), None, "a recovered session that changes nothing writes nothing"); |
| 3994 | assert_eq!(autosave_gain(&auto), "clipgain audio 1 0 -2"); |
| 3995 | let dated = std::fs::read_dir(td.path()).unwrap().filter(|e| e.as_ref().unwrap().file_name().to_string_lossy().starts_with("au.autosave-")).count(); |
| 3996 | assert_eq!(dated, 1); |
| 3997 | } |
| 3998 | |
| 3999 | /// A recovered autosave that the session edits is replaced in place, with nothing moved aside. |
| 4000 | #[test] |
| 4001 | fn recovered_autosave_is_replaced_in_place() { |
| 4002 | engine::ao::set_silent_output(); |
| 4003 | let (td, path, auto) = unrecovered_project("autosave-recover-in-place"); |
| 4004 | let mut run = Server::new(); |
| 4005 | assert!(!project_open(&mut run, &json!({"path": path, "recover": true})).is_error); |
| 4006 | run.session.as_mut().unwrap().import(&asset("test_ac3.mp4")).expect("a different edit"); |
| 4007 | assert_eq!(autosave_at_eof(&run).as_deref(), Some(auto.as_path())); |
| 4008 | let dated = std::fs::read_dir(td.path()).unwrap().filter(|e| e.as_ref().unwrap().file_name().to_string_lossy().starts_with("proj.autosave-")).count(); |
| 4009 | assert_eq!(dated, 0, "no dated copy when the session recovered the autosave"); |
| 4010 | } |
| 4011 | |
| 4012 | /// A save-as to another file, then a save back to the original, needs no force: both are this |
| 4013 | /// project's files. A third file that exists and was never this project's is still refused. |
| 4014 | #[test] |
| 4015 | fn save_back_to_the_original_after_save_as_needs_no_force() { |
| 4016 | engine::ao::set_silent_output(); |
| 4017 | let td = crate::testutil::TestDir::new("save-back-original"); |
| 4018 | let orig = td.path().join("orig.edith"); |
| 4019 | let copy = td.path().join("copy.undo.edith"); |
| 4020 | let mut server = Server::new(); |
| 4021 | assert!(!project_new(&mut server, &json!({"path": orig, "resolution": "1280x720"})).is_error); |
| 4022 | server.session.as_mut().unwrap().import(&asset("test_av.mp4")).expect("import"); |
| 4023 | assert!(project_save(&mut server, &json!({})).text.starts_with("saved")); |
| 4024 | let as_copy = project_save(&mut server, &json!({"path": copy})); |
| 4025 | assert!(as_copy.text.starts_with("saved"), "{}", as_copy.text); |
| 4026 | let back = project_save(&mut server, &json!({"path": orig})); |
| 4027 | assert!(back.text.starts_with("saved"), "{}", back.text); |
| 4028 | // Opened in this session, so saving it needs no force either. |
| 4029 | let mut other = Server::new(); |
| 4030 | assert!(!project_open(&mut other, &json!({"path": orig})).is_error); |
| 4031 | let again = project_save(&mut other, &json!({})); |
| 4032 | assert!(again.text.starts_with("saved"), "{}", again.text); |
| 4033 | // The copy exists and this session never opened or saved it: refused. |
| 4034 | let foreign = project_save(&mut other, &json!({"path": copy})); |
| 4035 | assert!(foreign.is_error && foreign.text.contains("not this project's file"), "{}", foreign.text); |
| 4036 | // A file this session never touched is still refused. |
| 4037 | let stranger = td.path().join("stranger.edith"); |
| 4038 | std::fs::write(&stranger, b"not ours").unwrap(); |
| 4039 | let refused = project_save(&mut server, &json!({"path": stranger})); |
| 4040 | assert!(refused.is_error && refused.text.contains("not this project's file"), "{}", refused.text); |
| 4041 | } |
| 4042 | |
| 4043 | |
| 4044 | /// An autosave that cannot be written is reported by name, not silently dropped: the write |
| 4045 | /// returns the reason, and a discard that would have kept the edits says they are gone. |
| 4046 | #[test] |
| 4047 | fn a_failed_autosave_names_its_reason() { |
| 4048 | engine::ao::set_silent_output(); |
| 4049 | let td = crate::testutil::TestDir::new("autosave-fails"); |
| 4050 | // A file where the folder of the project should be: no autosave can be written beside it. |
| 4051 | std::fs::write(td.path().join("blocker"), b"x").unwrap(); |
| 4052 | let path = td.path().join("blocker").join("p.edith"); |
| 4053 | let mut server = Server::new(); |
| 4054 | server.session = Some(engine::PlaybackSession::empty(1280, 720, 30.0).expect("empty session")); |
| 4055 | server.path = Some(path.clone()); |
| 4056 | server.session.as_mut().unwrap().import(&asset("test_av.mp4")).expect("import"); |
| 4057 | let why = write_autosave(&server).expect_err("the write must fail"); |
| 4058 | assert!(why.contains("cannot create the folder"), "{why}"); |
| 4059 | assert!(autosave_at_eof(&server).is_none()); |
| 4060 | let note = discarded_note(&server); |
| 4061 | assert!(note.contains("autosave FAILED") && note.contains("gone"), "{note}"); |
| 4062 | } |
| 4063 | } |
| 4064 | |
| 4065 | #[cfg(test)] |
| 4066 | mod relink_tests { |
| 4067 | use super::*; |
| 4068 | |
| 4069 | fn asset(name: &str) -> PathBuf { |
| 4070 | Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets").join(name) |
| 4071 | } |
| 4072 | |
| 4073 | /// A saved project whose one source is a copy of a fixture, then the copy moved away. |
| 4074 | /// Returns the folder, the project path, the source's saved path and where it went. |
| 4075 | fn moved_source(name: &str) -> (crate::testutil::TestDir, PathBuf, PathBuf, PathBuf) { |
| 4076 | engine::ao::set_silent_output(); |
| 4077 | let td = crate::testutil::TestDir::new(name); |
| 4078 | let d = td.path().to_path_buf(); |
| 4079 | let media = d.join("film.mp4"); |
| 4080 | std::fs::copy(asset("test_av.mp4"), &media).expect("copy the fixture"); |
| 4081 | let path = d.join("proj.edith"); |
| 4082 | let mut server = Server::new(); |
| 4083 | assert!(!project_new(&mut server, &json!({"path": path, "resolution": "1280x720"})).is_error); |
| 4084 | server.session.as_mut().unwrap().import(&media).expect("import"); |
| 4085 | assert!(project_save(&mut server, &json!({})).text.starts_with("saved")); |
| 4086 | let moved_dir = d.join("moved"); |
| 4087 | std::fs::create_dir(&moved_dir).expect("make the new folder"); |
| 4088 | let moved = moved_dir.join("film.mp4"); |
| 4089 | std::fs::rename(&media, &moved).expect("move the media"); |
| 4090 | (td, path, media, moved_dir) |
| 4091 | } |
| 4092 | |
| 4093 | #[test] |
| 4094 | fn a_moved_source_opens_offline_and_names_its_fix() { |
| 4095 | let (_td, path, _media, _moved_dir) = moved_source("relink-offline"); |
| 4096 | let mut fresh = Server::new(); |
| 4097 | let opened = project_open(&mut fresh, &json!({"path": path})); |
| 4098 | assert!(!opened.is_error, "{}", opened.text); |
| 4099 | assert!(opened.text.contains("1 source(s) offline"), "{}", opened.text); |
| 4100 | assert!(opened.text.contains("src:0"), "{}", opened.text); |
| 4101 | assert!(opened.text.contains("media_relink") && opened.text.contains("\"search\""), "{}", opened.text); |
| 4102 | assert_eq!(fresh.session.as_ref().unwrap().offline_sources().len(), 1); |
| 4103 | } |
| 4104 | |
| 4105 | #[test] |
| 4106 | fn search_relinks_a_moved_source_by_file_name() { |
| 4107 | let (_td, path, _media, moved_dir) = moved_source("relink-search"); |
| 4108 | let mut fresh = Server::new(); |
| 4109 | let found = project_open( |
| 4110 | &mut fresh, |
| 4111 | &json!({"path": path, "search": [moved_dir.display().to_string()]}), |
| 4112 | ); |
| 4113 | assert!(!found.is_error, "{}", found.text); |
| 4114 | assert!(found.text.contains("src:0 relinked:"), "{}", found.text); |
| 4115 | assert!(!found.text.contains("offline"), "{}", found.text); |
| 4116 | assert!(fresh.session.as_ref().unwrap().offline_sources().is_empty()); |
| 4117 | } |
| 4118 | |
| 4119 | #[test] |
| 4120 | fn two_files_with_one_name_are_listed_not_guessed() { |
| 4121 | let (td, path, _media, moved_dir) = moved_source("relink-ambiguous"); |
| 4122 | let other = td.path().join("elsewhere"); |
| 4123 | std::fs::create_dir(&other).expect("make the other folder"); |
| 4124 | std::fs::copy(asset("test_av.mp4"), other.join("film.mp4")).expect("a second film.mp4"); |
| 4125 | let mut fresh = Server::new(); |
| 4126 | let found = project_open( |
| 4127 | &mut fresh, |
| 4128 | &json!({"path": path, "search": [moved_dir.display().to_string(), other.display().to_string()]}), |
| 4129 | ); |
| 4130 | assert!(found.text.contains("2 files named film.mp4"), "{}", found.text); |
| 4131 | assert!(found.text.contains("not relinked"), "{}", found.text); |
| 4132 | assert_eq!(fresh.session.as_ref().unwrap().offline_sources().len(), 1); |
| 4133 | } |
| 4134 | |
| 4135 | #[test] |
| 4136 | fn media_relink_points_an_offline_source_at_the_file_and_makes_it_dirty() { |
| 4137 | let (_td, path, _media, moved_dir) = moved_source("relink-tool"); |
| 4138 | let mut fresh = Server::new(); |
| 4139 | assert!(!project_open(&mut fresh, &json!({"path": path})).is_error); |
| 4140 | let moved = moved_dir.join("film.mp4"); |
| 4141 | let bad = crate::tools::media::relink(&mut fresh, &json!({"source": "src:9", "path": moved.display().to_string()})); |
| 4142 | assert!(bad.is_error && bad.text.contains("no src:9"), "{}", bad.text); |
| 4143 | let done = crate::tools::media::relink(&mut fresh, &json!({"source": "src:0", "path": moved.display().to_string()})); |
| 4144 | assert!(!done.is_error, "{}", done.text); |
| 4145 | assert!(done.text.contains("src:0 relinked"), "{}", done.text); |
| 4146 | assert!(fresh.session.as_ref().unwrap().offline_sources().is_empty()); |
| 4147 | assert!(dirty(&fresh), "a relink is an unsaved change"); |
| 4148 | } |
| 4149 | |
| 4150 | /// A dirty session that was never saved leaves only the autosave beside a project already on |
| 4151 | /// disk: an open that does not recover it says so, and the status does not claim "saved". |
| 4152 | #[test] |
| 4153 | fn an_unrecovered_autosave_is_not_reported_as_saved() { |
| 4154 | engine::ao::set_silent_output(); |
| 4155 | let td = crate::testutil::TestDir::new("relink-status"); |
| 4156 | let path = td.path().join("proj.edith"); |
| 4157 | let mut server = Server::new(); |
| 4158 | assert!(!project_new(&mut server, &json!({"path": path, "resolution": "1280x720"})).is_error); |
| 4159 | server.session.as_mut().unwrap().import(&asset("test_av.mp4")).expect("import"); |
| 4160 | assert!(project_save(&mut server, &json!({})).text.starts_with("saved")); |
| 4161 | server.session.as_mut().unwrap().import(&asset("test_av2.mp4")).expect("import"); |
| 4162 | autosave_at_eof(&server).expect("a dirty project autosaves"); |
| 4163 | // Refused: the autosave is not loaded, so the open reply can not call the project saved. |
| 4164 | let refused = project_open(&mut Server::new(), &json!({"path": path})); |
| 4165 | assert!(refused.is_error, "{}", refused.text); |
| 4166 | assert!(!refused.text.contains("· saved ·"), "{}", refused.text); |
| 4167 | } |
| 4168 | |
| 4169 | /// Each run that closes dirty used to add a dated copy of the same unrecovered autosave. Now |
| 4170 | /// one collision keeps one dated copy and the session's own autosave takes its place; a run |
| 4171 | /// that closes clean writes nothing. |
| 4172 | #[test] |
| 4173 | fn repeated_runs_do_not_pile_up_dated_autosaves() { |
| 4174 | engine::ao::set_silent_output(); |
| 4175 | let td = crate::testutil::TestDir::new("relink-clutter"); |
| 4176 | let path = td.path().join("proj.edith"); |
| 4177 | let mut server = Server::new(); |
| 4178 | assert!(!project_new(&mut server, &json!({"path": path, "resolution": "1280x720"})).is_error); |
| 4179 | server.session.as_mut().unwrap().import(&asset("test_av.mp4")).expect("import"); |
| 4180 | assert!(project_save(&mut server, &json!({})).text.starts_with("saved")); |
| 4181 | server.session.as_mut().unwrap().import(&asset("test_av2.mp4")).expect("import"); |
| 4182 | let auto = autosave_at_eof(&server).expect("a dirty project autosaves"); |
| 4183 | |
| 4184 | let dated = || { |
| 4185 | std::fs::read_dir(td.path()) |
| 4186 | .unwrap() |
| 4187 | .filter_map(Result::ok) |
| 4188 | .filter(|e| e.file_name().to_string_lossy().starts_with("proj.autosave-")) |
| 4189 | .count() |
| 4190 | }; |
| 4191 | // A run that edits without recovering: the older autosave is kept dated, once. |
| 4192 | let mut run = Server::new(); |
| 4193 | assert!(!project_open(&mut run, &json!({"path": path, "discard_autosave": true})).is_error); |
| 4194 | run.session.as_mut().unwrap().import(&asset("test_ac3.mp4")).expect("a different edit"); |
| 4195 | assert_eq!(autosave_at_eof(&run).as_deref(), Some(auto.as_path())); |
| 4196 | assert_eq!(dated(), 1, "the unrecovered autosave is kept under a dated name"); |
| 4197 | |
| 4198 | // A run that only looks: the unsaved edits of the run before are refused, not loaded, and |
| 4199 | // the run closes with nothing written. |
| 4200 | let mut clean = Server::new(); |
| 4201 | assert!(project_open(&mut clean, &json!({"path": path})).is_error); |
| 4202 | assert!(autosave_at_eof(&clean).is_none()); |
| 4203 | assert_eq!(dated(), 1); |
| 4204 | } |
| 4205 | } |
| 4206 | |
| 4207 | #[cfg(test)] |
| 4208 | mod notice_tests { |
| 4209 | use super::*; |
| 4210 | use crate::testutil::TestDir; |
| 4211 | |
| 4212 | fn asset(name: &str) -> PathBuf { |
| 4213 | Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets").join(name) |
| 4214 | } |
| 4215 | |
| 4216 | fn run(server: &mut Server, name: &str, args: Value) -> Reply { |
| 4217 | let t = crate::server::tools().into_iter().find(|t| t.name == name).expect("tool"); |
| 4218 | (t.run)(server, &args) |
| 4219 | } |
| 4220 | |
| 4221 | /// A project of the given media, saved, so its file says what those sources are. |
| 4222 | fn saved_project(dir: &Path, name: &str, media: &[PathBuf]) -> PathBuf { |
| 4223 | let project = dir.join(format!("{name}.edith")); |
| 4224 | let mut server = Server::new(); |
| 4225 | assert!(!run(&mut server, "project_new", json!({"path": project, "resolution": "1280x720"})).is_error); |
| 4226 | let paths: Vec<String> = media.iter().map(|p| p.display().to_string()).collect(); |
| 4227 | assert!(!run(&mut server, "media_import", json!({"paths": paths})).is_error); |
| 4228 | let saved = run(&mut server, "project_save", json!({})); |
| 4229 | assert!(!saved.is_error, "{}", saved.text); |
| 4230 | project |
| 4231 | } |
| 4232 | |
| 4233 | /// The autosave notice names a source whose file changed, by its index and both file names. |
| 4234 | #[test] |
| 4235 | fn autosave_notice_names_a_changed_source_path() { |
| 4236 | let td = TestDir::new("notice-src"); |
| 4237 | let a = saved_project(&td, "a", &[asset("test_hevc.mp4")]); |
| 4238 | let b = saved_project(&td, "b", &[asset("test_av.mp4")]); |
| 4239 | let fa = PlaybackSession::open_project(&a).expect("open a"); |
| 4240 | let fb = PlaybackSession::open_project(&b).expect("open b"); |
| 4241 | let text = autosave_summary(&fa, &fb, &[]); |
| 4242 | assert!(text.contains("src:0 test_hevc.mp4 -> test_av.mp4"), "{text}"); |
| 4243 | assert!(!text.contains("no clip, lane, setting or source differs"), "{text}"); |
| 4244 | } |
| 4245 | |
| 4246 | /// An import-only change is worded as one: the source added, and that no clip, lane or |
| 4247 | /// setting changed. |
| 4248 | #[test] |
| 4249 | fn autosave_notice_says_an_import_changed_no_clip() { |
| 4250 | let td = TestDir::new("notice-import"); |
| 4251 | let a = saved_project(&td, "a", &[asset("test_hevc.mp4")]); |
| 4252 | let c = saved_project(&td, "c", &[asset("test_hevc.mp4"), asset("test_av.mp4")]); |
| 4253 | let fa = PlaybackSession::open_project(&a).expect("open a"); |
| 4254 | let fc = PlaybackSession::open_project(&c).expect("open c"); |
| 4255 | let text = autosave_summary(&fa, &fc, &[]); |
| 4256 | assert!(text.contains("+1 source(s): src:1 test_av.mp4"), "{text}"); |
| 4257 | assert!(text.contains("(no clip, lane or setting changed)"), "{text}"); |
| 4258 | } |
| 4259 | |
| 4260 | /// project_new says the file waits for project_save, and that unsaved work is autosaved |
| 4261 | /// when the session ends: the behaviour, not "nothing is written". |
| 4262 | #[test] |
| 4263 | fn project_new_says_when_the_autosave_is_written() { |
| 4264 | let td = TestDir::new("notice-new"); |
| 4265 | let mut server = Server::new(); |
| 4266 | let r = run(&mut server, "project_new", json!({"path": td.path().join("n.edith")})); |
| 4267 | assert!(r.text.contains("written only by project_save"), "{}", r.text); |
| 4268 | assert!(r.text.contains("autosaved beside it when this session ends"), "{}", r.text); |
| 4269 | assert!(!r.text.contains("nothing is written until"), "{}", r.text); |
| 4270 | } |
| 4271 | |
| 4272 | /// A load fix makes the project unsaved, the status says so, and a save writes the fix and says it did. |
| 4273 | #[test] |
| 4274 | fn a_load_fix_makes_the_project_unsaved_until_saved() { |
| 4275 | let td = TestDir::new("notice-fix"); |
| 4276 | let project = saved_project(&td, "fix", &[asset("test_av.mp4")]); |
| 4277 | let mut server = Server::new(); |
| 4278 | assert!(!run(&mut server, "project_open", json!({"path": project})).is_error); |
| 4279 | assert!(!dirty(&server)); |
| 4280 | server.load_fixes = vec!["clip V1@0 ran past its source; cut to the source's end".to_string()]; |
| 4281 | assert!(dirty(&server)); |
| 4282 | let status = status_reply(&server); |
| 4283 | assert!(status.text.contains("unsaved: the open fixed 1 thing(s) to load"), "{}", status.text); |
| 4284 | assert!(status.text.contains("· dirty ·"), "{}", status.text); |
| 4285 | let saved = run(&mut server, "project_save", json!({})); |
| 4286 | assert!(saved.text.contains("written with the 1 fix(es) made to open it: clip V1@0"), "{}", saved.text); |
| 4287 | assert!(server.load_fixes.is_empty()); |
| 4288 | assert!(!dirty(&server)); |
| 4289 | } |
| 4290 | |
| 4291 | /// A source whose file is gone is named in the status with its fix, not only in media_list. |
| 4292 | #[test] |
| 4293 | fn status_names_an_offline_source_with_its_fix() { |
| 4294 | let td = TestDir::new("notice-offline"); |
| 4295 | std::fs::copy(asset("test_av.mp4"), td.path().join("moved.mp4")).expect("copy"); |
| 4296 | let project = saved_project(&td, "off", &[td.path().join("moved.mp4")]); |
| 4297 | std::fs::remove_file(td.path().join("moved.mp4")).expect("remove"); |
| 4298 | let mut server = Server::new(); |
| 4299 | assert!(!run(&mut server, "project_open", json!({"path": project})).is_error); |
| 4300 | let status = status_reply(&server); |
| 4301 | assert!(status.text.contains("OFFLINE: src:0 "), "{}", status.text); |
| 4302 | assert!(status.text.contains("(relink with media_relink)"), "{}", status.text); |
| 4303 | let structured = status.structured.expect("structured status"); |
| 4304 | assert_eq!(structured["offline"][0]["src"], json!(0)); |
| 4305 | } |
| 4306 | } |
| 4307 | |
| 4308 | /// Dogfood round 12: the save refusal, dated autosave listing and recovery, and relinks by search. |
| 4309 | #[cfg(test)] |
| 4310 | mod round12_tests { |
| 4311 | use super::*; |
| 4312 | use crate::testutil::TestDir; |
| 4313 | |
| 4314 | fn asset(name: &str) -> PathBuf { |
| 4315 | Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets").join(name) |
| 4316 | } |
| 4317 | |
| 4318 | fn run(server: &mut Server, name: &str, args: Value) -> Reply { |
| 4319 | let t = crate::server::tools().into_iter().find(|t| t.name == name).expect("tool"); |
| 4320 | (t.run)(server, &args) |
| 4321 | } |
| 4322 | |
| 4323 | /// A project saved with one source, then a second source imported and left to autosave. |
| 4324 | /// Returns the test dir, the project path and the autosave path. |
| 4325 | fn unrecovered(name: &str) -> (TestDir, PathBuf, PathBuf) { |
| 4326 | engine::ao::set_silent_output(); |
| 4327 | let td = TestDir::new(name); |
| 4328 | let path = td.path().join("proj.edith"); |
| 4329 | let mut server = Server::new(); |
| 4330 | assert!(!run(&mut server, "project_new", json!({"path": path, "resolution": "1280x720"})).is_error); |
| 4331 | server.session.as_mut().unwrap().import(&asset("test_av.mp4")).expect("import"); |
| 4332 | assert!(run(&mut server, "project_save", json!({})).text.starts_with("saved")); |
| 4333 | server.session.as_mut().unwrap().import(&asset("test_av2.mp4")).expect("import"); |
| 4334 | let auto = autosave_at_eof(&server).expect("a dirty project autosaves"); |
| 4335 | (td, path, auto) |
| 4336 | } |
| 4337 | |
| 4338 | /// Item 1: a save over an unrecovered autosave is refused by name, writes nothing, and |
| 4339 | /// `discard_autosave` sets the autosave aside as a dated copy. |
| 4340 | #[test] |
| 4341 | fn save_refuses_while_an_unrecovered_autosave_holds_edits() { |
| 4342 | let (_td, path, auto) = unrecovered("r12-refuse"); |
| 4343 | let before = std::fs::read(&path).expect("read the project"); |
| 4344 | let auto_bytes = std::fs::read(&auto).expect("read the autosave"); |
| 4345 | // The open is clean (no autosave beside the project yet); another session's autosave then |
| 4346 | // appears while this one runs. |
| 4347 | std::fs::remove_file(&auto).expect("take the autosave away before the open"); |
| 4348 | let mut fresh = Server::new(); |
| 4349 | assert!(!run(&mut fresh, "project_open", json!({"path": path})).is_error); |
| 4350 | std::fs::write(&auto, &auto_bytes).expect("the autosave appears after the open"); |
| 4351 | |
| 4352 | let refused = run(&mut fresh, "project_save", json!({})); |
| 4353 | assert!(refused.is_error, "{}", refused.text); |
| 4354 | assert!(refused.text.starts_with("an autosave from 20"), "{}", refused.text); |
| 4355 | assert!(refused.text.contains(" holds unsaved edits (+1 source(s)"), "{}", refused.text); |
| 4356 | assert!(refused.text.contains("not loaded by this session, holds unsaved edits"), "{}", refused.text); |
| 4357 | assert!(refused.text.contains("that are not in this project. project_save {discard_autosave:true} keeps THIS session's edits and sets the earlier autosave aside"), "{}", refused.text); |
| 4358 | assert!(refused.text.contains("project_open {\"path\": ") && refused.text.contains("\"recover\": true, \"discard\": true}"), "{}", refused.text); |
| 4359 | assert_eq!(std::fs::read(&path).expect("reread"), before, "the refused save writes nothing"); |
| 4360 | assert!(auto.is_file(), "the autosave is still there"); |
| 4361 | |
| 4362 | let saved = run(&mut fresh, "project_save", json!({"discard_autosave": true})); |
| 4363 | assert!(!saved.is_error, "{}", saved.text); |
| 4364 | assert!(saved.text.starts_with("kept the unrecovered autosave as "), "{}", saved.text); |
| 4365 | assert!(!auto.exists(), "the autosave moved aside"); |
| 4366 | } |
| 4367 | |
| 4368 | /// The stuck case: a project never saved, with an earlier session's autosave beside it. Its |
| 4369 | /// save and its reopen each named the other; now each names `project_save {discard_autosave}` |
| 4370 | /// (keeps this session's edits) and `project_open {recover, discard}` (drops them). |
| 4371 | #[test] |
| 4372 | fn already_open_unsaved_project_names_both_ways_out_of_a_stale_autosave() { |
| 4373 | let td = crate::testutil::TestDir::new("r15-stuck"); |
| 4374 | let path = td.path().join("p.edith"); |
| 4375 | let media = asset("test_av.mp4"); |
| 4376 | // The earlier session: a never-saved project whose edits were autosaved at exit. |
| 4377 | let mut earlier = Server::new(); |
| 4378 | assert!(!run(&mut earlier, "project_new", json!({"path": path, "resolution": "1280x720"})).is_error); |
| 4379 | earlier.session.as_mut().unwrap().import(&media).expect("import"); |
| 4380 | let auto = autosave_at_eof(&earlier).expect("the earlier session autosaves"); |
| 4381 | let auto_bytes = std::fs::read(&auto).expect("read the earlier autosave"); |
| 4382 | // This session: a new project at the path, started with no autosave beside it (project_new |
| 4383 | // refuses one). Another session's autosave appears while this one runs. |
| 4384 | std::fs::remove_file(&auto).expect("take the autosave away"); |
| 4385 | let mut now = Server::new(); |
| 4386 | assert!(!run(&mut now, "project_new", json!({"path": path, "resolution": "1280x720"})).is_error); |
| 4387 | std::fs::write(&auto, &auto_bytes).expect("the autosave appears"); |
| 4388 | now.session.as_mut().unwrap().import(&asset("test_av2.mp4")).expect("import"); |
| 4389 | |
| 4390 | let refused = run(&mut now, "project_save", json!({})); |
| 4391 | assert!(refused.is_error, "{}", refused.text); |
| 4392 | assert!(refused.text.contains("project_save {discard_autosave:true}"), "{}", refused.text); |
| 4393 | let reopened = run(&mut now, "project_open", json!({"path": path})); |
| 4394 | assert!(reopened.is_error, "{}", reopened.text); |
| 4395 | assert!(reopened.text.contains("not yet saved"), "{}", reopened.text); |
| 4396 | assert!(reopened.text.contains("project_save {discard_autosave:true}"), "{}", reopened.text); |
| 4397 | assert!(reopened.text.contains("\"discard\": true"), "{}", reopened.text); |
| 4398 | |
| 4399 | // The way out the refusals name: this session's edits are kept, the earlier autosave is kept too. |
| 4400 | let saved = run(&mut now, "project_save", json!({"discard_autosave": true})); |
| 4401 | assert!(!saved.is_error, "{}", saved.text); |
| 4402 | assert!(saved.text.contains("kept the unrecovered autosave as "), "{}", saved.text); |
| 4403 | assert!(!auto.exists(), "the earlier autosave moved aside"); |
| 4404 | assert!(path.is_file(), "this session's edits are saved"); |
| 4405 | assert_eq!(std::fs::read_dir(td.path()).unwrap().filter(|e| e.as_ref().is_ok_and(|e| e.file_name().to_string_lossy().contains(".autosave-"))).count(), 1); |
| 4406 | } |
| 4407 | |
| 4408 | /// `project_open {recover, discard}` over unsaved edits drops them and loads the autosave; |
| 4409 | /// without `discard` the recover is refused with both ways out, and nothing is dropped. |
| 4410 | #[test] |
| 4411 | fn recover_over_unsaved_edits_refuses_then_drops_them_only_on_discard() { |
| 4412 | let (_td, path, auto) = unrecovered("r15-recover-dirty"); |
| 4413 | let mut fresh = Server::new(); |
| 4414 | assert!(run(&mut fresh, "project_open", json!({"path": path})).is_error, "refused over the unloaded autosave"); |
| 4415 | assert!(!run(&mut fresh, "project_open", json!({"path": path, "recover": true})).is_error); |
| 4416 | // A settings change makes this session's edits unsaved. |
| 4417 | assert!(!run(&mut fresh, "project_settings", json!({"tonemap": "vivid"})).is_error); |
| 4418 | assert!(dirty(&fresh)); |
| 4419 | |
| 4420 | let refused = run(&mut fresh, "project_open", json!({"path": path, "recover": true})); |
| 4421 | assert!(refused.is_error, "{}", refused.text); |
| 4422 | assert!(refused.text.contains("project_save {discard_autosave:true}"), "{}", refused.text); |
| 4423 | assert!(refused.text.contains("\"discard\": true"), "{}", refused.text); |
| 4424 | assert!(dirty(&fresh), "a refusal drops nothing"); |
| 4425 | assert!(auto.is_file(), "the autosave is untouched by the refusal"); |
| 4426 | |
| 4427 | let ok = run(&mut fresh, "project_open", json!({"path": path, "recover": true, "discard": true})); |
| 4428 | assert!(!ok.is_error, "{}", ok.text); |
| 4429 | assert!(ok.text.starts_with("dropped the unsaved edits in "), "{}", ok.text); |
| 4430 | assert!(ok.text.contains("recovered the unsaved edits from "), "{}", ok.text); |
| 4431 | assert_eq!(fresh.session.as_ref().unwrap().sources().len(), 2, "the autosave's two sources are loaded"); |
| 4432 | assert!(auto.is_file(), "the autosave stays until a save removes it"); |
| 4433 | } |
| 4434 | |
| 4435 | /// Item 1: a recovered autosave saves without any flag, and the newest autosave is what |
| 4436 | /// `recover: true` loads. |
| 4437 | #[test] |
| 4438 | fn recovered_autosave_saves_without_a_flag() { |
| 4439 | let (_td, path, _auto) = unrecovered("r12-recover-saves"); |
| 4440 | let mut fresh = Server::new(); |
| 4441 | assert!(run(&mut fresh, "project_open", json!({"path": path})).is_error, "refused over the unloaded autosave"); |
| 4442 | assert!(!run(&mut fresh, "project_open", json!({"path": path, "recover": true})).is_error); |
| 4443 | let saved = run(&mut fresh, "project_save", json!({})); |
| 4444 | assert!(!saved.is_error, "{}", saved.text); |
| 4445 | assert_eq!(fresh.session.as_ref().unwrap().sources().len(), 2); |
| 4446 | } |
| 4447 | |
| 4448 | |
| 4449 | /// Two sessions over one folder. Session 1 leaves a 2-source autosave; session 2 recovers an |
| 4450 | /// older dated copy (1 source) and exits with no edits. The project's autosave must then hold |
| 4451 | /// what session 2 recovered, so session 3's plain recover loads that state and not the replaced |
| 4452 | /// one, and the replaced autosave is kept as a dated copy. |
| 4453 | #[test] |
| 4454 | fn a_dated_recovery_leaves_the_project_autosave_holding_the_recovered_state() { |
| 4455 | let (td, path, auto) = unrecovered("r29-recover-dated-state"); |
| 4456 | let auto_bytes = std::fs::read(&auto).expect("read the autosave"); |
| 4457 | let dated = td.path().join("proj.autosave-20260101-120000.edith"); |
| 4458 | std::fs::copy(&path, &dated).expect("a dated copy of the saved project"); |
| 4459 | |
| 4460 | // Session 2: recover the dated copy, make no edit, and exit. |
| 4461 | let mut second = Server::new(); |
| 4462 | let rec = run(&mut second, "project_open", json!({"path": path, "recover": "20260101-120000"})); |
| 4463 | assert!(!rec.is_error, "{}", rec.text); |
| 4464 | assert!(rec.text.contains("set aside as"), "the replaced autosave is named as a dated copy: {}", rec.text); |
| 4465 | assert_eq!(second.session.as_ref().unwrap().sources().len(), 1); |
| 4466 | assert!(autosave_at_eof(&second).is_none(), "an unedited recovery writes nothing new"); |
| 4467 | assert!(same_project(&auto, &dated), "the project's autosave now holds the recovered state"); |
| 4468 | |
| 4469 | // The replaced 2-source autosave is kept, not lost. |
| 4470 | let kept: Vec<PathBuf> = dated_autosaves(&path).into_iter().map(|(_, p)| p).filter(|p| p != &dated).collect(); |
| 4471 | assert_eq!(kept.len(), 1, "one dated copy holds the replaced autosave"); |
| 4472 | assert_eq!(std::fs::read(&kept[0]).expect("read the copy"), auto_bytes, "the copy holds the replaced edits"); |
| 4473 | |
| 4474 | // Session 3: a plain recover loads the same state session 2 recovered, not session 1's. |
| 4475 | let mut third = Server::new(); |
| 4476 | let rec = run(&mut third, "project_open", json!({"path": path, "recover": true})); |
| 4477 | assert!(!rec.is_error, "{}", rec.text); |
| 4478 | assert_eq!(third.session.as_ref().unwrap().sources().len(), 1, "the recovered state, not the replaced one"); |
| 4479 | // And a save writes that state over the project. |
| 4480 | let saved = run(&mut third, "project_save", json!({})); |
| 4481 | assert!(!saved.is_error, "{}", saved.text); |
| 4482 | assert_eq!(third.session.as_ref().unwrap().sources().len(), 1); |
| 4483 | } |
| 4484 | |
| 4485 | /// A recovery of the project's own autosave changes nothing beside it: no dated copy is made. |
| 4486 | #[test] |
| 4487 | fn recovering_the_own_autosave_makes_no_dated_copy() { |
| 4488 | let (_td, path, _auto) = unrecovered("r29-recover-own"); |
| 4489 | let mut server = Server::new(); |
| 4490 | assert!(!run(&mut server, "project_open", json!({"path": path, "recover": true})).is_error); |
| 4491 | assert!(dated_autosaves(&path).is_empty()); |
| 4492 | } |
| 4493 | |
| 4494 | /// Locks a lane, then changes the frame rate: a lane whose clip edges would move is refused |
| 4495 | /// unless force is set, and the refusal names the lane. A rate that moves no locked edge passes. |
| 4496 | #[test] |
| 4497 | fn an_fps_change_refuses_to_move_a_locked_lane_unless_forced() { |
| 4498 | engine::ao::set_silent_output(); |
| 4499 | let by_name = |server: &mut Server, name: &str, args: Value| run(server, name, args); |
| 4500 | let td = crate::testutil::TestDir::new("r29-fps-locked"); |
| 4501 | let path = td.path().join("proj.edith"); |
| 4502 | let mut server = Server::new(); |
| 4503 | assert!(!run(&mut server, "project_new", json!({"path": path})).is_error); |
| 4504 | let imported = by_name(&mut server, "media_import", json!({"paths": [asset("test_av.mp4").display().to_string()]})); |
| 4505 | assert!(!imported.is_error, "{}", imported.text); |
| 4506 | let cut = by_name(&mut server, "edit", json!({"ops": [{"op": "keep", "source": "src:0", "ranges": [["0s", "1.1s"]], "lane": "V1"}]})); |
| 4507 | assert!(!cut.is_error, "{}", cut.text); |
| 4508 | let locked = by_name(&mut server, "edit", json!({"ops": [{"op": "lane_flags", "lane": "V1", "locked": true}]})); |
| 4509 | assert!(!locked.is_error, "{}", locked.text); |
| 4510 | let steps = server.ledger.len(); |
| 4511 | |
| 4512 | let refused = by_name(&mut server, "project_settings", json!({"fps": 5})); |
| 4513 | assert!(refused.is_error, "{}", refused.text); |
| 4514 | assert!(refused.text.contains("locked lane V1") && refused.text.contains("force:true"), "{}", refused.text); |
| 4515 | assert_eq!(server.session.as_ref().unwrap().meta().frame_rate, 30.0, "nothing moved"); |
| 4516 | assert_eq!(server.ledger.len(), steps, "a refusal pushes no undo step"); |
| 4517 | |
| 4518 | // A whole multiple of the rate keeps every edge on its time: allowed on a locked lane. |
| 4519 | let doubled = by_name(&mut server, "project_settings", json!({"fps": 60})); |
| 4520 | assert!(!doubled.is_error, "{}", doubled.text); |
| 4521 | assert!(!doubled.text.contains("locked"), "{}", doubled.text); |
| 4522 | assert!(by_name(&mut server, "project_settings", json!({"fps": 30})).text.contains("fps 60 -> 30")); |
| 4523 | |
| 4524 | let forced = by_name(&mut server, "project_settings", json!({"fps": 5, "force": true})); |
| 4525 | assert!(!forced.is_error, "{}", forced.text); |
| 4526 | assert!(forced.text.contains("force:true moved the clips of locked lane V1"), "{}", forced.text); |
| 4527 | } |
| 4528 | |
| 4529 | /// A project_new folder that does not exist is made at project_new, so project_save later |
| 4530 | /// finds it. |
| 4531 | #[test] |
| 4532 | fn project_new_creates_its_folder_so_a_later_save_works() { |
| 4533 | engine::ao::set_silent_output(); |
| 4534 | let td = crate::testutil::TestDir::new("r29-new-folder"); |
| 4535 | let path = td.path().join("made").join("later").join("proj.edith"); |
| 4536 | let mut server = Server::new(); |
| 4537 | let made = run(&mut server, "project_new", json!({"path": path, "resolution": "1280x720"})); |
| 4538 | assert!(!made.is_error, "{}", made.text); |
| 4539 | assert!(made.text.contains("created the folder"), "{}", made.text); |
| 4540 | assert!(path.parent().is_some_and(Path::is_dir), "the folder exists"); |
| 4541 | let imported = run(&mut server, "media_import", json!({"paths": [asset("test_av.mp4").display().to_string()]})); |
| 4542 | assert!(!imported.is_error, "{}", imported.text); |
| 4543 | let saved = run(&mut server, "project_save", json!({})); |
| 4544 | assert!(!saved.is_error, "{}", saved.text); |
| 4545 | assert!(path.is_file()); |
| 4546 | } |
| 4547 | |
| 4548 | /// Item 2: dated autosaves are listed in the open reply with local time and what they |
| 4549 | /// change; `recover` with a file name or a stamp loads the chosen one; a bad name is refused |
| 4550 | /// with the names that exist. |
| 4551 | #[test] |
| 4552 | fn dated_autosaves_are_listed_and_one_is_recoverable_by_name_or_stamp() { |
| 4553 | let (td, path, _auto) = unrecovered("r12-dated"); |
| 4554 | let dated = td.path().join("proj.autosave-20260101-120000.edith"); |
| 4555 | std::fs::copy(&path, &dated).expect("a dated copy of the saved project"); |
| 4556 | |
| 4557 | // Before any dated recovery: recover: true still loads the project's own (newest) autosave. |
| 4558 | let mut newest = Server::new(); |
| 4559 | let rec = run(&mut newest, "project_open", json!({"path": path, "recover": true})); |
| 4560 | assert!(!rec.is_error, "{}", rec.text); |
| 4561 | assert_eq!(newest.session.as_ref().unwrap().sources().len(), 2, "recover: true stays the newest"); |
| 4562 | |
| 4563 | // A plain open is refused over the unloaded newest autosave. The dated copies are listed by |
| 4564 | // a recover, which also names the one it loads (the newest stays unloaded beside it). |
| 4565 | let mut by_stamp = Server::new(); |
| 4566 | assert!(run(&mut by_stamp, "project_open", json!({"path": path})).is_error); |
| 4567 | let rec = run(&mut by_stamp, "project_open", json!({"path": path, "recover": "20260101-120000"})); |
| 4568 | assert!(!rec.is_error, "{}", rec.text); |
| 4569 | // The replaced autosave is set aside as a dated copy too, so it is listed beside the chosen one. |
| 4570 | assert!(rec.text.contains("older autosaves (2;"), "{}", rec.text); |
| 4571 | let when = local_text(mtime(&dated).expect("mtime")); |
| 4572 | let entry = format!("proj.autosave-20260101-120000.edith (edits from {when}: no clip, lane, setting or source differs)"); |
| 4573 | assert!(rec.text.contains(&entry), "{}", rec.text); |
| 4574 | assert!(rec.text.contains("recovered the unsaved edits from"), "{}", rec.text); |
| 4575 | assert!(rec.text.contains("the dated copy stays beside it"), "{}", rec.text); |
| 4576 | assert_eq!(by_stamp.session.as_ref().unwrap().sources().len(), 1, "the chosen copy is loaded"); |
| 4577 | // The project's own autosave now holds the recovered copy, so nothing is left unloaded. |
| 4578 | assert!(!by_stamp.unrecovered_autosave, "the autosave is this session's recovered state"); |
| 4579 | assert!(dirty(&by_stamp)); |
| 4580 | |
| 4581 | let mut by_name = Server::new(); |
| 4582 | let rec = run(&mut by_name, "project_open", json!({"path": path, "recover": "proj.autosave-20260101-120000.edith"})); |
| 4583 | assert!(!rec.is_error, "{}", rec.text); |
| 4584 | // The recovered state now lives in the project's own autosave, which is what a save replaces. |
| 4585 | assert_eq!(by_name.recovered_autosave.as_deref(), Some(autosave_path(&path).as_path())); |
| 4586 | |
| 4587 | let mut bad = Server::new(); |
| 4588 | let refused = run(&mut bad, "project_open", json!({"path": path, "recover": "nope"})); |
| 4589 | assert!(refused.is_error, "{}", refused.text); |
| 4590 | assert!(refused.text.contains("no dated autosave named nope"), "{}", refused.text); |
| 4591 | assert!(refused.text.contains("proj.autosave-20260101-120000.edith"), "{}", refused.text); |
| 4592 | } |
| 4593 | |
| 4594 | /// Item 3: a relink by search is unsaved until a save writes the new paths. |
| 4595 | #[test] |
| 4596 | fn relink_by_search_marks_the_project_unsaved() { |
| 4597 | let td = TestDir::new("r12-relink"); |
| 4598 | std::fs::create_dir_all(td.path().join("media")).expect("media dir"); |
| 4599 | std::fs::create_dir_all(td.path().join("moved")).expect("moved dir"); |
| 4600 | std::fs::copy(asset("test_av.mp4"), td.path().join("media/test_av.mp4")).expect("copy"); |
| 4601 | let project = td.path().join("rel.edith"); |
| 4602 | let mut server = Server::new(); |
| 4603 | assert!(!run(&mut server, "project_new", json!({"path": project, "resolution": "1280x720"})).is_error); |
| 4604 | let media = td.path().join("media/test_av.mp4").display().to_string(); |
| 4605 | assert!(!run(&mut server, "media_import", json!({"paths": [media]})).is_error); |
| 4606 | assert!(run(&mut server, "project_save", json!({})).text.starts_with("saved")); |
| 4607 | std::fs::rename(td.path().join("media/test_av.mp4"), td.path().join("moved/test_av.mp4")).expect("move"); |
| 4608 | |
| 4609 | let mut fresh = Server::new(); |
| 4610 | let search = td.path().join("moved").display().to_string(); |
| 4611 | let opened = run(&mut fresh, "project_open", json!({"path": project, "search": [search]})); |
| 4612 | assert!(!opened.is_error, "{}", opened.text); |
| 4613 | assert!(opened.text.contains("relinked 1 source(s); save to keep the new paths"), "{}", opened.text); |
| 4614 | assert!(dirty(&fresh), "a relink is unsaved"); |
| 4615 | assert!(status_reply(&fresh).text.contains("dirty"), "{}", status_reply(&fresh).text); |
| 4616 | |
| 4617 | let saved = run(&mut fresh, "project_save", json!({})); |
| 4618 | assert!(!saved.is_error, "{}", saved.text); |
| 4619 | assert!(saved.text.contains("written with the 1 fix(es) made to open it: relinked 1 source(s) by name"), "{}", saved.text); |
| 4620 | assert!(std::fs::read_to_string(&project).expect("reread").contains("moved"), "the saved file has the new path"); |
| 4621 | assert!(!dirty(&fresh)); |
| 4622 | } |
| 4623 | |
| 4624 | /// `project_new {overwrite:true}` replaces the project, so the earlier session's autosave beside |
| 4625 | /// it is set aside as a dated copy: the next save is not refused over it. |
| 4626 | #[test] |
| 4627 | fn project_new_overwrite_sets_the_earlier_autosave_aside() { |
| 4628 | let (_td, path, auto) = unrecovered("p16-overwrite-auto"); |
| 4629 | let bytes = std::fs::read(&auto).expect("the autosave"); |
| 4630 | let mut server = Server::new(); |
| 4631 | let made = project_new(&mut server, &json!({"path": path, "overwrite": true, "resolution": "1280x720"})); |
| 4632 | assert!(!made.is_error, "{}", made.text); |
| 4633 | assert!(made.text.contains("set the earlier autosave"), "{}", made.text); |
| 4634 | assert!(made.text.contains("the copy is kept (the newest 3 dated copies and any from the last 7 days are kept; older ones are deleted)"), "{}", made.text); |
| 4635 | assert!(!auto.exists(), "the autosave moved aside"); |
| 4636 | let dated = dated_autosaves(&path); |
| 4637 | assert_eq!(dated.len(), 1, "{:?}", dated); |
| 4638 | assert!(made.text.contains(&dated[0].1.display().to_string()), "the reply names the copy: {}", made.text); |
| 4639 | assert_eq!(std::fs::read(&dated[0].1).expect("read the copy"), bytes, "the copy holds the same edits"); |
| 4640 | |
| 4641 | server.session.as_mut().unwrap().import(&asset("test_av.mp4")).expect("import"); |
| 4642 | let saved = project_save(&mut server, &json!({})); |
| 4643 | assert!(!saved.is_error, "{}", saved.text); |
| 4644 | assert!(saved.text.starts_with("saved "), "{}", saved.text); |
| 4645 | } |
| 4646 | |
| 4647 | /// Without overwrite the earlier autosave is not touched. |
| 4648 | #[test] |
| 4649 | fn project_new_without_overwrite_leaves_the_earlier_autosave_in_place() { |
| 4650 | let (_td, path, auto) = unrecovered("p16-no-overwrite"); |
| 4651 | let mut server = Server::new(); |
| 4652 | // The project file exists, so project_new refuses without overwrite; the autosave is untouched. |
| 4653 | let made = project_new(&mut server, &json!({"path": path, "resolution": "1280x720"})); |
| 4654 | assert!(made.is_error, "{}", made.text); |
| 4655 | let auto_path = autosave_path(&path).display().to_string(); |
| 4656 | assert!(made.text.starts_with(&format!("the autosave at {auto_path} from ")), "{}", made.text); |
| 4657 | assert!(made.text.contains("differs from the saved project by "), "{}", made.text); |
| 4658 | assert!(!made.text.contains("set the earlier autosave"), "{}", made.text); |
| 4659 | assert!(auto.is_file(), "the autosave is still there"); |
| 4660 | assert!(dated_autosaves(&path).is_empty()); |
| 4661 | assert!(server.session.is_none(), "nothing was created"); |
| 4662 | } |
| 4663 | |
| 4664 | /// `project_new` over an autosave with no project file: refused before anything is created, |
| 4665 | /// naming the autosave and its summary, with both ways on. `overwrite` then sets the autosave |
| 4666 | /// aside as a dated copy (kept), and the recover choice would have loaded it instead. |
| 4667 | #[test] |
| 4668 | fn project_new_refuses_an_autosave_without_a_file_and_overwrite_sets_it_aside() { |
| 4669 | engine::ao::set_silent_output(); |
| 4670 | let td = crate::testutil::TestDir::new("new-over-autosave"); |
| 4671 | let path = td.path().join("n.edith"); |
| 4672 | let mut earlier = Server::new(); |
| 4673 | assert!(!run(&mut earlier, "project_new", json!({"path": path, "resolution": "1280x720"})).is_error); |
| 4674 | earlier.session.as_mut().unwrap().import(&asset("test_av.mp4")).expect("import"); |
| 4675 | let auto = autosave_at_eof(&earlier).expect("the earlier session autosaves"); |
| 4676 | assert!(!path.exists(), "no project file, only the autosave"); |
| 4677 | |
| 4678 | let mut server = Server::new(); |
| 4679 | let refused = run(&mut server, "project_new", json!({"path": path, "resolution": "1280x720"})); |
| 4680 | assert!(refused.is_error, "{}", refused.text); |
| 4681 | // The comparison is named: with no project file, the autosave is read against an empty project. |
| 4682 | assert!(refused.text.starts_with(&format!("the autosave at {} from ", auto.display())), "{}", refused.text); |
| 4683 | assert!(refused.text.contains(&format!("differs from an empty project, since {} is not saved yet by +1 source(s)", path.display())), "{}", refused.text); |
| 4684 | assert!(refused.text.contains("project_open {\"path\": ") && refused.text.contains("\"recover\": true}"), "{}", refused.text); |
| 4685 | assert!(refused.text.contains("project_new {\"path\": ") && refused.text.contains("\"overwrite\": true}"), "{}", refused.text); |
| 4686 | assert!(server.session.is_none(), "nothing was created"); |
| 4687 | assert!(!path.exists() && auto.is_file(), "nothing was written or moved"); |
| 4688 | |
| 4689 | let fresh = run(&mut server, "project_new", json!({"path": path, "resolution": "1280x720", "overwrite": true})); |
| 4690 | assert!(!fresh.is_error, "{}", fresh.text); |
| 4691 | assert!(fresh.text.contains("set the earlier autosave"), "{}", fresh.text); |
| 4692 | assert!(!auto.exists(), "the autosave moved aside"); |
| 4693 | assert_eq!(dated_autosaves(&path).len(), 1, "one dated copy, kept"); |
| 4694 | } |
| 4695 | |
| 4696 | /// Dated copies are capped at the newest DATED_KEEP: a set-aside deletes the older ones and the |
| 4697 | /// reply says which were deleted. |
| 4698 | #[test] |
| 4699 | fn dated_autosave_copies_are_capped_and_the_deletions_are_named() { |
| 4700 | let (_td, path, auto) = unrecovered("p16-cap"); |
| 4701 | for day in 1u64..=4 { |
| 4702 | let old = path.with_file_name(format!("proj.autosave-2026010{day}-120000.edith")); |
| 4703 | std::fs::write(&old, b"x").unwrap(); |
| 4704 | let t = SystemTime::UNIX_EPOCH + Duration::from_secs(1_767_225_600 + day * 86_400); |
| 4705 | std::fs::File::options().write(true).open(&old).unwrap().set_modified(t).unwrap(); |
| 4706 | } |
| 4707 | let mut fresh = Server::new(); |
| 4708 | let opened = project_open(&mut fresh, &json!({"path": path, "discard_autosave": true})); |
| 4709 | assert!(!opened.is_error, "{}", opened.text); |
| 4710 | assert!(opened.text.contains("deleted 2 older dated autosave(s) beyond the newest 3"), "{}", opened.text); |
| 4711 | assert!(opened.text.contains("proj.autosave-20260101-120000.edith") && opened.text.contains("proj.autosave-20260102-120000.edith"), "{}", opened.text); |
| 4712 | let left: Vec<String> = dated_autosaves(&path).iter().map(|(_, p)| p.file_name().unwrap().to_string_lossy().into_owned()).collect(); |
| 4713 | assert_eq!(left.len(), DATED_KEEP, "{:?}", left); |
| 4714 | assert!(left.iter().any(|n| n.starts_with("proj.autosave-2026")) && !left.contains(&"proj.autosave-20260101-120000.edith".to_string())); |
| 4715 | assert!(!auto.exists()); |
| 4716 | assert!(opened.text.contains(&kept_name(&left)), "the new copy is among those kept: {}", opened.text); |
| 4717 | } |
| 4718 | |
| 4719 | /// A dated copy written within the last 7 days is kept even past the cap; an older one beyond it |
| 4720 | /// is deleted, and the reply says its edits are gone. |
| 4721 | #[test] |
| 4722 | fn a_recent_dated_copy_past_the_cap_is_kept_and_an_old_one_is_said_to_be_gone() { |
| 4723 | let (_td, path, auto) = unrecovered("p17-recent"); |
| 4724 | let now = SystemTime::now(); |
| 4725 | for (name, days) in [("recent-a", 1u64), ("recent-b", 2), ("recent-c", 3), ("old-d", 30)] { |
| 4726 | let copy = path.with_file_name(format!("proj.autosave-{name}.edith")); |
| 4727 | std::fs::write(©, b"x").unwrap(); |
| 4728 | let t = now - Duration::from_secs(days * 86_400); |
| 4729 | std::fs::File::options().write(true).open(©).unwrap().set_modified(t).unwrap(); |
| 4730 | } |
| 4731 | let mut fresh = Server::new(); |
| 4732 | let opened = project_open(&mut fresh, &json!({"path": path, "discard_autosave": true})); |
| 4733 | assert!(!opened.is_error, "{}", opened.text); |
| 4734 | assert!(opened.text.contains("deleted 1 older dated autosave(s)"), "{}", opened.text); |
| 4735 | assert!(opened.text.contains("proj.autosave-old-d.edith"), "{}", opened.text); |
| 4736 | assert!(opened.text.contains("Their unsaved edits are gone"), "{}", opened.text); |
| 4737 | let left: Vec<String> = dated_autosaves(&path).iter().map(|(_, p)| p.file_name().unwrap().to_string_lossy().into_owned()).collect(); |
| 4738 | assert_eq!(left.len(), 4, "the new copy and the three recent ones: {:?}", left); |
| 4739 | assert!(!left.iter().any(|n| n.contains("old-d")), "{:?}", left); |
| 4740 | assert!(!auto.exists()); |
| 4741 | } |
| 4742 | |
| 4743 | /// The name of the newest copy among `left`: the one just set aside has the latest stamp. |
| 4744 | fn kept_name(left: &[String]) -> String { |
| 4745 | left.iter().max().cloned().unwrap_or_default() |
| 4746 | } |
| 4747 | |
| 4748 | /// Item 4: an unsupported version names the versions this build reads. |
| 4749 | #[test] |
| 4750 | fn unsupported_version_names_the_versions_this_build_reads() { |
| 4751 | let td = TestDir::new("p16-version"); |
| 4752 | let path = td.path().join("old.edith"); |
| 4753 | std::fs::write(&path, b"edith 99\n").unwrap(); |
| 4754 | let mut server = Server::new(); |
| 4755 | let opened = project_open(&mut server, &json!({"path": path})); |
| 4756 | assert!(opened.is_error, "{}", opened.text); |
| 4757 | assert!(opened.text.contains(&format!("unsupported version 99; this edith reads project versions up to {}", engine::edith::NEWEST_VERSION)), "{}", opened.text); |
| 4758 | assert!(opened.text.contains(&path.display().to_string()), "the reply names the file: {}", opened.text); |
| 4759 | } |
| 4760 | |
| 4761 | /// Item 4: a garbage file gets the corrected grammar and the dated copies beside it as the way out. |
| 4762 | #[test] |
| 4763 | fn garbage_project_names_the_dated_copies_as_the_way_out() { |
| 4764 | let td = TestDir::new("p16-garbage"); |
| 4765 | let path = td.path().join("bad.edith"); |
| 4766 | std::fs::write(&path, b"not a project at all\n").unwrap(); |
| 4767 | let dated = td.path().join("bad.autosave-20260101-120000.edith"); |
| 4768 | std::fs::write(&dated, b"x").unwrap(); |
| 4769 | let mut server = Server::new(); |
| 4770 | let opened = project_open(&mut server, &json!({"path": path})); |
| 4771 | assert!(opened.is_error, "{}", opened.text); |
| 4772 | assert!(opened.text.contains("not an edith file"), "{}", opened.text); |
| 4773 | assert!(!opened.text.contains("not a edith"), "{}", opened.text); |
| 4774 | assert!(opened.text.contains("the way out is the dated autosaves bad.autosave-20260101-120000.edith"), "{}", opened.text); |
| 4775 | } |
| 4776 | |
| 4777 | /// Item 4: with no autosave or dated copy beside it, the way out is the checkpoints. |
| 4778 | #[test] |
| 4779 | fn empty_project_names_its_checkpoints_as_the_way_out() { |
| 4780 | let td = TestDir::new("p16-empty"); |
| 4781 | let path = td.path().join("empty.edith"); |
| 4782 | std::fs::write(&path, b"").unwrap(); |
| 4783 | let cps = td.path().join("checkpoints").join("empty"); |
| 4784 | std::fs::create_dir_all(&cps).unwrap(); |
| 4785 | std::fs::write(cps.join("before-cut.edith"), b"x").unwrap(); |
| 4786 | let mut server = Server::new(); |
| 4787 | let opened = project_open(&mut server, &json!({"path": path})); |
| 4788 | assert!(opened.is_error, "{}", opened.text); |
| 4789 | assert!(opened.text.contains("the way out is the checkpoints before-cut"), "{}", opened.text); |
| 4790 | } |
| 4791 | |
| 4792 | /// Item 5: a refused write names the folder to choose instead of a bare "Permission denied". |
| 4793 | #[test] |
| 4794 | fn a_permission_refusal_on_save_names_the_folder_to_choose() { |
| 4795 | let got = write_failure(Path::new("/ro/x.edith"), "Permission denied (os error 13)"); |
| 4796 | assert_eq!(got, "cannot write /ro/x.edith: permission denied; choose a folder you can write to"); |
| 4797 | assert!(write_failure(Path::new("/ro/x.edith"), "disk full").starts_with("save failed: could not write /ro/x.edith")); |
| 4798 | } |
| 4799 | |
| 4800 | /// Item 6: a relative path is resolved against the working directory and the reply says so. |
| 4801 | #[test] |
| 4802 | fn a_relative_path_is_shown_as_the_absolute_file_used() { |
| 4803 | let mut server = Server::new(); |
| 4804 | let made = project_new(&mut server, &json!({"path": "p16-rel-x.edith", "resolution": "1280x720"})); |
| 4805 | assert!(!made.is_error, "{}", made.text); |
| 4806 | let abs = std::env::current_dir().unwrap().join("p16-rel-x.edith"); |
| 4807 | assert!(made.text.contains(&format!("new project {}", abs.display())), "{}", made.text); |
| 4808 | assert!(made.text.contains("p16-rel-x.edith is a relative path; the file used is "), "{}", made.text); |
| 4809 | assert_eq!(server.path.as_deref(), Some(abs.as_path())); |
| 4810 | } |
| 4811 | |
| 4812 | /// The locked-lane note names each kept lane's moved addresses, and leaves out lanes whose times |
| 4813 | /// moved (the force warning covers those) and addresses that did not change. |
| 4814 | #[test] |
| 4815 | fn locked_address_note_names_the_moved_frame_addresses() { |
| 4816 | let v1 = Lane::V1; |
| 4817 | let a1 = Lane::A1; |
| 4818 | let before = vec![(v1, 100), (v1, 0), (a1, 50)]; |
| 4819 | let after = vec![(v1, 120), (v1, 0), (a1, 60)]; |
| 4820 | assert_eq!( |
| 4821 | locked_address_note(&before, &after, &[]).as_deref(), |
| 4822 | Some("locked lanes V1, A1 keep their times; their frame addresses change: V1@100→V1@120, A1@50→A1@60") |
| 4823 | ); |
| 4824 | // A lane whose times moved is named by the force warning, not here. |
| 4825 | assert_eq!( |
| 4826 | locked_address_note(&before, &after, &["A1".to_string()]).as_deref(), |
| 4827 | Some("locked lane V1 keeps its times; its frame addresses change: V1@100→V1@120") |
| 4828 | ); |
| 4829 | // Nothing changes address: no note. |
| 4830 | assert_eq!(locked_address_note(&before, &before, &[]), None); |
| 4831 | } |
| 4832 | |
| 4833 | /// Past eight moved addresses the note says how many it leaves out. |
| 4834 | #[test] |
| 4835 | fn locked_address_note_counts_the_addresses_it_leaves_out() { |
| 4836 | let before: Vec<(Lane, u32)> = (0..10).map(|i| (Lane::V1, i * 10)).collect(); |
| 4837 | let after: Vec<(Lane, u32)> = (0..10).map(|i| (Lane::V1, i * 12)).collect(); |
| 4838 | let note = locked_address_note(&before, &after, &[]).expect("a note"); |
| 4839 | assert!(note.ends_with("V1@80→V1@96, … (1 more)"), "{note}"); |
| 4840 | assert_eq!(note.matches('→').count(), ADDRESSES_SHOWN, "{note}"); |
| 4841 | } |
| 4842 | |
| 4843 | /// An exact fps change on a locked lane is allowed, says which addresses moved, and keeps the times. |
| 4844 | #[test] |
| 4845 | fn an_exact_fps_change_on_a_locked_lane_notes_its_new_addresses() { |
| 4846 | engine::ao::set_silent_output(); |
| 4847 | let td = crate::testutil::TestDir::new("r30-fps-note"); |
| 4848 | let path = td.path().join("proj.edith"); |
| 4849 | let mut server = Server::new(); |
| 4850 | assert!(!run(&mut server, "project_new", json!({"path": path})).is_error); |
| 4851 | let imported = run(&mut server, "media_import", json!({"paths": [asset("test_av.mp4").display().to_string()]})); |
| 4852 | assert!(!imported.is_error, "{}", imported.text); |
| 4853 | // One clip at 0 s and one at 2 s (frame 60 at 30 fps); the second moves to frame 120 at 60 fps. |
| 4854 | let first = run(&mut server, "edit", json!({"ops": [{"op": "keep", "source": "src:0", "ranges": [["0s", "1s"]], "lane": "V1"}]})); |
| 4855 | assert!(!first.is_error, "{}", first.text); |
| 4856 | let second = run(&mut server, "edit", json!({"ops": [{"op": "keep", "source": "src:0", "ranges": [["0s", "1s"]], "lane": "V1", "at": "2s"}]})); |
| 4857 | assert!(!second.is_error, "{}", second.text); |
| 4858 | let locked = run(&mut server, "edit", json!({"ops": [{"op": "lane_flags", "lane": "V1", "locked": true}]})); |
| 4859 | assert!(!locked.is_error, "{}", locked.text); |
| 4860 | |
| 4861 | let doubled = run(&mut server, "project_settings", json!({"fps": 60})); |
| 4862 | assert!(!doubled.is_error, "{}", doubled.text); |
| 4863 | assert!( |
| 4864 | doubled.text.contains("locked lane V1 keeps its times; its frame addresses change: V1@60→V1@120"), |
| 4865 | "{}", |
| 4866 | doubled.text |
| 4867 | ); |
| 4868 | assert!(!doubled.text.contains("warning"), "{}", doubled.text); |
| 4869 | let kept: Vec<(Lane, u32)> = locked_starts(server.session.as_ref().unwrap()); |
| 4870 | assert_eq!(kept, vec![(Lane::V1, 0), (Lane::V1, 120)], "the clips moved to the new frame numbers"); |
| 4871 | } |
| 4872 | |
| 4873 | /// A recovery names a dated autosave by its file name or by its stamp, collision suffix included. |
| 4874 | #[test] |
| 4875 | fn autosave_matches_takes_the_listed_file_name_or_its_stamp() { |
| 4876 | let auto = Path::new("/x/E.autosave-20261018-200851.edith"); |
| 4877 | assert!(autosave_matches(auto, "E.autosave-20261018-200851.edith")); |
| 4878 | assert!(autosave_matches(auto, "20261018-200851")); |
| 4879 | assert!(!autosave_matches(auto, "20261018-200844"), "the content time is not the stamp"); |
| 4880 | let second = Path::new("/x/E.autosave-20261018-200851-2.edith"); |
| 4881 | assert!(autosave_matches(second, "20261018-200851-2")); |
| 4882 | assert!(autosave_matches(second, "E.autosave-20261018-200851-2.edith")); |
| 4883 | } |
| 4884 | } |