forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

library.rs3550 lines, 160.9 KiBHistoryRawDownload
1//! What comes in and what goes out: the sources, the imports, the
2//! subtitles, the project file and the lanes.
3
4use crate::*;
5use crate::follow::{Follow, follow_decision};
6use crate::notices::{ToastAction, Tone, push_sticky_toast};
7use crate::player::project_dialogs::PathFor;
8
9/// Edits since the last autosave that make the next tick write without
10/// waiting for the timer.
11const AUTOSAVE_EDITS: u32 = 20;
12/// The autosave periods Settings offers, in seconds: `None` is Off, which writes no
13/// autosave at all. A missing or unreadable preference is one minute.
14pub(crate) const AUTOSAVE_CHOICES: [Option<u64>; 4] = [None, Some(30), Some(60), Some(300)];
15const AUTOSAVE_DEFAULT_SECS: u64 = 60;
16
17/// The least time between two autosaves that a structural edit asked for: a burst of new
18/// sequences or markers writes once, not once per click.
19const AUTOSAVE_THROTTLE: Duration = Duration::from_secs(5);
20
21/// The name of the one undo step a recovery takes: what Edit reads back as
22/// "Undo Recover unsaved edits".
23const RECOVER_STEP: &str = "Recover unsaved edits";
24
25/// The session a recovery installs: the saved file as it stands, with the
26/// autosave's timeline taken over on top of it as one undo step
27/// ([`PlaybackSession::adopt_as_step`]), so undo takes the recovered edits back
28/// to the saved timeline. With no saved file to stand on (`saved` is `None`, an
29/// untitled session) the autosave is the project and undo has nothing earlier
30/// to return to. Free of any `Player`, so a test can recover a file pair.
31pub(crate) fn recovered_session(
32 saved: Option<&Path>,
33 autosave: &Path,
34) -> Result<PlaybackSession, String> {
35 let autosaved = PlaybackSession::open_project(autosave).map_err(|e| e.to_string())?;
36 let Some(saved) = saved.filter(|p| p.is_file()) else {
37 return Ok(autosaved);
38 };
39 let mut session = PlaybackSession::open_project(saved).map_err(|e| e.to_string())?;
40 let mark = session.step_mark();
41 if session.adopt_as_step(&autosaved) {
42 session.name_step(mark, RECOVER_STEP);
43 Ok(session)
44 } else {
45 Err("the autosave does not fit on the saved project as one step".into())
46 }
47}
48
49/// Where the auto-proxies *default* survives, beside the keybindings and the
50/// theme, same corner-cut persistence as [`crate::subs::subtitle_style_path`]:
51/// a torn write costs this one preference and nothing else.
52///
53/// This is the window's own answer, not the project's: a project that was
54/// saved with the switch set already carries its own line
55/// ([`engine::edith::Document::auto_proxy`]) and always wins once one is
56/// open ([`Player::install_project`]) -- this file is only ever read before
57/// that, which is what makes it the difference between "the switch reverts to
58/// On on every relaunch" and "the switch stayed how it was left".
59/// The toasts for the clips a save had to shorten to their files' ends: one toast
60/// each, since a toast is one line that the window would cut off past its width.
61/// Past three, the rest are counted in one line.
62pub(crate) fn shortened_notes(notes: &[String]) -> Vec<String> {
63 const SHOWN: usize = 3;
64 let mut out: Vec<String> = notes.iter().take(SHOWN).cloned().collect();
65 if notes.len() > SHOWN {
66 out.push(format!("{} more clips were shortened to fit their files.", notes.len() - SHOWN));
67 }
68 out
69}
70
71pub(crate) fn auto_proxies_pref_path() -> PathBuf {
72 crate::keymap::Keymap::config_path().with_file_name("auto-proxies")
73}
74
75/// `Off` unless the file says `on`; missing, unreadable or garbled all read as
76/// `Off`, the same as [`load_proxies_pref`] -- a preference file is not the
77/// user's work, so a bad one is worth no message at startup.
78pub(crate) fn load_auto_proxies_pref() -> bool {
79 match std::fs::read_to_string(auto_proxies_pref_path()) {
80 Ok(text) => text.trim() == "on",
81 Err(_) => false,
82 }
83}
84
85/// Writes the pick whole, the way [`crate::ui::theme::save`] writes the
86/// palette.
87pub(crate) fn save_auto_proxies_pref(on: bool) -> std::io::Result<()> {
88 let path = auto_proxies_pref_path();
89 if let Some(dir) = path.parent() {
90 std::fs::create_dir_all(dir)?;
91 }
92 std::fs::write(path, if on { "on\n" } else { "off\n" })
93}
94
95/// Where the Proxies *default* survives -- Proxies' own sibling of
96/// [`auto_proxies_pref_path`], same corner-cut persistence.
97///
98/// This is the window's own answer, not the project's: a project saved with
99/// the switch set carries its own line and always wins once one is open
100/// ([`Player::install_project`]) -- this file is only ever read before that.
101/// The Settings word for one autosave period: `Off`, or how often it is written.
102pub(crate) fn autosave_label(secs: Option<u64>) -> String {
103 match secs {
104 None => "Off".to_string(),
105 Some(s) if s % 60 == 0 => format!("{} min", s / 60),
106 Some(s) => format!("Every {s} s"),
107 }
108}
109
110/// The small print beside one autosave period in its list.
111pub(crate) fn autosave_detail(secs: Option<u64>) -> &'static str {
112 match secs {
113 None => "unsaved edits are lost if edith quits",
114 Some(_) => "written beside the project while you work",
115 }
116}
117
118pub(crate) fn autosave_pref_path() -> PathBuf {
119 crate::keymap::Keymap::config_path().with_file_name("autosave")
120}
121
122/// The period the file names: `off` is `None`, a number of seconds is that period. Missing or
123/// garbled reads as one minute, the default, since a preference file is not the user's work.
124pub(crate) fn load_autosave_pref() -> Option<u64> {
125 match std::fs::read_to_string(autosave_pref_path()) {
126 Ok(text) => match text.trim() {
127 "off" => None,
128 n => Some(n.parse().unwrap_or(AUTOSAVE_DEFAULT_SECS)),
129 },
130 Err(_) => Some(AUTOSAVE_DEFAULT_SECS),
131 }
132}
133
134/// Writes the pick whole, the way [`save_proxies_pref`] does.
135pub(crate) fn save_autosave_pref(secs: Option<u64>) -> std::io::Result<()> {
136 let path = autosave_pref_path();
137 if let Some(dir) = path.parent() {
138 std::fs::create_dir_all(dir)?;
139 }
140 std::fs::write(path, secs.map_or("off\n".to_string(), |n| format!("{n}\n")))
141}
142
143pub(crate) fn proxies_pref_path() -> PathBuf {
144 crate::keymap::Keymap::config_path().with_file_name("proxies")
145}
146
147/// `Off` unless the file says `on`; missing, unreadable or garbled all read as
148/// `Off`, the same default the field has always started at -- a preference
149/// file is not the user's work, so a bad one is worth no message at startup.
150pub(crate) fn load_proxies_pref() -> bool {
151 match std::fs::read_to_string(proxies_pref_path()) {
152 Ok(text) => text.trim() == "on",
153 Err(_) => false,
154 }
155}
156
157/// Writes the pick whole, the way [`save_auto_proxies_pref`] does.
158pub(crate) fn save_proxies_pref(on: bool) -> std::io::Result<()> {
159 let path = proxies_pref_path();
160 if let Some(dir) = path.parent() {
161 std::fs::create_dir_all(dir)?;
162 }
163 std::fs::write(path, if on { "on\n" } else { "off\n" })
164}
165
166/// How long ago an autosave was written, in plain words: the recovery question's
167/// first half. Under a minute is "a moment ago"; a day back is "yesterday".
168/// Pure, so the words are tested without a file or a clock.
169pub(crate) fn age_words(secs: u64) -> String {
170 let ago = |n: u64, one: &str, many: &str| format!("{} ago", crate::notices::count_noun(n as usize, one, many));
171 match secs {
172 0..60 => "a moment ago".to_string(),
173 60..3600 => ago(secs / 60, "minute", "minutes"),
174 3600..86_400 => ago(secs / 3600, "hour", "hours"),
175 86_400..172_800 => "yesterday".to_string(),
176 _ => ago(secs / 86_400, "day", "days"),
177 }
178}
179
180/// The recovery question's words for an autosave: when its unsaved edits were
181/// written. The buttons carry the rest of the question.
182pub(crate) fn recovery_words(sidecar: &Path) -> String {
183 match std::fs::metadata(sidecar).and_then(|m| m.modified()) {
184 Ok(written) => recovery_words_at(written, std::time::SystemTime::now()),
185 Err(_) => "Unsaved edits were found".to_string(),
186 }
187}
188
189/// [`recovery_words`] for an autosave written at `written`, read at `now`: the
190/// local clock time it was written and how long ago that was, so "from 14:32
191/// (1 minute ago)" says both when and how recent. Pure but for the time zone.
192pub(crate) fn recovery_words_at(written: std::time::SystemTime, now: std::time::SystemTime) -> String {
193 let age = now.duration_since(written).map_or(0, |d| d.as_secs());
194 let clock = chrono::DateTime::<chrono::Local>::from(written).format("%H:%M");
195 format!("Unsaved edits from {clock} ({}) were found.", age_words(age))
196}
197
198/// The recovery toast's words once the window has edits of its own: recovering
199/// would replace them, and says so before the button is pressed.
200pub(crate) fn recovery_replaces_words() -> String {
201 "Recovering will replace the current edits · undo takes them back".to_string()
202}
203
204impl Player {
205 /// The lanes an insert of `path` writes, mirroring the choice
206 /// [`PlaybackSession::place_stream_at`] makes: a still goes on a video lane
207 /// alone, a song on an audio lane alone, and a picture takes its sound with
208 /// it (the grouped take on `V1`/`A1`, or the same-numbered pair for a named
209 /// further lane). With no lane named, a still and a picture land on `V1`
210 /// and a song on `A1`.
211 pub(crate) fn insert_lanes(path: &Path, onto: Option<Lane>) -> Vec<Lane> {
212 if engine::is_image(path) {
213 let lane = match onto {
214 Some(lane) if lane.kind == LaneKind::Video => lane,
215 _ => Lane::V1,
216 };
217 return vec![lane];
218 }
219 if engine::is_audio(path) {
220 let lane = match onto {
221 Some(lane) if lane.kind == LaneKind::Audio => lane,
222 _ => Lane::A1,
223 };
224 return vec![lane];
225 }
226 match onto {
227 Some(lane) if lane.ord > 0 => vec![lane, Lane::new(LaneKind::Audio, lane.ord)],
228 _ => vec![Lane::V1, Lane::A1],
229 }
230 }
231
232 /// The one way a library row reaches the timeline: the Add button and a row
233 /// dragged onto a lane both come here, so there is a single answer to what
234 /// "add this source" does. The whole source goes in as one grouped take at
235 /// `at` -- the frame the pointer let it go on, or the playhead for the
236 /// button, which names no place. It is the same insert a paste makes, so
237 /// everything after it moves along rather than being painted over. Reseeks
238 /// like every other edit, and drops the timeline's selection with it: the
239 /// insert has just moved the indices it pointed at.
240 /// Puts a source on the end of the timeline: the frame past the last clip on any lane, so
241 /// nothing is pushed and nothing is overwritten.
242 pub(crate) fn append_source(&mut self, path: &Path, stream: usize, cx: &mut Context<Self>) {
243 let end = self.session.as_ref().map(|s| (s.timeline_duration() * self.fps).round() as u32);
244 self.insert_source(path, stream, None, end, cx);
245 }
246
247 pub(crate) fn insert_source(
248 &mut self,
249 path: &Path,
250 stream: usize,
251 onto: Option<Lane>,
252 at: Option<u32>,
253 cx: &mut Context<Self>,
254 ) {
255 self.place_source(path, stream, onto, at, false, cx);
256 }
257
258 /// A library item let go on the bed: it **overwrites** what is under it for its length, and
259 /// nothing is pushed along, unless `insert` (Ctrl held) asks for the push
260 /// ([`insert_source`](Self::insert_source)). Refusals say why in a toast, as every placement does.
261 pub(crate) fn drop_source(
262 &mut self,
263 path: &Path,
264 stream: usize,
265 onto: Option<Lane>,
266 at: Option<u32>,
267 insert: bool,
268 cx: &mut Context<Self>,
269 ) {
270 self.place_source(path, stream, onto, at, !insert, cx);
271 }
272
273 /// A library item let go below the last lane, where there is no row to aim at: the
274 /// track it needs is made first, in the same undo step as the placement. A file with a
275 /// picture needs its video lane *and* the audio lane beside it, so both are made (`V2`
276 /// with `A2`, say), and a placement that is refused takes the new lanes back again, so no
277 /// empty track is ever left behind.
278 pub(crate) fn drop_source_below_lanes(
279 &mut self,
280 path: &Path,
281 stream: usize,
282 at: Option<u32>,
283 insert: bool,
284 cx: &mut Context<Self>,
285 ) {
286 if self.exporting().is_some() {
287 return;
288 }
289 let Some(session) = self.session.as_mut() else {
290 return;
291 };
292 session.begin_batch();
293 let lane = add_drop_lanes(session, path);
294 self.drop_source(path, stream, Some(lane), at, insert, cx);
295 let Some(session) = self.session.as_mut() else {
296 return;
297 };
298 let placed = !session.lane_clips(lane).is_empty();
299 session.end_batch();
300 if !placed {
301 // Refused: the batch holds nothing but the lanes just made, so one undo takes them back.
302 session.undo();
303 self.reset_after_reseek();
304 }
305 }
306
307 /// The one placement behind [`insert_source`](Self::insert_source) and
308 /// [`drop_source`](Self::drop_source): `overwrite` picks the engine door.
309 fn place_source(
310 &mut self,
311 path: &Path,
312 stream: usize,
313 onto: Option<Lane>,
314 at: Option<u32>,
315 overwrite: bool,
316 cx: &mut Context<Self>,
317 ) {
318 if self.exporting().is_some() {
319 return;
320 }
321 // The drop ends the hover: nothing is below the stack any more.
322 self.drag_below = false;
323 // The source monitor's own item, dragged by its picture or its row
324 // with marks set: the marked part goes, not the whole file.
325 if self.source_has_marks(path, stream) {
326 let kind = match overwrite {
327 true => engine::SourceEdit::Overwrite,
328 false => engine::SourceEdit::Insert,
329 };
330 self.source_edit_at(kind, at, onto, cx);
331 return;
332 }
333 // The lane the pointer named cannot hold this kind of file: refused by
334 // name, in the same words the ghost was tinted by on the way down
335 // ([`lane_refuses`]). The Add button names no lane and so is never
336 // refused here -- where a file goes when nobody says is the engine's
337 // choice, in `place_stream_at`, not one made twice here.
338 if let Some(why) = onto.and_then(|lane| lane_refuses(path, lane, self.has_video(path))) {
339 self.notify_user(why.into());
340 cx.notify();
341 return;
342 }
343 // A locked lane takes nothing, named or chosen: the Add button's pick
344 // and a drop onto a lane both write the lanes [`Self::insert_lanes`]
345 // names, and the one that is locked refuses the whole insert with its
346 // own toast before anything moves.
347 for lane in Self::insert_lanes(path, onto) {
348 if self.lane_locked_refusal(lane) {
349 cx.notify();
350 return;
351 }
352 }
353 // The engine's own length for the file, noted when the import took it
354 // in: a row that has never been on a lane is placeable at its full
355 // length, which is the whole point of an import that only fills the
356 // library.
357 let fps = self.fps;
358 let placed = match &mut self.session {
359 // Seconds, because that is what the engine's own door takes: the
360 // frame the pointer named goes back through the same rate every box
361 // on the bed is drawn at, so it lands on the frame it was let go on
362 // rather than a neighbouring one.
363 Some(session) => {
364 let at = at.map_or_else(|| session.now(), |frame| f64::from(frame) / fps);
365 match overwrite {
366 true => session.place_stream_overwrite_at(at, path, stream, onto),
367 false => session.place_stream_at(at, path, stream, onto),
368 }
369 }
370 None => Ok(false),
371 };
372 match placed {
373 Ok(true) => {
374 self.selected.clear();
375 self.reset_after_reseek();
376 }
377 // The engine's own words: a stream that cannot join this timeline
378 // says which property disagrees, exactly as a refused import does.
379 Err(e) => self.notify_user(format!("Nothing added: {e}").into()),
380 Ok(false) => {
381 self.notify_user("Nothing added: that file could not be placed here".into())
382 }
383 }
384 cx.notify();
385 }
386
387 /// `I`/`O` while a library item is previewed: the preview's playhead becomes
388 /// that item's in or out mark (the source monitor's marks), kept in order
389 /// the way the timeline's pair is.
390 pub(crate) fn mark_source(&mut self, is_in: bool, cx: &mut Context<Self>) {
391 let Some(preview) = &self.preview_session else {
392 return;
393 };
394 let Some(src) = preview.sources().first() else {
395 return;
396 };
397 let key = (src.path.clone(), src.audio_stream);
398 let at = preview.now();
399 let (mut a, mut b) = self.source_marks.get(&key).copied().unwrap_or((None, None));
400 if is_in {
401 a = Some(at);
402 } else {
403 b = Some(at);
404 }
405 if let (Some(x), Some(y)) = (a, b)
406 && x > y
407 {
408 (a, b) = (Some(y), Some(x));
409 }
410 self.source_marks.insert(key, (a, b));
411 cx.notify();
412 }
413
414 /// `ctrl+u` while a library item is previewed: lets go of that item's marks.
415 pub(crate) fn clear_source_marks(&mut self, cx: &mut Context<Self>) {
416 if let Some(src) = self.preview_session.as_ref().and_then(|p| p.sources().first()) {
417 self.source_marks.remove(&(src.path.clone(), src.audio_stream));
418 }
419 cx.notify();
420 }
421
422 /// The three-point edit (`F9` insert, `F10` overwrite): the library item
423 /// being previewed, or the last one that was, goes onto the timeline at the
424 /// playhead (the timeline's in mark when set) for its marked in..out -- the
425 /// whole item with no marks -- onto the first unlocked video and audio
426 /// lanes it has. Insert cuts the clip there and ripples the later ones on
427 /// those lanes; overwrite replaces what is there and moves nothing. One
428 /// undo step ([`PlaybackSession::edit_from_source_at`]); a locked lane or a
429 /// take it would pull apart refuses with the engine's words. On success the
430 /// preview closes (the timeline shows what was done) and the playhead
431 /// moves to the end of the new take, so the next press follows on.
432 pub(crate) fn source_edit(&mut self, kind: engine::SourceEdit, cx: &mut Context<Self>) {
433 self.source_edit_at(kind, None, None, cx);
434 }
435
436 /// Whether `(path, stream)` is the source monitor's item and has a mark.
437 fn source_has_marks(&self, path: &Path, stream: usize) -> bool {
438 self.preview_session.is_some()
439 && self.source_target.as_ref().is_some_and(|(p, s)| p == path && *s == stream)
440 && self
441 .source_marks
442 .get(&(path.to_path_buf(), stream))
443 .is_some_and(|(a, b)| a.is_some() || b.is_some())
444 }
445
446 /// [`Self::source_edit`] at a given frame and onto a given lane (a drop),
447 /// else at the playhead on the first free lanes.
448 pub(crate) fn source_edit_at(
449 &mut self,
450 kind: engine::SourceEdit,
451 drop_at: Option<u32>,
452 onto: Option<Lane>,
453 cx: &mut Context<Self>,
454 ) {
455 if self.exporting().is_some() {
456 return;
457 }
458 let verb = match kind {
459 engine::SourceEdit::Insert => "Insert",
460 engine::SourceEdit::Overwrite => "Overwrite",
461 };
462 let target = self
463 .preview_session
464 .as_ref()
465 .and_then(|p| p.sources().first().map(|s| (s.path.clone(), s.audio_stream)))
466 .or_else(|| self.source_target.clone());
467 let Some((path, stream)) = target else {
468 self.notify_user(
469 format!("{verb}: no library item has been previewed").into(),
470 );
471 cx.notify();
472 return;
473 };
474 let Some(session) = &self.session else {
475 return;
476 };
477 let canon = |p: &Path| std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf());
478 let want = canon(&path);
479 let Some(source) = session
480 .sources()
481 .iter()
482 .position(|s| s.audio_stream == stream && (s.path == path || canon(&s.path) == want))
483 else {
484 self.notify_user(format!("{verb}: {} is not in this project", file_name(&path)).into());
485 cx.notify();
486 return;
487 };
488 let fps = self.fps;
489 let still = engine::is_image(&path);
490 let picture = still || (!engine::is_audio(&path) && engine::probe_media(&path).video.is_some());
491 let sound = !still
492 && engine::AudioSession::probe_streams(&path).is_ok_and(|streams| streams.len() > stream);
493 let total = if picture {
494 session.file_frames(&path)
495 } else {
496 engine::AudioSession::stream_duration_secs(&path, stream)
497 .ok()
498 .flatten()
499 .map_or(0, |secs| (secs * fps).ceil() as u32)
500 };
501 let lanes: Vec<(Lane, bool)> = session
502 .lanes()
503 .into_iter()
504 .filter(|l| l.kind != LaneKind::Subtitle)
505 .map(|l| (l, session.lane_locked(l)))
506 .collect();
507 let ask = SourceEditAsk {
508 fps,
509 lanes: &lanes,
510 playhead: drop_at.unwrap_or_else(|| frame_at(session.now(), fps)),
511 range: self.range.filter(|_| drop_at.is_none()),
512 marks: self.source_marks.get(&(path.clone(), stream)).copied().unwrap_or((None, None)),
513 source,
514 total,
515 picture: picture && self.source_video,
516 sound: sound && self.source_audio,
517 still,
518 video_patch: Some(self.patch_video),
519 audio_patch: Some(self.patch_audio),
520 };
521 let (at, items) = match plan_source_edit(&ask) {
522 Ok((at, mut items)) => {
523 // A drop names its lane: the half of that kind goes there.
524 if let Some(lane) = onto
525 && !lanes.iter().any(|(l, locked)| *l == lane && *locked)
526 && let Some(item) = items.iter_mut().find(|(l, _)| l.kind == lane.kind)
527 {
528 item.0 = lane;
529 }
530 (at, items)
531 }
532 Err(why) => {
533 self.notify_user(format!("{verb}: {why}").into());
534 cx.notify();
535 return;
536 }
537 };
538 let len = items.iter().map(|(_, c)| c.frames()).max().unwrap_or(0);
539 let done = match self.session.as_mut() {
540 Some(session) => session.edit_from_source_at(kind, f64::from(at) / fps, &items),
541 None => return,
542 };
543 match done {
544 Ok(()) => {
545 self.selected.clear();
546 self.reset_after_reseek();
547 self.mark_dirty();
548 // The source monitor stays up, ready for the next edit; only
549 // the timeline's playhead moves, to the end of the new take.
550 if let Some(session) = self.session.as_mut() {
551 session.seek(f64::from(at + len) / fps);
552 }
553 self.reset_after_reseek();
554 let (word, where_) = match kind {
555 engine::SourceEdit::Insert => ("Inserted", "rippling what follows"),
556 engine::SourceEdit::Overwrite => ("Overwrote", "nothing moved"),
557 };
558 self.notify_user(
559 format!(
560 "{word} {} at {} for {}: {where_}; ctrl+z undoes it",
561 file_name(&path),
562 timecode(f64::from(at) / fps, fps),
563 timecode(f64::from(len) / fps, fps),
564 )
565 .into(),
566 );
567 }
568 Err(e) => self.notify_user(format!("{verb} refused: {e}").into()),
569 }
570 cx.notify();
571 }
572
573 /// Paints a sliding waveform of the marked audio clip onto a video lane.
574 /// Same implementation the clip menu and the `h` stroke both reach.
575 pub(crate) fn create_visualizer(&mut self, cx: &mut Context<Self>) {
576 if self.exporting().is_some() {
577 return;
578 }
579 let Some((lane, idx)) = self.selected.anchor() else {
580 self.notify_user("No visualizer: select a clip with sound".into());
581 cx.notify();
582 return;
583 };
584 let placed = match &mut self.session {
585 None => {
586 self.notify_user("No visualizer: no file open".into());
587 cx.notify();
588 return;
589 }
590 Some(session) => {
591 let Some(clip) = session.lane_clips(lane).get(idx).cloned() else {
592 self.notify_user("No visualizer: select a clip with sound".into());
593 cx.notify();
594 return;
595 };
596 let Some(src) = session.sources().get(clip.source).cloned() else {
597 self.notify_user("No visualizer: that clip has no source".into());
598 cx.notify();
599 return;
600 };
601 session.place_visualizer(
602 clip.start,
603 &src.path,
604 src.audio_stream,
605 clip.in_frame,
606 clip.out_frame,
607 None,
608 )
609 }
610 };
611 match placed {
612 Ok(true) => {
613 self.notify_user("Visualizer added".into());
614 self.reset_after_reseek();
615 }
616 Err(e) => self.notify_user(format!("No visualizer: {e}").into()),
617 Ok(false) => self.notify_user("No visualizer: that clip could not be placed".into()),
618 }
619 cx.notify();
620 }
621
622 pub(crate) fn toggle_viz_flag(&mut self, bit: u8, cx: &mut Context<Self>) {
623 let Some((lane, idx)) = self.selected.anchor() else {
624 return;
625 };
626 let Some(session) = &mut self.session else {
627 return;
628 };
629 let Some(clip) = session.lane_clips(lane).get(idx).cloned() else {
630 return;
631 };
632 if clip.visualizer & 1 == 0 {
633 return;
634 }
635 if session.set_visualizer(lane, idx, clip.visualizer ^ bit) {
636 // A look is a project field, so the write arms autosave and the
637 // close prompt the same way a grade or a trim does -- these chips
638 // are clicked, not dispatched through `act`, so nothing upstream
639 // has armed it for them.
640 self.mark_dirty();
641 self.reset_after_reseek();
642 }
643 cx.notify();
644 }
645
646 pub(crate) fn set_viz_style(&mut self, style: u8, cx: &mut Context<Self>) {
647 let Some((lane, idx)) = self.selected.anchor() else {
648 return;
649 };
650 let Some(session) = &mut self.session else {
651 return;
652 };
653 let Some(clip) = session.lane_clips(lane).get(idx).cloned() else {
654 return;
655 };
656 if clip.visualizer & 1 == 0 {
657 return;
658 }
659 let next = engine::decode::with_viz_style(clip.visualizer, style);
660 if next != clip.visualizer && session.set_visualizer(lane, idx, next) {
661 // [`Self::toggle_viz_flag`]'s own reason: a clicked look arms
662 // autosave here, because nothing upstream has.
663 self.mark_dirty();
664 self.reset_after_reseek();
665 }
666 cx.notify();
667 }
668
669 pub(crate) fn viz_paint(&self) -> u64 {
670 self.selected
671 .anchor()
672 .and_then(|(lane, idx)| {
673 self.session
674 .as_ref()?
675 .lane_clips(lane)
676 .get(idx)
677 .map(|c| c.viz_paint)
678 })
679 .unwrap_or(0)
680 }
681
682 /// Which of the two inks the look section's wheel and colour field act on
683 /// ([`VizSlot`]). An open colour field is given up with the change: it is
684 /// seeded with the picked slot's colour, so it would otherwise edit a
685 /// colour the row is no longer showing.
686 pub(crate) fn set_viz_slot(&mut self, slot: VizSlot, cx: &mut Context<Self>) {
687 self.viz_slot = slot;
688 self.viz_hex_edit = None;
689 cx.notify();
690 }
691
692 /// Opens the colour type-in on `seed`, the picked slot's colour as the row
693 /// already shows it, so a backspace edits that rather than a field opening
694 /// empty over a colour still in force (the number field's own rule). The
695 /// transition row's field is given up: one inline editor at a time.
696 pub(crate) fn edit_viz_hex(&mut self, seed: &str) {
697 self.transition_edit = None;
698 self.viz_hex_edit = Some(ColorEdit::new(seed));
699 }
700
701 /// The colour field's enter. A colour it can read is written on the picked
702 /// slot -- one undo step, a typed colour being one edit -- and the field
703 /// closes. Anything else is refused *in words* with the field left open and
704 /// the colour where it was, so the next try is a backspace away.
705 pub(crate) fn commit_viz_hex(&mut self, cx: &mut Context<Self>) {
706 let Some((hue, sat)) = self.viz_hex_edit.as_mut().and_then(|edit| edit.commit()) else {
707 // Refused in words: the field stays open holding what it could
708 // not read.
709 cx.notify();
710 return;
711 };
712 self.viz_hex_edit = None;
713 // Nothing changed is not an edit. The field opens seeded with the
714 // row's own `viz_color_hex`, and that hex reads back as a *different*
715 // (hue, sat) for a large share of inks (the engine's round-trip
716 // canary counts 47 053 of 65 536 exact), so a commit that wrote
717 // whatever it parsed would take an undo step -- and arm autosave --
718 // for the colour the row was already showing, on an enter that
719 // changed nothing.
720 let paint = self.viz_paint();
721 let slot = self.viz_slot.picked(paint);
722 if slot.hue_sat(paint) == (hue, sat) {
723 cx.notify();
724 return;
725 }
726 self.write_viz_hs(hue, sat, false, cx);
727 }
728
729 /// Puts hue and saturation on the picked slot ([`VizSlot::picked`]): the
730 /// wheel's sample and the colour field's commit both land here, so the two
731 /// doors cannot disagree about which ink they write.
732 ///
733 /// `live` is [`Player::write_color`]'s own flag, for the colour card's
734 /// reason: the false one takes the undo step the whole gesture rolls back
735 /// to, the true one is every sample *inside* a drag
736 /// (`PlaybackSession::set_viz_paint_live`). A wheel sample is not a table
737 /// entry but the painter's own input, and it is the write that rebuilds the
738 /// picture at the playhead -- so one committed entry per pointer sample
739 /// would stamp a sixty-entry gesture into a hundred-step history and leave
740 /// the user a hundred-step history of one drag.
741 pub(crate) fn write_viz_hs(&mut self, hue: u8, sat: u8, live: bool, cx: &mut Context<Self>) {
742 // A write supersedes whatever a drag was holding
743 // ([`Player::write_color`]'s rule).
744 self.pending_viz = None;
745 let slot = self.viz_slot;
746 self.set_viz_paint_with(live, move |p| slot.picked(p).set_hue_sat(p, hue, sat), cx);
747 }
748
749 /// One pointer sample on the wheel, as the hue and saturation under it.
750 /// `first` is the press, which is never held: it is the pick the gesture
751 /// rolls back to, so it has to be taken against the ink the hand picked up.
752 /// Every sample after it goes through [`stash_or_write`] -- a wheel sample
753 /// is not a table entry but the painter's input, so the write is what
754 /// rebuilds the whole picture at the playhead, and a sweep that wrote each
755 /// one would queue a reopen per pixel, cancel all but one and freeze the
756 /// window for the sum.
757 pub(crate) fn drag_viz_hs(
758 &mut self,
759 at: gpui::Point<Pixels>,
760 first: bool,
761 cx: &mut Context<Self>,
762 ) {
763 let b = self.viz_wheel.get();
764 let w = f32::from(b.size.width).max(1.);
765 let h = f32::from(b.size.height).max(1.);
766 let dx = f32::from(at.x - b.origin.x) - w / 2.;
767 let dy = h / 2. - f32::from(at.y - b.origin.y);
768 let radius = w.min(h) / 2.;
769 let r = (dx * dx + dy * dy).sqrt() / radius;
770 let sat = (r.clamp(0., 1.) * 255.).round() as u8;
771 let ang = dx.atan2(dy).to_degrees();
772 let hue_deg = (ang + 360.) % 360.;
773 let hue = (hue_deg / 360. * 256.).round() as u16 as u8;
774 // The slot is read once, at the sample that carries it: whichever ink
775 // the hand picked up is the one the whole gesture writes, and the slot
776 // is what the held sample draws with while the worker catches up.
777 let slot = self.viz_slot.picked(self.viz_paint());
778 let busy = self.seek_since.is_some();
779 match stash_or_write(&mut self.pending_viz, (slot, hue, sat), first, busy) {
780 Some((_, hue, sat)) => self.write_viz_hs(hue, sat, !first, cx),
781 // The wheel draws off the held sample, so the mark goes on
782 // following the hand while the picture catches up.
783 None => cx.notify(),
784 }
785 }
786
787 pub(crate) fn set_viz_strands(&mut self, n: u8, cx: &mut Context<Self>) {
788 self.set_viz_paint_with(false, |p| engine::decode::with_viz_paint_strands(p, n), cx);
789 }
790
791 pub(crate) fn set_viz_glow(&mut self, n: u8, cx: &mut Context<Self>) {
792 self.set_viz_paint_with(false, |p| engine::decode::with_viz_paint_glow(p, n), cx);
793 }
794
795 /// `live` picks the door, as [`Player::write_viz_hs`] does: the strands and
796 /// glow steppers are presses and take their own undo step, and the two are
797 /// on the packed bytes rather than on either ink, so they are unaffected by
798 /// which slot the wheel is on.
799 fn set_viz_paint_with(
800 &mut self,
801 live: bool,
802 f: impl FnOnce(u64) -> u64,
803 cx: &mut Context<Self>,
804 ) {
805 let Some((lane, idx)) = self.selected.anchor() else {
806 return;
807 };
808 let Some(session) = &mut self.session else {
809 return;
810 };
811 let Some(clip) = session.lane_clips(lane).get(idx).cloned() else {
812 return;
813 };
814 if clip.visualizer & 1 == 0 {
815 return;
816 }
817 let next = f(clip.viz_paint);
818 if next != clip.viz_paint {
819 let took = match live {
820 true => session.set_viz_paint_live(lane, idx, next),
821 false => session.set_viz_paint(lane, idx, next),
822 };
823 if took {
824 // Every look write arms autosave and the close gate
825 // (`write_color`'s own rule, and these doors have no keymap
826 // action behind them to arm it the way `act` does for the
827 // verbs): the wheel's press, a strands/glow stepper and a
828 // typed colour all land here. The drag's live samples land
829 // here too, which is why the arm is on the write and not on
830 // the gesture -- `mark_dirty` is idempotent, so the press, the
831 // samples and the release are one armed edit rather than
832 // sixty.
833 self.mark_dirty();
834 self.reset_after_reseek();
835 }
836 }
837 cx.notify();
838 }
839
840 /// Takes a library row's file out of the list, which is the one thing a row
841 /// can lose. Refused in the engine's own words while clips still play from
842 /// it -- and those words name the lanes holding them, so the refusal says
843 /// what to delete first. The list itself is the report that it worked: the
844 /// row is gone from it.
845 pub(crate) fn remove_source(&mut self, path: &Path, stream: usize, cx: &mut Context<Self>) {
846 if self.exporting().is_some() {
847 return;
848 }
849 let removed = self
850 .session
851 .as_mut()
852 .map(|session| session.remove_source(path, stream));
853 let text = match removed {
854 Some(Ok(idx)) => {
855 // Tells a running background scan of this source nobody wants
856 // its levels any more, and drops the entry that was standing
857 // in the way of a re-add starting a fresh one
858 // ([`Player::cache_media`]'s dedupe reads presence here).
859 if let Some(scan) = self.silence_bg.remove(&(path.to_path_buf(), stream)) {
860 scan.cancel
861 .store(true, std::sync::atomic::Ordering::Relaxed);
862 }
863 // The picked row may be the one that just went, and the engine
864 // reseeks, so this owes the flag reset like every other edit.
865 if self.selected_asset.as_ref() == Some(&(path.to_path_buf(), stream)) {
866 self.selected_asset = None;
867 }
868 self.asset_picks.retain(|r| *r != (path.to_path_buf(), stream));
869 // A copied clip names its source by *index*, and every index
870 // past the one that went has just moved down: without this the
871 // next paste puts some other file on the timeline.
872 self.clipboard = clipboard_after_remove(std::mem::take(&mut self.clipboard), idx);
873 // The library is project state, and this door is the row's
874 // own menu click -- nothing in [`Player::act`]'s list arms
875 // it. Behind the `Ok`, so a refusal (the engine's own words
876 // while clips still play the file) is not an edit.
877 self.mark_dirty();
878 self.reset_after_reseek();
879 // The last row leaves a session naming no file: nothing to
880 // play, nothing to save and nothing to show, which is the empty
881 // window the editor launches as. The next import scaffolds a
882 // fresh timeline from whatever file it is, at that file's own
883 // rate -- which is why the session goes rather than lingering
884 // on with the gone file's parameters.
885 match self
886 .session
887 .as_ref()
888 .is_some_and(|s| s.sources().is_empty())
889 {
890 true => {
891 self.close_session();
892 format!("Removed {}: the library is empty", file_name(path))
893 }
894 // The undo stack goes with it (`Project::remove_source`):
895 // said here, because a `z` that does nothing afterwards
896 // would otherwise read as a bug.
897 false => format!("Removed {}: there is nothing left to undo", file_name(path)),
898 }
899 }
900 Some(Err(e)) => format!("Not removed: {e}"),
901 None => "No timeline: no file open".to_string(),
902 };
903 self.notify_user(text.into());
904 cx.notify();
905 }
906
907 /// Removes a library row *and* every clip playing it, in that order --
908 /// the plain [`Player::remove_source`] is refused by the engine while any
909 /// clip still plays a source, which left a placed file with no reachable
910 /// way out of the library at all (user 2026-08-21: "can not remove a
911 /// media from library"). Destructive, and named so on the plate it is
912 /// picked from; one undo entry per deleted clip, exactly as deleting them
913 /// by hand would leave, and then the source itself goes the same door
914 /// every other removal takes.
915 pub(crate) fn remove_source_and_clips(
916 &mut self,
917 path: &Path,
918 stream: usize,
919 cx: &mut Context<Self>,
920 ) {
921 if self.exporting().is_some() {
922 return;
923 }
924 let Some(session) = self.session.as_mut() else {
925 self.notify_user("No timeline: no file open".into());
926 return;
927 };
928 let Some(idx) = session
929 .sources()
930 .iter()
931 .position(|s| s.path == path && s.audio_stream == stream)
932 else {
933 return;
934 };
935 // One clip at a time, re-scanning after each: deleting a clip takes
936 // its group partners (a V1 picture and its A1 sound) with it, so a
937 // list of indices collected up front goes stale the moment the first
938 // one lands -- and a stale index deletes some other film's clip.
939 // Bounded by the count that was there when we started, so a
940 // `delete_clip` that ever answers false cannot spin here.
941 let count_of = |session: &engine::PlaybackSession| {
942 session
943 .lanes()
944 .into_iter()
945 .flat_map(|lane| session.lane_clips(lane))
946 .filter(|c| c.source == idx)
947 .count()
948 };
949 let started_with = count_of(session);
950 let mut budget = session
951 .lanes()
952 .into_iter()
953 .flat_map(|lane| session.lane_clips(lane))
954 .filter(|c| c.source == idx)
955 .count();
956 while budget > 0 {
957 let Some((lane, at)) = session.lanes().into_iter().find_map(|lane| {
958 session
959 .lane_clips(lane)
960 .iter()
961 .position(|c| c.source == idx)
962 .map(|at| (lane, at))
963 }) else {
964 break;
965 };
966 if !session.delete_clip(lane, at) {
967 break;
968 }
969 budget -= 1;
970 }
971 // What actually left the bench, not how many calls it took: one
972 // `delete_clip` on a grouped clip takes its partner with it.
973 let deleted = started_with.saturating_sub(count_of(session));
974 self.reset_after_reseek();
975 self.remove_source(path, stream, cx);
976 // `remove_source` already wrote its own line; this one says what went
977 // with it, which is the half that line cannot know about.
978 if deleted > 0 {
979 self.notify_user(
980 format!(
981 "{deleted} clip{} deleted with {}",
982 if deleted == 1 { "" } else { "s" },
983 file_name(path)
984 )
985 .into(),
986 );
987 }
988 cx.notify();
989 }
990
991 /// Back to the window the editor launches as: no timeline, no library, no
992 /// picture -- and the hint that says to open a file. What removing the last
993 /// library row leaves, since a session whose library is empty has nothing
994 /// left to be ([`Player::remove_source`]).
995 ///
996 /// Everything a *loaded project* resets goes here for its reasons (an index
997 /// into a timeline that is gone names nothing), plus the three per-file
998 /// caches: they are keyed by path, and the next file to arrive fills them
999 /// again.
1000 pub(crate) fn close_session(&mut self) {
1001 self.session = None;
1002 self.session_swapped();
1003 // The picture goes with it, or the empty window would keep showing the
1004 // last frame of a timeline that no longer exists.
1005 //
1006 // corner-cut: its atlas tile is not released -- `window.drop_image` wants
1007 // a `&mut Window` this door has no other reason to take. One tile per
1008 // emptied library, against one per displayed frame in `pump`; the
1009 // upgrade path is threading the window through `act_on_row`.
1010 self.image = None;
1011 // The drawn cue with it, and its tile for the same reason as above.
1012 self.sub_image = None;
1013 self.clipboard.clear();
1014 self.selected.clear();
1015 self.selected_asset = None;
1016 self.asset_picks.clear();
1017 // The subtitle rows go with the timeline they were on, and so does the
1018 // lane that was shown: S1 of one project is not S1 of the next.
1019 self.sub_track = 0;
1020 self.sub_lane = None;
1021 self.context_menu = None;
1022 self.library_menu = None;
1023 self.eq_open = None;
1024 self.color_open = None;
1025 self.transform_open = None;
1026 self.speed_open = None;
1027 self.effects_open = None;
1028 self.close_silence();
1029 self.waves.clear();
1030 self.thumbs.clear();
1031 self.streams.clear();
1032 self.bitrates.clear();
1033 self.facts.clear();
1034 self.sizes.clear();
1035 self.syncs.clear();
1036 self.has_video.clear();
1037 // Scanned off sources that are not in the library any more.
1038 self.silence_levels.clear();
1039 // ...and every background read still chasing one of them: cancelled
1040 // rather than merely dropped, so a landing closure over a gone window
1041 // does not write into a `silence_levels` the next session starts
1042 // empty (`Player::cache_media`'s spawn checks this flag before it
1043 // inserts).
1044 for scan in self.silence_bg.values() {
1045 scan.cancel
1046 .store(true, std::sync::atomic::Ordering::Relaxed);
1047 }
1048 self.silence_bg.clear();
1049 // Every gesture in flight, dropped for `reset_after_reseek`'s reason
1050 // (it drops the trim below): a drag holds a bar, a clip or a band of a
1051 // timeline that has just stopped existing.
1052 self.scrubbing = false;
1053 self.volume_dragging = false;
1054 self.preview_scrubbing = false;
1055 self.eq_dragging = false;
1056 self.speed_dragging = false;
1057 self.effects_drag = None;
1058 self.effects_draft = None;
1059 self.color_dragging = false;
1060 self.color_wheel_drag = None;
1061 self.viz_hs_dragging = false;
1062 self.pending_color = None;
1063 self.pending_viz = None;
1064 self.transform_dragging = false;
1065 self.pending_transform = None;
1066 self.curve_drag = None;
1067 self.pending_speed = None;
1068 self.displayed = 0;
1069 self.dropped = 0;
1070 self.started = None;
1071 // The empty window's own: no name in the titlebar, nowhere chosen to
1072 // export or save to yet, and a rate that only keeps the timecode
1073 // reading in frames until a file brings its own (`main`).
1074 self.name = NO_FILE.into();
1075 self.export_path = PathBuf::new();
1076 self.project_path = PathBuf::new();
1077 self.fps = 30.;
1078 // No decoder to wait for a frame from: the hint is what shows. The
1079 // transport reads `Stopped` from the session being gone, so there is no
1080 // end-of-stream state left to clear here.
1081 self.reset_after_reseek();
1082 self.seek_since = None;
1083 }
1084
1085 /// The row's own play button: opens `path` as a session of its own and
1086 /// shows it in place of the timeline's picture, without moving the
1087 /// timeline's playhead or touching its undo stack -- what a library
1088 /// preview is. [`PlaybackSession::open_with_audio_stream`] builds exactly
1089 /// this (a one-clip session, ungraded, passthrough) bound to `stream`, the
1090 /// row's own audio track rather than always the file's first.
1091 pub(crate) fn open_preview(
1092 &mut self,
1093 path: &std::path::Path,
1094 stream: usize,
1095 cx: &mut Context<Self>,
1096 ) {
1097 if self.exporting().is_some() {
1098 return;
1099 }
1100 // The timeline would otherwise keep playing under the preview -- two
1101 // soundtracks at once -- so it is paused here and resumed on the way
1102 // out only if this is what paused it ([`Player::close_preview`]).
1103 self.preview_playing = self
1104 .session
1105 .as_ref()
1106 .is_some_and(PlaybackSession::is_playing);
1107 if let Some(session) = self.session.as_mut() {
1108 session.pause();
1109 }
1110 match PlaybackSession::open_with_audio_stream(path, stream) {
1111 Ok(mut session) => {
1112 self.source_target = Some((path.to_path_buf(), stream));
1113 self.source_video = true;
1114 self.source_audio = true;
1115 session.drop_late_pictures(true);
1116 // Parked on its first frame, paused: opening a source is looking at it,
1117 // and play is one press away.
1118 self.preview_session = Some(session);
1119 // The one place the window's level reaches a session
1120 // ([`Player::apply_volume`]) -- and it goes at the timeline
1121 // under the preview too, which is what makes closing the
1122 // preview hand back a session already at the shown level
1123 // rather than the one it had before the preview opened.
1124 self.apply_volume();
1125 self.session_swapped();
1126 self.notify_user(
1127 format!(
1128 "Previewing {}. Drag it onto the timeline to use it.",
1129 stem(path)
1130 )
1131 .into(),
1132 );
1133 }
1134 Err(e) => self.notify_user(format!("Preview failed: {e}").into()),
1135 }
1136 self.reset_after_reseek();
1137 cx.notify();
1138 }
1139
1140 /// The way out of a preview: `esc`, or the banner's own button. The
1141 /// timeline was never pumped while the preview played, so its picture is
1142 /// stale where it left off -- a reseek to the position it is already at
1143 /// is what brings a fresh frame back, exactly as loading a project does.
1144 pub(crate) fn close_preview(&mut self, cx: &mut Context<Self>) {
1145 if self.preview_session.take().is_none() {
1146 return;
1147 }
1148 self.notify_user("Back to the timeline".into());
1149 match self.session.as_ref().map(PlaybackSession::now) {
1150 Some(now) => {
1151 self.seek(now, cx);
1152 if self.preview_playing
1153 && let Some(session) = self.session.as_mut()
1154 {
1155 session.play();
1156 }
1157 }
1158 None => {
1159 self.image = None;
1160 cx.notify();
1161 }
1162 }
1163 // The session on screen is the timeline's again, and it is told the
1164 // window's level here rather than being trusted to have kept it: a
1165 // level changed while the preview was up reaches every session
1166 // ([`Player::apply_volume`]), and this is the belt to that pair of
1167 // braces -- the session that takes the picture is the one that must be
1168 // heard at the level the control shows.
1169 self.apply_volume();
1170 // The picture swaps back to the timeline's, so everything keyed to a
1171 // session hears it (`Player::session_swapped`) -- the sound watch among
1172 // them, or the timeline's own unchanged reason would read as a device
1173 // that came back the moment the preview closed.
1174 self.session_swapped();
1175 self.preview_playing = false;
1176 }
1177
1178 /// The rate and layout the whole timeline's audio is, taken from the stream
1179 /// of the first source that could have one: what a library row has to match
1180 /// to be placeable. `None` until that file has been probed, and then nothing
1181 /// is greyed for it.
1182 ///
1183 /// The first source that is *not a still*, which is the rule the engine
1184 /// holds every import to (`playback::audio_source_of`) -- a picture at the
1185 /// head of the list (a removal moves indexes) has no stream to describe
1186 /// anything with.
1187 pub(crate) fn timeline_audio(&self) -> Option<(u32, u16)> {
1188 let first = self
1189 .session
1190 .as_ref()?
1191 .sources()
1192 .iter()
1193 .find(|s| !engine::is_image(&s.path))?;
1194 let info = self
1195 .streams
1196 .get(&first.path)?
1197 .iter()
1198 .find(|s| s.index == first.audio_stream)?;
1199 Some((info.sample_rate, info.channels))
1200 }
1201
1202 /// Queues a file for the library. Nothing is read here: the reading is
1203 /// [`read_ahead`] on a worker, and [`Player::take_import`] is what finally
1204 /// touches the timeline, one repaint later and with the pages warm. A drop
1205 /// is not a key press, so the export guard on the key handler does not
1206 /// cover it and this checks for itself.
1207 ///
1208 /// One file at a time, in arrival order: a drop can carry six and argv can
1209 /// name more, and six header walks racing over one disk finish no sooner
1210 /// than six in a row -- while the line above the panel has exactly one file
1211 /// to name.
1212 pub(crate) fn import(&mut self, path: &std::path::Path, cx: &mut Context<Self>) {
1213 if self.exporting().is_some() {
1214 return;
1215 }
1216 self.imports.push_back(path.to_path_buf());
1217 self.start_import(cx);
1218 }
1219
1220 /// Starts the worker for the next queued file, if no worker is running.
1221 /// Called again as each import lands, which is what drains the queue.
1222 pub(crate) fn start_import(&mut self, cx: &mut Context<Self>) {
1223 if self.importing.is_some() {
1224 return;
1225 }
1226 let Some(path) = self.imports.pop_front() else {
1227 return;
1228 };
1229 // An OpenTimelineIO file is read here, whole, and is no media to probe: it becomes a sequence.
1230 if crate::importing::is_timeline(&path) {
1231 self.import_timeline_file(&path, cx);
1232 self.start_import(cx);
1233 return;
1234 }
1235 let stage = Arc::new(std::sync::atomic::AtomicU8::new(ImportStage::Header as u8));
1236 let cancelled = Arc::new(std::sync::atomic::AtomicBool::new(false));
1237 // The fork is made here, once, and carried to the landing: an import is
1238 // *probed* on the worker and registered from what came back, while the
1239 // file argv named -- and a file arriving at a window with no timeline to
1240 // import into -- is *opened* on the worker and handed over whole. None
1241 // of the three leaves the UI thread anything to read: a cold 24 GB
1242 // header walk is twenty seconds, and the window keeps painting through
1243 // all of them.
1244 let what = arrival(self.opening.as_deref(), &path);
1245 // The timeline the file will be checked against, taken here because the
1246 // worker cannot reach the session: two clones and no disk
1247 // ([`PlaybackSession::import_gate`]). `None` is a window with nothing to
1248 // import into, which is the fork that opens the file outright.
1249 let gate = self.session.as_ref().map(PlaybackSession::import_gate);
1250 let read = cx.background_executor().spawn({
1251 let (path, stage) = (path.clone(), Arc::clone(&stage));
1252 let cancelled = Arc::clone(&cancelled);
1253 // The Cancel beside the line reaches the *walk* this way: every
1254 // cluster the reads below step over checks this flag, so a stopped
1255 // import stops the disk rather than only the landing
1256 // ([`engine::demux::with_cancel`]).
1257 async move {
1258 engine::demux::with_cancel(&cancelled, || open_ahead(what, &path, &stage, gate))
1259 }
1260 });
1261 let now = Instant::now();
1262 self.importing = Some(Import {
1263 path: path.clone(),
1264 started: now,
1265 stage,
1266 seen: ImportStage::Header,
1267 since: now,
1268 cancelled: Arc::clone(&cancelled),
1269 });
1270 cx.spawn(async move |this, cx| {
1271 let landed = read.await;
1272 this.update(cx, |this, cx| {
1273 this.importing = None;
1274 // Cancelled while it read: the window was given back at the
1275 // click and said so then, so what the worker carried is dropped
1276 // without a second word ([`Player::cancel_import`]).
1277 if cancelled.load(std::sync::atomic::Ordering::Relaxed) {
1278 return;
1279 }
1280 this.take_import(&path, landed, cx);
1281 // The next one is started by the repaint this notified, which
1282 // is also what starts the files argv named ([`poll_import`]).
1283 })
1284 .ok();
1285 })
1286 .detach();
1287 cx.notify();
1288 }
1289
1290 /// Keeps the import line's two clocks honest: the elapsed one runs from the
1291 /// worker, and the stall one from the last time the stage it is naming
1292 /// actually changed. Sampled here rather than while drawing, for
1293 /// [`Player::poll_export`]'s reason.
1294 ///
1295 /// ...and starts whatever is queued behind it, which is the one place the
1296 /// files argv named can begin: they are put in the queue before there is a
1297 /// context to spawn a worker from.
1298 /// Takes each finished stand-in's verdict, once. Sampled here rather than
1299 /// while drawing, for [`Player::poll_export`]'s reason -- and it is the one
1300 /// place a proxy job's outcome is read, so "ready" on a row and the file in
1301 /// the cache are the same fact.
1302 ///
1303 /// Nothing waits for it: until a proxy is ready the film itself is what
1304 /// plays, switch or no switch ([`engine::PlaybackSession::picture_path`]),
1305 /// so a failure costs a line and no more.
1306 ///
1307 /// A stopped one settles here too ([`Player::cancel_proxy`]), which is what
1308 /// makes the stop honest: the worker's own answer is what says the encode
1309 /// is over and its half-written file gone -- and where the encode *beat*
1310 /// the cancel, the answer is a finished stand-in and it is reported as one
1311 /// rather than thrown away.
1312 pub(crate) fn poll_proxies(&mut self, cx: &mut Context<Self>) {
1313 let done: Vec<(PathBuf, bool, engine::Result<PathBuf>)> = self
1314 .proxies
1315 .iter()
1316 .filter_map(|(path, state)| match state {
1317 Proxy::Making(job) => Some((path.clone(), false, job.outcome()?)),
1318 Proxy::Cancelling(job) => Some((path.clone(), true, job.outcome()?)),
1319 _ => None,
1320 })
1321 .collect();
1322 for (path, stopped, outcome) in done {
1323 let text = match (&outcome, stopped) {
1324 (Ok(_), _) => format!(
1325 "Editing copy ready for {}: Editing copies on cuts on it",
1326 file_name(&path)
1327 ),
1328 // Not a failure and not worded as one: the worker gave up
1329 // because it was asked to, and it took its half-written file
1330 // with it.
1331 (Err(_), true) => format!(
1332 "Editing copy stopped for {}: nothing of it was kept, and the original is what \
1333 plays",
1334 file_name(&path)
1335 ),
1336 (Err(e), false) => format!(
1337 "Editing copy failed for {}: {e} — the original is what plays",
1338 file_name(&path)
1339 ),
1340 };
1341 eprintln!("{text}");
1342 self.notify_user(text.into());
1343 let state = match (outcome, stopped) {
1344 (Ok(_), _) => Proxy::Ready,
1345 (Err(_), true) => Proxy::Cancelled,
1346 (Err(_), false) => Proxy::Failed,
1347 };
1348 self.proxies.insert(path, state);
1349 cx.notify();
1350 }
1351 }
1352
1353 /// Starts the stand-in for one file: the slot is taken the moment the ask
1354 /// goes out, so a repaint mid-encode cannot start a second one, and what
1355 /// comes back off the worker settles the slot.
1356 ///
1357 /// One body, two doors: the sweep [`Player::cache_media`] runs over
1358 /// everything the session has not seen, and the switch on a library row
1359 /// ([`Player::toggle_proxy`]) for the one file under the pointer. The cap on
1360 /// how many run at once belongs to the sweep -- a person who asks for *this*
1361 /// film's stand-in has asked, and is told by the row how far it has got.
1362 pub(crate) fn start_proxy_for(&mut self, path: &std::path::Path, cx: &mut Context<Self>) {
1363 let path = path.to_path_buf();
1364 // The same flag [`engine::proxy::generate_if_wanted`] polls at the door
1365 // and around the header read: a click on the row while the header is
1366 // still being walked ([`Player::toggle_proxy`]'s `Asked` arm) sets it,
1367 // so the walk unwinds mid-read instead of running to completion.
1368 let cancel = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
1369 self.proxies
1370 .insert(path.clone(), Proxy::Asked(cancel.clone()));
1371 let started = cx.background_executor().spawn({
1372 let path = path.clone();
1373 async move { engine::proxy::generate_if_wanted(&path, &cancel) }
1374 });
1375 cx.spawn(async move |this, cx| {
1376 let started = started.await;
1377 this.update(cx, |this, cx| {
1378 // Switched off while the header was being read
1379 // ([`Player::toggle_proxy`]): the slot is no longer the `Asked`
1380 // this put there, so what came back is *stopped as it lands*
1381 // rather than installed over the stop. Without this the second
1382 // half of a click made during the ask is an encoder nothing in
1383 // the map can reach -- and it finishes minutes later and puts
1384 // back the stand-in somebody switched off.
1385 let stopped = !matches!(this.proxies.get(&path), Some(Proxy::Asked(_)));
1386 let state = match started {
1387 // Cancelled and *held*, exactly as a stop of a running one
1388 // is: the worker's own answer is what settles it, so an
1389 // encode that beat the stop is reported as the finished
1390 // stand-in it is ([`Player::poll_proxies`]).
1391 Ok(Some(job)) if stopped => {
1392 job.cancel();
1393 Proxy::Cancelling(job)
1394 }
1395 // ...and a stop of something that was never going to be
1396 // encoded is simply the film itself, which is what it was.
1397 Ok(None) | Err(_) if stopped => Proxy::Cancelled,
1398 Ok(Some(job)) => Proxy::Making(job),
1399 // A film that needs none keeps the state it was inserted
1400 // with, which is what it is.
1401 Ok(None) => Proxy::Native,
1402 Err(e) => {
1403 let text = format!(
1404 "No editing copy for {}: {e} — the original is what plays",
1405 file_name(&path)
1406 );
1407 eprintln!("{text}");
1408 this.notify_user(text.into());
1409 Proxy::Failed
1410 }
1411 };
1412 this.proxies.insert(path, state);
1413 cx.notify();
1414 })
1415 .ok();
1416 })
1417 .detach();
1418 }
1419
1420 /// The switch on a library row: this file's stand-in on, or off. One
1421 /// control for the whole life of the thing, because a row with a separate
1422 /// start, stop and delete is three buttons for one fact.
1423 ///
1424 /// * being made -- the ask is to *stop*, which is
1425 /// [`Player::cancel_proxy`]'s half-written-file-and-all path and never a
1426 /// deletion;
1427 /// * asked for, and the worker has not answered yet -- the same stop, made
1428 /// before there is a job to stop: the slot is marked and the answer is
1429 /// cancelled as it lands ([`Player::start_proxy_for`]). Never a second
1430 /// start, which is what two encoders on one `.part` path used to be;
1431 /// * there is one -- the file in the cache goes ([`engine::proxy::delete`]),
1432 /// and the slot is left [`Proxy::Cancelled`] rather than emptied: an empty
1433 /// slot is what the next repaint's sweep starts an encode from
1434 /// ([`proxies_to_start`] passes on everything the map has not seen), so
1435 /// emptying it would rebuild the stand-in a second after it was turned
1436 /// off. A delete that could not happen leaves the row *on*, because the
1437 /// file is still there and still what plays;
1438 /// * anything else -- start one.
1439 ///
1440 /// `showed_stop` is what the row was drawing when the pointer went down:
1441 /// a stand-in that finished between that paint and this click is a click on
1442 /// a **stop**, and a stop settles as the ready stand-in it is rather than
1443 /// deleting a file nobody asked to lose ([`Player::cancel_proxy`]'s own
1444 /// promise).
1445 ///
1446 /// The off is remembered past the window ([`engine::proxy::set_off`]): the
1447 /// sweep runs again at every launch, and a switch that forgets is one that
1448 /// re-encodes tomorrow what was turned off today.
1449 pub(crate) fn toggle_proxy(
1450 &mut self,
1451 path: &std::path::Path,
1452 showed_stop: bool,
1453 cx: &mut Context<Self>,
1454 ) {
1455 match self.proxies.get(path) {
1456 Some(Proxy::Making(_)) => self.cancel_proxy(path, cx),
1457 // Already winding down: the second click on a stop is nothing.
1458 Some(Proxy::Cancelling(_)) => {}
1459 Some(Proxy::Asked(cancel)) => {
1460 // Wakes the header read mid-walk ([`engine::proxy::started`]):
1461 // without this the stop only ever landed once the read had
1462 // already run to completion on its own (DEBT #91).
1463 cancel.store(true, std::sync::atomic::Ordering::Release);
1464 engine::proxy::set_off(path, true);
1465 self.proxies.insert(path.to_path_buf(), Proxy::Cancelled);
1466 let text = format!("Stopping the stand-in for {}…", file_name(path));
1467 eprintln!("{text}");
1468 self.notify_user(text.into());
1469 cx.notify();
1470 }
1471 // The encode beat the click: what is under the pointer is a stop,
1472 // and the film has a stand-in now.
1473 Some(Proxy::Ready) if showed_stop => {
1474 let text = format!(
1475 "Editing copy ready for {}: it finished before the stop",
1476 file_name(path)
1477 );
1478 eprintln!("{text}");
1479 self.notify_user(text.into());
1480 cx.notify();
1481 }
1482 Some(Proxy::Ready) => {
1483 let text = match engine::proxy::delete(path) {
1484 Ok(gone) => {
1485 engine::proxy::set_off(path, true);
1486 self.proxies.insert(path.to_path_buf(), Proxy::Cancelled);
1487 match gone {
1488 true => format!(
1489 "Editing copy off for {}: the original is what plays",
1490 file_name(path)
1491 ),
1492 false => {
1493 format!("No editing copy for {}: nothing to delete", file_name(path))
1494 }
1495 }
1496 }
1497 // The file is still on the disk and [`engine::proxy::cached`]
1498 // is still handing it to playback, so the row stays on: the
1499 // one thing it must never do is say off over a proxy that is
1500 // playing.
1501 Err(e) => format!(
1502 "Editing copy kept for {}: {e} — it could not be deleted and is still what plays",
1503 file_name(path)
1504 ),
1505 };
1506 eprintln!("{text}");
1507 self.notify_user(text.into());
1508 cx.notify();
1509 }
1510 _ => {
1511 engine::proxy::set_off(path, false);
1512 self.start_proxy_for(path, cx);
1513 }
1514 }
1515 }
1516
1517 /// The × on a library row while its stand-in is being made: the worker is
1518 /// asked to give up at its next frame and delete the half-written file it
1519 /// was writing ([`engine::proxy::Job::cancel`]), and the row says so until
1520 /// it has. A whole feature film re-encoded is minutes of a machine the cut
1521 /// is being made on, and there was no way to take it back.
1522 ///
1523 /// Nothing is deleted from here and nothing waits: the film itself is what
1524 /// plays throughout ([`engine::PlaybackSession::picture_path`] stats the
1525 /// cache and finds nothing), so a stop costs a line and no more. Asking
1526 /// twice is asking once -- the second click finds a state that is not
1527 /// [`Proxy::Making`] and answers nothing -- and a cancel that arrives after
1528 /// the encode has already written its file settles as the *ready* stand-in
1529 /// it is ([`Player::poll_proxies`]), never as a deletion of one in use.
1530 pub(crate) fn cancel_proxy(&mut self, path: &std::path::Path, cx: &mut Context<Self>) {
1531 // Taken out of its slot and put back one state on, rather than removed:
1532 // a path that left this map is a path the next repaint starts an encode
1533 // for all over again ([`Player::cache_media`]).
1534 let Some(slot) = self.proxies.get_mut(path) else {
1535 return;
1536 };
1537 if !matches!(slot, Proxy::Making(_)) {
1538 return;
1539 }
1540 let Proxy::Making(job) = std::mem::replace(slot, Proxy::Cancelled) else {
1541 unreachable!("the slot was just read as one being made")
1542 };
1543 job.cancel();
1544 *slot = Proxy::Cancelling(job);
1545 // Remembered past this window, for [`Player::toggle_proxy`]'s reason:
1546 // the launch sweep would otherwise start again what was just stopped.
1547 engine::proxy::set_off(path, true);
1548 let text = format!("Stopping the stand-in for {}…", file_name(path));
1549 eprintln!("{text}");
1550 self.notify_user(text.into());
1551 cx.notify();
1552 }
1553
1554 /// What the Proxies button says after the state: how far the stand-ins
1555 /// have got, since "on" with nothing made yet and "on" with the whole
1556 /// library standing in are two different things to be looking at. Empty
1557 /// where no film here wants one, which is the ordinary case.
1558 pub(crate) fn proxy_tail(&self) -> String {
1559 // No session, no library row could be making anything: a prior
1560 // session's jobs (never cleared out of `self.proxies` on close, since
1561 // a proxy is derived and re-checked from disk on next open rather
1562 // than tracked per session) must not print as this one's progress.
1563 if self.session.is_none() {
1564 return String::new();
1565 }
1566 let making = self.proxies.values().filter_map(|p| match p {
1567 Proxy::Making(job) => Some(job.progress()),
1568 _ => None,
1569 });
1570 // The one furthest along would read as done while three others sit at
1571 // nothing: the *least* finished is what the button reports.
1572 match making.fold(f32::INFINITY, f32::min) {
1573 least if least.is_finite() => format!(" · {}%", (least * 100.) as u32),
1574 _ => String::new(),
1575 }
1576 }
1577
1578 /// Pushes the window's two stand-in switches at the session, which is the
1579 /// only place they are ever written -- [`Player::apply_volume`]'s contract,
1580 /// and for a sharper reason: a fresh session comes up making stand-ins for
1581 /// every big film, so a person who turned that off before importing
1582 /// anything would watch the very import they were waiting to prevent start
1583 /// an encode.
1584 pub(crate) fn apply_proxies(&mut self) {
1585 let (on, auto) = (self.proxies_on, self.auto_proxies_on);
1586 if let Some(session) = &mut self.session {
1587 // Deliberately not armed: the only caller is
1588 // [`Self::install_media`], the import/load path, where arming is
1589 // the one thing the `autosave_armed` rule forbids -- a project
1590 // nobody has written must not start asking to be saved. The
1591 // user's own door is the switch ([`Self::toggle_proxies`] /
1592 // [`Self::toggle_auto_proxies`]), and that is where the arm is.
1593 session.set_proxies(on);
1594 session.set_auto_proxies(auto);
1595 }
1596 }
1597
1598 /// Whether any stand-in is still being made -- what keeps the frame loop
1599 /// alive while one is, so its percentage moves on screen.
1600 ///
1601 /// One being stopped counts: its worker is still running until it reaches
1602 /// the frame it gives up at, and the repaint that notices *that* is this
1603 /// same loop -- without it a stopped row would sit on "stopping…" until
1604 /// something else happened to repaint the window.
1605 pub(crate) fn making_proxies(&self) -> bool {
1606 self.proxies
1607 .values()
1608 .any(|p| matches!(p, Proxy::Making(_) | Proxy::Cancelling(_)))
1609 }
1610
1611 /// How many films are between "shall we?" and "done": the number the start
1612 /// of another is held against ([`PROXIES_AT_ONCE`]). A header being read
1613 /// counts, because the answer may be an encode -- and so does one still
1614 /// winding down from a stop, which is an encoder that has not let go of the
1615 /// seat yet.
1616 pub(crate) fn in_flight_proxies(&self) -> usize {
1617 self.proxies
1618 .values()
1619 .filter(|p| matches!(p, Proxy::Asked(_) | Proxy::Making(_) | Proxy::Cancelling(_)))
1620 .count()
1621 }
1622
1623 /// Cuts on the stand-ins, or on the films themselves. The picture and only
1624 /// the picture: the sound is the film's either way, and so is every frame
1625 /// an export writes.
1626 ///
1627 /// Set on the window and pushed at the session, not the other way about:
1628 /// this is an import option and a person picks it before the first film
1629 /// arrives ([`Player::apply_proxies`]). With nothing open it is the pick
1630 /// the next session comes up with.
1631 pub(crate) fn toggle_proxies(&mut self, cx: &mut Context<Self>) {
1632 let on = !self.proxies_on;
1633 self.proxies_on = on;
1634 if let Some(session) = &mut self.session {
1635 let changed = session.proxies() != on;
1636 session.set_proxies(on);
1637 if changed {
1638 self.mark_dirty();
1639 }
1640 }
1641 // What is really under the switch, said in the same breath: a project
1642 // whose films have no stand-in yet would otherwise read as a switch
1643 // that does nothing.
1644 let ready = self
1645 .proxies
1646 .values()
1647 .filter(|p| matches!(p, Proxy::Ready))
1648 .count();
1649 let making = self
1650 .proxies
1651 .values()
1652 .filter(|p| matches!(p, Proxy::Making(_)))
1653 .count();
1654 let text = match (on, ready, making) {
1655 (false, ..) => "Editing copies off: the originals are what play".to_string(),
1656 (true, 0, 0) => "Editing copies on: no video here has one".to_string(),
1657 (true, 0, n) => format!("Editing copies on: {n} still being made"),
1658 (true, n, 0) => format!("Editing copies on: cutting on {n}"),
1659 (true, n, m) => format!("Editing copies on: cutting on {n}, {m} still being made"),
1660 };
1661 eprintln!("{text}");
1662 // Kept for the next launch, not only the next project -- the same
1663 // reason auto-proxies keeps one ([`save_auto_proxies_pref`]).
1664 if let Err(e) = save_proxies_pref(on) {
1665 let path = proxies_pref_path();
1666 self.notify_user(
1667 format!(
1668 "Editing copies default could not be kept: {} — {e}",
1669 path.display()
1670 )
1671 .into(),
1672 );
1673 }
1674 self.notify_user(text.into());
1675 // The switch reseeks the session, and the wait for that picture is what
1676 // this clears -- with nothing open there is no open to wait for, and a
1677 // clock started against one would be a seek line about nothing.
1678 if self.session.is_some() {
1679 self.reset_after_reseek();
1680 }
1681 cx.notify();
1682 }
1683
1684 /// Makes the stand-ins as the films arrive, or makes none until they are
1685 /// asked for. The other half of the switch above: this one decides what is
1686 /// *encoded*, that one what is *watched*.
1687 ///
1688 /// With it off nothing is started by an import at all -- turning Proxies on
1689 /// is what asks for the ones this project needs ([`Player::cache_media`]),
1690 /// which is said here because a switch whose only effect is elsewhere is a
1691 /// switch that reads as doing nothing.
1692 ///
1693 /// The window's own, like the switch above and for its reason: this one
1694 /// decides what an *import* does, so it is answerable before the import.
1695 pub(crate) fn toggle_auto_proxies(&mut self, cx: &mut Context<Self>) {
1696 let on = !self.auto_proxies_on;
1697 self.auto_proxies_on = on;
1698 if let Some(session) = &mut self.session {
1699 // [`Self::toggle_proxies`]'s own gate: the switch is a click and
1700 // the session is where the project hears it.
1701 let changed = session.auto_proxies() != on;
1702 session.set_auto_proxies(on);
1703 if changed {
1704 self.mark_dirty();
1705 }
1706 }
1707 let text = match on {
1708 true => "Editing copies on import: every import gets one",
1709 false => "Editing copies on import off: no import makes one",
1710 };
1711 eprintln!("{text}");
1712 // Kept for the next launch, not only the next project -- a flip made
1713 // with nothing open, or a project never saved after it, used to
1714 // vanish the moment the window closed ([`load_auto_proxies_pref`]).
1715 if let Err(e) = save_auto_proxies_pref(on) {
1716 let path = auto_proxies_pref_path();
1717 self.notify_user(
1718 format!(
1719 "Import editing copies default could not be kept: {} — {e}",
1720 path.display()
1721 )
1722 .into(),
1723 );
1724 }
1725 self.notify_user(text.into());
1726 cx.notify();
1727 }
1728
1729 pub(crate) fn poll_import(&mut self, cx: &mut Context<Self>) {
1730 match &mut self.importing {
1731 Some(import) => {
1732 import.poll();
1733 }
1734 None => self.start_import(cx),
1735 }
1736 }
1737
1738 /// The Cancel beside the import line: the window is given back at once and
1739 /// the file does not land. Everything queued behind it goes too -- a person
1740 /// who has stopped an import of six dropped files has stopped the six, and
1741 /// leaving five to start themselves would be the same wait under another
1742 /// name.
1743 ///
1744 /// The read in flight is stopped too, where the container lets it be: a
1745 /// Matroska walk checks this flag between clusters and gives up there
1746 /// ([`engine::demux::with_cancel`]). See [`Import::cancelled`] for what an
1747 /// mp4 header still costs.
1748 pub(crate) fn cancel_import(&mut self, cx: &mut Context<Self>) {
1749 let Some(import) = self.importing.take() else {
1750 return;
1751 };
1752 import
1753 .cancelled
1754 .store(true, std::sync::atomic::Ordering::Relaxed);
1755 let waiting = self.imports.len();
1756 self.imports.clear();
1757 let tail = match waiting {
1758 0 => String::new(),
1759 n => format!(" — {n} more dropped from the queue"),
1760 };
1761 let text = format!(
1762 "Import cancelled: {}{tail} — the read stops where the container lets it",
1763 file_name(&import.path)
1764 );
1765 eprintln!("{text}");
1766 self.notify_user(text.into());
1767 cx.notify();
1768 }
1769
1770 /// Takes a read-ahead file into the library and nowhere else: the timeline
1771 /// is not touched, and the row is dragged onto a lane when it is wanted
1772 /// there. Nothing moves, so nothing reseeks; a refusal is shown as the
1773 /// engine worded it and changes nothing.
1774 ///
1775 /// The export guard again, and not for the caller's sake: an export can
1776 /// have started during the seconds the worker was reading, and a drop
1777 /// during an export has always been a silent no-op.
1778 pub(crate) fn take_import(
1779 &mut self,
1780 path: &std::path::Path,
1781 landed: Landed,
1782 cx: &mut Context<Self>,
1783 ) {
1784 if self.exporting().is_some() {
1785 return;
1786 }
1787 // The file argv named is the one file in the queue that is not an
1788 // import: it *is* the timeline, and the worker has already opened it.
1789 // All that is left here is to hang everything derived from it off the
1790 // window -- the clock, the title, where an export and a save go -- and
1791 // that is arithmetic, not a read.
1792 let (subs, probe) = match landed {
1793 Landed::Read(subs, probe) => (subs, probe),
1794 what => {
1795 // Only when *this* is the file argv named: a project dropped
1796 // while that one is still being read must not make it land as
1797 // an import.
1798 if self.opening.as_deref() == Some(path) {
1799 self.opening = None;
1800 }
1801 match what {
1802 Landed::Project(opened) => self.install_project(path, opened, cx),
1803 Landed::Media(opened, place) => {
1804 let text = self.install_media(path, opened, place);
1805 eprintln!("{text}");
1806 self.notify_user(text.into());
1807 // The file argv named becomes the timeline, and a
1808 // timeline that arrives fits, as a first import does
1809 // (DESIGN §7). Opened without a place it is a library
1810 // row and the view stays where it is.
1811 if place && self.session.as_ref().is_some_and(|s| !s.is_empty()) {
1812 self.zoom_fit(cx);
1813 }
1814 cx.notify();
1815 }
1816 Landed::Read(..) => unreachable!("matched above"),
1817 }
1818 // The line a launch has always printed, now printed when the
1819 // file actually arrives: it is the mark that says the timeline
1820 // is up, as the window's own appearance is the other one.
1821 if let Some(meta) = self.session.as_ref().map(PlaybackSession::meta) {
1822 println!(
1823 "{}: {}x{} @ {:.2} fps, {} samples",
1824 path.display(),
1825 meta.width,
1826 meta.height,
1827 meta.frame_rate,
1828 meta.frame_count
1829 );
1830 }
1831 // A new project's first footage is in: the file it was named for is written now.
1832 if std::mem::take(&mut self.new_project_fresh) {
1833 self.save_project(cx);
1834 }
1835 return;
1836 }
1837 };
1838 // An empty window has no library to add to yet: the file opens one. An
1839 // import is an import whether or not a session was already up, so it
1840 // fills the library either way; the one thing that differs is that the
1841 // first file into an empty timeline is also placed on it, and the zoom
1842 // fits it (DESIGN §7). A file *named at launch* is the other fork --
1843 // that one is an open, and it does become the timeline (`main`).
1844 // A subtitle file is not a source and lands on no lane: it joins the
1845 // timeline's own list of them, which is what the library's subtitle
1846 // section shows and what the overlay draws. With no timeline open there
1847 // is nothing for the cues to be timed against, and it says so.
1848 if is_subtitle(path) {
1849 self.take_subtitles(path, subs, cx);
1850 return;
1851 }
1852 // The container was read on the worker and what came back is registered
1853 // here ([`engine::PlaybackSession::import_probed`]): no header walk, no
1854 // decoder open, no probe of the timeline's own first source -- the three
1855 // reads that used to be spent on this thread. A song and a still fork
1856 // before the demuxer and pay their own small read
1857 // ([`engine::PlaybackSession::import`]); a window whose timeline went
1858 // away while the worker read falls to the slow door below, which is the
1859 // one that can still open one.
1860 // A refusal that only says "no picture" is not a refusal here: the
1861 // slow door below re-reads the file and lands it as audio, the same
1862 // fallback every other door in makes.
1863 let no_video = matches!(&probe, Some(Err(e)) if engine::demux::NoVideoTrack::is_it(e));
1864 let registered = match (self.session.as_mut(), probe) {
1865 (Some(session), Some(Ok(probe))) => Some(session.import_probed(path, probe)),
1866 (Some(session), Some(Err(_))) if no_video => Some(session.import(path)),
1867 (Some(_), Some(Err(refused))) => Some(Err(refused)),
1868 (Some(session), None) => Some(session.import(path)),
1869 (None, _) => None,
1870 };
1871 // Whether this import is the first thing into an empty timeline, so it
1872 // is also placed on it once the library line below has been said.
1873 let first = match &self.session {
1874 Some(session) => session.is_empty(),
1875 None => true,
1876 };
1877 let joins: bool;
1878 let text = match registered {
1879 Some(Ok(_)) => {
1880 // The file's own subtitle tracks with it, exactly as an open
1881 // takes them: an import is the other door the same file arrives
1882 // through. The cues were read on the worker
1883 // ([`read_ahead`]); what happens here is the push.
1884 let tail = self
1885 .session
1886 .as_mut()
1887 .and_then(|session| subtitle_tail(session, subs))
1888 .unwrap_or_default();
1889 // A file with sound joining a session that opened silent is the
1890 // one import that *arms* the audio device
1891 // ([`engine::PlaybackSession::arm_audio`]); it comes up at full
1892 // volume, so the player's own level and mute are pushed at it
1893 // again here or a muted window would play.
1894 self.apply_volume();
1895 joins = first;
1896 let landing = match first {
1897 true => " and the timeline",
1898 false => "",
1899 };
1900 format!(
1901 "Imported {} to the library{landing}{tail}{}",
1902 file_name(path),
1903 audio_import_tail(path, self.has_video(path) && !no_video)
1904 )
1905 }
1906 // Named, because two files can fail in one launch and the queue now
1907 // shows both: "No such file or directory" twice over, with nothing
1908 // saying which file, is two messages that answer nothing.
1909 // The engine's words stay on stderr; the window says what the user can do about it.
1910 Some(Err(e)) => {
1911 joins = false;
1912 eprintln!("import of {} failed: {e}", path.display());
1913 let name = file_name(path);
1914 match path.exists() {
1915 false => format!("Couldn't import {name} \u{2014} the file isn't there."),
1916 true => format!("{name} isn't a video, audio or image file edith can read."),
1917 }
1918 }
1919 None => {
1920 let text = self.open_media(path, false, subs);
1921 // A window with no session that opened one has an empty
1922 // timeline under it, which is the case the first file fills.
1923 joins = self.session.is_some();
1924 text
1925 }
1926 };
1927 eprintln!("{text}");
1928 self.notify_loaded(text);
1929 cx.notify();
1930 // Placed after the line above, so a refusal from the insert is the last
1931 // word on the notice. The insert is one undo step (`place` snapshots
1932 // the project); the import that stands behind it is not.
1933 if joins {
1934 self.insert_source(path, 0, None, None, cx);
1935 if self
1936 .session
1937 .as_ref()
1938 .is_some_and(|session| !session.is_empty())
1939 {
1940 self.zoom_fit(cx);
1941 }
1942 }
1943 // A new project's first footage is in: the file it was named for is written now.
1944 if std::mem::take(&mut self.new_project_fresh) {
1945 self.save_project(cx);
1946 }
1947 }
1948
1949 /// Takes a file as the session an empty window is waiting for. Everything
1950 /// derived from the media -- the clock, the title, where an export and a
1951 /// save go -- is set here, exactly as a launch with a file argument sets
1952 /// it. Paused with its first frame showing, like every other way a timeline
1953 /// arrives.
1954 ///
1955 /// `place` is the difference between the two doors that come here: a file
1956 /// *opened* is the timeline, one *imported* into an empty window fills the
1957 /// library and leaves the lanes empty for a drag.
1958 pub(crate) fn open_media(&mut self, path: &std::path::Path, place: bool, subs: Subs) -> String {
1959 self.install_media(path, open_session(path, place, subs), place)
1960 }
1961
1962 /// The second half of it: everything the window derives from a session that
1963 /// has already been opened. Split from the open itself because the file
1964 /// argv named is opened on a worker ([`open_ahead`]) -- the twelve seconds
1965 /// of a cold header walk are not the UI thread's to spend -- and lands
1966 /// here, where nothing is read and nothing blocks.
1967 pub(crate) fn install_media(
1968 &mut self,
1969 path: &std::path::Path,
1970 opened: Result<(PlaybackSession, String), String>,
1971 place: bool,
1972 ) -> String {
1973 match opened {
1974 Ok((mut session, subs)) => {
1975 // A size and/or a rate picked before this file existed
1976 // ([`Player::apply_resolution`], [`Player::apply_frame_rate`])
1977 // are the project's from its very first frame -- the same
1978 // precedence a `.edith`'s own saved settings already have over
1979 // the scaffold ([`engine::PlaybackSession::open_project`]).
1980 // Consumed once: a later file replacing this session finds
1981 // nothing left pending.
1982 if let Some((w, h)) = self.pending_settings.0.take() {
1983 session.set_resolution(w, h);
1984 }
1985 if let Some(fps) = self.pending_settings.1.take() {
1986 session.set_frame_rate(fps);
1987 }
1988 if let Some(rate) = self.pending_settings.2.take() {
1989 session.set_sample_rate(Some(rate));
1990 }
1991 // A project started from a template without clips takes that template's lanes,
1992 // names and caption style now, and its export preset once the window is set up.
1993 let template_export = match self.pending_template.take() {
1994 Some(name) => match engine::templates::dir().map(|dir| engine::templates::apply(&dir, &name, &mut session)) {
1995 Some(Ok(export)) => Some(export),
1996 _ => {
1997 self.notify_user(format!("The template {name} could not be read").into());
1998 None
1999 }
2000 },
2001 None => None,
2002 };
2003 self.fps = session.meta().frame_rate;
2004 // This window *is* the real-time viewer: a picture already past
2005 // the clock is one `pump` takes off the channel and throws away,
2006 // so the worker stops paying for it instead
2007 // ([`PlaybackSession::drop_late_pictures`]).
2008 session.drop_late_pictures(true);
2009 // Read before the session moves: a file that plays silent says
2010 // so here or nowhere.
2011 let silent = audio_notice(&session);
2012 // A file replaces the one that was open, and track 3 of that one
2013 // is not track 3 of this.
2014 self.sub_track = 0;
2015 crate::export_ui::gui_default_seat(&mut session);
2016 self.session = Some(session);
2017 self.saved_revision = None;
2018 self.session_swapped();
2019 // A fresh session comes up at full volume; the player's own
2020 // setting outlives the file, so it is pushed at every new one.
2021 self.apply_volume();
2022 // ...and so do the stand-in switches, which were answerable
2023 // before this file existed and decide what its own import does.
2024 self.apply_proxies();
2025 self.project_path = match self.new_project.take() {
2026 // A project started from File > New > Project…: the footage arriving is its
2027 // first, and the file the person named is written as soon as it is placed.
2028 Some(target) => {
2029 self.new_project_fresh = true;
2030 target
2031 }
2032 None => project_path(path),
2033 };
2034 // Derived, not opened: `project_path` here is a guess at where
2035 // a save would land, not a file this window has any business
2036 // writing an autosave beside until a manual save earns it.
2037 self.autosave_armed = false;
2038 // An autosave left by an earlier, unsaved session of this media is
2039 // unsaved work too: offered like a project's newer autosave.
2040 self.recovery_sidecar = Self::recovery_offer(&self.project_path, false);
2041 self.name = match self.new_project_fresh {
2042 true => file_name(&self.project_path).trim_end_matches(".edith").to_string().into(),
2043 false => "Untitled".into(),
2044 };
2045 self.reset_export_default();
2046 if let Some(export) = template_export {
2047 self.apply_template_export(export.as_deref());
2048 }
2049 self.reset_after_reseek();
2050 let name = file_name(path);
2051 // The library is filled and the timeline is empty; the only
2052 // thing that says so is this line, so it says what to do next.
2053 let what = match place {
2054 true => format!("Opened {name}"),
2055 false => {
2056 format!("Imported {name} to the library")
2057 }
2058 };
2059 let audio = match place {
2060 true => String::new(),
2061 false => audio_import_tail(path, self.has_video(path)),
2062 };
2063 format!("{what}{}{subs}{audio}", silent.unwrap_or_default())
2064 }
2065 Err(_) => self.open_refused(path),
2066 }
2067 }
2068
2069 /// What a refused open says, in plain words, and the window's name put back:
2070 /// a launch that named a file the window never got to open must not stay
2071 /// titled with it.
2072 fn open_refused(&mut self, path: &std::path::Path) -> String {
2073 if self.session.is_none() {
2074 self.name = NO_FILE.into();
2075 }
2076 let name = file_name(path);
2077 match (path.exists(), path.extension().is_some_and(|e| e.eq_ignore_ascii_case("edith"))) {
2078 (false, _) => format!("Couldn't open {name} \u{2014} the file isn't there."),
2079 // A project that will not parse is a damaged one; any other file is media edith cannot read.
2080 (true, true) => format!("{name} is damaged or incomplete and can't be opened."),
2081 (true, false) => format!("{name} isn't video, audio or an image edith can read."),
2082 }
2083 }
2084
2085 /// File > Export timeline as: writes the active sequence in `ext` ("otio", "fcpxml" or
2086 /// "edl") to the default export folder, named like an export of this project. No chooser;
2087 /// the toast says where it went.
2088 pub(crate) fn export_timeline(&mut self, ext: &'static str, cx: &mut Context<Self>) {
2089 let Some(session) = self.session.as_ref() else {
2090 self.notify_user("No timeline to export: no project is open".into());
2091 cx.notify();
2092 return;
2093 };
2094 let timeline = session.timeline_snapshot();
2095 let text = match ext {
2096 "otio" => engine::interchange::otio::write(&timeline),
2097 "fcpxml" => engine::interchange::fcpxml::write(&timeline),
2098 _ => engine::interchange::edl::write(&timeline),
2099 };
2100 let sources: Vec<&Path> = session.sources().iter().map(|s| s.path.as_path()).collect();
2101 let first_clip = sources.first().map(|path| crate::files::stem(path));
2102 let path = default_path_with_ext(
2103 &self.project_path,
2104 self.autosave_armed || self.new_project_fresh,
2105 first_clip.as_deref(),
2106 &sources,
2107 ext,
2108 );
2109 let text = match std::fs::write(&path, text) {
2110 Ok(()) => format!("Timeline exported to {}", path.display()),
2111 Err(e) => format!("Couldn't export the timeline to {}: {e}", path.display()),
2112 };
2113 self.notify_user(text.into());
2114 cx.notify();
2115 }
2116
2117 /// Reads an OpenTimelineIO file and makes it a new sequence of the open project, which
2118 /// becomes the active one. Each file it names is taken in as a library file is. One undo step.
2119 pub(crate) fn import_timeline_file(&mut self, path: &std::path::Path, cx: &mut Context<Self>) {
2120 let text = match self.session.as_ref() {
2121 None => "No timeline imported: no project is open".to_string(),
2122 Some(session) => {
2123 let fps = session.timeline_frame_rate();
2124 let read = std::fs::read_to_string(path)
2125 .map_err(|e| e.to_string())
2126 .and_then(|t| engine::interchange::otio::read(&t, fps).map_err(|e| e.to_string()));
2127 match (read, self.session.as_mut()) {
2128 (Ok(timeline), Some(session)) => match session.import_timeline(&timeline) {
2129 Ok(_) => format!("Imported {} as a new sequence", timeline.name),
2130 Err(e) => format!("Couldn't import {}: {e}", file_name(path)),
2131 },
2132 (Err(e), _) => format!("Couldn't import {}: {e}", file_name(path)),
2133 (Ok(_), None) => "No timeline imported: no project is open".to_string(),
2134 }
2135 }
2136 };
2137 self.notify_user(text.into());
2138 cx.notify();
2139 }
2140
2141 /// The Import button: asks the desktop for a path and takes it the same way
2142 /// a drop would. The chooser is another process and the user may sit in it,
2143 /// so it runs on a background thread -- blocking here would freeze the
2144 /// window behind the dialog.
2145 pub(crate) fn pick_and_import(&mut self, cx: &mut Context<Self>) {
2146 if self.exporting().is_some() {
2147 return;
2148 }
2149 let picked = cx
2150 .background_executor()
2151 .spawn(async { pick_file("Import media") });
2152 cx.spawn(async move |this, cx| {
2153 let picked = picked.await;
2154 this.update(cx, |this, cx| match picked {
2155 // One queue, and the fork is made when its worker starts
2156 // ([`arrival`]): a project replaces the timeline, media joins
2157 // the library, and neither is read on this thread.
2158 Ok(Some(path)) => this.import(&path, cx),
2159 // Cancelled: the user already knows what happened.
2160 Ok(None) => {}
2161 // No chooser here: the same question, typed.
2162 Err(_) => this.open_path_entry(PathFor::Import, cx),
2163 })
2164 .ok();
2165 })
2166 .detach();
2167 }
2168
2169 /// The dock's "Paste path" verb (MOCK-SPEC "Dock" IMPORT section): reads
2170 /// whatever text sits on the OS clipboard and imports it the same way a
2171 /// drop or the Import button would, if it names a file that exists.
2172 /// `gpui::App::read_from_clipboard` already covers this -- no new
2173 /// dependency for what is otherwise a clipboard read and the existing
2174 /// [`Player::import`] door.
2175 pub(crate) fn paste_file_path(&mut self, cx: &mut Context<Self>) {
2176 if self.exporting().is_some() {
2177 return;
2178 }
2179 let Some(text) = cx.read_from_clipboard().and_then(|item| item.text()) else {
2180 self.notify_user("Copy a file's path first".into());
2181 cx.notify();
2182 return;
2183 };
2184 let text = text.trim().trim_matches(['"', '\'']);
2185 let path = std::path::PathBuf::from(text);
2186 if !path.is_file() {
2187 self.notify_user(format!("No file at {text}").into());
2188 cx.notify();
2189 return;
2190 }
2191 self.import(&path, cx);
2192 }
2193
2194 /// The `+ S` button and its key: asks the desktop for a file and takes the
2195 /// subtitle tracks out of it -- a standalone `.srt`/`.vtt`/`.ass` is one of
2196 /// them, a Matroska however many are inside. Only the subtitles: the file
2197 /// itself does not join the library, which is what the Import button beside
2198 /// this one is for.
2199 ///
2200 /// The chooser is another process and the user may sit in it, so it runs on
2201 /// a background thread, exactly as [`Player::pick_and_import`] does.
2202 pub(crate) fn pick_and_add_subtitles(&mut self, cx: &mut Context<Self>) {
2203 // What dims the `+ S` button, asked here as well so the key answers the
2204 // same question -- and *before* the chooser rather than after it: a door
2205 // that opens a dialog, waits for a file and only then says the timeline
2206 // was never there is the second door disagreeing with the first.
2207 if let Some(why) = self.enable(ActionId::ImportSubtitles, None).why() {
2208 let text = format!("No subtitles added: {why}");
2209 eprintln!("{text}");
2210 self.notify_user(text.into());
2211 cx.notify();
2212 return;
2213 }
2214 let picked = cx
2215 .background_executor()
2216 .spawn(async { pick_file("edith — subtitles to add") });
2217 cx.spawn(async move |this, cx| {
2218 let picked = picked.await;
2219 this.update(cx, |this, cx| match picked {
2220 Ok(Some(path)) => this.add_subtitles(&path, cx),
2221 // Cancelled: the user already knows what happened.
2222 Ok(None) => {}
2223 Err(_) => this.open_path_entry(PathFor::Subtitles, cx),
2224 })
2225 .ok();
2226 })
2227 .detach();
2228 }
2229
2230 /// Takes a file's subtitle tracks onto the timeline, off the render thread.
2231 /// The walk reads the whole container for its cues
2232 /// (`engine::PlaybackSession::parse_subtitles`) -- ~200 ms on a two-hour 4K
2233 /// remux and 1.3 s on a cold 3 GB one -- and a button that costs the window
2234 /// that many frames is a button that freezes it. So the *parse* is the
2235 /// worker's, whole, and the UI thread only pushes what came back
2236 /// ([`PlaybackSession::add_subtitle_tracks`]): no borrow crosses the await,
2237 /// because the parse is an associated fn that owns nothing.
2238 pub(crate) fn add_subtitles(&mut self, path: &std::path::Path, cx: &mut Context<Self>) {
2239 // Nothing to time the cues against: said now rather than after a walk
2240 // of a 25 GB file that was never going to be kept.
2241 if self.session.is_none() {
2242 self.landed_subtitles(path, None, cx);
2243 return;
2244 }
2245 self.notify_user(format!("Reading {} for subtitles…", file_name(path)).into());
2246 let parsed = cx.background_executor().spawn({
2247 let path = path.to_path_buf();
2248 async move { engine::PlaybackSession::parse_subtitles(&path) }
2249 });
2250 let path = path.to_path_buf();
2251 cx.spawn(async move |this, cx| {
2252 let parsed = parsed.await;
2253 this.update(cx, |this, cx| {
2254 // The dedupe lives inside the push, so a second `+ S` on the
2255 // same file still answers 0 and still says so below.
2256 let added = this
2257 .session
2258 .as_mut()
2259 .map(|session| parsed.and_then(|tracks| pushed(session, &path, tracks)));
2260 this.landed_subtitles(&path, added, cx);
2261 })
2262 .ok();
2263 })
2264 .detach();
2265 cx.notify();
2266 }
2267
2268 /// Every subtitle track a `.srt`/`.vtt`/`.ass` carries, onto the timeline
2269 /// and nowhere else: they are not clips and land on no lane. The cues came
2270 /// off the worker that read the file ([`read_ahead`]), like every other
2271 /// door's do, and what is left here is the push. The engine dedupes by
2272 /// (file, track), so the same `.srt` twice is one row and says so.
2273 pub(crate) fn take_subtitles(
2274 &mut self,
2275 path: &std::path::Path,
2276 subs: Subs,
2277 cx: &mut Context<Self>,
2278 ) {
2279 let added = self
2280 .session
2281 .as_mut()
2282 .map(|session| subs.and_then(|tracks| pushed(session, path, tracks)));
2283 self.landed_subtitles(path, added, cx);
2284 }
2285
2286 /// What the timeline says once the tracks are on it, whichever worker did
2287 /// the reading: the `+ S` button and its key ([`Self::add_subtitles`]), a
2288 /// dropped or imported subtitle file ([`Self::take_subtitles`]), and a
2289 /// window with nothing to time cues against all word the outcome here,
2290 /// once, so no two doors can drift apart.
2291 pub(crate) fn landed_subtitles(
2292 &mut self,
2293 path: &std::path::Path,
2294 added: Option<engine::Result<usize>>,
2295 cx: &mut Context<Self>,
2296 ) {
2297 let text = match added {
2298 Some(Ok(0)) => format!("{}'s subtitles are in the palette already", file_name(path)),
2299 // Where they are and what to do with them: the tracks are in the
2300 // palette and nothing is placed until one is dragged onto an S
2301 // track, which is the whole of what this door does.
2302 Some(Ok(n)) => format!(
2303 "Subtitles {}: {} in the palette — drag one onto an S track ({} adds \
2304 one), showing over the picture meanwhile, {} hides them",
2305 file_name(path),
2306 count_noun(n, "track", "tracks"),
2307 self.keymap.display(ActionId::AddSubtitleLane),
2308 self.keymap.display(ActionId::ToggleSubtitles)
2309 ),
2310 Some(Err(e)) => format!("Subtitle import failed: {e}"),
2311 None => "No subtitles added: no file open".to_string(),
2312 };
2313 eprintln!("{text}");
2314 self.notify_user(text.into());
2315 cx.notify();
2316 }
2317
2318 /// The × on a subtitle row, and the stroke that takes the picked one off:
2319 /// the track leaves the timeline and the pick moves with it. Every index
2320 /// past the one that went moves down
2321 /// ([`engine::Project::remove_subtitles`]), so a pick left where it was
2322 /// would name a *different* track -- and the pick is what an export writes
2323 /// into the file.
2324 ///
2325 /// One undo step, and the palette comes back with the reindex
2326 /// ([`engine::Project::remove_subtitles`]), so `^z` is a way back that
2327 /// works -- [`Player::step_history`] moves the pick back with it and drops
2328 /// the plate the old index drew. The second way back, for a caller that
2329 /// wants the *file's* tracks again, is putting them on
2330 /// ([`Player::pick_and_add_subtitles`]): a door of its own that reads the
2331 /// subtitles alone, never the media, which is what the notice names.
2332 pub(crate) fn remove_subtitle_track(&mut self, track: usize, cx: &mut Context<Self>) {
2333 // The one availability oracle, for the same reason the × on a row and
2334 // the stroke are one call: an empty list is not a failure, it is an
2335 // action with nothing to act on, and the engine's "there is no subtitle
2336 // track 0" is an index nobody typed. A real removal that fails still
2337 // says what the engine said, below.
2338 // The palette's list is what this takes a row off, and an empty list is
2339 // the very fact the toggle is refused by -- so the same arm answers
2340 // both (oracle.rs) rather than a second reading of the same state.
2341 if let Some(why) = self.enable(ActionId::ToggleSubtitles, None).why() {
2342 let text = format!("No subtitles removed: {why}");
2343 eprintln!("{text}");
2344 self.notify_user(text.into());
2345 cx.notify();
2346 return;
2347 }
2348 // Read before it goes: a notice naming an index names nothing.
2349 let name = self
2350 .session
2351 .as_ref()
2352 .and_then(|session| sub_pick_name(session.subtitles(), track))
2353 .unwrap_or_else(|| format!("subtitle track {track}"));
2354 let text = match self
2355 .session
2356 .as_mut()
2357 .map(|session| session.remove_subtitles(track))
2358 {
2359 Some(Ok(())) => {
2360 let left = self
2361 .session
2362 .as_ref()
2363 .map_or(0, |session| session.subtitles().len());
2364 self.sub_track = sub_pick_after_removal(self.sub_track, track, left);
2365 // The cue over the picture goes with the pick: its tile is
2366 // keyed by *where* the cue sits ([`Player::sub_picture`]'s
2367 // `(lane, start_us)`) and never by the track it shows, so the
2368 // index that moved here is not something that cache can be
2369 // asked about. Conservative, and the same drop a history step
2370 // makes for the same reason ([`Player::step_history`]).
2371 //
2372 // corner-cut: its atlas tile is not released -- `close_session`'s
2373 // note, for its reason and with its upgrade path.
2374 self.sub_image = None;
2375 format!(
2376 "{name} removed: {} puts a file's subtitles back in the palette, the file \
2377 itself stays off",
2378 self.keymap.display(ActionId::ImportSubtitles)
2379 )
2380 }
2381 Some(Err(e)) => format!("No subtitles removed: {e}"),
2382 None => "No subtitles removed: no file open".to_string(),
2383 };
2384 eprintln!("{text}");
2385 self.notify_user(text.into());
2386 cx.notify();
2387 }
2388
2389 /// Swaps the whole timeline for one restored from a `.edith`, for
2390 /// [`Player::install_media`]'s reason: the open is a worker's -- a project
2391 /// naming a 24 GB film opens that film, which is the same twenty seconds
2392 /// ([`arrival`] sends every `.edith` through the one queue) -- and this is
2393 /// what is left once it lands. Nothing is replaced until the new session is
2394 /// in hand, so a refusal is shown as the engine worded it and leaves what is
2395 /// playing alone.
2396 pub(crate) fn install_project(
2397 &mut self,
2398 path: &std::path::Path,
2399 opened: Result<PlaybackSession, String>,
2400 cx: &mut Context<Self>,
2401 ) {
2402 if self.exporting().is_some() {
2403 return;
2404 }
2405 let text = match opened {
2406 Ok(mut session) => {
2407 // A `.edith` carries its own saved size and rate, read at
2408 // [`engine::PlaybackSession::open_project`] -- a pick made
2409 // before this project loaded is not this project's.
2410 self.pending_settings = (None, None, None);
2411 self.pending_template = None;
2412 // Another project was opened: a new one still waiting for footage is given up.
2413 self.new_project = None;
2414 self.new_project_fresh = false;
2415 self.fps = session.meta().frame_rate;
2416 // As at the file door above: the window watches in real time.
2417 session.drop_late_pictures(true);
2418 let silent = audio_notice(&session);
2419 crate::export_ui::gui_default_seat(&mut session);
2420 self.session = Some(session);
2421 self.session_swapped();
2422 self.apply_volume();
2423 // The other way round from every other door: a project carries
2424 // its own two switches ([`engine::edith`]) and they are what it
2425 // was saved with, so the window takes *them* rather than
2426 // pushing what it had -- and the buttons say what was loaded.
2427 if let Some(session) = &self.session {
2428 self.proxies_on = session.proxies();
2429 self.auto_proxies_on = session.auto_proxies();
2430 }
2431 self.project_path = path.to_path_buf();
2432 crate::recent::push(path);
2433 // Opened from the `.edith` itself: the file this window will
2434 // autosave beside is the one the user actually chose.
2435 self.autosave_armed = true;
2436 self.disk_known = crate::follow::stamp(path);
2437 self.edited_since_save = false;
2438 self.saved_revision = self.revision_now();
2439 self.name = file_name(path).into();
2440 self.reset_export_default();
2441 // A copied clip names its source by index, which means a
2442 // different file -- or none -- in another project.
2443 self.clipboard.clear();
2444 self.selected.clear();
2445 // A menu can be up while a project is dropped on the window --
2446 // the scrim swallows clicks, never a drop -- and its index
2447 // would name some other timeline's clip. The two clip cards
2448 // hold a (lane, idx) of the old timeline for the same reason.
2449 self.context_menu = None;
2450 self.eq_open = None;
2451 self.color_open = None;
2452 self.transform_open = None;
2453 // Marks are timeline frames of the timeline that was.
2454 self.close_silence();
2455 // A different set of sources: the row that was picked is not
2456 // the file that index names any more -- and neither is the
2457 // subtitle track that was showing.
2458 self.selected_asset = None;
2459 self.asset_picks.clear();
2460 self.sub_track = 0;
2461 // The counters describe one timeline; the eof line must not
2462 // report the old one's frames against the new one.
2463 self.displayed = 0;
2464 self.dropped = 0;
2465 self.started = None;
2466 // Loaded paused at its saved playhead, so the still it owes
2467 // reaches the screen the way a seek's does. The old picture is
2468 // released by the swap in `pump`, as after any other seek.
2469 self.reset_after_reseek();
2470 // A saved view is the project's own place: it is set after the
2471 // reseek (which resets the hand's flag) and wins over the
2472 // first-import fit, so a project with none keeps today's view.
2473 if let Some(state) = crate::view_state::load(path) {
2474 let restored = crate::view_state::restored(&state);
2475 self.scale = restored.scale;
2476 self.lane_h = restored.lane_h;
2477 self.panned = restored.panned;
2478 self.fitted_bed = restored.fitted_bed;
2479 self.fit_pending = restored.fit_pending;
2480 self.viewer = state.viewer;
2481 self.viewer_pan = (0., 0.);
2482 self.collapsed_bins = state.closed_bins.iter().copied().collect();
2483 self.sections_mem = state.sections.clone();
2484 self.sections_anchor = None;
2485 self.waveforms = state.waveforms;
2486 self.scrub_audio = state.scrub_audio;
2487 } else {
2488 self.viewer = crate::viewer_view::Prefs::default();
2489 self.viewer_pan = (0., 0.);
2490 self.collapsed_bins.clear();
2491 self.sections_mem.clear();
2492 self.sections_anchor = None;
2493 self.waveforms = true;
2494 self.scrub_audio = true;
2495 }
2496 // Offered right after the load it is about: `notify_loaded` puts the
2497 // question on its own sticky toast, under the "Loaded" line.
2498 self.recovery_sidecar = Self::recovery_offer(path, true);
2499 format!("Loaded {}{}", file_name(path), silent.unwrap_or_default())
2500 }
2501 Err(_) => self.open_refused(path),
2502 };
2503 eprintln!("{text}");
2504 self.notify_loaded(text);
2505 cx.notify();
2506 }
2507
2508 /// Says what a load did. A recovery on offer is its own sticky toast with
2509 /// Recover and Discard: it stays on the bar until one of them is pressed, so
2510 /// the question cannot time out under the person's nose.
2511 fn notify_loaded(&mut self, text: String) {
2512 self.notify_user(text.into());
2513 if let Some(sidecar) = self.recovery_sidecar.clone() {
2514 push_sticky_toast(
2515 &mut self.notices,
2516 recovery_words(&sidecar).into(),
2517 Tone::Info,
2518 vec![ToastAction::Recover, ToastAction::Discard],
2519 );
2520 }
2521 }
2522
2523 /// Takes the recovery question off the bar: the one the recovery answers
2524 /// have just been given to, or that a save made moot.
2525 fn drop_recovery_toasts(&mut self) {
2526 self.notices
2527 .retain(|toast| !toast.actions.contains(&ToastAction::Recover));
2528 }
2529
2530 /// Whether a close has to be answered instead of obeyed: unsaved edits on
2531 /// the timeline, or an export that has not finished.
2532 pub(crate) fn close_needs_answer(&self) -> bool {
2533 self.close_dirty() || self.queue.unfinished() > 0
2534 }
2535
2536 /// Unsaved work on the timeline: the save half of the close question. It
2537 /// reads `edited_since_save` (a real save clears it), never the autosave's
2538 /// flag: an autosave is crash recovery, not saving, so an edit the autosave
2539 /// has already written still asks on close.
2540 pub(crate) fn close_dirty(&self) -> bool {
2541 let clips = self.session.as_ref().map_or(0, |session| {
2542 session
2543 .lanes()
2544 .into_iter()
2545 .map(|lane| session.lane_clips(lane).len())
2546 .sum()
2547 });
2548 Self::close_asks(clips, self.edited_since_save)
2549 }
2550
2551 /// The close question as a value: clips on the timeline and an edit since
2552 /// the last real save. Split out of [`Player::close_dirty`] so the rule can
2553 /// be read and tested without a window or a session. An empty timeline
2554 /// closes the way it always did.
2555 pub(crate) fn close_asks(clips: usize, edited: bool) -> bool {
2556 clips > 0 && edited
2557 }
2558
2559 /// Whether a save has to be answered instead of obeyed: `project_path`
2560 /// names a file on disk that this window itself did not put there --
2561 /// neither loaded ([`Player::install_project`]) nor written
2562 /// ([`Player::save_project`]) -- so the first ^s would clobber a
2563 /// `.edith` this timeline only derives its name from beside an
2564 /// imported media file (user 2026-09-11). `autosave_armed` is the
2565 /// whole difference: once this window's own save has confirmed the
2566 /// overwrite, later saves on the file are silent again.
2567 pub(crate) fn save_needs_answer(&self) -> bool {
2568 Self::save_asks(self.project_path.exists(), self.autosave_armed)
2569 }
2570
2571 /// The overwrite question as a value: a target on disk and a window
2572 /// that has not earned the write. Split out of
2573 /// [`Player::save_needs_answer`] so the rule can be read and tested
2574 /// without a window or a session, the way [`Player::close_asks`] is.
2575 pub(crate) fn save_asks(target_exists: bool, armed: bool) -> bool {
2576 target_exists && !armed
2577 }
2578
2579 /// Writes the timeline back to its project file -- the confirmed write.
2580 /// The overwrite question, when one is owed at all, was asked by Save's
2581 /// door ([`Player::save_guarded`]) or already answered at the quit
2582 /// plate; the notice here is the confirmation, not the permission.
2583 /// Returns whether the file was written, so a close that is answered with
2584 /// Save only goes once the work is actually on disk.
2585 pub(crate) fn save_project(&mut self, cx: &mut Context<Self>) -> bool {
2586 let saved = self
2587 .session
2588 .as_ref()
2589 .map(|session| session.save_project_noted(&self.project_path));
2590 let written = matches!(saved, Some(Ok(_)));
2591 let mut shortened = Vec::new();
2592 let text = match saved {
2593 Some(Ok(notes)) => {
2594 shortened = notes;
2595 // The manual save is now the newest copy of the timeline, so
2596 // the sidecar's job is done -- left behind it would outlive
2597 // its use and, if it later grew younger than a *later* manual
2598 // save through some clock oddity, could be offered as
2599 // "recovery" over a file that already holds everything it did.
2600 for armed in [true, false] {
2601 if let Some(autosave) = Self::autosave_target(&self.project_path, armed) {
2602 let _ = std::fs::remove_file(autosave);
2603 }
2604 }
2605 self.autosave_dirty = false;
2606 self.autosave_edits = 0;
2607 // The file now holds everything the offered autosave did: the
2608 // question is answered by the save itself.
2609 self.recovery_sidecar = None;
2610 self.drop_recovery_toasts();
2611 self.save_view_state();
2612 // A manual save is exactly the event this flag exists to
2613 // require: whatever `project_path` was derived from, it now
2614 // names a file the user just chose to write.
2615 // The export's default follows the project to where it was just saved, unless
2616 // the person had already chosen one.
2617 let was_default = self.export_path == self.default_export_target();
2618 self.autosave_armed = true;
2619 if was_default || self.export_path.as_os_str().is_empty() {
2620 self.reset_export_default();
2621 }
2622 // Our own write: the stamp it left is what the file is now, so
2623 // the follow tick reads it as unchanged and not as the agent's.
2624 self.disk_known = crate::follow::stamp(&self.project_path);
2625 self.edited_since_save = false;
2626 self.saved_revision = self.revision_now();
2627 crate::recent::push(&self.project_path);
2628 format!("Saved {}", file_name(&self.project_path))
2629 }
2630 Some(Err(e)) => format!("Save failed: {e}"),
2631 None => "Nothing to save: no file open".to_string(),
2632 };
2633 eprintln!("{text}");
2634 self.notify_user(text.into());
2635 for note in shortened_notes(&shortened) {
2636 eprintln!("{note}");
2637 self.notify_user(note.into());
2638 }
2639 cx.notify();
2640 written
2641 }
2642
2643 /// Drops the unsaved edits for good, as the close question's Don't save
2644 /// does: the autosave goes on disk and in memory, so the next open does not
2645 /// offer the edits back as recovery. Nothing else is touched -- the project
2646 /// file keeps what it had.
2647 pub(crate) fn discard_unsaved_edits(&mut self) {
2648 for armed in [true, false] {
2649 if let Some(autosave) = Self::autosave_target(&self.project_path, armed) {
2650 Self::discard_sidecar(&autosave);
2651 }
2652 }
2653 if let Some(sidecar) = self.recovery_sidecar.take() {
2654 Self::discard_sidecar(&sidecar);
2655 }
2656 self.drop_recovery_toasts();
2657 self.autosave_dirty = false;
2658 self.autosave_edits = 0;
2659 self.edited_since_save = false;
2660 self.saved_revision = self.revision_now();
2661 }
2662
2663 /// Keeps the view the project is left in, beside the project's hash
2664 /// ([`crate::view_state`]). Best effort: a view that fails to write costs
2665 /// the next open its place and nothing else. A project with no file yet
2666 /// (its first import has not been saved) has nothing to key on.
2667 pub(crate) fn save_view_state(&self) {
2668 if self.session.is_none() || !self.project_path.is_file() {
2669 return;
2670 }
2671 let state = crate::view_state::ViewState {
2672 pps: self.scale.pps,
2673 start: self.scale.start,
2674 lane_h: self.lane_h.clone(),
2675 viewer: self.viewer,
2676 closed_bins: {
2677 let mut ids: Vec<u32> = self.collapsed_bins.iter().copied().collect();
2678 ids.sort_unstable();
2679 ids
2680 },
2681 sections: self.sections_mem.clone(),
2682 waveforms: self.waveforms,
2683 scrub_audio: self.scrub_audio,
2684 };
2685 let _ = crate::view_state::save(&self.project_path, &state);
2686 }
2687
2688 /// Save's door: asks before the first overwrite of a file this window
2689 /// never put there, saves straight through once the file is the
2690 /// window's own. Raising the question does not save -- the overwrite
2691 /// plate (the root `on_key_down` in `ui::stance`) owns the keyboard
2692 /// until it is answered, and only its `enter` comes back to
2693 /// [`Player::save_project`], which is what arms `autosave_armed` and
2694 /// makes every later save on the file silent.
2695 pub(crate) fn save_guarded(&mut self, cx: &mut Context<Self>) {
2696 if self.save_needs_answer() {
2697 self.save_ask = true;
2698 cx.notify();
2699 return;
2700 }
2701 self.save_project(cx);
2702 }
2703
2704 /// Marks that an edit has landed since the sidecar last caught up, and
2705 /// when: the door every edit that funnels through [`Player::act`] or a
2706 /// timeline gesture calls on its way through. Cheap and safe to call on a
2707 /// refusal too -- an autosave a beat early costs nothing a real edit
2708 /// would not have earned anyway.
2709 pub(crate) fn mark_dirty(&mut self) {
2710 // An edit can change the picture as shot at the frame on screen, so the compare view reads it again.
2711 self.before_at = None;
2712 self.autosave_dirty = true;
2713 self.edited_since_save = true;
2714 self.autosave_edits = self.autosave_edits.saturating_add(1);
2715 // An edit made while the recovery is on offer: the offer now says what
2716 // recovering costs, since the edits it would replace are real. `act`
2717 // calls this before an edit lands, so the revision is not read here.
2718 if self.recovery_sidecar.is_some() {
2719 self.word_recovery_replaces();
2720 }
2721 }
2722
2723 /// An edit that changes what the window is (a sequence made, copied, opened or nested, a
2724 /// marker dropped): the autosave is written soon after it, not at the next 20 edits, so a
2725 /// crash right after it loses nothing. Throttled by [`AUTOSAVE_THROTTLE`].
2726 pub(crate) fn mark_structural(&mut self) {
2727 self.mark_dirty();
2728 self.autosave_urgent = true;
2729 }
2730
2731 /// The engine revision of the timeline as it stands, `None` with no session.
2732 pub(crate) fn revision_now(&self) -> Option<u64> {
2733 self.session.as_ref().map(PlaybackSession::revision)
2734 }
2735
2736 /// The mark an undo or a redo leaves, after [`Player::mark_dirty`]: the
2737 /// window is edited unless the timeline it landed on is the saved one. Undo
2738 /// and redo are the only steps that can walk back to the saved timeline, so
2739 /// this is the one place the flag is cleared by an edit's door.
2740 pub(crate) fn settle_saved_point(&mut self) {
2741 self.edited_since_save = self.revision_now() != self.saved_revision;
2742 }
2743
2744 /// Puts the recovery's cost on its own toast, in place of the age-only line,
2745 /// once the timeline has moved off the saved one.
2746 fn word_recovery_replaces(&mut self) {
2747 if self.recovery_sidecar.is_none() {
2748 return;
2749 }
2750 let text: SharedString = recovery_replaces_words().into();
2751 if let Some(toast) = self
2752 .notices
2753 .iter_mut()
2754 .find(|toast| toast.actions.contains(&ToastAction::Recover))
2755 {
2756 toast.text = text;
2757 }
2758 }
2759
2760 /// Where the autosave for `project_path` goes. Beside a project this window
2761 /// opened or saved (`armed`), as `<stem>.autosave.edith`, the name
2762 /// `edith_mcp` reads too. An untitled session (`armed` false) has a
2763 /// `project_path` that is only a guess at where a save would land, and
2764 /// that file may be somebody's real project, so its autosave goes to the
2765 /// state directory instead, one file per guessed path. `None` when there is
2766 /// no path at all.
2767 pub(crate) fn autosave_target(project_path: &Path, armed: bool) -> Option<PathBuf> {
2768 if project_path.as_os_str().is_empty() {
2769 return None;
2770 }
2771 let stem = project_path
2772 .file_stem()
2773 .map_or_else(|| "untitled".to_string(), |s| s.to_string_lossy().into_owned());
2774 if armed {
2775 return Some(project_path.with_file_name(format!("{stem}.autosave.edith")));
2776 }
2777 // FNV-1a over the path's bytes: a name that stays the same across builds,
2778 // which `DefaultHasher` does not promise.
2779 let hash = project_path
2780 .as_os_str()
2781 .as_encoded_bytes()
2782 .iter()
2783 .fold(0xcbf2_9ce4_8422_2325u64, |h, b| (h ^ u64::from(*b)).wrapping_mul(0x100_0000_01b3));
2784 Some(Self::autosave_state_dir()?.join(format!("{stem}-{hash:016x}.autosave.edith")))
2785 }
2786
2787 /// `$XDG_STATE_HOME/edith`, or `~/.local/state/edith` when that is unset or
2788 /// not an absolute path, as the XDG base directory spec says.
2789 pub(crate) fn autosave_state_dir() -> Option<PathBuf> {
2790 let state = std::env::var_os("XDG_STATE_HOME")
2791 .filter(|v| !v.is_empty() && Path::new(v).is_absolute())
2792 .map(PathBuf::from)
2793 .or_else(|| {
2794 std::env::var_os("HOME").map(|home| PathBuf::from(home).join(".local").join("state"))
2795 })?;
2796 Some(state.join("edith"))
2797 }
2798
2799 /// The Recover answer to the recovery notice: the autosave's unsaved edits
2800 /// go on top of the saved project ([`recovered_session`]), and the window's
2801 /// own timeline as it stands is kept one undo step back, so the recovery
2802 /// replaces the edits made since the file was opened without losing them:
2803 /// undo brings them back ([`PlaybackSession::adopt_as_step`]). Nothing here
2804 /// writes the project file: the next thing to touch it is still only a
2805 /// manual save.
2806 pub(crate) fn recover_from_sidecar(&mut self, cx: &mut Context<Self>) {
2807 let Some(sidecar) = self.recovery_sidecar.clone() else {
2808 return;
2809 };
2810 let project_path = self.project_path.clone();
2811 // An armed window's saved file is the base the autosave goes on top of;
2812 // an untitled one has no saved file to be the base.
2813 let armed = self.autosave_armed;
2814 let opened = match recovered_session(armed.then_some(project_path.as_path()), &sidecar) {
2815 Ok(recovered) => match self.session.take() {
2816 // The window's own timeline becomes the step back: its history
2817 // stays, and its current state is one undo step away.
2818 Some(mut current) => {
2819 let mark = current.step_mark();
2820 if current.adopt_as_step(&recovered) {
2821 current.name_step(mark, RECOVER_STEP);
2822 Ok(current)
2823 } else {
2824 self.session = Some(current);
2825 Err("the recovered edits do not fit on the edits made here as one step".to_string())
2826 }
2827 }
2828 None => Ok(recovered),
2829 },
2830 Err(e) => Err(e),
2831 };
2832 if let Err(e) = opened {
2833 // Nothing was taken or dropped: the window is as it was, and the
2834 // autosave stays on disk for another try or for Discard. Said in a
2835 // dialog, since the reason can be a sentence long.
2836 let kept = if self.edited_since_save {
2837 "Your edits in this window are still here"
2838 } else {
2839 "Your saved version is open"
2840 };
2841 self.recovery_failure = Some(format!("Reason: {e}. {kept}. Nothing was deleted."));
2842 cx.notify();
2843 return;
2844 }
2845 // The saved timeline is the file's, not the one recovery stands on:
2846 // install_project would take the new session's as saved, so keep ours.
2847 let saved_revision = self.saved_revision;
2848 // The export's own default is the project's, so a path the person picked
2849 // after opening is theirs to keep through the recovery.
2850 let export_path = self.export_path.clone();
2851 self.install_project(&project_path, opened, cx);
2852 self.export_path = export_path;
2853 self.saved_revision = saved_revision;
2854 // `install_project` arms the window, as any opened `.edith` does. An
2855 // untitled session stays unarmed: its `project_path` is still a guess.
2856 self.autosave_armed = armed;
2857 // install_project re-ran the offer on its way in and found the same
2858 // autosave still younger; offering it back here would be the one loop.
2859 self.recovery_sidecar = None;
2860 self.drop_recovery_toasts();
2861 // The recovered edits are not in the file yet, so the next autosave
2862 // must write them out.
2863 self.mark_dirty();
2864 self.notify_user(
2865 format!(
2866 "Recovered unsaved edits · undo {}",
2867 self.keymap.display(ActionId::Undo)
2868 )
2869 .into(),
2870 );
2871 cx.notify();
2872 }
2873
2874 /// The Discard answer to the recovery notice: the autosave goes, on disk as
2875 /// well as in memory, so the offer does not come back on the next open.
2876 pub(crate) fn discard_recovery(&mut self) {
2877 if let Some(sidecar) = self.recovery_sidecar.take() {
2878 Self::discard_sidecar(&sidecar);
2879 }
2880 self.drop_recovery_toasts();
2881 }
2882
2883 /// Deletes an autosave the person declined to recover: on disk as well as in
2884 /// memory. Left behind, an unread
2885 /// autosave from a scratch session would keep outdating the real project
2886 /// it sits beside and reappear as "recovery" on every open of that file
2887 /// (reference-editor behaviour: a declined backup is discarded, not kept
2888 /// around to ask again). Pure at the path level so it needs no `Player`
2889 /// to test -- a missing sidecar is not an error, only a no-op.
2890 pub(crate) fn discard_sidecar(sidecar: &Path) {
2891 let _ = std::fs::remove_file(sidecar);
2892 }
2893
2894 /// Whether opening `project_path` should offer a recovery, and the autosave
2895 /// it would recover. An armed project (a `.edith` this window opened or
2896 /// saved) is offered only when its autosave is strictly the younger of the
2897 /// two. An untitled session has no saved file to be newer than, so any
2898 /// autosave left for it is unsaved work. Reads only the filesystem: no
2899 /// session, no `Player`, so a test can ask it with nothing but paths.
2900 pub(crate) fn recovery_offer(project_path: &Path, armed: bool) -> Option<PathBuf> {
2901 let sidecar = Self::autosave_target(project_path, armed)?;
2902 if !armed {
2903 return sidecar.is_file().then_some(sidecar);
2904 }
2905 let project_mtime = std::fs::metadata(project_path)
2906 .and_then(|m| m.modified())
2907 .ok()?;
2908 let sidecar_mtime = std::fs::metadata(&sidecar)
2909 .and_then(|m| m.modified())
2910 .ok()?;
2911 (sidecar_mtime > project_mtime).then_some(sidecar)
2912 }
2913
2914 /// Starts the one background loop that ticks the autosave: every second,
2915 /// forever, for as long as the window is up. Cheap to run idle --
2916 /// a tick with nothing dirty does nothing but reschedule itself -- so one
2917 /// loop for the window's whole life is simpler than arming and disarming
2918 /// a timer around every edit.
2919 pub(crate) fn start_autosave(&mut self, cx: &mut Context<Self>) {
2920 cx.spawn(async move |this, cx| {
2921 loop {
2922 cx.background_executor()
2923 .timer(std::time::Duration::from_secs(1))
2924 .await;
2925 if this.update(cx, |this, cx| this.autosave_tick(cx)).is_err() {
2926 return;
2927 }
2928 }
2929 })
2930 .detach();
2931 }
2932
2933 /// Starts the loop that watches the open project file for a write from
2934 /// outside (the agent's, through `edith_mcp`): every half second, for as
2935 /// long as the window is up. A stat each tick, nothing more.
2936 pub(crate) fn start_follow(&mut self, cx: &mut Context<Self>) {
2937 cx.spawn(async move |this, cx| {
2938 loop {
2939 cx.background_executor()
2940 .timer(Duration::from_millis(500))
2941 .await;
2942 if this.update(cx, |this, cx| this.follow_tick(cx)).is_err() {
2943 return;
2944 }
2945 }
2946 })
2947 .detach();
2948 }
2949
2950 /// One look at the project file. Only a project this window opened or
2951 /// saved is followed: a derived path names a file the window never
2952 /// claimed. Acting on what [`follow_decision`] says is all this does.
2953 fn follow_tick(&mut self, cx: &mut Context<Self>) {
2954 if !self.autosave_armed || self.exporting().is_some() {
2955 return;
2956 }
2957 let now = crate::follow::stamp(&self.project_path);
2958 match follow_decision(self.disk_known, now, self.edited_since_save) {
2959 Follow::Wait | Follow::Idle => {}
2960 Follow::Adopt => self.disk_known = now,
2961 Follow::Reload => self.reload_from_disk(cx),
2962 Follow::Ask => {
2963 // Recorded as answered before the question is asked, so the
2964 // same change does not ask again on the next tick.
2965 self.disk_known = now;
2966 self.notify_user_actions(
2967 "Project changed on disk".into(),
2968 vec![ToastAction::Reload, ToastAction::KeepMine],
2969 );
2970 cx.notify();
2971 }
2972 }
2973 }
2974
2975 /// Reloads the open project from its file, in place. The timeline becomes
2976 /// the file's; the playhead stays where it was (clamped to the file's own
2977 /// length); the view (zoom, scroll, lane heights) stays as it was. Play
2978 /// stays paused, as a load always leaves it. Undo history and the selection
2979 /// belong to the old timeline and go with it.
2980 pub(crate) fn reload_from_disk(&mut self, cx: &mut Context<Self>) {
2981 if self.exporting().is_some() || !self.autosave_armed || self.session.is_none() {
2982 return;
2983 }
2984 let path = self.project_path.clone();
2985 let at = self.playhead(self.drawn_duration());
2986 let scale = self.scale;
2987 let lane_h = self.lane_h.clone();
2988 let (panned, fitted_bed, fit_pending) =
2989 (self.panned, self.fitted_bed, self.fit_pending);
2990 let before = self.notices.back().map(|toast| toast.id);
2991 let opened = PlaybackSession::open_project(&path).map_err(|e| e.to_string());
2992 let ok = opened.is_ok();
2993 self.install_project(&path, opened, cx);
2994 // Recorded whether or not the open took: a file that will not open is
2995 // answered once, not retried on every tick.
2996 self.disk_known = crate::follow::stamp(&path);
2997 if !ok {
2998 return;
2999 }
3000 // install_project's own "Loaded" line is replaced by the one that says
3001 // what happened here. Taken off only if install pushed one.
3002 if self.notices.back().map(|toast| toast.id) != before {
3003 self.notices.pop_back();
3004 }
3005 self.recovery_sidecar = None;
3006 self.scale = scale;
3007 self.lane_h = lane_h;
3008 // A seek takes the view back to the playhead; the view is put back
3009 // after it, so the reload keeps where the person was looking.
3010 let dur = self.drawn_duration();
3011 self.seek(at.clamp(0., dur), cx);
3012 (self.panned, self.fitted_bed, self.fit_pending) = (panned, fitted_bed, fit_pending);
3013 self.notify_user("Reloaded — changed on disk".into());
3014 cx.notify();
3015 }
3016
3017 /// The reload asked for by the menu or the palette. Unsaved edits are not
3018 /// dropped on a click: they get the same question a changed file does.
3019 pub(crate) fn reload_request(&mut self, cx: &mut Context<Self>) {
3020 if self.exporting().is_some() || !self.autosave_armed || self.session.is_none() {
3021 return;
3022 }
3023 if self.edited_since_save {
3024 self.notify_user_actions(
3025 "Reload would drop unsaved edits".into(),
3026 vec![ToastAction::Reload, ToastAction::KeepMine],
3027 );
3028 cx.notify();
3029 return;
3030 }
3031 self.reload_from_disk(cx);
3032 }
3033
3034 /// Whether a tick is allowed to write at all: dirty and not mid-export.
3035 /// Pure, so a test can ask it with two bools and no `Player` to build.
3036 fn autosave_gate(dirty: bool, exporting: bool) -> bool {
3037 dirty && !exporting
3038 }
3039
3040 /// One tick of the loop above. Writes the autosave when [`AUTOSAVE_EDITS`]
3041 /// edits have landed since the last write, or the session has been dirty
3042 /// for [`AUTOSAVE_PERIOD`] without one. Never while an export is running:
3043 /// the two would fight the same disk and worker for nothing an export
3044 /// needs. The write is [`PlaybackSession::save_autosave`]: atomic (a
3045 /// `.part` file, fsynced, renamed over), and it cannot refuse over a
3046 /// session's state the way a manual save may. Failure is a stderr line,
3047 /// never a notice: a modal over a lost autosave would be worse than the risk.
3048 fn autosave_tick(&mut self, cx: &mut Context<Self>) {
3049 // An autosave on offer is the unsaved work the person has not answered
3050 // for yet: writing this session over it would destroy that work silently.
3051 if self.recovery_sidecar.is_some() {
3052 return;
3053 }
3054 // Off writes no autosave at all: the Settings row says so.
3055 let Some(period) = self.autosave_secs.map(Duration::from_secs) else {
3056 return;
3057 };
3058 if !Self::autosave_gate(self.autosave_dirty, self.exporting().is_some()) {
3059 return;
3060 }
3061 let now = Instant::now();
3062 let overdue = self
3063 .autosave_last_run
3064 .is_none_or(|t| now.duration_since(t) >= period);
3065 // A structural edit is written once the throttle has let the last write go by.
3066 let urgent = self.autosave_urgent
3067 && self
3068 .autosave_last_run
3069 .is_none_or(|t| now.duration_since(t) >= AUTOSAVE_THROTTLE);
3070 if self.autosave_edits < AUTOSAVE_EDITS && !overdue && !urgent {
3071 return;
3072 }
3073 let Some(target) = Self::autosave_target(&self.project_path, self.autosave_armed) else {
3074 return;
3075 };
3076 let Some(session) = self.session.as_ref() else {
3077 return;
3078 };
3079 if let Some(dir) = target.parent() {
3080 let _ = std::fs::create_dir_all(dir);
3081 }
3082 match session.save_autosave(&target) {
3083 Ok(()) => {
3084 self.autosave_dirty = false;
3085 self.autosave_edits = 0;
3086 self.autosave_urgent = false;
3087 self.autosave_last_run = Some(now);
3088 }
3089 Err(e) => eprintln!("AUTOSAVE FAILED: {e}"),
3090 }
3091 cx.notify();
3092 }
3093
3094 /// A new empty track under the ones already there. One undo step in the
3095 /// engine, so the stroke that takes back an edit takes back a track too, and
3096 /// no reseek: nothing plays differently until something is dropped on it.
3097 /// The selection stays -- the lanes it indexes into have not moved.
3098 pub(crate) fn add_lane(&mut self, kind: LaneKind, cx: &mut Context<Self>) {
3099 if self.exporting().is_some() {
3100 return;
3101 }
3102 match &mut self.session {
3103 Some(session) => {
3104 let lane = session.add_lane(kind);
3105 self.notify_user(
3106 format!(
3107 "{} added · undo {}",
3108 lane.label(),
3109 self.keymap.display(ActionId::Undo)
3110 )
3111 .into(),
3112 );
3113 }
3114 None => self.notify_user("No track added: no file open".into()),
3115 }
3116 cx.notify();
3117 }
3118
3119 /// The × in a track's header: the add taken back, one undo step, and the
3120 /// engine's own words when it refuses -- those name the clips still on the
3121 /// track, so the notice says what to delete first. A removal never deletes a
3122 /// clip.
3123 ///
3124 /// Everything holding a `(lane, idx)` is dropped, because the tracks below
3125 /// the one that went have just moved up an `ord`
3126 /// ([`engine::Project::remove_lane`]): a selection or an open card kept
3127 /// across it would be pointing at the *next* track's clip.
3128 pub(crate) fn remove_lane(&mut self, lane: Lane, cx: &mut Context<Self>) {
3129 if self.exporting().is_some() {
3130 return;
3131 }
3132 let removed = self
3133 .session
3134 .as_mut()
3135 .map(|session| session.remove_lane(lane));
3136 let text = match removed {
3137 Some(Ok(())) => {
3138 // The arm lives here, on the one answer that means the track
3139 // went: `remove_lane` refuses a track still holding clips or
3140 // captions, and the last of its kind, and both used to arrive
3141 // with the `unsaved` ghost already lit behind them.
3142 self.mark_dirty();
3143 self.selected.clear();
3144 self.context_menu = None;
3145 self.eq_open = None;
3146 self.color_open = None;
3147 self.transform_open = None;
3148 self.speed_open = None;
3149 self.effects_open = None;
3150 self.close_silence();
3151 // The shown lane with them: a `Lane` is a position among
3152 // its kind, so a pick now names another track -- the same
3153 // reason the selection and the cards go. The first lane
3154 // left is drawn ([`subs::active_lane`]).
3155 self.sub_lane = None;
3156 format!(
3157 "{} removed — {} brings it back",
3158 lane.label(),
3159 self.keymap.display(ActionId::Undo)
3160 )
3161 }
3162 Some(Err(e)) => format!("No track removed: {e}"),
3163 None => "No track removed: no file open".to_string(),
3164 };
3165 self.notify_user(text.into());
3166 cx.notify();
3167 }
3168
3169 /// A header let go over another header: the track in the hand takes that
3170 /// one's place in the stack, clips and all
3171 /// ([`engine::Project::move_lane`]), one undo step. The gesture every
3172 /// editor reorders tracks with, and the only way the order is ever changed
3173 /// -- there is no second list of it to keep in step.
3174 ///
3175 /// Display order is the stack, so moving a video track past another video
3176 /// track changes which picture wins, here and in an export alike; audio is
3177 /// summed and does not care, which is what makes `A1` above `V1` a purely
3178 /// visual arrangement. A label is a position among the tracks of its kind,
3179 /// so a track that crossed one of its own kind comes back under a different
3180 /// name -- and everything holding a `(lane, idx)` is dropped exactly then,
3181 /// for [`Player::remove_lane`]'s reason: those handles now name another
3182 /// track's clip. A move that crossed only the other kind renames nothing
3183 /// and keeps the selection.
3184 pub(crate) fn reorder_lane(&mut self, lane: Lane, onto: Lane, cx: &mut Context<Self>) {
3185 self.lane_drop = None;
3186 if self.exporting().is_some() {
3187 return;
3188 }
3189 let Some(session) = self.session.as_mut() else {
3190 return;
3191 };
3192 let Some(to) = session.lanes().iter().position(|&l| l == onto) else {
3193 return;
3194 };
3195 // Picked up and put back down where it was is a click, and a click says
3196 // nothing -- `move_lane` refuses it and every other no-op.
3197 let Some(moved) = session.move_lane(lane, to) else {
3198 cx.notify();
3199 return;
3200 };
3201 self.mark_dirty();
3202 if moved != lane {
3203 self.selected.clear();
3204 self.context_menu = None;
3205 self.eq_open = None;
3206 self.color_open = None;
3207 self.transform_open = None;
3208 self.speed_open = None;
3209 self.effects_open = None;
3210 self.close_silence();
3211 // The shown lane with them: a `Lane` is a position among its
3212 // kind, so a pick now names another track -- the same reason
3213 // the selection and the cards go.
3214 self.sub_lane = None;
3215 }
3216 self.notify_user(
3217 format!(
3218 "{} is track {} now · undo {}",
3219 moved.label(),
3220 to + 1,
3221 self.keymap.display(ActionId::Undo)
3222 )
3223 .into(),
3224 );
3225 cx.notify();
3226 }
3227
3228 /// What the remove keys act on: the last track of that kind, which is the
3229 /// one the matching add key appended. Nothing at all before a file is open,
3230 /// where the timeline drawn is a placeholder pair.
3231 pub(crate) fn remove_last_lane(&mut self, kind: LaneKind, cx: &mut Context<Self>) {
3232 let last = self
3233 .session
3234 .as_ref()
3235 .and_then(|session| session.lanes().into_iter().rfind(|l| l.kind == kind));
3236 match last {
3237 Some(lane) => self.remove_lane(lane, cx),
3238 // Two different nothings: no timeline at all, and a timeline whose
3239 // lanes of this kind have all gone -- which is the ordinary state of
3240 // the subtitle ones, since a project starts with none. "Open a file
3241 // first" over an open file is a notice that reads as a bug.
3242 None => {
3243 self.notify_user(
3244 match self.session.is_some() {
3245 true => format!(
3246 "No track removed: there is no {} track to remove",
3247 match kind {
3248 LaneKind::Video => "video",
3249 LaneKind::Audio => "audio",
3250 LaneKind::Subtitle => "subtitle",
3251 }
3252 ),
3253 false => "No track removed: no file open".to_string(),
3254 }
3255 .into(),
3256 );
3257 cx.notify();
3258 }
3259 }
3260 }
3261}
3262
3263impl Player {
3264 /// Where an export goes until the person says otherwise: [`default_export_target`](Self::default_export_target),
3265 /// which is the format the card is set to, so a new file keeps that choice.
3266 pub(crate) fn reset_export_default(&mut self) {
3267 self.export_path = self.default_export_target();
3268 }
3269
3270 /// The export's default target right now: [`default_export_path`] over this
3271 /// session's sources, the first of which names an untitled project.
3272 pub(crate) fn default_export_target(&self) -> PathBuf {
3273 let sources: Vec<&Path> = self
3274 .session
3275 .as_ref()
3276 .map_or_else(Vec::new, |s| s.sources().iter().map(|s| s.path.as_path()).collect());
3277 let first_clip = sources.first().map(|path| crate::files::stem(path));
3278 default_export_path(&self.project_path, self.autosave_armed || self.new_project_fresh, first_clip.as_deref(), &sources, self.format)
3279 }
3280}
3281
3282/// [`Player::reset_export_default`]'s rule. A saved project is named after itself,
3283/// an untitled one after its first clip (`<clip> edit`), and nothing with neither is
3284/// "Untitled". The name never equals one of `sources`: a taken one gets " (2)", " (3)"
3285/// and so on until it is free.
3286pub(crate) fn default_export_path(
3287 project: &Path,
3288 saved: bool,
3289 first_clip: Option<&str>,
3290 sources: &[&Path],
3291 format: Format,
3292) -> PathBuf {
3293 default_path_with_ext(project, saved, first_clip, sources, format.ext())
3294}
3295
3296/// [`default_export_path`] for any extension: a timeline export ([`Player::export_timeline`])
3297/// lands beside an export of the same project, under the same name rule.
3298pub(crate) fn default_path_with_ext(
3299 project: &Path,
3300 saved: bool,
3301 first_clip: Option<&str>,
3302 sources: &[&Path],
3303 ext: &str,
3304) -> PathBuf {
3305 let stem = match (saved, project.file_stem(), first_clip) {
3306 (true, Some(stem), _) => stem.to_string_lossy().into_owned(),
3307 (_, _, Some(clip)) => format!("{clip} edit"),
3308 _ => "Untitled".to_string(),
3309 };
3310 let folder = engine::export::default_export_folder(project);
3311 let mut n = 1;
3312 loop {
3313 let name = match n {
3314 1 => stem.clone(),
3315 n => format!("{stem} ({n})"),
3316 };
3317 let path = folder.join(format!("{name}.{ext}"));
3318 if !is_a_source(&path, sources) {
3319 return path;
3320 }
3321 n += 1;
3322 }
3323}
3324
3325/// The lanes a drop below the stack needs, made in the open batch: a picture gets a video
3326/// lane and an audio lane of the same number, so [`PlaybackSession::place_take`] finds its
3327/// partner, and a sound gets an audio lane. Returns the lane the file lands on.
3328fn add_drop_lanes(session: &mut PlaybackSession, path: &Path) -> Lane {
3329 if engine::is_audio(path) {
3330 return session.add_lane(LaneKind::Audio);
3331 }
3332 let count = |session: &PlaybackSession, kind: LaneKind| {
3333 session.lanes().into_iter().filter(|l| l.kind == kind).count()
3334 };
3335 let ord = count(session, LaneKind::Video).max(count(session, LaneKind::Audio));
3336 while count(session, LaneKind::Video) <= ord {
3337 session.add_lane(LaneKind::Video);
3338 }
3339 while count(session, LaneKind::Audio) <= ord {
3340 session.add_lane(LaneKind::Audio);
3341 }
3342 Lane::new(LaneKind::Video, ord)
3343}
3344
3345#[cfg(test)]
3346mod autosave_tests {
3347 use super::*;
3348
3349 /// The three cases the user named: an empty timeline closes, a saved one
3350 /// closes, and only work that is both there and unsaved asks first --
3351 /// the rule the window's close request routes through.
3352 #[test]
3353 fn only_unsaved_clips_ask_before_the_window_closes() {
3354 assert!(!Player::close_asks(0, false));
3355 assert!(
3356 !Player::close_asks(0, true),
3357 "an empty timeline has nothing to lose"
3358 );
3359 assert!(
3360 !Player::close_asks(3, false),
3361 "saved work closes without a question"
3362 );
3363 assert!(Player::close_asks(1, true));
3364 }
3365
3366 /// The recovery question reads the sidecar's own mtime, not the clock of the
3367 /// open: a sidecar written three minutes ago says so.
3368 #[test]
3369 fn the_recovery_question_reads_the_sidecars_real_age() {
3370 let dir = std::env::temp_dir().join(format!("edith-recovery-age-{}", std::process::id()));
3371 std::fs::create_dir_all(&dir).unwrap();
3372 let sidecar = dir.join("p.autosave.edith");
3373 std::fs::write(&sidecar, b"autosave").unwrap();
3374 let written = std::time::SystemTime::now() - Duration::from_secs(3 * 60 + 5);
3375 std::fs::File::options()
3376 .write(true)
3377 .open(&sidecar)
3378 .unwrap()
3379 .set_modified(written)
3380 .unwrap();
3381 // The clock time is the local time the file was written, so the test
3382 // reads it back the same way rather than naming a zone's hour.
3383 let clock = chrono::DateTime::<chrono::Local>::from(written).format("%H:%M").to_string();
3384 assert_eq!(
3385 recovery_words(&sidecar),
3386 format!("Unsaved edits from {clock} (3 minutes ago) were found.")
3387 );
3388 std::fs::remove_dir_all(&dir).unwrap();
3389 }
3390
3391 /// The recovery question names the local clock time the autosave was written
3392 /// and how long ago it was: "from 14:32 (1 minute ago)".
3393 #[test]
3394 fn the_recovery_question_names_the_clock_time_and_the_age() {
3395 let now = std::time::SystemTime::UNIX_EPOCH + Duration::from_secs(1_000_000);
3396 let words = recovery_words_at(now - Duration::from_secs(70), now);
3397 let clock = chrono::DateTime::<chrono::Local>::from(now - Duration::from_secs(70)).format("%H:%M").to_string();
3398 assert_eq!(clock.len(), 5, "HH:MM");
3399 assert_eq!(
3400 words,
3401 format!("Unsaved edits from {clock} (1 minute ago) were found.")
3402 );
3403 let just = recovery_words_at(now, now);
3404 assert!(just.contains("(a moment ago) were found"), "{just}");
3405 }
3406
3407 /// The recovery question's age, in plain words at each step.
3408 #[test]
3409 fn the_recovery_age_reads_in_plain_words() {
3410 assert_eq!(age_words(0), "a moment ago");
3411 assert_eq!(age_words(59), "a moment ago");
3412 assert_eq!(age_words(60), "1 minute ago");
3413 assert_eq!(age_words(7 * 60), "7 minutes ago");
3414 assert_eq!(age_words(3600), "1 hour ago");
3415 assert_eq!(age_words(5 * 3600), "5 hours ago");
3416 assert_eq!(age_words(86_400), "yesterday");
3417 assert_eq!(age_words(2 * 86_400 - 1), "yesterday");
3418 assert_eq!(age_words(3 * 86_400), "3 days ago");
3419 }
3420
3421 /// The overwrite question Save's door asks: a target that exists on
3422 /// disk but was never this window's (an import-derived `project_path`,
3423 /// `autosave_armed` still false) warns before the first clobber; a
3424 /// fresh path writes silently, and a file the window itself already
3425 /// saved keeps every later ^s silent. The close rule's sibling.
3426 #[test]
3427 fn only_a_foreign_existing_file_asks_before_a_save_overwrites_it() {
3428 assert!(Player::save_asks(true, false));
3429 assert!(
3430 !Player::save_asks(false, false),
3431 "nothing on disk yet -- a first save needs no warning"
3432 );
3433 assert!(
3434 !Player::save_asks(true, true),
3435 "the window's own file -- later saves stay silent"
3436 );
3437 }
3438
3439 /// The three answers [`Player::recovery_offer`] gives, off nothing but a
3440 /// project file and a sidecar's mtimes: younger sidecar offers it, an
3441 /// older one or none at all offers nothing. Nowhere near a `Player` or a
3442 /// `PlaybackSession` -- the helper reads only the filesystem, which is
3443 /// what makes it askable from a test at all ([`Player`] needs a
3444 /// `gpui::TestAppContext` this repo has no way to build).
3445 #[test]
3446 fn recovery_offer_reads_only_the_newer_sidecar() {
3447 let dir = std::env::temp_dir().join(format!(
3448 "edith-autosave-test-{}-{:?}",
3449 std::process::id(),
3450 std::thread::current().id()
3451 ));
3452 std::fs::create_dir_all(&dir).unwrap();
3453 let project = dir.join("p.edith");
3454 let sidecar = dir.join("p.autosave.edith");
3455
3456 // Neither file exists yet.
3457 assert_eq!(Player::recovery_offer(&project, true), None);
3458
3459 std::fs::write(&project, b"project").unwrap();
3460 // A project with no sidecar beside it: nothing to offer.
3461 assert_eq!(Player::recovery_offer(&project, true), None);
3462
3463 std::fs::write(&sidecar, b"sidecar").unwrap();
3464 let now = std::time::SystemTime::now();
3465 // Sidecar written after the project (the ordinary case: an edit
3466 // landed since the last manual save) -- offered.
3467 std::fs::File::open(&project)
3468 .unwrap()
3469 .set_modified(now - Duration::from_secs(60))
3470 .unwrap();
3471 std::fs::File::open(&sidecar)
3472 .unwrap()
3473 .set_modified(now)
3474 .unwrap();
3475 assert_eq!(Player::recovery_offer(&project, true), Some(sidecar.clone()));
3476
3477 // The sidecar left over from *before* the last manual save (the save
3478 // that answered it, per `Player::save_project`, deletes it -- but an
3479 // older one left by some other means must not be offered as newer
3480 // than a file it predates).
3481 std::fs::File::open(&project)
3482 .unwrap()
3483 .set_modified(now)
3484 .unwrap();
3485 std::fs::File::open(&sidecar)
3486 .unwrap()
3487 .set_modified(now - Duration::from_secs(60))
3488 .unwrap();
3489 assert_eq!(Player::recovery_offer(&project, true), None);
3490
3491 std::fs::remove_dir_all(&dir).unwrap();
3492 }
3493
3494 /// An untitled session's autosave never lands beside the guessed `.edith`
3495 /// (which may be somebody's real project): it goes to the state directory,
3496 /// one file per guessed path. A saved window's goes beside it, by the name
3497 /// `edith_mcp` reads.
3498 #[test]
3499 fn untitled_autosave_goes_to_the_state_dir_never_beside_the_guess() {
3500 let guessed = Path::new("/media/clips/take1.edith");
3501 let untitled = Player::autosave_target(guessed, false).expect("a path to autosave for");
3502 let state = Player::autosave_state_dir().expect("a state dir");
3503 assert!(untitled.starts_with(&state), "{untitled:?} is not under {state:?}");
3504 assert_ne!(untitled.parent(), guessed.parent());
3505 // The same guess names the same file every time, and another guess another one.
3506 assert_eq!(Player::autosave_target(guessed, false), Some(untitled.clone()));
3507 assert_ne!(
3508 Player::autosave_target(Path::new("/media/clips/take2.edith"), false),
3509 Some(untitled)
3510 );
3511 assert_eq!(
3512 Player::autosave_target(guessed, true),
3513 Some(PathBuf::from("/media/clips/take1.autosave.edith"))
3514 );
3515 assert_eq!(Player::autosave_target(Path::new(""), true), None);
3516 }
3517
3518 /// Autosave writes on a dirty session and nowhere else: a clean one, or
3519 /// one mid-export, is left alone.
3520 #[test]
3521 fn only_a_dirty_session_outside_an_export_writes() {
3522 assert!(Player::autosave_gate(true, false));
3523 assert!(!Player::autosave_gate(true, true), "an export owns the disk");
3524 assert!(!Player::autosave_gate(false, false), "nothing changed");
3525 }
3526
3527 /// Discard on the recovery notice deletes the sidecar on disk, not just the
3528 /// in-memory offer -- otherwise the same stale sidecar outdates the project
3529 /// again on the very next open.
3530 #[test]
3531 fn declining_recovery_deletes_the_sidecar() {
3532 let dir = std::env::temp_dir().join(format!(
3533 "edith-autosave-decline-test-{}-{:?}",
3534 std::process::id(),
3535 std::thread::current().id()
3536 ));
3537 std::fs::create_dir_all(&dir).unwrap();
3538 let sidecar = dir.join("p.autosave.edith");
3539 std::fs::write(&sidecar, b"stale").unwrap();
3540
3541 Player::discard_sidecar(&sidecar);
3542 assert!(!sidecar.exists());
3543
3544 // A missing sidecar (already recovered, or declined twice) is a
3545 // no-op, not an error.
3546 Player::discard_sidecar(&sidecar);
3547
3548 std::fs::remove_dir_all(&dir).unwrap();
3549 }
3550}