Skip to content

LightCraft: An open-source non-destructive photo editor written by scratch in pure Rust

LRC-LIB-CATALOG-SWITCH: merge main (upstream file split)

OneSlips77829547d273
diff --cc apps/lightcraft/src/launch.rs
index 000000000,a7b8904d6..f73ee291f
mode 000000,100644..100644
--- a/apps/lightcraft/src/launch.rs
+++ b/apps/lightcraft/src/launch.rs
@@@ -1,0 -1,138 +1,168 @@@
+ use super::prefs::config_dir;
+
+ pub(crate) const HELP: &str = "\
+ lightcraft — photo library + raw developer
+
-USAGE: lightcraft [OPTIONS] [FILES/FOLDERS…] (files and folders are imported)
++USAGE: lightcraft [OPTIONS] [FILES/FOLDERS…] (files and folders are imported; a library's catalog.snap or
++ folder opens that library)
+
+ OPTIONS:
+ --library DIR open (or create) this library (env LIGHTCRAFT_LIBRARY; default: the last library opened, or
+ a list of the recent ones with Settings > General > At launch: Ask me or Alt/Option held,
+ else ~/Pictures/LightCraft Library)
+ --no-demo don't seed a new library with the procedural demo photos
+ --memory throwaway in-memory session (alias --demo); nothing is saved
+ --control PORT serve the JSON-lines control channel on 127.0.0.1:PORT (env LIGHTCRAFT_CONTROL_PORT;
+ see docs/control-protocol.md)
+ --version, --help
+
+ ENVIRONMENT:
+ LIGHTCRAFT_CONFIG_DIR=DIR use this settings folder instead of the platform default (empty = no settings folder).
+ Without it, a portable.txt file next to the program puts the folder beside it (LightCraftData)
+ LIGHTCRAFT_GPU_BACKEND=dx12|vulkan|metal|auto|off graphics backend (default: DX12 on Windows, Metal on macOS,
+ Vulkan on Linux; off = render on the CPU); else WGPU_BACKEND. LIGHTCRAFT_GPU=0: CPU rendering.
+ LIGHTCRAFT_SAM3_DIR=DIR the SAM 3 model for Object / Describe masks (default: <settings folder>/models/sam3;
+ optional: LightCraft offers to download it when first needed)
+ LIGHTCRAFT_SAM3_MIRRORS=URL,… where to download the SAM 3 model from (base URLs, tried in order)
+ LIGHTCRAFT_LOG=info|debug more log detail from LightCraft itself (default: info from LightCraft, warnings
+ from other crates); else RUST_LOG=<env_logger directives>. Records go to stderr and to
+ <settings folder>/logs/lightcraft.log (previous runs: lightcraft.1.log, lightcraft.2.log)
+ ";
+
+ /// The launch arguments' files and folders to import (absolute), and a notice for each one that
+ /// is not imported (see [`lightcraft_engine::import::launch_path`]; issue #374).
-pub(crate) fn launch_imports(args: &[String]) -> (Vec<String>, Vec<String>) {
++pub(crate) fn launch_imports(args: &[String]) -> LaunchArgs {
+ let cwd = std::env::current_dir().ok();
+ let home = std::env::var_os(if cfg!(windows) { "USERPROFILE" } else { "HOME" }).filter(|h| !h.is_empty()).map(std::path::PathBuf::from);
+ launch_imports_in(args, cwd.as_deref(), home.as_deref())
+ }
+
-pub(crate) fn launch_imports_in(args: &[String], cwd: Option<&std::path::Path>, home: Option<&std::path::Path>) -> (Vec<String>, Vec<String>) {
++/// The library a launch argument names, after `--library` (`flag`) and `LIGHTCRAFT_LIBRARY` (`env`):
++/// the library to pass on as the flag, and whether the argument chose it (it is then remembered).
++pub(crate) fn launch_library_choice(
++ flag: Option<std::path::PathBuf>,
++ env: Option<&std::path::PathBuf>,
++ argument: Option<std::path::PathBuf>,
++) -> (Option<std::path::PathBuf>, bool) {
++ match (flag, env, argument) {
++ (Some(flag), _, _) => (Some(flag), false),
++ (None, None, Some(argument)) => (Some(argument), true),
++ _ => (None, false),
++ }
++}
++
++/// What the launch arguments ask for: files and folders to import, a library to open (a library's `catalog.snap`
++/// or folder, double-clicked in the file manager), and a notice for each argument
++/// left alone.
++#[derive(Debug, Default, PartialEq)]
++pub(crate) struct LaunchArgs {
++ pub(crate) files: Vec<String>,
++ pub(crate) library: Option<std::path::PathBuf>,
++ pub(crate) notices: Vec<String>,
++}
++
++pub(crate) fn launch_imports_in(args: &[String], cwd: Option<&std::path::Path>, home: Option<&std::path::Path>) -> LaunchArgs {
+ use lightcraft_engine::import::{LaunchPath, launch_path};
- let (mut files, mut notices) = (Vec::new(), Vec::new());
++ let (mut files, mut notices, mut library) = (Vec::new(), Vec::new(), None);
+ for a in args {
+ match launch_path(a, cwd, home, lightcraft_engine::devices::dcim_in) {
++ Some(LaunchPath::Library(dir)) if library.is_none() => library = Some(std::path::PathBuf::from(dir)),
++ Some(LaunchPath::Library(dir)) => {
++ log::warn!("one library at a time: not opening {dir} given at launch");
++ notices.push(format!("{dir} was not opened: LightCraft opens one library at a time. Open it with File ▸ Open Library…"));
++ }
+ Some(LaunchPath::Import(p)) => files.push(p),
+ Some(LaunchPath::Refused { path, why }) => {
+ log::warn!("not importing {path} given at launch: {why}");
+ notices
+ .push(format!("{path} was not imported: it is {why}. To import from it, choose a folder inside it with File ▸ Import Photos…"));
+ }
+ None => {}
+ }
+ }
- (files, notices)
++ LaunchArgs { files, library, notices }
+ }
+
+ /// Where the log files live: `logs` in the settings folder, next to `ui.json` (see `logging`).
+ /// None with `LIGHTCRAFT_NO_PREFS` (tests, scripts), so those runs don't rotate away the user's logs.
+ pub(crate) fn log_dir() -> Option<std::path::PathBuf> {
+ if std::env::var_os("LIGHTCRAFT_NO_PREFS").is_some() {
+ return None;
+ }
+ config_dir().map(|d| d.join("logs"))
+ }
+
+ /// The control port `value` names; a value that isn't a port is logged and ignored (`what` is
+ /// the option or variable it came from). Logged before the log file opens, so it is kept for it.
+ pub(crate) fn control_port_from(what: &str, value: Option<String>) -> Option<u16> {
+ let value = value?;
+ let port = value.trim().parse().ok();
+ if port.is_none() {
+ log::warn!("{what} {value:?} is not a port number; no control server");
+ }
+ port
+ }
+
+ /// An isolated profile keeps the emergency crash log with its other app data. With no
+ /// override (or an empty override), retain the historical system-temp location.
+ pub(crate) fn panic_log_path_with(env: impl Fn(&str) -> Option<std::ffi::OsString>, temp: std::path::PathBuf) -> std::path::PathBuf {
+ env("LIGHTCRAFT_CONFIG_DIR").filter(|value| !value.is_empty()).map(std::path::PathBuf::from).unwrap_or(temp).join("lightcraft-panics.log")
+ }
+
+ /// What to tell the user when LightCraft stopped while running (`error`), and why when the GPU
+ /// was lost (`lost`): GPU rendering is off from the next start.
+ pub(crate) fn stopped_text(error: &str, lost: Option<&str>) -> String {
+ match lost {
+ Some(reason) => format!(
+ "{error}. The graphics driver reset the GPU ({reason}). LightCraft renders on the CPU from its next start; \
+ Settings ▸ Performance ▸ Use the GPU for rendering turns the GPU back on"
+ ),
+ None => error.to_string(),
+ }
+ }
+
+ /// LightCraft stopped while its window was up: say so in the log and in a native message box
+ /// naming the log file (as [`startup_failed`] does for a start that failed).
+ pub(crate) fn stopped_while_running(text: &str, log_file: Option<&std::path::Path>) {
+ log::error!("LightCraft stopped: {text}");
+ if std::env::var_os("LIGHTCRAFT_NO_PREFS").is_some() {
+ return; // tests and scripts: no dialog to click away
+ }
+ let (title, text) = lightcraft_ui_egui::i18n::stopped_message(text, log_file.map(|p| p.display().to_string()).as_deref());
+ let _ = rfd::MessageDialog::new()
+ .set_level(rfd::MessageLevel::Error)
+ .set_title(title)
+ .set_description(text)
+ .set_buttons(rfd::MessageButtons::Ok)
+ .show();
+ }
+
+ /// The window could not start (e.g. no usable graphics device): say so in the log and in a native
+ /// message box naming the log file, instead of exiting without a trace — the release builds have
+ /// no console on Windows, and an app started from Finder shows no standard error (issue #260).
+ pub(crate) fn startup_failed(error: &str, log_file: Option<&std::path::Path>) {
+ log::error!("LightCraft could not open its window: {error}");
+ if std::env::var_os("LIGHTCRAFT_NO_PREFS").is_some() {
+ return; // tests and scripts: no dialog to click away
+ }
+ let (title, text) = lightcraft_ui_egui::i18n::startup_failed_message(error, log_file.map(|p| p.display().to_string()).as_deref());
+ let _ = rfd::MessageDialog::new()
+ .set_level(rfd::MessageLevel::Error)
+ .set_title(title)
+ .set_description(text)
+ .set_buttons(rfd::MessageButtons::Ok)
+ .show();
+ }
+
+ #[cfg(test)]
+ mod config_path_tests {
+ use super::*;
+
+ #[test]
+ fn config_override_keeps_panic_log_in_isolated_profile() {
+ let temp = std::path::PathBuf::from("temp");
+ assert_eq!(panic_log_path_with(|_| Some("isolated".into()), temp.clone()), std::path::PathBuf::from("isolated/lightcraft-panics.log"));
+ assert_eq!(panic_log_path_with(|_| None, temp.clone()), temp.join("lightcraft-panics.log"));
+ assert_eq!(panic_log_path_with(|_| Some("".into()), temp.clone()), temp.join("lightcraft-panics.log"));
+ }
+ }
diff --cc apps/lightcraft/src/main.rs
index 232caca51,7b572fa0e..ea1a29700
--- a/apps/lightcraft/src/main.rs
+++ b/apps/lightcraft/src/main.rs
@@@ -44,6 -44,25 +44,28 @@@ use lightcraft_engine::Session
use lightcraft_ui_egui::panels::library_problem::{Launch, LibraryProblem};
use lightcraft_ui_egui::{LightcraftApp, Services, UiState};
+ mod gpu_crash;
+ mod launch;
+ mod platform;
+ mod prefs;
+ mod session;
+
+ use gpu_crash::{gpu_crash_check, gpu_lost_check_at, gpu_lost_marker_path, gpu_lost_reason, record_gpu_lost, window_files};
+ #[cfg(test)]
+ use gpu_crash::{gpu_crash_check_at, gpu_crash_notice, window_wgpu_options};
+ #[cfg(test)]
+ use launch::launch_imports_in;
-use launch::{HELP, control_port_from, launch_imports, log_dir, panic_log_path_with, startup_failed, stopped_text, stopped_while_running};
++use launch::{
++ HELP, LaunchArgs, control_port_from, launch_imports, launch_library_choice, log_dir, panic_log_path_with, startup_failed, stopped_text,
++ stopped_while_running,
++};
+ #[cfg(test)]
+ use platform::{explorer_select_arg, explorer_select_command, windows_open_url_command};
+ use prefs::{PrefsWriter, as_remembered, load_prefs, prefs_path};
+ #[cfg(test)]
+ use prefs::{load_prefs_at, write_atomic};
+ use session::{open_session, services};
+
/// Reverse-DNS app id: Wayland app id, `.desktop` file and hicolor icon name.
const APP_ID: &str = "ai.storyteller.lightcraft";
diff --cc apps/lightcraft/src/tests.rs
index 000000000,0afbc4b2c..4cf0445f7
mode 000000,100644..100644
--- a/apps/lightcraft/src/tests.rs
+++ b/apps/lightcraft/src/tests.rs
@@@ -1,0 -1,464 +1,504 @@@
+ use super::*;
+
+ fn dir(tag: &str) -> std::path::PathBuf {
+ let d = std::env::temp_dir().join(format!("lc-app-prefs-{tag}-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&d);
+ std::fs::create_dir_all(&d).unwrap();
+ d
+ }
+
+ /// Issue #374: launch arguments that would walk a whole drive or home folder are reported,
+ /// not imported; empty ones are ignored; the rest are imported as absolute paths.
+ #[test]
+ fn launch_arguments_never_walk_a_drive_or_the_home_folder() {
+ let home = dir("launch");
+ std::fs::create_dir_all(home.join("Trip")).unwrap();
+ let args: Vec<String> = ["", " ", ".", "Trip", &home.to_string_lossy()].iter().map(|s| s.to_string()).collect();
- let (files, notices) = launch_imports_in(&args, Some(&home), Some(&home));
++ let LaunchArgs { files, notices, library } = launch_imports_in(&args, Some(&home), Some(&home));
++ assert_eq!(library, None);
+ assert_eq!(files, [home.join("Trip").to_string_lossy().to_string()]);
+ assert_eq!(notices.len(), 2, "{notices:?}");
+ assert!(notices.iter().all(|n| n.contains("was not imported")), "{notices:?}");
+ // the working folder is a drive root (a launcher's choice): `.` is never the whole drive
+ let root = home.ancestors().last().unwrap().to_path_buf();
- let (files, notices) = launch_imports_in(&[".".to_string()], Some(&root), None);
++ let LaunchArgs { files, notices, .. } = launch_imports_in(&[".".to_string()], Some(&root), None);
+ assert!(files.iter().all(|f| f.ends_with("DCIM")) && files.len() + notices.len() == 1, "{files:?} {notices:?}");
+ let _ = std::fs::remove_dir_all(&home);
+ }
+
++/// `--library` and `LIGHTCRAFT_LIBRARY` win over a library given as an argument, which is
++/// then not remembered either.
++#[test]
++fn the_library_flag_and_variable_win_over_a_library_argument() {
++ use std::path::PathBuf;
++ let (flag, env, arg) = (PathBuf::from("flag"), PathBuf::from("env"), PathBuf::from("arg"));
++ assert_eq!(launch_library_choice(Some(flag.clone()), Some(&env), Some(arg.clone())), (Some(flag.clone()), false));
++ assert_eq!(launch_library_choice(None, Some(&env), Some(arg.clone())), (None, false), "the variable is passed on as itself");
++ assert_eq!(launch_library_choice(None, None, Some(arg.clone())), (Some(arg), true));
++ assert_eq!(launch_library_choice(None, None, None), (None, false));
++ assert_eq!(launch_library_choice(Some(flag.clone()), None, None), (Some(flag), false));
++}
++
++/// A library's catalog.snap (double-clicked in Explorer) or its folder given at
++/// launch opens that library and is never imported as photos; a second library is left with a notice.
++#[test]
++fn a_librarys_catalog_given_at_launch_opens_that_library() {
++ let home = dir("launch-library");
++ let lib = home.join("Wedding LC");
++ let mut s = lightcraft_engine::Session::new().with_fs();
++ s.open_library(&lib, false).unwrap();
++ s.close_library().unwrap();
++ let snap = lib.join("catalog.snap");
++ assert!(snap.is_file(), "a library keeps its catalog.snap");
++ let other = home.join("Other LC");
++ let mut s = lightcraft_engine::Session::new().with_fs();
++ s.open_library(&other, false).unwrap();
++ s.close_library().unwrap();
++ for arg in [snap.to_string_lossy().to_string(), lib.to_string_lossy().to_string(), "Wedding LC/catalog.snap".to_string()] {
++ let got = launch_imports_in(std::slice::from_ref(&arg), Some(&home), Some(&home.join("elsewhere")));
++ assert_eq!(got.library.as_deref(), Some(lib.as_path()), "{arg}");
++ assert!(got.files.is_empty() && got.notices.is_empty(), "{arg}: never imported: {got:?}");
++ }
++ let got = launch_imports_in(&[snap.to_string_lossy().to_string(), other.to_string_lossy().to_string()], Some(&home), None);
++ assert_eq!(got.library.as_deref(), Some(lib.as_path()), "the first one");
++ assert_eq!(got.notices.len(), 1, "{got:?}");
++ let _ = std::fs::remove_dir_all(&home);
++}
++
+ /// Issue #236: the window answers control requests on its UI thread, so the desktop session
+ /// adds to Apple Photos on a worker (headless sessions wait instead).
+ #[test]
+ fn the_desktop_session_adds_to_apple_photos_in_the_background() {
+ let (s, problem) = open_session(true, &Launch::Open { dir: None, alt_asks: false }, false);
+ assert!(problem.is_none());
+ assert!(s.apple_photos_background);
+ assert!(!lightcraft_engine::Session::new().apple_photos_background);
+ }
+
+ /// Issue #1290: with Settings ▸ At launch ▸ Ask me nothing is opened (nor seeded with demo
+ /// photos) before the user chooses, and the settings are still saved while the list shows (a
+ /// removed entry is kept), unlike the failed-library window's temporary session.
+ #[test]
+ fn asking_at_launch_opens_nothing_and_still_saves_the_settings() {
+ let (s, problem) = open_session(false, &Launch::Ask, true);
+ assert!(problem.is_none() && s.library.is_none() && s.catalog.is_empty());
+ assert!(s.apple_photos_background, "the same desktop session as an opened one");
+
+ let d = dir("writer-ask");
+ let path = d.join("ui.json");
+ let mut app = LightcraftApp::new(s, Services::default());
+ app.ui.settings.recent_libraries = vec!["/gone/a".into(), "/gone/b".into()];
+ app.library_problem = Some(LibraryProblem::choose_later(&app.ui.settings));
+ let mut w = PrefsWriter { path: Some(path.clone()), ..Default::default() };
+ app.ui.settings.recent_libraries.remove(0);
+ w.save(&app).unwrap();
+ let saved: UiState = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
+ assert_eq!(saved.settings.recent_libraries, ["/gone/b"]);
+ // the failed-library window still writes nothing
+ app.library_problem = Some(LibraryProblem::new("/gone/b", "not there"));
+ app.ui.settings.recent_libraries.clear();
+ w.save(&app).unwrap();
+ let saved: UiState = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
+ assert_eq!(saved.settings.recent_libraries, ["/gone/b"]);
+ let _ = std::fs::remove_dir_all(&d);
+ }
+
+ /// Issue #103: a damaged ui.json (which holds the library location) is kept aside and
+ /// reported, not silently replaced by the defaults.
+ #[test]
+ fn damaged_ui_json_is_kept_and_reported() {
+ let d = dir("damaged");
+ let path = d.join("ui.json");
+ std::fs::write(&path, br#"{"settings": {"library_path": "/Volumes/Photos/Lib"#).unwrap();
+ let (ui, warning, keep) = load_prefs_at(&path, true);
+ assert!(ui.is_none() && !keep);
+ let warning = warning.unwrap();
+ assert!(warning.contains("damaged") && warning.contains("ui.json.corrupt-"), "{warning}");
+ assert!(!path.exists());
+ let kept: Vec<_> = std::fs::read_dir(&d).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().to_string()).collect();
+ assert!(kept.len() == 1 && kept[0].starts_with("ui.json.corrupt-"), "{kept:?}");
+ // a missing file is just "no settings yet"
+ assert_eq!(load_prefs_at(&path, true).1, None);
+ let _ = std::fs::remove_dir_all(&d);
+ }
+
+ /// Issue #164: a `--memory` session reads the settings but writes nothing — a damaged file is
+ /// reported and left where it is, not set aside.
+ #[test]
+ fn memory_session_leaves_a_damaged_ui_json_alone() {
+ let d = dir("damaged-memory");
+ let path = d.join("ui.json");
+ let bytes = br#"{"settings": {"library_path": "/Volumes/Photos/Lib"#;
+ std::fs::write(&path, bytes).unwrap();
+ let (ui, warning, keep) = load_prefs_at(&path, false);
+ assert!(ui.is_none() && keep);
+ let warning = warning.unwrap();
+ assert!(warning.contains("damaged") && warning.contains("nothing is saved"), "{warning}");
+ assert_eq!(std::fs::read(&path).unwrap(), bytes);
+ assert_eq!(std::fs::read_dir(&d).unwrap().count(), 1);
+ let _ = std::fs::remove_dir_all(&d);
+ }
+
+ #[test]
+ fn docking_survives_native_settings_file_reload() {
+ use lightcraft_ui_egui::docking::Panel;
+ let d = dir("docking-reload");
+ let path = d.join("ui.json");
+ let mut app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services::default());
+ app.run("ui.dock", serde_json::json!({"operation":"float", "panel":"tools", "rect":[70,80,310,500]})).unwrap();
+ app.run("ui.dock", serde_json::json!({"operation":"close", "panel":"tools"})).unwrap();
+ let mut writer = PrefsWriter { path: Some(path.clone()), ..Default::default() };
+ writer.save_ui(&app.ui, false).unwrap();
+ let (restored, warning, keep) = load_prefs_at(&path, false);
+ assert!(warning.is_none());
+ assert!(!keep);
+ let mut restored_app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services::default());
+ restored_app.ui = restored.unwrap();
+ restored_app.run("ui.dock", serde_json::json!({"operation":"open", "panel":"tools"})).unwrap();
+ assert_eq!(
+ restored_app.ui.docking.as_ref().unwrap().layout.floating.iter().find(|g| g.contains(&Panel::Tools)).unwrap().rect,
+ [70.0, 80.0, 310.0, 500.0]
+ );
+ std::fs::remove_dir_all(d).unwrap();
+ }
+
+ #[test]
+ fn future_docking_preserves_library_settings_and_the_original_preferences_file() {
+ let d = dir("future-docking");
+ let path = d.join("ui.json");
+ let mut ui = UiState { thumb_size: 210.0, filmstrip: false, ..Default::default() };
+ ui.settings.library_path = "/Volumes/Photos/Synthetic Library".into();
+ for docking in [serde_json::json!({"layout":{"root":{"FutureLayout":{}}}}), serde_json::json!(false)] {
+ let mut saved = serde_json::to_value(&ui).unwrap();
+ saved["docking"] = docking;
+ assert!(serde_json::from_value::<UiState>(saved.clone()).is_err(), "runtime state parsing stays strict");
+ let bytes = serde_json::to_vec(&saved).unwrap();
+ for set_aside in [false, true] {
+ std::fs::write(&path, &bytes).unwrap();
+ let (loaded, warning, keep) = load_prefs_at(&path, set_aside);
+ let loaded = loaded.unwrap();
+ assert_eq!(loaded.settings.library_path, ui.settings.library_path);
+ assert_eq!(loaded.thumb_size, ui.thumb_size);
+ assert!(!loaded.filmstrip);
+ assert!(loaded.docking.is_none());
+ assert!(warning.unwrap().contains("Other settings were loaded"));
+ assert!(keep);
+ let mut writer = PrefsWriter { path: Some(path.clone()), keep_file: keep, ..Default::default() };
+ writer.save_ui(&loaded, false).unwrap();
+ assert_eq!(std::fs::read(&path).unwrap(), bytes);
+ assert_eq!(std::fs::read_dir(&d).unwrap().count(), 1, "a future layout does not rename or replace the settings file");
+ }
+ }
+ std::fs::remove_dir_all(d).unwrap();
+ }
+
+ /// Issue #164: the writer saves changed settings to its file — and nothing at all without one
+ /// (`--memory`) or while the session is the temporary one offered when the library can't open.
+ #[test]
+ fn prefs_writer_writes_nothing_in_a_memory_or_temporary_session() {
+ let d = dir("writer");
+ let path = d.join("sub").join("ui.json");
+ let mut ui = UiState::default();
+ // an ordinary session: a change is written, the folder created on the way
+ let mut w = PrefsWriter { path: Some(path.clone()), ..Default::default() };
+ ui.thumb_size += 50.0;
+ w.save_ui(&ui, false).unwrap();
+ let saved = std::fs::read(&path).unwrap();
+ assert!(String::from_utf8_lossy(&saved).contains("thumbSize"), "{}", String::from_utf8_lossy(&saved));
+ // the temporary session (library problem): a further change is not written…
+ ui.thumb_size += 50.0;
+ w.save_ui(&ui, true).unwrap();
+ assert_eq!(std::fs::read(&path).unwrap(), saved);
+ // …until a library opens
+ w.save_ui(&ui, false).unwrap();
+ assert_ne!(std::fs::read(&path).unwrap(), saved);
+ // --memory: no path, so no file and no folder, whatever changes
+ let d2 = dir("writer-memory");
+ let _ = std::fs::remove_dir_all(&d2);
+ let mut w = PrefsWriter { path: None, ..Default::default() };
+ ui.thumb_size += 50.0;
+ w.save_ui(&ui, false).unwrap();
+ assert!(w.written.is_empty() && !d2.exists());
+ let _ = std::fs::remove_dir_all(&d);
+ }
+
+ /// Issue #169: a `--memory` session neither arms the GPU crash sentinel (which would create
+ /// the settings folder) nor removes a marker a crashed launch left; it still reports it, and
+ /// the next ordinary launch finds it, reports it and clears it.
+ #[test]
+ fn memory_session_leaves_the_gpu_marker_and_folder_alone() {
+ let d = dir("gpu-marker-memory");
+ let _ = std::fs::remove_dir_all(&d);
+ let m = d.join("gpu-init.marker");
+ // nothing left behind: no notice, and the folder is not created
+ assert_eq!(gpu_crash_check_at(Some(m.clone()), true), None);
+ assert!(!d.exists(), "a --memory session must not create the settings folder");
+ // a marker left by a crashed launch: reported, kept
+ std::fs::create_dir_all(&d).unwrap();
+ std::fs::write(&m, "GPU device creation started (backends METAL)").unwrap();
+ let notice = gpu_crash_check_at(Some(m.clone()), true).unwrap();
+ assert!(notice.contains("GPU rendering is now off"), "{notice}");
+ assert!(m.exists(), "the marker stays for the next ordinary launch");
+ // the next ordinary launch reports it once and removes it
+ assert!(gpu_crash_check_at(Some(m.clone()), false).is_some());
+ lightcraft_engine::gpu::backend::set_init_marker(None);
+ assert!(!m.exists());
+ assert_eq!(gpu_crash_check_at(Some(m.clone()), false), None);
+ lightcraft_engine::gpu::backend::set_init_marker(None);
+ let _ = std::fs::remove_dir_all(&d);
+ }
+
+ /// Issue #1337: the window stopped drawing after the graphics driver reset the GPU during an
+ /// export, and the dialog said the window "could not open". The stop is recorded; the next
+ /// launch says why once and renders on the CPU (a `--memory` session leaves the record).
+ #[test]
+ fn a_gpu_lost_while_running_turns_the_gpu_off_next_time() {
+ let d = dir("gpu-lost");
+ let m = d.join("gpu-lost.marker");
+ assert_eq!(gpu_lost_check_at(Some(&m), false), None, "nothing recorded");
+ assert_eq!(gpu_lost_check_at(None, false), None, "no settings folder");
+ record_gpu_lost(Some(&m), "device lost (Unknown): Device is lost");
+ let notice = gpu_lost_check_at(Some(&m), true).unwrap();
+ assert!(
+ notice.contains("(device lost (Unknown): Device is lost)")
+ && notice.contains("GPU rendering is now off")
+ && notice.contains("Use the GPU for rendering"),
+ "{notice}"
+ );
+ assert!(m.exists(), "a --memory session leaves it");
+ assert!(gpu_lost_check_at(Some(&m), false).is_some());
+ assert!(!m.exists());
+ assert_eq!(gpu_lost_check_at(Some(&m), false), None, "said once");
+ // the message box: LightCraft stopped (not "could not open its window"), and why
+ let text = stopped_text("its window stopped drawing (the renderer panicked)", Some("device lost (Unknown): Device is lost"));
+ assert!(text.contains("reset the GPU (device lost (Unknown)") && text.contains("renders on the CPU from its next start"), "{text}");
+ assert_eq!(stopped_text("its window stopped drawing", None), "its window stopped drawing");
+ let (title, body) = lightcraft_ui_egui::i18n::stopped_message(&text, Some("/logs/lightcraft.log"));
+ assert_eq!(title, "LightCraft stopped");
+ assert!(body.starts_with("LightCraft stopped unexpectedly: its window stopped drawing") && body.ends_with("/logs/lightcraft.log"), "{body}");
+ let _ = std::fs::remove_dir_all(&d);
+ }
+
+ /// Issue #136: a GPU init marker left by a crashed launch is reported once and removed.
+ #[test]
+ fn gpu_crash_marker_is_reported_once() {
+ let d = dir("gpu-marker");
+ let m = d.join("gpu-init.marker");
+ assert_eq!(lightcraft_engine::gpu::backend::take_init_marker(&m), None);
+ std::fs::write(&m, "GPU device creation started (backends VULKAN | DX12)").unwrap();
+ let what = lightcraft_engine::gpu::backend::take_init_marker(&m).unwrap();
+ let notice = gpu_crash_notice(&what);
+ assert!(notice.contains("GPU rendering is now off") && notice.contains("Use the GPU for rendering"), "{notice}");
+ assert!(!m.exists());
+ let _ = std::fs::remove_dir_all(&d);
+ }
+
+ /// Issue #136: Windows windows render with DX12 alone (no Vulkan driver loaded) by default.
+ #[test]
+ fn window_backends_follow_the_platform_default() {
+ let eframe::egui_wgpu::WgpuSetup::CreateNew(n) = window_wgpu_options().wgpu_setup else { panic!("expected CreateNew") };
+ let b = n.instance_descriptor.backends;
+ if std::env::var_os("LIGHTCRAFT_GPU_BACKEND").is_none() && std::env::var_os("WGPU_BACKEND").is_none() {
+ if cfg!(windows) {
+ assert_eq!(b, eframe::wgpu::Backends::DX12);
+ } else if cfg!(target_os = "macos") {
+ assert_eq!(b, eframe::wgpu::Backends::METAL);
+ }
+ }
+ assert!(!b.is_empty());
+ }
+
+ /// Issue #471: the window's DX12 shaders compile with FXC — wgpu's default loaded any
+ /// `dxcompiler.dll` on the search path, and one without `dxil.dll` kept the window from opening.
+ #[test]
+ fn window_compiles_dx12_shaders_with_fxc() {
+ let eframe::egui_wgpu::WgpuSetup::CreateNew(n) = window_wgpu_options().wgpu_setup else { panic!("expected CreateNew") };
+ if std::env::var_os("WGPU_DX12_COMPILER").is_none() {
+ assert!(matches!(n.instance_descriptor.backend_options.dx12.shader_compiler, eframe::wgpu::Dx12Compiler::Fxc));
+ }
+ }
+
+ /// Issue #250: the window's device is created without wgpu's indirect-call validation pipeline,
+ /// which Intel Macs' Metal compiler fails to build (the device was lost, the window never opened).
+ #[test]
+ fn window_has_no_indirect_call_validation_pipeline() {
+ let eframe::egui_wgpu::WgpuSetup::CreateNew(n) = window_wgpu_options().wgpu_setup else { panic!("expected CreateNew") };
+ if std::env::var_os("WGPU_VALIDATION_INDIRECT_CALL").is_none() {
+ assert!(!n.instance_descriptor.flags.contains(eframe::wgpu::InstanceFlags::VALIDATION_INDIRECT_CALL));
+ }
+ }
+
+ /// Issue #234: Windows opens links with the URL protocol handler (the default browser), not
+ /// File Explorer, and passes the whole map link, `?`, `&` and `#` included, as one argument.
+ #[test]
+ fn windows_links_open_in_the_browser() {
+ let url = "https://www.openstreetmap.org/?mlat=48.856600&mlon=2.352200#map=15/48.856600/2.352200";
+ let c = windows_open_url_command(url);
+ assert_eq!(c.get_program(), "rundll32");
+ let args: Vec<&std::ffi::OsStr> = c.get_args().collect();
+ assert_eq!(args, ["url.dll,FileProtocolHandler", url]);
+ }
+
+ /// Issue #272: Explorer gets the file to select quoted after `/select,`, with backslashes and
+ /// without the verbatim prefix, even when the path has spaces (else it opens Documents).
+ #[test]
+ fn explorer_select_quotes_the_path() {
+ assert_eq!(explorer_select_arg(r"C:\Users\Me\My Photos\IMG 1.jpg"), r#"/select,"C:\Users\Me\My Photos\IMG 1.jpg""#);
+ assert_eq!(explorer_select_arg("D:/Example/Photos/IMG_0001.CR3"), r#"/select,"D:\Example\Photos\IMG_0001.CR3""#);
+ assert_eq!(explorer_select_arg(r"\\server\share\My Photos\a.jpg"), r#"/select,"\\server\share\My Photos\a.jpg""#);
+ assert_eq!(explorer_select_arg(r"\\?\D:\My Photos\a.jpg"), r#"/select,"D:\My Photos\a.jpg""#);
+ assert_eq!(explorer_select_arg(r"\\?\UNC\server\share\a.jpg"), r#"/select,"\\server\share\a.jpg""#);
+ // a `"` can't end the quoted path and add arguments to the raw command line
+ assert_eq!(explorer_select_arg(r#"C:\a" "C:\b.jpg"#), r#"/select,"C:\a C:\b.jpg""#);
+ let c = explorer_select_command(r"C:\My Photos\a.jpg");
+ assert_eq!(c.get_program(), "explorer");
+ let args: Vec<&std::ffi::OsStr> = c.get_args().collect();
+ assert_eq!(args, [r#"/select,"C:\My Photos\a.jpg""#]);
+ }
+
+ #[test]
+ fn a_control_port_that_is_not_a_number_is_ignored() {
+ assert_eq!(control_port_from("--control", Some("7980".into())), Some(7980));
+ assert_eq!(control_port_from("--control", Some(" 18001 ".into())), Some(18001));
+ assert_eq!(control_port_from("--control", Some("nope".into())), None);
+ assert_eq!(control_port_from("--control", Some(String::new())), None);
+ assert_eq!(control_port_from("--control", Some("70000".into())), None);
+ assert_eq!(control_port_from("LIGHTCRAFT_CONTROL_PORT", None), None);
+ }
+
+ #[test]
+ fn ui_json_is_written_atomically() {
+ let d = dir("atomic");
+ let path = d.join("ui.json");
+ std::fs::write(&path, b"old").unwrap();
+ write_atomic(&path, b"{\"new\": true}").unwrap();
+ assert_eq!(std::fs::read(&path).unwrap(), b"{\"new\": true}");
+ assert!(!d.join("ui.json.tmp").exists());
+ // a failed write leaves the old file
+ let missing = d.join("gone").join("ui.json");
+ assert!(write_atomic(&missing, b"x").is_err());
+ assert_eq!(std::fs::read(&path).unwrap(), b"{\"new\": true}");
+ let ui = UiState::default();
+ write_atomic(&path, &serde_json::to_vec_pretty(&ui).unwrap()).unwrap();
+ let (loaded, warning, _) = load_prefs_at(&path, true);
+ assert!(loaded.is_some() && warning.is_none());
+ let _ = std::fs::remove_dir_all(&d);
+ }
+
+ /// Given what the settings remember of the window, when the app's window is built, then it
+ /// opens at that size, zoomed if it was, where the system puts it; with nothing remembered it
+ /// opens at the usual size.
+ #[test]
+ fn the_window_opens_as_it_was() {
+ use lightcraft_ui_egui::window_place::{DEFAULT_SIZE, WindowPlace};
+ let fresh = as_remembered(egui::ViewportBuilder::default(), None);
+ assert_eq!((fresh.inner_size, fresh.position, fresh.maximized), (Some(egui::Vec2::from(DEFAULT_SIZE)), None, None));
+ let b = as_remembered(egui::ViewportBuilder::default(), Some(WindowPlace { size: [1300.0, 800.0], zoomed: true }));
+ assert_eq!((b.inner_size, b.position, b.maximized), (Some(egui::vec2(1300.0, 800.0)), None, Some(true)));
+ // (not asked to un-zoom: macOS would then resize a window that fills its screen)
+ let b = as_remembered(egui::ViewportBuilder::default(), Some(WindowPlace { size: [1300.0, 800.0], zoomed: false }));
+ assert_eq!((b.inner_size, b.position, b.maximized), (Some(egui::vec2(1300.0, 800.0)), None, None));
+ }
+
+ /// Given a window that rests at a size, when the settings are written and read again, then
+ /// they hold how it was. A window in the file that is not one (a hand edit, another version's)
+ /// reads as nothing remembered and costs no other setting; and a window resized just before
+ /// the app quits is remembered at that size.
+ #[test]
+ fn the_settings_keep_how_the_window_was() {
+ use lightcraft_ui_egui::window_place::{Seen, WindowPlace};
+ let d = dir("window");
+ let path = d.join("ui.json");
+ let mut app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services::default());
+ app.ui.settings.library_path = "/pictures/library".into();
+ let mut writer = PrefsWriter { path: Some(path.clone()), ..Default::default() };
+ writer.save(&app).unwrap();
+ assert!(!std::fs::read_to_string(&path).unwrap().contains("\"window\""), "nothing to remember yet");
+ let window = WindowPlace { size: [1300.0, 800.0], zoomed: true };
+ app.ui.window = Some(window);
+ writer.save(&app).unwrap();
+ let (restored, warning, _) = load_prefs_at(&path, false);
+ assert_eq!((restored.unwrap().window, warning), (Some(window), None));
+
+ // a window that is no window: the file is read all the same, with its other settings
+ let text = std::fs::read_to_string(&path).unwrap();
+ for odd in [r#""window": {}"#, r#""window": "wide""#, r#""window": {"size": [1, 2, 3]}"#, r#""window": {"size": [null, 800.0]}"#] {
+ let start = text.find("\"window\"").unwrap();
+ let end = start + text[start..].find('}').unwrap() + 1;
+ std::fs::write(&path, format!("{}{odd}{}", &text[..start], &text[end..])).unwrap();
+ let (restored, warning, keep) = load_prefs_at(&path, true);
+ let restored = restored.unwrap_or_else(|| panic!("{odd}: {warning:?}"));
+ assert_eq!((restored.window, restored.settings.library_path.as_str(), warning, keep), (None, "/pictures/library", None, false), "{odd}");
+ }
+
+ // resized, and the app quits a moment later: the new size is what is written
+ let mut writer = PrefsWriter { path: Some(path.clone()), ..Default::default() };
+ let rest = Some(WindowPlace { size: [1300.0, 800.0], zoomed: false });
+ writer.window.note(rest, &Seen { size: Some([1500.0, 900.0]), ..Default::default() }, 0.0);
+ writer.window_since = std::time::Instant::now().checked_sub(std::time::Duration::from_millis(400));
+ assert!(writer.window_since.is_some());
+ assert_eq!(writer.window_at_exit(rest), Some(WindowPlace { size: [1500.0, 900.0], zoomed: false }));
+ assert_eq!(PrefsWriter::default().window_at_exit(rest), rest, "a window that was never seen");
+ let _ = std::fs::remove_dir_all(&d);
+ }
+
+ /// Given the app's window at a size, when the settings writer looks at it frame after frame,
+ /// then it asks to be woken while the size has still to rest, remembers the size once it has,
+ /// and asks for nothing more. A window in the settings that is not one (a script set it) is
+ /// put right before it is gone by.
+ #[test]
+ fn the_writer_follows_the_window_from_frame_to_frame() {
+ use lightcraft_ui_egui::window_place::WindowPlace;
+ let mut app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services::default());
+ let mut writer = PrefsWriter::default();
+ let ctx = egui::Context::default();
+ let pass = |look: &mut dyn FnMut(&egui::Context)| {
+ let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1300.0, 800.0))), ..Default::default() };
+ let mut out = ctx.run_ui(raw, |ui| look(ui.ctx()));
+ out.textures_delta.clear();
+ out.viewport_output.get(&egui::ViewportId::ROOT).map(|v| v.repaint_delay)
+ };
+ // (egui's own first frames ask for another: let them pass)
+ for _ in 0..3 {
+ pass(&mut |_| {});
+ }
+ app.ui.window = Some(WindowPlace { size: [f32::NAN, 800.0], zoomed: true });
+ let asked = pass(&mut |ctx| writer.tick(&mut app, ctx));
+ assert_eq!(app.ui.window, None, "no window, and not yet at rest");
+ assert!(asked.is_some_and(|wait| wait <= std::time::Duration::from_secs(1)), "{asked:?}");
+ // a second later
+ writer.window_since = writer.window_since.and_then(|since| since.checked_sub(std::time::Duration::from_secs(1)));
+ pass(&mut |ctx| writer.tick(&mut app, ctx));
+ assert_eq!(app.ui.window, Some(WindowPlace { size: [1300.0, 800.0], zoomed: false }));
+ let asked = pass(&mut |ctx| writer.tick(&mut app, ctx));
+ assert!(asked.is_none_or(|wait| wait > std::time::Duration::from_secs(3600)), "at rest and remembered: {asked:?}");
+ }
+
+ /// #1331: on macOS the process ends inside `on_exit`, before eframe would tear the window down.
+ /// The check runs in a child (this test binary again), since on macOS it ends the process.
+ #[test]
+ fn on_exit_ends_the_process_on_macos() {
+ if std::env::var_os("LIGHTCRAFT_TEST_ON_EXIT").is_some() {
+ let app = LightcraftApp::new(lightcraft_engine::Session::new(), Services::default());
+ let mut app = App(
+ app,
+ PrefsWriter::default(),
+ #[cfg(target_os = "macos")]
+ None,
+ );
+ println!("calling on_exit");
+ eframe::App::on_exit(&mut app, None);
+ println!("on_exit returned");
+ return;
+ }
+ let out = std::process::Command::new(std::env::current_exe().unwrap())
+ .args(["--exact", "tests::on_exit_ends_the_process_on_macos", "--nocapture"])
+ .env("LIGHTCRAFT_TEST_ON_EXIT", "1")
+ .env("LIGHTCRAFT_NO_PREFS", "1")
+ .output()
+ .unwrap();
+ let stdout = String::from_utf8_lossy(&out.stdout);
+ assert!(out.status.success(), "{stdout}");
+ assert!(stdout.contains("calling on_exit"), "the child didn't run the test: {stdout}");
+ assert_eq!(stdout.contains("on_exit returned"), !cfg!(target_os = "macos"), "{stdout}");
+ }
diff --cc crates/engine/src/import/files.rs
index 000000000,2cbfc85e7..5b07e1171
mode 000000,100644..100644
--- a/crates/engine/src/import/files.rs
+++ b/crates/engine/src/import/files.rs
@@@ -1,0 -1,372 +1,389 @@@
+ #[cfg(not(target_arch = "wasm32"))]
+ use super::commit::workers;
+ #[cfg(test)]
+ use super::job::{ImportJob, Prepared, PreparedItem, ReadyFile};
+ use super::scan::ScanProgress;
+ #[cfg(test)]
+ use super::types::{ImportMode, ImportOptions};
+ use super::*;
+
+ /// File extensions offered by import discovery and file pickers (lower case).
+ /// This includes preview-only raws; the file probe decides whether sensor decoding is available.
+ pub const EXTENSIONS: &[&str] = &[
+ "jpg", "jpeg", "png", "tif", "tiff", "webp", "dng", "cr2", "cr3", "nef", "nrw", "arw", "sr2", "srf", "raf", "orf", "rw2", "rwl", "raw", "pef",
+ "srw", "psd", "psb", "jxl", "gif", "bmp",
+ // Decoded when built with the codecs' `heif` feature; otherwise the import reports them as
+ // failed with the reason ("HEIC/HEIF support isn't included in this build").
+ "heic", "heif", "avif", // no AV1 decoder yet: reported as failed, like a HEIC without the feature
+ "iiq", "crw", "mrw", "x3f", "kdc", "mos", "erf", "3fr", "fff", "mef",
+ ];
+
+ pub fn is_supported(path: &Path) -> bool {
+ path.extension().is_some_and(|e| EXTENSIONS.contains(&e.to_string_lossy().to_lowercase().as_str()))
+ }
+
+ /// The web file picker's accept list, derived from [`EXTENSIONS`]. Each extension
+ /// is listed in both cases: browsers' `accept` matching is case-insensitive per
+ /// spec, but some implementations (e.g. Windows/Edge) match case-sensitively and
+ /// rejected uppercase `.NEF` files, so a lowercase-only list silently hid raws
+ /// such as CR3, NRW, RAF, ORF, RW2, RWL, RAW, PEF and SRW from the picker.
+ ///
+ /// The picker only offers files this build can actually import: `.avif` has no
+ /// AV1 decoder in any build, and `.heic`/`.heif` decode only when the codecs'
+ /// `heif` feature is enabled ([`lightcraft_codecs::Format::Heif::can_decode`]).
+ /// [`EXTENSIONS`] itself stays complete — files on disk are still recognised,
+ /// and import reports them as failed, saying why.
+ pub fn accept_list() -> String {
+ let heif_decodable = lightcraft_codecs::Format::Heif.can_decode();
+ let mut out = String::new();
+ for &ext in EXTENSIONS {
+ // Skip extensions a web user could pick but this build could not import.
+ let pickable = match ext {
+ "avif" => false,
+ "heic" | "heif" => heif_decodable,
+ _ => true,
+ };
+ if !pickable {
+ continue;
+ }
+ if !out.is_empty() {
+ out.push(',');
+ }
+ out.push('.');
+ out.push_str(ext);
+ out.push(',');
+ out.push('.');
+ out.push_str(&ext.to_uppercase());
+ }
+ out
+ }
+
+ /// Expand files and folders (recursively) into supported files. `skip` (e.g. the library folder)
+ /// is never descended into. Each folder's walk is bounded ([`crate::walk::Limits::default`]); a
+ /// walk that stops at a bound is logged.
+ pub fn expand(paths: &[String], skip: Option<&Path>) -> Vec<String> {
+ expand_within(paths, skip, crate::walk::Limits::default()).0
+ }
+
+ /// [`expand`] with the walk bounded by `limits` → (files, whether a walk stopped at a bound).
+ pub fn expand_within(paths: &[String], skip: Option<&Path>, limits: crate::walk::Limits) -> (Vec<String>, bool) {
+ expand_noting(paths, skip, limits, None)
+ }
+
+ /// [`expand_within`], handing the listing of every folder that is walked to `note`
+ /// ([`crate::walk::files_in_noting`]).
+ pub(crate) fn expand_noting(
+ paths: &[String],
+ skip: Option<&Path>,
+ limits: crate::walk::Limits,
+ mut note: Option<crate::walk::NoteFolder>,
+ ) -> (Vec<String>, bool) {
+ let mut out = Vec::new();
+ let mut truncated = false;
+ for p in paths {
+ let p = Path::new(p);
+ if skip.is_some_and(|s| p == s) {
+ continue;
+ }
+ if p.is_dir() {
+ let w = match note.as_mut() {
+ Some(note) => crate::walk::files_in_noting(p, skip, limits, is_supported, &mut **note),
+ None => crate::walk::files_in(p, skip, limits, is_supported),
+ };
+ if w.truncated {
+ log::warn!(
+ "import: stopped looking in {} after {} entries (limits: {} entries, {} folder levels)",
+ p.display(),
+ w.entries,
+ limits.max_entries,
+ limits.max_depth
+ );
+ }
+ truncated |= w.truncated;
+ out.extend(w.files.into_iter().map(|f| f.to_string_lossy().to_string()));
+ } else {
+ // explicitly named files are attempted even with an unknown extension (sniffed)
+ out.push(p.to_string_lossy().to_string());
+ }
+ }
+ let mut seen = std::collections::HashSet::new();
+ out.retain(|p| seen.insert(p.clone()));
+ (out, truncated)
+ }
+
+ /// What a path given on the command line at launch becomes ([`launch_path`]).
+ #[derive(Clone, Debug, PartialEq, Eq)]
+ pub enum LaunchPath {
+ /// Import this (absolute) file or folder, in the background.
+ Import(String),
+ /// Not imported: `path` (absolute) is a whole drive or the whole home folder, which is never
+ /// walked without being chosen in the app (issue #374).
+ Refused { path: String, why: String },
++ /// Open this (absolute) library folder: the argument was a library's `catalog.snap` or its folder, as a
++ /// double-click on a catalog in the file manager gives. Never imported.
++ Library(String),
++}
++
++/// The library folder `path` names: a library's `catalog.snap` (its folder), or a folder holding one. `None` for
++/// anything else (photos, folders of photos).
++pub fn library_dir_of(path: &Path) -> Option<PathBuf> {
++ let snapshot = lightcraft_catalog::journal::SNAPSHOT;
++ let named = path.file_name().is_some_and(|n| n.to_string_lossy().eq_ignore_ascii_case(snapshot));
++ if named && path.is_file() {
++ return path.parent().map(Path::to_path_buf);
++ }
++ (path.is_dir() && path.join(snapshot).is_file()).then(|| path.to_path_buf())
+ }
+
+ /// Resolve a launch argument for importing (issue #374). An empty argument is ignored (`None`);
+ /// a relative one (`.`, `..`, `photos`; `/` or `\` on Windows, the current drive's root) is
+ /// resolved against `cwd` — the working folder a launcher picked, often a drive root or
+ /// `C:\Windows\System32` — and refused when that leaves no folder (`cwd` unknown). A drive
+ /// or file-system root is replaced by its camera folder (`DCIM`, from `dcim`: a memory card) or
+ /// refused, and so is the home folder `home`: either would walk most of the disk.
+ pub fn launch_path(arg: &str, cwd: Option<&Path>, home: Option<&Path>, dcim: impl Fn(&Path) -> Option<PathBuf>) -> Option<LaunchPath> {
+ if arg.trim().is_empty() {
+ return None;
+ }
+ let given = Path::new(arg);
+ let joined = if given.is_absolute() {
+ given.to_path_buf()
+ } else {
+ match cwd {
+ Some(c) => c.join(given),
+ None => return Some(LaunchPath::Refused { path: arg.to_string(), why: "a relative path, and the working folder is unknown".into() }),
+ }
+ };
+ // `.` and `..` resolved by name (no file-system access)
+ let mut abs = PathBuf::new();
+ for c in joined.components() {
+ match c {
+ std::path::Component::CurDir => {}
+ std::path::Component::ParentDir => {
+ abs.pop();
+ }
+ other => abs.push(other.as_os_str()),
+ }
+ }
+ let shown = abs.to_string_lossy().to_string();
+ if abs.parent().is_none() {
+ return Some(match dcim(&abs) {
+ Some(d) => LaunchPath::Import(d.to_string_lossy().to_string()),
+ None => LaunchPath::Refused { path: shown, why: "a whole drive".into() },
+ });
+ }
+ let key = lightcraft_catalog::query::folder_key;
+ if home.is_some_and(|h| key(&h.to_string_lossy()) == key(&shown)) {
+ return Some(LaunchPath::Refused { path: shown, why: "the whole home folder".into() });
+ }
++ if let Some(dir) = library_dir_of(&abs) {
++ return Some(LaunchPath::Library(dir.to_string_lossy().to_string()));
++ }
+ Some(LaunchPath::Import(shown))
+ }
+
+ /// Probe files (headers + content hash) as an import would.
+ pub(crate) fn probe_paths(s: &Session, paths: &[String]) -> Vec<Result<ProbeInfo, String>> {
+ let progress = ScanProgress::default();
+ probe_all(s.media.file_probe.as_ref(), paths, &progress.done, &progress.cancel)
+ }
+
+ /// Probe files with `probe` (a clone of the session's file probe), off the session: on a worker thread.
+ pub(crate) fn probe_with(probe: &crate::media::FileProbe, paths: &[String]) -> Vec<Result<ProbeInfo, String>> {
+ let progress = ScanProgress::default();
+ probe_all(Some(probe), paths, &progress.done, &progress.cancel)
+ }
+
+ /// Probe `paths` (several at once), counting each in `done`. Stops before the next file once
+ /// `cancel` is set: the files not reached come back as errors.
+ pub(crate) fn probe_all(
+ probe: Option<&crate::media::FileProbe>,
+ paths: &[String],
+ done: &std::sync::atomic::AtomicUsize,
+ cancel: &std::sync::atomic::AtomicBool,
+ ) -> Vec<Result<ProbeInfo, String>> {
+ use std::sync::atomic::Ordering::Relaxed;
+ let Some(probe) = probe.cloned() else {
+ return paths
+ .iter()
+ .map(|p| {
+ Ok(ProbeInfo {
+ format: Path::new(p).extension().map(|e| e.to_string_lossy().to_uppercase()).unwrap_or_default(),
+ ..Default::default()
+ })
+ })
+ .collect();
+ };
+ #[cfg(not(target_arch = "wasm32"))]
+ {
+ let n = workers(paths.len());
+ if n > 1 {
+ let mut results: Vec<Option<Result<ProbeInfo, String>>> = vec![None; paths.len()];
+ let next = std::sync::atomic::AtomicUsize::new(0);
+ let out = std::sync::Mutex::new(&mut results);
+ std::thread::scope(|sc| {
+ for _ in 0..n {
+ sc.spawn(|| {
+ loop {
+ let i = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
+ if i >= paths.len() {
+ break;
+ }
+ if cancel.load(Relaxed) {
+ break;
+ }
+ let r = probe(&paths[i]);
+ done.fetch_add(1, Relaxed);
+ out.lock().unwrap_or_else(|e| e.into_inner())[i] = Some(r);
+ }
+ });
+ }
+ });
+ return results.into_iter().map(|r| r.unwrap_or_else(|| Err("not probed".into()))).collect();
+ }
+ }
+ paths
+ .iter()
+ .map(|p| {
+ if cancel.load(Relaxed) {
+ return Err("cancelled".into());
+ }
+ let r = probe(p);
+ done.fetch_add(1, Relaxed);
+ r
+ })
+ .collect()
+ }
+
+ /// Copy `src` into `dir` as `name` (default: its own name), made unique with -1, -2…; returns the
+ /// new path. The copy is verified ([`crate::import_move::copy_new`]: a new file, synced and
+ /// checked against `probe_hash`, the content hash the probe computed — or compared byte for byte
+ /// with the source when there is none); a bad one is removed and the photo reported as failed.
+ pub(super) fn copy_into(dir: &Path, src: &str, name: Option<&str>, probe_hash: Option<&str>) -> Result<String, String> {
+ let name = name
+ .map(str::to_string)
+ .unwrap_or_else(|| Path::new(src).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "photo".into()));
+ let expect = probe_hash.and_then(lightcraft_preview::Hash128::parse);
+ crate::import_move::copy_new(Path::new(src), dir, &name, expect).map(|p| p.to_string_lossy().to_string())
+ }
+
+ #[cfg(test)]
+ mod prepared_tests {
+ use super::*;
+
+ /// Extensions the picker may offer: every one in [`EXTENSIONS`], minus the
+ /// files this build cannot import (see [`accept_list`]).
+ fn pickable_extensions() -> Vec<&'static str> {
+ let heif_decodable = lightcraft_codecs::Format::Heif.can_decode();
+ EXTENSIONS
+ .iter()
+ .copied()
+ .filter(|ext| match *ext {
+ "avif" => false,
+ "heic" | "heif" => heif_decodable,
+ _ => true,
+ })
+ .collect()
+ }
+
+ #[test]
+ fn accept_list_covers_every_pickable_extension_in_both_cases() {
+ let list = accept_list();
+ for ext in pickable_extensions() {
+ assert!(list.contains(&format!(".{ext}")), "lowercase .{ext} missing from accept list");
+ assert!(list.contains(&format!(".{}", ext.to_uppercase())), "uppercase .{} missing from accept list", ext.to_uppercase());
+ }
+ }
+
+ /// The web picker must not offer files this build cannot import: `.avif` has
+ /// no AV1 decoder in any build, so it is never listed, in either case.
+ #[test]
+ fn accept_list_never_offers_avif() {
+ let list = accept_list();
+ assert!(!list.contains(".avif"), "{list}");
+ assert!(!list.contains(".AVIF"), "{list}");
+ }
+
+ /// `.heic`/`.heif` follow the codecs' `heif` feature: listed (in both cases)
+ /// only when this build can decode them; otherwise hidden, so a web user
+ /// cannot pick a file that would fail to import.
+ #[test]
+ fn accept_list_offers_heic_heif_only_when_decodable() {
+ let list = accept_list();
+ let listed = lightcraft_codecs::Format::Heif.can_decode();
+ for ext in ["heic", "heif"] {
+ assert_eq!(list.contains(&format!(".{ext}")), listed, "lowercase .{ext}");
+ assert_eq!(list.contains(&format!(".{}", ext.to_uppercase())), listed, "uppercase .{ext}");
+ }
+ }
+
+ #[test]
+ fn revalidate_add_only_converts_matching_ready_item() {
+ let mut s = Session::new();
+ let existing_path = std::env::temp_dir().join("lightcraft-revalidate-existing.jpg");
+ let other_path = std::env::temp_dir().join("lightcraft-revalidate-other.jpg");
+ let existing = Photo::new(PhotoId(1), Source::File { path: existing_path.to_string_lossy().into() }, "existing.jpg", "JPG", 1, 1, "now");
+ s.commit("existing", Op::AddPhoto { photo: Box::new(existing) }).unwrap();
+ let ready = |path: &Path| ReadyFile {
+ path: path.to_string_lossy().into(),
+ stored: path.to_string_lossy().into(),
+ info: ProbeInfo { format: "JPG".into(), ..ProbeInfo::default() },
+ sidecar: None,
+ placed: None,
+ };
+ let mut prepared = Prepared {
+ scanned: 2,
+ items: vec![PreparedItem::Ready(Box::new(ready(&existing_path))), PreparedItem::Ready(Box::new(ready(&other_path)))],
+ };
+ prepared.revalidate_add(&s);
+ assert!(matches!(prepared.items.first(), Some(PreparedItem::Duplicate { reason: "path", .. })));
+ assert!(matches!(prepared.items.get(1), Some(PreparedItem::Ready(_))));
+ }
+
+ fn unread_paths(n: usize) -> Vec<String> {
+ (0..n).map(|i| std::env::temp_dir().join(format!("lightcraft-probe-progress-{i}.jpg")).to_string_lossy().into()).collect()
+ }
+
+ /// Reading the files of a large import (a Lightroom catalog's originals) reported nothing:
+ /// the progress stood still at "14 of 24554" for as long as it took.
+ #[test]
+ fn prepare_counts_the_files_it_reads() {
+ use std::sync::atomic::Ordering::Relaxed;
+ let mut s = Session::new();
+ let seen = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
+ let (seen_in_probe, done_in_probe) = (seen.clone(), std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)));
+ let mut job = ImportJob::new(&mut s, ImportOptions { mode: ImportMode::Add, ..ImportOptions::default() }).unwrap();
+ let (done, last) = (job.read_done.clone(), done_in_probe.clone());
+ job.probe = Some(std::sync::Arc::new(move |_: &str| {
+ seen_in_probe.fetch_add(1, Relaxed);
+ last.fetch_max(done.load(Relaxed), Relaxed);
+ Ok(ProbeInfo { format: "JPEG".into(), ..ProbeInfo::default() })
+ }));
+ let prepared = job.prepare(&unread_paths(40), &std::sync::atomic::AtomicBool::new(false));
+ assert_eq!(prepared.items.len(), 40);
+ assert_eq!(seen.load(Relaxed), 40);
+ assert!(done_in_probe.load(Relaxed) > 0, "progress moves while files are read");
+ assert_eq!((job.read_done.load(Relaxed), job.read_total.load(Relaxed)), (40, 40), "every file read is counted");
+ assert_eq!((job.done.load(Relaxed), job.total.load(Relaxed)), (40, 40), "handling them is counted on its own");
+ }
+
+ /// Cancel had no effect until every file had been read.
+ #[test]
+ fn cancel_stops_reading_files() {
+ use std::sync::atomic::Ordering::Relaxed;
+ let mut s = Session::new();
+ let cancel = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
+ let seen = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
+ let mut job = ImportJob::new(&mut s, ImportOptions { mode: ImportMode::Add, ..ImportOptions::default() }).unwrap();
+ let (seen_in_probe, cancel_in_probe) = (seen.clone(), cancel.clone());
+ job.probe = Some(std::sync::Arc::new(move |_: &str| {
+ seen_in_probe.fetch_add(1, Relaxed);
+ cancel_in_probe.store(true, Relaxed);
+ Ok(ProbeInfo { format: "JPEG".into(), ..ProbeInfo::default() })
+ }));
+ let prepared = job.prepare(&unread_paths(400), &cancel);
+ // at most the files the (up to 8) readers had already started
+ assert!(seen.load(Relaxed) <= 8, "read {} files after cancel", seen.load(Relaxed));
+ assert!(prepared.items.is_empty());
+ }
+ }
diff --cc docs/parity-checklist.md
index fceab030b,90cfc248f..bb407adfe
--- a/docs/parity-checklist.md
+++ b/docs/parity-checklist.md
@@@ -699,13 -699,13 +699,13 @@@ From `08-lightroom-classic-extras.md` (
| LRC-LIB-SURVEY | Survey view | P2 | ✅ | `cmd:view.survey` | N |
| LRC-LIB-REFVIEW | Reference view | P2 | ✅ | `cmd:view.reference`, `cmd:photo.setReference`, `crates/ui-egui/src/panels/compare.rs` (`show_reference`) | View ▸ Reference View (⇧R): the reference photo beside the active one (edited with the Edit panel); photo menu ▸ Set as Reference Photo; each pane says “Rendering…” (widget `compare:rendering:<pane>`) or “This photo can't be opened” (`compare:renderFailed:<pane>`) as the loupe does. Escape → Detail without losing edits; pins are catalog-local; missing/deleted photos refused and deleted references no longer drawn (Windows regression/native smoke verified) |
| LRC-LIB-CATALOG-PANEL | Catalog sets | P1 | ✅ | `cmd:library.source` (`missing`) | all, recently added, picks, recently deleted, missing photos (when any) |
- | LRC-LIB-CATALOG-IMPORT | Native Lightroom Classic catalog import | P1 | 🟡 | `cmd:library.inspectLightroom`, `cmd:library.importLightroom`, `cmd:file.importLightroom`, `crates/engine/src/lightroom_catalog.rs`, `crates/ui-egui/src/lightroom_destination.rs`, `crates/ui-egui/src/tests_lightroom_destination.rs`, `docs/lightroom-catalog-import.md` | before the import starts, File ▸ Import Lightroom Catalog… asks where the catalog goes: merge into the open library (named, with its photo count; preselected when it is empty) or create a new library (named after the catalog file, next to the open library, both editable), which is made and opened following File ▸ New Library…'s rules before the import; Cancel does nothing; Settings ▸ General ▸ "When importing a Lightroom catalog" (Ask where to import it / Always merge into the open library) or the window's "Don't ask again" turns it off; `file.importLightroom` takes `into` (`open` / `new`), `name`, `location` to choose without the window; a session in memory merges without asking (issue #2672); read-only `.lrcat` plus committed WAL pages (also WAL-only tables with main schema format 0), in-tree read-only Rust SQLite B-tree reader; on-demand main-file pages up to 16 GiB with existing table/record bounds (WAL still capped at 1 GiB, issue #798); background inspection/import with progress/cancellation, per-open library identity checks; persistent result with destination library, offline-original counts and Show in Library, dismissed when switching libraries; offline Local records are promoted without probing missing files; originals in place, ratings/flags/labels, XMP, hierarchical keywords, collection sets/regular collections, virtual copies, mapped develop settings; stable reimport identities, undo, missing-file placeholders, a root folder not found at its recorded path looked up relative to the catalog (Lightroom's `relativePathFromCatalog`, so a project folder copied from another computer stays linked; reported as a warning), existing edits preserved. Best-effort deduplicated recovery archives retain settings/history/snapshots/collection rules (32 MiB each, eight archives/128 MiB aggregate); archive limits/write failures and optional-table limits warn without blocking photo import; unrelated unsupported tables and opaque SQL BLOBs skipped. Custom white balance on relative-WB raws (`RAW` in Lightroom's terms) stays As Shot and is reported, since the catalog keeps no as-shot white to shift from (issue #510). An image whose file, folder or root folder record is missing from the catalog, or whose original path is empty, is skipped with its virtual copies instead of failing the whole import; the report lists them as data (`skipped`: image id and reason) and the result window counts them in the UI language (PR #2230). Adobe rendering, AI data and native history replay remain incomplete; no writes to Lightroom catalogs. Open Library given a Lightroom catalog folder, an `.lrdata` / `.lrcat-data` folder or the `.lrcat` makes no library there and offers this import with the catalog found (`cmd:app.openLibrary`, `crates/engine/src/lightroom_folder.rs`; issue #891) |
+ | LRC-LIB-CATALOG-IMPORT | Native Lightroom Classic catalog import | P1 | 🟡 | `cmd:library.inspectLightroom`, `cmd:library.importLightroom`, `cmd:file.importLightroom`, `crates/engine/src/lightroom_catalog.rs`, `crates/ui-egui/src/dialogs/lightroom_destination.rs`, `crates/ui-egui/src/tests/lightroom_destination.rs`, `docs/lightroom-catalog-import.md` | before the import starts, File ▸ Import Lightroom Catalog… asks where the catalog goes: merge into the open library (named, with its photo count; preselected when it is empty) or create a new library (named after the catalog file, next to the open library, both editable), which is made and opened following File ▸ New Library…'s rules before the import; Cancel does nothing; Settings ▸ General ▸ "When importing a Lightroom catalog" (Ask where to import it / Always merge into the open library) or the window's "Don't ask again" turns it off; `file.importLightroom` takes `into` (`open` / `new`), `name`, `location` to choose without the window; a session in memory merges without asking (issue #2672); read-only `.lrcat` plus committed WAL pages (also WAL-only tables with main schema format 0), in-tree read-only Rust SQLite B-tree reader; on-demand main-file pages up to 16 GiB with existing table/record bounds (WAL still capped at 1 GiB, issue #798); background inspection/import with progress/cancellation, per-open library identity checks; persistent result with destination library, offline-original counts and Show in Library, dismissed when switching libraries; offline Local records are promoted without probing missing files; originals in place, ratings/flags/labels, XMP, hierarchical keywords, collection sets/regular collections, virtual copies, mapped develop settings; stable reimport identities, undo, missing-file placeholders, a root folder not found at its recorded path looked up relative to the catalog (Lightroom's `relativePathFromCatalog`, so a project folder copied from another computer stays linked; reported as a warning), existing edits preserved. Best-effort deduplicated recovery archives retain settings/history/snapshots/collection rules (32 MiB each, eight archives/128 MiB aggregate); archive limits/write failures and optional-table limits warn without blocking photo import; unrelated unsupported tables and opaque SQL BLOBs skipped. Custom white balance on relative-WB raws (`RAW` in Lightroom's terms) stays As Shot and is reported, since the catalog keeps no as-shot white to shift from (issue #510). An image whose file, folder or root folder record is missing from the catalog, or whose original path is empty, is skipped with its virtual copies instead of failing the whole import; the report lists them as data (`skipped`: image id and reason) and the result window counts them in the UI language (PR #2230). Adobe rendering, AI data and native history replay remain incomplete; no writes to Lightroom catalogs. Open Library given a Lightroom catalog folder, an `.lrdata` / `.lrcat-data` folder or the `.lrcat` makes no library there and offers this import with the catalog found (`cmd:app.openLibrary`, `crates/engine/src/lightroom_folder.rs`; issue #891) |
| LRC-LIB-CATALOG-LOCK | Catalog open in one program at a time | P1 | ✅ | `cmd:app.openLibrary`, `crates/catalog/src/lock.rs`, `crates/engine/src/library.rs` (`open_library`) | exclusive OS lock on `catalog.lock` for the session (app and `lightcraft-cli --library`); a second opener is refused with who has it (`catalog.lock.owner`: program, process, computer); released by the OS on a crash, so never stale; file systems without locks open unprotected with a warning (the app's notices, `library.info` → `settingsWarnings`, and the CLI's stderr; issue #171); no read-only mode; the browser build (OPFS) has no guard across tabs yet. A library that can't be opened at launch (locked, unreadable, newer format, drive missing) shows a window — Try Again, Choose Another Library…, Continue Without Saving (then a banner; nothing written), Quit — instead of a silent demo session (`crates/ui-egui/src/panels/library_problem.rs`); the lock is released explicitly when the library closes, not by letting its file handle close, so a program another thread is starting at that moment (which holds a copy of every file handle until it is launched) cannot keep the library "already open" for a moment (issue #680) |
- | LRC-LIB-CATALOG-SWITCH | New / Open Recent catalog, catalog name shown | P1 | ✅ | `cmd:app.newLibrary`, `cmd:app.openLibrary`, `cmd:app.recentLibraries`, `cmd:app.clearRecentLibraries`, `crates/ui-egui/src/panels/settings.rs`, `crates/ui-egui/src/panels/left.rs`, `crates/ui-egui/src/panels/library_problem.rs` (`launch_plan`, `show_chooser`), `crates/ui-egui/src/tests_launch_library.rs` | File ▸ New Library… (name, then location), File ▸ Open Recent Library (last 8; missing ones greyed out, dropped when opened; Remove from List ▸ one entry, or `app.recentLibraries {remove}`, which forgets only the path; Clear), the open library's name under My Photos and in the window title (issue #902); Open/New refused during imports and their folder scans; a library that can't be opened leaves the current one and its reference pin intact; a successful switch clears the catalog-local reference pin; ⌘O (Ctrl+O on Windows and Linux) runs Open Library… and asks for a folder once (`crates/ui-egui/src/tests_keymap.rs`: `cmd_o_opens_the_library_picker_once`); a dialog or a text field with the focus keeps the key; Settings ▸ General ▸ At launch: Open the last library (default) or Ask me, a window listing the recent libraries (name, folder, when last opened; missing, unreadable or no-longer-library ones greyed out with the reason, checked read-only — nothing is locked or written, so a library another program has open is reported, with who has it, when Open is pressed; the last one selected; Open, Open Another…, New Library…, Remove from List, Quit; ↑ ↓ Return Esc), also shown once when Alt/Option is held in the first 2 s after the window appears (macOS reports an Option key held since before launch only once it changes); `--library` and `LIGHTCRAFT_LIBRARY` come first and `lightcraft-cli` never asks (issue #1290); a library's `catalog.snap` or folder given at launch (a double-click in the file manager) opens that library, through the usual launch path (lock check), makes it the library in use and is never imported; a second library argument gets a notice |
-| LRC-LIB-CATALOG-SWITCH | New / Open Recent catalog, catalog name shown | P1 | ✅ | `cmd:app.newLibrary`, `cmd:app.openLibrary`, `cmd:app.recentLibraries`, `cmd:app.clearRecentLibraries`, `crates/ui-egui/src/dialogs/settings.rs`, `crates/ui-egui/src/panels/left.rs`, `crates/ui-egui/src/panels/library_problem.rs` (`launch_plan`, `show_chooser`), `crates/ui-egui/src/tests/launch_library.rs` | File ▸ New Library… (name, then location), File ▸ Open Recent Library (last 8; missing ones greyed out, dropped when opened; Remove from List ▸ one entry, or `app.recentLibraries {remove}`, which forgets only the path; Clear), the open library's name under My Photos and in the window title (issue #902); Open/New refused during imports and their folder scans; a library that can't be opened leaves the current one and its reference pin intact; a successful switch clears the catalog-local reference pin; ⌘O (Ctrl+O on Windows and Linux) runs Open Library… and asks for a folder once (`crates/ui-egui/src/tests/keymap.rs`: `cmd_o_opens_the_library_picker_once`); a dialog or a text field with the focus keeps the key; Settings ▸ General ▸ At launch: Open the last library (default) or Ask me, a window listing the recent libraries (name, folder, when last opened; missing, unreadable or no-longer-library ones greyed out with the reason, checked read-only — nothing is locked or written, so a library another program has open is reported, with who has it, when Open is pressed; the last one selected; Open, Open Another…, New Library…, Remove from List, Quit; ↑ ↓ Return Esc), also shown once when Alt/Option is held in the first 2 s after the window appears (macOS reports an Option key held since before launch only once it changes); `--library` and `LIGHTCRAFT_LIBRARY` come first and `lightcraft-cli` never asks (issue #1290) |
++| LRC-LIB-CATALOG-SWITCH | New / Open Recent catalog, catalog name shown | P1 | ✅ | `cmd:app.newLibrary`, `cmd:app.openLibrary`, `cmd:app.recentLibraries`, `cmd:app.clearRecentLibraries`, `crates/ui-egui/src/dialogs/settings.rs`, `crates/ui-egui/src/panels/left.rs`, `crates/ui-egui/src/panels/library_problem.rs` (`launch_plan`, `show_chooser`), `crates/ui-egui/src/tests/launch_library.rs` | File ▸ New Library… (name, then location), File ▸ Open Recent Library (last 8; missing ones greyed out, dropped when opened; Remove from List ▸ one entry, or `app.recentLibraries {remove}`, which forgets only the path; Clear), the open library's name under My Photos and in the window title (issue #902); Open/New refused during imports and their folder scans; a library that can't be opened leaves the current one and its reference pin intact; a successful switch clears the catalog-local reference pin; ⌘O (Ctrl+O on Windows and Linux) runs Open Library… and asks for a folder once (`crates/ui-egui/src/tests/keymap.rs`: `cmd_o_opens_the_library_picker_once`); a dialog or a text field with the focus keeps the key; Settings ▸ General ▸ At launch: Open the last library (default) or Ask me, a window listing the recent libraries (name, folder, when last opened; missing, unreadable or no-longer-library ones greyed out with the reason, checked read-only — nothing is locked or written, so a library another program has open is reported, with who has it, when Open is pressed; the last one selected; Open, Open Another…, New Library…, Remove from List, Quit; ↑ ↓ Return Esc), also shown once when Alt/Option is held in the first 2 s after the window appears (macOS reports an Option key held since before launch only once it changes); `--library` and `LIGHTCRAFT_LIBRARY` come first and `lightcraft-cli` never asks (issue #1290); a library's `catalog.snap` or folder given at launch (a double-click in the file manager) opens that library, through the usual launch path (lock check), makes it the library in use and is never imported; a second library argument gets a notice |
| LRC-LIB-FOLDERS | Disk folder tree | P1 | ✅ | `cmd:library.browse`, `cmd:folder.rename`, `cmd:folder.move`, `crates/ui-egui/src/panels/left.rs` (`local_section`, `folder_tree`) | standard places + the browsed folder + Browse Folder…, each an expandable tree of subfolders, breadcrumb navigation; context menu: Rename Folder…, Move Folder To…, Show in Finder (on disk, photos relinked; one undo step each: undo / redo move the folder back and forth, refused when the destination is taken) |
- | LRC-LIB-LIBFOLDERS | Library folders | P1 | ✅ | `cmd:library.folders`, `cmd:library.source` (`libraryFolder`), `cmd:library.filter` (`libraryFolder`), `cmd:library.removeFolder`, `cmd:folder.rename`, `cmd:folder.move`, `cmd:folder.label`, `cmd:folder.create`, `cmd:photo.moveToFolder`, `cmd:folder.scanChanges`, `cmd:folder.synchronize`, `crates/catalog/src/folders.rs`, `crates/engine/src/sync.rs`, `crates/ui-egui/src/sync.rs`, `crates/ui-egui/src/panels/left.rs` (`folders_section`, `folder_menu_for_library`, `row_menu`), `crates/ui-egui/src/tests_panels.rs` | sidebar Folders: the folders the library's photos were imported from, with photo counts (subfolders included), as another way to explore the library next to By Date and Keywords; Local stays the way to browse any folder on disk. Each disk is a row of its own and starts open: a drive letter, a Windows share (`\\server\share`, `\\?\UNC\…`, `\\wsl$\…`), a macOS share or disk (`/Volumes/tokyo`), a Linux mount (`/media`, `/run/media`, `/mnt`, gvfs `smb-share:…`, `/net/<host>`), NFS (`/Network/Servers/<host>`), else “This Computer” — told apart from the stored paths alone, so an offline share lists like a mounted one and the sidebar never waits on a network. Only folders that hold imported photos are listed (browsed, deleted and demo photos don't count); every folder is a row of its own (`Users` → `me` → `Pictures`), and a folder that holds nothing itself and leads to one folder starts open; every level indents one step more than its parent however deep it goes (16 pt while the deepest open row of any sidebar tree fits the panel with room for its name and count; narrower in bands of 14, 12, 10 and 8 pt when it would not, the same for every tree, chosen from the last frame; issue #2298): past 8 pt the whole sidebar (Albums, Local, By Date, Folders, Keywords) scrolls sideways when its widest row is wider than the panel (rows are measured one frame behind; Create Album and the counts stay at the visible edge); a name that does not fit ends in an ellipsis at the count (the full name on hover; a row asks for room for at most 140 pt of its name, so depth, not one long name, makes the sidebar scroll), as does the grid title; selection and hover bars end at the panel's edge; click makes the folder the source, like an album or a Local folder (its photos and those of the folders inside it fill the grid, titled “photos/travel”; the filter bar narrows it further; `library.source` `libraryFolder` + `path`; kept with the library's view), and its row is always opened into view; the shown folder follows a rename or move and their undo (engine-tested; the sidebar test covers rename), is dropped back to All Photos when it is removed or no longer holds a photo, and a smart album made from the view keeps it, also when its rules are edited (the editor has no folder field). Only a folder that shows exactly its own photos can be shown (not the startup disk, not `/Volumes`-like folders above disks, not an empty one). A row that would cover other disks' photos too (the startup disk, `/Volumes`, `/mnt`…) only opens. Right-click (row or triangle): Rename Folder…, Move Folder To…, New Folder on Disk… (`folder.create`; one undo step, undo removes it while empty), Move Selected Photos Here (`photo.moveToFolder`, also *Move to Folder…* in the photo context menu, and photos dragged from the grid onto a Folders row: the row lights up, the dragged label says “Move 3 photos to “Trip””, a closed folder held under the pointer opens, a row covering several disks and Local photos are refused with the reason, photos already there say so; a drop asks first (“Move 2 photos to “Porto”?”, Don't ask again, Settings → Confirm before moving photos to another folder on disk), and photos that leave the view leave the selection; files and XMP sidecars move, virtual copies follow, across volumes copied (streamed) and verified before the source goes, a name taken in the destination refuses the whole move, one undo step; an undo with the share offline or read-only is refused with the reason and kept until it can run, nothing deleted), Show in Finder (on disk, photos relinked, as in Local), Set Color Label ▸ (the five colours with their custom names, None, Edit Label Names…; `folder.label`, one undo step; the row shows the label's dot before its count and says it with its name; kept in the catalog as a folder record under the folder's identity, so it follows Rename / Move and their undo and redo, the folders inside going along), Synchronize Folder… (the dialog opens at once and scans the folder and the folders inside it on a worker thread — the look for new files beside parallel checks of the library's photos — then offers Import new photos (checked; files only browsed in Local count as new), Relink photos whose file was renamed or moved within the folder (checked; matched by content — a Duplicate's too — or, for a photo with no hash on record such as one from a Lightroom catalog, by file size and dimensions when exactly one file agrees), Remove missing photos from the library (to Recently Deleted) and Read metadata updates from XMP sidecars (saved after the photo came in or was last edited here, and saying something the library doesn't; the sidecar wins), with counts and skipped duplicates / unreadable files; a folder with none of these changes only says the library is up to date with it, with one Close and no choices, and closing it starts no job; `folder.scanChanges` / `folder.synchronize`, which acts on exactly the scan shown — a scan whose folder's photos changed meanwhile is refused and made again in the background — and is one undo step, also with a full history; a folder that isn't there (an unplugged disk) is reported as such, not as every photo missing; a whole disk or a folder holding disks needs `disk: true`; Esc stops the scan; Synchronize hands everything to a worker thread — the import, the checks that moved and missing files are still as found, the sidecar reads — and commits its steps between frames, shown in the activity stack with ✕ to stop, so no file is touched on the UI thread) and Remove from Library… (asks; moves the folder's photos to Recently Deleted, one undo step, no file touched); a disk row (not the startup disk) offers Set Color Label ▸, Synchronize Folder… and Remove Disk from Library… (the command needs `disk: true` for a whole disk or a folder spanning several). Limits: names are compared as written (macOS `/Volumes/tokyo` vs `/Volumes/TOKYO` are two disks; `/Volumes/Macintosh HD/…` and `/…` two rows); no disk capacity / online status; no “include subfolders” switch (a folder always includes the ones inside it); photos can't yet be dragged onto a folder row (use the menus); a name clash on moving photos is refused rather than renamed -1, -2; folders can't be filtered or sorted by label, and a label stays with the old path when the folder is moved outside LightCraft (Find Missing relinks photos, not folder records); Synchronize has no “show import dialog first” or “show missing photos” option, and only knows when a photo came in or was last developed here: a rating, label or metadata change made here (auto-write off) after another app saved the sidecar is listed as an update, and reading it restores the sidecar's older value (reading is never the default); the walk for new files stops when the scan is cancelled, and its depth/entry limits are only logged |
+ | LRC-LIB-LIBFOLDERS | Library folders | P1 | ✅ | `cmd:library.folders`, `cmd:library.source` (`libraryFolder`), `cmd:library.filter` (`libraryFolder`), `cmd:library.removeFolder`, `cmd:folder.rename`, `cmd:folder.move`, `cmd:folder.label`, `cmd:folder.create`, `cmd:photo.moveToFolder`, `cmd:folder.scanChanges`, `cmd:folder.synchronize`, `crates/catalog/src/folders.rs`, `crates/engine/src/sync.rs`, `crates/ui-egui/src/sync.rs`, `crates/ui-egui/src/panels/left.rs` (`folders_section`, `folder_menu_for_library`, `row_menu`), `crates/ui-egui/src/tests/panels.rs` | sidebar Folders: the folders the library's photos were imported from, with photo counts (subfolders included), as another way to explore the library next to By Date and Keywords; Local stays the way to browse any folder on disk. Each disk is a row of its own and starts open: a drive letter, a Windows share (`\\server\share`, `\\?\UNC\…`, `\\wsl$\…`), a macOS share or disk (`/Volumes/tokyo`), a Linux mount (`/media`, `/run/media`, `/mnt`, gvfs `smb-share:…`, `/net/<host>`), NFS (`/Network/Servers/<host>`), else “This Computer” — told apart from the stored paths alone, so an offline share lists like a mounted one and the sidebar never waits on a network. Only folders that hold imported photos are listed (browsed, deleted and demo photos don't count); every folder is a row of its own (`Users` → `me` → `Pictures`), and a folder that holds nothing itself and leads to one folder starts open; every level indents one step more than its parent however deep it goes (16 pt while the deepest open row of any sidebar tree fits the panel with room for its name and count; narrower in bands of 14, 12, 10 and 8 pt when it would not, the same for every tree, chosen from the last frame; issue #2298): past 8 pt the whole sidebar (Albums, Local, By Date, Folders, Keywords) scrolls sideways when its widest row is wider than the panel (rows are measured one frame behind; Create Album and the counts stay at the visible edge); a name that does not fit ends in an ellipsis at the count (the full name on hover; a row asks for room for at most 140 pt of its name, so depth, not one long name, makes the sidebar scroll), as does the grid title; selection and hover bars end at the panel's edge; click makes the folder the source, like an album or a Local folder (its photos and those of the folders inside it fill the grid, titled “photos/travel”; the filter bar narrows it further; `library.source` `libraryFolder` + `path`; kept with the library's view), and its row is always opened into view; the shown folder follows a rename or move and their undo (engine-tested; the sidebar test covers rename), is dropped back to All Photos when it is removed or no longer holds a photo, and a smart album made from the view keeps it, also when its rules are edited (the editor has no folder field). Only a folder that shows exactly its own photos can be shown (not the startup disk, not `/Volumes`-like folders above disks, not an empty one). A row that would cover other disks' photos too (the startup disk, `/Volumes`, `/mnt`…) only opens. Right-click (row or triangle): Rename Folder…, Move Folder To…, New Folder on Disk… (`folder.create`; one undo step, undo removes it while empty), Move Selected Photos Here (`photo.moveToFolder`, also *Move to Folder…* in the photo context menu, and photos dragged from the grid onto a Folders row: the row lights up, the dragged label says “Move 3 photos to “Trip””, a closed folder held under the pointer opens, a row covering several disks and Local photos are refused with the reason, photos already there say so; a drop asks first (“Move 2 photos to “Porto”?”, Don't ask again, Settings → Confirm before moving photos to another folder on disk), and photos that leave the view leave the selection; files and XMP sidecars move, virtual copies follow, across volumes copied (streamed) and verified before the source goes, a name taken in the destination refuses the whole move, one undo step; an undo with the share offline or read-only is refused with the reason and kept until it can run, nothing deleted), Show in Finder (on disk, photos relinked, as in Local), Set Color Label ▸ (the five colours with their custom names, None, Edit Label Names…; `folder.label`, one undo step; the row shows the label's dot before its count and says it with its name; kept in the catalog as a folder record under the folder's identity, so it follows Rename / Move and their undo and redo, the folders inside going along), Synchronize Folder… (the dialog opens at once and scans the folder and the folders inside it on a worker thread — the look for new files beside parallel checks of the library's photos — then offers Import new photos (checked; files only browsed in Local count as new), Relink photos whose file was renamed or moved within the folder (checked; matched by content — a Duplicate's too — or, for a photo with no hash on record such as one from a Lightroom catalog, by file size and dimensions when exactly one file agrees), Remove missing photos from the library (to Recently Deleted) and Read metadata updates from XMP sidecars (saved after the photo came in or was last edited here, and saying something the library doesn't; the sidecar wins), with counts and skipped duplicates / unreadable files; a folder with none of these changes only says the library is up to date with it, with one Close and no choices, and closing it starts no job; `folder.scanChanges` / `folder.synchronize`, which acts on exactly the scan shown — a scan whose folder's photos changed meanwhile is refused and made again in the background — and is one undo step, also with a full history; a folder that isn't there (an unplugged disk) is reported as such, not as every photo missing; a whole disk or a folder holding disks needs `disk: true`; Esc stops the scan; Synchronize hands everything to a worker thread — the import, the checks that moved and missing files are still as found, the sidecar reads — and commits its steps between frames, shown in the activity stack with ✕ to stop, so no file is touched on the UI thread) and Remove from Library… (asks; moves the folder's photos to Recently Deleted, one undo step, no file touched); a disk row (not the startup disk) offers Set Color Label ▸, Synchronize Folder… and Remove Disk from Library… (the command needs `disk: true` for a whole disk or a folder spanning several). Limits: names are compared as written (macOS `/Volumes/tokyo` vs `/Volumes/TOKYO` are two disks; `/Volumes/Macintosh HD/…` and `/…` two rows); no disk capacity / online status; no “include subfolders” switch (a folder always includes the ones inside it); photos can't yet be dragged onto a folder row (use the menus); a name clash on moving photos is refused rather than renamed -1, -2; folders can't be filtered or sorted by label, and a label stays with the old path when the folder is moved outside LightCraft (Find Missing relinks photos, not folder records); Synchronize has no “show import dialog first” or “show missing photos” option, and only knows when a photo came in or was last developed here: a rating, label or metadata change made here (auto-write off) after another app saved the sidecar is listed as an update, and reading it restores the sidecar's older value (reading is never the default); the walk for new files stops when the scan is cancelled, and its depth/entry limits are only logged |
| LRC-LIB-COLLECTIONS | Collections & sets | P1 | ✅ | `cmd:album.create`, `cmd:album.createSmart`, `cmd:album.toggleTarget`, `cmd:album.setTarget`, `cmd:album.clearQuick` | albums + folders (sets), smart albums (rule editor; rules incl. File Path — the whole string, either separator, case-insensitive), Quick Collection and target album (B in the grids adds / removes the selection; album menu ▸ Set as Target Album; the target is marked +) |
- | LRC-LIB-SMARTCOLL | Smart-collection rules | P1 | ✅ | `cmd:album.createSmart`, `cmd:album.setRules`, `cmd:album.ruleFields`, `cmd:dialog.smartAlbum`, `crates/catalog/src/rules.rs`, `crates/ui-egui/src/panels/rules_editor.rs` | rule editor: match all / any / none, nested groups (⌥+ or + Group), 47 fields. The field menu shows Rating, Pick Flag, Color Label and Any Searchable Text, then one submenu per group (`FIELD_GROUPS`; `album.ruleFields` reports each field's `group`): Source (album — a plain or a smart album, so one smart album can include or exclude another; a rule that would make an album include itself, directly or through others, is refused, and a loop saved anyway can't recurse: inside it, the album being evaluated counts as holding no photos, so an "isn't" rule on it matches every photo, and the sidebar marks it ⚠ —, virtual copy, copy name, in a stack), File (filename, extension, file path, type, format, video duration), Date (capture / import / edit), Keywords & People (keywords, keyword count, people on named faces, people count), Description (title, caption, alt text, creator, copyright, copyright status), Camera Info (camera, lens, focal length, aperture, shutter speed as 1/250, ISO), Location (any, city, state / province, country, GPS), Size (long / short edge, aspect ratio and megapixels, all of the photo as shown: oriented and cropped), Develop (has edits, cropped, treatment), Assisted Culling (focus, best of similar shots); text / number / date / in-the-last operators; live match count; also usable as a library filter (`ruleSet`). Missing vs Classic: develop preset, flash, exposure bias, camera serial, colour profile / bit depth, IPTC Job, smart-preview status. Choice values read as words in every language (Public Domain, Black & White; `album.ruleFields` gives `choiceLabels`), while rules store the ids; yes/no fields read Yes / No and take `true`/`false`, `"yes"`/`"no"`, `"true"`/`"false"` or 1/0. Every value is checked against its field (`RuleSet::check`): numbers (rating 0–5), shutter speeds, dates (`2026`, `2026-08`, `2026-08-14`, then `T10`, `T10:00` or `T10:00:00`, a space working as the `T`, and after whole seconds a fraction and a time zone as imported capture times carry them (`.250+02:00`); no 30 February; `rules::rule_date` is the one reading for the check and the matcher; each date field has a calendar picker, `crates/ui-egui/src/date_picker.rs`, that picks a year, a month or a day and keeps a "between" in order), between = two bounds in order, in the last = more than 0 of a known unit, choices (ids, the flag's picked / rejected, a colour label's custom name), text with something to look for, an existing album (plain or smart, not a folder), no empty groups; each problem names its rule (`rule 2.1: no rating 0–5 is 9`), and album.createSmart / setRules / library.filter refuse them. The editor marks each bad rule under its row (inside groups too), keeps OK disabled until they are fixed (and its confirm refuses them before renaming anything), picks an Album rule's album with an album picker (`crates/ui-egui/src/album_picker.rs`: the sidebar's tree with folders, or type part of a name or folder; ↑ / ↓ / Enter; albums that can't be picked shown greyed with the reason) (is / isn't; a folder can't be tested), and drawing it never changes a rule: a rating of 9, "in the last 0 days" or 20,000 days, a "between" that isn't a pair all stay as stored (and are marked where they can't match) until edited. Album rules saved with an old operator (≥, between) are read as the "isn't" they always meant (`RuleSet::upgrade`). Saved smart albums whose rules no longer check are marked ⚠ in the sidebar (tooltip: what to fix; `albums.list` `problems`, `Catalog::smart_album_problems`); the name and rules of an album are saved as one undo step (`album.setRules` `name`). Problems read as the field's name and the issue in the editor's language (“Titel: braucht einen Suchbegriff”; `Problem::issue` / `field`, `Issue::text`, translated in every locale), while commands keep the English `rule 2.1: …` message for agents |
+ | LRC-LIB-SMARTCOLL | Smart-collection rules | P1 | ✅ | `cmd:album.createSmart`, `cmd:album.setRules`, `cmd:album.ruleFields`, `cmd:dialog.smartAlbum`, `crates/catalog/src/rules.rs`, `crates/ui-egui/src/dialogs/rules_editor.rs` | rule editor: match all / any / none, nested groups (⌥+ or + Group), 47 fields. The field menu shows Rating, Pick Flag, Color Label and Any Searchable Text, then one submenu per group (`FIELD_GROUPS`; `album.ruleFields` reports each field's `group`): Source (album — a plain or a smart album, so one smart album can include or exclude another; a rule that would make an album include itself, directly or through others, is refused, and a loop saved anyway can't recurse: inside it, the album being evaluated counts as holding no photos, so an "isn't" rule on it matches every photo, and the sidebar marks it ⚠ —, virtual copy, copy name, in a stack), File (filename, extension, file path, type, format, video duration), Date (capture / import / edit), Keywords & People (keywords, keyword count, people on named faces, people count), Description (title, caption, alt text, creator, copyright, copyright status), Camera Info (camera, lens, focal length, aperture, shutter speed as 1/250, ISO), Location (any, city, state / province, country, GPS), Size (long / short edge, aspect ratio and megapixels, all of the photo as shown: oriented and cropped), Develop (has edits, cropped, treatment), Assisted Culling (focus, best of similar shots); text / number / date / in-the-last operators; live match count; also usable as a library filter (`ruleSet`). Missing vs Classic: develop preset, flash, exposure bias, camera serial, colour profile / bit depth, IPTC Job, smart-preview status. Choice values read as words in every language (Public Domain, Black & White; `album.ruleFields` gives `choiceLabels`), while rules store the ids; yes/no fields read Yes / No and take `true`/`false`, `"yes"`/`"no"`, `"true"`/`"false"` or 1/0. Every value is checked against its field (`RuleSet::check`): numbers (rating 0–5), shutter speeds, dates (`2026`, `2026-08`, `2026-08-14`, then `T10`, `T10:00` or `T10:00:00`, a space working as the `T`, and after whole seconds a fraction and a time zone as imported capture times carry them (`.250+02:00`); no 30 February; `rules::rule_date` is the one reading for the check and the matcher; each date field has a calendar picker, `crates/ui-egui/src/widgets/date_picker.rs`, that picks a year, a month or a day and keeps a "between" in order), between = two bounds in order, in the last = more than 0 of a known unit, choices (ids, the flag's picked / rejected, a colour label's custom name), text with something to look for, an existing album (plain or smart, not a folder), no empty groups; each problem names its rule (`rule 2.1: no rating 0–5 is 9`), and album.createSmart / setRules / library.filter refuse them. The editor marks each bad rule under its row (inside groups too), keeps OK disabled until they are fixed (and its confirm refuses them before renaming anything), picks an Album rule's album with an album picker (`crates/ui-egui/src/widgets/album_picker.rs`: the sidebar's tree with folders, or type part of a name or folder; ↑ / ↓ / Enter; albums that can't be picked shown greyed with the reason) (is / isn't; a folder can't be tested), and drawing it never changes a rule: a rating of 9, "in the last 0 days" or 20,000 days, a "between" that isn't a pair all stay as stored (and are marked where they can't match) until edited. Album rules saved with an old operator (≥, between) are read as the "isn't" they always meant (`RuleSet::upgrade`). Saved smart albums whose rules no longer check are marked ⚠ in the sidebar (tooltip: what to fix; `albums.list` `problems`, `Catalog::smart_album_problems`); the name and rules of an album are saved as one undo step (`album.setRules` `name`). Problems read as the field's name and the issue in the editor's language (“Titel: braucht einen Suchbegriff”; `Problem::issue` / `field`, `Issue::text`, translated in every locale), while commands keep the English `rule 2.1: …` message for agents |
| LRC-LIB-PUBLISH | Publish services | P2 | ⬜ | | |
| LRC-LIB-FILTERBAR | Library filter bar | P1 | ✅ | `cmd:view.filterBar`, `cmd:filter.applyPreset`, `cmd:library.filter` (`labels`, `ruleSet`), `crates/ui-egui/src/panels/filterbar.rs` | rating/flag/label (several labels at once = any of them)/kind/edited/camera/lens/keyword, clear, save as smart album, filter presets; the filter stays as you change albums (an album the filter held is replaced by the album you show; always locked, as in the desktop app); arbitrary conditions via the smart-album rule editor |
| LRC-LIB-STACKS | Stacks (full) | P1 | ✅ | `crates/catalog/src/stacks.rs`, `cmd:stack.group`, `cmd:stack.split`, `cmd:stack.moveUp`, `cmd:stack.moveDown` | group / ungroup / toggle / set top / remove / auto by time / split / move up and down |