forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

templates.rs447 lines, 18.7 KiBHistoryRawDownload
1//! Project templates: a named starting point for a new project. A template keeps the settings a
2//! project is started with -- frame rate, canvas size, the lanes and their names, the caption
3//! style and the export preset -- and, when asked, the clips too.
4//!
5//! A template file is `<name>.edith` in the user's data folder (`$XDG_DATA_HOME/edith/templates`,
6//! else `~/.local/share/edith/templates`). Its header lines hold the settings, so a template
7//! without clips needs no project body: a project file must name a source, and a template has
8//! none. A template with clips carries the project file after the header:
9//!
10//! ```text
11//! edith-template 1
12//! export youtube_1080p (or `export -` for none)
13//! clips no (or `clips yes`, and the project file follows the header)
14//! settings 1920 1080 30
15//! lane video
16//! lane audio Dialogue
17//! capstyle none ffffff 0 0 3
18//! ```
19//!
20//! The built-in templates ([`BUILTINS`]) are made in code and nothing is on disk for them.
21
22use std::path::{Path, PathBuf};
23use std::sync::atomic::{AtomicU64, Ordering};
24
25use crate::captionanim::{CaptionAnim, CaptionStyle};
26use crate::project::{Lane, LaneKind};
27use crate::PlaybackSession;
28
29/// The first line of a template file.
30const MAGIC: &str = "edith-template 1";
31/// The longest template name, in characters.
32pub const NAME_MAX: usize = 40;
33/// The export preset a template stores for "match the project" (the export sheet's Match project).
34pub const MATCH_PROJECT: &str = "match_project";
35
36/// A template made in code.
37#[derive(Clone, Copy, Debug, PartialEq)]
38pub struct Builtin {
39 pub name: &'static str,
40 pub width: u32,
41 pub height: u32,
42 pub fps: f64,
43 /// The export preset it starts on ([`crate::export_presets::by_id`]), `None` for the project's own.
44 pub export: Option<&'static str>,
45}
46
47/// The templates that ship with edith, in menu order.
48pub const BUILTINS: [Builtin; 3] = [
49 Builtin { name: "YouTube 1080p 30", width: 1920, height: 1080, fps: 30.0, export: Some("youtube_1080p") },
50 Builtin { name: "Vertical 1080\u{d7}1920 30", width: 1080, height: 1920, fps: 30.0, export: Some("shorts_reels") },
51 Builtin { name: "Square 1080 30", width: 1080, height: 1080, fps: 30.0, export: None },
52];
53
54/// One row of the template list.
55#[derive(Clone, Debug, PartialEq, Eq)]
56pub struct Info {
57 pub name: String,
58 /// Shipped with edith rather than saved by a person.
59 pub builtin: bool,
60 /// Whether the template carries clips as well as its settings.
61 pub clips: bool,
62}
63
64/// What a template opens as: the project and the export preset it names, if any.
65pub struct Opened {
66 pub session: PlaybackSession,
67 pub export: Option<String>,
68}
69
70/// The folder templates are kept in: `$XDG_DATA_HOME/edith/templates`, else under `~/.local/share`.
71pub fn dir() -> Option<PathBuf> {
72 Some(dir_in(&data_home()?))
73}
74
75/// The templates folder under the data folder `data` (what [`dir`] is for the user's own).
76pub fn dir_in(data: &Path) -> PathBuf {
77 data.join("edith").join("templates")
78}
79
80/// The user's data folder: `$XDG_DATA_HOME` when it is an absolute path, else `~/.local/share`.
81pub fn data_home() -> Option<PathBuf> {
82 std::env::var_os("XDG_DATA_HOME")
83 .filter(|v| !v.is_empty() && Path::new(v).is_absolute())
84 .map(PathBuf::from)
85 .or_else(|| std::env::var_os("HOME").filter(|h| !h.is_empty()).map(|h| PathBuf::from(h).join(".local").join("share")))
86}
87
88/// Whether `name` can name a template: 1 to 40 characters once trimmed, no path separators or
89/// control characters, not starting with a dot, and not the name of a built-in.
90pub fn valid_name(name: &str) -> bool {
91 let n = name.trim();
92 !n.is_empty()
93 && n.chars().count() <= NAME_MAX
94 && !n.starts_with('.')
95 && !n.chars().any(|c| matches!(c, '/' | '\\' | '\0') || c.is_control())
96 && !BUILTINS.iter().any(|b| b.name.eq_ignore_ascii_case(n))
97}
98
99/// The file a template named `name` is kept in.
100pub fn file(dir: &Path, name: &str) -> PathBuf {
101 dir.join(format!("{}.edith", name.trim()))
102}
103
104/// Every template: the built-ins first, then the saved ones by name. A folder that is missing is
105/// no saved templates, and a file that does not read as one is left out.
106pub fn list(dir: &Path) -> Vec<Info> {
107 let mut out: Vec<Info> = BUILTINS.iter().map(|b| Info { name: b.name.to_string(), builtin: true, clips: false }).collect();
108 let Ok(rd) = std::fs::read_dir(dir) else {
109 return out;
110 };
111 let mut saved: Vec<Info> = rd
112 .filter_map(|e| e.ok().map(|e| e.path()))
113 .filter(|p| p.extension().is_some_and(|x| x == "edith"))
114 .filter_map(|p| {
115 let name = p.file_stem()?.to_string_lossy().into_owned();
116 let text = std::fs::read_to_string(&p).ok()?;
117 let (head, _) = parse(&text).ok()?;
118 Some(Info { name, builtin: false, clips: head.clips })
119 })
120 .collect();
121 saved.sort_by(|a, b| a.name.to_lowercase().cmp(&b.name.to_lowercase()).then_with(|| a.name.cmp(&b.name)));
122 out.extend(saved);
123 out
124}
125
126/// Saves the open project as template `name` in `dir`, replacing one of that name. The settings
127/// are always kept. `keep_clips` also keeps the clips and their sources, and is ignored for a
128/// project with no sources (it has no clips to keep). `export` is the preset id the template starts
129/// on, `None` for none. Returns whether a template of that name was replaced.
130pub fn save(dir: &Path, s: &PlaybackSession, name: &str, keep_clips: bool, export: Option<&str>) -> crate::Result<bool> {
131 if !valid_name(name) {
132 return Err(format!("template name `{}` is not usable: 1 to 40 characters, no slashes, not a built-in's name", name.trim()).into());
133 }
134 if let Some(id) = export
135 && id != MATCH_PROJECT
136 && crate::export_presets::by_id(id).is_none()
137 {
138 return Err(format!("export preset `{id}` is not one edith has").into());
139 }
140 let clips = keep_clips && !s.sources().is_empty();
141 let (w, h) = s.resolution();
142 let lanes = s
143 .lanes()
144 .into_iter()
145 .filter(|l| l.kind != LaneKind::Subtitle)
146 .map(|l| (l.kind, s.lane_name(l).unwrap_or("").to_string()))
147 .collect();
148 let head = Head {
149 export: export.map(str::to_string),
150 clips,
151 width: w,
152 height: h,
153 fps: s.meta().frame_rate,
154 lanes,
155 caption: s.caption_style(),
156 };
157 let mut text = render(&head).into_bytes();
158 if clips {
159 text.extend_from_slice(&project_bytes(s, dir)?);
160 }
161 std::fs::create_dir_all(dir).map_err(|e| format!("cannot make {}: {e}", dir.display()))?;
162 let path = file(dir, name);
163 let replaced = path.exists();
164 crate::edith::write_atomic(&path, &text)?;
165 Ok(replaced)
166}
167
168/// The project a new one starts as: the built-in `name` made in code, or the saved template
169/// `name` in `dir`. Nothing is written. A template without clips is a project with no source, so
170/// it is not a project file yet.
171pub fn open(dir: &Path, name: &str) -> crate::Result<Opened> {
172 let (head, body) = load(dir, name)?;
173 let session = match body {
174 Some(bytes) => {
175 let work = scratch_dir(dir);
176 std::fs::create_dir_all(&work).map_err(|e| format!("cannot make {}: {e}", work.display()))?;
177 let scratch = work.join("body.edith");
178 let opened = std::fs::write(&scratch, &bytes)
179 .map_err(|e| format!("cannot read template {}: {e}", name.trim()))
180 .and_then(|()| PlaybackSession::open_project(&scratch).map_err(|e| e.to_string()));
181 let _ = std::fs::remove_dir_all(&work);
182 opened.map_err(|e| format!("template {} does not open: {e}", name.trim()))?
183 }
184 None => {
185 let mut s = PlaybackSession::empty(head.width, head.height, head.fps)?;
186 apply_lanes(&mut s, &head);
187 s.set_caption_style(head.caption);
188 s
189 }
190 };
191 Ok(Opened { session, export: head.export })
192}
193
194/// Puts the lanes, lane names and caption style of template `name` onto `s`, the way a project
195/// that has footage takes them when its first media arrives. Its canvas and rate are the caller's.
196/// Returns the export preset the template names. A template with clips is refused: its clips
197/// come with [`write_project`] only.
198pub fn apply(dir: &Path, name: &str, s: &mut PlaybackSession) -> crate::Result<Option<String>> {
199 let (head, body) = load(dir, name)?;
200 if body.is_some() {
201 return Err(format!("template {} has clips, so it starts a project of its own", name.trim()).into());
202 }
203 apply_lanes(s, &head);
204 s.set_caption_style(head.caption);
205 Ok(head.export)
206}
207
208/// Writes the project file template `name` starts as to `target`, for a template that carries
209/// clips (its sources come with it). Returns the export preset the template names. A template
210/// without clips is refused: its file appears with the first footage ([`apply`]).
211pub fn write_project(dir: &Path, name: &str, target: &Path) -> crate::Result<Option<String>> {
212 let (head, body) = load(dir, name)?;
213 let Some(body) = body else {
214 return Err(format!("template {} has no clips: its project is made with the first footage", name.trim()).into());
215 };
216 crate::edith::write_atomic(target, &body)?;
217 Ok(head.export)
218}
219
220/// The settings a template keeps, read off its header.
221struct Head {
222 export: Option<String>,
223 clips: bool,
224 width: u32,
225 height: u32,
226 fps: f64,
227 lanes: Vec<(LaneKind, String)>,
228 caption: CaptionStyle,
229}
230
231fn render(h: &Head) -> String {
232 let mut out = format!(
233 "{MAGIC}\nexport {}\nclips {}\nsettings {} {} {}\n",
234 h.export.as_deref().unwrap_or("-"),
235 if h.clips { "yes" } else { "no" },
236 h.width,
237 h.height,
238 h.fps
239 );
240 for (kind, name) in &h.lanes {
241 // A name is one line: a control character in it would end the lane's line.
242 let name: String = name.chars().map(|c| if c.is_control() { ' ' } else { c }).collect();
243 let line = if name.is_empty() { format!("lane {}\n", kind_word(*kind)) } else { format!("lane {} {name}\n", kind_word(*kind)) };
244 out.push_str(&line);
245 }
246 let [r, g, b] = h.caption.highlight;
247 out.push_str(&format!(
248 "capstyle {} {r:02x}{g:02x}{b:02x} {} {} {}\n",
249 h.caption.anim.name(),
250 u8::from(h.caption.hl_box),
251 u8::from(h.caption.uppercase),
252 h.caption.words_per_line
253 ));
254 out
255}
256
257fn kind_word(kind: LaneKind) -> &'static str {
258 match kind {
259 LaneKind::Video => "video",
260 LaneKind::Audio => "audio",
261 LaneKind::Subtitle => "subtitle",
262 }
263}
264
265/// The header of a template, and the project file bytes after it when it has clips.
266fn parse(text: &str) -> Result<(Head, Option<usize>), String> {
267 let mut lines = Vec::new();
268 let mut body_at = None;
269 let mut at = 0usize;
270 for line in text.split_inclusive('\n') {
271 if line.starts_with("edith ") {
272 body_at = Some(at);
273 break;
274 }
275 lines.push(line.trim_end_matches(['\n', '\r']));
276 at += line.len();
277 }
278 let mut it = lines.into_iter();
279 if it.next() != Some(MAGIC) {
280 return Err("not an edith template".into());
281 }
282 let export = it.next().and_then(|l| l.strip_prefix("export ")).ok_or("no export line")?;
283 let clips = match it.next().and_then(|l| l.strip_prefix("clips ")) {
284 Some("yes") => true,
285 Some("no") => false,
286 _ => return Err("no clips line".into()),
287 };
288 if clips != body_at.is_some() {
289 return Err("its clips line and its project do not agree".into());
290 }
291 let mut head = Head {
292 export: Some(export).filter(|e| *e != "-").map(str::to_string),
293 clips,
294 width: 0,
295 height: 0,
296 fps: 0.0,
297 lanes: Vec::new(),
298 caption: CaptionStyle::default(),
299 };
300 let mut have_settings = false;
301 for line in it {
302 if let Some(rest) = line.strip_prefix("settings ") {
303 let f: Vec<&str> = rest.split(' ').collect();
304 let (Some(w), Some(h), Some(fps)) = (f.first(), f.get(1), f.get(2)) else {
305 return Err("a settings line needs a width, height and rate".into());
306 };
307 head.width = w.parse().map_err(|_| "bad width")?;
308 head.height = h.parse().map_err(|_| "bad height")?;
309 head.fps = fps.parse().map_err(|_| "bad rate")?;
310 have_settings = true;
311 } else if let Some(rest) = line.strip_prefix("lane ") {
312 let (kind, name) = rest.split_once(' ').unwrap_or((rest, ""));
313 let kind = match kind {
314 "video" => LaneKind::Video,
315 "audio" => LaneKind::Audio,
316 other => return Err(format!("a lane of kind {other} is not one a template holds")),
317 };
318 head.lanes.push((kind, name.to_string()));
319 } else if let Some(rest) = line.strip_prefix("capstyle ") {
320 let f: Vec<&str> = rest.split(' ').collect();
321 let (Some(anim), Some(hex), Some(bx), Some(up), Some(wpl)) = (f.first(), f.get(1), f.get(2), f.get(3), f.get(4)) else {
322 return Err("a capstyle line needs five fields".into());
323 };
324 let channel = |i: usize| hex.get(i..i + 2).and_then(|c| u8::from_str_radix(c, 16).ok());
325 let (Some(r), Some(g), Some(b)) = (channel(0), channel(2), channel(4)) else {
326 return Err("a capstyle colour is six hex digits".into());
327 };
328 head.caption = CaptionStyle {
329 anim: CaptionAnim::from_name(anim).ok_or("unknown caption animation")?,
330 highlight: [r, g, b],
331 hl_box: *bx == "1",
332 uppercase: *up == "1",
333 words_per_line: wpl.parse().map_err(|_| "bad words per line")?,
334 };
335 }
336 }
337 if !have_settings {
338 return Err("no settings line".into());
339 }
340 Ok((head, body_at))
341}
342
343/// The header and, for a template with clips, the project file bytes after it.
344fn load(dir: &Path, name: &str) -> crate::Result<(Head, Option<Vec<u8>>)> {
345 if let Some(b) = BUILTINS.iter().find(|b| b.name == name) {
346 let head = Head {
347 export: b.export.map(str::to_string),
348 clips: false,
349 width: b.width,
350 height: b.height,
351 fps: b.fps,
352 lanes: vec![(LaneKind::Video, String::new()), (LaneKind::Audio, String::new())],
353 caption: CaptionStyle::default(),
354 };
355 return Ok((head, None));
356 }
357 let path = file(dir, name);
358 let bytes = std::fs::read(&path).map_err(|e| format!("no template named {}: {e}", name.trim()))?;
359 let text = String::from_utf8_lossy(&bytes);
360 let (head, body_at) = parse(&text).map_err(|e| format!("template {}: {e}", name.trim()))?;
361 Ok((head, body_at.map(|at| bytes[at..].to_vec())))
362}
363
364/// Adds the lanes of `h` that `s` lacks, in order, and names each lane. Lanes already there keep
365/// their clips; only the names are set.
366fn apply_lanes(s: &mut PlaybackSession, h: &Head) {
367 for (i, (kind, name)) in h.lanes.iter().enumerate() {
368 let ord = h.lanes[..i].iter().filter(|(k, _)| k == kind).count();
369 let lane = Lane::new(*kind, ord);
370 if !s.lanes().contains(&lane) {
371 let _ = s.add_lane(*kind);
372 }
373 if !name.is_empty() {
374 let _ = s.set_lane_name(lane, name);
375 }
376 }
377}
378
379/// The project file bytes of `s`, written through a scratch file.
380/// The project a clips template's body is written as, through a scratch folder of its own
381/// inside `dir`. Sources are written relative to the folder their project file is in when they sit
382/// inside it, so a folder that holds no media keeps every source path absolute: the body then
383/// reads the same from wherever it is copied to.
384fn project_bytes(s: &PlaybackSession, dir: &Path) -> crate::Result<Vec<u8>> {
385 let work = scratch_dir(dir);
386 std::fs::create_dir_all(&work).map_err(|e| format!("cannot make {}: {e}", work.display()))?;
387 let path = work.join("body.edith");
388 let written = s.save_project(&path);
389 let bytes = written.and_then(|()| std::fs::read(&path).map_err(Into::into));
390 let _ = std::fs::remove_dir_all(&work);
391 bytes
392}
393
394/// A scratch folder name no other call uses, inside the templates folder `dir`. Hidden, so a
395/// listing of the folder skips it.
396fn scratch_dir(dir: &Path) -> PathBuf {
397 static N: AtomicU64 = AtomicU64::new(0);
398 dir.join(format!(".work-{}-{}", std::process::id(), N.fetch_add(1, Ordering::Relaxed)))
399}
400
401#[cfg(test)]
402mod tests {
403 use super::*;
404 use crate::scratch::Scratch;
405
406 fn media() -> PathBuf {
407 Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/test_av.mp4")
408 }
409
410 /// One test for the whole feature: built-ins, settings-only templates (with lanes, names and
411 /// captions applied to footage), clips templates with absolute sources, and refusals.
412 #[test]
413 fn a_template_keeps_its_settings_and_clips_and_refuses_bad_input() {
414 let dir = Scratch::dir("tpl_round");
415 let vertical = open(&dir, "Vertical 1080×1920 30").expect("built-in opens");
416 assert_eq!((vertical.session.resolution(), vertical.session.meta().frame_rate), ((1080, 1920), 30.0));
417 assert!(open(&dir, "Nope").is_err());
418
419 let mut s = PlaybackSession::open(media()).expect("open test asset");
420 s.set_lane_name(Lane::A1, "Voice").expect("names a lane");
421 let _ = s.add_lane(LaneKind::Audio);
422 let styled = CaptionStyle { anim: CaptionAnim::Pop, uppercase: true, ..CaptionStyle::default() };
423 assert!(s.set_caption_style(styled));
424 let clips = crate::versions::clip_count(&s);
425 assert!(!save(&dir, &s, "Voices", false, Some("podcast")).expect("saves"));
426 let o = open(&dir, "Voices").expect("opens");
427 assert!(o.session.is_empty() && o.export.as_deref() == Some("podcast"));
428 assert_eq!(o.session.caption_style(), styled);
429 let mut fresh = PlaybackSession::open(media()).expect("open test asset");
430 apply(&dir, "Voices", &mut fresh).expect("applies");
431 assert_eq!(fresh.lane_name(Lane::A1), Some("Voice"));
432 assert_eq!(crate::versions::clip_count(&fresh), clips);
433
434 save(&dir, &s, "Full", true, None).expect("saves with clips");
435 let text = std::fs::read_to_string(file(&dir, "Full")).expect("reads");
436 let media_path = media().canonicalize().expect("media");
437 assert!(text.contains(&media_path.display().to_string()), "{text}");
438 let target = dir.join("Full-copy.edith");
439 write_project(&dir, "Full", &target).expect("writes");
440 assert_eq!(crate::versions::clip_count(&PlaybackSession::open_project(&target).expect("opens")), clips);
441
442 assert!(save(&dir, &s, "a/b", false, None).is_err());
443 assert!(save(&dir, &s, "Ok", false, Some("no_such_preset")).is_err());
444 std::fs::write(file(&dir, "junk"), "edith 51\n").unwrap();
445 assert!(!list(&dir).iter().any(|i| i.name == "junk"));
446 }
447}