Skip to content

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

A non-Unicode command-line argument is a usage error, not a startup panic (#1108) (#1168)

wstock5e13abd67cb0
diff --git a/apps/photocraft-cli/src/lib.rs b/apps/photocraft-cli/src/lib.rs
index a68658acb..43f71fb76 100644
--- a/apps/photocraft-cli/src/lib.rs
+++ b/apps/photocraft-cli/src/lib.rs
@@ -125,6 +125,23 @@ impl Args {
type R = Result<(), String>;
+/// [`run`] on the raw process arguments. An argument that is not valid Unicode is a usage error
+/// naming its position and a lossy rendering (exit 2), never a panic: `std::env::args()` aborts
+/// the process on one (issue #1108).
+pub fn run_os(args: &[std::ffi::OsString], out: &mut dyn Write, err: &mut dyn Write) -> i32 {
+ let mut strings = Vec::with_capacity(args.len());
+ for (i, a) in args.iter().enumerate() {
+ match a.clone().into_string() {
+ Ok(s) => strings.push(s),
+ Err(raw) => {
+ let _ = writeln!(err, "error: argument {} is not valid Unicode: `{}`\n\n{USAGE}", i + 1, raw.to_string_lossy());
+ return 2;
+ }
+ }
+ }
+ run(&strings, out, err)
+}
+
/// Run the CLI. Returns the process exit code (0 ok, 1 failure, 2 usage).
pub fn run(args: &[String], out: &mut dyn Write, err: &mut dyn Write) -> i32 {
let Some(cmd) = args.first() else {
diff --git a/apps/photocraft-cli/src/main.rs b/apps/photocraft-cli/src/main.rs
index ec851e925..c0bce7826 100644
--- a/apps/photocraft-cli/src/main.rs
+++ b/apps/photocraft-cli/src/main.rs
@@ -1,7 +1,9 @@
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
fn main() {
- let args: Vec<String> = std::env::args().skip(1).collect();
- let code = photocraft_cli::run(&args, &mut std::io::stdout(), &mut std::io::stderr());
+ // `args_os`, not `args`: a non-Unicode argument (a Latin-1 file name on Linux) must be a
+ // usage error, not a panic before anything is printed (issue #1108).
+ let args: Vec<std::ffi::OsString> = std::env::args_os().skip(1).collect();
+ let code = photocraft_cli::run_os(&args, &mut std::io::stdout(), &mut std::io::stderr());
std::process::exit(code);
}
diff --git a/apps/photocraft-cli/tests/cli.rs b/apps/photocraft-cli/tests/cli.rs
index c3f934741..0f2a339c3 100644
--- a/apps/photocraft-cli/tests/cli.rs
+++ b/apps/photocraft-cli/tests/cli.rs
@@ -546,3 +546,19 @@ fn tiff_output_is_flat_unless_tiff_layers_is_given() {
assert_eq!(layer_count(&kept), 2);
std::fs::remove_dir_all(d).unwrap();
}
+
+/// Issue #1108: a non-Unicode argument (a Latin-1 file name on Linux) used to panic in
+/// `std::env::args()` before anything was printed. It is a usage error naming the argument.
+#[cfg(unix)]
+#[test]
+fn a_non_unicode_argument_is_a_usage_error_not_a_panic() {
+ use std::os::unix::ffi::OsStrExt;
+ let name = std::ffi::OsStr::from_bytes(b"caf\xe9.png");
+ for args in [vec![std::ffi::OsStr::new("info"), name], vec![std::ffi::OsStr::new("convert"), name, std::ffi::OsStr::new("out.png")]] {
+ let o = bin().args(&args).output().unwrap();
+ let err = String::from_utf8_lossy(&o.stderr);
+ assert_eq!(o.status.code(), Some(2), "{err}");
+ assert!(err.contains("argument 2 is not valid Unicode") && err.contains("caf\u{fffd}.png"), "{err}");
+ assert!(!err.contains("panicked"), "{err}");
+ }
+}
diff --git a/apps/photocraft/src/main.rs b/apps/photocraft/src/main.rs
index 152531a85..37a3533fb 100644
--- a/apps/photocraft/src/main.rs
+++ b/apps/photocraft/src/main.rs
@@ -147,31 +147,40 @@ fn main() -> eframe::Result {
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 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().skip(1);
+ let mut args = std::env::args_os().skip(1);
while let Some(a) = args.next() {
- match a.as_str() {
- "--control" => match args.next() {
- Some(value) => match parse_control_port(&value, "--control") {
+ match a.to_str() {
+ Some("--control") => match args.next() {
+ Some(value) => match parse_control_port(&value.to_string_lossy(), "--control") {
Ok(port) => control_port = Some(port),
Err(error) => control_arg_errors.push(error),
},
None => control_arg_errors.push("--control: missing port value (expected `--control <port>`)".to_string()),
},
- "--control-token" => control_token = args.next(),
- "--control-token-file" => control_token_file = args.next().map(std::path::PathBuf::from),
- "--automation-read-root" => automation_read_root = args.next().map(std::path::PathBuf::from),
- "--automation-write-root" => automation_write_root = args.next().map(std::path::PathBuf::from),
- "--safe-gpu" => safe_gpu = true,
- "--in-window-menus" => in_window_menus = true,
- "--version" => {
+ Some("--control-token") => match args.next().map(std::ffi::OsString::into_string) {
+ Some(Ok(token)) => control_token = Some(token),
+ Some(Err(raw)) => control_arg_errors.push(format!("--control-token: value is not valid Unicode (`{}`)", raw.to_string_lossy())),
+ None => control_token = None,
+ },
+ Some("--control-token-file") => control_token_file = args.next().map(std::path::PathBuf::from),
+ Some("--automation-read-root") => automation_read_root = args.next().map(std::path::PathBuf::from),
+ Some("--automation-write-root") => automation_write_root = args.next().map(std::path::PathBuf::from),
+ Some("--safe-gpu") => safe_gpu = true,
+ Some("--in-window-menus") => in_window_menus = true,
+ Some("--version") => {
println!("photocraft {}", photocraft_engine::build_info::long_version());
return Ok(());
}
// Old macOS passes a process serial number when launched from Finder.
- _ if a.starts_with("-psn_") => {}
- _ => files.push(a),
+ Some(s) if s.starts_with("-psn_") => {}
+ Some(s) => files.push(s.to_owned()),
+ None => unreadable_paths.push(a.to_string_lossy().into_owned()),
}
}
@@ -406,6 +415,10 @@ fn main() -> eframe::Result {
tablet::spawn_x11(&app.stylus.feed, display);
// Paths on the command line (Linux/Windows file associations, `photocraft a.psd`).
app.open_paths(&files);
+ if !unreadable_paths.is_empty() {
+ let lines = unreadable_paths.iter().map(|p| format!("{p}: the path is not valid Unicode; rename the file and open it again.")).collect();
+ photocraft_ui_egui::notices::post(&mut app, "Could not open", lines, true, None);
+ }
// Portable marker found but its data folder isn't writable (#228): say where settings went.
if let Some(w) = &app_dirs::current().warning {
photocraft_ui_egui::notices::post(&mut app, "Portable mode is off", vec![w.clone()], false, None);