edith
Clone
https://git.tahinli.com/Tahinli/edith.git
0 watching·0 forks·Rust·18.3 MiB·ff99ad6·Tahinli·6 days ago·1055 commits
| 1 | //! The File menu's project dialogs: Save version, Versions and Collect media, plus Open recent. |
| 2 | //! The work is the engine's ([`engine::versions`], [`engine::collect`]); this is the state a dialog |
| 3 | //! holds, the keys it takes and the hand-over to the session. Drawn by `ui::project_dialogs`. |
| 4 | |
| 5 | use std::path::{Path, PathBuf}; |
| 6 | use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; |
| 7 | use std::sync::{Arc, Mutex}; |
| 8 | |
| 9 | use engine::collect::{self, Plan, Stop}; |
| 10 | use engine::versions::{self, Version}; |
| 11 | |
| 12 | use crate::player::text_field::{FieldKey, TextField}; |
| 13 | use crate::*; |
| 14 | |
| 15 | /// The longest name a version may have ([`versions::valid_name`]). |
| 16 | const NAME_MAX: usize = 40; |
| 17 | |
| 18 | /// Which dialog is up, with what it shows. |
| 19 | pub(crate) enum Dialog { |
| 20 | NewProject(NewProject), |
| 21 | SaveTemplate(SaveTemplate), |
| 22 | SaveVersion(SaveVersion), |
| 23 | Captions(CaptionsExport), |
| 24 | Versions(VersionList), |
| 25 | Collect(Collect), |
| 26 | PathEntry(PathEntry), |
| 27 | Notes(Notes), |
| 28 | Record(RecordVoiceover), |
| 29 | } |
| 30 | |
| 31 | /// Record voice-over: the input and lane picked, and the take while it runs. |
| 32 | pub(crate) struct RecordVoiceover { |
| 33 | /// The inputs the audio server lists, monitors included. Empty when none answers. |
| 34 | pub(crate) inputs: Vec<engine::pulse::Source>, |
| 35 | /// The input picked, an index into `inputs`; `None` is the server's default input. |
| 36 | pub(crate) input: Option<usize>, |
| 37 | /// The audio lane the take lands on; `None` is a new audio lane. |
| 38 | pub(crate) lane: Option<engine::project::Lane>, |
| 39 | /// Whether the timeline is heard while recording. Off, the output is muted so the mic |
| 40 | /// does not pick up the speakers. |
| 41 | pub(crate) hear: bool, |
| 42 | /// The take in progress, from Record until Stop. |
| 43 | pub(crate) take: Option<super::voice_record::InProgress>, |
| 44 | pub(crate) error: Option<String>, |
| 45 | } |
| 46 | |
| 47 | /// The longest note the project notes take. |
| 48 | pub(crate) const NOTES_MAX: usize = 20_000; |
| 49 | |
| 50 | /// The project notes being edited: the text, with the caret at its end. |
| 51 | pub(crate) struct Notes { |
| 52 | pub(crate) field: TextField, |
| 53 | } |
| 54 | |
| 55 | /// What a typed path is for: the Import button, Open project, Import subtitles, a look file (a |
| 56 | /// new one, or the one a clip's look already holds) or Relink. |
| 57 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 58 | pub(crate) enum PathFor { |
| 59 | Import, |
| 60 | OpenProject, |
| 61 | Subtitles, |
| 62 | Lut { relink: bool }, |
| 63 | Relink, |
| 64 | } |
| 65 | |
| 66 | /// The sheet a file picker's fallback opens: the path typed or pasted, and what it is for. |
| 67 | pub(crate) struct PathEntry { |
| 68 | pub(crate) field: TextField, |
| 69 | pub(crate) what: PathFor, |
| 70 | /// The missing file a Relink is for; `None` for every other path. |
| 71 | pub(crate) from: Option<PathBuf>, |
| 72 | /// A refusal from the last try, shown under the field. |
| 73 | pub(crate) error: Option<String>, |
| 74 | } |
| 75 | |
| 76 | /// The sizes File > New > Project… offers, as direct choices: the label and the canvas. |
| 77 | pub(crate) const NEW_SIZES: [(&str, (u32, u32)); 4] = |
| 78 | [("1080p", (1920, 1080)), ("4K", (3840, 2160)), ("Vertical", (1080, 1920)), ("Square", (1080, 1080))]; |
| 79 | /// ...and the frame rates. |
| 80 | pub(crate) const NEW_RATES: [f64; 4] = [24., 25., 30., 60.]; |
| 81 | |
| 82 | /// The [`NEW_RATES`] entry a new project starts on: the one nearest the footage's |
| 83 | /// own rate when there is footage and it is within a frame per second of one |
| 84 | /// (25 fps footage starts on 25, 23.976 on 24), else 30, the rate most people |
| 85 | /// shoot and deliver at. |
| 86 | pub(crate) fn default_rate_index(footage: Option<f64>) -> usize { |
| 87 | const DEFAULT: usize = 2; |
| 88 | let Some(fps) = footage.filter(|f| f.is_finite() && *f > 0.) else { |
| 89 | return DEFAULT; |
| 90 | }; |
| 91 | NEW_RATES |
| 92 | .iter() |
| 93 | .enumerate() |
| 94 | .map(|(i, &rate)| (i, (rate - fps).abs())) |
| 95 | .filter(|&(_, gap)| gap <= 1.) |
| 96 | .min_by(|a, b| a.1.total_cmp(&b.1)) |
| 97 | .map_or(DEFAULT, |(i, _)| i) |
| 98 | } |
| 99 | /// The longest project name the field takes. |
| 100 | const PROJECT_NAME_MAX: usize = 60; |
| 101 | /// The longest path the path sheet takes. |
| 102 | const PATH_MAX: usize = 4096; |
| 103 | /// The longest time the Go to time field takes. |
| 104 | const TIME_MAX: usize = 24; |
| 105 | |
| 106 | pub(crate) struct NewProject { |
| 107 | pub(crate) field: TextField, |
| 108 | pub(crate) dir: PathBuf, |
| 109 | /// Index into [`NEW_SIZES`] and [`NEW_RATES`]. |
| 110 | pub(crate) size: usize, |
| 111 | pub(crate) rate: usize, |
| 112 | /// The template the project starts from, when it is File > New from template: its size, rate, |
| 113 | /// lanes and caption style come with it, so the size and rate choices are not offered. |
| 114 | pub(crate) template: Option<String>, |
| 115 | /// A refusal from the last try, shown under the fields. |
| 116 | pub(crate) error: Option<String>, |
| 117 | } |
| 118 | |
| 119 | impl NewProject { |
| 120 | /// Where the project file will be written, or `None` while the name is empty. |
| 121 | pub(crate) fn target(&self) -> Option<PathBuf> { |
| 122 | project_file_name(&self.field.text).map(|n| self.dir.join(n)) |
| 123 | } |
| 124 | } |
| 125 | |
| 126 | /// The file name a typed project name makes: trimmed, path separators turned into `-`, and |
| 127 | /// `.edith` added unless the person typed it. `None` for a name with nothing in it. |
| 128 | pub(crate) fn project_file_name(typed: &str) -> Option<String> { |
| 129 | let name: String = typed.trim().chars().map(|c| if matches!(c, '/' | '\\' | '\0') || c.is_control() { '-' } else { c }).collect(); |
| 130 | let name = name.strip_suffix(".edith").unwrap_or(&name).trim().trim_matches('.').to_string(); |
| 131 | (!name.is_empty()).then(|| format!("{name}.edith")) |
| 132 | } |
| 133 | |
| 134 | /// The folder a new project is offered in: the one the newest recent project sits in, else |
| 135 | /// `~/Videos`, else the home folder. |
| 136 | pub(crate) fn default_project_dir() -> PathBuf { |
| 137 | if let Some(dir) = crate::recent::list().iter().find_map(|r| r.path.parent().filter(|d| d.is_dir()).map(Path::to_path_buf)) { |
| 138 | return dir; |
| 139 | } |
| 140 | let home = std::env::var_os("HOME").map(PathBuf::from).unwrap_or_default(); |
| 141 | let videos = home.join("Videos"); |
| 142 | if videos.is_dir() { videos } else { home } |
| 143 | } |
| 144 | |
| 145 | /// Save as template: the name, and whether the clips are kept with the settings. |
| 146 | pub(crate) struct SaveTemplate { |
| 147 | pub(crate) field: TextField, |
| 148 | pub(crate) keep_clips: bool, |
| 149 | /// A refusal from the last try, shown under the field. |
| 150 | pub(crate) error: Option<String>, |
| 151 | } |
| 152 | |
| 153 | pub(crate) struct SaveVersion { |
| 154 | pub(crate) field: TextField, |
| 155 | pub(crate) dir: PathBuf, |
| 156 | /// A refusal from the last try, shown under the field. |
| 157 | pub(crate) error: Option<String>, |
| 158 | } |
| 159 | |
| 160 | /// The caption file a File > Export captions writes. |
| 161 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 162 | pub(crate) enum CaptionFormat { |
| 163 | Srt, |
| 164 | Vtt, |
| 165 | } |
| 166 | |
| 167 | impl CaptionFormat { |
| 168 | pub(crate) const ALL: [CaptionFormat; 2] = [CaptionFormat::Srt, CaptionFormat::Vtt]; |
| 169 | |
| 170 | pub(crate) fn ext(self) -> &'static str { |
| 171 | match self { |
| 172 | CaptionFormat::Srt => "srt", |
| 173 | CaptionFormat::Vtt => "vtt", |
| 174 | } |
| 175 | } |
| 176 | } |
| 177 | |
| 178 | /// The sheet File > Export captions opens: the name of the file (its folder is the default |
| 179 | /// export folder), and whether it is SRT or WebVTT. |
| 180 | pub(crate) struct CaptionsExport { |
| 181 | pub(crate) field: TextField, |
| 182 | pub(crate) format: CaptionFormat, |
| 183 | pub(crate) dir: PathBuf, |
| 184 | /// A refusal from the last try, shown under the field. |
| 185 | pub(crate) error: Option<String>, |
| 186 | } |
| 187 | |
| 188 | pub(crate) struct VersionList { |
| 189 | pub(crate) rows: Vec<Version>, |
| 190 | pub(crate) picked: usize, |
| 191 | pub(crate) dir: PathBuf, |
| 192 | /// A restore is being read in. |
| 193 | pub(crate) busy: bool, |
| 194 | } |
| 195 | |
| 196 | pub(crate) enum Collect { |
| 197 | /// What will be copied, asked before anything is. |
| 198 | Ask(Plan), |
| 199 | /// Copying on a worker thread. |
| 200 | Run(Run), |
| 201 | /// What happened, one line each. |
| 202 | Done(Vec<String>), |
| 203 | Failed(String), |
| 204 | } |
| 205 | |
| 206 | pub(crate) struct Run { |
| 207 | pub(crate) plan: Plan, |
| 208 | pub(crate) total: u64, |
| 209 | pub(crate) done: Arc<AtomicU64>, |
| 210 | pub(crate) cancel: Arc<AtomicBool>, |
| 211 | pub(crate) result: Arc<Mutex<Option<Result<collect::Done, Stop>>>>, |
| 212 | } |
| 213 | |
| 214 | impl Run { |
| 215 | pub(crate) fn fraction(&self) -> f32 { |
| 216 | match self.total { |
| 217 | 0 => 0., |
| 218 | t => (self.done.load(Ordering::Relaxed) as f64 / t as f64).min(1.) as f32, |
| 219 | } |
| 220 | } |
| 221 | } |
| 222 | |
| 223 | impl Player { |
| 224 | /// Whether a dialog is up that has not been dealt with by `Esc`. |
| 225 | pub(crate) fn collect_running(&self) -> bool { |
| 226 | matches!(&self.proj_dialog, Some(Dialog::Collect(Collect::Run(_)))) |
| 227 | } |
| 228 | |
| 229 | /// Whether a modal dialog (a question, the project dialogs, About, Settings) is up: it owns |
| 230 | /// the keyboard, and Tab walks its controls. |
| 231 | pub(crate) fn dialog_up(&self) -> bool { |
| 232 | self.quit_ask || self.save_ask || self.export_ask || self.proj_dialog.is_some() || self.about_open || self.settings_open |
| 233 | } |
| 234 | |
| 235 | /// The dialog shell's X: cancels the topmost dialog, the way Esc does. |
| 236 | pub(crate) fn dialog_cancel(&mut self, cx: &mut Context<Self>) { |
| 237 | if self.quit_ask { |
| 238 | self.quit_ask = false; |
| 239 | } else if self.save_ask { |
| 240 | self.save_ask = false; |
| 241 | } else if self.export_ask { |
| 242 | self.answer_overwrite(Overwrite::Cancel, cx); |
| 243 | } else if self.proj_dialog.is_some() { |
| 244 | if self.collect_running() { |
| 245 | self.cancel_collect(cx); |
| 246 | } else { |
| 247 | self.close_project_dialog(cx); |
| 248 | } |
| 249 | } else if self.about_open { |
| 250 | self.about_open = false; |
| 251 | } else if self.settings_open { |
| 252 | self.settings_open = false; |
| 253 | self.keys_filter.clear(); |
| 254 | } else if self.keys_open { |
| 255 | self.keys_open = false; |
| 256 | self.keys_filter.clear(); |
| 257 | } |
| 258 | cx.notify(); |
| 259 | } |
| 260 | |
| 261 | /// Dialog keyboard navigation, ahead of every dialog's own keys: Tab and Shift+Tab move the |
| 262 | /// focus ring through the dialog's controls; Enter and Space on a focused control are left to |
| 263 | /// its own (key-up) click, so they do not also fire the dialog's primary answer. |
| 264 | pub(crate) fn dialog_nav_key(&mut self, key: &str, shift: bool, window: &mut Window, cx: &mut Context<Self>) -> bool { |
| 265 | match key { |
| 266 | "tab" => { |
| 267 | crate::ui::kit::set_kbd_ring(true); |
| 268 | if shift { |
| 269 | window.focus_prev(); |
| 270 | } else { |
| 271 | window.focus_next(); |
| 272 | } |
| 273 | cx.notify(); |
| 274 | true |
| 275 | } |
| 276 | "enter" | "space" => self.dlg_pool.iter().any(|h| h.is_focused(window)), |
| 277 | _ => false, |
| 278 | } |
| 279 | } |
| 280 | |
| 281 | pub(crate) fn close_project_dialog(&mut self, cx: &mut Context<Self>) { |
| 282 | // A take is never dropped by a click away: closing the sheet places it, as Stop does. |
| 283 | if self.record_running() { |
| 284 | self.record_stop(cx); |
| 285 | return; |
| 286 | } |
| 287 | if let Some(Dialog::Collect(Collect::Run(run))) = &self.proj_dialog { |
| 288 | run.cancel.store(true, Ordering::Relaxed); |
| 289 | } |
| 290 | self.proj_dialog = None; |
| 291 | cx.notify(); |
| 292 | } |
| 293 | |
| 294 | /// The keys a project dialog takes; every other key is the dialog's to ignore. |
| 295 | pub(crate) fn project_dialog_key(&mut self, key: &str, ctrl: bool, alt: bool, key_char: Option<&str>, cx: &mut Context<Self>) { |
| 296 | if matches!((ctrl && !alt, key), (true, "v")) && matches!(self.proj_dialog, Some(Dialog::PathEntry(_))) { |
| 297 | return self.path_entry_paste(cx); |
| 298 | } |
| 299 | match &mut self.proj_dialog { |
| 300 | None => {} |
| 301 | Some(Dialog::NewProject(d)) => match d.field.key(key, ctrl, alt, key_char, PROJECT_NAME_MAX) { |
| 302 | FieldKey::Cancel => self.close_project_dialog(cx), |
| 303 | FieldKey::Commit => self.commit_new_project(cx), |
| 304 | FieldKey::Edited => { |
| 305 | d.error = None; |
| 306 | cx.notify(); |
| 307 | } |
| 308 | }, |
| 309 | Some(Dialog::SaveTemplate(d)) => match d.field.key(key, ctrl, alt, key_char, NAME_MAX) { |
| 310 | FieldKey::Cancel => self.close_project_dialog(cx), |
| 311 | FieldKey::Commit => self.commit_save_template(cx), |
| 312 | FieldKey::Edited => { |
| 313 | d.error = None; |
| 314 | cx.notify(); |
| 315 | } |
| 316 | }, |
| 317 | Some(Dialog::SaveVersion(d)) => match d.field.key(key, ctrl, alt, key_char, NAME_MAX) { |
| 318 | FieldKey::Cancel => self.close_project_dialog(cx), |
| 319 | FieldKey::Commit => self.commit_save_version(cx), |
| 320 | FieldKey::Edited => { |
| 321 | d.error = None; |
| 322 | cx.notify(); |
| 323 | } |
| 324 | }, |
| 325 | Some(Dialog::PathEntry(d)) => match d.field.key(key, ctrl, alt, key_char, PATH_MAX) { |
| 326 | FieldKey::Cancel => self.close_project_dialog(cx), |
| 327 | FieldKey::Commit => self.commit_path_entry(cx), |
| 328 | FieldKey::Edited => { |
| 329 | d.error = None; |
| 330 | cx.notify(); |
| 331 | } |
| 332 | }, |
| 333 | // Several lines: Enter starts a new one, Ctrl+Enter saves, Escape drops the edit. |
| 334 | Some(Dialog::Notes(d)) => match (key, ctrl && !alt) { |
| 335 | ("escape", _) => self.close_project_dialog(cx), |
| 336 | ("enter", true) => self.commit_project_notes(cx), |
| 337 | ("enter", false) => { |
| 338 | if d.field.all { |
| 339 | d.field.text.clear(); |
| 340 | d.field.all = false; |
| 341 | } |
| 342 | if d.field.text.chars().count() < NOTES_MAX { |
| 343 | d.field.text.push('\n'); |
| 344 | } |
| 345 | cx.notify(); |
| 346 | } |
| 347 | _ => match d.field.key(key, ctrl, alt, key_char, NOTES_MAX) { |
| 348 | FieldKey::Cancel => self.close_project_dialog(cx), |
| 349 | FieldKey::Commit => self.commit_project_notes(cx), |
| 350 | FieldKey::Edited => cx.notify(), |
| 351 | }, |
| 352 | }, |
| 353 | // Escape closes the sheet; a take still running is placed, as Stop places it. |
| 354 | Some(Dialog::Record(_)) => { |
| 355 | if key == ESCAPE { |
| 356 | self.close_project_dialog(cx); |
| 357 | } |
| 358 | } |
| 359 | Some(Dialog::Captions(d)) => match d.field.key(key, ctrl, alt, key_char, NAME_MAX) { |
| 360 | FieldKey::Cancel => self.close_project_dialog(cx), |
| 361 | FieldKey::Commit => self.commit_export_captions(cx), |
| 362 | FieldKey::Edited => { |
| 363 | d.error = None; |
| 364 | cx.notify(); |
| 365 | } |
| 366 | }, |
| 367 | Some(Dialog::Versions(d)) => match key { |
| 368 | "escape" => self.close_project_dialog(cx), |
| 369 | "enter" => self.restore_picked_version(cx), |
| 370 | "up" if d.picked > 0 && !d.busy => { |
| 371 | d.picked -= 1; |
| 372 | cx.notify(); |
| 373 | } |
| 374 | "down" if d.picked + 1 < d.rows.len() && !d.busy => { |
| 375 | d.picked += 1; |
| 376 | cx.notify(); |
| 377 | } |
| 378 | _ => {} |
| 379 | }, |
| 380 | Some(Dialog::Collect(c)) => match (&*c, key) { |
| 381 | (Collect::Run(_), "escape") => self.cancel_collect(cx), |
| 382 | (Collect::Ask(_), "enter") => self.start_collect(cx), |
| 383 | (Collect::Ask(_), "escape") | (Collect::Done(_) | Collect::Failed(_), "enter" | "escape") => self.close_project_dialog(cx), |
| 384 | _ => {} |
| 385 | }, |
| 386 | } |
| 387 | } |
| 388 | |
| 389 | // ---- New project ------------------------------------------------------------------- |
| 390 | |
| 391 | /// File > New > Project…, the welcome screen's New project: asks for a name, a folder, a |
| 392 | /// size and a rate, all direct choices. |
| 393 | pub(crate) fn open_new_project(&mut self, cx: &mut Context<Self>) { |
| 394 | self.open_new_project_from(None, cx); |
| 395 | } |
| 396 | |
| 397 | /// File > New project, or, with a template, File > New from template and the welcome screen's |
| 398 | /// From template: the same dialog, with the template's own settings in place of the size and rate. |
| 399 | pub(crate) fn open_new_project_from(&mut self, template: Option<String>, cx: &mut Context<Self>) { |
| 400 | if self.exporting().is_some() { |
| 401 | return; |
| 402 | } |
| 403 | let size = 0; |
| 404 | let rate = default_rate_index(match self.session { |
| 405 | Some(_) => Some(self.fps), |
| 406 | None => self.pending_settings.1, |
| 407 | }); |
| 408 | self.close_card(); |
| 409 | self.welcome_templates = false; |
| 410 | self.proj_dialog = Some(Dialog::NewProject(NewProject { |
| 411 | field: TextField::selected("Untitled"), |
| 412 | dir: default_project_dir(), |
| 413 | size, |
| 414 | rate, |
| 415 | template, |
| 416 | error: None, |
| 417 | })); |
| 418 | cx.notify(); |
| 419 | } |
| 420 | |
| 421 | /// File > Save as template…: the open project's settings, and optionally its clips, as a named |
| 422 | /// template in the user's data folder. |
| 423 | pub(crate) fn open_save_template(&mut self, cx: &mut Context<Self>) { |
| 424 | if self.session.is_none() || self.exporting().is_some() { |
| 425 | return; |
| 426 | } |
| 427 | self.close_card(); |
| 428 | self.proj_dialog = Some(Dialog::SaveTemplate(SaveTemplate { |
| 429 | field: TextField::selected("My template"), |
| 430 | keep_clips: false, |
| 431 | error: None, |
| 432 | })); |
| 433 | cx.notify(); |
| 434 | } |
| 435 | |
| 436 | /// The Keep clips switch of the Save as template dialog. |
| 437 | pub(crate) fn set_template_keep_clips(&mut self, on: bool, cx: &mut Context<Self>) { |
| 438 | if let Some(Dialog::SaveTemplate(d)) = &mut self.proj_dialog { |
| 439 | d.keep_clips = on; |
| 440 | cx.notify(); |
| 441 | } |
| 442 | } |
| 443 | |
| 444 | /// Writes the open project as the template the dialog names. The export preset the export sheet |
| 445 | /// shows is kept with it, unless the sheet is on Custom. |
| 446 | pub(crate) fn commit_save_template(&mut self, cx: &mut Context<Self>) { |
| 447 | let Some(Dialog::SaveTemplate(d)) = &mut self.proj_dialog else { |
| 448 | return; |
| 449 | }; |
| 450 | let name = d.field.text.trim().to_string(); |
| 451 | if !engine::templates::valid_name(&name) { |
| 452 | d.error = Some(if engine::templates::BUILTINS.iter().any(|b| b.name.eq_ignore_ascii_case(&name)) { |
| 453 | format!("{name} is a built-in template: pick another name") |
| 454 | } else { |
| 455 | "Type a name of up to 40 characters, without slashes".into() |
| 456 | }); |
| 457 | cx.notify(); |
| 458 | return; |
| 459 | } |
| 460 | let keep = d.keep_clips; |
| 461 | let Some(session) = self.session.as_ref() else { |
| 462 | return; |
| 463 | }; |
| 464 | let export = self.preset_now(); |
| 465 | let Some(dir) = engine::templates::dir() else { |
| 466 | if let Some(Dialog::SaveTemplate(d)) = &mut self.proj_dialog { |
| 467 | d.error = Some("There is no data folder to keep templates in".into()); |
| 468 | } |
| 469 | cx.notify(); |
| 470 | return; |
| 471 | }; |
| 472 | match engine::templates::save(&dir, session, &name, keep, export) { |
| 473 | Ok(replaced) => { |
| 474 | self.proj_dialog = None; |
| 475 | let verb = if replaced { "Replaced" } else { "Saved" }; |
| 476 | self.notify_user(format!("{verb} template {name}").into()); |
| 477 | } |
| 478 | Err(e) => { |
| 479 | if let Some(Dialog::SaveTemplate(d)) = &mut self.proj_dialog { |
| 480 | d.error = Some(format!("Not saved: {e}")); |
| 481 | } |
| 482 | } |
| 483 | } |
| 484 | cx.notify(); |
| 485 | } |
| 486 | |
| 487 | pub(crate) fn new_project_pick(&mut self, size: Option<usize>, rate: Option<usize>, cx: &mut Context<Self>) { |
| 488 | if let Some(Dialog::NewProject(d)) = &mut self.proj_dialog { |
| 489 | d.size = size.unwrap_or(d.size).min(NEW_SIZES.len() - 1); |
| 490 | d.rate = rate.unwrap_or(d.rate).min(NEW_RATES.len() - 1); |
| 491 | cx.notify(); |
| 492 | } |
| 493 | } |
| 494 | |
| 495 | pub(crate) fn choose_new_project_folder(&mut self, cx: &mut Context<Self>) { |
| 496 | let Some(Dialog::NewProject(d)) = &self.proj_dialog else { |
| 497 | return; |
| 498 | }; |
| 499 | let start = d.dir.clone(); |
| 500 | let picked = cx.background_executor().spawn(async move { crate::files::pick_folder("edith — new project folder", &start) }); |
| 501 | cx.spawn(async move |this, cx| { |
| 502 | let picked = picked.await; |
| 503 | this.update(cx, |this, cx| match picked { |
| 504 | Ok(Some(folder)) => { |
| 505 | if let Some(Dialog::NewProject(d)) = &mut this.proj_dialog { |
| 506 | d.dir = folder; |
| 507 | d.error = None; |
| 508 | cx.notify(); |
| 509 | } |
| 510 | } |
| 511 | Ok(None) => {} |
| 512 | Err(text) => { |
| 513 | this.notify_user(text.into()); |
| 514 | cx.notify(); |
| 515 | } |
| 516 | }) |
| 517 | .ok(); |
| 518 | }) |
| 519 | .detach(); |
| 520 | } |
| 521 | |
| 522 | /// Starts the project. Nothing is written yet: a project file names at least one source, so |
| 523 | /// the file appears with the first footage, which is saved to it at once. Until then the |
| 524 | /// size and rate wait as the pending settings the first file is conformed to. |
| 525 | pub(crate) fn commit_new_project(&mut self, cx: &mut Context<Self>) { |
| 526 | let Some(Dialog::NewProject(d)) = &mut self.proj_dialog else { |
| 527 | return; |
| 528 | }; |
| 529 | let Some(target) = d.target() else { |
| 530 | d.error = Some("Type a name for the project".into()); |
| 531 | cx.notify(); |
| 532 | return; |
| 533 | }; |
| 534 | if target.exists() { |
| 535 | d.error = Some(format!("{} is already there: pick another name", file_name(&target))); |
| 536 | cx.notify(); |
| 537 | return; |
| 538 | } |
| 539 | let (size, rate) = (NEW_SIZES[d.size].1, NEW_RATES[d.rate]); |
| 540 | let dir = d.dir.clone(); |
| 541 | let clips = self.session.as_ref().map_or(0, engine::versions::clip_count); |
| 542 | if self.session.is_some() && self.edited_since_save && clips > 0 { |
| 543 | if let Some(Dialog::NewProject(d)) = &mut self.proj_dialog { |
| 544 | d.error = Some(format!("{} has unsaved changes: save it first", file_name(&self.project_path))); |
| 545 | } |
| 546 | cx.notify(); |
| 547 | return; |
| 548 | } |
| 549 | if let Err(e) = std::fs::create_dir_all(&dir) { |
| 550 | if let Some(Dialog::NewProject(d)) = &mut self.proj_dialog { |
| 551 | d.error = Some(format!("Could not use that folder: {e}")); |
| 552 | } |
| 553 | cx.notify(); |
| 554 | return; |
| 555 | } |
| 556 | if let Some(template) = d.template.clone() { |
| 557 | return self.start_from_template(&template, target, cx); |
| 558 | } |
| 559 | self.proj_dialog = None; |
| 560 | if self.session.is_some() { |
| 561 | self.close_session(); |
| 562 | } |
| 563 | self.pending_settings = (Some(size), Some(rate), None); |
| 564 | self.name = file_name(&target).trim_end_matches(".edith").to_string().into(); |
| 565 | self.new_project = Some(target); |
| 566 | cx.notify(); |
| 567 | } |
| 568 | |
| 569 | /// Starts the project File > New from template makes. A template with clips writes its project |
| 570 | /// file to `target` (its sources come with it) and opens it. One without clips is started as a |
| 571 | /// new project: its canvas and rate are pending, and its lanes, names, caption style and export |
| 572 | /// preset are put on when the first footage arrives, as the file appears then. |
| 573 | fn start_from_template(&mut self, template: &str, target: PathBuf, cx: &mut Context<Self>) { |
| 574 | let Some(dir) = engine::templates::dir() else { |
| 575 | if let Some(Dialog::NewProject(d)) = &mut self.proj_dialog { |
| 576 | d.error = Some("There is no data folder to read templates from".into()); |
| 577 | } |
| 578 | cx.notify(); |
| 579 | return; |
| 580 | }; |
| 581 | let info = engine::templates::list(&dir).into_iter().find(|i| i.name == template); |
| 582 | let Some(info) = info else { |
| 583 | self.proj_dialog = None; |
| 584 | self.notify_user(format!("The template {template} is gone").into()); |
| 585 | cx.notify(); |
| 586 | return; |
| 587 | }; |
| 588 | self.proj_dialog = None; |
| 589 | if info.clips { |
| 590 | return match engine::templates::write_project(&dir, template, &target) { |
| 591 | Ok(export) => { |
| 592 | self.apply_template_export(export.as_deref()); |
| 593 | self.open_recent(&target, cx); |
| 594 | } |
| 595 | Err(e) => { |
| 596 | self.notify_user(format!("Could not start from {template}: {e}").into()); |
| 597 | cx.notify(); |
| 598 | } |
| 599 | }; |
| 600 | } |
| 601 | let Ok(opened) = engine::templates::open(&dir, template) else { |
| 602 | self.notify_user(format!("Could not start from {template}").into()); |
| 603 | cx.notify(); |
| 604 | return; |
| 605 | }; |
| 606 | let session = opened.session; |
| 607 | let size = session.resolution(); |
| 608 | let fps = session.meta().frame_rate; |
| 609 | if self.session.is_some() { |
| 610 | self.close_session(); |
| 611 | } |
| 612 | self.pending_settings = (Some(size), Some(fps), None); |
| 613 | self.pending_template = Some(template.to_string()); |
| 614 | self.name = file_name(&target).trim_end_matches(".edith").to_string().into(); |
| 615 | self.new_project = Some(target); |
| 616 | cx.notify(); |
| 617 | } |
| 618 | |
| 619 | /// Sets the export sheet to the preset a template names (`None`, or the match-project tile, when |
| 620 | /// the template names no preset of edith's own). |
| 621 | pub(crate) fn apply_template_export(&mut self, export: Option<&str>) { |
| 622 | if let Some(id) = export { |
| 623 | self.choose_preset(id); |
| 624 | } |
| 625 | } |
| 626 | |
| 627 | // ---- Save version ------------------------------------------------------------------ |
| 628 | |
| 629 | /// The folder this project's versions live in: beside the project file. |
| 630 | fn versions_dir(&self) -> PathBuf { |
| 631 | versions::dir_beside(&self.project_path) |
| 632 | } |
| 633 | |
| 634 | /// File > Project notes: the notes the project holds, open for editing with the caret at the end. |
| 635 | pub(crate) fn open_project_notes(&mut self, cx: &mut Context<Self>) { |
| 636 | let Some(session) = &self.session else { |
| 637 | return; |
| 638 | }; |
| 639 | let text = session.notes().to_string(); |
| 640 | self.close_card(); |
| 641 | self.proj_dialog = Some(Dialog::Notes(Notes { field: TextField { text, all: false } })); |
| 642 | cx.notify(); |
| 643 | } |
| 644 | |
| 645 | /// Save on the notes dialog: one undo step in the project when the text changed, and the |
| 646 | /// project reads unsaved until it is written. |
| 647 | pub(crate) fn commit_project_notes(&mut self, cx: &mut Context<Self>) { |
| 648 | let Some(Dialog::Notes(d)) = &self.proj_dialog else { |
| 649 | return; |
| 650 | }; |
| 651 | let text = d.field.text.clone(); |
| 652 | if let Some(session) = &mut self.session |
| 653 | && session.set_notes(&text) |
| 654 | { |
| 655 | self.mark_dirty(); |
| 656 | self.notify_user("Project notes saved".into()); |
| 657 | } |
| 658 | self.proj_dialog = None; |
| 659 | cx.notify(); |
| 660 | } |
| 661 | |
| 662 | pub(crate) fn open_save_version(&mut self, cx: &mut Context<Self>) { |
| 663 | if self.session.is_none() { |
| 664 | return; |
| 665 | } |
| 666 | let dir = self.versions_dir(); |
| 667 | // A name that is free, ready to be typed over. |
| 668 | let taken: Vec<String> = versions::list(&dir).into_iter().map(|v| v.name).collect(); |
| 669 | let name = (1..).map(|n| format!("version-{n}")).find(|n| !taken.contains(n)).unwrap_or_default(); |
| 670 | self.close_card(); |
| 671 | self.proj_dialog = Some(Dialog::SaveVersion(SaveVersion { field: TextField::selected(name), dir, error: None })); |
| 672 | cx.notify(); |
| 673 | } |
| 674 | |
| 675 | pub(crate) fn commit_save_version(&mut self, cx: &mut Context<Self>) { |
| 676 | let Some(Dialog::SaveVersion(d)) = &mut self.proj_dialog else { |
| 677 | return; |
| 678 | }; |
| 679 | let Some(name) = versions::clean_name(&d.field.text) else { |
| 680 | d.error = Some("Type a name for this version".into()); |
| 681 | cx.notify(); |
| 682 | return; |
| 683 | }; |
| 684 | let Some(session) = self.session.as_ref() else { |
| 685 | return; |
| 686 | }; |
| 687 | let text = match versions::save(session, &d.dir, &name) { |
| 688 | Ok(saved) => { |
| 689 | let replaced = if saved.replaced.is_some() { "Replaced" } else { "Saved" }; |
| 690 | format!("{replaced} version {name} · {} clip{}", saved.clips, if saved.clips == 1 { "" } else { "s" }) |
| 691 | } |
| 692 | Err(e) => { |
| 693 | d.error = Some(format!("Not saved: {e}")); |
| 694 | cx.notify(); |
| 695 | return; |
| 696 | } |
| 697 | }; |
| 698 | eprintln!("{text}"); |
| 699 | self.proj_dialog = None; |
| 700 | self.notify_user(text.into()); |
| 701 | cx.notify(); |
| 702 | } |
| 703 | |
| 704 | // ---- Export captions --------------------------------------------------------------- |
| 705 | |
| 706 | /// File > Export captions: the sheet opens on the default export name and folder, as an |
| 707 | /// export does, with SRT chosen. No picker opens. |
| 708 | pub(crate) fn open_export_captions(&mut self, cx: &mut Context<Self>) { |
| 709 | let Some(session) = self.session.as_ref() else { |
| 710 | return; |
| 711 | }; |
| 712 | let sources: Vec<&Path> = session.sources().iter().map(|s| s.path.as_path()).collect(); |
| 713 | let first_clip = sources.first().map(|path| crate::files::stem(path)); |
| 714 | let saved = self.autosave_armed || self.new_project_fresh; |
| 715 | let path = crate::player::library::default_export_path(&self.project_path, saved, first_clip.as_deref(), &sources, engine::export::Format::Mp4); |
| 716 | let stem = path.file_stem().map_or_else(String::new, |s| s.to_string_lossy().into_owned()); |
| 717 | let dir = path.parent().map(Path::to_path_buf).unwrap_or_default(); |
| 718 | self.close_card(); |
| 719 | self.proj_dialog = Some(Dialog::Captions(CaptionsExport { field: TextField::selected(stem), format: CaptionFormat::Srt, dir, error: None })); |
| 720 | cx.notify(); |
| 721 | } |
| 722 | |
| 723 | /// The format row: SRT or WebVTT, a direct choice. |
| 724 | pub(crate) fn captions_pick(&mut self, at: usize, cx: &mut Context<Self>) { |
| 725 | if let Some(Dialog::Captions(d)) = &mut self.proj_dialog { |
| 726 | d.format = CaptionFormat::ALL[at.min(CaptionFormat::ALL.len() - 1)]; |
| 727 | d.error = None; |
| 728 | cx.notify(); |
| 729 | } |
| 730 | } |
| 731 | |
| 732 | /// Writes the timeline's captions as the sheet names them. A name with a separator in it, |
| 733 | /// and a timeline with no captions, stay on the sheet with the reason under the field. |
| 734 | pub(crate) fn commit_export_captions(&mut self, cx: &mut Context<Self>) { |
| 735 | let Some(Dialog::Captions(d)) = &mut self.proj_dialog else { |
| 736 | return; |
| 737 | }; |
| 738 | let name = d.field.text.trim().to_string(); |
| 739 | if name.is_empty() || name.contains(['/', '\\']) { |
| 740 | d.error = Some("Type a name for the file, without a slash".into()); |
| 741 | cx.notify(); |
| 742 | return; |
| 743 | } |
| 744 | let Some(session) = self.session.as_ref() else { |
| 745 | return; |
| 746 | }; |
| 747 | let cues = session.caption_cues(); |
| 748 | if cues.is_empty() { |
| 749 | d.error = Some("No captions on the timeline yet".into()); |
| 750 | cx.notify(); |
| 751 | return; |
| 752 | } |
| 753 | let path = d.dir.join(format!("{name}.{}", d.format.ext())); |
| 754 | let text = match d.format { |
| 755 | CaptionFormat::Srt => engine::subtitle::write_srt(&cues), |
| 756 | CaptionFormat::Vtt => engine::subtitle::write_vtt(&cues), |
| 757 | }; |
| 758 | if let Err(e) = std::fs::write(&path, text) { |
| 759 | d.error = Some(format!("Not saved: {e}")); |
| 760 | cx.notify(); |
| 761 | return; |
| 762 | } |
| 763 | self.proj_dialog = None; |
| 764 | self.notify_user(format!("Captions saved to {}", path.display()).into()); |
| 765 | cx.notify(); |
| 766 | } |
| 767 | |
| 768 | // ---- Path entry -------------------------------------------------------------------- |
| 769 | |
| 770 | /// The sheet that stands in for a file picker when no chooser can open here: the person |
| 771 | /// types or pastes the path and the same door takes it. |
| 772 | pub(crate) fn open_path_entry(&mut self, what: PathFor, cx: &mut Context<Self>) { |
| 773 | self.open_path_entry_from(what, None, cx); |
| 774 | } |
| 775 | |
| 776 | /// The same sheet for a Relink, which keeps the missing file it is for. |
| 777 | pub(crate) fn open_path_entry_from(&mut self, what: PathFor, from: Option<PathBuf>, cx: &mut Context<Self>) { |
| 778 | if self.exporting().is_some() { |
| 779 | return; |
| 780 | } |
| 781 | self.close_card(); |
| 782 | self.proj_dialog = Some(Dialog::PathEntry(PathEntry { field: TextField::clicked(""), what, from, error: None })); |
| 783 | cx.notify(); |
| 784 | } |
| 785 | |
| 786 | /// The Paste key on the sheet: the clipboard's text goes in at the caret, as typed. |
| 787 | pub(crate) fn path_entry_paste(&mut self, cx: &mut Context<Self>) { |
| 788 | let Some(Dialog::PathEntry(d)) = &mut self.proj_dialog else { |
| 789 | return; |
| 790 | }; |
| 791 | let Some(text) = cx.read_from_clipboard().and_then(|item| item.text()) else { |
| 792 | return; |
| 793 | }; |
| 794 | if d.field.all { |
| 795 | d.field.text.clear(); |
| 796 | d.field.all = false; |
| 797 | } |
| 798 | d.field.text.extend(text.trim().chars().filter(|c| !c.is_control()).take(PATH_MAX.saturating_sub(d.field.text.len()))); |
| 799 | d.error = None; |
| 800 | cx.notify(); |
| 801 | } |
| 802 | |
| 803 | /// Takes the typed path to what it was for. A path that is not a file stays on the sheet |
| 804 | /// with the reason under the field. |
| 805 | pub(crate) fn commit_path_entry(&mut self, cx: &mut Context<Self>) { |
| 806 | let Some(Dialog::PathEntry(d)) = &mut self.proj_dialog else { |
| 807 | return; |
| 808 | }; |
| 809 | let text = d.field.text.trim().trim_matches(['"', '\'']).to_string(); |
| 810 | let path = PathBuf::from(&text); |
| 811 | if text.is_empty() { |
| 812 | d.error = Some("Type the file's path first".into()); |
| 813 | cx.notify(); |
| 814 | return; |
| 815 | } |
| 816 | if !path.is_file() { |
| 817 | d.error = Some(format!("No file at {text}")); |
| 818 | cx.notify(); |
| 819 | return; |
| 820 | } |
| 821 | let (what, from) = (d.what, d.from.clone()); |
| 822 | self.proj_dialog = None; |
| 823 | match what { |
| 824 | PathFor::Import => self.import(&path, cx), |
| 825 | PathFor::OpenProject => self.open_recent(&path, cx), |
| 826 | PathFor::Subtitles => self.add_subtitles(&path, cx), |
| 827 | PathFor::Lut { relink } => self.set_lut(&path, relink, cx), |
| 828 | PathFor::Relink => { |
| 829 | if let Some(from) = from { |
| 830 | self.relink_to(from, path, cx); |
| 831 | } |
| 832 | } |
| 833 | } |
| 834 | cx.notify(); |
| 835 | } |
| 836 | |
| 837 | // ---- Go to time -------------------------------------------------------------------- |
| 838 | |
| 839 | /// The timecode on the transport, clicked: it becomes a field with the time it shows all |
| 840 | /// selected, so the first key replaces it. Keys then go to [`Player::time_edit_key`]. |
| 841 | pub(crate) fn open_time_entry(&mut self, cx: &mut Context<Self>) { |
| 842 | if self.exporting().is_some() || self.session.is_none() { |
| 843 | return; |
| 844 | } |
| 845 | let now = self.session.as_ref().map_or(0., PlaybackSession::now); |
| 846 | let shown = crate::viewport::timecode(self.hero_position(now), self.active_fps()); |
| 847 | self.close_card(); |
| 848 | self.time_edit = Some(TextField::selected(shown)); |
| 849 | cx.notify(); |
| 850 | } |
| 851 | |
| 852 | /// The keys the Go to time field takes: enter jumps, escape cancels, the rest is text. |
| 853 | pub(crate) fn time_edit_key(&mut self, key: &str, ctrl: bool, alt: bool, key_char: Option<&str>, cx: &mut Context<Self>) { |
| 854 | let Some(field) = self.time_edit.as_mut() else { |
| 855 | return; |
| 856 | }; |
| 857 | match field.key(key, ctrl, alt, key_char, TIME_MAX) { |
| 858 | FieldKey::Cancel => self.time_edit = None, |
| 859 | FieldKey::Commit => self.commit_time_entry(cx), |
| 860 | FieldKey::Edited => {} |
| 861 | } |
| 862 | cx.notify(); |
| 863 | } |
| 864 | |
| 865 | /// Enter on the time field: the typed time is read and the playhead goes there. A time that |
| 866 | /// does not read is said in a note, and the field stays open with what was typed. |
| 867 | pub(crate) fn commit_time_entry(&mut self, cx: &mut Context<Self>) { |
| 868 | let Some(field) = &self.time_edit else { |
| 869 | return; |
| 870 | }; |
| 871 | let jump = match crate::ui::timeband_stance::parse_jump(&field.text, self.active_fps()) { |
| 872 | Ok(jump) => jump, |
| 873 | Err(why) => { |
| 874 | self.notify_user(why.into()); |
| 875 | cx.notify(); |
| 876 | return; |
| 877 | } |
| 878 | }; |
| 879 | self.time_edit = None; |
| 880 | match jump { |
| 881 | crate::ui::timeband_stance::Jump::By(frames) => self.step(frames, cx), |
| 882 | crate::ui::timeband_stance::Jump::At(frame) => { |
| 883 | let fps = self.active_fps(); |
| 884 | let last = self |
| 885 | .active_session() |
| 886 | .map_or(0, |s| ((s.timeline_duration() * fps).round() as i64 - 1).max(0)); |
| 887 | self.seek(frame.clamp(0, last) as f64 / fps, cx); |
| 888 | } |
| 889 | } |
| 890 | cx.notify(); |
| 891 | } |
| 892 | |
| 893 | // ---- Versions ---------------------------------------------------------------------- |
| 894 | |
| 895 | pub(crate) fn open_versions(&mut self, cx: &mut Context<Self>) { |
| 896 | if self.session.is_none() { |
| 897 | return; |
| 898 | } |
| 899 | let dir = self.versions_dir(); |
| 900 | let rows = versions::list(&dir); |
| 901 | self.close_card(); |
| 902 | self.proj_dialog = Some(Dialog::Versions(VersionList { rows, picked: 0, dir, busy: false })); |
| 903 | cx.notify(); |
| 904 | } |
| 905 | |
| 906 | pub(crate) fn pick_version(&mut self, at: usize, cx: &mut Context<Self>) { |
| 907 | if let Some(Dialog::Versions(d)) = &mut self.proj_dialog |
| 908 | && !d.busy |
| 909 | && at < d.rows.len() |
| 910 | { |
| 911 | d.picked = at; |
| 912 | cx.notify(); |
| 913 | } |
| 914 | } |
| 915 | |
| 916 | /// Reads the picked version in on a worker (a project names films; opening one is not |
| 917 | /// instant) and takes it over as one undo step ([`PlaybackSession::adopt_as_step`]). |
| 918 | pub(crate) fn restore_picked_version(&mut self, cx: &mut Context<Self>) { |
| 919 | let Some(Dialog::Versions(d)) = &mut self.proj_dialog else { |
| 920 | return; |
| 921 | }; |
| 922 | let Some(row) = d.rows.get(d.picked).filter(|_| !d.busy) else { |
| 923 | return; |
| 924 | }; |
| 925 | let (name, file) = (row.name.clone(), versions::file(&d.dir, &row.name)); |
| 926 | d.busy = true; |
| 927 | cx.notify(); |
| 928 | let opened = cx.background_executor().spawn(async move { PlaybackSession::open_project(&file).map_err(|e| e.to_string()) }); |
| 929 | cx.spawn(async move |this, cx| { |
| 930 | let opened = opened.await; |
| 931 | this.update(cx, |this, cx| this.finish_restore(&name, opened, cx)).ok(); |
| 932 | }) |
| 933 | .detach(); |
| 934 | } |
| 935 | |
| 936 | fn finish_restore(&mut self, name: &str, opened: Result<PlaybackSession, String>, cx: &mut Context<Self>) { |
| 937 | let text = match opened { |
| 938 | Err(e) => { |
| 939 | if let Some(Dialog::Versions(d)) = &mut self.proj_dialog { |
| 940 | d.busy = false; |
| 941 | } |
| 942 | format!("Version {name} not restored: {e}") |
| 943 | } |
| 944 | Ok(other) => { |
| 945 | if self.exporting().is_some() { |
| 946 | format!("Version {name} not restored: an export is running") |
| 947 | } else if self.step_history(|s| s.adopt_as_step(&other)) { |
| 948 | self.selected.clear(); |
| 949 | self.mark_dirty(); |
| 950 | self.proj_dialog = None; |
| 951 | format!("Restored version {name} · {} takes it back", self.keymap.display(ActionId::Undo)) |
| 952 | } else { |
| 953 | format!("Version {name} not restored: it does not fit on this project") |
| 954 | } |
| 955 | } |
| 956 | }; |
| 957 | if let Some(Dialog::Versions(d)) = &mut self.proj_dialog { |
| 958 | d.busy = false; |
| 959 | } |
| 960 | eprintln!("{text}"); |
| 961 | self.notify_user(text.into()); |
| 962 | cx.notify(); |
| 963 | } |
| 964 | |
| 965 | // ---- Collect media ----------------------------------------------------------------- |
| 966 | |
| 967 | pub(crate) fn open_collect(&mut self, cx: &mut Context<Self>) { |
| 968 | let Some(session) = self.session.as_ref() else { |
| 969 | return; |
| 970 | }; |
| 971 | let folder = collect::default_folder(&self.project_path); |
| 972 | let plan = collect::plan(session.sources(), &folder); |
| 973 | self.close_card(); |
| 974 | self.proj_dialog = Some(Dialog::Collect(Collect::Ask(plan))); |
| 975 | cx.notify(); |
| 976 | } |
| 977 | |
| 978 | /// Asks the desktop for the folder, then plans again for it. |
| 979 | pub(crate) fn choose_collect_folder(&mut self, cx: &mut Context<Self>) { |
| 980 | let Some(Dialog::Collect(Collect::Ask(plan))) = &self.proj_dialog else { |
| 981 | return; |
| 982 | }; |
| 983 | let start = plan.folder.parent().map(Path::to_path_buf).unwrap_or_default(); |
| 984 | let picked = cx.background_executor().spawn(async move { crate::files::pick_folder("edith — collect media into", &start) }); |
| 985 | cx.spawn(async move |this, cx| { |
| 986 | let picked = picked.await; |
| 987 | this.update(cx, |this, cx| match picked { |
| 988 | Ok(Some(folder)) => this.replan_collect(folder, cx), |
| 989 | Ok(None) => {} |
| 990 | Err(text) => { |
| 991 | this.notify_user(text.into()); |
| 992 | cx.notify(); |
| 993 | } |
| 994 | }) |
| 995 | .ok(); |
| 996 | }) |
| 997 | .detach(); |
| 998 | } |
| 999 | |
| 1000 | fn replan_collect(&mut self, folder: PathBuf, cx: &mut Context<Self>) { |
| 1001 | if let (Some(session), Some(Dialog::Collect(c @ Collect::Ask(_)))) = (self.session.as_ref(), &mut self.proj_dialog) { |
| 1002 | *c = Collect::Ask(collect::plan(session.sources(), &folder)); |
| 1003 | cx.notify(); |
| 1004 | } |
| 1005 | } |
| 1006 | |
| 1007 | pub(crate) fn start_collect(&mut self, cx: &mut Context<Self>) { |
| 1008 | let Some(Dialog::Collect(c)) = &mut self.proj_dialog else { |
| 1009 | return; |
| 1010 | }; |
| 1011 | let Collect::Ask(plan) = &*c else { |
| 1012 | return; |
| 1013 | }; |
| 1014 | if plan.items.is_empty() { |
| 1015 | return; |
| 1016 | } |
| 1017 | let plan = plan.clone(); |
| 1018 | let (done, cancel, result) = (Arc::new(AtomicU64::new(0)), Arc::new(AtomicBool::new(false)), Arc::new(Mutex::new(None))); |
| 1019 | let run = Run { total: plan.bytes(), plan: plan.clone(), done: done.clone(), cancel: cancel.clone(), result: result.clone() }; |
| 1020 | *c = Collect::Run(run); |
| 1021 | std::thread::spawn(move || { |
| 1022 | let r = collect::copy_all(&plan, &cancel, &mut |d, _| done.store(d, Ordering::Relaxed)); |
| 1023 | *result.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(r); |
| 1024 | }); |
| 1025 | cx.notify(); |
| 1026 | } |
| 1027 | |
| 1028 | pub(crate) fn cancel_collect(&mut self, cx: &mut Context<Self>) { |
| 1029 | if let Some(Dialog::Collect(Collect::Run(run))) = &self.proj_dialog { |
| 1030 | run.cancel.store(true, Ordering::Relaxed); |
| 1031 | cx.notify(); |
| 1032 | } |
| 1033 | } |
| 1034 | |
| 1035 | /// Called every frame: when the worker has finished, relinks and shows the outcome. |
| 1036 | pub(crate) fn poll_collect(&mut self, cx: &mut Context<Self>) { |
| 1037 | let Some(Dialog::Collect(Collect::Run(run))) = &self.proj_dialog else { |
| 1038 | return; |
| 1039 | }; |
| 1040 | let Some(result) = run.result.lock().unwrap_or_else(std::sync::PoisonError::into_inner).take() else { |
| 1041 | return; |
| 1042 | }; |
| 1043 | let plan = run.plan.clone(); |
| 1044 | match result { |
| 1045 | Err(Stop::Cancelled) => { |
| 1046 | self.proj_dialog = None; |
| 1047 | self.notify_user("Collect cancelled — nothing was copied".into()); |
| 1048 | } |
| 1049 | Err(Stop::Failed(why)) => self.proj_dialog = Some(Dialog::Collect(Collect::Failed(why))), |
| 1050 | Ok(done) => { |
| 1051 | let moved = self.session.as_mut().map_or(0, |s| s.relink_all(&done.pairs)); |
| 1052 | if moved > 0 { |
| 1053 | self.mark_dirty(); |
| 1054 | self.reset_after_reseek(); |
| 1055 | } |
| 1056 | self.proj_dialog = Some(Dialog::Collect(Collect::Done(collect_report(&plan, &done, moved, self.keymap.display(ActionId::Undo))))); |
| 1057 | } |
| 1058 | } |
| 1059 | cx.notify(); |
| 1060 | } |
| 1061 | |
| 1062 | // ---- Open recent ------------------------------------------------------------------- |
| 1063 | |
| 1064 | /// Opens a project from the Open recent list. Unsaved edits are not dropped on a click. |
| 1065 | pub(crate) fn open_recent(&mut self, path: &Path, cx: &mut Context<Self>) { |
| 1066 | if self.exporting().is_some() { |
| 1067 | return; |
| 1068 | } |
| 1069 | let clips = self.session.as_ref().map_or(0, engine::versions::clip_count); |
| 1070 | if self.edited_since_save && clips > 0 { |
| 1071 | self.notify_user_actions( |
| 1072 | format!("Save changes to {} before opening {}?", file_name(&self.project_path), file_name(path)).into(), |
| 1073 | vec![ToastAction::SaveThenOpen(path.to_path_buf()), ToastAction::OpenDiscarding(path.to_path_buf())], |
| 1074 | ); |
| 1075 | cx.notify(); |
| 1076 | return; |
| 1077 | } |
| 1078 | self.import(path, cx); |
| 1079 | } |
| 1080 | |
| 1081 | /// File > Open project… and the welcome screen's Open project button: a chooser that shows |
| 1082 | /// only `.edith` files, and the file it picks goes through the same door a recent project |
| 1083 | /// does (so unsaved edits are asked about, not dropped). The chooser runs on a background |
| 1084 | /// thread, as the import one does, so the window keeps painting while it is up. |
| 1085 | pub(crate) fn pick_open_project(&mut self, cx: &mut Context<Self>) { |
| 1086 | if self.exporting().is_some() { |
| 1087 | return; |
| 1088 | } |
| 1089 | let picked = cx.background_executor().spawn(async { pick_project_file() }); |
| 1090 | cx.spawn(async move |this, cx| { |
| 1091 | let picked = picked.await; |
| 1092 | this.update(cx, |this, cx| match picked { |
| 1093 | Ok(Some(path)) => this.open_recent(&path, cx), |
| 1094 | // Cancelled: nothing to say. |
| 1095 | Ok(None) => {} |
| 1096 | // No chooser here: the same question, typed. |
| 1097 | Err(_) => this.open_path_entry(PathFor::OpenProject, cx), |
| 1098 | }) |
| 1099 | .ok(); |
| 1100 | }) |
| 1101 | .detach(); |
| 1102 | } |
| 1103 | } |
| 1104 | |
| 1105 | /// The project chooser: zenity or kdialog, filtered to `.edith` files and titled for what it is |
| 1106 | /// for. `Err` is a machine with no chooser at all. |
| 1107 | fn pick_project_file() -> Result<Option<PathBuf>, &'static str> { |
| 1108 | crate::files::run_picker([ |
| 1109 | ( |
| 1110 | "zenity", |
| 1111 | vec!["--file-selection".into(), "--title=Open project".into(), "--file-filter=edith projects | *.edith".into()], |
| 1112 | ), |
| 1113 | ("kdialog", vec!["--title=Open project".into(), "--getopenfilename".into(), ".".into(), "*.edith".into()]), |
| 1114 | ]) |
| 1115 | .ok_or(crate::files::NO_DIALOG) |
| 1116 | } |
| 1117 | |
| 1118 | /// The lines the Done face shows: what was copied, what was relinked, what was left alone. |
| 1119 | pub(crate) fn collect_report(plan: &Plan, done: &collect::Done, moved: usize, undo: String) -> Vec<String> { |
| 1120 | let mut lines = vec![ |
| 1121 | format!("Copied {} file{} ({}) to", done.files, plural(done.files), collect::size_text(done.bytes)), |
| 1122 | crate::recent::short_path(&plan.folder, 58), |
| 1123 | format!("Relinked {moved} source{} to the copies. Save the project to keep it; {undo} takes it back.", plural(moved)), |
| 1124 | ]; |
| 1125 | let reused = plan.items.iter().filter(|i| i.present).count(); |
| 1126 | if reused > 0 { |
| 1127 | lines.push(format!("{reused} file{} were already there and were reused", plural(reused))); |
| 1128 | } |
| 1129 | if plan.generated > 0 { |
| 1130 | lines.push(format!("{} generated source{} skipped (not files)", plan.generated, plural(plan.generated))); |
| 1131 | } |
| 1132 | if !plan.offline.is_empty() { |
| 1133 | lines.push(format!("{} missing file{} skipped: {}", plan.offline.len(), plural(plan.offline.len()), names(&plan.offline))); |
| 1134 | } |
| 1135 | lines |
| 1136 | } |
| 1137 | |
| 1138 | fn plural(n: usize) -> &'static str { |
| 1139 | if n == 1 { "" } else { "s" } |
| 1140 | } |
| 1141 | |
| 1142 | fn names(paths: &[PathBuf]) -> String { |
| 1143 | let mut shown: Vec<String> = paths.iter().take(3).map(|p| file_name(p)).collect(); |
| 1144 | if paths.len() > 3 { |
| 1145 | shown.push(format!("and {} more", paths.len() - 3)); |
| 1146 | } |
| 1147 | shown.join(", ") |
| 1148 | } |
| 1149 | |
| 1150 | #[cfg(test)] |
| 1151 | mod tests { |
| 1152 | use super::*; |
| 1153 | |
| 1154 | #[test] |
| 1155 | fn the_report_names_what_was_left_alone() { |
| 1156 | let plan = Plan { |
| 1157 | folder: PathBuf::from("/p/x_media"), |
| 1158 | generated: 2, |
| 1159 | offline: vec![PathBuf::from("/a/gone.mp4")], |
| 1160 | ..Plan::default() |
| 1161 | }; |
| 1162 | let mut done = collect::Done::default(); |
| 1163 | done.files = 1; |
| 1164 | done.bytes = 3_400_000; |
| 1165 | let lines = collect_report(&plan, &done, 1, "Ctrl+Z".into()); |
| 1166 | assert_eq!(lines[0], "Copied 1 file (3.4 MB) to", "{lines:?}"); |
| 1167 | assert_eq!(lines[1], "/p/x_media", "{lines:?}"); |
| 1168 | assert!(lines[2].starts_with("Relinked 1 source to"), "{lines:?}"); |
| 1169 | assert!(lines.iter().any(|l| l.contains("2 generated sources skipped"))); |
| 1170 | assert!(lines.iter().any(|l| l.contains("1 missing file skipped: gone.mp4"))); |
| 1171 | } |
| 1172 | } |