Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

Merge PR #6499: Desktop: a control/automation flag without its value is a usage error (#6429)

aiongg71a5bc44be5a
diff --cc apps/photocraft/src/main.rs
index 05355e55b,085adff59..12ef08987
--- a/apps/photocraft/src/main.rs
+++ b/apps/photocraft/src/main.rs
@@@ -164,149 -155,76 +164,136 @@@ fn usage_exit_code(errors: &[String]) -
if errors.is_empty() { None } else { Some(2) }
}
+/// `photocraft --help`. Keep in step with the options `main` accepts and the module docs.
+const USAGE: &str = "\
+Usage: photocraft [options] [--] [files…]
+
+Opens PhotoCraft with the given files.
+
+Options:
+ -h, --help Print this help and exit
+ --version Print the version, commit and build date and exit
+ --safe-gpu Start with the CPU renderer for this launch (after a graphics driver crash)
+ --in-window-menus macOS: keep the menus inside the window instead of the menu bar
+ --new-instance Windows and Linux: start a separate PhotoCraft instead of opening
+ the files in the one already running
+ --present-mode <mode> How frames reach the display: fifo, autovsync or novsync
+ --frame-latency <n> Frames queued for the display: 1 to 3
+ --stroke-trace <stderr|file.csv>
+ Time each brush stroke's frames
+ --control <port> Start the localhost JSON-lines control server on this port
+ --control-token <64-hex> Control server token (default: a new random one, printed)
+ --control-token-file <path> Read the control server token from this file, or create it
+ with a new one
+ --automation-read-root <dir> Directory the control server may read files from
+ --automation-write-root <dir>
+ Directory the control server may write files to
+ -- Treat every later argument as a file, even one starting with `-`
+
+A bad --present-mode, --frame-latency or --stroke-trace value is reported and ignored.
+Environment: PHOTOCRAFT_CONTROL_PORT, PHOTOCRAFT_CONTROL_TOKEN, PHOTOCRAFT_CONTROL_TOKEN_FILE,
+PHOTOCRAFT_AUTOMATION_READ_ROOT, PHOTOCRAFT_AUTOMATION_WRITE_ROOT, PHOTOCRAFT_PRESENT_MODE,
+PHOTOCRAFT_FRAME_LATENCY, PHOTOCRAFT_STROKE_TRACE, PHOTOCRAFT_IN_WINDOW_MENUS, PHOTOCRAFT_NEW_INSTANCE,
+PHOTOCRAFT_CONFIG_DIR.
+";
+
+/// Print to standard output for `--help` / `--version`. Unlike `println!`, never panics when
+/// stdout is closed or a pipe (`photocraft --help | head -1`).
+fn print_stdout(text: &str) {
+ use std::io::Write as _;
+ let mut out = std::io::stdout().lock();
+ let _ = out.write_all(text.as_bytes()).and_then(|()| out.flush());
+}
+
- #[cfg(test)]
- mod control_port_tests {
- use super::{parse_control_port, usage_exit_code};
-
- #[test]
- fn control_port_errors_exit_non_zero() {
- assert_eq!(usage_exit_code(&[]), None);
- let errors = vec![parse_control_port("nope", "--control").unwrap_err()];
- assert_eq!(usage_exit_code(&errors), Some(2));
- }
-
- #[test]
- fn control_port_accepts_valid_numbers() {
- assert_eq!(parse_control_port("50494", "--control"), Ok(50494));
- assert_eq!(parse_control_port(" 8080 ", "--control"), Ok(8080));
- assert_eq!(parse_control_port("0", "PHOTOCRAFT_CONTROL_PORT"), Ok(0));
- }
-
- #[test]
- fn control_port_rejects_unparseable_values_naming_them() {
- // Out of range, a following flag eaten as the value, and an empty value all fail,
- // naming the offending value in the message.
- let err = parse_control_port("78787", "--control").unwrap_err();
- assert!(err.contains("78787"), "{err}");
- assert!(parse_control_port("--safe-gpu", "--control").is_err());
- assert!(parse_control_port("", "--control").is_err());
- }
+ /// Everything the desktop launcher takes from the command line, on top of the environment
+ /// defaults handed in to `parse_launch_args`.
+ #[derive(Debug, Default, PartialEq, Eq)]
+ struct LaunchArgs {
+ control_port: Option<u16>,
+ control_token: Option<String>,
+ control_token_file: Option<std::path::PathBuf>,
+ automation_read_root: Option<std::path::PathBuf>,
+ automation_write_root: Option<std::path::PathBuf>,
+ files: Vec<String>,
+ /// Arguments that are not valid Unicode (issue #1108): a file manager can hand over a Latin-1
+ /// file name on Linux, and `std::env::args()` would panic before any window opened. Paths are
+ /// reported in a notice once the app is up; a control token is a usage error like a bad port.
+ unreadable_paths: Vec<String>,
+ safe_gpu: bool,
+ new_instance: bool,
+ /// Options that apply only to the process they're given to; a launch with any keeps its own.
+ launch_options: Vec<&'static str>,
+ present_mode_arg: Option<String>,
+ frame_latency_arg: Option<String>,
+ stroke_trace_arg: Option<String>,
+ in_window_menus: bool,
++ /// `--help` / `-h`: print [`USAGE`] and exit 0; parsing stops there.
++ help: bool,
++ /// `--version`: print the version and exit 0; parsing stops there.
+ version: bool,
- /// Usage errors in the control/automation flags; a non-empty list fails the launch (issue #701).
++ /// Usage errors (a bad or missing control/automation value, an unknown option); a non-empty
++ /// list fails the launch with exit status 2 (issues #701, #6429, #6431).
+ errors: Vec<String>,
}
- fn main() -> eframe::Result {
- // First, so the panic hook and every start-up warning are recorded (`logging`).
- let logger = logging::install();
- crash_guard::install_hook();
- // The system font scan can take seconds (minutes on some Macs): run it off the UI thread.
- photocraft_ui_egui::type_tool::warm_fonts();
- let mut control_port: Option<u16> = None;
- let mut usage_errors: Vec<String> = Vec::new();
- if let Some(value) = std::env::var("PHOTOCRAFT_CONTROL_PORT").ok().filter(|v| !v.trim().is_empty()) {
- match parse_control_port(&value, "PHOTOCRAFT_CONTROL_PORT") {
- Ok(port) => control_port = Some(port),
- Err(error) => usage_errors.push(error),
- }
- }
- let mut control_token = None;
- let mut control_token_file = None;
- let mut automation_read_root = std::env::var_os("PHOTOCRAFT_AUTOMATION_READ_ROOT").map(std::path::PathBuf::from);
- let mut automation_write_root = std::env::var_os("PHOTOCRAFT_AUTOMATION_WRITE_ROOT").map(std::path::PathBuf::from);
- let mut files = Vec::new();
- // Arguments that are not valid Unicode (issue #1108): a file manager can hand over a Latin-1
- // file name on Linux, and `std::env::args()` would panic before any window opened. Paths are
- // reported in a notice once the app is up; a control token is a usage error like a bad port.
- let mut unreadable_paths: Vec<String> = Vec::new();
- let mut safe_gpu = false;
- let mut new_instance = false;
- // Options that apply only to the process they're given to; a launch with any keeps its own.
- let mut launch_options: Vec<&'static str> = Vec::new();
- let (mut present_mode_arg, mut frame_latency_arg, mut stroke_trace_arg): (Option<String>, Option<String>, Option<String>) = (None, None, None);
- let mut in_window_menus = std::env::var_os("PHOTOCRAFT_IN_WINDOW_MENUS").is_some_and(|v| !v.is_empty() && v != "0");
- let mut args = std::env::args_os().skip(1);
+ /// Parse the desktop launch arguments over the environment defaults in `out`. A control or
+ /// automation flag with no value is a usage error naming the flag (issue #6429), never a silent
+ /// fall back to a generated token or to no root: like `--control` with a bad port, it exits 2.
++/// So is an unknown option (#6431); a file whose name starts with `-` goes after `--`.
+ fn parse_launch_args(args: impl Iterator<Item = std::ffi::OsString>, mut out: LaunchArgs) -> LaunchArgs {
+ let mut args = args;
+ // After `--`, every argument is a file, even one that starts with `-`.
+ let mut only_files = false;
while let Some(a) = args.next() {
+ if only_files {
+ match a.into_string() {
- Ok(s) => files.push(s),
- Err(raw) => unreadable_paths.push(raw.to_string_lossy().into_owned()),
++ Ok(s) => out.files.push(s),
++ Err(raw) => out.unreadable_paths.push(raw.to_string_lossy().into_owned()),
+ }
+ continue;
+ }
match a.to_str() {
+ Some("--") => only_files = true,
+ Some("--help" | "-h") => {
- print_stdout(USAGE);
- return Ok(());
++ out.help = true;
++ break;
+ }
Some("--control") => match args.next() {
Some(value) => match parse_control_port(&value.to_string_lossy(), "--control") {
- Ok(port) => control_port = Some(port),
- Err(error) => usage_errors.push(error),
+ Ok(port) => out.control_port = Some(port),
+ Err(error) => out.errors.push(error),
},
- None => usage_errors.push("--control: missing port value (expected `--control <port>`)".to_string()),
+ None => out.errors.push("--control: missing port value (expected `--control <port>`)".to_string()),
},
Some("--control-token") => match args.next().map(std::ffi::OsString::into_string) {
- Some(Ok(token)) => control_token = Some(token),
- Some(Err(raw)) => usage_errors.push(format!("--control-token: value is not valid Unicode (`{}`)", raw.to_string_lossy())),
- None => control_token = None,
+ Some(Ok(token)) => out.control_token = Some(token),
+ Some(Err(raw)) => out.errors.push(format!("--control-token: value is not valid Unicode (`{}`)", raw.to_string_lossy())),
+ None => out.errors.push("--control-token: missing token value (expected `--control-token <token>`)".to_string()),
+ },
+ Some("--control-token-file") => match args.next() {
+ Some(value) => out.control_token_file = Some(std::path::PathBuf::from(value)),
+ None => out.errors.push("--control-token-file: missing file path value (expected `--control-token-file <path>`)".to_string()),
},
- Some("--control-token-file") => control_token_file = args.next().map(std::path::PathBuf::from),
Some("--automation-read-root") => {
- launch_options.push("--automation-read-root");
- automation_read_root = args.next().map(std::path::PathBuf::from);
+ out.launch_options.push("--automation-read-root");
+ match args.next() {
+ Some(value) => out.automation_read_root = Some(std::path::PathBuf::from(value)),
+ None => out.errors.push("--automation-read-root: missing directory value (expected `--automation-read-root <dir>`)".to_string()),
+ }
}
Some("--automation-write-root") => {
- launch_options.push("--automation-write-root");
- automation_write_root = args.next().map(std::path::PathBuf::from);
+ out.launch_options.push("--automation-write-root");
+ match args.next() {
+ Some(value) => out.automation_write_root = Some(std::path::PathBuf::from(value)),
+ None => out.errors.push("--automation-write-root: missing directory value (expected `--automation-write-root <dir>`)".to_string()),
+ }
}
Some("--safe-gpu") => {
- launch_options.push("--safe-gpu");
- safe_gpu = true;
+ out.launch_options.push("--safe-gpu");
+ out.safe_gpu = true;
}
Some(flag @ ("--present-mode" | "--frame-latency" | "--stroke-trace")) => {
- launch_options.push(match flag {
+ out.launch_options.push(match flag {
"--present-mode" => "--present-mode",
"--frame-latency" => "--frame-latency",
_ => "--stroke-trace",
@@@ -333,25 -251,169 +320,191 @@@
}
// Old macOS passes a process serial number when launched from Finder.
Some(s) if s.starts_with("-psn_") => {}
+ // A typo such as `--safegpu`, or `--help` spelt another way, must not open the window
+ // and then fail to open the flag as a file (#6431).
- Some(s) if s.starts_with('-') => usage_errors.push(format!("unknown option `{s}` (put `--` before a file name that starts with `-`)")),
- Some(s) => files.push(s.to_owned()),
- None => unreadable_paths.push(a.to_string_lossy().into_owned()),
++ Some(s) if s.starts_with('-') => out.errors.push(format!("unknown option `{s}` (put `--` before a file name that starts with `-`)")),
+ Some(s) => out.files.push(s.to_owned()),
+ None => out.unreadable_paths.push(a.to_string_lossy().into_owned()),
+ }
+ }
+ out
+ }
+
+ #[cfg(test)]
+ mod control_port_tests {
- use super::{control_args_exit_code, parse_control_port};
++ use super::{parse_control_port, usage_exit_code};
+
+ #[test]
+ fn control_port_errors_exit_non_zero() {
- assert_eq!(control_args_exit_code(&[]), None);
++ assert_eq!(usage_exit_code(&[]), None);
+ let errors = vec![parse_control_port("nope", "--control").unwrap_err()];
- assert_eq!(control_args_exit_code(&errors), Some(2));
++ assert_eq!(usage_exit_code(&errors), Some(2));
+ }
+
+ #[test]
+ fn control_port_accepts_valid_numbers() {
+ assert_eq!(parse_control_port("50494", "--control"), Ok(50494));
+ assert_eq!(parse_control_port(" 8080 ", "--control"), Ok(8080));
+ assert_eq!(parse_control_port("0", "PHOTOCRAFT_CONTROL_PORT"), Ok(0));
+ }
+
+ #[test]
+ fn control_port_rejects_unparseable_values_naming_them() {
+ // Out of range, a following flag eaten as the value, and an empty value all fail,
+ // naming the offending value in the message.
+ let err = parse_control_port("78787", "--control").unwrap_err();
+ assert!(err.contains("78787"), "{err}");
+ assert!(parse_control_port("--safe-gpu", "--control").is_err());
+ assert!(parse_control_port("", "--control").is_err());
+ }
+ }
+
+ #[cfg(test)]
+ mod launch_args_tests {
- use super::{LaunchArgs, control_args_exit_code, parse_launch_args};
++ use super::{LaunchArgs, parse_launch_args, usage_exit_code};
+ use std::ffi::OsString;
+
+ fn parse(values: &[&str]) -> LaunchArgs {
+ parse_launch_args(values.iter().map(OsString::from), LaunchArgs::default())
+ }
+
+ #[test]
+ fn flags_without_a_value_are_usage_errors() {
+ // Issue #6429: a missing value must fail the launch, not silently fall back to a
+ // generated token or to no root.
+ for flag in ["--control", "--control-token", "--control-token-file", "--automation-read-root", "--automation-write-root"] {
+ let parsed = parse(&[flag]);
+ assert_eq!(parsed.errors.len(), 1, "{flag}: {:?}", parsed.errors);
+ assert!(parsed.errors[0].starts_with(flag), "{}", parsed.errors[0]);
+ assert!(parsed.errors[0].contains("missing"), "{}", parsed.errors[0]);
- assert_eq!(control_args_exit_code(&parsed.errors), Some(2));
++ assert_eq!(usage_exit_code(&parsed.errors), Some(2));
}
}
- // A malformed control port must not silently drop the control server (issue #701), and an
- // unknown option must not open the window (#6431): name the bad argument and fail the launch,
- // like `photocraft-cli` does for the same typos. Exit status 2 is the usual command-line usage
- // error, so a launcher sees the failure.
- if let Some(code) = usage_exit_code(&usage_errors) {
- for error in &usage_errors {
+ #[test]
+ fn missing_value_does_not_clear_an_environment_default() {
+ // `--automation-read-root` with no value must not drop a root set through the env var.
+ let defaults = LaunchArgs { automation_read_root: Some("/env/read".into()), automation_write_root: Some("/env/write".into()), ..Default::default() };
+ let parsed = parse_launch_args(["--automation-read-root"].iter().map(OsString::from), defaults);
+ assert_eq!(parsed.automation_read_root.as_deref(), Some(std::path::Path::new("/env/read")));
+ assert_eq!(parsed.automation_write_root.as_deref(), Some(std::path::Path::new("/env/write")));
+ assert_eq!(parsed.errors.len(), 1, "{:?}", parsed.errors);
+ }
+
+ #[test]
+ fn values_are_parsed_and_no_errors_remain() {
+ let parsed = parse(&[
+ "--control",
+ "50494",
+ "--control-token",
+ "abcd",
+ "--control-token-file",
+ "/tmp/token",
+ "--automation-read-root",
+ "/r",
+ "--automation-write-root",
+ "/w",
+ "--safe-gpu",
+ "--in-window-menus",
+ "--new-instance",
+ "--present-mode",
+ "mailbox",
+ "photo.psd",
+ ]);
+ assert!(parsed.errors.is_empty(), "{:?}", parsed.errors);
+ assert_eq!(parsed.control_port, Some(50494));
+ assert_eq!(parsed.control_token.as_deref(), Some("abcd"));
+ assert_eq!(parsed.control_token_file.as_deref(), Some(std::path::Path::new("/tmp/token")));
+ assert_eq!(parsed.automation_read_root.as_deref(), Some(std::path::Path::new("/r")));
+ assert_eq!(parsed.automation_write_root.as_deref(), Some(std::path::Path::new("/w")));
+ assert!(parsed.safe_gpu);
+ assert!(parsed.in_window_menus);
+ assert!(parsed.new_instance);
+ assert_eq!(parsed.present_mode_arg.as_deref(), Some("mailbox"));
+ assert_eq!(parsed.launch_options, vec!["--automation-read-root", "--automation-write-root", "--safe-gpu", "--in-window-menus", "--present-mode"]);
+ assert_eq!(parsed.files, vec!["photo.psd".to_string()]);
+ }
+
+ #[test]
+ fn version_stops_parsing() {
+ let parsed = parse(&["--version", "--control"]);
+ assert!(parsed.version);
+ assert!(parsed.errors.is_empty(), "{:?}", parsed.errors);
+ }
++
++ #[test]
++ fn help_stops_parsing_and_double_dash_ends_options() {
++ let parsed = parse(&["-h", "--safegpu", "--control"]);
++ assert!(parsed.help);
++ assert!(parsed.errors.is_empty(), "{:?}", parsed.errors);
++
++ let parsed = parse(&["--safegpu", "--", "--help", "-x"]);
++ assert!(!parsed.help);
++ assert_eq!(parsed.errors.len(), 1, "{:?}", parsed.errors);
++ assert!(parsed.errors[0].contains("unknown option `--safegpu`"), "{}", parsed.errors[0]);
++ assert_eq!(parsed.files, vec!["--help".to_string(), "-x".to_string()]);
++ }
+ }
+
+ fn main() -> eframe::Result {
+ // First, so the panic hook and every start-up warning are recorded (`logging`).
+ let logger = logging::install();
+ crash_guard::install_hook();
+ // The system font scan can take seconds (minutes on some Macs): run it off the UI thread.
+ photocraft_ui_egui::type_tool::warm_fonts();
+ let mut launch = LaunchArgs {
+ automation_read_root: std::env::var_os("PHOTOCRAFT_AUTOMATION_READ_ROOT").map(std::path::PathBuf::from),
+ automation_write_root: std::env::var_os("PHOTOCRAFT_AUTOMATION_WRITE_ROOT").map(std::path::PathBuf::from),
+ in_window_menus: std::env::var_os("PHOTOCRAFT_IN_WINDOW_MENUS").is_some_and(|v| !v.is_empty() && v != "0"),
+ ..Default::default()
+ };
+ if let Some(value) = std::env::var("PHOTOCRAFT_CONTROL_PORT").ok().filter(|v| !v.trim().is_empty()) {
+ match parse_control_port(&value, "PHOTOCRAFT_CONTROL_PORT") {
+ Ok(port) => launch.control_port = Some(port),
+ Err(error) => launch.errors.push(error),
+ }
+ }
+ launch = parse_launch_args(std::env::args_os().skip(1), launch);
++ if launch.help {
++ print_stdout(USAGE);
++ return Ok(());
++ }
+ if launch.version {
- println!("photocraft {}", photocraft_engine::build_info::long_version());
++ print_stdout(&format!("photocraft {}\n", photocraft_engine::build_info::long_version()));
+ return Ok(());
+ }
+
- // A malformed control port must not silently drop the control server (issue #701), and a
- // control or automation flag without its value must not silently fall back to a generated
- // token or to no root (issue #6429): name the flag and fail the launch, like
- // `photocraft-cli serve --port` does for the same typo. Exit status 2 is the usual
- // command-line usage error, so a launcher sees the failure.
- if let Some(code) = control_args_exit_code(&launch.errors) {
++ // A malformed control port must not silently drop the control server (issue #701), a control
++ // or automation flag without its value must not silently fall back to a generated token or
++ // to no root (issue #6429), and an unknown option must not open the window (#6431): name the
++ // bad argument and fail the launch, like `photocraft-cli` does for the same typos. Exit
++ // status 2 is the usual command-line usage error, so a launcher sees the failure.
++ if let Some(code) = usage_exit_code(&launch.errors) {
+ for error in &launch.errors {
eprintln!("photocraft: {error}");
}
+ eprintln!("Run `photocraft --help` for usage.");
std::process::exit(code);
}
+ let LaunchArgs {
+ control_port,
+ control_token,
+ control_token_file,
+ automation_read_root,
+ automation_write_root,
+ files,
+ unreadable_paths,
+ safe_gpu,
+ new_instance,
+ launch_options,
+ present_mode_arg,
+ frame_latency_arg,
+ stroke_trace_arg,
+ in_window_menus,
++ help: _,
+ version: _,
+ errors: _,
+ } = launch;
// The log file lives under the settings directory; opened after the arguments, so `--version`
// and usage errors leave no file behind. Records logged until now are written to it first.