FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust
Merge main into #858: launch arguments as OsString next to --graphics and the graphics fallback start
Brandon Thomas0cbc6e78dc18
diff --cc apps/filmcraft/src/args.rsindex 6f289dce8,946cd6604..c64e3509f--- a/apps/filmcraft/src/args.rs+++ b/apps/filmcraft/src/args.rs@@@ -51,17 -53,21 +56,26 @@@ pub struct Launch/// mistyped flag helps nobody, and starting without the control server that was asked for leaves/// a script waiting for it. That holds for the whole line, so `--version --bogus` is an error/// too, and for a port from the environment exactly as for one from `--control`.-pub fn parse(env_control_port: Option<String>, args: impl IntoIterator<Item = String>) -> Result<Cli, String> {+///+/// The arguments come from `std::env::args_os`: not every argument is Unicode (a Linux file name+/// in Latin-1), and `std::env::args` panics on one. A file name that is not is passed on lossily+/// (its import then reports it missing); `--data-dir` keeps the folder exactly.+pub fn parse(env_control_port: Option<String>, args: impl IntoIterator<Item = OsString>) -> Result<Cli, String> {- let mut l = Launch { control_port: None, control_input_only: false, files: Vec::new(), demo: true, startup_flag: false, recover: None, data_dir: None };+ let mut l = Launch {+ control_port: None,+ control_input_only: false,+ files: Vec::new(),+ demo: true,+ startup_flag: false,+ recover: None,+ data_dir: None,+ graphics: None,+ };let (mut help, mut version) = (false, false);let mut args = args.into_iter();- while let Some(a) = args.next() {- match a.as_str() {+ while let Some(raw) = args.next() {+ let a = raw.to_string_lossy();+ match a.as_ref() {"-h" | "--help" => help = true,"--version" => version = true,"--control" => {@@@ -74,9 -79,13 +88,13 @@@"--empty" => (l.demo, l.startup_flag) = (false, true),"--recover" => l.recover = Some(true),"--no-recover" => l.recover = Some(false),- "--data-dir" => l.data_dir = Some(args.next().map(std::path::PathBuf::from).ok_or("--data-dir needs a folder")?),+ "--data-dir" => l.data_dir = Some(args.next().map(PathBuf::from).ok_or("--data-dir needs a folder")?),+ "--graphics" => {+ let name = args.next().ok_or("--graphics needs a mode: default, dx12 or software")?;- l.graphics = Some(graphics_mode(&name)?);++ l.graphics = Some(graphics_mode(&name.to_string_lossy())?);+ }// everything after `--` is a file, whatever it looks like- "--" => l.files.extend(args.by_ref()),+ "--" => l.files.extend(args.by_ref().map(|f| f.to_string_lossy().into_owned())),// macOS adds a process serial number when it launches an app bundle_ if a.starts_with("-psn_") => {}_ if a.len() > 1 && a.starts_with('-') => return Err(format!("unknown option `{a}`")),@@@ -100,28 -109,17 +118,39 @@@Ok(Cli::Run(l))}+/// Whether a launch file is a FilmCraft project. The extension's case does not matter: Windows file+/// associations and the Linux MIME glob start the app for `CUT.FCPROJ` too (#850).+pub fn is_project(path: &str) -> bool {+ Path::new(path).extension().is_some_and(|e| e.eq_ignore_ascii_case("fcproj"))+}++/// `path` made absolute against the working directory, so a project or media file named relative+/// to a terminal's folder is still found once the app runs from another one (Recent Projects, the+/// media paths saved in the project). Unlike `canonicalize`, `std::path::absolute` keeps symlinks+/// and adds no Windows verbatim `\\?\` prefix. A path it cannot resolve is kept as given.+pub fn absolute(path: &str) -> String {+ std::path::absolute(path).ok().and_then(|p| p.into_os_string().into_string().ok()).unwrap_or_else(|| path.to_string())+}++/// The launch files as the project to open (the first one, see [`is_project`]) and the media files+/// to import (every file that is not a project), all made [`absolute`].+pub fn project_and_media(files: &[String]) -> (Option<String>, Vec<String>) {+ let project = files.iter().find(|f| is_project(f)).map(|f| absolute(f));+ let media = files.iter().filter(|f| !is_project(f)).map(|f| absolute(f)).collect();+ (project, media)+}++ /// A `--graphics` value: one of this platform's modes.+ fn graphics_mode(name: &str) -> Result<crate::graphics::Mode, String> {+ use crate::graphics::{LADDER, Mode};+ let here = || LADDER.iter().map(|m| m.name()).collect::<Vec<_>>().join(", ");+ let mode = Mode::parse(name).ok_or_else(|| format!("--graphics needs one of {}, got `{name}`", here()))?;+ if !LADDER.contains(&mode) {+ return Err(format!("--graphics {name} is not available on this platform (use one of {})", here()));+ }+ Ok(mode)+ }+#[cfg(test)]mod tests {use super::*;diff --cc apps/filmcraft/src/main.rsindex 234d4e85f,7456aebf4..d824eb8e0--- a/apps/filmcraft/src/main.rs+++ b/apps/filmcraft/src/main.rs@@@ -80,7 -81,7 +81,7 @@@ fn main() -> eframe::Resultlet logger = logging::install();// lossy, so a value that is not Unicode is reported like any other bad port instead of ignoredlet env_port = std::env::var_os("FILMCRAFT_CONTROL_PORT").map(|p| p.to_string_lossy().into_owned());- let Launch { control_port, control_input_only, files, demo, startup_flag, recover, data_dir } = match args::parse(env_port, std::env::args_os().skip(1)) {- let launch = match args::parse(env_port, std::env::args().skip(1)) {++ let launch = match args::parse(env_port, std::env::args_os().skip(1)) {Ok(Cli::Run(l)) => l,Ok(Cli::Help) => {tell(args::USAGE, false);@@@ -133,158 -179,161 +179,160 @@@ fn native_options(agent: bool) -> efram.with_icon(app_icon())// Wayland matches the window to `packaging/linux/ai.storyteller.filmcraft.desktop`..with_app_id(APP_ID),- event_loop_builder: agent_event_loop(control_port.is_some()),+ event_loop_builder: agent_event_loop(agent),..Default::default()- };- // Before eframe creates the wgpu instance: leave OpenGL out on Windows (see graphics.rs).- #[cfg(target_os = "windows")]- let options = {- let mut options = options;- graphics::configure(&mut options, eframe::wgpu::Backends::from_env());- options- };- let started = eframe::run_native(- "FilmCraft",- options,- Box::new(move |cc| {- let mut session = Session::default();- if let Some(dir) = data_dir.clone().or_else(default_data_dir) {- let mut cfg = AutosaveConfig::new(dir);- cfg.local_offset = local_offset;- if let Err(e) = session.start_autosave(cfg) {- log::warn!("auto-save and crash recovery unavailable: {e}");+ }+ }++ /// Creates the app once eframe has its window and graphics device; sets `created` when it runs,+ /// and confirms the graphics mode once two frames have painted.+ fn app_creator(launch: Launch, graphics: graphics::GraphicsStart, created: Arc<AtomicBool>) -> eframe::AppCreator<'static> {+ let Launch { control_port, control_input_only, files, demo, startup_flag, recover, data_dir, graphics: _ } = launch;+ Box::new(move |cc| {+ created.store(true, Ordering::Relaxed);+ // A fallback graphics mode says so in the window, with a button back to the default.+ let notice = graphics.degraded().then(|| {+ let start = graphics.clone();+ filmcraft_ui_egui::graphics_notice::GraphicsNotice::new(graphics.mode().label(), Box::new(move || start.reset_to_default()))+ });+ let confirmed = AtomicBool::new(false);+ cc.egui_ctx.on_end_pass(+ "graphics-start",+ Arc::new(move |ui| {+ if ui.ctx().cumulative_frame_nr() >= 2 && !confirmed.swap(true, Ordering::Relaxed) {+ graphics.confirm();}+ }),+ );+ let mut session = Session::default();+ if let Some(dir) = data_dir.clone().or_else(default_data_dir) {+ let mut cfg = AutosaveConfig::new(dir);+ cfg.local_offset = local_offset;+ if let Err(e) = session.start_autosave(cfg) {+ log::warn!("auto-save and crash recovery unavailable: {e}");}- // voice-over recording reads the microphone through cpal- session.voiceover.input = Some(Box::new(audio_in::CpalIn::new(&session.prefs.audio_hardware.device_class)));- let (project, media) = args::project_and_media(&files);- if let Some(p) = project {- if let Err(e) = session.execute("file.open", json!({"path": p})) {- log::error!("{e}");- }- } else if !startup_flag && session.prefs.general.at_startup == "openMostRecent" {- // Settings ▸ General ▸ At Startup ▸ Open Most Recent- let recent = session.prefs.general.recent_projects.iter().find(|p| std::path::Path::new(p).exists()).cloned();- match recent {- Some(p) => {- if let Err(e) = session.execute("file.open", json!({"path": p})) {- log::error!("{e}");- }- }- None => {- let _ = session.execute("file.openDemoProject", json!({}));+ }+ // voice-over recording reads the microphone through cpal+ session.voiceover.input = Some(Box::new(audio_in::CpalIn::new(&session.prefs.audio_hardware.device_class)));- let project = files.iter().find(|f| f.ends_with(".fcproj")).cloned();++ let (project, media) = args::project_and_media(&files);+ if let Some(p) = project {+ if let Err(e) = session.execute("file.open", json!({"path": p})) {+ log::error!("{e}");+ }+ } else if !startup_flag && session.prefs.general.at_startup == "openMostRecent" {+ // Settings ▸ General ▸ At Startup ▸ Open Most Recent+ let recent = session.prefs.general.recent_projects.iter().find(|p| std::path::Path::new(p).exists()).cloned();+ match recent {+ Some(p) => {+ if let Err(e) = session.execute("file.open", json!({"path": p})) {+ log::error!("{e}");}}- } else if !startup_flag && session.prefs.general.at_startup == "emptyProject" {- } else if demo {- let _ = session.execute("file.openDemoProject", json!({}));- }- if !media.is_empty() {- let _ = session.execute("file.import", json!({"paths": media}));- }- if recover == Some(true) && !session.recovery_candidates().is_empty() {- let id = session.recovery_candidates()[0].id.clone();- match session.execute("file.recover", json!({"id": id})) {- Ok(r) => log::info!("recovered {r}"),- Err(e) => log::error!("recovery failed: {e}"),+ None => {+ let _ = session.execute("file.openDemoProject", json!({}));}}- let mut app = FilmcraftApp::new(session);- if recover == Some(false) {- app.dialog = None;- }- app.integrated_titlebar = cfg!(target_os = "macos");- if let Some(rs) = cc.wgpu_render_state.clone()- && std::env::var_os("FILMCRAFT_CPU_COMPOSITE").is_none()- {- app.set_wgpu(rs);- }- // Keep device selection available even when the default device is unavailable.- // Settings ▸ Audio Hardware is applied on the first frame (`apply_prefs`).- app.audio = Some(Box::new(audio::CpalOut::new()));- app.hooks.pick_files = Some(Box::new(|exts: &[&str]| {- rfd::FileDialog::new()- .add_filter(filmcraft_ui_egui::i18n::t("Media"), &file_filters::extensions(exts))- .pick_files()- .unwrap_or_default()- .into_iter()- .map(|p| p.to_string_lossy().to_string())- .collect()- }));- // Link Media ▸ Locate…, Attach Proxies, Reconnect Full Resolution: one path, not imported.- app.hooks.pick_file_for_relink = Some(Box::new(|exts: &[&str], _hint| {- rfd::FileDialog::new()- .add_filter(filmcraft_ui_egui::i18n::t("Media"), &file_filters::extensions(exts))- .pick_file()- .map(|p| p.to_string_lossy().to_string())- }));- app.hooks.pick_save = Some(Box::new(|name: &str| {- rfd::FileDialog::new()- .add_filter(filmcraft_ui_egui::i18n::t("FilmCraft Project"), &file_filters::extensions(&["fcproj"]))- .set_file_name(name)- .save_file()- .map(|p| p.to_string_lossy().to_string())- }));- app.hooks.pick_save_as = Some(Box::new(|filter: &str, exts: &[&str], name: &str| {- rfd::FileDialog::new()- .add_filter(filmcraft_ui_egui::i18n::t(filter), &file_filters::extensions(exts))- .set_file_name(name)- .save_file()- .map(|p| p.to_string_lossy().to_string())- }));- app.hooks.pick_folder = Some(Box::new(|| rfd::FileDialog::new().pick_folder().map(|p| p.to_string_lossy().to_string())));- app.hooks.pick_folder_at =- Some(Box::new(|dir: &str| rfd::FileDialog::new().set_directory(dir).pick_folder().map(|p| p.to_string_lossy().into_owned())));- app.hooks.open_path = Some(Box::new(open_path));- // Help menu, About and Discord links (#642): eframe is built without its `links`- // feature, so `ctx.open_url` does nothing on the desktop. Detached, so a launcher- // that waits for the browser never freezes the UI.- app.hooks.open_url = Some(Box::new(|url: &str| open::that_detached(url).map_err(|e| e.to_string())));- app.hooks.clipboard_media = Some(Box::new(clipboard_media));- // Settings ▸ General ▸ Interface Language ▸ System Language (#218).- app.hooks.cursor_screen_position = Some(Box::new(filmcraft_platform::cursor::cursor_screen_position));- app.hooks.system_languages = Some(Box::new(|| sys_locale::get_locales().collect()));- // Settings ▸ Appearance ▸ Appearance Mode ▸ Sync with system on Linux desktops whose- // compositor reports no theme to winit (no polling: see appearance.rs).- app.hooks.system_theme = appearance::service();- app.hooks.raise_without_focus = Some(Box::new(|| {- window_raise::raise_without_focus();- }));- app.hooks.pick_open_file = Some(Box::new(|filter: &str, exts: &[&str]| {- rfd::FileDialog::new()- .add_filter(filmcraft_ui_egui::i18n::t(filter), &file_filters::extensions(exts))- .pick_file()- .map(|p| p.to_string_lossy().to_string())- }));- app.hooks.pick_open_project = Some(Box::new(|| {- rfd::FileDialog::new()- .add_filter(filmcraft_ui_egui::i18n::t("FilmCraft Project"), &file_filters::extensions(&["fcproj"]))- .pick_file()- .map(|p| p.to_string_lossy().to_string())- }));- #[cfg(target_os = "macos")]- {- let (rx, update) = native_menu::install(&app, cc.egui_ctx.clone());- app.command_inbox = Some(rx);- app.hooks.shortcuts_changed = Some(update);- app.ui.show_menu_bar = false;- }- if let Some(port) = control_port {- let rx = control_server::start(port, cc.egui_ctx.clone());- app = if control_input_only { app.with_control_input_only(rx) } else { app.with_control(rx) };+ } else if !startup_flag && session.prefs.general.at_startup == "emptyProject" {+ } else if demo {+ let _ = session.execute("file.openDemoProject", json!({}));+ }- let media: Vec<String> = files.iter().filter(|f| !f.ends_with(".fcproj")).cloned().collect();+ if !media.is_empty() {+ let _ = session.execute("file.import", json!({"paths": media}));+ }+ if recover == Some(true) && !session.recovery_candidates().is_empty() {+ let id = session.recovery_candidates()[0].id.clone();+ match session.execute("file.recover", json!({"id": id})) {+ Ok(r) => log::info!("recovered {r}"),+ Err(e) => log::error!("recovery failed: {e}"),}- Ok(Box::new(app))- }),- );- // The window could not be created (no usable GPU / graphics driver, no display): say so- // instead of exiting silently, and keep the reason in the crash log.- if let Err(e) = &started {- let msg = format!("FilmCraft could not start its window: {e}\n\nUpdating the graphics driver usually fixes this.");- log::error!("{msg}");- filmcraft_ui_egui::crash::record(&msg);- let _ = rfd::MessageDialog::new().set_title("FilmCraft").set_description(&msg).set_level(rfd::MessageLevel::Error).show();- }- started+ }+ let mut app = FilmcraftApp::new(session);+ app.graphics_notice = notice;+ if recover == Some(false) {+ app.dialog = None;+ }+ app.integrated_titlebar = cfg!(target_os = "macos");+ if let Some(rs) = cc.wgpu_render_state.clone()+ && std::env::var_os("FILMCRAFT_CPU_COMPOSITE").is_none()+ {+ app.set_wgpu(rs);+ }+ // Keep device selection available even when the default device is unavailable.+ // Settings ▸ Audio Hardware is applied on the first frame (`apply_prefs`).+ app.audio = Some(Box::new(audio::CpalOut::new()));+ app.hooks.pick_files = Some(Box::new(|exts: &[&str]| {+ rfd::FileDialog::new()+ .add_filter(filmcraft_ui_egui::i18n::t("Media"), &file_filters::extensions(exts))+ .pick_files()+ .unwrap_or_default()+ .into_iter()+ .map(|p| p.to_string_lossy().to_string())+ .collect()+ }));+ // Link Media ▸ Locate…, Attach Proxies, Reconnect Full Resolution: one path, not imported.+ app.hooks.pick_file_for_relink = Some(Box::new(|exts: &[&str], _hint| {+ rfd::FileDialog::new()+ .add_filter(filmcraft_ui_egui::i18n::t("Media"), &file_filters::extensions(exts))+ .pick_file()+ .map(|p| p.to_string_lossy().to_string())+ }));+ app.hooks.pick_save = Some(Box::new(|name: &str| {+ rfd::FileDialog::new()+ .add_filter(filmcraft_ui_egui::i18n::t("FilmCraft Project"), &file_filters::extensions(&["fcproj"]))+ .set_file_name(name)+ .save_file()+ .map(|p| p.to_string_lossy().to_string())+ }));+ app.hooks.pick_save_as = Some(Box::new(|filter: &str, exts: &[&str], name: &str| {+ rfd::FileDialog::new()+ .add_filter(filmcraft_ui_egui::i18n::t(filter), &file_filters::extensions(exts))+ .set_file_name(name)+ .save_file()+ .map(|p| p.to_string_lossy().to_string())+ }));+ app.hooks.pick_folder = Some(Box::new(|| rfd::FileDialog::new().pick_folder().map(|p| p.to_string_lossy().to_string())));+ app.hooks.pick_folder_at =+ Some(Box::new(|dir: &str| rfd::FileDialog::new().set_directory(dir).pick_folder().map(|p| p.to_string_lossy().into_owned())));+ app.hooks.open_path = Some(Box::new(open_path));+ // Help menu, About and Discord links (#642): eframe is built without its `links`+ // feature, so `ctx.open_url` does nothing on the desktop. Detached, so a launcher+ // that waits for the browser never freezes the UI.+ app.hooks.open_url = Some(Box::new(|url: &str| open::that_detached(url).map_err(|e| e.to_string())));+ app.hooks.clipboard_media = Some(Box::new(clipboard_media));+ // Settings ▸ General ▸ Interface Language ▸ System Language (#218).+ app.hooks.cursor_screen_position = Some(Box::new(filmcraft_platform::cursor::cursor_screen_position));+ app.hooks.system_languages = Some(Box::new(|| sys_locale::get_locales().collect()));+ // Settings ▸ Appearance ▸ Appearance Mode ▸ Sync with system on Linux desktops whose+ // compositor reports no theme to winit (no polling: see appearance.rs).+ app.hooks.system_theme = appearance::service();+ app.hooks.raise_without_focus = Some(Box::new(|| {+ window_raise::raise_without_focus();+ }));+ app.hooks.pick_open_file = Some(Box::new(|filter: &str, exts: &[&str]| {+ rfd::FileDialog::new()+ .add_filter(filmcraft_ui_egui::i18n::t(filter), &file_filters::extensions(exts))+ .pick_file()+ .map(|p| p.to_string_lossy().to_string())+ }));+ app.hooks.pick_open_project = Some(Box::new(|| {+ rfd::FileDialog::new()+ .add_filter(filmcraft_ui_egui::i18n::t("FilmCraft Project"), &file_filters::extensions(&["fcproj"]))+ .pick_file()+ .map(|p| p.to_string_lossy().to_string())+ }));+ #[cfg(target_os = "macos")]+ {+ let (rx, update) = native_menu::install(&app, cc.egui_ctx.clone());+ app.command_inbox = Some(rx);+ app.hooks.shortcuts_changed = Some(update);+ app.ui.show_menu_bar = false;+ }+ if let Some(port) = control_port {+ let rx = control_server::start(port, cc.egui_ctx.clone());+ app = if control_input_only { app.with_control_input_only(rx) } else { app.with_control(rx) };+ }+ Ok(Box::new(app))+ })}/// Files copied in the file manager, else an image, on the system clipboard (Paste, #611).