diff --git a/Cargo.lock b/Cargo.lock index 970af35b65..e0ff3c9eac 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5172,6 +5172,58 @@ version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +[[package]] +name = "jiff" +version = "0.2.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "175dc66334db3b9ab9985bf8b61cfed50dc16d20964bb47f9e479adcae984a7f" +dependencies = [ + "jiff-core", + "jiff-static", + "jiff-tzdb-platform", + "log", + "portable-atomic", + "portable-atomic-util", + "serde_core", + "windows-link", +] + +[[package]] +name = "jiff-core" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e599b80292e597019b8b3e392de3f4bea2959ddfb8c7dff60e035e9e311a2c1b" +dependencies = [ + "log", +] + +[[package]] +name = "jiff-static" +version = "0.2.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7b1af7547d47354bc438d797e3854601bde8f8d185780c5ba4ab27afa54f1ba" +dependencies = [ + "jiff-core", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "jiff-tzdb" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0980fca2cc272465bd60e82397607ba9f33add9e48defd77923301bbd03808f2" + +[[package]] +name = "jiff-tzdb-platform" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "875a5a69ac2bab1a891711cf5eccbec1ce0341ea805560dcd90b7a2e925132e8" +dependencies = [ + "jiff-tzdb", +] + [[package]] name = "jixel" version = "0.3.4" @@ -5775,6 +5827,7 @@ dependencies = [ "crc32fast", "fs4", "harfrust 0.13.3", + "jiff", "libc", "lightcraft-catalog", "lightcraft-codecs", @@ -5864,6 +5917,7 @@ name = "lightcraft-gpu" version = "0.21.1" dependencies = [ "bytemuck", + "candle-core", "lightcraft-color", "lightcraft-denoise", "lightcraft-develop", @@ -5873,6 +5927,7 @@ dependencies = [ "lightcraft-raster", "lightcraft-raw", "lightcraft-scenes", + "lightcraft-segment", "lightcraft-testkit", "log", "pollster 1.0.1", diff --git a/Cargo.toml b/Cargo.toml index 7957026351..a87448270f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -101,6 +101,12 @@ libm = "0.2" # pure-Rust maths for lightcraft-film (target-independent results) libc = "0.2" # dev-only: process CPU time in benches dhat = "0.3" # opt-in heap profiling (lightcraft-cli --features dhat-heap) and heap tests; never in product builds +# The host's time zone: the catalog stores local civil times, so a file's modification time and +# the session clock need the UTC offset in force at that instant (DST included). Native only; the +# web build keeps its fixed clock. Zero dependencies on Unix (it reads the system tzdb); on Windows +# it embeds one, since Windows has no canonical copy. +jiff = { version = "0.2", default-features = false, features = ["std", "tz-system", "tzdb-zoneinfo", "tzdb-bundle-platform"] } + # formats miniz_oxide = "0.9" @@ -129,7 +135,7 @@ muda = { version = "0.21", default-features = false } # native menu bar (macOS: # macOS: the profile of the screen showing the window (safe AppKit bindings; muda and wgpu use the same) objc2 = { version = "0.6", default-features = false, features = ["std"] } objc2-app-kit = { version = "0.3.2", default-features = false, features = ["std", "NSApplication", "NSAccessibility", "NSColorSpace", "NSResponder", "NSScreen", "NSWindow", "NSWorkspace"] } -objc2-foundation = { version = "0.3", default-features = false, features = ["std", "NSArray", "NSData"] } +objc2-foundation = { version = "0.3", default-features = false, features = ["std", "NSArray", "NSData", "NSString", "NSUserDefaults"] } # Linux: the desktop's dark/light setting from the XDG settings portal (Settings ▸ Interface ▸ # Appearance Mode ▸ Auto). Pure Rust; the version accesskit already brings in, pinned to it. zbus = "=5.19.0" diff --git a/NOTICE b/NOTICE index 91f6e9e055..2a7431a0d3 100644 --- a/NOTICE +++ b/NOTICE @@ -62,8 +62,8 @@ BIZ UDPGothic Regular, Noto Sans Thai Regular, Noto Sans Georgian Regular and No Regular, and loads Noto Sans CJK SC separately. Release packages include each font's licence as OFL-.txt; Windows installers include their texts in FONT-LICENCES.txt. -Place names for reverse geocoding (Photo > Fill Location from GPS) are not part of LightCraft and -are never distributed with it. On the user's request (Photo > Download Place Names) the app +Place names for reverse geocoding (Photo > Metadata > Fill Location from GPS) are not part of LightCraft and +are never distributed with it. On the user's request (Photo > Metadata > Download Place Names) the app downloads cities15000.zip, admin1CodesASCII.txt and countryInfo.txt from GeoNames (https://download.geonames.org/export/dump/) into the settings folder. GeoNames data is licensed under Creative Commons Attribution 4.0 (https://creativecommons.org/licenses/by/4.0/); diff --git a/apps/lightcraft-cli/src/main.rs b/apps/lightcraft-cli/src/main.rs index eeeafaa7f1..4c569062a3 100644 --- a/apps/lightcraft-cli/src/main.rs +++ b/apps/lightcraft-cli/src/main.rs @@ -298,8 +298,11 @@ fn calibrate(args: &[String]) -> Result<(), String> { let result = std::fs::read(path).map_err(|e| e.to_string()).and_then(|bytes| pool.add(&bytes)); let n = done.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1; match result { - Ok(Some(model)) => eprintln!("[{n}/{}] {} ({model})", files.len(), path.display()), - Ok(None) => eprintln!("[{n}/{}] {}: skipped (no usable camera JPEG or colour)", files.len(), path.display()), + Ok(Some(added)) if added.colour => eprintln!("[{n}/{}] {} ({})", files.len(), path.display(), added.model), + Ok(Some(added)) => { + eprintln!("[{n}/{}] {} ({}, tone only: too dark or colourless)", files.len(), path.display(), added.model) + } + Ok(None) => eprintln!("[{n}/{}] {}: skipped (no usable or a black-and-white camera JPEG)", files.len(), path.display()), Err(e) => eprintln!("[{n}/{}] {}: {e}", files.len(), path.display()), } } @@ -319,11 +322,12 @@ fn calibrate(args: &[String]) -> Result<(), String> { Ok(profile) => { let path = lightcraft_engine::camera_profiles::save(&profile, &dir)?; println!( - "{}: {} photos, {} colour pairs, hue/saturation table {} → {}", + "{}: {} photos, {} colour pairs, hue/saturation table {}, tone curve {} → {}", profile.model, profile.files, profile.samples, profile.hue_sat.is_some(), + profile.tone.is_some(), path.display() ); written += 1; diff --git a/apps/lightcraft-web/src/files.rs b/apps/lightcraft-web/src/files.rs index 9cd934ce57..4712e2c83e 100644 --- a/apps/lightcraft-web/src/files.rs +++ b/apps/lightcraft-web/src/files.rs @@ -190,6 +190,10 @@ impl Store for FilesStore { self.0.truncate(name, len as usize); Ok(()) } + /// The browser always runs the newest build, and its storage is small. + fn keeps_replaced_formats(&self) -> bool { + false + } fn describe(&self) -> String { "browser storage".into() } diff --git a/apps/lightcraft-web/src/wire.rs b/apps/lightcraft-web/src/wire.rs index 9854798673..16802032bd 100644 --- a/apps/lightcraft-web/src/wire.rs +++ b/apps/lightcraft-web/src/wire.rs @@ -132,6 +132,7 @@ impl WireJob { proof: None, window: self.window.map(|[x, y, w, h]| lightcraft_engine::pipeline::PixelWindow { x, y, w, h }), display: None, + downscale: lightcraft_engine::pipeline::Downscale::Smooth, } } diff --git a/apps/lightcraft/src/appkit_defaults.rs b/apps/lightcraft/src/appkit_defaults.rs new file mode 100644 index 0000000000..b2df33a113 --- /dev/null +++ b/apps/lightcraft/src/appkit_defaults.rs @@ -0,0 +1,58 @@ +//! Menu rows AppKit adds to the menu bar by itself, switched off through the app's user defaults +//! (macOS). +//! +//! AppKit puts "Send Feedback" at the top of the Help menu for every app (Feedback +//! Assistant's entry), beside LightCraft's own Help ▸ Send Feedback…. Setting `NSShowFeedbackMenu` +//! to `false` removes it (read on macOS 27 from the app's menu bar). AppKit reads the default when +//! it builds the menus, so it is set before the menu bar exists. +//! +//! The value is written to the app's preferences (the safe `setBool:forKey:`; registering it only +//! for the process takes `unsafe`, which this crate forbids) and written again at every start, +//! except in a `--memory` session, which writes nothing (issue #164); a run with +//! `LIGHTCRAFT_NO_PREFS` still writes it. + +use objc2_foundation::{NSString, NSUserDefaults}; + +/// The user defaults that stop AppKit adding a row, each set to `false`. +const OFF: &[&str] = &["NSShowFeedbackMenu"]; + +/// Writes [`OFF`] into `defaults`. +fn switch_off(defaults: &NSUserDefaults) { + for key in OFF { + defaults.setBool_forKey(false, &NSString::from_str(key)); + } +} + +/// Switches off the rows in [`OFF`] for this app. Call before the menu bar is installed. +pub fn install() { + switch_off(&NSUserDefaults::standardUserDefaults()); +} + +#[cfg(test)] +mod tests { + use super::*; + use objc2::AllocAnyThread; + + /// Removes the throwaway domain, also when an assertion fails. + struct Domain(objc2::rc::Retained, objc2::rc::Retained); + impl Drop for Domain { + fn drop(&mut self) { + self.1.removePersistentDomainForName(&self.0); + } + } + + #[test] + fn the_system_feedback_row_is_switched_off() { + // a throwaway domain: the test never touches the real preferences of the app + let suite = NSString::from_str(&format!("com.storytold.lightcraft.test.appkit-defaults.{}", std::process::id())); + let defaults = NSUserDefaults::initWithSuiteName(NSUserDefaults::alloc(), Some(&suite)).expect("a test domain"); + let _domain = Domain(suite, defaults.clone()); + let key = NSString::from_str("NSShowFeedbackMenu"); + // the row shows while the default is on (AppKit registers `true`, measured); set it so the + // test doesn't depend on the developer's own defaults + defaults.setBool_forKey(true, &key); + assert!(defaults.boolForKey(&key), "the row shows until the default says otherwise"); + switch_off(&defaults); + assert!(!defaults.boolForKey(&key), "AppKit's Send Feedback row is off"); + } +} diff --git a/apps/lightcraft/src/main.rs b/apps/lightcraft/src/main.rs index 3fa12125bb..3a46f8f3e8 100644 --- a/apps/lightcraft/src/main.rs +++ b/apps/lightcraft/src/main.rs @@ -26,6 +26,8 @@ mod alloc_release; mod appearance; +#[cfg(target_os = "macos")] +mod appkit_defaults; #[cfg(test)] mod build_channel; mod build_flavor; @@ -74,7 +76,7 @@ use launch::{ }; #[cfg(test)] use platform::{explorer_select_arg, explorer_select_command, windows_open_url_command}; -use prefs::{PrefsWriter, as_remembered, load_prefs, prefs_path}; +use prefs::{MAXIMIZE_LATER, PrefsWriter, as_remembered, load_prefs, prefs_path}; #[cfg(test)] use prefs::{load_prefs_at, write_atomic}; use session::{open_session, services}; @@ -270,6 +272,20 @@ impl eframe::App for App { /// a second; anything slower gives way to quitting. const EXIT_WAIT: std::time::Duration = std::time::Duration::from_secs(2); +/// Import files passed on the command line once the library is open. Preserve an explicit Detail +/// startup view; Grid and Last keep the existing Photo Grid launch behavior. +fn start_launch_files(app: &mut LightcraftApp, files: Vec) { + if files.is_empty() { + return; + } + if let Err(e) = lightcraft_ui_egui::import::start_paths(app, files) { + log::warn!("import at launch: {e}"); + } + if app.ui.settings.startup_view != lightcraft_ui_egui::state::StartupView::Detail { + app.ui.view = lightcraft_ui_egui::state::ViewMode::PhotoGrid; + } +} + /// The nightly Windows taskbar/Start identity, before any window or COM service exists. fn initialize_nightly_process_identity() -> Result<(), process_identity::IdentityError> { process_identity::initialize( @@ -483,6 +499,12 @@ fn main() -> eframe::Result { None => logger.no_file(), } } + // before the menu bar exists, after the arguments: AppKit reads these defaults when it builds + // its menus, and `--version` / `--help` / a --memory session (issue #164) write nothing + #[cfg(target_os = "macos")] + if !in_memory { + appkit_defaults::install(); + } // what the arguments name, resolved now: an empty or relative argument never becomes a drive // root, and a whole drive or home folder is not walked (issue #374) let LaunchArgs { files, library: launch_library, notices: launch_notices } = launch_imports(&files); @@ -543,7 +565,7 @@ fn main() -> eframe::Result { let opens_as = prefs.as_ref().and_then(|ui| ui.window).and_then(lightcraft_ui_egui::window_place::WindowPlace::checked); let options = eframe::NativeOptions { renderer, - viewport: as_remembered(egui::ViewportBuilder::default().with_title(lightcraft_ui_egui::channel::name()), opens_as) + viewport: as_remembered(egui::ViewportBuilder::default().with_title(lightcraft_ui_egui::channel::name()), opens_as, MAXIMIZE_LATER) .with_min_inner_size(lightcraft_ui_egui::window_place::MIN_SIZE) .with_drag_and_drop(true) .with_transparent(window_gpu::composes_window(compose_window, window_renderer)) @@ -629,6 +651,10 @@ fn main() -> eframe::Result { written: serde_json::to_vec_pretty(&app.ui).unwrap_or_default(), library: app.ui.settings.library_path.clone(), keep_file: keep_prefs_file, + start: Some( + lightcraft_ui_egui::window_place::StartPlace::new(MAXIMIZE_LATER && opens_as.is_some_and(|w| w.zoomed)) + .remembered(opens_as.map(|w| w.size)), + ), ..Default::default() }; // a library opened from its catalog file is the one in use from now on, as Open Library makes it @@ -662,10 +688,7 @@ fn main() -> eframe::Result { // listed and read on the import worker once the window shows (issue #374: never // here, before the first frame, where a large folder kept the window from // appearing) - if let Err(e) = lightcraft_ui_egui::import::start_paths(&mut app, files) { - log::warn!("import at launch: {e}"); - } - app.ui.view = lightcraft_ui_egui::state::ViewMode::PhotoGrid; + start_launch_files(&mut app, files); } // native menu bar generated from the command registry (macOS; elsewhere the menus are // drawn in the window's top bar). LIGHTCRAFT_NO_NATIVE_MENU=1 keeps the in-window menus. diff --git a/apps/lightcraft/src/prefs.rs b/apps/lightcraft/src/prefs.rs index ba9396d36d..8c3a1859b8 100644 --- a/apps/lightcraft/src/prefs.rs +++ b/apps/lightcraft/src/prefs.rs @@ -24,13 +24,24 @@ pub(crate) fn config_dir() -> Option { /// The window at the size it was last used at, zoomed if it was (`window`), or at the usual size /// when nothing is remembered. A zoomed window is given the size it goes back to. Where it /// opens is the system's to say. -pub(crate) fn as_remembered(builder: egui::ViewportBuilder, window: Option) -> egui::ViewportBuilder { +/// +/// Windows: a window built maximized could open covering half the screen while +/// the system took it for maximized, so there (`maximize_later`) it is built at its size and +/// maximized once it shows ([`lightcraft_ui_egui::window_place::StartPlace`]). +pub(crate) fn as_remembered( + builder: egui::ViewportBuilder, + window: Option, + maximize_later: bool, +) -> egui::ViewportBuilder { let builder = builder.with_inner_size(window.map_or(lightcraft_ui_egui::window_place::DEFAULT_SIZE, |w| w.size)); // (only ever asked to zoom: asked not to, macOS un-zooms a window whose size fills the screen // to a size of its own choosing) - if window.is_some_and(|w| w.zoomed) { builder.with_maximized(true) } else { builder } + if window.is_some_and(|w| w.zoomed) && !maximize_later { builder.with_maximized(true) } else { builder } } +/// Windows maximizes a remembered maximized window once it shows (see [`as_remembered`]). +pub(crate) const MAXIMIZE_LATER: bool = cfg!(target_os = "windows"); + /// `/ui.json`, the saved UI state and app settings — `None` when nothing is read or /// written: `LIGHTCRAFT_NO_PREFS` (tests, scripts) or no home folder. pub(crate) fn prefs_path() -> Option { @@ -161,6 +172,9 @@ pub(crate) struct PrefsWriter { /// When the window was first looked at: its watch goes by the clock from then on, not by /// the interface's time, which stands still while the window is hidden. pub(crate) window_since: Option, + /// The window as it first shows: maximized then on Windows, fitted to a smaller screen. + /// `None` once done, and in tests. + pub(crate) start: Option, } impl PrefsWriter { @@ -221,7 +235,24 @@ impl PrefsWriter { // `run_logic` pass has no fresh content rect: keep the last known placement. let remembered = app.ui.window.and_then(lightcraft_ui_egui::window_place::WindowPlace::checked); let at = self.window_since.get_or_insert_with(std::time::Instant::now).elapsed().as_secs_f64(); - if !hidden { + // (while the window is being placed it is not remembered: it may not be as it will be; a + // hidden pass's stale size places nothing) + let placing = self.start.is_some(); + if let Some(start) = &mut self.start { + if !hidden { + for command in start.step(&seen, at, zoom) { + ctx.send_viewport_cmd(command); + } + } else { + // (hidden: nothing to place by, but the time limit still runs) + start.idle(at); + } + match start.waits() { + Some(wait) => ctx.request_repaint_after(wait), + None => self.start = None, + } + } + if !hidden && !placing { app.ui.window = self.window.note(remembered, &seen, at); } if let Some(wait) = self.window.waits(at) { diff --git a/apps/lightcraft/src/tests.rs b/apps/lightcraft/src/tests.rs index 0e56a1efaa..4aaf8b43a7 100644 --- a/apps/lightcraft/src/tests.rs +++ b/apps/lightcraft/src/tests.rs @@ -54,6 +54,126 @@ fn dir(tag: &str) -> std::path::PathBuf { d } +fn startup_headless( + tag: &str, + startup_view: lightcraft_ui_egui::state::StartupView, + seed_demo: bool, +) -> (std::path::PathBuf, lightcraft_ui_egui::headless::Headless) { + let root = dir(tag); + let mut session = Session::new().with_fs(); + session.open_library(root.join("library"), seed_demo).unwrap(); + let mut app = LightcraftApp::new(session, Services::default()); + let mut ui = UiState::default(); + ui.settings.startup_view = startup_view; + app.ui = ui.sanitized(); + (root, lightcraft_ui_egui::headless::Headless::new(app, [1000.0, 700.0], 1.0)) +} + +fn startup_png(path: &std::path::Path, seed: u8) -> Vec { + let image = lightcraft_raster::Rgba8 { width: 8, height: 8, data: vec![[seed, 40, 90, 255]; 64] }; + let bytes = lightcraft_codecs::encode_png(&lightcraft_codecs::EncodeImage::rgba8(&image), &lightcraft_codecs::EncodeMeta::default()).unwrap(); + std::fs::write(path, &bytes).unwrap(); + bytes +} + +fn start_launch_photo(h: &mut lightcraft_ui_egui::headless::Headless, path: &std::path::Path) { + start_launch_files(&mut h.app, vec![path.to_string_lossy().into_owned()]); + assert!(h.settle(std::time::Duration::from_secs(30)), "launch import did not settle"); + assert!(h.app.import.is_none(), "launch import completed"); +} + +fn assert_launch_photo(h: &lightcraft_ui_egui::headless::Headless, name: &str) -> u64 { + let id = h.app.session.selection.active.expect("launch import selects a photo"); + let photo = h.app.session.catalog.photo(id).expect("selected photo is in the catalog"); + assert_eq!(photo.file_name, name); + id.0 +} + +#[test] +fn startup_view_detail_with_new_file() { + use lightcraft_ui_egui::state::{StartupView, ViewMode}; + let (root, mut h) = startup_headless("startup-detail-new", StartupView::Detail, false); + let file = root.join("new.png"); + let original = startup_png(&file, 25); + + start_launch_photo(&mut h, &file); + + assert_eq!(h.app.ui.view, ViewMode::Detail); + assert_eq!(h.app.session.catalog.photos().count(), 1); + assert_launch_photo(&h, "new.png"); + assert_eq!(std::fs::read(&file).unwrap(), original); + drop(h); + let _ = std::fs::remove_dir_all(root); +} + +#[test] +fn startup_view_detail_with_existing_file() { + use lightcraft_ui_egui::state::{StartupView, ViewMode}; + let (root, mut h) = startup_headless("startup-detail-existing", StartupView::Grid, false); + let file = root.join("existing.png"); + let original = startup_png(&file, 75); + start_launch_photo(&mut h, &file); + let original_id = assert_launch_photo(&h, "existing.png"); + + let mut ui = h.app.ui.clone(); + ui.settings.startup_view = StartupView::Detail; + h.app.ui = ui.sanitized(); + start_launch_photo(&mut h, &file); + + assert_eq!(h.app.ui.view, ViewMode::Detail); + assert_eq!(h.app.session.catalog.photos().count(), 1, "an existing launch argument is not duplicated"); + assert_eq!(assert_launch_photo(&h, "existing.png"), original_id); + assert_eq!(std::fs::read(&file).unwrap(), original); + drop(h); + let _ = std::fs::remove_dir_all(root); +} + +#[test] +fn startup_view_grid_with_file() { + use lightcraft_ui_egui::state::{StartupView, ViewMode}; + let (root, mut h) = startup_headless("startup-grid-file", StartupView::Grid, false); + let file = root.join("grid.png"); + let original = startup_png(&file, 120); + + start_launch_photo(&mut h, &file); + + assert_eq!(h.app.ui.view, ViewMode::PhotoGrid); + assert_eq!(h.app.session.catalog.photos().count(), 1); + assert_launch_photo(&h, "grid.png"); + assert_eq!(std::fs::read(&file).unwrap(), original); + drop(h); + let _ = std::fs::remove_dir_all(root); +} + +#[test] +fn startup_view_without_files_preserves_preferences() { + use lightcraft_ui_egui::state::{StartupView, ViewMode}; + let (root, mut h) = startup_headless("startup-no-files", StartupView::Detail, true); + assert!(h.app.session.catalog.photos().count() > 0, "the launch library is populated"); + start_launch_files(&mut h.app, Vec::new()); + assert!(h.app.import.is_none()); + assert_eq!(h.app.ui.view, ViewMode::Detail); + drop(h); + let _ = std::fs::remove_dir_all(root); +} + +#[test] +fn startup_view_last_with_files_preserves_current_policy() { + use lightcraft_ui_egui::state::{StartupView, ViewMode}; + let (root, mut h) = startup_headless("startup-last-file", StartupView::Last, false); + let file = root.join("last.png"); + let original = startup_png(&file, 170); + + start_launch_photo(&mut h, &file); + + assert_eq!(h.app.ui.view, ViewMode::PhotoGrid); + assert_eq!(h.app.session.catalog.photos().count(), 1); + assert_launch_photo(&h, "last.png"); + assert_eq!(std::fs::read(&file).unwrap(), original); + drop(h); + let _ = std::fs::remove_dir_all(root); +} + /// 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] @@ -542,12 +662,15 @@ fn ui_json_is_written_atomically() { #[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); + let fresh = as_remembered(egui::ViewportBuilder::default(), None, false); 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 })); + let b = as_remembered(egui::ViewportBuilder::default(), Some(WindowPlace { size: [1300.0, 800.0], zoomed: true }), false); assert_eq!((b.inner_size, b.position, b.maximized), (Some(egui::vec2(1300.0, 800.0)), None, Some(true))); + // Windows: built at its size, maximized once it shows + let b = as_remembered(egui::ViewportBuilder::default(), Some(WindowPlace { size: [1300.0, 800.0], zoomed: true }), true); + assert_eq!((b.inner_size, b.maximized), (Some(egui::vec2(1300.0, 800.0)), None)); // (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 })); + let b = as_remembered(egui::ViewportBuilder::default(), Some(WindowPlace { size: [1300.0, 800.0], zoomed: false }), false); assert_eq!((b.inner_size, b.position, b.maximized), (Some(egui::vec2(1300.0, 800.0)), None, None)); } diff --git a/contributors/people.toml b/contributors/people.toml index e9fddbc4a3..5ccb02efe7 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -92,3 +92,6 @@ display_name = "Terra854" [people.P2Hdontusegithub] display_name = "Pizhy" + +[people.gmrmad1] +real_name = "Madhav Agarwal" diff --git a/crates/catalog/src/bursts.rs b/crates/catalog/src/bursts.rs new file mode 100644 index 0000000000..b9c0bcf334 --- /dev/null +++ b/crates/catalog/src/bursts.rs @@ -0,0 +1,167 @@ +//! Bursts: the look-alike shots Assisted Culling groups ([`crate::Analysis::group`]), in the +//! order they are shown and arranged — the pick first. +//! +//! A burst culling made is ordered by what culling found: its best photo, then the sharper +//! shots, then capture time. Once the person arranges a burst by hand every member carries its +//! place ([`crate::Analysis::rank`]), and that order is kept. + +use std::cmp::Reverse; +use std::collections::{HashMap, HashSet}; + +use crate::{Catalog, Photo, PhotoId}; + +/// A photo's place in its burst: hand-placed ones by their place, then the best, the sharper, +/// the earlier (a time that doesn't read last), the lower id. +fn order_key(p: &Photo) -> (u32, bool, Reverse, bool, &str, PhotoId) { + let a = p.analysis.unwrap_or_default(); + let when = p.captured.as_deref().and_then(wall_clock); + (a.rank.unwrap_or(u32::MAX), !a.best, Reverse(sharpness_key(a.sharpness)), when.is_none(), when.unwrap_or(""), p.id) +} + +/// Sharpness (0..100) in thousandths: a fixed-point key keeps the sort total. `as` saturates, so +/// an infinity is the sharpest or softest there is, and a NaN counts as 0. +fn sharpness_key(sharpness: f32) -> i64 { + (sharpness * 1000.0) as i64 +} + +/// The local wall-clock part of an ISO 8601 capture time (`2026-05-01T10:00:00`, with any +/// fraction of a second), or `None` when it isn't one. Its digits stand in fixed places, so as +/// text it sorts in time order. A zone suffix is left out, as culling's burst gap does: a burst's +/// shots are seconds apart from one camera and share their zone. +fn wall_clock(iso: &str) -> Option<&str> { + let b = iso.as_bytes(); + let digits = |from: usize, to: usize| b.get(from..to).is_some_and(|d| d.iter().all(u8::is_ascii_digit)); + let at = |i: usize, c: u8| b.get(i) == Some(&c); + let shape = digits(0, 4) && at(4, b'-') && digits(5, 7) && at(7, b'-') && digits(8, 10) && at(10, b'T'); + if !(shape && digits(11, 13) && at(13, b':') && digits(14, 16) && at(16, b':') && digits(17, 19)) { + return None; + } + let end = iso[19..].find(|c: char| c != '.' && !c.is_ascii_digit()).map_or(iso.len(), |i| 19 + i); + Some(&iso[..end]) +} + +impl Catalog { + /// Every burst: its number → its photos (deleted ones left out), pick first. + pub fn burst_index(&self) -> HashMap> { + let mut by: HashMap> = HashMap::new(); + for p in self.photos.values().filter(|p| !p.deleted) { + if let Some(g) = p.analysis.and_then(|a| a.group) { + by.entry(g).or_default().push(&**p); + } + } + by.into_iter() + .map(|(g, mut photos)| { + photos.sort_by(|a, b| order_key(a).cmp(&order_key(b))); + (g, photos.into_iter().map(|p| p.id).collect()) + }) + .collect() + } + + /// The photos of burst `group`, pick first (empty when there is no such burst). + pub fn burst(&self, group: u32) -> Vec { + self.burst_index().remove(&group).unwrap_or_default() + } + + /// The bursts `ids` meet, in the order their first photo appears in `ids`, each pick first. + /// Only photos in `scope` count as members (the photos of a view and the hidden members of + /// its collapsed stacks, say); `None` takes every photo of the burst. + pub fn bursts_among(&self, ids: &[PhotoId], scope: Option<&HashSet>) -> Vec<(u32, Vec)> { + let mut index = self.burst_index(); + let mut out = Vec::new(); + for id in ids { + let Some(g) = self.photo(*id).and_then(|p| p.analysis).and_then(|a| a.group) else { continue }; + if let Some(mut photos) = index.remove(&g) { + if let Some(scope) = scope { + photos.retain(|p| scope.contains(p)); + } + if !photos.is_empty() { + out.push((g, photos)); + } + } + } + out + } + + /// A burst number no photo uses (deleted ones included, so Undo never brings back a clash). + pub fn next_burst_id(&self) -> u32 { + self.photos.values().filter_map(|p| p.analysis.and_then(|a| a.group)).max().unwrap_or(0) + 1 + } +} + +#[cfg(test)] +mod tests { + use crate::{Analysis, Catalog, Op, Photo, PhotoId, Source}; + + fn add(c: &mut Catalog, when: &str, a: Option) -> PhotoId { + let id = c.alloc_photo_id(); + let mut p = Photo::new(id, Source::File { path: format!("/p/{}.jpg", id.0) }, "p.jpg", "JPEG", 4, 3, "2026-01-01"); + p.captured = Some(when.into()); + p.analysis = a; + c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + id + } + + fn shot(group: u32, sharpness: f32, best: bool, rank: Option) -> Option { + Some(Analysis { sharpness, group: Some(group), best, rank, ..Default::default() }) + } + + #[test] + fn a_culled_burst_shows_its_best_then_the_sharper_shots() { + let mut c = Catalog::new(); + let a = add(&mut c, "2026-05-01T10:00:00", shot(1, 20.0, false, None)); + let b = add(&mut c, "2026-05-01T10:00:01", shot(1, 80.0, true, None)); + let d = add(&mut c, "2026-05-01T10:00:02", shot(1, 50.0, false, None)); + let loose = add(&mut c, "2026-05-01T10:00:03", Some(Analysis::default())); + assert_eq!(c.burst(1), vec![b, d, a]); + assert!(c.burst(2).is_empty()); + assert_eq!(c.bursts_among(&[a, loose, d], None), vec![(1, vec![b, d, a])]); + assert_eq!(c.next_burst_id(), 2); + } + + #[test] + fn a_burst_arranged_by_hand_keeps_its_order() { + let mut c = Catalog::new(); + // the pick by hand is the softest shot + let a = add(&mut c, "2026-05-01T10:00:00", shot(3, 20.0, true, Some(0))); + let b = add(&mut c, "2026-05-01T10:00:01", shot(3, 80.0, false, Some(2))); + let d = add(&mut c, "2026-05-01T10:00:02", shot(3, 50.0, false, Some(1))); + let other = add(&mut c, "2026-05-01T11:00:00", shot(7, 50.0, true, None)); + let other2 = add(&mut c, "2026-05-01T11:00:01", shot(7, 40.0, false, None)); + assert_eq!(c.burst(3), vec![a, d, b]); + // in the order the view meets them; a scope keeps a burst's members within it + assert_eq!(c.bursts_among(&[other, b], None), vec![(7, vec![other, other2]), (3, vec![a, d, b])]); + let scope = [b, d, other].into_iter().collect(); + assert_eq!(c.bursts_among(&[b, other], Some(&scope)), vec![(3, vec![d, b]), (7, vec![other])]); + assert_eq!(c.next_burst_id(), 8); + // deleted photos are no member + c.apply(Op::SetDeleted { id: d, deleted: true }).unwrap(); + assert_eq!(c.burst(3), vec![a, b]); + assert_eq!(c.next_burst_id(), 8); + } + + #[test] + fn a_sharpness_that_does_not_measure_sorts_without_a_panic() { + let mut c = Catalog::new(); + let nan = add(&mut c, "2026-05-01T10:00:00", shot(4, f32::NAN, false, None)); + let soft = add(&mut c, "2026-05-01T10:00:01", shot(4, 10.0, false, None)); + let low = add(&mut c, "2026-05-01T10:00:02", shot(4, f32::NEG_INFINITY, false, None)); + let high = add(&mut c, "2026-05-01T10:00:03", shot(4, f32::INFINITY, false, None)); + // a NaN counts as 0; the infinities saturate at either end + assert_eq!(c.burst(4), vec![high, soft, nan, low]); + } + + #[test] + fn capture_times_sort_by_their_wall_clock() { + let mut c = Catalog::new(); + let s = |c: &mut Catalog, when: &str| add(c, when, shot(5, 50.0, false, None)); + let unread = s(&mut c, "1. Mai 2026"); + let second = s(&mut c, "2026-05-01T10:00:01+02:00"); + let half = s(&mut c, "2026-05-01T10:00:00.5"); + let missing = s(&mut c, ""); + let tenth = s(&mut c, "2026-05-01T10:00:00.12Z"); + // fractions of a second in order, the zone left out, a time that doesn't read last by id + assert_eq!(c.burst(5), vec![tenth, half, second, unread, missing]); + assert_eq!(super::wall_clock("2026-05-01T10:00:00.12-07:00"), Some("2026-05-01T10:00:00.12")); + assert_eq!(super::wall_clock("2026-05-01 10:00:00"), None); + } +} diff --git a/crates/catalog/src/fixtures/v6-catalog.log.jsonl b/crates/catalog/src/fixtures/v6-catalog.log.jsonl new file mode 100644 index 0000000000..de73d856c0 --- /dev/null +++ b/crates/catalog/src/fixtures/v6-catalog.log.jsonl @@ -0,0 +1,5 @@ +{"seq":4,"crc":2044174370,"op":{"op":"setDevelop","id":8,"settings":{"version":1,"profile":{"id":"lc.color","amount":100.0},"treatment":"color","wb":{"mode":"asShot","temp":7000.0,"tint":0.0},"light":{"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0},"curve":{"highlights":0.0,"lights":0.0,"darks":0.0,"shadows":0.0,"split_shadows":25.0,"split_mid":50.0,"split_highlights":75.0,"master":[],"red":[],"green":[],"blue":[],"refine_saturation":100.0},"color":{"vibrance":0.0,"saturation":0.0},"mixer":{"red":{"hue":0.0,"sat":0.0,"lum":0.0},"orange":{"hue":0.0,"sat":0.0,"lum":0.0},"yellow":{"hue":0.0,"sat":0.0,"lum":0.0},"green":{"hue":0.0,"sat":0.0,"lum":0.0},"aqua":{"hue":0.0,"sat":0.0,"lum":0.0},"blue":{"hue":0.0,"sat":0.0,"lum":0.0},"purple":{"hue":0.0,"sat":0.0,"lum":0.0},"magenta":{"hue":0.0,"sat":0.0,"lum":0.0}},"point_colors":[],"bw_mix":{"red":0.0,"orange":0.0,"yellow":0.0,"green":0.0,"aqua":0.0,"blue":0.0,"purple":0.0,"magenta":0.0},"grading":{"shadows":{"hue":0.0,"sat":0.0,"lum":0.0},"midtones":{"hue":0.0,"sat":0.0,"lum":0.0},"highlights":{"hue":0.0,"sat":0.0,"lum":0.0},"global":{"hue":0.0,"sat":0.0,"lum":0.0},"blending":50.0,"balance":0.0},"effects":{"texture":0.0,"clarity":0.0,"dehaze":0.0},"vignette":{"amount":0.0,"midpoint":50.0,"roundness":0.0,"feather":50.0,"highlights":0.0,"style":"highlightPriority"},"grain":{"amount":0.0,"size":25.0,"roughness":50.0,"seed":0},"detail":{"sharpen_amount":0.0,"sharpen_radius":1.0,"sharpen_detail":25.0,"sharpen_masking":0.0,"nr_luminance":0.0,"nr_detail":50.0,"nr_contrast":0.0,"nr_color":0.0,"nr_color_detail":50.0,"nr_color_smoothness":50.0},"optics":{"remove_ca":false,"lens_profile":false,"profile_distortion":100.0,"profile_vignetting":100.0,"defringe_purple_amount":0.0,"defringe_purple_hue_lo":30.0,"defringe_purple_hue_hi":70.0,"defringe_green_amount":0.0,"defringe_green_hue_lo":40.0,"defringe_green_hue_hi":60.0,"distortion":0.0,"vignetting":0.0,"vignetting_midpoint":50.0,"ca_red":0.0,"ca_blue":0.0},"geometry":{"upright":"off","guides":[],"upright_transform":null,"vertical":0.0,"horizontal":0.0,"rotate":0.0,"aspect":0.0,"scale":100.0,"offset_x":0.0,"offset_y":0.0,"constrain_crop":false},"crop":{"geometry":{"rect":{"x0":0.0,"y0":0.0,"x1":1.0,"y1":1.0},"angle":0.0},"aspect":null,"flip_h":false,"flip_v":false},"orientation":"Normal","masks":[],"spots":[],"red_eye":[],"lens_blur":{"enabled":false,"amount":0.0,"focal_distance":0.0,"focal_range":0.0},"enhance":{"denoise":0.0,"raw_details":false,"super_resolution":false},"calibration":{"shadows_tint":0.0,"red_hue":0.0,"red_sat":0.0,"green_hue":0.0,"green_sat":0.0,"blue_hue":0.0,"blue_sat":0.0},"disabled_sections":[]},"label":"Temperature","edited":"2026-10-10T14:00:00"}} +{"seq":5,"crc":1983535997,"op":{"op":"pushHistory","id":8,"step":{"label":"Temperature","settings":{"version":1,"profile":{"id":"lc.color","amount":100.0},"treatment":"color","wb":{"mode":"asShot","temp":7000.0,"tint":0.0},"light":{"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0},"curve":{"highlights":0.0,"lights":0.0,"darks":0.0,"shadows":0.0,"split_shadows":25.0,"split_mid":50.0,"split_highlights":75.0,"master":[],"red":[],"green":[],"blue":[],"refine_saturation":100.0},"color":{"vibrance":0.0,"saturation":0.0},"mixer":{"red":{"hue":0.0,"sat":0.0,"lum":0.0},"orange":{"hue":0.0,"sat":0.0,"lum":0.0},"yellow":{"hue":0.0,"sat":0.0,"lum":0.0},"green":{"hue":0.0,"sat":0.0,"lum":0.0},"aqua":{"hue":0.0,"sat":0.0,"lum":0.0},"blue":{"hue":0.0,"sat":0.0,"lum":0.0},"purple":{"hue":0.0,"sat":0.0,"lum":0.0},"magenta":{"hue":0.0,"sat":0.0,"lum":0.0}},"point_colors":[],"bw_mix":{"red":0.0,"orange":0.0,"yellow":0.0,"green":0.0,"aqua":0.0,"blue":0.0,"purple":0.0,"magenta":0.0},"grading":{"shadows":{"hue":0.0,"sat":0.0,"lum":0.0},"midtones":{"hue":0.0,"sat":0.0,"lum":0.0},"highlights":{"hue":0.0,"sat":0.0,"lum":0.0},"global":{"hue":0.0,"sat":0.0,"lum":0.0},"blending":50.0,"balance":0.0},"effects":{"texture":0.0,"clarity":0.0,"dehaze":0.0},"vignette":{"amount":0.0,"midpoint":50.0,"roundness":0.0,"feather":50.0,"highlights":0.0,"style":"highlightPriority"},"grain":{"amount":0.0,"size":25.0,"roughness":50.0,"seed":0},"detail":{"sharpen_amount":0.0,"sharpen_radius":1.0,"sharpen_detail":25.0,"sharpen_masking":0.0,"nr_luminance":0.0,"nr_detail":50.0,"nr_contrast":0.0,"nr_color":0.0,"nr_color_detail":50.0,"nr_color_smoothness":50.0},"optics":{"remove_ca":false,"lens_profile":false,"profile_distortion":100.0,"profile_vignetting":100.0,"defringe_purple_amount":0.0,"defringe_purple_hue_lo":30.0,"defringe_purple_hue_hi":70.0,"defringe_green_amount":0.0,"defringe_green_hue_lo":40.0,"defringe_green_hue_hi":60.0,"distortion":0.0,"vignetting":0.0,"vignetting_midpoint":50.0,"ca_red":0.0,"ca_blue":0.0},"geometry":{"upright":"off","guides":[],"upright_transform":null,"vertical":0.0,"horizontal":0.0,"rotate":0.0,"aspect":0.0,"scale":100.0,"offset_x":0.0,"offset_y":0.0,"constrain_crop":false},"crop":{"geometry":{"rect":{"x0":0.0,"y0":0.0,"x1":1.0,"y1":1.0},"angle":0.0},"aspect":null,"flip_h":false,"flip_v":false},"orientation":"Normal","masks":[],"spots":[],"red_eye":[],"lens_blur":{"enabled":false,"amount":0.0,"focal_distance":0.0,"focal_range":0.0},"enhance":{"denoise":0.0,"raw_details":false,"super_resolution":false},"calibration":{"shadows_tint":0.0,"red_hue":0.0,"red_sat":0.0,"green_hue":0.0,"green_sat":0.0,"blue_hue":0.0,"blue_sat":0.0},"disabled_sections":[]}}}} +{"seq":6,"crc":3297692306,"op":{"op":"setMeta","id":8,"meta":{"camera":"","lens":"","focal_mm":null,"aperture":null,"shutter":"","iso":null,"location":"","city":"","state":"","country":"","gps":null,"title":"Harbour","caption":"","alt_text":"","extended_description":"","copyright":"","creator":"","keywords":["boats"]}}} +{"seq":7,"crc":4123692544,"op":{"op":"setRating","id":9,"rating":3}} +{"seq":8,"crc":1875893688,"op":{"op":"setVersions","id":9,"versions":[{"name":"Rich","created":"2026-10-10T14:05:00","settings":{"version":1,"profile":{"id":"lc.mono","amount":150.0,"camera_local_tone":true},"treatment":"bw","wb":{"mode":"asShot","temp":6500.0,"tint":12.0},"light":{"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0},"curve":{"highlights":0.0,"lights":0.0,"darks":0.0,"shadows":0.0,"split_shadows":25.0,"split_mid":50.0,"split_highlights":75.0,"master":[{"x":0.0,"y":0.0},{"x":0.4,"y":0.55},{"x":1.0,"y":1.0}],"red":[{"x":0.0,"y":0.1},{"x":1.0,"y":0.9}],"green":[],"blue":[],"refine_saturation":100.0},"color":{"vibrance":0.0,"saturation":0.0},"mixer":{"red":{"hue":0.0,"sat":0.0,"lum":0.0},"orange":{"hue":0.0,"sat":0.0,"lum":0.0},"yellow":{"hue":0.0,"sat":0.0,"lum":0.0},"green":{"hue":0.0,"sat":0.0,"lum":0.0},"aqua":{"hue":0.0,"sat":0.0,"lum":0.0},"blue":{"hue":0.0,"sat":0.0,"lum":0.0},"purple":{"hue":0.0,"sat":0.0,"lum":0.0},"magenta":{"hue":0.0,"sat":0.0,"lum":0.0}},"point_colors":[{"lum":0.5,"chroma":0.1,"hue":0.0,"hue_shift":20.0,"sat_shift":0.0,"lum_shift":0.0,"variance":0.0,"range":50.0,"hue_range":50.0,"sat_range":50.0,"lum_range":50.0}],"bw_mix":{"red":0.0,"orange":0.0,"yellow":0.0,"green":0.0,"aqua":0.0,"blue":0.0,"purple":0.0,"magenta":0.0},"grading":{"shadows":{"hue":0.0,"sat":0.0,"lum":0.0},"midtones":{"hue":0.0,"sat":0.0,"lum":0.0},"highlights":{"hue":0.0,"sat":0.0,"lum":0.0},"global":{"hue":0.0,"sat":0.0,"lum":0.0},"blending":50.0,"balance":0.0},"effects":{"texture":0.0,"clarity":0.0,"dehaze":0.0},"vignette":{"amount":0.0,"midpoint":50.0,"roundness":0.0,"feather":50.0,"highlights":0.0,"style":"highlightPriority"},"grain":{"amount":0.0,"size":25.0,"roughness":50.0,"seed":0},"detail":{"sharpen_amount":0.0,"sharpen_radius":1.0,"sharpen_detail":25.0,"sharpen_masking":0.0,"nr_luminance":0.0,"nr_detail":50.0,"nr_contrast":0.0,"nr_color":0.0,"nr_color_detail":50.0,"nr_color_smoothness":50.0},"optics":{"remove_ca":false,"lens_profile":false,"profile_distortion":100.0,"profile_vignetting":100.0,"defringe_purple_amount":0.0,"defringe_purple_hue_lo":30.0,"defringe_purple_hue_hi":70.0,"defringe_green_amount":0.0,"defringe_green_hue_lo":40.0,"defringe_green_hue_hi":60.0,"distortion":0.0,"vignetting":0.0,"vignetting_midpoint":50.0,"ca_red":0.0,"ca_blue":0.0},"geometry":{"upright":"off","guides":[[{"x":0.1,"y":0.1},{"x":0.1,"y":0.9}],[{"x":0.9,"y":0.1},{"x":0.8,"y":0.9}]],"upright_transform":[1.0,0.01,0.0,-0.01,1.0,0.0,0.0,0.002,1.0],"vertical":0.0,"horizontal":0.0,"rotate":0.0,"aspect":0.0,"scale":100.0,"offset_x":0.0,"offset_y":0.0,"constrain_crop":false},"crop":{"geometry":{"rect":{"x0":0.0,"y0":0.0,"x1":1.0,"y1":1.0},"angle":1.5},"aspect":[3,2],"flip_h":true,"flip_v":false},"orientation":"Normal","masks":[{"id":1,"name":"Sky","visible":true,"invert":false,"components":[{"op":"add","invert":false,"shape":{"kind":"linear","start":{"x":0.5,"y":0.0},"end":{"x":0.5,"y":0.4}}},{"name":"Sun","op":"add","invert":true,"shape":{"kind":"radial","center":{"x":0.7,"y":0.2},"rx":0.1,"ry":0.1,"angle":0.0,"feather":50.0,"invert":false}},{"op":"add","invert":false,"shape":{"kind":"luminanceRange","lo":0.6,"hi":1.0,"lo_feather":0.1,"hi_feather":0.0}}],"adjust":{"temp":0.0,"tint":0.0,"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0,"texture":0.0,"clarity":0.0,"dehaze":0.0,"hue":0.0,"saturation":0.0,"sharpness":0.0,"noise":0.0,"moire":0.0,"defringe":0.0,"color_hue":0.0,"color_sat":0.0,"amount":100.0},"refine":30.0},{"id":2,"name":"Boat","visible":true,"invert":false,"components":[{"op":"add","invert":false,"shape":{"kind":"object","hint":[{"x":0.4,"y":0.6}],"exclude":[{"x":0.1,"y":0.1}],"seg":{"side":256,"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7]},"detail":[{"side":128,"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7]},{"side":64,"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7]}],"edge":2.0}},{"op":"add","invert":false,"shape":{"kind":"prompt","text":"the red boat"}},{"op":"add","invert":false,"shape":{"kind":"colorRange","samples":[[0.5,0.1,0.2]],"refine":40.0}},{"op":"add","invert":false,"shape":{"kind":"people","person":1,"parts":["face"]}},{"op":"add","invert":false,"shape":{"kind":"subject"}}],"adjust":{"temp":0.0,"tint":0.0,"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0,"texture":0.0,"clarity":0.0,"dehaze":0.0,"hue":0.0,"saturation":0.0,"sharpness":0.0,"noise":0.0,"moire":0.0,"defringe":0.0,"color_hue":0.0,"color_sat":0.0,"amount":100.0}}],"spots":[{"mode":"remove","points":[{"x":0.3,"y":0.3},{"x":0.32,"y":0.31}],"size":0.02,"feather":50.0,"opacity":100.0,"source_offset":{"x":0.05,"y":0.0}}],"red_eye":[{"center":{"x":0.5,"y":0.4},"rx":0.02,"ry":0.015,"pupil_size":50.0,"darken":50.0,"pet":false,"catchlight":{"x":0.1,"y":-0.1}}],"lens_blur":{"enabled":false,"amount":0.0,"focal_distance":0.0,"focal_range":0.0},"enhance":{"denoise":0.0,"raw_details":false,"super_resolution":false},"calibration":{"shadows_tint":0.0,"red_hue":0.0,"red_sat":0.0,"green_hue":0.0,"green_sat":0.0,"blue_hue":0.0,"blue_sat":0.0},"disabled_sections":["detail","light"]},"auto":false}]}} diff --git a/crates/catalog/src/fixtures/v6-catalog.snap.json b/crates/catalog/src/fixtures/v6-catalog.snap.json new file mode 100644 index 0000000000..7908b5c43c --- /dev/null +++ b/crates/catalog/src/fixtures/v6-catalog.snap.json @@ -0,0 +1 @@ +{"format":"lightcraft-catalog","version":6,"seq":3,"catalog":{"photos":{"7":{"id":7,"source":{"type":"file","path":"/pictures/2019/trip/IMG_0007.jpg"},"file_name":"IMG_0007.jpg","kind":"raw","format":"JPEG","width":4032,"height":3024,"file_size":25000000,"captured":"2019-07-14T15:21:07","imported":"2026-10-10T12:00:00","meta":{"camera":"Camera Model X","lens":"24-70mm f/2.8","focal_mm":35.0,"aperture":4.0,"shutter":"1/250","iso":400,"location":"Old harbour","city":"Lisbon","state":"Lisboa","country":"Portugal","gps":[38.7,-9.1],"title":"Harbour","caption":"Boats at dusk","alt_text":"Three boats","extended_description":"Three boats moored at dusk","copyright":"(c) Someone","copyright_status":"copyrighted","usage_terms":"All rights reserved","copyright_url":"https://example.org/rights","creator":"Someone","keywords":["Places|Lisbon","boats"],"regions":[{"rect":{"x0":0.1,"y0":0.2,"x1":0.3,"y1":0.4},"kind":"Face","name":"Ana","description":null}]},"rating":4,"flag":"pick","label":"green","develop":{"version":1,"profile":{"id":"lc.mono","amount":150.0,"camera_local_tone":true},"treatment":"bw","wb":{"mode":"asShot","temp":6500.0,"tint":12.0},"light":{"exposure":0.3,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0},"curve":{"highlights":0.0,"lights":0.0,"darks":0.0,"shadows":0.0,"split_shadows":25.0,"split_mid":50.0,"split_highlights":75.0,"master":[{"x":0.0,"y":0.0},{"x":0.4,"y":0.55},{"x":1.0,"y":1.0}],"red":[{"x":0.0,"y":0.1},{"x":1.0,"y":0.9}],"green":[],"blue":[],"refine_saturation":100.0},"color":{"vibrance":0.0,"saturation":0.0},"mixer":{"red":{"hue":0.0,"sat":0.0,"lum":0.0},"orange":{"hue":0.0,"sat":0.0,"lum":0.0},"yellow":{"hue":0.0,"sat":0.0,"lum":0.0},"green":{"hue":0.0,"sat":0.0,"lum":0.0},"aqua":{"hue":0.0,"sat":0.0,"lum":0.0},"blue":{"hue":0.0,"sat":0.0,"lum":0.0},"purple":{"hue":0.0,"sat":0.0,"lum":0.0},"magenta":{"hue":0.0,"sat":0.0,"lum":0.0}},"point_colors":[{"lum":0.5,"chroma":0.1,"hue":0.0,"hue_shift":20.0,"sat_shift":0.0,"lum_shift":0.0,"variance":0.0,"range":50.0,"hue_range":50.0,"sat_range":50.0,"lum_range":50.0}],"bw_mix":{"red":0.0,"orange":0.0,"yellow":0.0,"green":0.0,"aqua":0.0,"blue":0.0,"purple":0.0,"magenta":0.0},"grading":{"shadows":{"hue":0.0,"sat":0.0,"lum":0.0},"midtones":{"hue":0.0,"sat":0.0,"lum":0.0},"highlights":{"hue":0.0,"sat":0.0,"lum":0.0},"global":{"hue":0.0,"sat":0.0,"lum":0.0},"blending":50.0,"balance":0.0},"effects":{"texture":0.0,"clarity":0.0,"dehaze":0.0},"vignette":{"amount":0.0,"midpoint":50.0,"roundness":0.0,"feather":50.0,"highlights":0.0,"style":"highlightPriority"},"grain":{"amount":0.0,"size":25.0,"roughness":50.0,"seed":0},"detail":{"sharpen_amount":0.0,"sharpen_radius":1.0,"sharpen_detail":25.0,"sharpen_masking":0.0,"nr_luminance":0.0,"nr_detail":50.0,"nr_contrast":0.0,"nr_color":0.0,"nr_color_detail":50.0,"nr_color_smoothness":50.0},"optics":{"remove_ca":false,"lens_profile":false,"profile_distortion":100.0,"profile_vignetting":100.0,"defringe_purple_amount":0.0,"defringe_purple_hue_lo":30.0,"defringe_purple_hue_hi":70.0,"defringe_green_amount":0.0,"defringe_green_hue_lo":40.0,"defringe_green_hue_hi":60.0,"distortion":0.0,"vignetting":0.0,"vignetting_midpoint":50.0,"ca_red":0.0,"ca_blue":0.0},"geometry":{"upright":"off","guides":[[{"x":0.1,"y":0.1},{"x":0.1,"y":0.9}],[{"x":0.9,"y":0.1},{"x":0.8,"y":0.9}]],"upright_transform":[1.0,0.01,0.0,-0.01,1.0,0.0,0.0,0.002,1.0],"vertical":0.0,"horizontal":0.0,"rotate":0.0,"aspect":0.0,"scale":100.0,"offset_x":0.0,"offset_y":0.0,"constrain_crop":false},"crop":{"geometry":{"rect":{"x0":0.0,"y0":0.0,"x1":1.0,"y1":1.0},"angle":1.5},"aspect":[3,2],"flip_h":true,"flip_v":false},"orientation":"Normal","masks":[{"id":1,"name":"Sky","visible":true,"invert":false,"components":[{"op":"add","invert":false,"shape":{"kind":"linear","start":{"x":0.5,"y":0.0},"end":{"x":0.5,"y":0.4}}},{"name":"Sun","op":"add","invert":true,"shape":{"kind":"radial","center":{"x":0.7,"y":0.2},"rx":0.1,"ry":0.1,"angle":0.0,"feather":50.0,"invert":false}},{"op":"add","invert":false,"shape":{"kind":"luminanceRange","lo":0.6,"hi":1.0,"lo_feather":0.1,"hi_feather":0.0}}],"adjust":{"temp":0.0,"tint":0.0,"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0,"texture":0.0,"clarity":0.0,"dehaze":0.0,"hue":0.0,"saturation":0.0,"sharpness":0.0,"noise":0.0,"moire":0.0,"defringe":0.0,"color_hue":0.0,"color_sat":0.0,"amount":100.0},"refine":30.0},{"id":2,"name":"Boat","visible":true,"invert":false,"components":[{"op":"add","invert":false,"shape":{"kind":"object","hint":[{"x":0.4,"y":0.6}],"exclude":[{"x":0.1,"y":0.1}],"seg":{"side":256,"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7]},"detail":[{"side":128,"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7]},{"side":64,"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7]}],"edge":2.0}},{"op":"add","invert":false,"shape":{"kind":"prompt","text":"the red boat"}},{"op":"add","invert":false,"shape":{"kind":"colorRange","samples":[[0.5,0.1,0.2]],"refine":40.0}},{"op":"add","invert":false,"shape":{"kind":"people","person":1,"parts":["face"]}},{"op":"add","invert":false,"shape":{"kind":"subject"}}],"adjust":{"temp":0.0,"tint":0.0,"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0,"texture":0.0,"clarity":0.0,"dehaze":0.0,"hue":0.0,"saturation":0.0,"sharpness":0.0,"noise":0.0,"moire":0.0,"defringe":0.0,"color_hue":0.0,"color_sat":0.0,"amount":100.0}}],"spots":[{"mode":"remove","points":[{"x":0.3,"y":0.3},{"x":0.32,"y":0.31}],"size":0.02,"feather":50.0,"opacity":100.0,"source_offset":{"x":0.05,"y":0.0}}],"red_eye":[{"center":{"x":0.5,"y":0.4},"rx":0.02,"ry":0.015,"pupil_size":50.0,"darken":50.0,"pet":false,"catchlight":{"x":0.1,"y":-0.1}}],"lens_blur":{"enabled":false,"amount":0.0,"focal_distance":0.0,"focal_range":0.0},"enhance":{"denoise":0.0,"raw_details":false,"super_resolution":false},"calibration":{"shadows_tint":0.0,"red_hue":0.0,"red_sat":0.0,"green_hue":0.0,"green_sat":0.0,"blue_hue":0.0,"blue_sat":0.0},"disabled_sections":["detail","light"]},"edited":"2026-10-10T13:00:00","versions":[{"name":"Warm","created":"2026-10-10T12:30:00","settings":{"version":1,"profile":{"id":"lc.color","amount":100.0},"treatment":"color","wb":{"mode":"asShot","temp":6500.0,"tint":0.0},"light":{"exposure":0.0,"contrast":20.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0},"curve":{"highlights":0.0,"lights":0.0,"darks":0.0,"shadows":0.0,"split_shadows":25.0,"split_mid":50.0,"split_highlights":75.0,"master":[],"red":[],"green":[],"blue":[],"refine_saturation":100.0},"color":{"vibrance":0.0,"saturation":0.0},"mixer":{"red":{"hue":0.0,"sat":0.0,"lum":0.0},"orange":{"hue":0.0,"sat":0.0,"lum":0.0},"yellow":{"hue":0.0,"sat":0.0,"lum":0.0},"green":{"hue":0.0,"sat":0.0,"lum":0.0},"aqua":{"hue":0.0,"sat":0.0,"lum":0.0},"blue":{"hue":0.0,"sat":0.0,"lum":0.0},"purple":{"hue":0.0,"sat":0.0,"lum":0.0},"magenta":{"hue":0.0,"sat":0.0,"lum":0.0}},"point_colors":[],"bw_mix":{"red":0.0,"orange":0.0,"yellow":0.0,"green":0.0,"aqua":0.0,"blue":0.0,"purple":0.0,"magenta":0.0},"grading":{"shadows":{"hue":0.0,"sat":0.0,"lum":0.0},"midtones":{"hue":0.0,"sat":0.0,"lum":0.0},"highlights":{"hue":0.0,"sat":0.0,"lum":0.0},"global":{"hue":0.0,"sat":0.0,"lum":0.0},"blending":50.0,"balance":0.0},"effects":{"texture":0.0,"clarity":0.0,"dehaze":0.0},"vignette":{"amount":0.0,"midpoint":50.0,"roundness":0.0,"feather":50.0,"highlights":0.0,"style":"highlightPriority"},"grain":{"amount":0.0,"size":25.0,"roughness":50.0,"seed":0},"detail":{"sharpen_amount":0.0,"sharpen_radius":1.0,"sharpen_detail":25.0,"sharpen_masking":0.0,"nr_luminance":0.0,"nr_detail":50.0,"nr_contrast":0.0,"nr_color":0.0,"nr_color_detail":50.0,"nr_color_smoothness":50.0},"optics":{"remove_ca":false,"lens_profile":false,"profile_distortion":100.0,"profile_vignetting":100.0,"defringe_purple_amount":0.0,"defringe_purple_hue_lo":30.0,"defringe_purple_hue_hi":70.0,"defringe_green_amount":0.0,"defringe_green_hue_lo":40.0,"defringe_green_hue_hi":60.0,"distortion":0.0,"vignetting":0.0,"vignetting_midpoint":50.0,"ca_red":0.0,"ca_blue":0.0},"geometry":{"upright":"off","guides":[],"upright_transform":null,"vertical":0.0,"horizontal":0.0,"rotate":0.0,"aspect":0.0,"scale":100.0,"offset_x":0.0,"offset_y":0.0,"constrain_crop":false},"crop":{"geometry":{"rect":{"x0":0.0,"y0":0.0,"x1":1.0,"y1":1.0},"angle":0.0},"aspect":null,"flip_h":false,"flip_v":false},"orientation":"Normal","masks":[],"spots":[],"red_eye":[],"lens_blur":{"enabled":false,"amount":0.0,"focal_distance":0.0,"focal_range":0.0},"enhance":{"denoise":0.0,"raw_details":false,"super_resolution":false},"calibration":{"shadows_tint":0.0,"red_hue":0.0,"red_sat":0.0,"green_hue":0.0,"green_sat":0.0,"blue_hue":0.0,"blue_sat":0.0},"disabled_sections":[]},"auto":true}],"history":[{"label":"Contrast","settings":{"version":1,"profile":{"id":"lc.color","amount":100.0},"treatment":"color","wb":{"mode":"asShot","temp":6500.0,"tint":0.0},"light":{"exposure":0.0,"contrast":20.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0},"curve":{"highlights":0.0,"lights":0.0,"darks":0.0,"shadows":0.0,"split_shadows":25.0,"split_mid":50.0,"split_highlights":75.0,"master":[],"red":[],"green":[],"blue":[],"refine_saturation":100.0},"color":{"vibrance":0.0,"saturation":0.0},"mixer":{"red":{"hue":0.0,"sat":0.0,"lum":0.0},"orange":{"hue":0.0,"sat":0.0,"lum":0.0},"yellow":{"hue":0.0,"sat":0.0,"lum":0.0},"green":{"hue":0.0,"sat":0.0,"lum":0.0},"aqua":{"hue":0.0,"sat":0.0,"lum":0.0},"blue":{"hue":0.0,"sat":0.0,"lum":0.0},"purple":{"hue":0.0,"sat":0.0,"lum":0.0},"magenta":{"hue":0.0,"sat":0.0,"lum":0.0}},"point_colors":[],"bw_mix":{"red":0.0,"orange":0.0,"yellow":0.0,"green":0.0,"aqua":0.0,"blue":0.0,"purple":0.0,"magenta":0.0},"grading":{"shadows":{"hue":0.0,"sat":0.0,"lum":0.0},"midtones":{"hue":0.0,"sat":0.0,"lum":0.0},"highlights":{"hue":0.0,"sat":0.0,"lum":0.0},"global":{"hue":0.0,"sat":0.0,"lum":0.0},"blending":50.0,"balance":0.0},"effects":{"texture":0.0,"clarity":0.0,"dehaze":0.0},"vignette":{"amount":0.0,"midpoint":50.0,"roundness":0.0,"feather":50.0,"highlights":0.0,"style":"highlightPriority"},"grain":{"amount":0.0,"size":25.0,"roughness":50.0,"seed":0},"detail":{"sharpen_amount":0.0,"sharpen_radius":1.0,"sharpen_detail":25.0,"sharpen_masking":0.0,"nr_luminance":0.0,"nr_detail":50.0,"nr_contrast":0.0,"nr_color":0.0,"nr_color_detail":50.0,"nr_color_smoothness":50.0},"optics":{"remove_ca":false,"lens_profile":false,"profile_distortion":100.0,"profile_vignetting":100.0,"defringe_purple_amount":0.0,"defringe_purple_hue_lo":30.0,"defringe_purple_hue_hi":70.0,"defringe_green_amount":0.0,"defringe_green_hue_lo":40.0,"defringe_green_hue_hi":60.0,"distortion":0.0,"vignetting":0.0,"vignetting_midpoint":50.0,"ca_red":0.0,"ca_blue":0.0},"geometry":{"upright":"off","guides":[],"upright_transform":null,"vertical":0.0,"horizontal":0.0,"rotate":0.0,"aspect":0.0,"scale":100.0,"offset_x":0.0,"offset_y":0.0,"constrain_crop":false},"crop":{"geometry":{"rect":{"x0":0.0,"y0":0.0,"x1":1.0,"y1":1.0},"angle":0.0},"aspect":null,"flip_h":false,"flip_v":false},"orientation":"Normal","masks":[],"spots":[],"red_eye":[],"lens_blur":{"enabled":false,"amount":0.0,"focal_distance":0.0,"focal_range":0.0},"enhance":{"denoise":0.0,"raw_details":false,"super_resolution":false},"calibration":{"shadows_tint":0.0,"red_hue":0.0,"red_sat":0.0,"green_hue":0.0,"green_sat":0.0,"blue_hue":0.0,"blue_sat":0.0},"disabled_sections":[]}},{"label":"Exposure","settings":{"version":1,"profile":{"id":"lc.mono","amount":150.0,"camera_local_tone":true},"treatment":"bw","wb":{"mode":"asShot","temp":6500.0,"tint":12.0},"light":{"exposure":0.3,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0},"curve":{"highlights":0.0,"lights":0.0,"darks":0.0,"shadows":0.0,"split_shadows":25.0,"split_mid":50.0,"split_highlights":75.0,"master":[{"x":0.0,"y":0.0},{"x":0.4,"y":0.55},{"x":1.0,"y":1.0}],"red":[{"x":0.0,"y":0.1},{"x":1.0,"y":0.9}],"green":[],"blue":[],"refine_saturation":100.0},"color":{"vibrance":0.0,"saturation":0.0},"mixer":{"red":{"hue":0.0,"sat":0.0,"lum":0.0},"orange":{"hue":0.0,"sat":0.0,"lum":0.0},"yellow":{"hue":0.0,"sat":0.0,"lum":0.0},"green":{"hue":0.0,"sat":0.0,"lum":0.0},"aqua":{"hue":0.0,"sat":0.0,"lum":0.0},"blue":{"hue":0.0,"sat":0.0,"lum":0.0},"purple":{"hue":0.0,"sat":0.0,"lum":0.0},"magenta":{"hue":0.0,"sat":0.0,"lum":0.0}},"point_colors":[{"lum":0.5,"chroma":0.1,"hue":0.0,"hue_shift":20.0,"sat_shift":0.0,"lum_shift":0.0,"variance":0.0,"range":50.0,"hue_range":50.0,"sat_range":50.0,"lum_range":50.0}],"bw_mix":{"red":0.0,"orange":0.0,"yellow":0.0,"green":0.0,"aqua":0.0,"blue":0.0,"purple":0.0,"magenta":0.0},"grading":{"shadows":{"hue":0.0,"sat":0.0,"lum":0.0},"midtones":{"hue":0.0,"sat":0.0,"lum":0.0},"highlights":{"hue":0.0,"sat":0.0,"lum":0.0},"global":{"hue":0.0,"sat":0.0,"lum":0.0},"blending":50.0,"balance":0.0},"effects":{"texture":0.0,"clarity":0.0,"dehaze":0.0},"vignette":{"amount":0.0,"midpoint":50.0,"roundness":0.0,"feather":50.0,"highlights":0.0,"style":"highlightPriority"},"grain":{"amount":0.0,"size":25.0,"roughness":50.0,"seed":0},"detail":{"sharpen_amount":0.0,"sharpen_radius":1.0,"sharpen_detail":25.0,"sharpen_masking":0.0,"nr_luminance":0.0,"nr_detail":50.0,"nr_contrast":0.0,"nr_color":0.0,"nr_color_detail":50.0,"nr_color_smoothness":50.0},"optics":{"remove_ca":false,"lens_profile":false,"profile_distortion":100.0,"profile_vignetting":100.0,"defringe_purple_amount":0.0,"defringe_purple_hue_lo":30.0,"defringe_purple_hue_hi":70.0,"defringe_green_amount":0.0,"defringe_green_hue_lo":40.0,"defringe_green_hue_hi":60.0,"distortion":0.0,"vignetting":0.0,"vignetting_midpoint":50.0,"ca_red":0.0,"ca_blue":0.0},"geometry":{"upright":"off","guides":[[{"x":0.1,"y":0.1},{"x":0.1,"y":0.9}],[{"x":0.9,"y":0.1},{"x":0.8,"y":0.9}]],"upright_transform":[1.0,0.01,0.0,-0.01,1.0,0.0,0.0,0.002,1.0],"vertical":0.0,"horizontal":0.0,"rotate":0.0,"aspect":0.0,"scale":100.0,"offset_x":0.0,"offset_y":0.0,"constrain_crop":false},"crop":{"geometry":{"rect":{"x0":0.0,"y0":0.0,"x1":1.0,"y1":1.0},"angle":1.5},"aspect":[3,2],"flip_h":true,"flip_v":false},"orientation":"Normal","masks":[{"id":1,"name":"Sky","visible":true,"invert":false,"components":[{"op":"add","invert":false,"shape":{"kind":"linear","start":{"x":0.5,"y":0.0},"end":{"x":0.5,"y":0.4}}},{"name":"Sun","op":"add","invert":true,"shape":{"kind":"radial","center":{"x":0.7,"y":0.2},"rx":0.1,"ry":0.1,"angle":0.0,"feather":50.0,"invert":false}},{"op":"add","invert":false,"shape":{"kind":"luminanceRange","lo":0.6,"hi":1.0,"lo_feather":0.1,"hi_feather":0.0}}],"adjust":{"temp":0.0,"tint":0.0,"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0,"texture":0.0,"clarity":0.0,"dehaze":0.0,"hue":0.0,"saturation":0.0,"sharpness":0.0,"noise":0.0,"moire":0.0,"defringe":0.0,"color_hue":0.0,"color_sat":0.0,"amount":100.0},"refine":30.0},{"id":2,"name":"Boat","visible":true,"invert":false,"components":[{"op":"add","invert":false,"shape":{"kind":"object","hint":[{"x":0.4,"y":0.6}],"exclude":[{"x":0.1,"y":0.1}],"seg":{"side":256,"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7]},"detail":[{"side":128,"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7]},{"side":64,"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7]}],"edge":2.0}},{"op":"add","invert":false,"shape":{"kind":"prompt","text":"the red boat"}},{"op":"add","invert":false,"shape":{"kind":"colorRange","samples":[[0.5,0.1,0.2]],"refine":40.0}},{"op":"add","invert":false,"shape":{"kind":"people","person":1,"parts":["face"]}},{"op":"add","invert":false,"shape":{"kind":"subject"}}],"adjust":{"temp":0.0,"tint":0.0,"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0,"texture":0.0,"clarity":0.0,"dehaze":0.0,"hue":0.0,"saturation":0.0,"sharpness":0.0,"noise":0.0,"moire":0.0,"defringe":0.0,"color_hue":0.0,"color_sat":0.0,"amount":100.0}}],"spots":[{"mode":"remove","points":[{"x":0.3,"y":0.3},{"x":0.32,"y":0.31}],"size":0.02,"feather":50.0,"opacity":100.0,"source_offset":{"x":0.05,"y":0.0}}],"red_eye":[{"center":{"x":0.5,"y":0.4},"rx":0.02,"ry":0.015,"pupil_size":50.0,"darken":50.0,"pet":false,"catchlight":{"x":0.1,"y":-0.1}}],"lens_blur":{"enabled":false,"amount":0.0,"focal_distance":0.0,"focal_range":0.0},"enhance":{"denoise":0.0,"raw_details":false,"super_resolution":false},"calibration":{"shadows_tint":0.0,"red_hue":0.0,"red_sat":0.0,"green_hue":0.0,"green_sat":0.0,"blue_hue":0.0,"blue_sat":0.0},"disabled_sections":["detail","light"]}}],"deleted":true,"local":true,"duration":12.5,"as_shot_wb":[5200.0,3.0],"content_hash":"00000000000000009e3779b97f4a7c15","embedded_lens":{"warp":null,"vignette":{"k":[0.0,0.0,0.0,0.0,0.0],"center":{"x":0.0,"y":0.0},"radius":0.0}},"copy_of":3,"copy_name":"Copy 1","import_look":{"version":1,"profile":{"id":"lc.color","amount":100.0},"treatment":"color","wb":{"mode":"asShot","temp":6500.0,"tint":0.0},"light":{"exposure":0.0,"contrast":20.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0},"curve":{"highlights":0.0,"lights":0.0,"darks":0.0,"shadows":0.0,"split_shadows":25.0,"split_mid":50.0,"split_highlights":75.0,"master":[],"red":[],"green":[],"blue":[],"refine_saturation":100.0},"color":{"vibrance":0.0,"saturation":0.0},"mixer":{"red":{"hue":0.0,"sat":0.0,"lum":0.0},"orange":{"hue":0.0,"sat":0.0,"lum":0.0},"yellow":{"hue":0.0,"sat":0.0,"lum":0.0},"green":{"hue":0.0,"sat":0.0,"lum":0.0},"aqua":{"hue":0.0,"sat":0.0,"lum":0.0},"blue":{"hue":0.0,"sat":0.0,"lum":0.0},"purple":{"hue":0.0,"sat":0.0,"lum":0.0},"magenta":{"hue":0.0,"sat":0.0,"lum":0.0}},"point_colors":[],"bw_mix":{"red":0.0,"orange":0.0,"yellow":0.0,"green":0.0,"aqua":0.0,"blue":0.0,"purple":0.0,"magenta":0.0},"grading":{"shadows":{"hue":0.0,"sat":0.0,"lum":0.0},"midtones":{"hue":0.0,"sat":0.0,"lum":0.0},"highlights":{"hue":0.0,"sat":0.0,"lum":0.0},"global":{"hue":0.0,"sat":0.0,"lum":0.0},"blending":50.0,"balance":0.0},"effects":{"texture":0.0,"clarity":0.0,"dehaze":0.0},"vignette":{"amount":0.0,"midpoint":50.0,"roundness":0.0,"feather":50.0,"highlights":0.0,"style":"highlightPriority"},"grain":{"amount":0.0,"size":25.0,"roughness":50.0,"seed":0},"detail":{"sharpen_amount":0.0,"sharpen_radius":1.0,"sharpen_detail":25.0,"sharpen_masking":0.0,"nr_luminance":0.0,"nr_detail":50.0,"nr_contrast":0.0,"nr_color":0.0,"nr_color_detail":50.0,"nr_color_smoothness":50.0},"optics":{"remove_ca":false,"lens_profile":false,"profile_distortion":100.0,"profile_vignetting":100.0,"defringe_purple_amount":0.0,"defringe_purple_hue_lo":30.0,"defringe_purple_hue_hi":70.0,"defringe_green_amount":0.0,"defringe_green_hue_lo":40.0,"defringe_green_hue_hi":60.0,"distortion":0.0,"vignetting":0.0,"vignetting_midpoint":50.0,"ca_red":0.0,"ca_blue":0.0},"geometry":{"upright":"off","guides":[],"upright_transform":null,"vertical":0.0,"horizontal":0.0,"rotate":0.0,"aspect":0.0,"scale":100.0,"offset_x":0.0,"offset_y":0.0,"constrain_crop":false},"crop":{"geometry":{"rect":{"x0":0.0,"y0":0.0,"x1":1.0,"y1":1.0},"angle":0.0},"aspect":null,"flip_h":false,"flip_v":false},"orientation":"Normal","masks":[],"spots":[],"red_eye":[],"lens_blur":{"enabled":false,"amount":0.0,"focal_distance":0.0,"focal_range":0.0},"enhance":{"denoise":0.0,"raw_details":false,"super_resolution":false},"calibration":{"shadows_tint":0.0,"red_hue":0.0,"red_sat":0.0,"green_hue":0.0,"green_sat":0.0,"blue_hue":0.0,"blue_sat":0.0},"disabled_sections":[]},"analysis":{"sharpness":71.0,"clipped":0.02,"group":4,"best":true},"preview_only":"unsupported raw variant","local_baseline":3735928559},"8":{"id":8,"source":{"type":"file","path":"/pictures/2019/trip/IMG_0008.jpg"},"file_name":"IMG_0008.jpg","kind":"image","format":"JPEG","width":4032,"height":3024,"file_size":0,"captured":null,"imported":"2026-10-10T12:00:00","meta":{"camera":"","lens":"","focal_mm":null,"aperture":null,"shutter":"","iso":null,"location":"","city":"","state":"","country":"","gps":null,"title":"","caption":"","alt_text":"","extended_description":"","copyright":"","creator":"","keywords":[]},"rating":0,"flag":"none","label":null,"develop":{"version":1,"profile":{"id":"lc.color","amount":100.0},"treatment":"color","wb":{"mode":"asShot","temp":6500.0,"tint":0.0},"light":{"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0},"curve":{"highlights":0.0,"lights":0.0,"darks":0.0,"shadows":0.0,"split_shadows":25.0,"split_mid":50.0,"split_highlights":75.0,"master":[],"red":[],"green":[],"blue":[],"refine_saturation":100.0},"color":{"vibrance":0.0,"saturation":0.0},"mixer":{"red":{"hue":0.0,"sat":0.0,"lum":0.0},"orange":{"hue":0.0,"sat":0.0,"lum":0.0},"yellow":{"hue":0.0,"sat":0.0,"lum":0.0},"green":{"hue":0.0,"sat":0.0,"lum":0.0},"aqua":{"hue":0.0,"sat":0.0,"lum":0.0},"blue":{"hue":0.0,"sat":0.0,"lum":0.0},"purple":{"hue":0.0,"sat":0.0,"lum":0.0},"magenta":{"hue":0.0,"sat":0.0,"lum":0.0}},"point_colors":[],"bw_mix":{"red":0.0,"orange":0.0,"yellow":0.0,"green":0.0,"aqua":0.0,"blue":0.0,"purple":0.0,"magenta":0.0},"grading":{"shadows":{"hue":0.0,"sat":0.0,"lum":0.0},"midtones":{"hue":0.0,"sat":0.0,"lum":0.0},"highlights":{"hue":0.0,"sat":0.0,"lum":0.0},"global":{"hue":0.0,"sat":0.0,"lum":0.0},"blending":50.0,"balance":0.0},"effects":{"texture":0.0,"clarity":0.0,"dehaze":0.0},"vignette":{"amount":0.0,"midpoint":50.0,"roundness":0.0,"feather":50.0,"highlights":0.0,"style":"highlightPriority"},"grain":{"amount":0.0,"size":25.0,"roughness":50.0,"seed":0},"detail":{"sharpen_amount":0.0,"sharpen_radius":1.0,"sharpen_detail":25.0,"sharpen_masking":0.0,"nr_luminance":0.0,"nr_detail":50.0,"nr_contrast":0.0,"nr_color":0.0,"nr_color_detail":50.0,"nr_color_smoothness":50.0},"optics":{"remove_ca":false,"lens_profile":false,"profile_distortion":100.0,"profile_vignetting":100.0,"defringe_purple_amount":0.0,"defringe_purple_hue_lo":30.0,"defringe_purple_hue_hi":70.0,"defringe_green_amount":0.0,"defringe_green_hue_lo":40.0,"defringe_green_hue_hi":60.0,"distortion":0.0,"vignetting":0.0,"vignetting_midpoint":50.0,"ca_red":0.0,"ca_blue":0.0},"geometry":{"upright":"off","guides":[],"upright_transform":null,"vertical":0.0,"horizontal":0.0,"rotate":0.0,"aspect":0.0,"scale":100.0,"offset_x":0.0,"offset_y":0.0,"constrain_crop":false},"crop":{"geometry":{"rect":{"x0":0.0,"y0":0.0,"x1":1.0,"y1":1.0},"angle":0.0},"aspect":null,"flip_h":false,"flip_v":false},"orientation":"Normal","masks":[],"spots":[],"red_eye":[],"lens_blur":{"enabled":false,"amount":0.0,"focal_distance":0.0,"focal_range":0.0},"enhance":{"denoise":0.0,"raw_details":false,"super_resolution":false},"calibration":{"shadows_tint":0.0,"red_hue":0.0,"red_sat":0.0,"green_hue":0.0,"green_sat":0.0,"blue_hue":0.0,"blue_sat":0.0},"disabled_sections":[]},"edited":null,"versions":[],"history":[],"deleted":false,"duration":null,"as_shot_wb":null},"9":{"id":9,"source":{"type":"file","path":"/pictures/2019/trip/IMG_0009.jpg"},"file_name":"IMG_0009.jpg","kind":"image","format":"JPEG","width":4032,"height":3024,"file_size":0,"captured":null,"imported":"2026-10-10T12:00:00","meta":{"camera":"","lens":"","focal_mm":null,"aperture":null,"shutter":"","iso":null,"location":"","city":"","state":"","country":"","gps":null,"title":"","caption":"","alt_text":"","extended_description":"","copyright":"","creator":"","keywords":[]},"rating":0,"flag":"none","label":null,"develop":{"version":1,"profile":{"id":"lc.mono","amount":150.0,"camera_local_tone":true},"treatment":"bw","wb":{"mode":"asShot","temp":6500.0,"tint":12.0},"light":{"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0},"curve":{"highlights":0.0,"lights":0.0,"darks":0.0,"shadows":0.0,"split_shadows":25.0,"split_mid":50.0,"split_highlights":75.0,"master":[{"x":0.0,"y":0.0},{"x":0.4,"y":0.55},{"x":1.0,"y":1.0}],"red":[{"x":0.0,"y":0.1},{"x":1.0,"y":0.9}],"green":[],"blue":[],"refine_saturation":100.0},"color":{"vibrance":0.0,"saturation":0.0},"mixer":{"red":{"hue":0.0,"sat":0.0,"lum":0.0},"orange":{"hue":0.0,"sat":0.0,"lum":0.0},"yellow":{"hue":0.0,"sat":0.0,"lum":0.0},"green":{"hue":0.0,"sat":0.0,"lum":0.0},"aqua":{"hue":0.0,"sat":0.0,"lum":0.0},"blue":{"hue":0.0,"sat":0.0,"lum":0.0},"purple":{"hue":0.0,"sat":0.0,"lum":0.0},"magenta":{"hue":0.0,"sat":0.0,"lum":0.0}},"point_colors":[{"lum":0.5,"chroma":0.1,"hue":0.0,"hue_shift":20.0,"sat_shift":0.0,"lum_shift":0.0,"variance":0.0,"range":50.0,"hue_range":50.0,"sat_range":50.0,"lum_range":50.0}],"bw_mix":{"red":0.0,"orange":0.0,"yellow":0.0,"green":0.0,"aqua":0.0,"blue":0.0,"purple":0.0,"magenta":0.0},"grading":{"shadows":{"hue":0.0,"sat":0.0,"lum":0.0},"midtones":{"hue":0.0,"sat":0.0,"lum":0.0},"highlights":{"hue":0.0,"sat":0.0,"lum":0.0},"global":{"hue":0.0,"sat":0.0,"lum":0.0},"blending":50.0,"balance":0.0},"effects":{"texture":0.0,"clarity":0.0,"dehaze":0.0},"vignette":{"amount":0.0,"midpoint":50.0,"roundness":0.0,"feather":50.0,"highlights":0.0,"style":"highlightPriority"},"grain":{"amount":0.0,"size":25.0,"roughness":50.0,"seed":0},"detail":{"sharpen_amount":0.0,"sharpen_radius":1.0,"sharpen_detail":25.0,"sharpen_masking":0.0,"nr_luminance":0.0,"nr_detail":50.0,"nr_contrast":0.0,"nr_color":0.0,"nr_color_detail":50.0,"nr_color_smoothness":50.0},"optics":{"remove_ca":false,"lens_profile":false,"profile_distortion":100.0,"profile_vignetting":100.0,"defringe_purple_amount":0.0,"defringe_purple_hue_lo":30.0,"defringe_purple_hue_hi":70.0,"defringe_green_amount":0.0,"defringe_green_hue_lo":40.0,"defringe_green_hue_hi":60.0,"distortion":0.0,"vignetting":0.0,"vignetting_midpoint":50.0,"ca_red":0.0,"ca_blue":0.0},"geometry":{"upright":"off","guides":[[{"x":0.1,"y":0.1},{"x":0.1,"y":0.9}],[{"x":0.9,"y":0.1},{"x":0.8,"y":0.9}]],"upright_transform":[1.0,0.01,0.0,-0.01,1.0,0.0,0.0,0.002,1.0],"vertical":0.0,"horizontal":0.0,"rotate":0.0,"aspect":0.0,"scale":100.0,"offset_x":0.0,"offset_y":0.0,"constrain_crop":false},"crop":{"geometry":{"rect":{"x0":0.0,"y0":0.0,"x1":1.0,"y1":1.0},"angle":1.5},"aspect":[3,2],"flip_h":true,"flip_v":false},"orientation":"Normal","masks":[{"id":1,"name":"Sky","visible":true,"invert":false,"components":[{"op":"add","invert":false,"shape":{"kind":"linear","start":{"x":0.5,"y":0.0},"end":{"x":0.5,"y":0.4}}},{"name":"Sun","op":"add","invert":true,"shape":{"kind":"radial","center":{"x":0.7,"y":0.2},"rx":0.1,"ry":0.1,"angle":0.0,"feather":50.0,"invert":false}},{"op":"add","invert":false,"shape":{"kind":"luminanceRange","lo":0.6,"hi":1.0,"lo_feather":0.1,"hi_feather":0.0}}],"adjust":{"temp":0.0,"tint":0.0,"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0,"texture":0.0,"clarity":0.0,"dehaze":0.0,"hue":0.0,"saturation":0.0,"sharpness":0.0,"noise":0.0,"moire":0.0,"defringe":0.0,"color_hue":0.0,"color_sat":0.0,"amount":100.0},"refine":30.0},{"id":2,"name":"Boat","visible":true,"invert":false,"components":[{"op":"add","invert":false,"shape":{"kind":"object","hint":[{"x":0.4,"y":0.6}],"exclude":[{"x":0.1,"y":0.1}],"seg":{"side":256,"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7]},"detail":[{"side":128,"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7]},{"side":64,"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7]}],"edge":2.0}},{"op":"add","invert":false,"shape":{"kind":"prompt","text":"the red boat"}},{"op":"add","invert":false,"shape":{"kind":"colorRange","samples":[[0.5,0.1,0.2]],"refine":40.0}},{"op":"add","invert":false,"shape":{"kind":"people","person":1,"parts":["face"]}},{"op":"add","invert":false,"shape":{"kind":"subject"}}],"adjust":{"temp":0.0,"tint":0.0,"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0,"texture":0.0,"clarity":0.0,"dehaze":0.0,"hue":0.0,"saturation":0.0,"sharpness":0.0,"noise":0.0,"moire":0.0,"defringe":0.0,"color_hue":0.0,"color_sat":0.0,"amount":100.0}}],"spots":[{"mode":"remove","points":[{"x":0.3,"y":0.3},{"x":0.32,"y":0.31}],"size":0.02,"feather":50.0,"opacity":100.0,"source_offset":{"x":0.05,"y":0.0}}],"red_eye":[{"center":{"x":0.5,"y":0.4},"rx":0.02,"ry":0.015,"pupil_size":50.0,"darken":50.0,"pet":false,"catchlight":{"x":0.1,"y":-0.1}}],"lens_blur":{"enabled":false,"amount":0.0,"focal_distance":0.0,"focal_range":0.0},"enhance":{"denoise":0.0,"raw_details":false,"super_resolution":false},"calibration":{"shadows_tint":0.0,"red_hue":0.0,"red_sat":0.0,"green_hue":0.0,"green_sat":0.0,"blue_hue":0.0,"blue_sat":0.0},"disabled_sections":["detail","light"]},"edited":null,"versions":[],"history":[],"deleted":false,"local":true,"duration":null,"as_shot_wb":null,"local_baseline":5167973575965256545}},"albums":{},"next_photo":10,"next_album":1,"next_stack":1}} diff --git a/crates/catalog/src/index.rs b/crates/catalog/src/index.rs index 8510a743c8..f7a3dc90e9 100644 --- a/crates/catalog/src/index.rs +++ b/crates/catalog/src/index.rs @@ -1,6 +1,8 @@ //! Lookups derived from the catalog's own data, so questions asked once per photo of a big library //! don't scan a list each time: which stack a photo is in, whether a regular album holds it, which -//! photos have their file in a folder, which have a file of a given name. +//! photos have their file in a folder, which have a file of a given name, which photos have the same +//! content, the lower-cased text the free-text search reads, and the text a smart album's Text rule +//! reads (each made for every photo the first time it is needed for every photo). //! //! They are never saved (the on-disk format is unchanged). Each is built on first use from what //! the catalog holds, so a catalog read from a snapshot, replayed from the journal or cloned starts @@ -8,12 +10,16 @@ //! date: the ops that change stacks or album photos (`AddStack`, `RemoveStack`, `SetStack`, //! `AddAlbum`, `RemoveAlbum`, `SetAlbumPhotos`) and those that add, remove or point a photo at //! another file (`AddPhoto`, `RemovePhoto`, `Relink`, `SetFile`) update them as they apply, -//! inverses and the rollback of a failed batch included, as those are ops too. +//! inverses and the rollback of a failed batch included, as those are ops too. The contents index +//! is kept up to date, and the photos with a photo's content touched, by the ops that change a +//! photo's content as the library sees it, once a rule has built it or while a smart album asks +//! about contents ([`Catalog::follows_contents`], [`Catalog::content_moved`]). +//! The two texts follow every op that changes a photo's fields, and the photo moving to another place in memory. -use std::collections::{HashMap, HashSet}; +use std::collections::{BTreeSet, HashMap, HashSet}; use std::sync::OnceLock; -use crate::{AlbumId, Catalog, PhotoId, Source, StackId}; +use crate::{AlbumId, Catalog, Photo, PhotoId, Source, StackId}; #[derive(Default)] pub(crate) struct Indexes { @@ -22,6 +28,10 @@ pub(crate) struct Indexes { stacks: OnceLock>>, /// Album → its photos (regular albums; a smart album's list is empty). albums: OnceLock>>, + /// Content ([`content_key`]) → the photos that have it. + contents: OnceLock>>, + /// Whether a smart album asks whether a photo has the same content as another ([`Catalog::follows_contents`]). + contents_asked: OnceLock, /// Folder (its [`photo_folder_index_key`], lower-cased) → the photos whose file is directly in /// it, whatever their state (in the library, in Recently Deleted, browsed in Local). Demo /// photos have none. @@ -29,6 +39,14 @@ pub(crate) struct Indexes { /// File name, lower-cased ([`file_name_index_key`]) → the photos whose file has it (same /// states as `folders`). names: OnceLock>>, + /// The smart albums on a loop (see [`crate::Catalog::album_on_a_loop`]). Built from the albums' + /// rules, so forgotten whenever an album is added or removed or its rules change (and by no + /// other op: photos never change which album tests which). + looping: OnceLock>, + /// Photo → its lower-cased searchable text ([`PhotoText`]), for the free-text search. + search: OnceLock>, + /// Photo → the lower-cased text a smart album's Text rule looks through ([`crate::rules::rule_text`]). + rule_text: OnceLock>, } /// A copy builds its own when asked (copies are made to be saved, not queried). @@ -59,6 +77,12 @@ impl std::fmt::Debug for Indexes { } impl Indexes { + /// An op is about to add or remove an album or change its rules (the undo of any of them is + /// one of those too): the albums on a loop are worked out again when asked. + pub(crate) fn forget_loops(&mut self) { + self.looping.take(); + } + /// Stack `id` held `old` and holds `new` now (empty: it was added, or is gone). pub(crate) fn stack_changed(&mut self, id: StackId, old: &[PhotoId], new: &[PhotoId]) { let Some(Some(m)) = self.stacks.get_mut() else { return }; @@ -85,6 +109,55 @@ impl Indexes { } } + /// Photo `id` is `p` now (`None`: it is gone): the text kept for it is made again. + pub(crate) fn text_changed(&mut self, id: PhotoId, p: Option<&Photo>) { + if let Some(m) = self.search.get_mut() { + match p { + Some(p) => m.insert(id, PhotoText::of(p)), + None => m.remove(&id), + }; + } + if let Some(m) = self.rule_text.get_mut() { + match p { + Some(p) => m.insert(id, RuleText::of(p)), + None => m.remove(&id), + }; + } + } + + /// Photo `id` is about to be changed in place, at `p`: an edit of a photo that others hold + /// (`Arc::make_mut`) puts it at another address, which its text follows. + pub(crate) fn text_moved(&mut self, id: PhotoId, p: &Photo) { + let at = addr(p); + if let Some(t) = self.search.get_mut().and_then(|m| m.get_mut(&id)) { + t.at = at; + } + if let Some(t) = self.rule_text.get_mut().and_then(|m| m.get_mut(&id)) { + t.at = at; + } + } + + /// Photo `id` had content `old` and has `new` now (`None`: none the library counts). + fn content_changed(&mut self, id: PhotoId, old: Option<&str>, new: Option) { + let Some(m) = self.contents.get_mut() else { return }; + if let Some(old) = old + && let Some(ids) = m.get_mut(old) + { + ids.retain(|p| *p != id); + if ids.is_empty() { + m.remove(old); + } + } + if let Some(new) = new { + m.entry(new).or_default().push(id); + } + } + + /// An album came, went or got other rules: whether a smart album asks about contents is asked again. + pub(crate) fn albums_changed(&mut self) { + self.contents_asked = OnceLock::new(); + } + /// Photo `id`'s file was at `old` and is at `new` now (`None`: no file, or the photo was added /// or is gone). pub(crate) fn file_changed(&mut self, id: PhotoId, old: Option<&str>, new: Option<&str>) { @@ -100,6 +173,135 @@ impl Indexes { } } +/// A map from photos, for a pass over the library that asks about each one in id order. +type ByPhoto = HashMap>; + +/// Hashes a photo id as itself in the table's low bits, which is where the table looks first, so +/// ids that follow each other sit next to each other and a pass in id order walks it in order +/// rather than jumping about (a pass over 300 000 photos spent most of its time on that). The top +/// bits, which tag an entry in the table, are mixed so entries still tell each other apart. +#[derive(Default)] +pub(crate) struct IdHasher(u64); + +impl std::hash::Hasher for IdHasher { + fn finish(&self) -> u64 { + self.0 ^ (self.0.wrapping_mul(0x9E37_79B9_7F4A_7C15) & 0xFE00_0000_0000_0000) + } + + fn write(&mut self, bytes: &[u8]) { + for b in bytes { + self.0 = self.0.rotate_left(8) ^ u64::from(*b); + } + } + + fn write_u64(&mut self, n: u64) { + self.0 = n; + } +} + +/// Where `p` is in memory. The contract of the kept texts: a text is used only for the photo at the +/// address it was made for. The catalog's own photos (`Arc` contents) stay where they are +/// until `Arc::make_mut` copies one that others hold, which `photo_mut` reports ([`Indexes::text_moved`]; `repair` +/// copies them in bulk and drops every lookup instead); +/// every op that changes a searched field makes the text again ([`Indexes::text_changed`]). A copy +/// of a photo (a candidate tried with other values) is at another address, so it is read from its +/// own fields, never from a text kept for the photo with its id. Only ids and addresses are +/// compared; the address is never turned back into a reference. A catalog read from a snapshot +/// (and then repaired) or cloned starts with no texts at all: they are made when asked. +fn addr(p: &Photo) -> usize { + std::ptr::from_ref(p).addr() +} + +/// What the free-text search looks through for one photo, lower-cased as `str::to_lowercase` does +/// for each field alone: file name, title, caption, camera, lens, location, format, then each +/// keyword, then the name of each person (a named face), separated by NUL. A search word may hold +/// white space (a quoted phrase); one that holds NUL is read from the fields one by one +/// ([`PhotoText::field_contains`]), so no word runs over a field. +pub(crate) struct PhotoText { + /// The address of the photo this was made from ([`addr`]). + at: usize, + text: Box, +} + +impl PhotoText { + /// The fields of `p` that the text joins before its keywords and people. + fn fields(p: &Photo) -> [&String; 7] { + [&p.file_name, &p.meta.title, &p.meta.caption, &p.meta.camera, &p.meta.lens, &p.meta.location, &p.format] + } + + pub(crate) fn of(p: &Photo) -> PhotoText { + let fields = Self::fields(p); + let people = p.people(); + // (exact for ASCII, which most text is: the box takes the buffer without copying it) + let len = fields + .iter() + .map(|f| f.len() + 1) + .chain(p.meta.keywords.iter().map(|k| k.len() + 1)) + .chain(people.iter().map(|n| n.len() + 1)) + .sum::() + .saturating_sub(1); + let mut text = String::with_capacity(len); + for (i, field) in fields.into_iter().enumerate() { + if i > 0 { + text.push('\0'); + } + push_lowercase(&mut text, field); + } + for k in p.meta.keywords.iter().map(String::as_str).chain(people) { + text.push('\0'); + push_lowercase(&mut text, k); + } + PhotoText { at: addr(p), text: text.into_boxed_str() } + } + + /// Whether the lower-cased word `t` is in the file name, title, caption, camera, lens, + /// location, format, a keyword or the name of a person. + pub(crate) fn contains(&self, t: &str) -> bool { + self.text.contains(t) + } + + /// [`PhotoText::contains`] read from `p`'s fields one by one, for a word that holds NUL: the joined text can't tell + /// the NUL that separates two fields from one inside a field, and a word never runs over two fields. + pub(crate) fn field_contains(p: &Photo, t: &str) -> bool { + Self::fields(p) + .into_iter() + .map(String::as_str) + .chain(p.meta.keywords.iter().map(String::as_str)) + .chain(p.people()) + .any(|f| f.to_lowercase().contains(t)) + } + + #[cfg(test)] + pub(crate) fn text(&self) -> &str { + &self.text + } +} + +/// Push `s` lower-cased as `str::to_lowercase` gives it, without a temporary string for ASCII. +fn push_lowercase(out: &mut String, s: &str) { + if s.is_ascii() { + let from = out.len(); + out.push_str(s); + if let Some(added) = out.get_mut(from..) { + added.make_ascii_lowercase(); + } + } else { + out.push_str(&s.to_lowercase()); + } +} + +/// A photo's text for a smart album's Text rule: [`crate::rules::rule_text`]. +struct RuleText { + at: usize, + text: Box, +} + +impl RuleText { + fn of(p: &Photo) -> RuleText { + RuleText { at: addr(p), text: crate::rules::rule_text(p).into_boxed_str() } + } +} + fn rekey(m: &mut HashMap>, id: PhotoId, old: Option, new: Option) { if let Some(k) = old && let Some(set) = m.get_mut(&k) @@ -166,7 +368,29 @@ fn sorted(set: Option<&HashSet>) -> Vec { v } +/// The content photo `p` stands for in the library: its file's hash, without the `:dup` a Duplicate's carries. +/// `None` for a photo with no hash, a virtual copy (the same photo as its master, not another one), a photo in +/// Recently Deleted and one only browsed in Local. +pub(crate) fn content_key(p: &Photo) -> Option<&str> { + if p.copy_of.is_some() || p.deleted || p.local { + return None; + } + p.content_hash.as_deref().map(|h| h.split(':').next().unwrap_or(h)).filter(|h| !h.is_empty()) +} + impl Catalog { + /// The smart albums that lead back to themselves through the albums they test, worked out once + /// (by [`crate::AlbumGraph`]) and kept until an album is added, removed or has its rules changed. + pub(crate) fn looping(&self) -> &BTreeSet { + self.index.looping.get_or_init(|| crate::AlbumGraph::of(self.albums.values()).on_a_loop()) + } + + /// Whether the albums on a loop are worked out and kept now (what the tests look at). + #[cfg(test)] + pub(crate) fn loops_known(&self) -> bool { + self.index.looping.get().is_some() + } + /// The stack photo `photo` is in, by the index (built on first use). pub(crate) fn stack_id_of(&self, photo: PhotoId) -> Option { let m = self.index.stacks.get_or_init(|| { @@ -193,6 +417,86 @@ impl Catalog { m.get(&album).is_some_and(|s| s.contains(&photo)) } + /// `p`'s lower-cased text for the free-text search, when `p` is this catalog's own photo and the + /// text was made. `build`: make it for every photo first when it wasn't (a pass over the whole + /// library does; testing one photo shouldn't build it for 300 000). + pub(crate) fn search_text(&self, p: &Photo, build: bool) -> Option<&PhotoText> { + let m = if build { + self.index.search.get_or_init(|| self.photos.values().map(|p| (p.id, PhotoText::of(p))).collect()) + } else { + self.index.search.get()? + }; + m.get(&p.id).filter(|t| t.at == addr(p)) + } + + /// [`Catalog::search_text`] for a smart album's Text rule: the lower-cased, trimmed text of + /// [`crate::rules::rule_text`], made for every photo on first use (a smart album's count or + /// view asks for it photo by photo). + pub(crate) fn rule_text_of(&self, p: &Photo) -> Option<&str> { + let m = self.index.rule_text.get_or_init(|| self.photos.values().map(|p| (p.id, RuleText::of(p))).collect()); + let t = m.get(&p.id)?; + (t.at == addr(p)).then_some(&*t.text) + } + + /// Whether the Text rules' text has been made (asking for it makes it, so a test cannot look with + /// [`Catalog::rule_text_of`]). + #[cfg(test)] + pub(crate) fn rule_text_made(&self) -> bool { + self.index.rule_text.get().is_some() + } + + /// Content → its photos, by the index (built on first use). + fn contents(&self) -> &HashMap> { + self.index.contents.get_or_init(|| { + let mut m: HashMap> = HashMap::with_capacity(self.photos.len()); + for p in self.photos.values() { + if let Some(k) = content_key(p) { + m.entry(k.to_string()).or_default().push(p.id); + } + } + m + }) + } + + /// Whether another photo of the library has the same content as `p` ([`content_key`]). + pub fn has_same_content(&self, p: &Photo) -> bool { + content_key(p).is_some_and(|k| self.contents().get(k).is_some_and(|ids| ids.iter().any(|id| *id != p.id))) + } + + /// Whether ops have to follow photos' contents ([`Catalog::content_moved`]): the index was built (a rule + /// asked), or a smart album asks (whose count may be followed from a copy of the catalog that built its own). + /// Else nothing has asked, and a library that never does carries no index. + pub(crate) fn follows_contents(&self) -> bool { + self.index.contents.get().is_some() + || *self.index.contents_asked.get_or_init(|| { + self.albums.values().any(|a| a.smart.as_ref().and_then(|f| f.rule_set.as_ref()).is_some_and(|r| r.reads("sameContent"))) + }) + } + + /// The content photo `id` stands for now ([`content_key`]). + pub(crate) fn content_of(&self, id: PhotoId) -> Option { + self.photos.get(&id).and_then(|p| content_key(p)).map(str::to_string) + } + + /// The op just applied took photo `id` from content `old` to `new` ([`Catalog::follows_contents`]): the index + /// follows, and the photos with either content are touched too ([`Catalog::touched_since`]), as whether they + /// have the same content as another photo may have changed with it. + pub(crate) fn content_moved(&mut self, id: PhotoId, old: Option, new: Option) { + if old == new { + return; + } + let built = self.index.contents.get().is_some(); + // (built now if it wasn't: from the catalog as it is, this op included, which holds the same other photos) + let twins: Vec = + [&old, &new].into_iter().flatten().filter_map(|k| self.contents().get(k.as_str())).flatten().copied().filter(|p| *p != id).collect(); + if built { + self.index.content_changed(id, old.as_deref(), new); + } + for p in twins { + self.touch(p); + } + } + fn file_index(&self, which: &str, key: fn(&str) -> Option) -> HashMap> { let t = web_time::Instant::now(); let mut m: HashMap> = HashMap::new(); diff --git a/crates/catalog/src/journal.rs b/crates/catalog/src/journal.rs index fc93ea9f13..0d0987d6f4 100644 --- a/crates/catalog/src/journal.rs +++ b/crates/catalog/src/journal.rs @@ -47,7 +47,9 @@ //! # Format versions //! //! The snapshot's `version` is the catalog format, and it covers the log beside it: the log has -//! no header of its own, and is only ever appended to under a snapshot of this build's format. +//! no header of its own, and is appended to under a snapshot of this build's format. (Except +//! for a library left in an older format because its files could not be kept or its upgrade +//! written: it goes on as it is, and its log gets this build's ops until a snapshot upgrades it.) //! //! | Version | Written by | Adds | //! |---|---|---| @@ -65,6 +67,7 @@ //! | 11 | lens database profiles named in the Optics panel | `EmbeddedLens.source` | //! | 12 | history steps and versions share segmentation grids (#2154) | `Catalog.grids`, `SegMask.grid` | //! | 13 | Lens Blur | `DevelopSettings.lens_blur`, `Mask.adjust.lens_blur` | +//! | 14 | bursts arranged by hand in Assisted Culling | `Analysis.rank` | //! //! Rules: //! - **Bump [`VERSION`]** (and add a row above) in the change that adds an [`Op`] variant or a @@ -74,7 +77,27 @@ //! - **Opening an older format upgrades it**: right after loading, [`Journal::open`] writes a //! snapshot in this build's format (also for a new library), before anything is appended — so a //! library is never a mix, and older builds refuse it from then on instead of reading part of it. -//! [`LoadReport::upgraded_from`] says when that happened. +//! (Except where the upgrade can't be written or its files can't be kept: see the next rule.) +//! [`LoadReport::upgraded_from`] says when the upgrade happened at open. +//! - **An upgrade keeps what it replaces**: older builds can't read the upgraded library, so the +//! files it was are first kept beside it as `catalog.snap.v-` and +//! `catalog.log.v-` (`seq`: the last change they hold), byte for byte +//! ([`LoadReport::kept`]; a damaged log is kept under its own name instead, as it always was). +//! A file already there under one of the names above is never replaced or removed (a library +//! restored from an older backup can reach the same format and change as a set kept before): +//! other bytes make both names end `-2` (then `-3`, … up to 100 sets, then the upgrade is +//! refused), the same bytes are the copy already. Put back under +//! their own names, they are the library as the older build left it (what a later snapshot +//! keeps is the library as it was at open: a torn tail already cut, and what a session of this +//! build appended while it stayed in its old format, which an older build may refuse). They stay unless the +//! library on disk is known to be in its old format still: an upgrade at open that did not +//! happen leaves none of the copies it wrote (one that was there before stays), and one that was written keeps its copy whatever fails after it. +//! Nothing removes them afterwards: they are the user's to delete. (Not where the store says +//! there is no going back, [`Store::keeps_replaced_formats`].) A library left in its old format +//! at open (its files couldn't be kept, or the upgrade couldn't be written) is upgraded by a +//! later snapshot (compaction, or closing), which first keeps the files as they were at open +//! (the snapshot, and the log up to where it ended then) and is not written when it can't. Those +//! files stay even if that snapshot then fails and the library is still in its old format. //! - **A newer format is refused, untouched**: a snapshot whose `version` is above [`VERSION`], //! or a log record whose CRC matches (so it is exactly what was written) but whose op doesn't //! parse, fails [`Journal::open`] with [`CatalogError::Newer`] before any file is modified — it @@ -89,7 +112,7 @@ pub const LOG: &str = "catalog.log"; const FORMAT: &str = "lightcraft-catalog"; /// The catalog format this build writes (and the newest it reads). See the module docs → /// *Format versions*; bump it whenever an [`Op`] variant or a serialized field is added. -pub const VERSION: u32 = 13; +pub const VERSION: u32 = 14; /// When [`Journal::wants_snapshot`] says it's time to compact the log. #[derive(Clone, Copy, Debug)] @@ -104,6 +127,29 @@ impl Default for SnapshotPolicy { } } +/// How much an upgrade to this build's format is needed (see [`Journal::upgrade`]). +#[derive(Clone, Copy, PartialEq, Eq)] +enum Upgrade { + /// The library may go on as it is if it can't be upgraded now. + May, + /// The library can't be used as it is: its damaged log would be appended to after the damage, + /// so the snapshot must also have replaced that log. + Repair, +} + +/// The files kept for one upgrade (see [`Journal::keep_replaced`]). +#[derive(Default)] +struct Kept { + /// All of them: the snapshot, then the log. + names: Vec, + /// Those this attempt wrote. The others were there already, byte for byte the same. + created: Vec, +} + +/// How many sets of kept files with the same format and change can stand side by side before a +/// further one is refused (an upgrade that can't keep its files is not done). +const MAX_KEPT_COPIES: u32 = 100; + /// What happened while loading. #[derive(Clone, Debug, Default, PartialEq)] pub struct LoadReport { @@ -129,6 +175,13 @@ pub struct LoadReport { pub upgraded_from: Option, /// What [`Catalog::repair`] changed in a damaged snapshot (empty for a sound one). pub repaired: Vec, + /// The files that upgrade replaced, kept beside the library under these names (the snapshot, + /// then the log; a file there was none of has no copy). + pub kept: Vec, + /// The store keeps the files an upgrade replaces ([`Store::keeps_replaced_formats`]): a + /// store that doesn't (the browser's) has no copy of the library as it was, whatever else it + /// set aside (a damaged log). + pub kept_files: bool, } /// Where persistence time goes (reported by `library.info` → `persistence`; printed to stderr @@ -195,6 +248,21 @@ pub struct Journal { /// `seq` of the last durable op. seq: u64, snapshot_seq: u64, + /// The snapshot in the store is still in an older format (`Some(format)`): the library was + /// not upgraded at open, because its files could not be kept or the upgrade could not be + /// written. A later snapshot (a compaction, or closing) writes the upgrade then, + /// and keeps the files first ([`Journal::keep_before_upgrade`]). + behind: Option, + /// What the library was at open while `behind` is set: the `seq` its files held and the + /// length of its log. Appends only add to the log after that, so the first `log_len` bytes + /// and the snapshot are the library as this session opened it, whatever is appended + /// meanwhile (an earlier session of this build may have appended already, while the library + /// stayed in its old format: that is in them, and an older build may refuse it). + behind_at: (u64, u64), + /// The files [`Journal::keep_before_upgrade`] kept for a snapshot that is not written yet, + /// and, once that snapshot is, the names for [`Journal::take_kept`]. + kept_pending: Option>, + kept_written: Vec, log_records: u64, log_bytes: u64, pub policy: SnapshotPolicy, @@ -428,23 +496,27 @@ struct SnapFile { impl Journal { /// Open (or create) the catalog in `store`: load the snapshot, replay the log, repair a torn - /// tail. Fails only if the snapshot itself is unreadable (then nothing is modified). + /// tail. Fails if the snapshot is unreadable or a newer LightCraft's (then nothing is + /// modified), or if the library is in an older format and its damaged log can't be replaced, + /// its snapshot can't be kept, or it can't be told whether its upgrade was written (see the + /// module docs → *Format versions*). pub fn open(mut store: Box) -> Result<(Journal, Catalog, LoadReport)> { let mut report = LoadReport::default(); let snap = store.read(SNAPSHOT).map_err(io)?; let log = store.read(LOG).map_err(io)?; report.created = snap.is_none() && log.is_none(); - let (mut catalog, snapshot_seq, snapshot_version) = match snap { + report.kept_files = store.keeps_replaced_formats(); + let (mut catalog, snapshot_seq, snapshot_version) = match &snap { Some(bytes) => { // the header first: a newer snapshot may not parse as this version's catalog - let h: SnapHeader = serde_json::from_slice(&bytes).map_err(|e| CatalogError::Corrupt(format!("{SNAPSHOT}: {e}")))?; + let h: SnapHeader = serde_json::from_slice(bytes).map_err(|e| CatalogError::Corrupt(format!("{SNAPSHOT}: {e}")))?; if h.format != FORMAT { return Err(CatalogError::Corrupt(format!("{SNAPSHOT}: not a LightCraft catalog (format {:?})", h.format))); } if h.version > VERSION { return Err(newer(format!("{SNAPSHOT} is catalog format v{}", h.version))); } - let s: SnapFile = serde_json::from_slice(&bytes).map_err(|e| CatalogError::Corrupt(format!("{SNAPSHOT}: {e}")))?; + let s: SnapFile = serde_json::from_slice(bytes).map_err(|e| CatalogError::Corrupt(format!("{SNAPSHOT}: {e}")))?; // a seq this high can't come from real use; the next record's seq would wrap if s.seq > MAX_SEQ { return Err(CatalogError::Corrupt(format!("{SNAPSHOT}: seq {} is out of range", s.seq))); @@ -463,6 +535,10 @@ impl Journal { store, seq: snapshot_seq, snapshot_seq, + behind: None, + behind_at: (0, 0), + kept_pending: None, + kept_written: Vec::new(), log_records: 0, log_bytes: 0, policy: SnapshotPolicy::default(), @@ -512,7 +588,9 @@ impl Journal { report.stale += 1; } Some((seq, op)) if j.seq.checked_add(1) == Some(seq) => { - if catalog.apply(op).is_err() { + // (a batch that was only partly taken back when it was applied is logged as it was: replaying it is + // not damage, see `Catalog::replay_op`) + if catalog.replay_op(op).is_err() { report.failed += 1; } else { report.replayed += 1; @@ -542,12 +620,23 @@ impl Journal { needs_newline = !has_nl; } + // An older (or snapshot-less) library is brought to this build's format before anything + // is appended: a snapshot in this format makes older builds refuse the library instead + // of misreading ops or dropping fields they don't know. + let older = (!report.created && snapshot_version != Some(VERSION)).then(|| snapshot_version.unwrap_or(0)); if let Some(at) = damaged_at { let name = format!("{LOG}.damaged-{}", j.seq); j.store.write_atomic(&name, &log).map_err(io)?; log::warn!("catalog log damaged at byte {at}; kept as {name}; state recovered up to op {}", j.seq); report.damaged = Some(name); - j.snapshot(&catalog)?; + match older { + // (its log goes either way: the snapshot it was is kept like any other upgrade's) + Some(from) => { + report.kept = j.upgrade(&catalog, from, snap.as_deref(), &[], Upgrade::Repair)?.unwrap_or_default(); + report.upgraded_from = Some(from); + } + None => j.snapshot(&catalog)?, + } } else { if good_end < log.len() { report.torn_bytes = (log.len() - good_end) as u64; @@ -561,31 +650,210 @@ impl Journal { j.log_bytes = good_end as u64; } } - // Bring an older (or new, or snapshot-less) library to this version's format before - // anything is appended: a snapshot in this format makes older builds refuse the library - // instead of misreading ops or dropping fields they don't know. if report.created { // tiny: written directly, not counted as a compaction let empty = format!("{{\"format\":\"{FORMAT}\",\"version\":{VERSION},\"seq\":0,\"catalog\":{}}}\n", catalog.to_snapshot()); if let Err(e) = j.store.write_atomic(SNAPSHOT, empty.as_bytes()) { log::warn!("catalog: can't write the new library's snapshot: {e}"); } - } else if report.damaged.is_none() && snapshot_version != Some(VERSION) { - report.upgraded_from = Some(snapshot_version.unwrap_or(0)); - match j.snapshot(&catalog) { - Ok(()) => { - if let Some(v) = report.upgraded_from { - log::info!("catalog: upgraded from format v{v} to v{VERSION}"); - } - } - // nothing lost: the old files are intact and still load; retried on next open - Err(e) => log::warn!("catalog: can't write the format v{VERSION} snapshot: {e}"), + } else if let (Some(from), None) = (older, &report.damaged) { + // The library may go on as it is when it can't be upgraded now (the next open tries + // again). Appends are not refused meanwhile: refusing them would leave a library + // whose files can't be copied (little room left) unable to save anything. What is + // appended is this build's ops; the files kept when a later snapshot upgrades it are + // the library as it is here (`behind_at`), which an older build reads. + if let Some(kept) = j.upgrade(&catalog, from, snap.as_deref(), &log, Upgrade::May)? { + report.upgraded_from = Some(from); + report.kept = kept; + } else { + j.behind = Some(from); + j.behind_at = (j.seq, j.log_bytes); } } catalog.revision = 0; Ok((j, catalog, report)) } + /// Bring a library in format `from` to this build's: keep the files it was (`snap` and `log`, + /// see [`Journal::keep_replaced`]), then write the snapshot. `Some`: upgraded, with the names + /// of the files kept. `None` (only with [`Upgrade::May`]): not upgraded, and as it was, with + /// nothing kept. Otherwise that is an error: the library can't be used as it is. + /// + /// The kept files stay unless the library on disk is known to be in its old format still: + /// also when the snapshot was committed and something after it failed (emptying the log), + /// and when what is on disk can't be read to say. + fn upgrade(&mut self, catalog: &Catalog, from: u32, snap: Option<&[u8]>, log: &[u8], how: Upgrade) -> Result>> { + let refused = |what: &str, e: String| CatalogError::Io(format!("the library is in an older format (v{from}) and {what}: {e}")); + let kept = match self.keep_replaced(from, snap, log) { + Ok(kept) => kept, + Err(e) if how == Upgrade::May => { + // not upgraded without its way back: it opens as it is; retried on next open + log::warn!("catalog: can't keep the format v{from} files, so the library is not upgraded: {e}"); + return Ok(None); + } + Err(e) => return Err(refused("its files can't be kept before it is upgraded", e.to_string())), + }; + if let Err(e) = self.snapshot(catalog) { + match self.on_disk_version() { + // Committed all the same (the log could not be emptied): the library is upgraded, + // and its way back stays. Its log's records are in the snapshot and are passed + // over when it is read. Not so a damaged log, which would be appended to after + // its damage: the next open has to deal with it first. + Some(Some(VERSION)) if how != Upgrade::Repair => log::warn!("catalog: upgraded to format v{VERSION}, but: {e}"), + Some(Some(VERSION)) => return Err(refused("was upgraded, but its damaged log is still in place", e.to_string())), + // what is on disk can't be read to say: the way back stays + None => return Err(refused("it can't be told whether its upgrade was written", e.to_string())), + // Nothing lost: the old files are intact and still load. No copy of them from this + // attempt stays: there is nothing to go back from. + Some(_) => { + self.forget_kept(&kept.created); + if how != Upgrade::May { + return Err(refused("can't be upgraded", e.to_string())); + } + log::warn!("catalog: can't write the format v{VERSION} snapshot: {e}"); + return Ok(None); + } + } + } + log::info!("catalog: upgraded from format v{from} to v{VERSION}; the files it was are kept as {:?}", kept.names); + Ok(Some(kept.names)) + } + + /// The format of the snapshot in the store: `Some(None)` where there is none, `None` where + /// it can't be read to say. + fn on_disk_version(&mut self) -> Option> { + match self.store.read(SNAPSHOT) { + Ok(None) => Some(None), + Ok(Some(bytes)) => serde_json::from_slice::(&bytes).ok().map(|h| Some(h.version)), + Err(_) => None, + } + } + + /// Keep the files of a library in format `from` before an upgrade replaces them: `snap` and + /// `log` as they were read, under names that say their format and the last change they hold. + /// Returns the names (none where the store keeps none). All or nothing: on an error, what + /// this call wrote is removed again. + /// + /// A file that is in the way is never replaced or removed: a library restored from an older + /// backup can reach the same format and change as a set kept before, with other bytes. The + /// names then end `-2`, `-3`, … (for both files alike), the first that holds nothing, or + /// these very bytes (that file is reused, and is not this call's to remove). + fn keep_replaced(&mut self, from: u32, snap: Option<&[u8]>, log: &[u8]) -> std::io::Result { + let mut kept = Kept::default(); + if !self.store.keeps_replaced_formats() { + return Ok(kept); + } + let seq = self.seq; + let files: Vec<(&str, &[u8])> = + [(SNAPSHOT, snap), (LOG, (!log.is_empty()).then_some(log))].into_iter().filter_map(|(name, bytes)| Some((name, bytes?))).collect(); + // (nothing is written until every name of the set is known to be free or ours) + let mut plan: Vec<(String, &[u8], bool)> = Vec::new(); + 'sets: for copy in 1..=MAX_KEPT_COPIES { + plan.clear(); + for &(name, bytes) in &files { + let name = if copy == 1 { format!("{name}.v{from}-{seq}") } else { format!("{name}.v{from}-{seq}-{copy}") }; + match self.store.read(&name)? { + None => plan.push((name, bytes, true)), + Some(there) if there == bytes => plan.push((name, bytes, false)), + Some(_) => continue 'sets, + } + } + break; + } + if plan.len() != files.len() { + return Err(std::io::Error::other(format!("{MAX_KEPT_COPIES} sets of files kept as format v{from} at change {seq} are in the way"))); + } + for (name, bytes, write) in plan { + if write { + if let Err(e) = self.store.write_atomic(&name, bytes) { + // (a write that says it failed may have landed all the same, a network share that + // dropped its answer: the name was free, so what is there now is this call's) + kept.created.push(name); + self.forget_kept(&kept.created); + return Err(e); + } + kept.created.push(name.clone()); + } + kept.names.push(name); + } + Ok(kept) + } + + /// Remove kept files that keep nothing (the upgrade they were for did not happen): only + /// those a call of [`Journal::keep_replaced`] wrote, never one that was there before. + fn forget_kept(&mut self, created: &[String]) { + for name in created { + if let Err(e) = self.store.remove(name) { + log::warn!("catalog: can't remove {name}: {e}"); + } + } + } + + /// A library that was left in an older format at open (see `behind`) keeps its files, as + /// they were then, before a snapshot upgrades it: the snapshot as it is (nothing writes it + /// until the upgrade) and the log up to its length at open (what was appended since is this + /// build's, which an older build may refuse). The names are those the open would have kept + /// them under (a name taken since ends `-2`, … as there), so files kept for an upgrade that + /// did not land are not left behind under other names. Kept once: when a snapshot failed and is tried again, they stay as they are + /// (the failed one may have landed all the same, and the snapshot is then no longer what + /// could be kept). A snapshot that is already in this build's format (that landed after its + /// files were kept, or before them, reporting a failure) is the upgrade done, with nothing + /// to keep. An error means they could not be kept (or read): the snapshot is not written, so + /// the library stays as it was, with its way back. + fn keep_before_upgrade(&mut self) -> Result<()> { + let Some(from) = self.behind else { return Ok(()) }; + if self.kept_pending.is_some() { + return Ok(()); + } + let snap = self.store.read(SNAPSHOT).map_err(io)?; + if let Some(bytes) = snap.as_deref() { + match serde_json::from_slice::(bytes).ok().map(|h| h.version) { + Some(v) if v == from => {} + // the upgrade is written already: the snapshot after it is a plain one + Some(VERSION) => { + self.upgraded_later(); + return Ok(()); + } + _ => return Err(CatalogError::Io(format!("the snapshot is no longer in format v{from}, and can't be kept as it was"))), + } + } + let mut log = self.store.read(LOG).map_err(io)?.unwrap_or_default(); + let (seq, log_len) = self.behind_at; + log.truncate(usize::try_from(log_len).unwrap_or(usize::MAX)); + let at = std::mem::replace(&mut self.seq, seq); + let kept = self.keep_replaced(from, snap.as_deref(), &log); + self.seq = at; + let kept = kept.map_err(io)?; + log::info!("catalog: the files of format v{from} are kept as {:?} before the upgrade", kept.names); + self.kept_pending = Some(kept.names); + Ok(()) + } + + /// The snapshot that upgrades a library left behind is durable: the files kept for it are + /// now the library's way back, for [`Journal::take_kept`] to tell. + fn upgraded_later(&mut self) { + self.behind = None; + if let Some(kept) = self.kept_pending.take() { + self.kept_written.extend(kept); + } + } + + /// A snapshot reported a failure: one that landed all the same (a share that dropped its answer) and is in this + /// build's format did the upgrade, so the files kept for it are the way back now, to be told without waiting for + /// a later snapshot that succeeds. + fn upgraded_despite_error(&mut self) { + if self.behind.is_some() && self.on_disk_version() == Some(Some(VERSION)) { + self.upgraded_later(); + } + } + + /// The files a snapshot kept when it upgraded a library that was left in an older format at + /// open (see `behind`), once, after it was written: [`LoadReport::kept`] has only what the + /// open kept. Empty when there are none. + pub fn take_kept(&mut self) -> Vec { + std::mem::take(&mut self.kept_written) + } + /// Append ops (already applied to the live catalog) durably, in order. pub fn append(&mut self, ops: &[Op]) -> Result<()> { if ops.is_empty() { @@ -648,10 +916,17 @@ impl Journal { } let t0 = web_time::Instant::now(); let seq = self.seq.checked_add(unlogged).ok_or_else(|| CatalogError::Corrupt(format!("{SNAPSHOT}: op counter overflow")))?; + if let Err(e) = self.keep_before_upgrade() { + // not upgraded without its way back; try again later like any failed snapshot + self.stats.failed_snapshots += 1; + self.retry_at_records = self.log_records + self.policy.max_records; + return Err(e); + } let mut timing = match write_snapshot(self.store.as_mut(), seq, catalog) { Ok(t) => t, Err(e) => { // nothing lost (the log is whole); don't retry on every append + self.upgraded_despite_error(); self.stats.failed_snapshots += 1; self.retry_at_records = self.log_records + self.policy.max_records; return Err(io(e)); @@ -660,6 +935,7 @@ impl Journal { // the snapshot is durable: it holds every op up to `seq` self.seq = seq; self.snapshot_seq = seq; + self.upgraded_later(); let t2 = web_time::Instant::now(); // A crash here leaves old records in the log; they are skipped by seq on load. self.store.write_atomic(LOG, b"").map_err(io)?; @@ -684,6 +960,11 @@ impl Journal { return Ok(()); } let t0 = web_time::Instant::now(); + if let Err(e) = self.keep_before_upgrade() { + self.stats.failed_snapshots += 1; + self.retry_at_records = self.log_records + self.policy.max_records; + return Err(e); + } let Some(mut writer) = self.store.background_writer() else { return self.snapshot(catalog) }; let copy = catalog.clone(); let seq = self.seq; @@ -737,6 +1018,7 @@ impl Journal { Ok(t) => t, Err(e) => { // the log still holds every record: nothing lost, retry later + self.upgraded_despite_error(); self.stats.failed_snapshots += 1; self.retry_at_records = self.log_records + self.policy.max_records; log::error!("catalog: background snapshot failed: {e}"); @@ -747,6 +1029,7 @@ impl Journal { // Keep exactly the ones appended since (a crash before this rewrite skips the stale ones). let t1 = web_time::Instant::now(); self.snapshot_seq = p.seq; + self.upgraded_later(); if let Err(e) = self.store.write_atomic(LOG, &p.tail) { // the log stays whole (stale records are skipped on load); compact again later self.retry_at_records = self.log_records + self.policy.max_records; diff --git a/crates/catalog/src/keywords.rs b/crates/catalog/src/keywords.rs index c6bea67520..ccc892044a 100644 --- a/crates/catalog/src/keywords.rs +++ b/crates/catalog/src/keywords.rs @@ -10,7 +10,7 @@ //! photo has them, or given attributes ([`KeywordInfo`]: synonyms, export options, person). The //! tree is the keyword list together with the keywords photos carry. -use std::collections::BTreeMap; +use std::collections::{BTreeMap, HashSet}; use serde::{Deserialize, Serialize}; @@ -42,6 +42,12 @@ pub fn is_under(k: &str, parent: &str) -> bool { k == p || k.strip_prefix(&p).is_some_and(|rest| rest.starts_with(SEP)) } +/// The upper levels of a case folded keyword path, each as a prefix of it ending before a `|` +/// (`a|b|c` gives `a`, `a|b`), the way [`is_under`] sees them. +fn upper_levels(folded: &str) -> impl Iterator { + folded.match_indices(SEP).map(|(i, _)| &folded[..i]) +} + /// Replace the `from` prefix of `k` (which [`is_under`] `from`) with `to`. By levels, not bytes: /// `from` may be written in another case, which can change a letter's length (ẞ / ß). pub fn reparent(k: &str, from: &str, to: &str) -> String { @@ -80,17 +86,39 @@ pub fn to_file(keywords: &[String]) -> FileKeywords { /// A file's keywords as a photo carries them: the paths of `lr:hierarchicalSubject`, then the /// names of `dc:subject` that aren't levels of those paths (Lightroom Classic writes each keyword's /// name, its parents' and synonyms flat besides its path). Each once, cleaned. +/// +/// An entry holding several lines is several keywords: some cameras' metadata presets write the +/// whole list as one `dc:subject` item, a keyword a line ("Beautiful Bride Bride and +/// Groom…"). Read as one, it would be a single keyword many lines tall. pub fn from_file(flat: &[String], hierarchical: &[String]) -> Vec { - let mut out: Vec = hierarchical.iter().map(|k| clean(k)).collect(); + let lines = |v: &[String]| -> Vec { v.iter().flat_map(|k| split_lines(k)).collect() }; + let (flat, hierarchical) = (lines(flat), lines(hierarchical)); + let mut out: Vec = hierarchical.iter().map(|k| clean(k)).filter(|k| !k.is_empty()).collect(); // One lowered set of every hierarchical level, not a search of `hierarchical` for each flat // keyword: disjoint lists from sidecars made the old approach quadratic in both (CWE-407), and // `same` allocates two lower-cased strings per comparison. let levels: std::collections::HashSet = hierarchical.iter().flat_map(|h| h.split(SEP).map(|l| l.trim().to_lowercase())).collect(); - out.extend(flat.iter().map(|k| clean(k)).filter(|k| !levels.contains(&k.to_lowercase()))); + out.extend(flat.iter().map(|k| clean(k)).filter(|k| !k.is_empty()).filter(|k| !levels.contains(&k.to_lowercase()))); dedupe(&mut out); out } +/// The keywords of one metadata entry: one a line (any of `\r`, `\n`, the Unicode line and +/// paragraph separators), blank lines dropped. +pub fn split_lines(k: &str) -> Vec { + k.split(['\r', '\n', '\u{2028}', '\u{2029}']).map(str::trim).filter(|l| !l.is_empty()).map(str::to_string).collect() +} + +/// `text` on one line: line breaks become spaces (a name drawn in a row must never spill over +/// the rows around it). +pub fn one_line(text: &str) -> std::borrow::Cow<'_, str> { + if text.contains(['\r', '\n', '\u{2028}', '\u{2029}']) { + std::borrow::Cow::Owned(split_lines(text).join(" ")) + } else { + std::borrow::Cow::Borrowed(text) + } +} + /// The deepest a keyword list file may nest keywords: a file is input, so its nesting is bounded. pub const MAX_LEVELS: usize = 64; @@ -466,6 +494,97 @@ impl Catalog { Ok(Op::Batch { ops }) } + /// [`Self::delete_keyword_ops`] for several keywords at once: one batch, so one undo step. + /// Unlike one keyword (which may be absent and then changes nothing), every keyword named must + /// exist, or the whole batch is refused. + pub fn delete_keywords_ops(&self, keywords: &[String]) -> Result { + let gone: Vec = keywords.iter().map(|k| clean(k)).collect(); + if gone.is_empty() || gone.iter().any(String::is_empty) { + return Err(CatalogError::Invalid("empty keyword".into())); + } + // case folded once here, and each candidate once below, not once per pair + let folded: Vec = gone.iter().map(|g| g.to_lowercase()).collect(); + let under = |k: &str, p: &str| k == p || k.strip_prefix(p).is_some_and(|rest| rest.starts_with(SEP)); + let mut found = vec![false; folded.len()]; + let listed = self.keyword_list.values().map(|l| &l.path); + for k in listed.chain(self.photos().filter(|p| p.in_library()).flat_map(|p| p.meta.keywords.iter())) { + let k = k.to_lowercase(); + for (hit, p) in found.iter_mut().zip(&folded) { + *hit |= under(&k, p); + } + } + if let Some(i) = found.iter().position(|hit| !hit) { + return Err(CatalogError::Invalid(format!("no keyword “{}”", gone[i]))); + } + let goes = |k: &str| { + let k = k.to_lowercase(); + folded.iter().any(|p| under(&k, p)) + }; + let mut ops = self.keyword_ops(|kws| kws.iter().filter(|x| !goes(x)).cloned().collect()); + ops.extend(self.list_ops(|list| list.retain(|_, l| !goes(&l.path)))); + Ok(Op::Batch { ops }) + } + + /// Move several keywords (each with the keywords below it) inside `parent`, or to the top + /// level (`None`), as one batch. Each keeps its name. Of a keyword and one below it only the + /// upper one moves (the lower goes with it). Nothing merges here: a name that is taken where + /// they go ([`CatalogError::KeywordExists`]), or two of them with one name, refuses the whole + /// move. Returns the batch and each move as `(from, to)`. + pub fn move_keywords_ops(&self, keywords: &[String], parent: Option<&str>) -> Result<(Op, Vec<(String, String)>)> { + // paths are case folded once and kept in sets: a batch of thousands stays linear + let mut from: Vec = Vec::new(); + let mut seen: HashSet = HashSet::new(); + for k in keywords { + let path = self.keyword_path(k).ok_or_else(|| CatalogError::Invalid(format!("no keyword “{}”", clean(k))))?; + if seen.insert(path.to_lowercase()) { + from.push(path); + } + } + if from.is_empty() { + return Err(CatalogError::Invalid("no keyword to move".into())); + } + // the upper ones only: a keyword goes when one of its upper levels is named too + from.retain(|f| !upper_levels(&f.to_lowercase()).any(|up| seen.contains(up))); + let upper: HashSet = from.iter().map(|f| f.to_lowercase()).collect(); + let parent = parent.map(clean).filter(|p| !p.is_empty()).map(|p| self.keyword_path(&p).unwrap_or(p)); + if let Some(p) = &parent { + let p = p.to_lowercase(); + if upper.contains(&p) || upper_levels(&p).any(|up| upper.contains(up)) { + return Err(CatalogError::Invalid("can't move a keyword inside itself".into())); + } + } + let mut moves: Vec<(String, String)> = Vec::new(); + let mut names: HashSet = HashSet::new(); + for f in &from { + let leaf = f.rsplit(SEP).next().unwrap_or(f); + let to = parent.as_deref().map_or_else(|| leaf.to_string(), |p| format!("{p}{SEP}{leaf}")); + if !names.insert(to.to_lowercase()) { + return Err(CatalogError::Invalid(format!("two of them are named “{leaf}”: move them one at a time"))); + } + moves.push((f.clone(), to)); + } + // one that is there already stays; the others must find their name free + moves.retain(|(f, t)| !same(f, t)); + if let Some((_, taken)) = moves.iter().find(|(_, t)| self.has_keyword(t)) { + return Err(CatalogError::KeywordExists(taken.clone())); + } + // case folded once here and once per photo keyword, not once per pair + let folded_from: Vec = moves.iter().map(|(f, _)| f.to_lowercase()).collect(); + let moved = |k: &str| { + let k_folded = k.to_lowercase(); + moves.iter().zip(&folded_from).find_map(|((f, t), f_folded)| { + let under = k_folded == *f_folded || k_folded.strip_prefix(f_folded.as_str()).is_some_and(|rest| rest.starts_with(SEP)); + under.then(|| reparent(k, f, t)) + }) + }; + let mut ops = self.keyword_ops(|kws| kws.iter().map(|k| moved(k).unwrap_or_else(|| k.clone())).collect()); + // (the moves touch apart parts of the list: each one's listings are its own) + for (f, t) in &moves { + ops.extend(self.list_move_ops(std::slice::from_ref(f), t)); + } + Ok((Op::Batch { ops }, moves)) + } + /// Merge several keywords (with their children) into `into`. pub fn merge_keywords_ops(&self, from: &[String], into: &str) -> Result { let into = clean(into); diff --git a/crates/catalog/src/keywords/tests.rs b/crates/catalog/src/keywords/tests.rs index 343a5cac34..284135daf4 100644 --- a/crates/catalog/src/keywords/tests.rs +++ b/crates/catalog/src/keywords/tests.rs @@ -1,6 +1,18 @@ use super::*; use crate::{Filter, Photo, PhotoId, Source}; +/// A camera preset's keyword list written as one `dc:subject` item, a keyword a line, is one +/// keyword a line; names stay one line wherever they are drawn. +#[test] +fn a_list_in_one_entry_is_a_keyword_a_line() { + let flat = vec!["Beautiful Bride\r\n Bride and Groom\r\n\r\n Happy Couple".to_string(), "Solo".to_string()]; + assert_eq!(from_file(&flat, &[]), vec!["Beautiful Bride", "Bride and Groom", "Happy Couple", "Solo"]); + assert_eq!(from_file(&["a\nb".to_string()], &["x|a".to_string()]), vec!["x|a", "b"], "a level of a path isn't listed twice"); + assert_eq!(one_line("a\r\n b"), "a b"); + assert!(matches!(one_line("plain"), std::borrow::Cow::Borrowed(_))); + assert!(split_lines("\r\n").is_empty()); +} + fn lib(kws: &[&[&str]]) -> (Catalog, Vec) { let mut c = Catalog::new(); let mut ids = Vec::new(); diff --git a/crates/catalog/src/lib.rs b/crates/catalog/src/lib.rs index a67a1b6617..61e5a04670 100644 --- a/crates/catalog/src/lib.rs +++ b/crates/catalog/src/lib.rs @@ -13,6 +13,7 @@ #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +pub mod bursts; pub mod dates; #[cfg(not(target_arch = "wasm32"))] #[doc(hidden)] @@ -30,6 +31,7 @@ pub mod opened_folder; pub mod query; pub mod rules; pub mod safe_file; +pub mod shared; pub mod stacks; pub mod store; pub mod tally; @@ -74,6 +76,12 @@ pub enum CatalogError { /// version doesn't know). Nothing was read into the session and nothing was modified. #[error("this library was written by a newer version of LightCraft ({0}); update LightCraft to open it. The library was left unchanged.")] Newer(String), + /// A batch failed, and rolling back what it had applied failed too: the catalog is not as it was, and part of + /// the batch stays. `remaining` is what is left of the rollback (applied in order, it takes the catalog back to + /// where it was before the batch), so the change can still be undone, and the batch itself is the record to keep + /// of it: replaying the batch from the same catalog fails the same way and leaves the same changes. + #[error("{cause}; the change was only partly taken back, so part of it stays")] + PartlyApplied { cause: Box, remaining: Box }, } pub type Result = std::result::Result; @@ -300,8 +308,8 @@ pub struct Catalog { /// references and clears the table when a snapshot is read. #[serde(default, skip_serializing_if = "Vec::is_empty")] grids: Vec, - /// Increments on every applied op, and when a batch fails and its rollback cannot undo it whole (the catalog - /// changed, so what is keyed by the revision is out of date). + /// Increments on every applied op, and when a batch fails and part of it stays ([`CatalogError::PartlyApplied`]): the + /// catalog changed, so what is keyed by the revision is out of date. #[serde(skip)] pub revision: u64, /// Which photos the latest ops touched ([`Catalog::touched_since`]). @@ -381,23 +389,46 @@ impl std::fmt::Debug for PlansMemo { } } +/// What [`resolve_grids`] has made of each value with references so far: the value as read (held +/// here so its address stays its own), what it resolved to and how many dangling references it +/// held. Holders that shared a value before resolving share the result, whatever else is between +/// them (a photo's settings and its last history step, with the earlier steps in between). +type ResolvedGrids = std::collections::HashMap<*const DevelopSettings, (Arc, Arc, usize)>; + /// Resolves the shared-grid references of one settings holder (see [`Photo::settings_holders`]) /// against a snapshot's grid table: each referenced mask takes its /// grid's data and the reference is cleared. A reference past the table (a damaged snapshot) /// leaves the mask empty — it renders nothing, like any other damaged grid. Data present on the /// mask itself wins over a stray reference. Returns the dangling count added to `dangling`. -fn resolve_grids(settings: &mut Arc, grids: &[String], dangling: usize) -> usize { - let mut dangling = dangling; +/// +/// Settings that refer to no grid (nearly all of them) are left alone, so a value shared by many +/// holders stays shared: [`Arc::make_mut`] would copy it for each. A value with references is +/// resolved once (`done`): every holder that held it takes the same result, which is handed to +/// [`shared::settings`], so holders that are equal once resolved share one value too. +fn resolve_grids(settings: &mut Arc, grids: &[String], dangling: usize, done: &mut ResolvedGrids) -> usize { + let mut referenced = false; + settings.visit_seg_masks(&mut |m| referenced |= m.grid.is_some()); + if !referenced { + return dangling; + } + if let Some((_, resolved, dangled)) = done.get(&Arc::as_ptr(settings)) { + *settings = resolved.clone(); + return dangling + dangled; + } + let original = settings.clone(); + let mut dangled = 0usize; Arc::make_mut(settings).visit_seg_masks_mut(&mut |m| { if let Some(i) = m.grid.take() { match (m.data.is_empty(), grids.get(i as usize)) { (true, Some(data)) => m.data = data.clone(), - (true, None) => dangling += 1, + (true, None) => dangled += 1, (false, _) => {} } } }); - dangling + *settings = shared::settings(settings.clone()); + done.insert(Arc::as_ptr(&original), (original, settings.clone(), dangled)); + dangling + dangled } /// A short memory of what the latest ops changed, so that what is derived from the catalog (the grid's list) can @@ -419,8 +450,10 @@ struct Changes { /// outside (a library just loaded takes a range of its own, so that nothing kept from another library is /// taken for this one's): nothing is known of how the catalog got to where it is. seen: u64, - /// A batch that failed could not be rolled back whole: what it changed stays, so what it noted must too. - torn: bool, + /// The inverses of a failed batch's ops that could not be applied when it was rolled back, in the order they + /// are to be applied (see [`CatalogError::PartlyApplied`]). Empty unless a rollback is under way or has just + /// failed; [`Catalog::apply`] hands it out. + leftover: Vec, } impl PartialEq for Changes { @@ -430,6 +463,14 @@ impl PartialEq for Changes { } } +/// `op` and, when it is a batch, the ops in it (nested batches too), each alone and in the order the batch lists them. +fn unbatch(op: Op, out: &mut Vec) { + match op { + Op::Batch { ops } => ops.into_iter().for_each(|op| unbatch(op, out)), + op => out.push(op), + } +} + impl Catalog { pub fn new() -> Catalog { Catalog { next_photo: 1, next_album: 1, next_stack: 1, ..Default::default() } @@ -569,8 +610,33 @@ impl Catalog { /// Whether smart album `id` with `rules` (as [`Filter::prepare`]d) holds `p`. fn smart_album_has(&self, id: AlbumId, rules: &Filter, prepared: &query::Prepared, p: &Photo) -> bool { - // guarded: a smart album testing smart albums can't loop or recurse without end - !p.deleted && rules::smart_album_holds(id, p.id, || rules.matches_in(p, self, prepared)) + // an album on a loop holds nothing, whoever asks (see `album_on_a_loop`); beyond that, a + // smart album testing smart albums can't recurse without end (the guard) + !p.deleted && !self.looping().contains(&id) && rules::smart_album_holds(id, p.id, || rules.matches_in(p, self, prepared)) + } + + /// Whether album `id` is on a loop: a smart album that includes itself, directly or through + /// the smart albums it tests. Such an album holds no photos ([`Self::album_photos`], + /// [`Self::album_count`], [`Self::album_contains`] and the grid all agree), until its rules or + /// those of an album on the loop change. An album that only tests a looping album is not on + /// the loop: it is worked out as usual, seeing the looping album as empty. + pub fn album_on_a_loop(&self, id: AlbumId) -> bool { + self.looping().contains(&id) + } + + /// For an album on a loop, an album it tests that leads back to it: the one to name when + /// saying why it is empty (itself when it tests itself and nothing else on the loop). `None` + /// for an album that is not on a loop. + pub fn album_loops_through(&self, id: AlbumId) -> Option { + if !self.album_on_a_loop(id) { + return None; + } + let tested = self.albums.get(&id)?.smart.as_deref()?.albums_tested(); + tested + .iter() + .copied() + .find(|b| *b != id && self.album_on_a_loop(*b) && self.album_reaches(*b, id)) + .or_else(|| tested.contains(&id).then_some(id)) } /// Whether smart album `from` tests `to`, directly or through the smart albums it tests (the @@ -687,7 +753,10 @@ impl Catalog { fn photo_mut(&mut self, id: PhotoId) -> Result<&mut Photo> { self.touch(id); - self.photos.get_mut(&id).map(Arc::make_mut).ok_or(CatalogError::NoPhoto(id)) + let p = self.photos.get_mut(&id).map(Arc::make_mut).ok_or(CatalogError::NoPhoto(id))?; + // (`Arc::make_mut` copies a photo others hold: the text kept for it goes with the copy) + self.index.text_moved(id, p); + Ok(p) } /// The op being applied changes photo `id` (or adds or removes it). @@ -714,28 +783,53 @@ impl Catalog { /// Whether every change since the catalog was at `revision` is remembered photo by photo. fn remembers(&self, revision: u64) -> bool { - self.changes.seen == self.revision && revision <= self.revision && revision >= self.changes.floor && self.changes.broad <= revision + self.remembers_photos(revision) && self.changes.broad <= revision + } + + /// Whether every change to a photo since the catalog was at `revision` is remembered. + fn remembers_photos(&self, revision: u64) -> bool { + self.changes.seen == self.revision && revision <= self.revision && revision >= self.changes.floor } /// The photos changed, added or removed since the catalog was at `revision`, each once. `None` when that is not /// known: an op since then changed more than photos of its own, or it was too long ago. Then anything may /// have changed. pub fn touched_since(&self, revision: u64) -> Option> { - if !self.remembers(revision) { - return None; - } - let mut ids: Vec = self.changes.touched.iter().filter(|(r, _, _)| *r > revision).map(|(_, id, _)| *id).collect(); + self.remembers(revision).then(|| self.touched_after(revision, Aspects::ALL)) + } + + /// The photos whose `reads` (what a tally reads of them) changed since the catalog was at + /// `revision`, added and removed photos included, each once; ops that change no photo of their + /// own (an album, a stack, the keyword list, a folder's label) and other things of a photo (a + /// rating, a slider) aside: for what is counted from the photos alone (the folders, days and + /// keywords they carry). `None` when that is not known: too long ago, or the catalog was set + /// from outside (a library loaded). + pub fn photos_changed_since(&self, revision: u64, reads: Aspects) -> Option> { + // (every op that changes a photo says which, in `photo_mut` or as it adds or removes it: + // the ops `apply_inner` marks broad change no photo) + self.remembers_photos(revision).then(|| self.touched_after(revision, reads)) + } + + fn touched_after(&self, revision: u64, reads: Aspects) -> Vec { + let mut ids: Vec = self + .changes + .touched + .iter() + .filter(|(r, _, a)| *r > revision && (reads == Aspects::ALL || a.any_of(reads))) + .map(|(_, id, _)| *id) + .collect(); ids.sort_unstable(); ids.dedup(); - Some(ids) + ids } fn album_mut(&mut self, id: AlbumId) -> Result<&mut Album> { self.albums.get_mut(&id).ok_or(CatalogError::NoAlbum(id)) } /// Apply an op; returns its inverse. On error the catalog is as it was, the revision included, and nothing is - /// remembered of the op in what the latest ops touched. The one exception is a batch whose rollback fails: the - /// catalog did change, so the revision advances and anything may be taken to have changed. + /// remembered of the op in what the latest ops touched. The one exception is a batch that fails and cannot be rolled + /// back whole: it is [`CatalogError::PartlyApplied`], the catalog did change (the revision advances and anything may + /// be taken to have changed), and the caller must record the op. pub fn apply(&mut self, op: Op) -> Result { if self.changes.seen != self.revision { // the revision was set from outside: what is remembered is of another past @@ -743,20 +837,12 @@ impl Catalog { } let broad = self.changes.broad; let keyword_list = self.changes.keyword_list; - self.changes.torn = false; let inv = match self.apply_inner(op) { Ok(inv) => inv, - Err(e) => { + Err(cause) => { let made = self.revision.saturating_add(1); - if self.changes.torn { - // (a batch the rollback of which failed changed something and says not what: it makes a - // revision, so what is kept for the one before is dropped, and anything may have changed, as - // after an op of a wider reach) - self.changes.torn = false; - self.changes.broad = made; - self.revision = made; - self.changes.seen = made; - } else { + let left = std::mem::take(&mut self.changes.leftover); + if left.is_empty() { // (everything the failed op, or the rollback of a batch, noted was made for the revision it // would have made: nothing earlier has that one. A note the cap already dropped stays // dropped, which only says less than is known, as the cap does.) @@ -765,8 +851,15 @@ impl Catalog { } self.changes.broad = broad; self.changes.keyword_list = keyword_list; + return Err(cause); } - return Err(e); + // (a batch the rollback of which failed changed something and says not what: it makes a revision, so + // what is kept for the one before is dropped, and anything may have changed, as after an op of a + // wider reach) + self.changes.broad = made; + self.revision = made; + self.changes.seen = made; + return Err(CatalogError::PartlyApplied { cause: Box::new(cause), remaining: Box::new(Op::Batch { ops: left }) }); } }; self.revision += 1; @@ -813,6 +906,29 @@ impl Catalog { } fn apply_inner(&mut self, op: Op) -> Result { + // a photo that comes, goes, is deleted or restored, is imported from Local or gets other content can change + // whether the photos with its content have the same content as another one (`index::content_key`), when + // anything asks + let photo = match &op { + Op::AddPhoto { photo } => Some(photo.id), + Op::RemovePhoto { id } | Op::SetDeleted { id, .. } | Op::SetLocal { id, .. } | Op::SetContent { id, .. } => Some(*id), + _ => None, + } + .filter(|_| self.follows_contents()); + let albums = matches!(op, Op::AddAlbum { .. } | Op::RemoveAlbum { .. } | Op::SetAlbumRules { .. }); + let before = photo.and_then(|id| self.content_of(id)); + let inv = self.apply_op(op)?; + if let Some(id) = photo { + let after = self.content_of(id); + self.content_moved(id, before, after); + } + if albums { + self.index.albums_changed(); + } + Ok(inv) + } + + fn apply_op(&mut self, op: Op) -> Result { // An op that changes one photo says which (`photo_mut`, and adding or removing it below). Most other kinds // can change what any photo matches or where it sorts: an album's photos or rules, a stack. The keyword // list changes only lists of keywords. Listed kind by kind, so a new one has to be put on one side. @@ -867,13 +983,16 @@ impl Catalog { photo.trim_history(); let id = photo.id; self.next_photo = self.next_photo.max(id.0.saturating_add(1)); + shared::photo(&mut photo); self.index.file_changed(id, None, file_path(&photo.source)); self.photos.insert(id, Arc::new(*photo)); + self.index.text_changed(id, self.photos.get(&id).map(|p| &**p)); Op::RemovePhoto { id } } Op::RemovePhoto { id } => { let p = self.photos.remove(&id).ok_or(CatalogError::NoPhoto(id))?; self.index.file_changed(id, file_path(&p.source), None); + self.index.text_changed(id, None); // album membership is restored by the batch the engine builds (see `delete_permanently`) Op::AddPhoto { photo: Box::new((*p).clone()) } } @@ -895,13 +1014,15 @@ impl Catalog { } Op::SetDevelop { id, settings, label, edited } => { let p = self.photo_mut(id)?; - let old = std::mem::replace(&mut p.develop, settings); + let old = std::mem::replace(&mut p.develop, shared::settings(settings)); let old_edit = std::mem::replace(&mut p.edited, edited); Op::SetDevelop { id, settings: old, label, edited: old_edit } } Op::SetMeta { id, meta } => { let p = self.photo_mut(id)?; - Op::SetMeta { id, meta: Box::new(std::mem::replace(&mut p.meta, *meta)) } + let old = std::mem::replace(&mut p.meta, *meta); + self.index.text_changed(id, self.photos.get(&id).map(|p| &**p)); + Op::SetMeta { id, meta: Box::new(old) } } Op::SetDeleted { id, deleted } => { let p = self.photo_mut(id)?; @@ -911,12 +1032,15 @@ impl Catalog { let p = self.photo_mut(id)?; Op::SetLocal { id, local: std::mem::replace(&mut p.local, local) } } - Op::SetVersions { id, versions } => { + Op::SetVersions { id, mut versions } => { let p = self.photo_mut(id)?; + shared::Anchor::new(p.develop.clone()).versions(&mut versions); Op::SetVersions { id, versions: std::mem::replace(&mut p.versions, versions) } } - Op::SetHistory { id, history } => { + Op::SetHistory { id, mut history } => { let p = self.photo_mut(id)?; + let own = shared::Anchor::new(p.develop.clone()); + history.iter_mut().for_each(|s| own.step(s)); let old = std::mem::replace(&mut p.history, history); let old_cursor = p.history_cursor; p.trim_history(); @@ -926,8 +1050,9 @@ impl Catalog { Op::Batch { ops: vec![Op::SetHistory { id, history: old }, Op::SetHistoryCursor { id, cursor: old_cursor }] } } } - Op::PushHistory { id, step } => { + Op::PushHistory { id, mut step } => { let p = self.photo_mut(id)?; + shared::Anchor::new(p.develop.clone()).step(&mut step); let old = p.history.clone(); let old_cursor = p.history_cursor.take(); // a new edit made from an earlier step drops the steps after it @@ -951,6 +1076,7 @@ impl Catalog { } Op::AddAlbum { album } => { self.plans = PlansMemo::default(); + self.index.forget_loops(); if self.albums.contains_key(&album.id) { return Err(CatalogError::Invalid(format!("album {:?} exists", album.id))); } @@ -973,6 +1099,7 @@ impl Catalog { } Op::RemoveAlbum { id } => { self.plans = PlansMemo::default(); + self.index.forget_loops(); if self.albums.values().any(|a| a.parent == Some(id)) { return Err(CatalogError::Invalid("folder is not empty".into())); } @@ -1034,6 +1161,7 @@ impl Catalog { } Op::SetAlbumRules { id, rules } => { self.plans = PlansMemo::default(); + self.index.forget_loops(); self.validate_rules(&rules)?; let a = self.album_mut(id)?; let Some(old) = a.smart.as_mut() else { @@ -1089,7 +1217,9 @@ impl Catalog { let p = self.photo_mut(id)?; let old_name = std::mem::replace(&mut p.file_name, file_name); let old_format = format.map(|f| std::mem::replace(&mut p.format, f)); - Op::Relink { id, file_name: old_name, source: std::mem::replace(&mut p.source, source), format: old_format } + let old = Op::Relink { id, file_name: old_name, source: std::mem::replace(&mut p.source, source), format: old_format }; + self.index.text_changed(id, self.photos.get(&id).map(|p| &**p)); + old } Op::SetContent { id, width, height, file_size, content_hash, preview_only, preview_checked } => { let p = self.photo_mut(id)?; @@ -1105,7 +1235,7 @@ impl Catalog { } Op::SetEmbeddedLens { id, lens } => { let p = self.photo_mut(id)?; - Op::SetEmbeddedLens { id, lens: std::mem::replace(&mut p.embedded_lens, lens.map(|l| *l)).map(Box::new) } + Op::SetEmbeddedLens { id, lens: std::mem::replace(&mut p.embedded_lens, lens) } } Op::SetAsShotWb { id, wb } => { if wb.is_some_and(|(t, tint)| !(t.is_finite() && tint.is_finite())) { @@ -1123,7 +1253,9 @@ impl Catalog { } let p = self.photo_mut(id)?; let old_name = std::mem::replace(&mut p.file_name, file_name); - Op::SetFile { id, file_name: old_name, source: std::mem::replace(&mut p.source, source) } + let old = Op::SetFile { id, file_name: old_name, source: std::mem::replace(&mut p.source, source) }; + self.index.text_changed(id, self.photos.get(&id).map(|p| &**p)); + old } Op::SetLabelName { label, name } => { let name = name.map(|n| n.trim().to_string()).filter(|n| !n.is_empty()); @@ -1170,12 +1302,21 @@ impl Catalog { match self.apply_inner(op) { Ok(inv) => inverses.push(inv), Err(e) => { - // roll back what was applied - for inv in inverses.into_iter().rev() { - if self.apply_inner(inv).is_err() { - self.changes.torn = true; + // roll back what was applied: first what a batch inside this one could not take back + // (it was done last), then the inverses, newest first. A batch among them (the inverse + // of one that went through) goes op by op, in the order it lists them: as a whole it would + // stop at the first op that cannot go yet and be kept whole, to stop there again at the + // retry, while its later ops (the one that makes the first possible) never ran. + let mut todo = Vec::new(); + let leftover = std::mem::take(&mut self.changes.leftover); + leftover.into_iter().chain(inverses.into_iter().rev()).for_each(|inv| unbatch(inv, &mut todo)); + let mut left = Vec::new(); + for inv in todo { + if self.apply_inner(inv.clone()).is_err() { + left.push(inv); } } + self.changes.leftover = left; return Err(e); } } @@ -1239,6 +1380,10 @@ impl Catalog { /// wrote). pub fn repair(&mut self) -> Vec { let mut changed = Vec::new(); + // Photos others hold are copied below (`Arc::make_mut`), which moves them in memory and strands the text kept + // for their address ([`index::Indexes`]), and stacks and albums change outside `apply`: nothing derived is + // kept across a repair, and the lookups are built again when asked. + self.index = index::Indexes::default(); // Segmentation grids shared by the snapshot this was read from (issue #2154): each // reference takes its grid's data, and the table is not kept — a live catalog always // stores the data inline, so masks render and serialize without the snapshot's table. @@ -1247,10 +1392,11 @@ impl Catalog { // an empty table, which is always dangling, so the table being empty does not skip it. let grids = std::mem::take(&mut self.grids); let mut dangling = 0usize; + let mut done = ResolvedGrids::new(); for p in self.photos.values_mut() { let photo = Arc::make_mut(p); for settings in photo.settings_holders_mut() { - dangling = resolve_grids(settings, &grids, dangling); + dangling = resolve_grids(settings, &grids, dangling, &mut done); } } if dangling > 0 { @@ -1349,9 +1495,8 @@ impl Catalog { self.next_stack = self.next_stack.max(stack); } if !changed.is_empty() { - // stacks and albums changed outside `apply`: the lookups are built again when asked - self.index = index::Indexes::default(); - // (and what was worked out from the albums, the guard of [`Self::keeps_written_order`] too) + // stacks and albums changed outside `apply`: what was worked out from the albums is made again (the guard of + // [`Self::keeps_written_order`] too) self.plans = PlansMemo::default(); } changed @@ -1364,7 +1509,7 @@ impl Catalog { for (i, line) in lines.iter().enumerate() { match serde_json::from_str::(line) { Ok(op) => { - self.apply(op)?; + self.replay_op(op)?; n += 1; } Err(e) if i + 1 == lines.len() => { @@ -1377,6 +1522,17 @@ impl Catalog { Ok(n) } + /// Apply one op of a saved log: the one place that says which failures of a logged op are the log being replayed, not + /// damage (`Journal::open` and [`Self::replay`] both go through it). A batch that was only partly taken back when it + /// was applied is logged as it was ([`CatalogError::PartlyApplied`]) and fails the same way again, leaving the same + /// changes, so replaying it counts as done; any other error is the caller's to handle. + pub(crate) fn replay_op(&mut self, op: Op) -> Result<()> { + match self.apply(op) { + Ok(_) | Err(CatalogError::PartlyApplied { .. }) => Ok(()), + Err(e) => Err(e), + } + } + pub fn op_to_log_line(op: &Op) -> String { let mut s = serde_json::to_string(op).unwrap_or_default(); s.push('\n'); @@ -1566,6 +1722,8 @@ mod tests_lock; #[cfg(all(test, not(target_arch = "wasm32")))] mod tests_log_thread; #[cfg(test)] +mod tests_looping_albums; +#[cfg(test)] mod tests_opened_folder; #[cfg(test)] mod tests_repair; @@ -1574,6 +1732,10 @@ mod tests_rule_order; #[cfg(test)] mod tests_scale; #[cfg(test)] +mod tests_search_text; +#[cfg(test)] +mod tests_shared; +#[cfg(test)] mod tests_tally; #[cfg(test)] mod tests_torn_append; diff --git a/crates/catalog/src/model.rs b/crates/catalog/src/model.rs index 4f689c4935..42bf566359 100644 --- a/crates/catalog/src/model.rs +++ b/crates/catalog/src/model.rs @@ -238,12 +238,89 @@ impl Meta { .filter(|t| lightcraft_meta::format_exposure_time(*t).is_some_and(|text| text == self.shutter.trim())) .or_else(|| parse_shutter_seconds(&self.shutter)) } + + /// The camera's maker and model as people name them, for display; None when the file names no camera. The maker + /// loses its company words ("OLYMPUS IMAGING CORP." is Olympus) and a name in capitals is written as a name + /// ("SONY" is Sony; an initialism such as "DJI" stays); the model is kept as the camera writes it, without the + /// maker said again ("NIKON CORPORATION NIKON Z 8" is Nikon Z 8). [`Meta::make`] says which words of `camera` are + /// the maker's; for a photo added before it was kept, the first word is. + pub fn camera_name(&self) -> Option { + let (camera, make) = (self.camera.trim(), self.make.trim()); + let after_make = camera.strip_prefix(make).filter(|rest| !make.is_empty() && (rest.is_empty() || rest.starts_with(char::is_whitespace))); + let (maker, model) = match after_make { + Some(model) => (make, model), + None => camera.split_once(char::is_whitespace).unwrap_or((camera, "")), + }; + let maker: Vec<&str> = maker.split_whitespace().filter(|w| !company_word(w)).collect(); + let said: Vec = maker.iter().map(|w| word_key(w)).collect(); + let model: Vec<&str> = if after_make.is_some() { + // drop the end of the make said again, with or without its company words ("NIKON", "ACME CAMERA SYSTEMS", + // or "KODAK" after "EASTMAN KODAK COMPANY"), then the make's own company words ("NIKON CORPORATION"); any + // other word, a company word included, is the model's; an end of company words alone is not the make + // ("ACME COMPUTER Computer 1000") + let model: Vec<&str> = model.split_whitespace().collect(); + let keys: Vec = model.iter().map(|w| word_key(w)).collect(); + let named = |end: &&[String]| keys.starts_with(end) && end.iter().any(|w| !company_word(w)); + let longest = |of: &[String]| (0..of.len()).filter_map(|i| of.get(i..)).find(named).map_or(0, <[String]>::len); + let full: Vec = make.split_whitespace().map(word_key).collect(); + let run = longest(&full).max(longest(&said)); + let own: Vec = make.split_whitespace().filter(|w| company_word(w)).map(word_key).collect(); + let rest = model.get(run..).unwrap_or_default(); + rest.iter().skip_while(|w| run > 0 && own.contains(&word_key(w))).copied().collect() + } else { + // the maker taken from the first word: drop the company words it left behind when they hold a legal form + // ("CASIO COMPUTER CO.,LTD.", with the maker said again among them), otherwise only the maker said again + // ("ACME Computer 1000" keeps Computer) + let model: Vec<&str> = model.split_whitespace().collect(); + let run: Vec<&str> = model.iter().copied().take_while(|w| said.contains(&word_key(w)) || company_word(w)).collect(); + let drop = if run.iter().any(|w| legal_form(w)) { run.len() } else { run.iter().take_while(|w| said.contains(&word_key(w))).count() }; + model.get(drop..).unwrap_or_default().to_vec() + }; + let words: Vec = maker.iter().map(|w| maker_word(w)).chain(model.into_iter().map(str::to_string)).collect(); + (!words.is_empty()).then(|| words.join(" ")) + } +} + +/// A word of a camera's name as words are compared: its letters and digits in lower case ("CORP." is corp, "CO.,LTD." +/// coltd). +fn word_key(w: &str) -> String { + w.chars().filter(|c| c.is_alphanumeric()).flat_map(char::to_lowercase).collect() +} + +/// Is `w` a word of a maker's company name ("IMAGING CORP.", "COMPANY, LTD.", "CAMERA AG"), or punctuation alone? +fn company_word(w: &str) -> bool { + const DESCRIPTIVE: &str = "imaging camera computer optical electronics"; + let key = word_key(w); + key.is_empty() || legal_form(w) || DESCRIPTIVE.split(' ').any(|c| c == key) +} + +/// Is `w` the legal form of a company ("CORP.", "CO.,LTD.", "AG")? Unlike "CAMERA" or "COMPUTER", no model starts +/// with one. +fn legal_form(w: &str) -> bool { + const FORMS: &str = "corporation corp company co ltd coltd limited inc llc gmbh ag"; + let key = word_key(w); + FORMS.split(' ').any(|c| c == key) +} + +/// A word of a maker's name as a name: one in capitals of more than three letters ("OLYMPUS") or in lower case +/// ("samsung") with only its first letter a capital; an initialism ("DJI"), a name in mixed case ("GoPro") and a word +/// with digits or punctuation as written. +fn maker_word(w: &str) -> String { + let letters = w.chars().all(char::is_alphabetic); + let capitals = w.chars().all(char::is_uppercase) && w.chars().count() > 3; + let lower = w.chars().all(char::is_lowercase); + if !(letters && (capitals || lower)) { + return w.to_string(); + } + let mut chars = w.chars(); + chars.next().map(|first| first.to_uppercase().chain(chars.flat_map(char::to_lowercase)).collect()).unwrap_or_default() } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Version { pub name: String, pub created: String, + #[serde(deserialize_with = "crate::shared::deserialize")] pub settings: Arc, #[serde(default)] pub auto: bool, @@ -252,6 +329,7 @@ pub struct Version { #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct HistoryStep { pub label: String, + #[serde(deserialize_with = "crate::shared::deserialize")] pub settings: Arc, } @@ -279,6 +357,7 @@ pub struct Photo { pub flag: Flag, #[serde(default)] pub label: Option, + #[serde(deserialize_with = "crate::shared::deserialize_current")] pub develop: Arc, #[serde(default)] pub edited: Option, @@ -310,7 +389,7 @@ pub struct Photo { /// Lens corrections embedded in the file (DNG `WarpRectilinear` / `FixVignetteRadial`), applied when /// "Enable Profile Corrections" is on. #[serde(default, skip_serializing_if = "Option::is_none")] - pub embedded_lens: Option, + pub embedded_lens: Option>, /// A virtual copy: the photo it was copied from (it shares that photo's file but has its own /// settings, metadata and history). #[serde(default, skip_serializing_if = "Option::is_none")] @@ -321,7 +400,7 @@ pub struct Photo { /// The settings import gave the photo when a user default (a raw/JPEG default preset, see /// the engine's import defaults) changed them from [`Photo::camera_defaults`]. They count as /// unedited, and Reset returns to them. - #[serde(default, skip_serializing_if = "Option::is_none")] + #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "crate::shared::deserialize_optional")] pub import_look: Option>, /// Assisted culling scores (`None` until analysed). #[serde(default, skip_serializing_if = "Option::is_none")] @@ -355,6 +434,20 @@ pub struct Analysis { pub group: Option, /// The best photo of its group. pub best: bool, + /// Set when the person arranged this photo's burst by hand (Window ▸ Bursts, or + /// `photo.moveToBurst`): its place in [`Analysis::group`], 0 being the pick, or `Some(0)` for + /// a photo taken out of every burst. Culling run again keeps such a photo's burst, place and + /// pick (unless asked to regroup). `None` while the burst is as culling made it; left out of the + /// catalog JSON then, so older catalogs read unchanged. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub rank: Option, +} + +impl Analysis { + /// Whether the person placed this photo by hand (see [`Analysis::rank`]). + pub fn by_hand(&self) -> bool { + self.rank.is_some() + } } /// Raw formats whose files carry vendor white-balance multipliers but no colour matrices: their starting @@ -423,7 +516,7 @@ impl Photo { rating: 0, flag: Flag::None, label: None, - develop: Arc::new(DevelopSettings::default()), + develop: crate::shared::default_settings(), edited: None, versions: Vec::new(), history: Vec::new(), @@ -575,6 +668,18 @@ impl Photo { pub fn in_library(&self) -> bool { !self.deleted && !self.local } + /// The file Missing Photos checks for this photo, if it is in scope: a library photo (not in + /// Recently Deleted, not a Local-only record seen while browsing a folder) whose original is a + /// file. Browse records are out of scope on purpose: browsing can leave tens of thousands of + /// them in the catalog, they never show in library views (Missing Photos included), and a + /// folder that is gone is simply not browsed again. The sidebar count, the Missing Photos view, + /// `library.missing` and Find Missing Photos all use this one rule. + pub fn library_file(&self) -> Option<&str> { + match &self.source { + Source::File { path } if self.in_library() => Some(path), + _ => None, + } + } /// Edited by the user: settings differ from what import gave the photo. pub fn is_edited(&self) -> bool { let mut defaults = self.import_defaults(); @@ -808,3 +913,65 @@ mod shutter_tests { assert_eq!(parse_shutter_seconds("1/250"), Some(0.004)); } } + +#[cfg(test)] +mod camera_name_tests { + use super::*; + + fn name(make: &str, camera: &str) -> Option { + Meta { make: make.into(), camera: camera.into(), ..Default::default() }.camera_name() + } + + #[test] + fn a_cameras_name_is_its_maker_once_without_company_words_then_its_model_as_written() { + for (make, camera) in [ + ("OLYMPUS IMAGING CORP.", "OLYMPUS IMAGING CORP. E-M5MarkII"), + ("NIKON CORPORATION", "NIKON CORPORATION NIKON Z 8"), + ("RICOH IMAGING COMPANY, LTD.", "RICOH IMAGING COMPANY, LTD. PENTAX K-1"), + ("LEICA CAMERA AG", "LEICA CAMERA AG LEICA Q3"), + ("Canon", "Canon Canon EOS R5"), + ] { + // the maker known, and a photo added before it was kept (its first word taken for the maker) + for make in [make, ""] { + let shown = name(make, camera).unwrap_or_else(|| panic!("{camera}: no name")); + let (maker, model) = shown.split_once(' ').unwrap_or_else(|| panic!("{shown}: no model")); + assert!(camera.ends_with(model), "{shown}: the model as {camera:?} writes it"); + assert!(!model.to_lowercase().contains(&maker.to_lowercase()), "{shown}: the maker said once"); + assert!(camera.to_lowercase().starts_with(&maker.to_lowercase()), "{shown}"); + } + } + // a maker in capitals is written as a name, an initialism or a name in mixed case as it is + assert!(name("SONY", "SONY ILCE-7M4").is_some_and(|n| n.starts_with("Sony "))); + assert!(name("DJI", "DJI FC3582").is_some_and(|n| n.starts_with("DJI "))); + assert_eq!(name("", "Apple iPhone 15 Pro").as_deref(), Some("Apple iPhone 15 Pro")); + // a maker of several words, and a model with no maker before it, as written + assert_eq!(name("OM Digital Solutions", "OM Digital Solutions OM-1").as_deref(), Some("OM Digital Solutions OM-1")); + assert_eq!(name("", "ILCE-7M4").as_deref(), Some("ILCE-7M4")); + assert_eq!(name("", " "), None, "no camera"); + // a maker whose company words follow its name ("COMPUTER CO.,LTD."), known or taken from the first word + for make in ["CASIO COMPUTER CO.,LTD.", ""] { + assert_eq!(name(make, "CASIO COMPUTER CO.,LTD. EX-Z1050").as_deref(), Some("Casio EX-Z1050"), "make {make:?}"); + } + // with the maker known, a company word that starts the model is the model's + assert_eq!(name("ACME", "ACME Computer 1000").as_deref(), Some("Acme Computer 1000")); + // but the maker said again in full, company words and all, is dropped + let repeated = "NIKON CORPORATION NIKON CORPORATION Z 8"; + assert_eq!(name("NIKON CORPORATION", repeated).as_deref(), Some("Nikon Z 8")); + // a model word that is only some word of the maker, or a company word the make never had, is the model's + let om = "OM Digital Solutions Digital 1000"; + assert_eq!(name("OM Digital Solutions", om).as_deref(), Some("OM Digital Solutions Digital 1000")); + assert_eq!(name("ACME", "ACME ACME Computer 1000").as_deref(), Some("Acme Computer 1000")); + assert_eq!(name("ACME COMPUTER", "ACME COMPUTER Computer 1000").as_deref(), Some("Acme Computer 1000")); + // with the maker taken from the first word, a company word with no legal form after it is the model's, and + // the first word ends at any space + assert_eq!(name("", "ACME Computer 1000").as_deref(), Some("Acme Computer 1000")); + assert_eq!(name("", "CANON\tALPHA R5").as_deref(), Some("Canon ALPHA R5")); + // the end of the maker said again is dropped ("EASTMAN KODAK" then "KODAK") + let kodak = "EASTMAN KODAK COMPANY KODAK EASYSHARE C875 ZOOM DIGITAL CAMERA"; + let shown = name("EASTMAN KODAK COMPANY", kodak); + assert_eq!(shown.as_deref(), Some("Eastman Kodak EASYSHARE C875 ZOOM DIGITAL CAMERA")); + // the make said again with a company word inside it is dropped whole + let systems = "ACME CAMERA SYSTEMS ACME CAMERA SYSTEMS 1000"; + assert_eq!(name("ACME CAMERA SYSTEMS", systems).as_deref(), Some("Acme Systems 1000")); + } +} diff --git a/crates/catalog/src/query.rs b/crates/catalog/src/query.rs index efa62ea6d8..069b01b781 100644 --- a/crates/catalog/src/query.rs +++ b/crates/catalog/src/query.rs @@ -152,6 +152,10 @@ fn shuffle_rank(seed: u64, id: PhotoId) -> u64 { pub(crate) struct Prepared { root: Option, only: Option>, + /// The search words ([`Filter::tokens`]). + tokens: Vec, + /// A pass over the library, which makes the text kept for each photo when it isn't ([`Catalog::search_text`]). + whole: bool, /// [`Filter::rule_set`] with its rules in the order to test them ([`crate::RuleSet::by_cost`]); /// `None` tests them as written. rules: Option, @@ -186,8 +190,8 @@ fn unquote(s: &str) -> &str { s.strip_prefix('"').map_or(s, |inner| inner.strip_suffix('"').unwrap_or(inner)) } -fn token_matches(p: &Photo, tok: &str) -> bool { - let t = tok.to_lowercase(); +/// Whether the word `t` (lower-cased) is in `p`, as a field of it or as plain text. +fn token_matches(p: &Photo, t: &str, hay: &Hay) -> bool { // a token that starts with a quote is a phrase, even with a colon in it if let Some((field, quoted)) = t.split_once(':').filter(|_| !t.starts_with('"')) { let val = unquote(quoted); @@ -231,20 +235,36 @@ fn token_matches(p: &Photo, tok: &str) -> bool { "name" | "file" => p.file_name.to_lowercase().contains(val), // Not a known field: the colon is part of a plain word ("10:30", "Re:"), its value unquoted // (`re:"a b"` is the text `re:a b`). - _ if val.len() != quoted.len() => text_matches(p, &format!("{field}:{val}")), - _ => text_matches(p, &t), + _ if val.len() != quoted.len() => hay.contains(&format!("{field}:{val}")), + _ => hay.contains(t), }; } - text_matches(p, unquote(&t)) + hay.contains(unquote(t)) } -/// Whether the lower-cased word `t` is in the file name, title, caption, camera, lens, location, -/// format, a keyword or the name of a person (a named face) of `p`. -fn text_matches(p: &Photo, t: &str) -> bool { - let hay = [&p.file_name, &p.meta.title, &p.meta.caption, &p.meta.camera, &p.meta.lens, &p.meta.location, &p.format]; - hay.iter().any(|h| h.to_lowercase().contains(t)) - || p.meta.keywords.iter().any(|k| k.to_lowercase().contains(t)) - || p.people().iter().any(|n| n.to_lowercase().contains(t)) +/// A photo's lower-cased text for the free-text search: the one the catalog keeps when `p` is its +/// own photo and a pass over the library made them ([`Prepared::whole`]), else made when first asked. +struct Hay<'a> { + p: &'a Photo, + cat: &'a Catalog, + whole: bool, + kept: std::cell::OnceCell>, + own: std::cell::OnceCell, +} + +impl Hay<'_> { + fn text(&self) -> &crate::index::PhotoText { + match self.kept.get_or_init(|| self.cat.search_text(self.p, self.whole)) { + Some(t) => t, + None => self.own.get_or_init(|| crate::index::PhotoText::of(self.p)), + } + } + + /// Whether `t` (lower-cased) is in one field of the photo ([`crate::index::PhotoText::contains`]): a word with NUL + /// is read from the fields themselves, for the joined text separates them with NUL. + fn contains(&self, t: &str) -> bool { + if t.contains('\0') { crate::index::PhotoText::field_contains(self.p, t) } else { self.text().contains(t) } + } } /// Whether `p` has a named face region called `name` (case-insensitive). @@ -356,13 +376,13 @@ impl Filter { pub fn matches(&self, p: &Photo, cat: &Catalog) -> bool { // one photo: its rules are tested as written (ordering them would cost more than it saves) - self.matches_in(p, cat, &Prepared { root: self.library_root(), only: None, rules: None }) + self.matches_in(p, cat, &Prepared { root: self.library_root(), only: None, tokens: self.tokens(), whole: false, rules: None }) } /// [`Filter::prepare`] for testing one photo at a time, with what each needs worked out once /// (the `only` ids are looked through, not hashed). pub(crate) fn prepare_one(&self, cat: &Catalog) -> Prepared { - Prepared { root: self.library_root(), only: None, rules: self.ordered_rules(cat) } + Prepared { root: self.library_root(), only: None, tokens: self.tokens(), whole: false, rules: self.ordered_rules(cat) } } /// The rule set to test, cheapest rule first: once per prepared filter, not per photo. `None` @@ -376,16 +396,23 @@ impl Filter { } /// What [`Filter::matches_in`] needs worked out once for a pass over many photos rather than - /// once per photo: the library folder's identity, the `only` ids as a set and the rules in the - /// order to test them. + /// once per photo: the library folder's identity, the `only` ids as a set, the search words and the + /// rules in the order to test them. pub(crate) fn prepare(&self, cat: &Catalog) -> Prepared { Prepared { root: self.library_root(), only: (!self.only.is_empty()).then(|| self.only.iter().copied().collect()), + tokens: self.tokens(), + whole: true, rules: self.ordered_rules(cat), } } + /// The search words ([`search_tokens`]), lower-cased (as `str::to_lowercase` does, once per query, not once per photo). + fn tokens(&self) -> Vec { + search_tokens(&self.text).map(str::to_lowercase).collect() + } + /// [`Filter::library_folder`] as a folder identity ([`folder_key`]); `None` without a choice. fn library_root(&self) -> Option { // as given: a folder may be named with spaces at its edge, and trimming would make it @@ -510,7 +537,11 @@ impl Filter { { return false; } - search_tokens(&self.text).all(|tok| token_matches(p, tok)) + if prepared.tokens.is_empty() { + return true; + } + let hay = Hay { p, cat, whole: prepared.whole, kept: std::cell::OnceCell::new(), own: std::cell::OnceCell::new() }; + prepared.tokens.iter().all(|t| token_matches(p, t, &hay)) } } diff --git a/crates/catalog/src/rules.rs b/crates/catalog/src/rules.rs index dc5a93a7e2..787a37a302 100644 --- a/crates/catalog/src/rules.rs +++ b/crates/catalog/src/rules.rs @@ -78,6 +78,7 @@ pub const FIELDS: &[(&str, &str, Kind)] = &[ ("kind", "File Type", Kind::Choice(&[("image", "Image"), ("raw", "Raw"), ("video", "Video")])), ("format", "File Format", Kind::Text), ("duration", "Video Duration", Kind::Number), + ("sameContent", "Same Content as Another Photo", Kind::Bool), // Date ("captureDate", "Capture Date", Kind::Date), ("importDate", "Import Date", Kind::Date), @@ -135,7 +136,7 @@ pub const TOP_LEVEL_FIELDS: &[&str] = &["rating", "flag", "label", "text"]; /// once or in [`TOP_LEVEL_FIELDS`]. pub const FIELD_GROUPS: &[(&str, &[&str])] = &[ ("Source", &["album", "virtualCopy", "copyName", "stacked"]), - ("File", &["fileName", "extension", "filePath", "kind", "format", "duration"]), + ("File", &["fileName", "extension", "filePath", "kind", "format", "duration", "sameContent"]), ("Date", &["captureDate", "importDate", "editDate"]), ("Keywords & People", &["keywords", "keywordCount", "person", "personCount"]), ("Description", &["title", "caption", "altText", "creator", "copyright", "copyrightStatus"]), @@ -713,8 +714,37 @@ fn lower(v: &Value) -> String { } } +/// What a Text rule looks through for `p`: its file name, title, caption, camera, lens, location, city, +/// state, country, alt text, format, keywords, people and copy name, trimmed and lower-cased. +pub(crate) fn rule_text(p: &Photo) -> String { + let m = &p.meta; + let all = [ + p.file_name.as_str(), + &m.title, + &m.caption, + &m.camera, + &m.lens, + &m.location, + &m.city, + &m.state, + &m.country, + &m.alt_text, + &p.format, + &m.keywords.join(" "), + &p.people().join(" "), + p.copy_name.as_deref().unwrap_or(""), + ] + .join(" "); + let all = all.trim(); + if all.is_ascii() { all.to_ascii_lowercase() } else { all.to_lowercase() } +} + fn text_op(op: &str, have: &str, want: &str) -> bool { - let have = have.trim().to_lowercase(); + text_op_lowered(op, &have.trim().to_lowercase(), want) +} + +/// [`text_op`] for a `have` that is trimmed and lower-cased already. +fn text_op_lowered(op: &str, have: &str, want: &str) -> bool { match op { "contains" => want.split_whitespace().all(|w| have.contains(w)), "notContains" => !want.split_whitespace().any(|w| have.contains(w)), @@ -1049,6 +1079,7 @@ impl Rule { "virtualCopy" => yes(p.copy_of.is_some()), "copyName" => text(p.copy_name.as_deref().unwrap_or("")), "stacked" => yes(cat.stack_of(p.id).is_some()), + "sameContent" => yes(cat.has_same_content(p)), "cropped" => yes(p.is_cropped()), "treatment" => { let t = if p.develop.treatment == lightcraft_develop::Treatment::Bw { "monochrome" } else { "color" }; @@ -1058,26 +1089,10 @@ impl Rule { "keywordCount" => num_op(op, Some(p.keyword_count() as f64), value), "person" => names_op(op, &p.people(), &want), "personCount" => num_op(op, Some(p.people().len() as f64), value), - "text" => { - let all = [ - p.file_name.as_str(), - &m.title, - &m.caption, - &m.camera, - &m.lens, - &m.location, - &m.city, - &m.state, - &m.country, - &m.alt_text, - &p.format, - &m.keywords.join(" "), - &p.people().join(" "), - p.copy_name.as_deref().unwrap_or(""), - ] - .join(" "); - text(&all) - } + "text" => match cat.rule_text_of(p) { + Some(have) => text_op_lowered(op, have, &want), + None => text_op_lowered(op, &rule_text(p), &want), + }, "fileName" => text(&p.file_name), "extension" => text_op(op, p.extension(), want.trim_start_matches('.')), "duration" => num_op(op, p.duration.filter(|d| d.is_finite()), value), @@ -1209,6 +1224,14 @@ impl RuleSet { }) } + /// Whether a rule (nested groups included) tests `field`. + pub fn reads(&self, field: &str) -> bool { + self.rules.iter().any(|r| match r { + Rule::Group { group } => group.reads(field), + Rule::Field { field: f, .. } => f == field, + }) + } + /// Bring rules saved by older versions up to date, keeping what they meant: an Album rule with /// an operator from when Album was a number field (≥, between…) always matched as "isn't", and /// now says so. Commands and the editor apply it before checking. diff --git a/crates/catalog/src/rules/tests.rs b/crates/catalog/src/rules/tests.rs index e78c37c8e3..35b5e9e155 100644 --- a/crates/catalog/src/rules/tests.rs +++ b/crates/catalog/src/rules/tests.rs @@ -215,6 +215,82 @@ fn file_source_description_and_location_rules() { assert!(m(&p, "location", "contains", json!("portugal")), "Location still covers the country"); } +/// Same Content as Another Photo: another photo of the library has the same file content, under another name +/// or in another folder (a Duplicate's `:dup` key included). +/// * A virtual copy is the same photo, not another one: it never matches and never makes a match. +/// * Neither does a photo in Recently Deleted or one only browsed in Local, nor a photo with no content hash. +/// * It follows the library: a twin deleted, restored, removed or given other content changes the others. +#[test] +fn same_content_as_another_photo() { + use crate::Op; + let mut cat = Catalog::new(); + let with = |id: u64, hash: Option<&str>| { + let mut p = photo(id); + p.content_hash = hash.map(str::to_string); + p + }; + let mut v = with(5, Some("cc")); + v.copy_of = Some(PhotoId(4)); + let mut local = with(7, Some("dd")); + local.local = true; + for p in [with(1, Some("aa")), with(2, Some("aa:dup2")), with(3, None), with(4, Some("cc")), v, with(6, Some("dd")), local, with(8, None)] { + cat.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + } + let same = |cat: &Catalog| -> Vec { + let r = rs(json!({"rules": [{"field": "sameContent", "op": "is", "value": true}]})); + let not = rs(json!({"rules": [{"field": "sameContent", "op": "is", "value": false}]})); + let mut ids: Vec = cat.photos().filter(|p| r.matches(p, cat)).map(|p| p.id.0).collect(); + ids.sort_unstable(); + assert!(cat.photos().all(|p| r.matches(p, cat) != not.matches(p, cat)), "is no is the opposite"); + ids + }; + assert_eq!(same(&cat), vec![1, 2], "a Duplicate's key is the same content; a virtual copy and a Local photo don't count"); + // the twin goes to Recently Deleted: the other is alone, and counts as touched (album counts and views + // follow an edit through the photos it touched); restored, both again + let before = cat.revision; + cat.apply(Op::SetDeleted { id: PhotoId(2), deleted: true }).unwrap(); + assert_eq!(same(&cat), Vec::::new()); + assert_eq!(cat.touched_since(before), Some(vec![PhotoId(1), PhotoId(2)])); + cat.apply(Op::SetDeleted { id: PhotoId(2), deleted: false }).unwrap(); + assert_eq!(same(&cat), vec![1, 2]); + // a batch that fails midway is undone as a whole: nothing changed + let bad = Op::Batch { ops: vec![Op::SetDeleted { id: PhotoId(2), deleted: true }, Op::SetRating { id: PhotoId(2), rating: 9 }] }; + assert!(cat.apply(bad).is_err()); + assert_eq!(same(&cat), vec![1, 2]); + // a copy of the catalog (made to count in the background) knows nothing yet, and while no smart album asks + // its edits follow no contents; once one asks, they touch the twins, so counts made before them can follow + let mut copy = cat.clone(); + copy.apply(Op::SetDeleted { id: PhotoId(3), deleted: true }).unwrap(); + let mut album = crate::Album::new(crate::AlbumId(1), "Twins"); + album.smart = Some(Box::new(crate::Filter { + rule_set: Some(rs(json!({"rules": [{"field": "sameContent", "op": "is", "value": true}]}))), + ..Default::default() + })); + copy.apply(Op::AddAlbum { album }).unwrap(); + let before = copy.revision; + copy.apply(Op::SetDeleted { id: PhotoId(2), deleted: true }).unwrap(); + assert_eq!(copy.touched_since(before), Some(vec![PhotoId(1), PhotoId(2)])); + // the Local photo is imported for real + cat.apply(Op::SetLocal { id: PhotoId(7), local: false }).unwrap(); + assert_eq!(same(&cat), vec![1, 2, 6, 7]); + // a file's content changed (Reload): it leaves one pair and joins another + let p = cat.photo(PhotoId(1)).unwrap().clone(); + let set = |hash: &str| Op::SetContent { + id: PhotoId(1), + width: p.width, + height: p.height, + file_size: p.file_size, + content_hash: Some(hash.into()), + preview_only: None, + preview_checked: String::new(), + }; + cat.apply(set("dd")).unwrap(); + assert_eq!(same(&cat), vec![1, 6, 7]); + // gone for good + cat.apply(Op::RemovePhoto { id: PhotoId(6) }).unwrap(); + assert_eq!(same(&cat), vec![1, 7]); +} + /// In a Stack, Video Duration (seconds; photos have none), Cropped and Treatment. #[test] fn source_file_and_develop_rules() { @@ -663,7 +739,7 @@ fn related_fields_share_a_group() { assert_eq!(field_group(f), Some(group), "{f}"); } }; - same(&["fileName", "extension", "filePath", "kind", "format", "duration"], "File"); + same(&["fileName", "extension", "filePath", "kind", "format", "duration", "sameContent"], "File"); same(&["album", "virtualCopy", "copyName", "stacked"], "Source"); same(&["longEdge", "shortEdge", "aspect", "megapixels"], "Size"); same(&["edited", "cropped", "treatment"], "Develop"); diff --git a/crates/catalog/src/shared.rs b/crates/catalog/src/shared.rs new file mode 100644 index 0000000000..19fd7ebc1e --- /dev/null +++ b/crates/catalog/src/shared.rs @@ -0,0 +1,365 @@ +//! One develop settings value for all the photos whose settings are equal. +//! +//! A photo holds its settings behind an `Arc`, and so do its history steps, versions and import +//! look. Most photos of a library were never edited: without sharing, each holds a copy of the +//! same defaults (over a third of the memory an unedited JPEG's record takes), and so does every +//! raw with the same import look. Here every +//! settings value that enters a catalog, read from a saved library or given by a change, is +//! replaced by the one already held when an equal one is. +//! Settings whose masks refer to a snapshot's grid table are shared again once the references are +//! resolved (`resolve_grids` in `lib.rs`); settings without a reference are left as they were read. +//! +//! Sharing never lets one photo's edit reach another: settings behind an `Arc` are not changed +//! in place (the catalog replaces them; `Arc::make_mut` copies a value that is shared). +//! +//! **Equal means the same down to the JSON.** `==` takes -0.0 for 0.0, which the saved form, a +//! photo's fingerprint and the preview-cache key tell apart. Two values are shared only when +//! they are `==` and neither holds a negative zero. Settings holding a negative zero are left +//! alone: never shared, never what others share. +//! +//! What is held to compare with: the defaults, and on each thread the last few values seen (a +//! camera's import defaults, a photo's own history). The thread's list keeps nothing alive: a +//! value no photo holds any more is gone from it too. + +use std::cell::{OnceCell, RefCell}; +use std::sync::{Arc, OnceLock, Weak}; + +use lightcraft_develop::DevelopSettings; +use serde::de::{Deserialize, Deserializer}; + +use crate::{HistoryStep, Photo, Version}; + +/// How many values a thread remembers besides the defaults and the current photo's. +const RECENT: usize = 4; + +/// Whether a value holds a -0.0 anywhere (a float the saved JSON writes as `-0.0`): found by +/// walking it as `Serialize` does, so no text is built (writing every float out costs as much as +/// reading the library did). +fn has_negative_zero(value: &T) -> bool { + value.serialize(Walk).is_err() +} + +/// Walks a value; stops with an error at the first -0.0. +struct Walk; + +#[derive(Debug)] +struct Found; + +impl std::fmt::Display for Found { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("negative zero") + } +} + +impl std::error::Error for Found {} + +impl serde::ser::Error for Found { + fn custom(_: T) -> Self { + Found + } +} + +type Walked = Result<(), Found>; + +macro_rules! nothing { + ($($method:ident($ty:ty)),* $(,)?) => { + $(fn $method(self, _: $ty) -> Walked { Ok(()) })* + }; +} + +impl serde::Serializer for Walk { + type Ok = (); + type Error = Found; + type SerializeSeq = Walk; + type SerializeTuple = Walk; + type SerializeTupleStruct = Walk; + type SerializeTupleVariant = Walk; + type SerializeMap = Walk; + type SerializeStruct = Walk; + type SerializeStructVariant = Walk; + + nothing!(serialize_bool(bool), serialize_i8(i8), serialize_i16(i16), serialize_i32(i32), serialize_i64(i64), serialize_i128(i128)); + nothing!(serialize_u8(u8), serialize_u16(u16), serialize_u32(u32), serialize_u64(u64), serialize_u128(u128)); + nothing!(serialize_char(char), serialize_str(&str), serialize_bytes(&[u8]), serialize_unit_struct(&'static str)); + + fn serialize_f32(self, v: f32) -> Walked { + if v == 0.0 && v.is_sign_negative() { Err(Found) } else { Ok(()) } + } + + fn serialize_f64(self, v: f64) -> Walked { + if v == 0.0 && v.is_sign_negative() { Err(Found) } else { Ok(()) } + } + + fn serialize_none(self) -> Walked { + Ok(()) + } + + fn serialize_some(self, v: &T) -> Walked { + v.serialize(Walk) + } + + fn serialize_unit(self) -> Walked { + Ok(()) + } + + fn serialize_unit_variant(self, _: &'static str, _: u32, _: &'static str) -> Walked { + Ok(()) + } + + fn serialize_newtype_struct(self, _: &'static str, v: &T) -> Walked { + v.serialize(Walk) + } + + fn serialize_newtype_variant(self, _: &'static str, _: u32, _: &'static str, v: &T) -> Walked { + v.serialize(Walk) + } + + fn serialize_seq(self, _: Option) -> Result { + Ok(Walk) + } + + fn serialize_tuple(self, _: usize) -> Result { + Ok(Walk) + } + + fn serialize_tuple_struct(self, _: &'static str, _: usize) -> Result { + Ok(Walk) + } + + fn serialize_tuple_variant(self, _: &'static str, _: u32, _: &'static str, _: usize) -> Result { + Ok(Walk) + } + + fn serialize_map(self, _: Option) -> Result { + Ok(Walk) + } + + fn serialize_struct(self, _: &'static str, _: usize) -> Result { + Ok(Walk) + } + + fn serialize_struct_variant(self, _: &'static str, _: u32, _: &'static str, _: usize) -> Result { + Ok(Walk) + } +} + +macro_rules! walk_elements { + ($($trait:ident::$method:ident),* $(,)?) => { + $(impl serde::ser::$trait for Walk { + type Ok = (); + type Error = Found; + + fn $method(&mut self, v: &T) -> Walked { + v.serialize(Walk) + } + + fn end(self) -> Walked { + Ok(()) + } + })* + }; +} + +walk_elements!( + SerializeSeq::serialize_element, + SerializeTuple::serialize_element, + SerializeTupleStruct::serialize_field, + SerializeTupleVariant::serialize_field +); + +impl serde::ser::SerializeMap for Walk { + type Ok = (); + type Error = Found; + + fn serialize_key(&mut self, k: &T) -> Walked { + k.serialize(Walk) + } + + fn serialize_value(&mut self, v: &T) -> Walked { + v.serialize(Walk) + } + + fn end(self) -> Walked { + Ok(()) + } +} + +impl serde::ser::SerializeStruct for Walk { + type Ok = (); + type Error = Found; + + fn serialize_field(&mut self, _: &'static str, v: &T) -> Walked { + v.serialize(Walk) + } + + fn end(self) -> Walked { + Ok(()) + } +} + +impl serde::ser::SerializeStructVariant for Walk { + type Ok = (); + type Error = Found; + + fn serialize_field(&mut self, _: &'static str, v: &T) -> Walked { + v.serialize(Walk) + } + + fn end(self) -> Walked { + Ok(()) + } +} + +fn held_default() -> &'static Arc { + static DEFAULT: OnceLock> = OnceLock::new(); + DEFAULT.get_or_init(|| Arc::new(DevelopSettings::default())) +} + +/// The default settings, held once. +pub fn default_settings() -> Arc { + held_default().clone() +} + +/// What a thread has seen: pointers that keep nothing alive (a value the catalog let go of is +/// gone from here too). None of the values holds a negative zero. +#[derive(Default)] +struct Seen { + /// The settings of the photo being read or added: its history (up to 200 steps, each seen + /// after it) usually ends with them. + current: Option>, + /// The last few values, the latest first. + recent: Vec>, +} + +thread_local! { + static SEEN: RefCell = RefCell::new(Seen::default()); +} + +/// How many values this thread remembers now (tests). +#[cfg(test)] +pub(crate) fn remembered() -> usize { + SEEN.with(|seen| seen.borrow().recent.len()) +} + +/// `settings`, or the value already held that is the same. +pub fn settings(settings: Arc) -> Arc { + share(settings, false) +} + +/// [`settings`] for a photo's own settings (`current`): what its history is compared with first. +fn share(settings: Arc, current: bool) -> Arc { + // (looked for at most once, and only when an equal value turned up or this one is kept) + let exact = OnceCell::new(); + let exact = || *exact.get_or_init(|| !has_negative_zero(settings.as_ref())); + let same = |held: &Arc| Arc::ptr_eq(held, &settings) || (**held == *settings && exact()); + let default = held_default(); + if same(default) { + // (the held default is compared with anyway) + if current { + let _ = SEEN.try_with(|seen| seen.try_borrow_mut().map(|mut s| s.current = None)); + } + return default.clone(); + } + let found = SEEN.try_with(|seen| { + let mut seen = seen.try_borrow_mut().ok()?; + let found = seen.current.as_ref().and_then(Weak::upgrade).filter(|s| same(s)).or_else(|| { + // (values that are gone drop out as they are met) + let mut found = None; + seen.recent.retain(|w| match w.upgrade() { + Some(s) if found.is_none() && same(&s) => { + found = Some(s); + false + } + Some(_) => true, + None => false, + }); + if let Some(f) = &found { + seen.recent.insert(0, Arc::downgrade(f)); + } + found + }); + if found.is_none() && exact() { + seen.recent.truncate(RECENT - 1); + seen.recent.insert(0, Arc::downgrade(&settings)); + } + if current { + seen.current = match &found { + Some(f) => Some(Arc::downgrade(f)), + None => exact().then(|| Arc::downgrade(&settings)), + }; + } + found + }); + // (a thread shutting down: as it came) + found.ok().flatten().unwrap_or(settings) +} + +/// Share the settings of a history step. +pub(crate) fn step(step: &mut HistoryStep) { + step.settings = settings(step.settings.clone()); +} + +/// What a change's settings are compared with first: the photo's own settings. +pub(crate) struct Anchor { + own: Arc, + /// Whether `own` holds no negative zero (looked for once, and only when an equal value turned up). + exact: OnceCell, +} + +impl Anchor { + pub(crate) fn new(own: Arc) -> Self { + Self { own, exact: OnceCell::new() } + } + + /// `s`, or the photo's own settings when equal (and neither holds a negative zero), or else what [`settings`] says. + fn settings(&self, s: Arc) -> Arc { + if Arc::ptr_eq(&self.own, &s) { + return s; + } + if *self.own == *s && *self.exact.get_or_init(|| !has_negative_zero(self.own.as_ref())) && !has_negative_zero(s.as_ref()) { + return self.own.clone(); + } + settings(s) + } + + pub(crate) fn step(&self, step: &mut HistoryStep) { + step.settings = self.settings(step.settings.clone()); + } + + pub(crate) fn versions(&self, versions: &mut [Version]) { + for v in versions { + v.settings = self.settings(v.settings.clone()); + } + } +} + +/// Share the settings of versions. +pub(crate) fn versions(versions: &mut [Version]) { + for v in versions { + v.settings = settings(v.settings.clone()); + } +} + +/// Share every settings value a photo holds. +pub(crate) fn photo(p: &mut Photo) { + p.develop = share(p.develop.clone(), true); + p.history.iter_mut().for_each(step); + versions(&mut p.versions); + p.import_look = p.import_look.take().map(settings); +} + +/// Settings read from a saved library (`deserialize_with`): shared. +pub(crate) fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result, D::Error> { + DevelopSettings::deserialize(d).map(|s| share(Arc::new(s), false)) +} + +/// [`deserialize`] for a photo's own settings: what its history, read after them, is compared +/// with first. +pub(crate) fn deserialize_current<'de, D: Deserializer<'de>>(d: D) -> Result, D::Error> { + DevelopSettings::deserialize(d).map(|s| share(Arc::new(s), true)) +} + +/// [`deserialize`] for settings a photo may not have (its import look). +pub(crate) fn deserialize_optional<'de, D: Deserializer<'de>>(d: D) -> Result>, D::Error> { + Ok(Option::::deserialize(d)?.map(|s| share(Arc::new(s), false))) +} diff --git a/crates/catalog/src/store.rs b/crates/catalog/src/store.rs index da9849105f..03c0194c95 100644 --- a/crates/catalog/src/store.rs +++ b/crates/catalog/src/store.rs @@ -40,6 +40,19 @@ pub trait Store: Send { /// Cut a file to `len` bytes (drop a torn tail before appending again). A missing file is /// left missing. fn truncate(&mut self, name: &str, len: u64) -> io::Result<()>; + /// Remove a file (a missing one is not an error). The default can't: such a store keeps what + /// it was asked to remove. + fn remove(&mut self, name: &str) -> io::Result<()> { + let _ = name; + Err(io::Error::new(io::ErrorKind::Unsupported, "this store can't remove files")) + } + /// Whether the files an upgrade to a newer catalog format replaces are kept beside the + /// library (see [`crate::journal`] → *Format versions*): the way back to the build that wrote + /// them. `false` where there is no such build to go back to (the browser always runs the + /// newest one) and room is short. + fn keeps_replaced_formats(&self) -> bool { + true + } /// Human-readable location (diagnostics). fn describe(&self) -> String; /// Another handle on the same files that a worker thread can write `catalog.snap` through @@ -241,10 +254,20 @@ impl Store for FsStore { self.folder.check()?; let tmp = self.path(&format!("{name}.tmp")); let mut f = create_staging(&tmp)?; - f.write_all(data)?; - f.sync_all()?; - check_staging(&self.folder, &tmp, &f)?; - std::fs::rename(&tmp, self.path(name))?; + let staged = (|| { + f.write_all(data)?; + f.sync_all()?; + check_staging(&self.folder, &tmp, &f)?; + std::fs::rename(&tmp, self.path(name)) + })(); + if let Err(e) = staged { + // no staging file is left beside the library (a kept copy is all or nothing), unless it is no longer ours: a + // folder or a name that came to belong to another save keeps its file (see `check_staging`) + if check_staging(&self.folder, &tmp, &f).is_ok() { + let _ = std::fs::remove_file(&tmp); + } + return Err(e); + } self.sync_dir(); self.reset_sync_log(name, data.len() as u64); Ok(()) @@ -283,7 +306,13 @@ impl Store for FsStore { } }; check_staging(&self.folder, &tmp, &file)?; - std::fs::rename(&tmp, self.path(name))?; + if let Err(e) = std::fs::rename(&tmp, self.path(name)) { + // (as in `write_atomic`: the staging file goes unless it came to belong to another save) + if check_staging(&self.folder, &tmp, &file).is_ok() { + let _ = std::fs::remove_file(&tmp); + } + return Err(e); + } self.sync_dir(); self.reset_sync_log(name, n); Ok(n) @@ -384,6 +413,30 @@ impl Store for FsStore { Ok(()) } + fn remove(&mut self, name: &str) -> io::Result<()> { + // What was handed to the log's thread is written first (a failure is the caller's: nothing is dropped). The thread + // goes only once the file is gone (it would read a missing file as another log), and the next append starts one. + #[cfg(not(target_arch = "wasm32"))] + let thread = self.log_for(name).is_some(); + #[cfg(not(target_arch = "wasm32"))] + if thread { + self.flush_log()?; + } + self.folder.check()?; + match std::fs::remove_file(self.path(name)) { + Ok(()) => {} + Err(e) if e.kind() == io::ErrorKind::NotFound => {} + Err(e) => return Err(e), + } + #[cfg(not(target_arch = "wasm32"))] + if thread { + self.log = None; + } + // (a removed log is a log of no bytes: what the next append is checked against) + self.reset_sync_log(name, 0); + Ok(()) + } + fn describe(&self) -> String { self.dir.display().to_string() } @@ -458,6 +511,10 @@ impl Store for MemStore { } Ok(()) } + fn remove(&mut self, name: &str) -> io::Result<()> { + self.files.lock().unwrap_or_else(|e| e.into_inner()).remove(name); + Ok(()) + } fn describe(&self) -> String { "memory".into() } @@ -515,3 +572,54 @@ mod tests_staging { let _ = std::fs::remove_dir_all(&dir); } } + +#[cfg(test)] +mod tests_failed_write { + use super::*; + + fn dir_with_a_directory_at(tag: &str, name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("lc-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join(name)).unwrap(); + dir + } + + /// A write that can't land (here the rename fails, the name being a directory) leaves no staging file behind: the + /// files a library keeps before an upgrade are "all or nothing", and a `.tmp` beside them is a copy lying about. + #[test] + fn write_atomic_that_fails_leaves_no_staging_file() { + let dir = dir_with_a_directory_at("write-atomic-fails", "catalog.snap.v6-8"); + let mut store = FsStore::open(&dir).unwrap(); + assert!(store.write_atomic("catalog.snap.v6-8", b"{}").is_err()); + assert!(!dir.join("catalog.snap.v6-8.tmp").exists(), "a staging file was left behind"); + let _ = std::fs::remove_dir_all(&dir); + } + + /// The streamed write cleans up the same way when the rename fails (it already did when the content can't be written). + #[test] + fn write_atomic_with_that_fails_to_rename_leaves_no_staging_file() { + let dir = dir_with_a_directory_at("write-atomic-with-fails", "catalog.log"); + let mut store = FsStore::open(&dir).unwrap(); + assert!(store.write_atomic_with("catalog.log", &mut |w| w.write_all(b"[1]")).is_err()); + assert!(!dir.join("catalog.log.tmp").exists(), "a staging file was left behind"); + let _ = std::fs::remove_dir_all(&dir); + } + + /// A log that is removed while its thread runs ends the thread: the next append starts one for the new, empty file, and is + /// written (a thread that outlived its file would find another file than the one it wrote and hold the record back). + #[test] + fn removing_the_log_ends_its_writer() { + let dir = std::env::temp_dir().join(format!("lc-remove-log-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let mut store = FsStore::open(&dir).unwrap(); + store.append("catalog.log", b"abc\n").unwrap(); + store.flush().unwrap(); + store.remove("catalog.log").unwrap(); + assert!(!dir.join("catalog.log").exists()); + store.append("catalog.log", b"de\n").unwrap(); + store.flush().unwrap(); + assert!(store.unwritten().is_none(), "nothing is held back"); + assert_eq!(std::fs::read(dir.join("catalog.log")).unwrap(), b"de\n"); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/crates/catalog/src/tests.rs b/crates/catalog/src/tests.rs index 1d59fe2680..4e056c03e3 100644 --- a/crates/catalog/src/tests.rs +++ b/crates/catalog/src/tests.rs @@ -661,7 +661,7 @@ fn set_embedded_lens_is_undoable_and_journaled() { let op = Op::SetEmbeddedLens { id: a, lens: Some(Box::new(lens)) }; let op: Op = serde_json::from_str(&serde_json::to_string(&op).unwrap()).unwrap(); let inv = c.apply(op).unwrap(); - assert_eq!(c.photo(a).unwrap().embedded_lens, Some(lens)); + assert_eq!(c.photo(a).unwrap().embedded_lens, Some(Box::new(lens))); let inv: Op = serde_json::from_str(&serde_json::to_string(&inv).unwrap()).unwrap(); c.apply(inv).unwrap(); assert_eq!(c.photo(a).unwrap().embedded_lens, None); @@ -994,6 +994,52 @@ fn search_text_finds_people_and_quoted_values() { assert_eq!(q(" \t jane \u{3000} "), vec![jane, both], "any whitespace separates tokens"); } +/// The photos a tally that reads only some things of a photo has to look at again: those whose file, presence or flag +/// changed, not those that were only rated, and not what an album, a stack or a folder label changed (no photo's own). +#[test] +fn photos_changed_since_names_the_photos_whose_read_aspects_changed() { + let mut c = Catalog::default(); + let add = |c: &mut Catalog, name: &str| { + let id = c.alloc_photo_id(); + c.apply(Op::AddPhoto { + photo: Box::new(Photo::new(id, Source::File { path: format!("/p/{name}") }, name, "JPEG", 60, 40, "2026-01-01T10:00:00")), + }) + .unwrap(); + id + }; + let (a, b) = (add(&mut c, "a.jpg"), add(&mut c, "b.jpg")); + let files = Aspects::PRESENCE.with(Aspects::FILE); + let start = c.revision; + assert_eq!(c.photos_changed_since(start, files), Some(vec![])); + // a rating changes neither; a flag is read by the flag reader only + c.apply(Op::SetRating { id: a, rating: 3 }).unwrap(); + c.apply(Op::SetFlag { id: b, flag: Flag::Pick }).unwrap(); + assert_eq!(c.photos_changed_since(start, files), Some(vec![])); + assert_eq!(c.photos_changed_since(start, Aspects::FLAG), Some(vec![b])); + assert_eq!(c.touched_since(start), Some(vec![a, b]), "touched_since says every photo that was touched"); + // a photo that comes in, moves or goes + let new = add(&mut c, "c.jpg"); + c.apply(Op::Relink { id: a, file_name: "m.jpg".into(), source: Source::File { path: "/p/m.jpg".into() }, format: None }).unwrap(); + c.apply(Op::RemovePhoto { id: b }).unwrap(); + assert_eq!(c.photos_changed_since(start, files), Some(vec![a, b, new]), "each once, in id order"); + // an op that changes no photo of its own is remembered, and is not in the answer (touched_since gives up on it) + let before = c.revision; + let album = c.alloc_album_id(); + c.apply(Op::AddAlbum { album: Album { photos: vec![a], ..Album::new(album, "Trip") } }).unwrap(); + assert_eq!(c.photos_changed_since(before, files), Some(vec![])); + assert_eq!(c.touched_since(before), None); + assert_eq!(c.photos_changed_since(start, files), Some(vec![a, b, new]), "what came before it is still known"); + // not known: a revision that is not this catalog's past, and one set from outside (a library just loaded) + assert_eq!(c.photos_changed_since(c.revision + 5, files), None); + let old = c.revision; + c.revision = 7 << 32; + assert_eq!(c.photos_changed_since(old, files), None); + let loaded = c.revision; + c.apply(Op::SetRating { id: a, rating: 1 }).unwrap(); + assert_eq!(c.photos_changed_since(loaded, files), Some(vec![])); + assert_eq!(c.photos_changed_since(old, files), None); +} + /// What the catalog remembers of its latest ops: which photos each changed and what of them, as long as that can be /// said photo by photo. #[test] @@ -1141,3 +1187,121 @@ fn a_batch_that_cannot_be_rolled_back_whole_makes_earlier_changes_unknown() { assert_eq!(c.touched_since(start), None, "so nothing is said of what changed"); assert_eq!(c.touched_since(c.revision), Some(vec![]), "from after it, it is known again"); } + +/// A batch that fails, and whose rollback fails halfway, says so and hands out what is left of the rollback. +#[test] +fn a_batch_that_cannot_be_rolled_back_whole_hands_out_what_is_left_of_the_rollback() { + let mut c = Catalog::default(); + let mut ids = Vec::new(); + for name in ["a.jpg", "b.jpg"] { + let id = c.alloc_photo_id(); + let photo = Photo::new(id, Source::File { path: format!("/p/{name}") }, name, "JPEG", 60, 40, "2026-01-01T10:00:00"); + c.apply(Op::AddPhoto { photo: Box::new(photo) }).unwrap(); + ids.push(id); + } + let stack = c.alloc_stack_id(); + c.apply(Op::AddStack { stack: Stack { id: stack, photos: ids.clone(), collapsed: false } }).unwrap(); + let before = c.to_snapshot(); + let missing = PhotoId(9_999); + // the photo goes, then its stack, then an op fails: putting the stack back needs the photo, which comes later + let torn = |ops: Vec| Op::Batch { ops: vec![Op::RemovePhoto { id: ids[0] }, Op::RemoveStack { id: stack }].into_iter().chain(ops).collect() }; + let fail = Op::SetRating { id: missing, rating: 1 }; + + let revision = c.revision; + let e = c.apply(torn(vec![fail.clone()])).unwrap_err(); + assert_eq!(c.revision, revision + 1, "the catalog changed, so what is derived from its revision is out of date"); + assert_eq!(c.touched_since(revision), None, "and nothing is said of what changed"); + let CatalogError::PartlyApplied { cause, remaining } = e else { panic!("expected a partly applied batch, got {e:?}") }; + assert_eq!(*cause, CatalogError::NoPhoto(missing)); + assert_ne!(c.to_snapshot(), before, "the rollback went only part of the way"); + // what is left finishes the rollback + c.apply(*remaining).unwrap(); + assert_eq!(c.to_snapshot(), before); + + // a batch in a batch: what the inner one could not take back is taken back by the outer one's rollback, when it can + let nested = Op::Batch { ops: vec![Op::SetRating { id: ids[1], rating: 5 }, torn(vec![fail.clone()])] }; + assert_eq!(c.apply(nested), Err(CatalogError::NoPhoto(missing))); + assert_eq!(c.to_snapshot(), before); + + // an op that fails plainly is not partly applied, and leaves nothing for the next op to hand out + assert_eq!(c.apply(fail), Err(CatalogError::NoPhoto(missing))); + assert_eq!(c.to_snapshot(), before); +} + +/// A batch that succeeded inside a batch that fails is taken back by its inverse, which is a batch too. When that inverse +/// cannot go through as a whole (the stack is put back before the photo it holds), its ops are taken back one by one, +/// so that what is handed out for a retry is only what still has to be done and the retry can finish. +#[test] +fn the_inverse_of_a_nested_batch_is_taken_back_op_by_op() { + let mut c = Catalog::default(); + let mut ids = Vec::new(); + for name in ["a.jpg", "b.jpg"] { + let id = c.alloc_photo_id(); + let photo = Photo::new(id, Source::File { path: format!("/p/{name}") }, name, "JPEG", 60, 40, "2026-01-01T10:00:00"); + c.apply(Op::AddPhoto { photo: Box::new(photo) }).unwrap(); + ids.push(id); + } + let stack = c.alloc_stack_id(); + c.apply(Op::AddStack { stack: Stack { id: stack, photos: ids.clone(), collapsed: false } }).unwrap(); + let before = c.to_snapshot(); + let missing = PhotoId(9_999); + // the inner batch goes through (the photo goes, then its stack); the outer one fails after it + let inner = Op::Batch { ops: vec![Op::RemovePhoto { id: ids[0] }, Op::RemoveStack { id: stack }] }; + let outer = Op::Batch { ops: vec![inner, Op::SetRating { id: missing, rating: 1 }] }; + let e = c.apply(outer).unwrap_err(); + let CatalogError::PartlyApplied { cause, remaining } = e else { panic!("expected a partly applied batch, got {e:?}") }; + assert_eq!(*cause, CatalogError::NoPhoto(missing)); + assert!(c.photo(ids[0]).is_some(), "the photo came back: only what could not yet be done is left"); + let Op::Batch { ops: left } = remaining.as_ref() else { panic!("a batch of what is left") }; + assert!(matches!(left.as_slice(), [Op::AddStack { .. }]), "just the stack, on its own: {left:?}"); + // what is left finishes the rollback + c.apply(*remaining).unwrap(); + assert_eq!(c.to_snapshot(), before); +} + +/// A batch that was only partly taken back is logged as it was and leaves the same changes when the log is replayed: the +/// replay counts it and goes on with the records after it (the journal's open does the same). +#[test] +fn replaying_a_log_goes_on_after_a_partly_applied_batch() { + let mut c = Catalog::default(); + let mut ids = Vec::new(); + for name in ["a.jpg", "b.jpg"] { + let id = c.alloc_photo_id(); + let photo = Photo::new(id, Source::File { path: format!("/p/{name}") }, name, "JPEG", 60, 40, "2026-01-01T10:00:00"); + c.apply(Op::AddPhoto { photo: Box::new(photo) }).unwrap(); + ids.push(id); + } + let stack = c.alloc_stack_id(); + c.apply(Op::AddStack { stack: Stack { id: stack, photos: ids.clone(), collapsed: false } }).unwrap(); + let start = c.clone(); + // the photo goes, then its stack, then an op fails: putting the stack back needs the photo, which comes later + let torn = + Op::Batch { ops: vec![Op::RemovePhoto { id: ids[0] }, Op::RemoveStack { id: stack }, Op::SetRating { id: PhotoId(9_999), rating: 1 }] }; + let rate = Op::SetRating { id: ids[1], rating: 4 }; + assert!(matches!(c.apply(torn.clone()), Err(CatalogError::PartlyApplied { .. }))); + c.apply(rate.clone()).unwrap(); + + let log = format!("{}{}", Catalog::op_to_log_line(&torn), Catalog::op_to_log_line(&rate)); + let mut replayed = start; + assert_eq!(replayed.replay(&log).unwrap(), 2, "both records were replayed"); + assert_eq!(replayed.to_snapshot(), c.to_snapshot(), "the log gives what the session had"); + + // an op that fails plainly still stops the replay + let bad = Op::SetRating { id: PhotoId(9_999), rating: 1 }; + assert_eq!(replayed.replay(&Catalog::op_to_log_line(&bad)), Err(CatalogError::NoPhoto(PhotoId(9_999)))); +} + +/// `Photo::embedded_lens` is boxed to keep photo records small; the box doesn't change the serialized form: +/// a photo written with the lens reads back with it, and its JSON is the bare lens, as before the box. +#[test] +fn boxed_embedded_lens_serializes_like_the_bare_lens() { + let lens = lightcraft_develop::EmbeddedLens { warp: Some(Default::default()), vignette: None, stages: Default::default(), ..Default::default() }; + let mut p = Photo::new(PhotoId(1), Source::File { path: "/x.dng".into() }, "x.dng", "DNG", 4000, 3000, "2026-10-06T00:00:00"); + p.embedded_lens = Some(Box::new(lens)); + let json = serde_json::to_value(&p).unwrap(); + assert_eq!(json["embedded_lens"], serde_json::to_value(lens).unwrap()); + let back: Photo = serde_json::from_value(json).unwrap(); + assert_eq!(back.embedded_lens.as_deref(), Some(&lens)); + p.embedded_lens = None; + assert!(serde_json::to_value(&p).unwrap().get("embedded_lens").is_none(), "no lens, no field"); +} diff --git a/crates/catalog/src/tests_format_version.rs b/crates/catalog/src/tests_format_version.rs index 248933a4a2..c123b97181 100644 --- a/crates/catalog/src/tests_format_version.rs +++ b/crates/catalog/src/tests_format_version.rs @@ -192,6 +192,33 @@ fn bad_crc_is_still_a_torn_tail() { assert!(r.torn_bytes > 0 && r.damaged.is_none(), "{r:?}"); } +/// A v13 library (bursts as culling made them) reads every analysis as not arranged by hand and +/// is rewritten in the current format; a place set by hand survives the round trip, and none is +/// written for a photo left as culling placed it. +#[test] +fn v13_analysis_loads_unarranged_and_is_upgraded() { + let mut c = Catalog::new(); + let id = c.alloc_photo_id(); + let mut p = Photo::new(id, Source::File { path: "/p/a.jpg".into() }, "a.jpg", "JPEG", 160, 120, "2026-01-01"); + p.analysis = Some(Analysis { sharpness: 61.0, clipped: 0.01, group: Some(2), best: true, ..Default::default() }); + c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + let snap = c.to_snapshot(); + assert!(!snap.contains("rank"), "nothing new is written for a burst culling made: {snap}"); + let m = MemStore::new(); + m.set(SNAPSHOT, format!("{{\"format\":\"lightcraft-catalog\",\"version\":13,\"seq\":1,\"catalog\":{snap}}}\n").into_bytes()); + let (_, loaded, r) = Journal::open(Box::new(m.clone())).unwrap(); + let a = loaded.photo(id).unwrap().analysis.unwrap(); + assert_eq!((a.group, a.best, a.rank, a.by_hand()), (Some(2), true, None, false)); + assert_eq!(r.upgraded_from, Some(13)); + assert_eq!(snapshot_version(&m), u64::from(VERSION)); + // a place set by hand round-trips + let mut c = loaded; + let b = Analysis { rank: Some(1), best: false, ..a }; + c.apply(Op::SetAnalysis { id, analysis: Some(b) }).unwrap(); + let again: Catalog = serde_json::from_str(&c.to_snapshot()).unwrap(); + assert_eq!(again.photo(id).unwrap().analysis, Some(b)); +} + /// Guard for the version rule (see `journal` → *Format versions*): adding an [`Op`] variant breaks /// this match. When it does, bump `journal::VERSION`, add a row to the format table, and add the /// variant here under the new version. A version that only adds serialized fields raises @@ -238,9 +265,595 @@ fn op_variants_are_versioned() { Op::SetHistoryCursor { .. } => 8, } } - /// v13: Lens Blur in develop settings and mask adjustments (v12: `Catalog.grids` and `SegMask.grid`; v11: `EmbeddedLens.source`; - /// v10: `Mask.on_photo`; v9: `Photo.preview_checked` and `Op::SetContent.preview_checked`). - const NEWEST_FIELDS: u32 = 13; + /// v14: `Analysis.rank` (v13: Lens Blur in develop settings and mask adjustments; v12: `Catalog.grids` and `SegMask.grid`; + /// v11: `EmbeddedLens.source`; v10: `Mask.on_photo`; v9: `Photo.preview_checked` and `Op::SetContent.preview_checked`). + const NEWEST_FIELDS: u32 = 14; let newest = since(&Op::SetHistoryCursor { id: PhotoId(1), cursor: None }); assert_eq!(newest.max(NEWEST_FIELDS), VERSION, "the newest op's or fields' version must be the current format version"); } + +// ---- an upgrade keeps what it replaces + +/// A store whose writes of some files fail. +struct Refusing { + files: MemStore, + refuse: fn(&str) -> bool, +} + +impl Store for Refusing { + fn read(&mut self, name: &str) -> std::io::Result>> { + self.files.read(name) + } + fn write_atomic(&mut self, name: &str, data: &[u8]) -> std::io::Result<()> { + if (self.refuse)(name) { + return Err(std::io::Error::other("disk full")); + } + self.files.write_atomic(name, data) + } + fn append(&mut self, name: &str, data: &[u8]) -> std::io::Result<()> { + self.files.append(name, data) + } + fn truncate(&mut self, name: &str, len: u64) -> std::io::Result<()> { + self.files.truncate(name, len) + } + fn remove(&mut self, name: &str) -> std::io::Result<()> { + self.files.remove(name) + } + fn describe(&self) -> String { + "refusing".into() + } +} + +/// The library `fixtures/v-catalog.*` holds, written by the build of format `N`. +fn fixture(version: u32) -> Option<(&'static str, &'static str)> { + match version { + 6 => Some((include_str!("fixtures/v6-catalog.snap.json"), include_str!("fixtures/v6-catalog.log.jsonl"))), + _ => None, + } +} + +/// A format 6 library (the fixture) in a store. +fn v6_library() -> (MemStore, Vec, Vec) { + let (snap, log) = fixture(6).unwrap(); + let m = MemStore::new(); + m.set(SNAPSHOT, snap.as_bytes().to_vec()); + m.set(LOG, log.as_bytes().to_vec()); + (m, snap.as_bytes().to_vec(), log.as_bytes().to_vec()) +} + +/// Given a library in an older format, when it is opened (which rewrites it in this build's +/// format, and older builds can't read that), then the files it was are kept beside it, byte for +/// byte, under names that say their format and the change they end at; the report names them; +/// and put back under their own names they are the library as it was. +#[test] +fn an_upgrade_keeps_the_files_it_replaces() { + let (m, snap, log) = v6_library(); + let (_, upgraded, r) = Journal::open(Box::new(m.clone())).unwrap(); + assert_eq!(r.upgraded_from, Some(6)); + assert_eq!(r.kept, ["catalog.snap.v6-8", "catalog.log.v6-8"]); + assert_eq!((m.get("catalog.snap.v6-8"), m.get("catalog.log.v6-8")), (Some(snap.clone()), Some(log.clone()))); + assert_eq!(snapshot_version(&m), u64::from(VERSION)); + + // the way back: the kept files under their own names + let back = MemStore::new(); + back.set(SNAPSHOT, m.get("catalog.snap.v6-8").unwrap()); + back.set(LOG, m.get("catalog.log.v6-8").unwrap()); + assert_eq!(snapshot_version(&back), 6); + let (_, mut as_it_was, _) = Journal::open(Box::new(back)).unwrap(); + as_it_was.revision = upgraded.revision; + assert_eq!(as_it_was, upgraded); +} + +/// Given a library that is in this build's format already, or a new one, when it is opened, +/// then nothing is kept: there is nothing an older build could have read. +#[test] +fn nothing_is_kept_without_an_upgrade() { + let m = MemStore::new(); + let (_, _, r) = Journal::open(Box::new(m.clone())).unwrap(); + assert!(r.created && r.kept.is_empty()); + let (_, _, r) = Journal::open(Box::new(m.clone())).unwrap(); + assert!(r.kept.is_empty() && r.upgraded_from.is_none()); + assert_eq!(m.files.lock().unwrap().keys().collect::>(), [SNAPSHOT]); +} + +/// Given a library from before snapshots (only a log), when it is opened, then the log is kept +/// (as format 0: there was no number yet) and no snapshot is made up for it. +#[test] +fn an_upgrade_of_a_log_only_library_keeps_the_log() { + let mut c = Catalog::new(); + let op = photo(&mut c); + let log = format!("{}\n", encode_record(1, &op)).into_bytes(); + let m = MemStore::new(); + m.set(LOG, log.clone()); + let (_, _, r) = Journal::open(Box::new(m.clone())).unwrap(); + assert_eq!((r.upgraded_from, r.kept.as_slice()), (Some(0), ["catalog.log.v0-1".to_string()].as_slice())); + assert_eq!(m.get("catalog.log.v0-1"), Some(log)); + assert_eq!(m.get("catalog.snap.v0-1"), None); +} + +/// Given an older library whose files can't be kept (the disk is full), when it is opened, then +/// it is not upgraded without its way back: it opens as it is, with its files as they were and +/// nothing half kept, and is upgraded once there is room. +#[test] +fn a_library_that_cannot_be_kept_is_not_upgraded() { + let (m, snap, log) = v6_library(); + let store = Refusing { files: m.clone(), refuse: |name| name.starts_with("catalog.log.v") }; + let (_, c, r) = Journal::open(Box::new(store)).unwrap(); + assert_eq!((c.photos().count(), r.upgraded_from, r.kept.len()), (3, None, 0)); + assert_eq!((m.get(SNAPSHOT), m.get(LOG)), (Some(snap), Some(log))); + assert_eq!(m.files.lock().unwrap().keys().collect::>(), [LOG, SNAPSHOT], "nothing half kept"); + + let (_, c, r) = Journal::open(Box::new(m.clone())).unwrap(); + assert_eq!((c.photos().count(), r.upgraded_from, r.kept.len()), (3, Some(6), 2)); +} + +/// Given an older library on disk whose files can't be kept (the staging name of the second is taken by a directory, +/// so the first was written and must be removed again), when it is opened, then it is not upgraded, and no copy or +/// half-written staging file of the files it tried to keep is left lying about in the library's folder. +#[test] +fn a_library_on_disk_that_cannot_be_kept_leaves_nothing_lying_about() { + let dir = std::env::temp_dir().join(format!("lc-keep-fails-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join("catalog.log.v6-8.tmp")).unwrap(); + let (snap, log) = fixture(6).unwrap(); + std::fs::write(dir.join(SNAPSHOT), snap).unwrap(); + std::fs::write(dir.join(LOG), log).unwrap(); + + let (_, c, r) = Journal::open(Box::new(FsStore::open(&dir).unwrap())).unwrap(); + assert_eq!((c.photos().count(), r.upgraded_from, r.kept.len()), (3, None, 0)); + let mut names: Vec<_> = std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect(); + names.sort(); + assert_eq!(names, [LOG, "catalog.log.v6-8.tmp", SNAPSHOT], "nothing but the library and the name that was taken"); + assert_eq!(std::fs::read(dir.join(SNAPSHOT)).unwrap(), snap.as_bytes()); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Given an older library whose upgrade can't be written, when it is opened, then it opens as it +/// was, with no copy of it left lying about: there is nothing to go back from. +#[test] +fn a_failed_upgrade_leaves_no_copy() { + let (m, snap, log) = v6_library(); + let store = Refusing { files: m.clone(), refuse: |name| name == SNAPSHOT }; + let (_, c, r) = Journal::open(Box::new(store)).unwrap(); + assert_eq!((c.photos().count(), r.upgraded_from, r.kept.len()), (3, None, 0)); + assert_eq!((m.get(SNAPSHOT), m.get(LOG)), (Some(snap), Some(log))); + assert_eq!(m.files.lock().unwrap().keys().collect::>(), [LOG, SNAPSHOT]); +} + +/// Given an older library whose upgrade is written but whose log then can't be emptied, when it +/// is opened, then it is upgraded all the same (the log's changes are in the snapshot, and are +/// passed over when it is read), and the files it was are kept: its way back is not thrown away +/// because something failed after the upgrade. +#[test] +fn an_upgrade_that_is_written_keeps_its_copies_whatever_fails_after() { + let (m, snap, log) = v6_library(); + let store = Refusing { files: m.clone(), refuse: |name| name == LOG }; + let (_, c, r) = Journal::open(Box::new(store)).unwrap(); + assert_eq!((c.photos().count(), r.upgraded_from), (3, Some(6))); + assert_eq!(r.kept, ["catalog.snap.v6-8", "catalog.log.v6-8"]); + assert_eq!((m.get("catalog.snap.v6-8"), m.get("catalog.log.v6-8")), (Some(snap), Some(log.clone()))); + assert_eq!(snapshot_version(&m), u64::from(VERSION)); + // the log it could not empty is all in the snapshot + assert_eq!(m.get(LOG), Some(log)); + let (_, mut again, r) = Journal::open(Box::new(m)).unwrap(); + again.revision = c.revision; + assert_eq!((again, r.replayed, r.upgraded_from), (c, 0, None)); +} + +/// Given an older library whose log is damaged, when it is opened (which saves what could be +/// read in this build's format), then that is an upgrade like any other: the snapshot it was is +/// kept beside the damaged log. +#[test] +fn a_damaged_older_library_keeps_its_snapshot() { + let (m, snap, log) = v6_library(); + // a record in the middle that is not what was written, with good ones after it + let mut lines: Vec = String::from_utf8(log).unwrap().lines().map(str::to_string).collect(); + lines[1] = lines[1].replacen("\"crc\":", "\"crc\":1", 1); + let damaged = format!("{}\n", lines.join("\n")).into_bytes(); + m.set(LOG, damaged.clone()); + let (_, _, r) = Journal::open(Box::new(m.clone())).unwrap(); + let kept_log = r.damaged.clone().expect("damaged"); + assert_eq!((r.upgraded_from, r.kept.as_slice()), (Some(6), ["catalog.snap.v6-4".to_string()].as_slice()), "{r:?}"); + assert_eq!((m.get("catalog.snap.v6-4"), m.get(&kept_log)), (Some(snap), Some(damaged))); + assert_eq!(snapshot_version(&m), u64::from(VERSION)); +} + +/// Given an older library whose log is damaged, when the upgrade is written but the damaged log +/// can't be replaced, then the library is refused (working in it would add changes after the +/// damage, where the next open would not read them), with the snapshot it was kept; and it +/// opens, repaired, once the log can be written. +#[test] +fn a_damaged_older_library_is_not_worked_in_with_its_damaged_log_in_place() { + let (m, snap, log) = v6_library(); + let mut lines: Vec = String::from_utf8(log).unwrap().lines().map(str::to_string).collect(); + lines[1] = lines[1].replacen("\"crc\":", "\"crc\":1", 1); + m.set(LOG, format!("{}\n", lines.join("\n")).into_bytes()); + let store = Refusing { files: m.clone(), refuse: |name| name == LOG }; + let e = Journal::open(Box::new(store)).err().expect("refused"); + assert!(matches!(&e, CatalogError::Io(why) if why.contains("damaged log")), "{e}"); + assert_eq!(m.get("catalog.snap.v6-4"), Some(snap), "its way back stays"); + + let (_, c, r) = Journal::open(Box::new(m.clone())).unwrap(); + assert_eq!(c.photos().count(), 3); + assert!(r.damaged.is_some() && m.get(LOG).unwrap().is_empty(), "{r:?}"); +} + +/// Given an older library whose upgrade fails in a way that leaves it unknown whether it was +/// written (the snapshot can't be read afterwards), then the files it was are kept: the way +/// back is given up only when the library is known to be as it was. +#[test] +fn an_upgrade_that_cannot_be_checked_keeps_its_copies() { + /// Fails the write of the snapshot, and every read of it after that. + struct Blind { + files: MemStore, + failed: bool, + } + impl Store for Blind { + fn read(&mut self, name: &str) -> std::io::Result>> { + if self.failed && name == SNAPSHOT { + return Err(std::io::Error::other("unreadable")); + } + self.files.read(name) + } + fn write_atomic(&mut self, name: &str, data: &[u8]) -> std::io::Result<()> { + if name == SNAPSHOT { + self.failed = true; + return Err(std::io::Error::other("the share went away")); + } + self.files.write_atomic(name, data) + } + fn append(&mut self, name: &str, data: &[u8]) -> std::io::Result<()> { + self.files.append(name, data) + } + fn truncate(&mut self, name: &str, len: u64) -> std::io::Result<()> { + self.files.truncate(name, len) + } + fn remove(&mut self, name: &str) -> std::io::Result<()> { + self.files.remove(name) + } + fn describe(&self) -> String { + "blind".into() + } + } + let (m, snap, log) = v6_library(); + let e = Journal::open(Box::new(Blind { files: m.clone(), failed: false })).err().expect("refused"); + assert!(matches!(&e, CatalogError::Io(why) if why.contains("can't be told")), "{e}"); + assert_eq!((m.get("catalog.snap.v6-8"), m.get("catalog.log.v6-8")), (Some(snap), Some(log))); +} + +/// Given an older library that was not upgraded at open (its files can't be kept), when a later +/// snapshot would upgrade it (a compaction, or closing), then that snapshot is not written: the +/// library stays as it was, with nothing half kept, and is never upgraded without its way back. +#[test] +fn a_library_that_could_not_be_kept_is_not_upgraded_by_a_later_snapshot_either() { + let (m, snap, log) = v6_library(); + let store = Refusing { files: m.clone(), refuse: |name| name.starts_with("catalog.log.v") }; + let (mut j, c, r) = Journal::open(Box::new(store)).unwrap(); + assert_eq!(r.upgraded_from, None); + assert!(j.snapshot(&c).is_err(), "closing"); + assert!(j.snapshot_in_background(&c).is_err(), "a compaction"); + assert_eq!((m.get(SNAPSHOT), m.get(LOG)), (Some(snap), Some(log))); + assert_eq!(m.files.lock().unwrap().keys().collect::>(), [LOG, SNAPSHOT], "nothing half kept"); +} + +/// Given an older library whose upgrade could not be written at open (a full disk), when a later +/// snapshot is written (the disk has room again), then the files it was are kept first, as the +/// open would have kept them, and the library is upgraded. +#[test] +fn a_library_left_in_its_old_format_keeps_its_files_when_a_later_snapshot_upgrades_it() { + static FULL: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true); + let (m, snap, log) = v6_library(); + let store = Refusing { files: m.clone(), refuse: |name| name == SNAPSHOT && FULL.load(std::sync::atomic::Ordering::SeqCst) }; + let (mut j, c, r) = Journal::open(Box::new(store)).unwrap(); + assert_eq!((r.upgraded_from, r.kept.len()), (None, 0)); + assert!(j.snapshot(&c).is_err(), "still full"); + assert_eq!(m.files.lock().unwrap().keys().collect::>(), [LOG, "catalog.log.v6-8", SNAPSHOT, "catalog.snap.v6-8"], "kept, not upgraded"); + FULL.store(false, std::sync::atomic::Ordering::SeqCst); + j.snapshot(&c).unwrap(); + assert_eq!((m.get("catalog.snap.v6-8"), m.get("catalog.log.v6-8")), (Some(snap), Some(log))); + assert_eq!(snapshot_version(&m), u64::from(VERSION)); +} + +/// Given an older library whose log is damaged and whose snapshot can't be kept, when it is +/// opened, then it is refused and left as it was (it is not repaired without its way back). +#[test] +fn a_damaged_older_library_whose_snapshot_cannot_be_kept_is_refused() { + let (m, snap, log) = v6_library(); + let mut lines: Vec = String::from_utf8(log).unwrap().lines().map(str::to_string).collect(); + lines[1] = lines[1].replacen("\"crc\":", "\"crc\":1", 1); + let damaged = format!("{}\n", lines.join("\n")).into_bytes(); + m.set(LOG, damaged.clone()); + let store = Refusing { files: m.clone(), refuse: |name| name.starts_with("catalog.snap.v") }; + let e = Journal::open(Box::new(store)).err().expect("refused"); + assert!(matches!(&e, CatalogError::Io(why) if why.contains("can't be kept")), "{e}"); + assert_eq!((m.get(SNAPSHOT), m.get(LOG)), (Some(snap), Some(damaged))); +} + +/// Given an older library that was not upgraded at open (its files can't be kept), when a later +/// snapshot upgrades it, then the files that snapshot kept are told once, after it is written +/// (not before, not for a snapshot that failed, and the open's report has none). +#[test] +fn the_files_a_later_snapshot_keeps_are_told_once_it_is_written() { + static FULL: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true); + let (m, _, _) = v6_library(); + let store = Refusing { files: m.clone(), refuse: |name| name == SNAPSHOT && FULL.load(std::sync::atomic::Ordering::SeqCst) }; + let (mut j, c, r) = Journal::open(Box::new(store)).unwrap(); + assert!(r.kept.is_empty()); + assert!(j.snapshot(&c).is_err(), "still full"); + assert!(j.take_kept().is_empty(), "kept for a snapshot that is not written: nothing to tell yet"); + FULL.store(false, std::sync::atomic::Ordering::SeqCst); + j.snapshot(&c).unwrap(); + assert_eq!(j.take_kept(), ["catalog.snap.v6-8", "catalog.log.v6-8"]); + assert!(j.take_kept().is_empty(), "once"); +} + +/// Given a library opened in its old format (its upgrade could not be written) that is then +/// changed, in this build's ops, before any snapshot is tried, when a later snapshot upgrades it, +/// then the files kept are the library as it was at open, under the names the open would have +/// given them: not the log as it is now, and nothing piles up. (An older build can read them +/// whatever was appended since.) +#[test] +fn files_kept_by_a_later_snapshot_are_the_library_as_it_was_at_open() { + static FULL: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true); + let (m, snap, log) = v6_library(); + let store = Refusing { files: m.clone(), refuse: |name| name == SNAPSHOT && FULL.load(std::sync::atomic::Ordering::SeqCst) }; + let (mut j, c, _) = Journal::open(Box::new(store)).unwrap(); + j.append(&[Op::SetLabelName { label: ColorLabel::ALL[0], name: Some("x".into()) }]).unwrap(); + assert!(m.get(LOG).unwrap().len() > log.len(), "the log has grown"); + assert!(j.snapshot(&c).is_err(), "still full"); + FULL.store(false, std::sync::atomic::Ordering::SeqCst); + j.snapshot(&c).unwrap(); + assert_eq!(j.take_kept(), ["catalog.snap.v6-8", "catalog.log.v6-8"]); + assert_eq!((m.get("catalog.snap.v6-8"), m.get("catalog.log.v6-8")), (Some(snap), Some(log))); + let files = m.files.lock().unwrap(); + assert_eq!(files.keys().filter(|k| k.contains(".v6-")).count(), 2, "{:?}", files.keys()); +} + +/// Given a library left in its old format whose snapshot is in this build's format already (a +/// write that landed and reported a failure, before anything was kept), when snapshots are +/// written, then each of them works: the upgrade is done, with nothing to keep (the old files +/// are gone from under that name), and nothing is refused until the library is reopened. +#[test] +fn a_snapshot_that_landed_is_the_upgrade_done() { + static FULL: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true); + let (m, _, log) = v6_library(); + let store = Refusing { files: m.clone(), refuse: |name| name == SNAPSHOT && FULL.load(std::sync::atomic::Ordering::SeqCst) }; + let (mut j, c, _) = Journal::open(Box::new(store)).unwrap(); + FULL.store(false, std::sync::atomic::Ordering::SeqCst); + m.set(SNAPSHOT, format!("{{\"format\":\"lightcraft-catalog\",\"version\":{VERSION},\"seq\":8,\"catalog\":{}}}\n", c.to_snapshot()).into_bytes()); + j.snapshot(&c).unwrap(); + j.snapshot(&c).unwrap(); + assert!(j.take_kept().is_empty()); + assert_eq!(snapshot_version(&m), u64::from(VERSION)); + assert!(!m.files.lock().unwrap().keys().any(|k| k.contains(".v6-")), "nothing kept from a snapshot that is not the old one"); + let _ = log; +} + +/// Given a library left in its old format, when a snapshot lands after its files were kept but +/// reports a failure, and the snapshot is tried again, then the retry goes through, and the files +/// told are the old library, not the snapshot that is there now. +#[test] +fn a_snapshot_that_landed_after_its_files_were_kept_is_tried_again() { + static LAND: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0); + struct Landing { + inner: Refusing, + } + impl Store for Landing { + fn read(&mut self, name: &str) -> std::io::Result>> { + self.inner.read(name) + } + fn write_atomic(&mut self, name: &str, data: &[u8]) -> std::io::Result<()> { + use std::sync::atomic::Ordering::SeqCst; + if name == SNAPSHOT && LAND.load(SeqCst) == 1 { + // lands, and says it did not (the share dropped the answer) + self.inner.files.write_atomic(name, data)?; + LAND.store(2, SeqCst); + return Err(std::io::Error::other("the share went away")); + } + self.inner.write_atomic(name, data) + } + fn append(&mut self, name: &str, data: &[u8]) -> std::io::Result<()> { + self.inner.append(name, data) + } + fn truncate(&mut self, name: &str, len: u64) -> std::io::Result<()> { + self.inner.truncate(name, len) + } + fn remove(&mut self, name: &str) -> std::io::Result<()> { + self.inner.remove(name) + } + fn describe(&self) -> String { + "landing".into() + } + } + let (m, snap, log) = v6_library(); + let store = + Landing { inner: Refusing { files: m.clone(), refuse: |name| name == SNAPSHOT && LAND.load(std::sync::atomic::Ordering::SeqCst) == 0 } }; + let (mut j, c, _) = Journal::open(Box::new(store)).unwrap(); + LAND.store(1, std::sync::atomic::Ordering::SeqCst); + assert!(j.snapshot(&c).is_err(), "landed, and said it did not"); + assert_eq!(snapshot_version(&m), u64::from(VERSION), "it did land"); + // the upgrade landed: its way back is told now, not only after a later snapshot succeeds + assert_eq!(j.take_kept(), ["catalog.snap.v6-8", "catalog.log.v6-8"]); + j.snapshot(&c).unwrap(); + assert_eq!((m.get("catalog.snap.v6-8"), m.get("catalog.log.v6-8")), (Some(snap), Some(log)), "the old library, not the snapshot that landed"); + assert!(j.take_kept().is_empty(), "told once"); +} + +/// Given a library left in its old format whose snapshot failed after its files were kept, when +/// the snapshot is tried again (a compaction retries as the log grows), then the files are not +/// copied again: a large library is not written out in full at every retry. +#[test] +fn files_kept_for_a_failed_snapshot_are_not_written_again_on_a_retry() { + static FULL: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true); + let (m, _, _) = v6_library(); + let store = Refusing { files: m.clone(), refuse: |name| name == SNAPSHOT && FULL.load(std::sync::atomic::Ordering::SeqCst) }; + let (mut j, c, _) = Journal::open(Box::new(store)).unwrap(); + assert!(j.snapshot(&c).is_err()); + m.set("catalog.snap.v6-8", b"marker".to_vec()); + assert!(j.snapshot(&c).is_err(), "still full"); + assert_eq!(m.get("catalog.snap.v6-8"), Some(b"marker".to_vec()), "not written again"); + FULL.store(false, std::sync::atomic::Ordering::SeqCst); + j.snapshot(&c).unwrap(); + assert_eq!(j.take_kept(), ["catalog.snap.v6-8", "catalog.log.v6-8"]); +} + +/// Given a library restored from an older backup that reaches the same format and change as a set +/// kept before (other bytes under the same names), when it is upgraded, then the set kept before is +/// left as it was, and the new files are kept beside it, both under names ending `-2`. +#[test] +fn files_kept_before_are_never_overwritten() { + let (m, snap, log) = v6_library(); + m.set("catalog.snap.v6-8", b"an earlier snapshot".to_vec()); + m.set("catalog.log.v6-8", b"an earlier log".to_vec()); + let (_, _, r) = Journal::open(Box::new(m.clone())).unwrap(); + assert_eq!((r.upgraded_from, r.kept.as_slice()), (Some(6), ["catalog.snap.v6-8-2".to_string(), "catalog.log.v6-8-2".to_string()].as_slice())); + assert_eq!((m.get("catalog.snap.v6-8"), m.get("catalog.log.v6-8")), (Some(b"an earlier snapshot".to_vec()), Some(b"an earlier log".to_vec()))); + assert_eq!((m.get("catalog.snap.v6-8-2"), m.get("catalog.log.v6-8-2")), (Some(snap), Some(log))); +} + +/// Given that set and a copy of it with the same name taken too, when the library is upgraded, then the next free name is used. +#[test] +fn the_next_free_name_is_used_when_several_are_taken() { + let (m, snap, _) = v6_library(); + for name in ["catalog.snap.v6-8", "catalog.snap.v6-8-2"] { + m.set(name, name.as_bytes().to_vec()); + } + let (_, _, r) = Journal::open(Box::new(m.clone())).unwrap(); + assert_eq!(r.kept, ["catalog.snap.v6-8-3", "catalog.log.v6-8-3"]); + assert_eq!(m.get("catalog.snap.v6-8-3"), Some(snap)); +} + +/// Given kept files that are there already, byte for byte the same (an earlier open of this very library), when it is +/// opened, then they are the copy: nothing is written under another name. +#[test] +fn kept_files_that_are_there_already_are_reused() { + let (m, snap, log) = v6_library(); + m.set("catalog.snap.v6-8", snap); + m.set("catalog.log.v6-8", log); + let (_, _, r) = Journal::open(Box::new(m.clone())).unwrap(); + assert_eq!(r.kept, ["catalog.snap.v6-8", "catalog.log.v6-8"]); + assert!(!m.files.lock().unwrap().keys().any(|k| k.ends_with("-2"))); +} + +/// Given a set kept before whose snapshot is this very one but whose log holds other bytes, when the library is +/// upgraded, then both files of the new set take the next name, and the set kept before is left as it was. +#[test] +fn a_set_with_the_same_snapshot_and_another_log_is_not_reused_in_part() { + let (m, snap, log) = v6_library(); + m.set("catalog.snap.v6-8", snap.clone()); + m.set("catalog.log.v6-8", b"another log".to_vec()); + let (_, _, r) = Journal::open(Box::new(m.clone())).unwrap(); + assert_eq!(r.kept, ["catalog.snap.v6-8-2", "catalog.log.v6-8-2"]); + assert_eq!((m.get("catalog.snap.v6-8"), m.get("catalog.log.v6-8")), (Some(snap.clone()), Some(b"another log".to_vec()))); + assert_eq!((m.get("catalog.snap.v6-8-2"), m.get("catalog.log.v6-8-2")), (Some(snap), Some(log))); +} + +/// Given a hundred sets kept before under every name the upgrade may take, when the library is opened, then it is not +/// upgraded, nothing is written and nothing is removed: an upgrade that can't keep its files is not done. +#[test] +fn an_upgrade_is_refused_when_a_hundred_kept_sets_are_in_the_way() { + let (m, snap, log) = v6_library(); + m.set("catalog.snap.v6-8", b"earlier".to_vec()); + for copy in 2..=100 { + m.set(&format!("catalog.snap.v6-8-{copy}"), b"earlier".to_vec()); + } + let before = m.files.lock().unwrap().clone(); + let (_, _, r) = Journal::open(Box::new(m.clone())).unwrap(); + assert_eq!((r.upgraded_from, r.kept.len()), (None, 0)); + assert_eq!(*m.files.lock().unwrap(), before, "nothing written or removed"); + assert_eq!((m.get(SNAPSHOT), m.get(LOG)), (Some(snap), Some(log))); +} + +/// Given kept files that were there before and an upgrade that is then not written (a full disk), when the library is +/// opened, then they stay: only what this open wrote is removed again. +#[test] +fn an_upgrade_that_is_not_written_removes_only_what_it_kept() { + let (m, snap, log) = v6_library(); + m.set("catalog.snap.v6-8", snap.clone()); + m.set("catalog.log.v6-8", log.clone()); + let store = Refusing { files: m.clone(), refuse: |name| name == SNAPSHOT }; + let (_, _, r) = Journal::open(Box::new(store)).unwrap(); + assert_eq!((r.upgraded_from, r.kept.len()), (None, 0)); + assert_eq!((m.get("catalog.snap.v6-8"), m.get("catalog.log.v6-8")), (Some(snap), Some(log)), "kept before, and still there"); + assert_eq!(snapshot_version(&m), 6); + + // and a different set that was in the way, with the new one not written whole + let (m, snap, log) = v6_library(); + m.set("catalog.snap.v6-8", b"earlier".to_vec()); + m.set("catalog.log.v6-8", b"earlier".to_vec()); + let store = Refusing { files: m.clone(), refuse: |name| name.starts_with("catalog.log.v") }; + let (_, _, r) = Journal::open(Box::new(store)).unwrap(); + assert_eq!((r.upgraded_from, r.kept.len()), (None, 0)); + assert_eq!((m.get("catalog.snap.v6-8"), m.get("catalog.log.v6-8")), (Some(b"earlier".to_vec()), Some(b"earlier".to_vec()))); + assert_eq!((m.get(SNAPSHOT), m.get(LOG)), (Some(snap), Some(log))); + assert_eq!(m.files.lock().unwrap().keys().collect::>(), [LOG, "catalog.log.v6-8", SNAPSHOT, "catalog.snap.v6-8"], "nothing half kept"); +} + +/// Given a store that writes a kept file and then reports a failure (a network share that dropped its answer), when an +/// older library is opened, then it is not upgraded, and the file that landed is not left behind. +#[test] +fn a_kept_file_that_landed_despite_an_error_is_removed() { + struct Dropped(MemStore); + impl Store for Dropped { + fn read(&mut self, name: &str) -> std::io::Result>> { + self.0.read(name) + } + fn write_atomic(&mut self, name: &str, data: &[u8]) -> std::io::Result<()> { + self.0.write_atomic(name, data)?; + if name.starts_with("catalog.log.v") { + return Err(std::io::Error::other("the share went away")); + } + Ok(()) + } + fn append(&mut self, name: &str, data: &[u8]) -> std::io::Result<()> { + self.0.append(name, data) + } + fn truncate(&mut self, name: &str, len: u64) -> std::io::Result<()> { + self.0.truncate(name, len) + } + fn remove(&mut self, name: &str) -> std::io::Result<()> { + self.0.remove(name) + } + fn describe(&self) -> String { + "dropped".into() + } + } + let (m, snap, log) = v6_library(); + let (_, c, r) = Journal::open(Box::new(Dropped(m.clone()))).unwrap(); + assert_eq!((c.photos().count(), r.upgraded_from, r.kept.len()), (3, None, 0)); + assert_eq!((m.get(SNAPSHOT), m.get(LOG)), (Some(snap), Some(log))); + assert_eq!(m.files.lock().unwrap().keys().collect::>(), [LOG, SNAPSHOT], "nothing left of the kept set"); +} + +/// Given a store that keeps no replaced files (the browser's), when an older library is opened, then the report says so +/// (so a damaged log set aside beside it isn't presented as half of a copy of the library as it was). +#[test] +fn the_report_says_whether_the_store_keeps_files() { + struct Browser(MemStore); + impl Store for Browser { + fn read(&mut self, name: &str) -> std::io::Result>> { + self.0.read(name) + } + fn write_atomic(&mut self, name: &str, data: &[u8]) -> std::io::Result<()> { + self.0.write_atomic(name, data) + } + fn append(&mut self, name: &str, data: &[u8]) -> std::io::Result<()> { + self.0.append(name, data) + } + fn truncate(&mut self, name: &str, len: u64) -> std::io::Result<()> { + self.0.truncate(name, len) + } + fn keeps_replaced_formats(&self) -> bool { + false + } + fn describe(&self) -> String { + "browser".into() + } + } + let (m, _, _) = v6_library(); + let (_, _, r) = Journal::open(Box::new(Browser(m.clone()))).unwrap(); + assert!(!r.kept_files && r.kept.is_empty() && r.upgraded_from == Some(6), "{r:?}"); + let (m, _, _) = v6_library(); + let (_, _, r) = Journal::open(Box::new(m)).unwrap(); + assert!(r.kept_files); +} diff --git a/crates/catalog/src/tests_grids.rs b/crates/catalog/src/tests_grids.rs index 54289565fb..2a9724a048 100644 --- a/crates/catalog/src/tests_grids.rs +++ b/crates/catalog/src/tests_grids.rs @@ -390,3 +390,81 @@ fn omitted_shared_grid_table_clears_dangling_references() { let MaskShape::Object { seg: Some(seg), .. } = &p.history[0].settings.masks[0].components[0].shape else { panic!("an Object mask") }; assert_eq!(seg.data, blob, "the history step's inline grid is untouched"); } + +/// Equal settings that refer to the same grid in a snapshot's table are held once after the +/// snapshot is read: resolving the references gives every holder its grid's data, and the +/// holders that are equal again share one value (a library with many masked photos is not +/// held once per photo and step). What is written back is unchanged. +#[test] +fn resolved_grid_references_share_equal_settings() { + let seg = SegMask::from_logits(32, &vec![1.0f32; 32 * 32]); + let settings = Arc::new(settings_with_seg(seg, 0.5)); + let mut live = Catalog::new(); + let mut ops = Vec::new(); + for n in 1..=2u64 { + let id = PhotoId(n); + let name = format!("{n}.jpg"); + ops.push(Op::AddPhoto { photo: Box::new(Photo::new(id, Source::Demo { scene: 0 }, &name, "JPEG", 60, 40, "2026-01-01")) }); + ops.push(Op::SetDevelop { id, settings: settings.clone(), label: "Exposure".into(), edited: Some("t".into()) }); + ops.push(Op::PushHistory { id, step: HistoryStep { label: "Exposure".into(), settings: settings.clone() } }); + ops.push(Op::SetVersions { + id, + versions: vec![Version { name: "v".into(), created: "2026-01-01".into(), settings: settings.clone(), auto: false }], + }); + } + for op in &ops { + live.apply(op.clone()).unwrap(); + } + let m = MemStore::new(); + let (mut j, _, _) = open(&m); + j.append(&ops).unwrap(); + j.snapshot(&live).unwrap(); + drop(j); + let snap_bytes = m.get(SNAPSHOT).unwrap(); + let v: serde_json::Value = serde_json::from_slice(&snap_bytes).unwrap(); + assert_eq!(v["catalog"]["grids"].as_array().unwrap().len(), 1, "the snapshot refers to its one grid"); + assert!(std::str::from_utf8(&snap_bytes).unwrap().contains("\"grid\":0"), "and its masks hold references"); + + let (_, loaded, report) = open(&m); + assert_eq!(report.repaired, Vec::::new(), "{:?}", report.repaired); + assert_eq!(loaded.to_snapshot(), live.to_snapshot()); + let first = &loaded.photo(PhotoId(1)).unwrap().develop; + for n in 1..=2 { + let p = loaded.photo(PhotoId(n)).unwrap(); + assert!(Arc::ptr_eq(&p.develop, first), "photo {n}'s settings"); + assert!(p.history.iter().all(|h| Arc::ptr_eq(&h.settings, first)), "photo {n}'s history"); + assert!(p.versions.iter().all(|v| Arc::ptr_eq(&v.settings, first)), "photo {n}'s versions"); + } +} + +/// A masked photo whose history is longer than the few values sharing remembers still holds its +/// settings and its last step once: the references of equal holders resolve to one value, not to +/// a copy per holder that is shared only when it happens to be remembered. +#[test] +fn a_masked_photos_settings_share_with_its_last_step_after_a_long_history() { + let seg = SegMask::from_logits(32, &vec![1.0f32; 32 * 32]); + let id = PhotoId(1); + let mut live = Catalog::new(); + let mut ops = vec![Op::AddPhoto { photo: Box::new(Photo::new(id, Source::Demo { scene: 0 }, "1.jpg", "JPEG", 60, 40, "2026-01-01")) }]; + let mut last = Arc::new(DevelopSettings::default()); + for i in 1..=10u32 { + last = Arc::new(settings_with_seg(seg.clone(), f64::from(i) * 0.1)); + ops.push(Op::PushHistory { id, step: HistoryStep { label: "Exposure".into(), settings: last.clone() } }); + } + ops.push(Op::SetDevelop { id, settings: last, label: "Exposure".into(), edited: Some("t".into()) }); + for op in &ops { + live.apply(op.clone()).unwrap(); + } + let m = MemStore::new(); + let (mut j, _, _) = open(&m); + j.append(&ops).unwrap(); + j.snapshot(&live).unwrap(); + drop(j); + let (_, loaded, report) = open(&m); + assert_eq!(report.repaired, Vec::::new(), "{:?}", report.repaired); + assert_eq!(loaded.to_snapshot(), live.to_snapshot()); + let p = loaded.photo(id).unwrap(); + assert_eq!(p.history.len(), 10); + let last = p.history.last().unwrap(); + assert!(Arc::ptr_eq(&p.develop, &last.settings), "the photo's settings and its last step are one value"); +} diff --git a/crates/catalog/src/tests_looping_albums.rs b/crates/catalog/src/tests_looping_albums.rs new file mode 100644 index 0000000000..50f887dd2d --- /dev/null +++ b/crates/catalog/src/tests_looping_albums.rs @@ -0,0 +1,235 @@ +//! A smart album on a loop (it includes itself through the albums it tests) holds nothing, +//! whichever way it is asked: its photos, its count, whether it holds one photo, the grid's query +//! for it. The rule, stated once: +//! +//! * an album **on** a loop (a ring of albums testing one another, or one testing itself) holds no +//! photos; +//! * an album **off** every loop is worked out as always, and one that tests a looping album sees +//! it as the empty album it is (so "is in A" matches nothing and "isn't in A" matches all); +//! * mending the loop (changing rules, removing an album) gives each album its photos back. + +use super::*; + +/// A smart album with `any` of the rules in `rules` (a JSON array). +fn any_of(id: u64, rules: serde_json::Value) -> Album { + let filter: Filter = serde_json::from_value(serde_json::json!({"ruleSet": {"match": "any", "rules": rules}})).unwrap(); + Album { smart: Some(Box::new(filter)), ..Album::new(AlbumId(id), format!("Smart {id}")) } +} + +fn in_album(op: &str, id: u64) -> serde_json::Value { + serde_json::json!({"field": "album", "op": op, "value": id}) +} + +fn picked() -> serde_json::Value { + serde_json::json!({"field": "flag", "op": "is", "value": "pick"}) +} + +fn rated(n: u64) -> serde_json::Value { + serde_json::json!({"field": "rating", "op": "gte", "value": n}) +} + +/// Three photos: `.0` is picked, `.1` is rated 5, `.2` is neither. +fn photos(c: &mut Catalog) -> (PhotoId, PhotoId, PhotoId) { + let mut add = |name: &str| { + let id = c.alloc_photo_id(); + let p = Photo::new(id, Source::Demo { scene: 1 }, name, "JPEG", 600, 400, "2026-09-30T10:00:00"); + c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + id + }; + let ids = (add("picked.jpg"), add("rated.jpg"), add("plain.jpg")); + c.apply(Op::SetFlag { id: ids.0, flag: Flag::Pick }).unwrap(); + c.apply(Op::SetRating { id: ids.1, rating: 5 }).unwrap(); + ids +} + +fn add(c: &mut Catalog, album: Album) { + c.apply(Op::AddAlbum { album }).unwrap(); +} + +/// What the grid shows for `album`: the query the sidebar click makes. +fn grid(c: &Catalog, album: u64) -> Vec { + c.query(&Filter { album: Some(AlbumId(album)), ..Default::default() }, &Sort::default()) +} + +/// Every way of asking what an album holds agrees it holds `want`. +#[track_caller] +fn assert_holds(c: &Catalog, album: u64, want: &[PhotoId]) { + let mut want = want.to_vec(); + want.sort(); + let mut got = c.album_photos(AlbumId(album)); + got.sort(); + assert_eq!(got, want, "album_photos of {album}"); + assert_eq!(c.album_count(AlbumId(album)), want.len(), "album_count of {album}"); + let mut shown = grid(c, album); + shown.sort(); + assert_eq!(shown, want, "the grid's source for {album}"); + for p in c.photos() { + assert_eq!(c.album_contains(AlbumId(album), p), want.contains(&p.id), "album_contains of {album} for {:?}", p.id); + } +} + +/// 1 ⇄ 2: each holds the photos of its own rule, or those of the other. Without the loop, 1 holds +/// the picked and the rated photo, and so does 2. +fn two_albums_in_a_loop() -> (Catalog, (PhotoId, PhotoId, PhotoId)) { + let mut c = Catalog::new(); + let p = photos(&mut c); + add(&mut c, any_of(1, serde_json::json!([picked(), in_album("is", 2)]))); + add(&mut c, any_of(2, serde_json::json!([rated(4), in_album("is", 1)]))); + (c, p) +} + +#[test] +fn two_albums_that_test_each_other_hold_nothing() { + let (c, _) = two_albums_in_a_loop(); + assert_holds(&c, 1, &[]); + assert_holds(&c, 2, &[]); +} + +#[test] +fn an_album_that_tests_itself_holds_nothing() { + let mut c = Catalog::new(); + photos(&mut c); + add(&mut c, any_of(1, serde_json::json!([picked(), in_album("is", 1)]))); + assert_holds(&c, 1, &[]); +} + +#[test] +fn every_album_on_a_longer_ring_holds_nothing_and_the_ones_leading_into_it_do_not_count_as_on_it() { + let mut c = Catalog::new(); + let (picked_photo, rated_photo, plain) = photos(&mut c); + // 1 → 2 → 3 → 1 + add(&mut c, any_of(1, serde_json::json!([picked(), in_album("is", 2)]))); + add(&mut c, any_of(2, serde_json::json!([rated(4), in_album("is", 3)]))); + add(&mut c, any_of(3, serde_json::json!([rated(1), in_album("is", 1)]))); + // 4 tests the ring (a tail into it), 5 tests 4: neither is on it + add(&mut c, any_of(4, serde_json::json!([rated(4), in_album("is", 1)]))); + add(&mut c, any_of(5, serde_json::json!([in_album("is", 4)]))); + for ring in [1, 2, 3] { + assert_holds(&c, ring, &[]); + } + assert_holds(&c, 4, &[rated_photo]); + assert_holds(&c, 5, &[rated_photo]); + let _ = (picked_photo, plain); +} + +#[test] +fn a_smart_album_off_every_loop_is_as_it_was() { + let mut c = Catalog::new(); + let (picked_photo, rated_photo, _) = photos(&mut c); + let (a, b) = (any_of(1, serde_json::json!([picked(), in_album("is", 2)])), any_of(2, serde_json::json!([rated(4), in_album("is", 1)]))); + add(&mut c, a); + add(&mut c, b); + // 3 and 4 form a chain, no loop: 4 holds what 3 holds + add(&mut c, any_of(3, serde_json::json!([picked(), rated(4)]))); + add(&mut c, any_of(4, serde_json::json!([in_album("is", 3)]))); + assert_holds(&c, 3, &[picked_photo, rated_photo]); + assert_holds(&c, 4, &[picked_photo, rated_photo]); +} + +#[test] +fn an_album_that_tests_a_looping_album_sees_it_as_empty() { + let (mut c, (a, b, d)) = two_albums_in_a_loop(); + // 3 isn't on the loop; it asks about album 1 + add(&mut c, any_of(3, serde_json::json!([in_album("is", 1)]))); + let mut not_in_one = any_of(4, serde_json::json!([in_album("isNot", 1)])); + not_in_one.name = "Not in one".into(); + add(&mut c, not_in_one); + assert_holds(&c, 3, &[]); + assert_holds(&c, 4, &[a, b, d]); +} + +#[test] +fn a_regular_album_is_not_a_loop() { + let (mut c, (a, ..)) = two_albums_in_a_loop(); + add(&mut c, Album { photos: vec![a], ..Album::new(AlbumId(9), "Plain") }); + assert_holds(&c, 9, &[a]); +} + +#[test] +fn mending_the_loop_gives_the_photos_back() { + let (mut c, (picked_photo, rated_photo, _)) = two_albums_in_a_loop(); + assert_holds(&c, 1, &[]); + // 2 stops testing 1 + let before = any_of(2, serde_json::json!([rated(4), in_album("is", 1)])).smart.unwrap(); + let inv = c.apply(Op::SetAlbumRules { id: AlbumId(2), rules: any_of(2, serde_json::json!([rated(4)])).smart.unwrap() }).unwrap(); + assert_holds(&c, 2, &[rated_photo]); + assert_holds(&c, 1, &[picked_photo, rated_photo]); + // undoing that brings the loop, and the emptiness, back + c.apply(inv).unwrap(); + assert_eq!(c.album(AlbumId(2)).and_then(|a| a.smart.as_deref()), Some(&*before)); + assert_holds(&c, 1, &[]); + assert_holds(&c, 2, &[]); + // removing 2 leaves 1 testing an album that is gone + c.apply(Op::RemoveAlbum { id: AlbumId(2) }).unwrap(); + assert_holds(&c, 1, &[picked_photo]); + // adding it back closes the loop again + add(&mut c, any_of(2, serde_json::json!([rated(4), in_album("is", 1)]))); + assert_holds(&c, 1, &[]); +} + +#[test] +fn the_loop_can_say_which_album_it_goes_through() { + let (mut c, _) = two_albums_in_a_loop(); + assert!(c.album_on_a_loop(AlbumId(1)) && c.album_on_a_loop(AlbumId(2))); + assert_eq!(c.album_loops_through(AlbumId(1)), Some(AlbumId(2))); + assert_eq!(c.album_loops_through(AlbumId(2)), Some(AlbumId(1))); + // 3 tests an album on the loop, and 4 tests itself as well as 3 + add(&mut c, any_of(3, serde_json::json!([in_album("is", 1)]))); + add(&mut c, any_of(4, serde_json::json!([in_album("is", 4)]))); + assert!(!c.album_on_a_loop(AlbumId(3)), "a tail into a loop is not on it"); + assert_eq!(c.album_loops_through(AlbumId(3)), None); + assert_eq!(c.album_loops_through(AlbumId(4)), Some(AlbumId(4)), "an album that tests itself loops through itself"); + // a plain album and an album that does not exist + add(&mut c, Album::new(AlbumId(5), "Plain")); + assert!(!c.album_on_a_loop(AlbumId(5)) && !c.album_on_a_loop(AlbumId(99))); + assert_eq!(c.album_loops_through(AlbumId(5)), None); +} + +#[test] +fn on_a_longer_ring_the_album_named_is_one_that_leads_back() { + let mut c = Catalog::new(); + // 1 → 2 → 3 → 1, and 1 also tests 7, which tests itself (a loop of its own, not 1's) + add(&mut c, any_of(1, serde_json::json!([in_album("is", 7), in_album("is", 2)]))); + add(&mut c, any_of(2, serde_json::json!([in_album("is", 3)]))); + add(&mut c, any_of(3, serde_json::json!([in_album("is", 1)]))); + add(&mut c, any_of(7, serde_json::json!([in_album("is", 7)]))); + assert_eq!(c.album_loops_through(AlbumId(1)), Some(AlbumId(2)), "7 is on a loop, but not the one 1 is on"); + assert_eq!(c.album_loops_through(AlbumId(2)), Some(AlbumId(3))); + assert_eq!(c.album_loops_through(AlbumId(3)), Some(AlbumId(1))); +} + +/// Asking is cheap: the albums on a loop are worked out once, and again only after an op that adds +/// or removes an album or changes rules, not after the edits to photos the library sees all day. +#[test] +fn the_loops_are_remembered_until_an_album_changes() { + let (mut c, (a, ..)) = two_albums_in_a_loop(); + assert!(!c.loops_known()); + assert_holds(&c, 1, &[]); + assert!(c.loops_known()); + c.apply(Op::SetRating { id: a, rating: 3 }).unwrap(); + c.apply(Op::SetFlag { id: a, flag: Flag::Reject }).unwrap(); + assert!(c.loops_known(), "photo edits don't change which album tests which"); + c.apply(Op::SetAlbumRules { id: AlbumId(2), rules: any_of(2, serde_json::json!([rated(4)])).smart.unwrap() }).unwrap(); + assert!(!c.loops_known(), "new rules"); + assert!(!c.album_on_a_loop(AlbumId(1))); + assert!(c.loops_known()); + add(&mut c, Album::new(AlbumId(9), "New")); + assert!(!c.loops_known(), "a new album"); + assert!(!c.album_on_a_loop(AlbumId(1))); + c.apply(Op::RemoveAlbum { id: AlbumId(9) }).unwrap(); + assert!(!c.loops_known(), "a removed album"); + // a copy builds its own when asked + assert!(!c.album_on_a_loop(AlbumId(1))); + assert!(!c.clone().loops_known()); +} + +/// A refused op leaves no half-forgotten state behind: the answer after it is still right. +#[test] +fn a_refused_edit_leaves_the_answers_as_they_were() { + let (mut c, _) = two_albums_in_a_loop(); + assert_holds(&c, 1, &[]); + assert!(c.apply(Op::SetAlbumRules { id: AlbumId(404), rules: any_of(1, serde_json::json!([rated(4)])).smart.unwrap() }).is_err()); + assert!(c.apply(Op::AddAlbum { album: any_of(1, serde_json::json!([rated(4)])) }).is_err(), "the id is taken"); + assert_holds(&c, 1, &[]); + assert_holds(&c, 2, &[]); +} diff --git a/crates/catalog/src/tests_search_text.rs b/crates/catalog/src/tests_search_text.rs new file mode 100644 index 0000000000..2c9ae6c668 --- /dev/null +++ b/crates/catalog/src/tests_search_text.rs @@ -0,0 +1,474 @@ +//! The free-text search and smart albums' Text rules read a photo's lower-cased text from a cache +//! ([`crate::index`]) rather than lower-casing every field of every photo on every keystroke. The +//! cache must give the matches the fields give, and follow every edit of a field it holds. + +use lightcraft_meta::{Rect, Region, RegionKind}; +use serde_json::json; + +use super::*; +use crate::index::PhotoText; + +fn photo(id: u64, file: &str) -> Photo { + Photo::new(PhotoId(id), Source::Demo { scene: 1 }, file, "JPEG", 60, 40, "2026-01-01T00:00:00") +} + +fn face(name: &str) -> Region { + Region { rect: Rect { x0: 0.4, y0: 0.4, x1: 0.6, y1: 0.6 }, kind: RegionKind::Face, name: Some(name.into()), description: None } +} + +/// Photos whose text is hard on a lower-casing shortcut: Unicode that changes length or depends on +/// its neighbours, a word that is only there across two fields, a colon in a plain word. +fn library() -> Catalog { + let mut photos = Vec::new(); + let mut p = photo(1, "IMG_0001.JPG"); + p.rating = 3; + p.meta.camera = "Canon EOS R5".into(); + p.meta.lens = "RF24-70mm F2.8 L".into(); + p.meta.title = "Trip to Ōsaka".into(); + p.meta.caption = "Straße am Fluss".into(); + p.meta.location = "Kyōto".into(); + p.meta.keywords = vec!["Travel|Italy".into(), "Ὀδυσσεύς".into(), "Kyōto Japan".into()]; + photos.push(p); + let mut p = photo(2, "İstanbul.jpg"); + p.meta.title = "ΣΊΣΥΦΟΣ".into(); + p.meta.caption = "Re: 10:30 meeting".into(); + p.meta.city = "Zürich".into(); + p.meta.regions = vec![face("Ana Lima")]; + photos.push(p); + let mut p = photo(3, "plain.png"); + p.format = "PNG".into(); + photos.push(p); + let mut p = photo(4, "abc"); + p.meta.camera = "def".into(); + p.meta.title = "Dž dž".into(); + photos.push(p); + let mut p = photo(5, "name:colon.jpg"); + p.meta.lens = "title:trip".into(); + p.copy_name = Some("Black and White".into()); + photos.push(p); + let mut c = Catalog::new(); + for p in photos { + c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + } + c +} + +/// How the search read a word before the cache: each field lower-cased alone, for every photo. +fn before_text_matches(p: &Photo, t: &str) -> bool { + let hay = [&p.file_name, &p.meta.title, &p.meta.caption, &p.meta.camera, &p.meta.lens, &p.meta.location, &p.format]; + hay.iter().any(|h| h.to_lowercase().contains(t)) + || p.meta.keywords.iter().any(|k| k.to_lowercase().contains(t)) + || p.people().iter().any(|n| n.to_lowercase().contains(t)) +} + +/// [`before_text_matches`] for the words the tests use: plain ones and the fields the cache serves. +fn before_matches(p: &Photo, text: &str) -> bool { + text.split_whitespace().all(|tok| { + let t = tok.to_lowercase(); + match t.split_once(':') { + Some(("camera", val)) => p.meta.camera.to_lowercase().contains(val), + Some(("lens", val)) => p.meta.lens.to_lowercase().contains(val), + Some(("name" | "file", val)) => p.file_name.to_lowercase().contains(val), + Some(("rating", val)) => p.rating.to_string() == val, + Some(("kw" | "keyword", val)) => p.meta.keywords.iter().any(|k| crate::keywords::is_under(k, val)), + _ => before_text_matches(p, &t), + } + }) +} + +const QUERIES: &[&str] = &[ + "img", + "IMG_0001", + "IMG_0001.JPG", + "canon r5", + "CANON eos", + "ōsaka", + "ŌSAKA", + "osaka", + "straße", + "STRASSE", + "i̇stanbul", + "İSTANBUL", + "istanbul", + "σίσυφος", + "ΣΊΣΥΦΟΣ", + "ς", + "σ", + "ὀδυσσεύς", + "travel", + "italy", + "travel|italy", + "kyōto japan", + "kyōto", + "10:30", + "re:", + "name:img", + "NAME:IMG_0001", + "file:plain", + "name:", + "camera:canon", + "camera:r5", + "lens:rf24", + "lens:", + "title:trip", + "abcdef", + "abc def", + "dž", + "rating:3 trip", + "kw:travel ōsaka", + "kw:travel osaka", + "png jpeg", + "", + " ", + "zzz", +]; + +fn shown(c: &Catalog, text: &str) -> Vec { + let f = Filter { text: text.into(), ..Default::default() }; + let mut ids: Vec = c.query(&f, &Sort::default()).into_iter().map(|id| id.0).collect(); + ids.sort_unstable(); + ids +} + +fn expected(c: &Catalog, text: &str) -> Vec { + c.photos().filter(|p| !p.deleted && before_matches(p, text)).map(|p| p.id.0).collect() +} + +/// A search finds what the fields hold, whether it asks for one photo at a time, as a pass over the +/// library that makes the cache, or one photo after that. +#[test] +fn search_matches_as_the_fields_do() { + let c = library(); + let mut one_by_one = Vec::new(); + for q in QUERIES.iter().copied() { + let f = Filter { text: q.into(), ..Default::default() }; + one_by_one.push(c.photos().filter(|p| f.matches(p, &c)).map(|p| p.id.0).collect::>()); + } + assert!(c.photos().all(|p| c.search_text(p, false).is_none()), "testing one photo makes no cache for the library"); + for (q, got) in QUERIES.iter().zip(&one_by_one) { + assert_eq!(*got, expected(&c, q), "{q:?}, one photo at a time"); + } + for q in QUERIES.iter().copied() { + assert_eq!(shown(&c, q), expected(&c, q), "{q:?}, a pass over the library"); + } + assert!(c.photos().all(|p| c.search_text(p, false).is_some()), "a pass made the cache"); + for q in QUERIES.iter().copied() { + let f = Filter { text: q.into(), ..Default::default() }; + let got: Vec = c.photos().filter(|p| f.matches(p, &c)).map(|p| p.id.0).collect(); + assert_eq!(got, expected(&c, q), "{q:?}, one photo at a time, with the cache"); + } +} + +/// A photo that isn't the catalog's own (an edit not made yet, a candidate being tried) is read +/// from its own fields, not from what the catalog kept for the photo with its id. +#[test] +fn a_copy_of_a_photo_is_read_as_it_is() { + let c = library(); + let f = Filter { text: "ōsaka".into(), ..Default::default() }; + assert_eq!(c.count(&f), 1); + let mut p = (**c.photo(PhotoId(1)).unwrap()).clone(); + p.meta.title = "Trip to Nara".into(); + p.meta.keywords.clear(); + p.meta.location.clear(); + assert!(!f.matches(&p, &c), "the catalog's own text says Ōsaka, this copy doesn't"); + let nara = Filter { text: "nara".into(), ..Default::default() }; + assert!(nara.matches(&p, &c)); + assert!(!nara.matches(c.photo(PhotoId(1)).unwrap(), &c)); + let rule = Filter { rule_set: Some(rules(json!({"rules": [{"field": "text", "op": "contains", "value": "nara"}]}))), ..Default::default() }; + assert_eq!(c.count(&rule), 0); + assert!(rule.matches(&p, &c)); +} + +fn rules(v: serde_json::Value) -> RuleSet { + serde_json::from_value(v).unwrap() +} + +fn text_rule(op: &str, value: &str) -> Filter { + Filter { rule_set: Some(rules(json!({"rules": [{"field": "text", "op": op, "value": value}]}))), ..Default::default() } +} + +/// What the cache holds is what a scan of the photos would give it, and every photo's is used. +fn assert_current(c: &Catalog) { + for p in c.photos() { + let kept = c.search_text(p, false).unwrap_or_else(|| panic!("photo {}: no text kept, or kept for another place", p.id.0)); + let now = PhotoText::of(p); + assert_eq!(kept.text(), now.text(), "photo {}", p.id.0); + assert_eq!(c.rule_text_of(p), Some(crate::rules::rule_text(p).as_str()), "photo {}: the Text rule's text", p.id.0); + } +} + +/// Make the caches, as the first search and the first smart album with a Text rule do. +fn warm(c: &Catalog) { + c.count(&Filter { text: "x".into(), ..Default::default() }); + c.count(&text_rule("contains", "x")); + assert_current(c); +} + +fn found(c: &Catalog, text: &str) -> usize { + c.count(&Filter { text: text.into(), ..Default::default() }) +} + +fn found_by_rule(c: &Catalog, text: &str) -> usize { + c.count(&text_rule("contains", text)) +} + +/// An edit of each field that is searched puts the new text in the cache and takes the old one out, +/// through the op, its inverse and a batch that fails and is taken back. +#[test] +fn the_cache_follows_every_field_that_is_searched() { + let mut c = library(); + warm(&c); + let id = PhotoId(3); + let edit = |c: &mut Catalog, set: &dyn Fn(&mut Meta)| { + let mut meta = c.photo(id).unwrap().meta.clone(); + set(&mut meta); + c.apply(Op::SetMeta { id, meta: Box::new(meta) }).unwrap() + }; + type Set = fn(&mut Meta, &str); + let fields: [(&str, Set); 6] = [ + ("title", |m, v| m.title = v.into()), + ("caption", |m, v| m.caption = v.into()), + ("camera", |m, v| m.camera = v.into()), + ("lens", |m, v| m.lens = v.into()), + ("location", |m, v| m.location = v.into()), + ("keywords", |m, v| m.keywords = vec![v.into()]), + ]; + for (n, (field, set)) in fields.into_iter().enumerate() { + let word = format!("Zq{n}x"); + let before = found(&c, &word); + let undo = edit(&mut c, &|m| set(m, &word)); + assert_eq!((before, found(&c, &word)), (0, 1), "{field}: found after the edit"); + assert_eq!(found_by_rule(&c, &word.to_lowercase()), 1, "{field}: the Text rule"); + assert_current(&c); + c.apply(undo).unwrap(); + assert_eq!(found(&c, &word), 0, "{field}: gone after the undo"); + assert_current(&c); + } + // the fields only Text rules read + let rule_fields: [(&str, Set); 3] = + [("city", |m, v| m.city = v.into()), ("state", |m, v| m.state = v.into()), ("country", |m, v| m.country = v.into())]; + for (n, (field, set)) in rule_fields.into_iter().enumerate() { + let word = format!("zr{n}y"); + let undo = edit(&mut c, &|m| set(m, &word)); + assert_eq!((found_by_rule(&c, &word), found(&c, &word)), (1, 0), "{field}"); + assert_current(&c); + c.apply(undo).unwrap(); + assert_eq!(found_by_rule(&c, &word), 0, "{field}: gone after the undo"); + } + let undo = edit(&mut c, &|m| m.alt_text = "zalt".into()); + assert_eq!(found_by_rule(&c, "zalt"), 1); + c.apply(undo).unwrap(); + assert_eq!(found_by_rule(&c, "zalt"), 0); + let undo = edit(&mut c, &|m| m.regions = vec![face("Zed Person")]); + assert_eq!(found_by_rule(&c, "zed person"), 1, "a person named on a face"); + c.apply(undo).unwrap(); + assert_eq!(found_by_rule(&c, "zed person"), 0); + assert_current(&c); +} + +#[test] +fn the_cache_follows_a_file_name_and_a_format() { + let mut c = library(); + warm(&c); + let id = PhotoId(3); + let source = Source::Demo { scene: 1 }; + let undo = c.apply(Op::SetFile { id, file_name: "Renamed_0042.PNG".into(), source: source.clone() }).unwrap(); + assert_eq!((found(&c, "renamed_0042"), found(&c, "plain"), found(&c, "name:renamed")), (1, 0, 1)); + assert_eq!((found_by_rule(&c, "renamed_0042"), found_by_rule(&c, "plain")), (1, 0)); + assert_current(&c); + c.apply(undo).unwrap(); + assert_eq!((found(&c, "renamed_0042"), found(&c, "plain")), (0, 1)); + assert_current(&c); + + let undo = c.apply(Op::Relink { id, file_name: "Moved.TIF".into(), source: source.clone(), format: Some("TIFF".into()) }).unwrap(); + assert_eq!((found(&c, "moved"), found(&c, "tiff"), found(&c, "png")), (1, 1, 0)); + assert_eq!((found_by_rule(&c, "moved"), found_by_rule(&c, "tiff"), found_by_rule(&c, "png")), (1, 1, 0)); + assert_current(&c); + c.apply(undo).unwrap(); + assert_eq!((found(&c, "moved"), found(&c, "tiff"), found(&c, "png")), (0, 0, 1)); + assert_current(&c); +} + +/// A photo that comes or goes (an import, a virtual copy, a permanent delete and its undo) does +/// too, and a virtual copy's name is read by a Text rule. +#[test] +fn the_cache_follows_photos_that_come_and_go() { + let mut c = library(); + warm(&c); + let mut copy = (**c.photo(PhotoId(1)).unwrap()).clone(); + copy.id = PhotoId(9); + copy.copy_of = Some(PhotoId(1)); + copy.meta = Default::default(); + copy.copy_name = Some("Zcopy Name".into()); + copy.file_name = "Zfresh.jpg".into(); + let undo = c.apply(Op::AddPhoto { photo: Box::new(copy) }).unwrap(); + assert_eq!((found(&c, "zfresh"), found_by_rule(&c, "zcopy"), found(&c, "zcopy")), (1, 1, 0)); + assert_current(&c); + let redo = c.apply(undo).unwrap(); + assert_eq!((found(&c, "zfresh"), found_by_rule(&c, "zcopy")), (0, 0)); + assert_current(&c); + c.apply(redo).unwrap(); + assert_eq!(found(&c, "zfresh"), 1); + assert_current(&c); + let removed = c.apply(Op::RemovePhoto { id: PhotoId(1) }).unwrap(); + assert_eq!(found(&c, "ōsaka"), 0); + assert_current(&c); + c.apply(removed).unwrap(); + assert_eq!(found(&c, "ōsaka"), 1); + assert_current(&c); +} + +/// A batch that fails half way is taken back, and the cache with it. +#[test] +fn the_cache_follows_a_batch_that_fails() { + let mut c = library(); + warm(&c); + let mut meta = c.photo(PhotoId(3)).unwrap().meta.clone(); + meta.title = "Zbatch title".into(); + let batch = Op::Batch { + ops: vec![ + Op::SetMeta { id: PhotoId(3), meta: Box::new(meta) }, + Op::SetFile { id: PhotoId(3), file_name: "Zbatch.png".into(), source: Source::Demo { scene: 1 } }, + Op::SetFile { id: PhotoId(404), file_name: "gone.png".into(), source: Source::Demo { scene: 1 } }, + ], + }; + assert!(c.apply(batch).is_err()); + assert_eq!((found(&c, "zbatch"), found_by_rule(&c, "zbatch")), (0, 0)); + assert_eq!(found(&c, "plain"), 1); + assert_current(&c); +} + +/// An edit of a photo that something else holds (a thumbnail list, an undo step) puts it at another +/// place in memory. The cache follows it, so a search isn't left reading every such photo from its fields. +#[test] +fn the_cache_follows_a_photo_that_others_hold() { + let mut c = library(); + warm(&c); + let held: Vec<_> = c.photos().cloned().collect(); + for p in &held { + c.apply(Op::SetRating { id: p.id, rating: 5 }).unwrap(); + } + assert!(held.iter().all(|old| !std::ptr::eq(&**old, &**c.photo(old.id).unwrap())), "the edits copied the photos"); + assert_current(&c); + assert_eq!(found(&c, "ōsaka"), 1); + c.apply(Op::SetFile { id: PhotoId(2), file_name: "after.jpg".into(), source: Source::Demo { scene: 1 } }).unwrap(); + assert_current(&c); + assert_eq!((found(&c, "after"), found(&c, "istanbul")), (1, 0)); +} + +/// A catalog read from a snapshot or cloned starts with no cache and builds its own. +#[test] +fn a_clone_builds_its_own() { + let mut c = library(); + warm(&c); + let mut copy = c.clone(); + assert!(copy.photos().all(|p| copy.search_text(p, false).is_none())); + assert_eq!(found(©, "ōsaka"), 1); + warm(©); + let mut meta = copy.photo(PhotoId(1)).unwrap().meta.clone(); + meta.title = "Elsewhere".into(); + copy.apply(Op::SetMeta { id: PhotoId(1), meta: Box::new(meta) }).unwrap(); + assert_eq!((found(©, "elsewhere"), found(&c, "elsewhere")), (1, 0)); + c.apply(Op::SetRating { id: PhotoId(1), rating: 1 }).unwrap(); + assert_current(&c); +} + +/// `repair` copies the photos others hold (`Arc::make_mut`) without reporting a change, so the cache would +/// still keep a text for the address the retained photo has. The retained photo, changed on its own, is +/// read from its fields, never from the text kept for the photo with its id. +#[test] +fn repair_keeps_no_text_for_a_photo_it_copied() { + let mut c = library(); + warm(&c); + let mut held = c.photo(PhotoId(1)).unwrap().clone(); + assert!(c.repair().is_empty(), "a sound catalog"); + assert!(!std::ptr::eq(&*held, &**c.photo(PhotoId(1)).unwrap()), "repair copied the photo"); + std::sync::Arc::make_mut(&mut held).meta.title = "Trip to Nara".into(); + let nara = Filter { text: "nara".into(), ..Default::default() }; + let osaka = Filter { text: "ōsaka".into(), ..Default::default() }; + assert!(nara.matches(&held, &c), "the retained photo's own title"); + assert!(!osaka.matches(&held, &c), "not the title it had"); + assert!(text_rule("contains", "nara").matches(&held, &c), "the Text rule reads the retained photo's own title"); + assert!(!text_rule("contains", "ōsaka").matches(&held, &c)); + warm(&c); + assert_eq!((found(&c, "ōsaka"), found(&c, "nara")), (1, 0)); +} + +/// The words of Text rules (not the search) read the same with the cache as without: what the fields give when each +/// photo is read alone (a copy of a photo is not the catalog's own, so the text kept for its id is not used), and what the +/// kept text gives. +#[test] +fn text_rules_match_as_the_fields_do() { + let c = library(); + let every_op = ["contains", "notContains", "is", "isNot", "startsWith", "endsWith", "isEmpty", "isNotEmpty"]; + let values = + ["", "ōsaka", "TRIP TO", "kyōto japan", "ana lima", "zürich", "img_0001.jpg", "black and white", "ς", "i̇stanbul", "png", "re: 10:30 meeting"]; + assert!(!c.rule_text_made(), "nothing made the text yet"); + let after: Vec> = every_op.iter().map(|op| values.iter().map(|v| c.count(&text_rule(op, v))).collect()).collect(); + assert!(c.rule_text_made(), "the first rule asked made the text"); + let from_the_fields: Vec> = every_op + .iter() + .map(|op| values.iter().map(|v| c.photos().filter(|p| text_rule(op, v).matches(&Photo::clone(p), &c)).count()).collect()) + .collect(); + assert_eq!(from_the_fields, after); + assert!(after.iter().flatten().any(|&n| n > 0), "the rules found something"); + let again: Vec> = + every_op.iter().map(|op| values.iter().map(|v| c.photos().filter(|p| text_rule(op, v).matches(p, &c)).count()).collect()).collect(); + assert_eq!(after, again); +} + +/// A smart album's count through the tally path (`album_contains`, one photo at a time) reads the +/// kept text: it is made there, and an edit shows in the next count. +#[test] +fn a_smart_album_count_reads_the_kept_text() { + let mut c = library(); + let mut album = Album::new(AlbumId(1), "Osaka"); + album.smart = Some(Box::new(text_rule("contains", "ōsaka"))); + c.apply(Op::AddAlbum { album }).unwrap(); + let one_by_one = |c: &Catalog| c.photos().filter(|p| c.album_contains(AlbumId(1), p)).count(); + assert!(!c.rule_text_made(), "nothing made the text yet"); + assert_eq!(one_by_one(&c), 1); + assert!(c.rule_text_made(), "counting made the text"); + let mut meta = c.photo(PhotoId(3)).unwrap().meta.clone(); + meta.title = "Ōsaka again".into(); + c.apply(Op::SetMeta { id: PhotoId(3), meta: Box::new(meta) }).unwrap(); + assert_eq!(one_by_one(&c), 2); +} + +/// The kept text holds the names of the people on a photo's faces, and a quoted phrase is read as +/// one word that never runs from one field into the next. +#[test] +fn the_kept_text_holds_the_people_and_a_phrase_stays_in_one_field() { + let mut c = library(); + warm(&c); + assert_eq!(found(&c, "ana"), 1, "a person's name is searched"); + assert_eq!(found(&c, "\"ana lima\""), 1, "a quoted name is one phrase"); + assert_eq!(found(&c, "\"lima ana\""), 0); + assert_eq!(found(&c, "\"ōsaka straße\""), 0, "a phrase doesn't run from the title into the caption"); + assert_eq!(found(&c, "\"trip to ōsaka\""), 1, "…but fits inside one field"); + assert_eq!(found(&c, "\"Kyōto Japan\""), 1, "…or one keyword"); + // (the photo that has Ana Lima's face) + let mut meta = c.photo(PhotoId(2)).unwrap().meta.clone(); + meta.regions = vec![face("Zed Person")]; + c.apply(Op::SetMeta { id: PhotoId(2), meta: Box::new(meta) }).unwrap(); + assert_eq!(found(&c, "\"zed person\""), 1, "a renamed person is found at once"); + assert_eq!(found(&c, "ana"), 0, "and the old name is gone"); + assert_current(&c); +} + +/// A word that holds NUL (a filter's text can) is looked for inside one field, as before the cache: it never matches across +/// the NUL the cache puts between two fields, and still matches a field that holds NUL itself. +#[test] +fn a_word_holding_nul_never_runs_over_two_fields() { + let mut c = Catalog::new(); + let mut p = photo(1, "a"); + p.meta.title = "b".into(); + c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + let mut p = photo(2, "c\0d"); + p.meta.title = "e".into(); + c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + for text in ["a\0b", "\"a\0b\"", "b\0", "\0e"] { + assert_eq!(shown(&c, text), Vec::::new(), "{text:?}"); + } + assert_eq!(shown(&c, "c\0d"), vec![2], "a field's own NUL is still found"); +} diff --git a/crates/catalog/src/tests_shared.rs b/crates/catalog/src/tests_shared.rs new file mode 100644 index 0000000000..72a6c77587 --- /dev/null +++ b/crates/catalog/src/tests_shared.rs @@ -0,0 +1,397 @@ +//! Photos whose develop settings are equal share one settings value in memory +//! ([`crate::shared`]): a library of photos nobody edited holds the defaults once, not once per +//! photo. + +use std::sync::Arc; + +use lightcraft_develop::DevelopSettings; + +use crate::journal::encode_record; +use crate::*; + +fn photo(id: u64) -> Photo { + Photo::new( + PhotoId(id), + Source::File { path: format!("/pictures/2019/trip/IMG_{id:06}.jpg") }, + &format!("IMG_{id:06}.jpg"), + "JPEG", + 4032, + 3024, + "2026-10-10T12:00:00", + ) +} + +fn raw(id: u64) -> Photo { + let mut p = photo(id); + p.kind = MediaKind::Raw; + p.format = "CR3".into(); + p.as_shot_wb = Some((5200.0, 3.0)); + // as an import gives it: settings of its own that equal every other CR3's + p.develop = Arc::new(p.import_defaults()); + p +} + +fn edited(d: impl FnOnce(&mut DevelopSettings)) -> Arc { + let mut s = DevelopSettings::default(); + d(&mut s); + Arc::new(s) +} + +fn catalog_of(photos: impl IntoIterator) -> Catalog { + let mut c = Catalog::new(); + for p in photos { + c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + } + c +} + +fn settings_of(c: &Catalog, id: u64) -> &Arc { + &c.photo(PhotoId(id)).unwrap().develop +} + +/// How many different settings values the catalog's photos hold between them. +fn distinct(c: &Catalog) -> usize { + let mut seen: Vec<*const DevelopSettings> = c.photos().map(|p| Arc::as_ptr(&p.develop)).collect(); + seen.sort_unstable(); + seen.dedup(); + seen.len() +} + +/// The catalog through a saved library and back: from its snapshot, from a library directory's +/// snapshot file, and from the log alone. +fn reloaded(c: &Catalog) -> Vec<(&'static str, Catalog)> { + let mut out = vec![("snapshot", Catalog::from_snapshot(&c.to_snapshot()).unwrap())]; + let m = MemStore::new(); + let (mut j, _, _) = Journal::open(Box::new(m.clone())).unwrap(); + j.snapshot(c).unwrap(); + drop(j); + out.push(("library", Journal::open(Box::new(m)).unwrap().1)); + let m = MemStore::new(); + let log: String = + c.photos().enumerate().map(|(k, p)| encode_record(k as u64 + 1, &Op::AddPhoto { photo: Box::new(p.as_ref().clone()) }) + "\n").collect(); + m.set(journal::LOG, log.into_bytes()); + out.push(("the log", Journal::open(Box::new(m)).unwrap().1)); + out +} + +/// Given photos nobody edited, when they are added to a catalog or a saved library is opened, +/// then they all hold the same settings value. +#[test] +fn unedited_photos_share_the_default_settings() { + let c = catalog_of((1..=20).map(photo)); + assert_eq!(distinct(&c), 1); + assert_eq!(**settings_of(&c, 1), DevelopSettings::default()); + for (how, back) in reloaded(&c) { + assert_eq!(back.len(), 20, "{how}"); + assert_eq!(distinct(&back), 1, "{how}"); + assert_eq!(back.to_snapshot(), c.to_snapshot(), "{how}"); + } +} + +/// Given raws that were given their import defaults one by one (equal settings, a value each), +/// then they share one value too, also after the library is opened again. +#[test] +fn photos_with_equal_settings_share_them() { + let c = catalog_of((1..=20).map(raw)); + assert_ne!(**settings_of(&c, 1), DevelopSettings::default()); + assert_eq!(distinct(&c), 1); + for (how, back) in reloaded(&c) { + assert_eq!(distinct(&back), 1, "{how}"); + assert_eq!(back.to_snapshot(), c.to_snapshot(), "{how}"); + } + // settings set by a change are shared like those a photo arrives with + let mut c = catalog_of((1..=4).map(photo)); + for id in 1..=4 { + c.apply(Op::SetDevelop { id: PhotoId(id), settings: edited(|s| s.light.exposure = 0.5), label: "Exposure".into(), edited: None }).unwrap(); + } + assert_eq!(distinct(&c), 1); +} + +/// Given photos that share their settings, when one of them is edited, then only that one +/// changes: sharing is never a way for one photo's edit to reach another. +#[test] +fn editing_one_photo_leaves_the_ones_it_shared_with() { + let mut c = catalog_of((1..=3).map(photo)); + let undo = + c.apply(Op::SetDevelop { id: PhotoId(2), settings: edited(|s| s.light.exposure = 1.0), label: "Exposure".into(), edited: None }).unwrap(); + assert_eq!(settings_of(&c, 2).light.exposure, 1.0); + assert_eq!((&**settings_of(&c, 1), &**settings_of(&c, 3)), (&DevelopSettings::default(), &DevelopSettings::default())); + assert!(Arc::ptr_eq(settings_of(&c, 1), settings_of(&c, 3))); + // and undoing it gives the photo the shared value back + c.apply(undo).unwrap(); + assert_eq!(distinct(&c), 1); + // a caller that edits a copy of a photo's settings (`Arc::make_mut` copies a shared value) and + // gives it back as a change leaves the photos that held the old value alone + let mut own = c.photo(PhotoId(1)).unwrap().as_ref().clone(); + Arc::make_mut(&mut own.develop).light.contrast = 30.0; + c.apply(Op::SetDevelop { id: PhotoId(1), settings: own.develop.clone(), label: "Contrast".into(), edited: None }).unwrap(); + assert_eq!(settings_of(&c, 1).light.contrast, 30.0); + assert_eq!(**settings_of(&c, 2), DevelopSettings::default()); + assert_eq!(**settings_of(&c, 3), DevelopSettings::default()); + assert_eq!(*shared::default_settings(), DevelopSettings::default()); + c.apply(Op::SetDevelop { id: PhotoId(1), settings: shared::default_settings(), label: "Reset".into(), edited: None }).unwrap(); + // the same after a reload + for (how, mut back) in reloaded(&c) { + back.apply(Op::SetDevelop { id: PhotoId(2), settings: edited(|s| s.light.exposure = 1.0), label: "Exposure".into(), edited: None }).unwrap(); + assert_eq!(**settings_of(&back, 1), DevelopSettings::default(), "{how}"); + assert_eq!(**settings_of(&back, 3), DevelopSettings::default(), "{how}"); + } +} + +/// A photo's history steps, versions and import look share with its settings where they are +/// equal: after the library is opened again as before it was saved. +#[test] +fn a_photos_history_shares_with_its_settings() { + let now = edited(|s| s.light.exposure = 0.3); + let before = edited(|s| s.light.contrast = 10.0); + let mut p = photo(1); + p.develop = now.clone(); + p.history = vec![ + HistoryStep { label: "Contrast".into(), settings: before.clone() }, + HistoryStep { label: "Reset".into(), settings: Arc::new(DevelopSettings::default()) }, + HistoryStep { label: "Exposure".into(), settings: now.clone() }, + ]; + p.versions = vec![Version { name: "A".into(), created: "2026-10-10".into(), settings: before.clone(), auto: false }]; + p.import_look = Some(before); + let c = catalog_of([p, photo(2)]); + for (how, back) in reloaded(&c).into_iter().chain([("as added", c.clone())]) { + let p = back.photo(PhotoId(1)).unwrap(); + assert!(Arc::ptr_eq(&p.develop, &p.history[2].settings), "{how}"); + assert!(Arc::ptr_eq(&p.history[0].settings, &p.versions[0].settings), "{how}"); + assert!(Arc::ptr_eq(&p.history[0].settings, p.import_look.as_ref().unwrap()), "{how}"); + assert!(Arc::ptr_eq(&p.history[1].settings, settings_of(&back, 2)), "{how}: the defaults"); + assert_eq!(back.to_snapshot(), c.to_snapshot(), "{how}"); + } +} + +/// A long history (more steps than a thread remembers values) still ends with the photo's +/// settings as one value. +#[test] +fn a_long_history_ends_with_the_photos_settings() { + let mut p = photo(1); + let mut d = DevelopSettings::default(); + for step in 0..40 { + d.light.exposure = f64::from(step) * 0.01; + p.history.push(HistoryStep { label: "Exposure".into(), settings: Arc::new(d.clone()) }); + } + p.develop = Arc::new(d); + let c = catalog_of([p, photo(2)]); + for (how, back) in reloaded(&c).into_iter().chain([("as added", c.clone())]) { + let p = back.photo(PhotoId(1)).unwrap(); + assert!(Arc::ptr_eq(&p.develop, &p.history[39].settings), "{how}"); + assert_eq!(back.to_snapshot(), c.to_snapshot(), "{how}"); + // the next photo's settings are its own + assert_eq!(**settings_of(&back, 2), DevelopSettings::default(), "{how}"); + } +} + +/// Settings that are equal but for the sign of a zero are not the same settings (their JSON, +/// and the fingerprint and preview-cache key made from it, differ): they are never shared. +#[test] +fn settings_that_differ_in_the_sign_of_a_zero_are_not_shared() { + let negative = |id: u64| { + let mut p = photo(id); + p.develop = edited(|s| s.wb.tint = -0.0); + p + }; + let c = catalog_of([photo(1), negative(2), photo(3), negative(4)]); + assert_eq!(*settings_of(&c, 2), *settings_of(&c, 1), "equal as numbers"); + for (how, back) in reloaded(&c).into_iter().chain([("as added", c.clone())]) { + for id in [2, 4] { + let p = back.photo(PhotoId(id)).unwrap(); + assert!(!Arc::ptr_eq(&p.develop, settings_of(&back, 1)), "{how}"); + assert!(p.develop.wb.tint.is_sign_negative(), "{how}"); + assert_eq!(p.develop.hash64(), c.photo(PhotoId(id)).unwrap().develop.hash64(), "{how}"); + } + assert!(settings_of(&back, 1).wb.tint.is_sign_positive() && Arc::ptr_eq(settings_of(&back, 1), settings_of(&back, 3)), "{how}"); + } +} + +/// Settings that aren't the defaults and their twin with a negative zero, met one after the +/// other in either order, as two photos' settings and as a photo's settings and history step: +/// each keeps its own sign, and neither is ever handed the other's value. +#[test] +fn a_negative_zero_twin_is_never_what_others_share() { + let twin = |tint: f64| { + edited(|s| { + s.light.exposure = 0.5; + s.wb.tint = tint; + }) + }; + for (first, second) in [(-0.0, 0.0), (0.0, -0.0)] { + let (mut a, mut b, mut both) = (photo(1), photo(2), photo(3)); + a.develop = twin(first); + b.develop = twin(second); + both.develop = twin(first); + both.history = vec![HistoryStep { label: "x".into(), settings: twin(second) }, HistoryStep { label: "y".into(), settings: twin(first) }]; + let c = catalog_of([a, b, both]); + for (how, back) in reloaded(&c).into_iter().chain([("as added", c.clone())]) { + let sign = |s: &Arc| s.wb.tint.is_sign_negative(); + let (a, b, both) = (settings_of(&back, 1), settings_of(&back, 2), back.photo(PhotoId(3)).unwrap()); + assert_eq!((sign(a), sign(b)), (first.is_sign_negative(), second.is_sign_negative()), "{how} {first} {second}"); + assert!(!Arc::ptr_eq(a, b), "{how}"); + assert_eq!((sign(&both.develop), sign(&both.history[0].settings), sign(&both.history[1].settings)), (sign(a), sign(b), sign(a)), "{how}"); + assert!(!Arc::ptr_eq(&both.history[0].settings, &both.history[1].settings), "{how}"); + assert_eq!((a.hash64(), b.hash64()), (twin(first).hash64(), twin(second).hash64()), "{how}"); + assert_ne!(a.hash64(), b.hash64()); + assert_eq!(back.to_snapshot(), c.to_snapshot(), "{how}"); + } + } +} + +/// A change's settings that equal the photo's own as numbers but differ in the sign of a zero are not handed +/// the photo's value, in either order. +#[test] +fn changes_never_take_the_photos_settings_across_a_negative_zero() { + let twin = |tint: f64| { + edited(|s| { + s.light.exposure = 0.5; + s.wb.tint = tint; + }) + }; + for (own, given) in [(0.0, -0.0), (-0.0, 0.0)] { + let mut c = catalog_of([photo(1)]); + c.apply(Op::SetDevelop { id: PhotoId(1), settings: twin(own), label: "Tint".into(), edited: None }).unwrap(); + c.apply(Op::SetHistory { id: PhotoId(1), history: vec![HistoryStep { label: "Tint".into(), settings: twin(given) }] }).unwrap(); + let p = c.photo(PhotoId(1)).unwrap(); + assert!(!Arc::ptr_eq(&p.develop, &p.history[0].settings), "own {own:?}, given {given:?}"); + assert_eq!(p.history[0].settings.wb.tint.is_sign_negative(), given.is_sign_negative()); + assert_eq!(p.develop.wb.tint.is_sign_negative(), own.is_sign_negative()); + } +} + +/// Settings given by any change are shared: a history step pushed or set, and versions. +#[test] +fn settings_given_by_changes_are_shared() { + let look = || edited(|s| s.light.exposure = 0.7); + let mut c = catalog_of((1..=2).map(photo)); + c.apply(Op::SetDevelop { id: PhotoId(1), settings: look(), label: "Exposure".into(), edited: None }).unwrap(); + c.apply(Op::PushHistory { id: PhotoId(1), step: HistoryStep { label: "Exposure".into(), settings: look() } }).unwrap(); + let p = c.photo(PhotoId(1)).unwrap(); + assert!(Arc::ptr_eq(&p.develop, &p.history[0].settings), "PushHistory"); + c.apply(Op::SetVersions { id: PhotoId(2), versions: vec![Version { name: "A".into(), created: "2026".into(), settings: look(), auto: false }] }) + .unwrap(); + assert!(Arc::ptr_eq(&c.photo(PhotoId(2)).unwrap().versions[0].settings, settings_of(&c, 1)), "SetVersions"); + c.apply(Op::SetHistory { id: PhotoId(2), history: vec![HistoryStep { label: "A".into(), settings: look() }] }).unwrap(); + assert!(Arc::ptr_eq(&c.photo(PhotoId(2)).unwrap().history[0].settings, settings_of(&c, 1)), "SetHistory"); + // a new photo's settings are the shared defaults from the start + assert!(Arc::ptr_eq(&photo(7).develop, &photo(8).develop)); +} + +/// Settings given by a change are shared with the photo's own settings even when the thread's list of recent +/// values has since moved on to others: the target photo's settings are what they are compared with first. +#[test] +fn settings_given_by_changes_are_shared_with_the_photos_own_even_when_not_recent() { + let look = || edited(|s| s.light.exposure = 0.7); + let mut c = catalog_of((1..=2).map(photo)); + c.apply(Op::SetDevelop { id: PhotoId(1), settings: look(), label: "Exposure".into(), edited: None }).unwrap(); + // more different values than the thread remembers, held by another photo + let others = |c: &mut Catalog| { + let versions = (1..=6u32) + .map(|i| Version { + name: format!("V{i}"), + created: "2026".into(), + settings: edited(|s| s.light.exposure = f64::from(i) / 10.0 + 1.0), + auto: false, + }) + .collect(); + c.apply(Op::SetVersions { id: PhotoId(2), versions }).unwrap(); + }; + others(&mut c); + c.apply(Op::SetHistory { id: PhotoId(1), history: vec![HistoryStep { label: "A".into(), settings: look() }] }).unwrap(); + let p = c.photo(PhotoId(1)).unwrap(); + assert!(Arc::ptr_eq(&p.develop, &p.history[0].settings), "SetHistory"); + others(&mut c); + c.apply(Op::PushHistory { id: PhotoId(1), step: HistoryStep { label: "B".into(), settings: look() } }).unwrap(); + let p = c.photo(PhotoId(1)).unwrap(); + assert!(Arc::ptr_eq(&p.develop, &p.history[1].settings), "PushHistory"); + others(&mut c); + c.apply(Op::SetVersions { id: PhotoId(1), versions: vec![Version { name: "C".into(), created: "2026".into(), settings: look(), auto: false }] }) + .unwrap(); + let p = c.photo(PhotoId(1)).unwrap(); + assert!(Arc::ptr_eq(&p.develop, &p.versions[0].settings), "SetVersions"); +} + +/// Settings that can't be read are still an error naming what is wrong, not shared defaults. +#[test] +fn bad_settings_are_still_refused() { + for bad in [r#"{"light":{"exposure":"a lot"}}"#, r#"["x"]"#, r#""x""#, r#"7"#, r#"null"#] { + let record = format!( + r#"{{"id":1,"source":{{"type":"file","path":"/a.jpg"}},"file_name":"a.jpg","format":"JPEG","width":1,"height":1,"imported":"2026","develop":{bad}}}"# + ); + assert!(serde_json::from_str::(&record).is_err(), "{bad}"); + } +} + +/// What a thread remembers to compare with keeps no settings alive, and is a handful of values: +/// settings no photo holds any more are freed, however many were seen. +#[test] +fn remembered_settings_are_not_kept_alive() { + let mut watched = Vec::new(); + for k in 0..50 { + let s = shared::settings(edited(|s| s.light.exposure = 0.001 * f64::from(k + 1))); + watched.push(Arc::downgrade(&s)); + } + assert!(watched.iter().all(|w| w.upgrade().is_none()), "{} kept alive", watched.iter().filter(|w| w.upgrade().is_some()).count()); + // and of values that are all still held (a library of photos each edited differently), it + // remembers a handful, not all of them + let held: Vec<_> = (1..=200).map(|k| shared::settings(edited(|s| s.light.contrast = f64::from(k)))).collect(); + assert!(shared::remembered() <= 4, "{} remembered", shared::remembered()); + drop(held); + // while they are held, an equal value is still found + let held = shared::settings(edited(|s| s.light.exposure = 0.9)); + assert!(Arc::ptr_eq(&held, &shared::settings(edited(|s| s.light.exposure = 0.9)))); +} + +/// New photos start from the one held default. +#[test] +fn a_new_photos_settings_are_the_held_default() { + assert!(Arc::ptr_eq(&photo(7).develop, &shared::default_settings())); +} + +/// A negative zero anywhere in the settings, in whatever field it is, keeps them from being +/// shared with the equal settings that hold a positive one. +#[test] +fn a_negative_zero_in_any_field_is_found() { + fn zeros(v: &serde_json::Value, path: &mut Vec, out: &mut Vec>) { + match v { + serde_json::Value::Number(n) if n.is_f64() && n.as_f64() == Some(0.0) => out.push(path.clone()), + serde_json::Value::Object(m) => { + for (k, v) in m { + path.push(k.clone()); + zeros(v, path, out); + path.pop(); + } + } + serde_json::Value::Array(a) => { + for (i, v) in a.iter().enumerate() { + path.push(i.to_string()); + zeros(v, path, out); + path.pop(); + } + } + _ => {} + } + } + let default = serde_json::to_value(DevelopSettings::default()).unwrap(); + let mut found = Vec::new(); + zeros(&default, &mut Vec::new(), &mut found); + assert!(found.len() > 20, "{} zeros in the defaults: the walk finds none", found.len()); + let base = shared::settings(Arc::new(DevelopSettings::default())); + let mut checked = 0; + for path in found { + let mut v = default.clone(); + let pointer = path.iter().map(|k| format!("/{k}")).collect::(); + *v.pointer_mut(&pointer).unwrap() = serde_json::Value::Number(serde_json::Number::from_f64(-0.0).unwrap()); + let twin: DevelopSettings = serde_json::from_value(v).unwrap(); + if twin.hash64() == DevelopSettings::default().hash64() { + continue; // (a zero the settings don't write back: nothing to tell apart) + } + assert_eq!(twin, DevelopSettings::default(), "{path:?}"); + checked += 1; + let twin = Arc::new(twin); + let shared = shared::settings(twin.clone()); + assert!(Arc::ptr_eq(&shared, &twin) && !Arc::ptr_eq(&shared, &base), "{path:?} was shared with the defaults"); + } + assert!(checked > 20, "only {checked} negative zeros could be told apart"); +} diff --git a/crates/codecs/src/lib.rs b/crates/codecs/src/lib.rs index 7370bde763..c2846db258 100644 --- a/crates/codecs/src/lib.rs +++ b/crates/codecs/src/lib.rs @@ -247,7 +247,7 @@ pub fn decode_unguarded(bytes: &[u8], format: Format, opts: &DecodeOptions) -> R let opts = *opts; // The reason a format can't be decoded lives in one place, `Format::not_decodable`. let unsupported = || Err(Error::Unsupported(format, format.not_decodable().unwrap_or("not decodable in this build"))); - match format { + let d = match format { Format::Jpeg => jpeg::decode(bytes, &opts), Format::Png => png_codec::decode(bytes, &opts), Format::Tiff => tiff_codec::decode(bytes, &opts), @@ -261,7 +261,20 @@ pub fn decode_unguarded(bytes: &[u8], format: Format, opts: &DecodeOptions) -> R Format::Heif => heif::decode(bytes, &opts), Format::Avif => avif_decode::decode(bytes, &opts), Format::RawTiffLike | Format::RawOther => unsupported(), + }?; + check_has_pixels(format, &d.image)?; + Ok(d) +} + +/// An image with no pixels (a malformed header claiming zero width or height, a `w × h` that +/// overflows, or a buffer shorter than its size) is refused, so nothing downstream sees an empty +/// image. +fn check_has_pixels(format: Format, image: &Rgb32f) -> Result<()> { + let (w, h) = (image.width, image.height); + if w == 0 || h == 0 || w.checked_mul(h).is_none_or(|n| image.data.len() < n) { + return Err(Error::Malformed(format, "image has no pixels".into())); } + Ok(()) } /// Convert a decode result to linear Rec.2020 D65 (Bradford-adapted), the develop working space. @@ -381,4 +394,29 @@ mod checked_arithmetic_tests { // 300 Mpx RGBA is within the default pixel limit, so it must not be refused by sample count. assert_eq!(checked_sample_buf_len(20_000, 15_000, 4), Some(1_200_000_000)); } + + #[test] + fn checked_sample_buf_len_does_not_wrap_like_32_bit_usize() { + // 65535 × 21846 × 3 = 4_295_032_830, which a 32-bit `usize` product wraps to 65_534 + assert_eq!(checked_sample_buf_len(65_535, 21_846, 3), Some(4_295_032_830)); + assert!(checked_sample_buf_len(65_535, 21_846, 3).is_some_and(|n| n > 65_534)); + } + + fn image(width: usize, height: usize, len: usize) -> Rgb32f { + Rgb32f { width, height, data: vec![[0.0; 3]; len] } + } + + #[test] + fn decoded_image_without_pixels_is_refused() { + for (w, h, len) in [(0, 4, 0), (4, 0, 0), (usize::MAX, 2, 1), (4, 4, 15)] { + let r = check_has_pixels(Format::Png, &image(w, h, len)); + assert!(matches!(r, Err(Error::Malformed(Format::Png, _))), "{w}x{h} with {len} pixels"); + } + } + + #[test] + fn decoded_image_with_all_pixels_is_accepted() { + assert!(check_has_pixels(Format::Png, &image(4, 4, 16)).is_ok()); + assert!(check_has_pixels(Format::Png, &image(1, 1, 1)).is_ok()); + } } diff --git a/crates/codecs/tests/it/fuzz.rs b/crates/codecs/tests/it/fuzz.rs index ceb271d869..7d445329b1 100644 --- a/crates/codecs/tests/it/fuzz.rs +++ b/crates/codecs/tests/it/fuzz.rs @@ -291,6 +291,43 @@ fn thumbnail_respects_configured_source_pixel_limit() { assert_eq!(decode_thumbnail_with(&bytes, &opts).unwrap().image.width, 1); } +/// A header claiming zero width or height is an error, never a decoded image with no pixels +/// (downstream filters index into it). +#[test] +// End-to-end no-panic check: headers claiming a zero dimension are errors. The JPEG and PNG +// readers already refuse these; `decode_unguarded`'s own final-output guard is tested directly in +// the crate's unit tests. +fn zero_size_headers_are_refused() { + let jpeg = seeds()[0].clone(); + let sof = jpeg.windows(2).position(|m| m == [0xFF, 0xC0]).unwrap(); + for at in [sof + 5, sof + 7] { + let mut j = jpeg.clone(); + j[at..at + 2].copy_from_slice(&[0, 0]); + assert!(decode_unguarded(&j, Format::Jpeg, &small_opts()).is_err()); + } + let png = seeds()[1].clone(); + for at in [16, 20] { + let mut p = png.clone(); + p[at..at + 4].copy_from_slice(&[0; 4]); + // repair the IHDR CRC so the dimension, not the checksum, is what gets refused + let crc = crc32(&p[12..29]); + p[29..33].copy_from_slice(&crc.to_be_bytes()); + assert!(decode_unguarded(&p, Format::Png, &small_opts()).is_err()); + } +} + +/// CRC-32 (IEEE), as PNG chunks use. +fn crc32(bytes: &[u8]) -> u32 { + let mut c = !0u32; + for &b in bytes { + c ^= u32::from(b); + for _ in 0..8 { + c = if c & 1 != 0 { 0xEDB8_8320 ^ (c >> 1) } else { c >> 1 }; + } + } + !c +} + fn seeds() -> &'static Vec> { static S: OnceLock>> = OnceLock::new(); S.get_or_init(|| { diff --git a/crates/denoise/src/cpu.rs b/crates/denoise/src/cpu.rs index 34e5269e42..9447fa28f4 100644 --- a/crates/denoise/src/cpu.rs +++ b/crates/denoise/src/cpu.rs @@ -35,6 +35,7 @@ fn sources(op: &Op) -> (usize, Option) { match op { Op::Conv(c) => (c.src, c.src2), Op::ConvT2(c) => (c.src, None), + Op::Add { src, src2 } => (*src, Some(*src2)), Op::MaxPool2 { src } | Op::DepthToSpace2 { src } => (*src, None), } } @@ -108,6 +109,7 @@ impl NetRunner { (a.channels, a.side / 2) } Op::DepthToSpace2 { .. } => (a.channels / 4, a.side.checked_mul(2).ok_or_else(|| bad("size overflow"))?), + Op::Add { .. } => (a.channels, a.side), }; let n = count(channels, side)?; let slot = busy @@ -215,6 +217,7 @@ impl NetRunner { &mut w.lower, &mut w.product, )?, + Op::Add { .. } => add(a, b.ok_or_else(|| bad("Add needs two inputs"))?, shape.side, dest)?, Op::MaxPool2 { .. } => pool(a, shape.side, dest)?, Op::DepthToSpace2 { .. } => shuffle(a, shape.side, dest)?, } @@ -381,6 +384,46 @@ fn shuffle(a: &[f32], side: usize, dest: &mut [f32]) -> Result<()> { } Ok(()) } +fn add(a: &[f32], b: &[f32], side: usize, dest: &mut [f32]) -> Result<()> { + let pixels = side * side; + let channels = a.len() / pixels; + let need = channels.checked_mul(pixels).ok_or_else(|| bad("Add size overflows"))?; + if a.len() < need || b.len() < need || dest.len() < need { + return Err(bad("Add inputs and output are not the same size")); + } + for c in 0..channels { + let a_plane = &a[c * pixels..(c + 1) * pixels]; + let b_plane = &b[c * pixels..(c + 1) * pixels]; + let d_plane = &mut dest[c * pixels..(c + 1) * pixels]; + for (d, (&av, &bv)) in d_plane.iter_mut().zip(a_plane.iter().zip(b_plane)) { + *d = av + bv; + } + } + Ok(()) +} + +#[cfg(test)] +#[test] +fn add_op_produces_elementwise_sum() { + use crate::net::{Conv, Net, Op, TensorId}; + + fn conv(src: TensorId, cin: usize, cout: usize) -> Op { + Op::Conv(Conv { src, src2: None, cin, cout, k: 1, weight: vec![0.1; cout * cin], bias: vec![0.0; cout], leaky: None }) + } + + let tile = 8usize; + let ops = vec![conv(0, 4, 12), Op::Add { src: 1, src2: 1 }, Op::DepthToSpace2 { src: 2 }]; + let net = Net::new(4, ops).unwrap(); + let runner = NetRunner::new(&net, tile).unwrap(); + + let pixels = tile * tile; + let input: Vec = vec![1.0; 4 * pixels]; + let output = runner.run(&input).unwrap(); + assert_eq!(output.len(), 3 * (2 * tile) * (2 * tile)); + for &v in &output { + assert!((v - 0.8).abs() < 1e-4, "expected 0.8, got {v}"); + } +} #[cfg(test)] mod tests; diff --git a/crates/denoise/src/net.rs b/crates/denoise/src/net.rs index 422418336b..7c648bb042 100644 --- a/crates/denoise/src/net.rs +++ b/crates/denoise/src/net.rs @@ -63,6 +63,11 @@ pub struct ConvT2 { pub enum Op { Conv(Conv), ConvT2(ConvT2), + /// Elementwise addition of two same-shape tensors. + Add { + src: TensorId, + src2: TensorId, + }, /// 2 × 2 maximum, stride 2. MaxPool2 { src: TensorId, @@ -146,6 +151,20 @@ impl Net { check_weights(i, &c.weight, c.cin.checked_mul(c.cout).and_then(|n| n.checked_mul(4)), &c.bias, c.cout, c.leaky, &mut weights)?; Shape { channels: c.cout, level: a.level - 1 } } + Op::Add { src, src2 } => { + let a = shape_of(*src)?; + let b = shape_of(*src2)?; + if a.channels != b.channels || a.level != b.level { + return invalid(format!("layer {i}: add of tensors of different shapes")); + } + if a.channels == 0 { + return invalid(format!("layer {i}: add with zero channels")); + } + if a.channels > MAX_CHANNELS { + return invalid(format!("layer {i}: add with more than {} channels", MAX_CHANNELS)); + } + Shape { channels: a.channels, level: a.level } + } Op::MaxPool2 { src } => { let a = shape_of(*src)?; Shape { channels: a.channels, level: a.level + 1 } diff --git a/crates/denoise/src/onnx.rs b/crates/denoise/src/onnx.rs index 074963695f..edc22a638d 100644 --- a/crates/denoise/src/onnx.rs +++ b/crates/denoise/src/onnx.rs @@ -2,16 +2,18 @@ //! //! Only what the denoise U-Nets are made of is understood: `Conv` (3 × 3 "same" or 1 × 1, stride 1, no groups, no //! dilation) optionally followed by `LeakyRelu`, `ConvTranspose` (2 × 2, stride 2) likewise, `MaxPool` (2 × 2, stride 2), -//! a two-input `Concat` on the channels that feeds a convolution, and a final `DepthToSpace` (2, `CRD`). Any other +//! a two-input `Concat` on the channels that feeds a convolution, an `Add` of two same-shape tensors (elementwise addition), +//! a standalone `LeakyRelu` (as a 1 × 1 identity convolution with the +//! activation, when its source has more than one reader), and a final `DepthToSpace` (2, `CRD`). Any other //! operator or attribute is [`NetError::Unsupported`], which is reported to the user by both runners. -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::path::Path; use crate::onnx_proto::{self, AttributeProto, NodeProto, TensorProto, ValueInfoProto}; use std::io::Read; -use crate::net::{Conv, ConvT2, MAX_WEIGHTS, Net, NetError, Op, TensorId}; +use crate::net::{Conv, ConvT2, MAX_CHANNELS, MAX_OPS, MAX_WEIGHTS, Net, NetError, Op, TensorId}; fn unsupported(why: impl Into) -> Result { Err(NetError::Unsupported(why.into())) @@ -62,11 +64,23 @@ fn read_bytes(bytes: &[u8]) -> Result { // a Concat is not a layer of its own: the convolution that reads it takes both sources let mut joins: HashMap = HashMap::new(); let mut ops: Vec = Vec::new(); + let mut shapes: Vec<(usize, i32)> = vec![(in_channels, 0)]; let mut weights_total = 0usize; let nodes = &graph.node; let mut i = 0; + let mut fused_indices = HashSet::new(); while i < nodes.len() { + // Skip nodes that were fused as LeakyRelu activations + while i < nodes.len() && fused_indices.contains(&i) { + i += 1; + } + if i >= nodes.len() { + break; + } + if ops.len() >= MAX_OPS { + return invalid("the network has too many layers"); + } let Some(node) = nodes.get(i) else { break }; i += 1; if node.output.len() != 1 || node.output.first().is_none_or(|n| n.is_empty() || ids.contains_key(n) || joins.contains_key(n)) { @@ -77,6 +91,8 @@ fn read_bytes(bytes: &[u8]) -> Result { "ConvTranspose" => &["kernel_shape", "pads", "strides", "dilations", "group", "output_padding", "auto_pad"], "MaxPool" => &["kernel_shape", "pads", "strides", "dilations", "ceil_mode", "storage_order", "auto_pad"], "Concat" => &["axis"], + "Add" => &[], + "LeakyRelu" => &["alpha"], "DepthToSpace" => &["blocksize", "mode"], _ => &[], }; @@ -87,25 +103,37 @@ fn read_bytes(bytes: &[u8]) -> Result { let lookup = |name: &str| -> Result { ids.get(name).copied().ok_or_else(|| NetError::Invalid(format!("`{}` reads `{name}`, which nothing makes", node.op_type))) }; - // a LeakyRelu straight after this layer, which nothing else reads, is part of it - let mut fuse_leaky = |out: &str| -> Result<(Option, String), NetError> { - if let Some(next) = nodes.get(i) - && next.op_type == "LeakyRelu" - && next.input.first().map(String::as_str) == Some(out) - && readers.get(out).copied() == Some(1) - { - if next.input.len() != 1 || next.output.len() != 1 || next.attribute.iter().any(|a| a.name != "alpha") { - return invalid("malformed LeakyRelu"); + // a LeakyRelu consuming this output, which nothing else reads, is part of it + let mut fuse_leaky = |out: &str, joins: &HashMap| -> Result<(Option, String), NetError> { + // Search forward for a LeakyRelu consuming this output + for j in i..nodes.len() { + if fused_indices.contains(&j) { + continue; + } + let next = &nodes[j]; + if next.op_type == "LeakyRelu" && next.input.first().map(String::as_str) == Some(out) && readers.get(out).copied() == Some(1) { + if next.input.len() != 1 || next.output.len() != 1 || next.attribute.iter().any(|a| a.name != "alpha") { + return invalid("malformed LeakyRelu"); + } + // only an omitted alpha gets the ONNX default; one that is not a single float must not read as 0 + let alpha = match next.attribute.as_slice() { + [] => 0.01, + [AttributeProto { f: Some(f), kind: 0 | 1, .. }] => *f, + _ => return invalid("LeakyRelu alpha is not a single float"), + }; + let name = next.output.first().cloned().ok_or_else(|| NetError::Invalid("LeakyRelu without an output".into()))?; + if name.is_empty() || ids.contains_key(&name) || joins.contains_key(&name) { + continue; + } + // Fusing gives the LeakyRelu's output the id of this op. If that output is the graph + // output it must stay the last tensor, so decline the fusion when another node after + // this one emits an operation: it would push the graph output before a later tensor. + if name == output.name.as_str() && nodes[i..].iter().enumerate().any(|(k, n)| i + k != j && emits_op(n.op_type.as_str())) { + continue; + } + fused_indices.insert(j); + return Ok((Some(alpha), name)); } - // only an omitted alpha gets the ONNX default; one that is not a single float must not read as 0 - let alpha = match next.attribute.as_slice() { - [] => 0.01, - [AttributeProto { f: Some(f), kind: 0 | 1, .. }] => *f, - _ => return invalid("LeakyRelu alpha is not a single float"), - }; - i += 1; - let name = next.output.first().cloned().ok_or_else(|| NetError::Invalid("LeakyRelu without an output".into()))?; - return Ok((Some(alpha), name)); } Ok((None, out.to_string())) }; @@ -147,8 +175,9 @@ fn read_bytes(bytes: &[u8]) -> Result { None => (lookup(src_name)?, None), }; let out = node.output.first().ok_or_else(|| NetError::Invalid("Conv without an output".into()))?; - let (leaky, out_name) = fuse_leaky(out)?; + let (leaky, out_name) = fuse_leaky(out, &joins)?; ids.insert(out_name, this); + shapes.push((cout, shapes.get(src).copied().map_or(0, |s| s.1))); ops.push(Op::Conv(Conv { src, src2, cin, cout, k: kh, weight: w.1, bias: b, leaky })); } "ConvTranspose" => { @@ -172,8 +201,9 @@ fn read_bytes(bytes: &[u8]) -> Result { } let src = lookup(node.input.first().map_or("", String::as_str))?; let out = node.output.first().ok_or_else(|| NetError::Invalid("ConvTranspose without an output".into()))?; - let (leaky, out_name) = fuse_leaky(out)?; + let (leaky, out_name) = fuse_leaky(out, &joins)?; ids.insert(out_name, this); + shapes.push((cout, shapes.get(src).copied().map_or(0, |s| s.1) - 1)); ops.push(Op::ConvT2(ConvT2 { src, cin, cout, weight: w.1, bias: b, leaky })); } "MaxPool" => { @@ -190,8 +220,72 @@ fn read_bytes(bytes: &[u8]) -> Result { let src = lookup(node.input.first().map_or("", String::as_str))?; let out = node.output.first().ok_or_else(|| NetError::Invalid("MaxPool without an output".into()))?; ids.insert(out.clone(), this); + shapes.push(shapes.get(src).copied().map_or((in_channels, 1), |(c, l)| (c, l + 1))); ops.push(Op::MaxPool2 { src }); } + "Add" => { + let [a, b] = node.input.as_slice() else { return unsupported("Add of other than two tensors") }; + if joins.contains_key(a) || joins.contains_key(b) { + return unsupported("Add reading a Concat output"); + } + if initialisers.contains_key(a.as_str()) || initialisers.contains_key(b.as_str()) { + return unsupported("Add with an initializer operand"); + } + let src = lookup(a)?; + let src2 = lookup(b)?; + let out = node.output.first().ok_or_else(|| NetError::Invalid("Add without an output".into()))?; + let (ca, la) = shapes.get(src).copied().ok_or_else(|| NetError::Invalid("Add reads a tensor with no shape".into()))?; + let (cb, lb) = shapes.get(src2).copied().ok_or_else(|| NetError::Invalid("Add reads a tensor with no shape".into()))?; + if ca != cb || la != lb { + return unsupported("Add of tensors of different shapes"); + } + if ca == 0 { + return invalid("Add with zero channels"); + } + if ca > MAX_CHANNELS { + return unsupported("Add with more than 4096 channels"); + } + ids.insert(out.clone(), this); + shapes.push((ca, la)); + ops.push(Op::Add { src, src2 }); + } + "LeakyRelu" => { + let [a] = node.input.as_slice() else { return invalid("malformed LeakyRelu") }; + if joins.contains_key(a) { + return unsupported("LeakyRelu reading a Concat output"); + } + if initialisers.contains_key(a.as_str()) { + return unsupported("LeakyRelu with an initializer operand"); + } + let src = lookup(a)?; + let out = node.output.first().ok_or_else(|| NetError::Invalid("LeakyRelu without an output".into()))?; + let (ca, la) = shapes.get(src).copied().ok_or_else(|| NetError::Invalid("LeakyRelu reads a tensor with no shape".into()))?; + if ca == 0 { + return invalid("LeakyRelu with zero channels"); + } + if ca > MAX_CHANNELS { + return unsupported("LeakyRelu with more than 4096 channels"); + } + let alpha = match node.attribute.as_slice() { + [] => 0.01, + [AttributeProto { f: Some(f), kind: 0 | 1, .. }] => *f, + _ => return invalid("LeakyRelu alpha is not a single float"), + }; + let nn = ca.checked_mul(ca).ok_or_else(|| NetError::Invalid("LeakyRelu channel count overflows".into()))?; + weights_total = weights_total.saturating_add(nn).saturating_add(ca); + if weights_total > MAX_WEIGHTS { + return invalid("the network has too many weights"); + } + let mut weight = vec![0.0f32; nn]; + for c in 0..ca { + if let Some(w) = weight.get_mut(c * ca + c) { + *w = 1.0; + } + } + ids.insert(out.clone(), this); + shapes.push((ca, la)); + ops.push(Op::Conv(Conv { src, src2: None, cin: ca, cout: ca, k: 1, weight, bias: vec![0.0; ca], leaky: Some(alpha) })); + } "DepthToSpace" => { if attr(node, "blocksize").map(|a| a.i) != Some(2) || attr(node, "mode").map(|a| a.s.as_slice()) != Some(&b"CRD"[..]) { return unsupported("depth-to-space other than block size 2 in CRD order"); @@ -199,6 +293,7 @@ fn read_bytes(bytes: &[u8]) -> Result { let src = lookup(node.input.first().map_or("", String::as_str))?; let out = node.output.first().ok_or_else(|| NetError::Invalid("DepthToSpace without an output".into()))?; ids.insert(out.clone(), this); + shapes.push(shapes.get(src).copied().map_or((in_channels / 4, -1), |(c, l)| (c / 4, l - 1))); ops.push(Op::DepthToSpace2 { src }); } other => return unsupported(format!("the `{other}` operator")), @@ -222,6 +317,12 @@ fn ints_or(n: &NodeProto, name: &str, default: &[i64]) -> Vec { attr(n, name).map_or_else(|| default.to_vec(), |a| a.ints.clone()) } +/// Whether an ONNX operator node emits a denoise-layer operation. `Concat` does not: it only +/// records a join for the convolution that follows it. +fn emits_op(op_type: &str) -> bool { + matches!(op_type, "Conv" | "ConvTranspose" | "MaxPool" | "Add" | "LeakyRelu" | "DepthToSpace") +} + fn four(dims: &[i64]) -> Result<(usize, usize, usize, usize), NetError> { match dims { [a, b, c, d] if dims.iter().all(|&v| v > 0 && v <= 1 << 20) => Ok((*a as usize, *b as usize, *c as usize, *d as usize)), @@ -297,6 +398,7 @@ fn channel_dim(v: &ValueInfoProto) -> Option { mod tests { use super::*; use crate::synthetic::unet_onnx; + use crate::synthetic_proto::{len_field, value_info_bytes, varint_field}; fn temp_model(name: &str, bytes: &[u8]) -> std::path::PathBuf { let p = std::env::temp_dir().join(format!("lc-denoise-onnx-{name}-{}.onnx", std::process::id())); @@ -304,6 +406,109 @@ mod tests { p } + fn node(op: &str, inputs: &[&str], output: &str, ints: &[(&str, i64)]) -> Vec { + let mut n = Vec::new(); + for i in inputs { + len_field(1, i.as_bytes(), &mut n); + } + len_field(2, output.as_bytes(), &mut n); + len_field(4, op.as_bytes(), &mut n); + for (name, value) in ints { + let mut a = Vec::new(); + len_field(1, name.as_bytes(), &mut a); + varint_field(3, *value as u64, &mut a); + varint_field(20, 2, &mut a); + len_field(5, &a, &mut n); + } + n + } + + fn tensor(name: &str, dims: &[u64], values: &[f32]) -> Vec { + let mut t = Vec::new(); + for d in dims { + varint_field(1, *d, &mut t); + } + varint_field(2, 1, &mut t); + len_field(8, name.as_bytes(), &mut t); + let raw: Vec = values.iter().flat_map(|v| v.to_le_bytes()).collect(); + len_field(9, &raw, &mut t); + t + } + + fn model(nodes: &[Vec], in_channels: u64, out: &str) -> Vec { + let mut graph = Vec::new(); + for n in nodes { + len_field(1, n, &mut graph); + } + len_field(11, &value_info_bytes("data", 1, &[Ok(1), Ok(in_channels), Ok(8), Ok(8)]), &mut graph); + len_field(12, &value_info_bytes(out, 1, &[Ok(1), Ok(3), Ok(8), Ok(8)]), &mut graph); + let mut ops = Vec::new(); + len_field(1, b"", &mut ops); + varint_field(2, 13, &mut ops); + let mut model = Vec::new(); + varint_field(1, 8, &mut model); + len_field(7, &graph, &mut model); + len_field(8, &ops, &mut model); + model + } + + fn varint(mut v: u64, out: &mut Vec) { + loop { + let b = (v & 0x7f) as u8; + v >>= 7; + if v == 0 { + out.push(b); + return; + } + out.push(b | 0x80); + } + } + + fn node_with_ints(op: &str, inputs: &[&str], output: &str, ints: &[(&str, &[i64])]) -> Vec { + let mut n = Vec::new(); + for i in inputs { + len_field(1, i.as_bytes(), &mut n); + } + len_field(2, output.as_bytes(), &mut n); + len_field(4, op.as_bytes(), &mut n); + for &(name, values) in ints { + let mut a = Vec::new(); + len_field(1, name.as_bytes(), &mut a); + // field 8: INTS (wire type 2) - varint-encoded list + varint(8 << 3 | 2, &mut a); + // length of the list in bytes (we'll compute after writing values) + let mut vals = Vec::new(); + for &v in values { + varint(v as u64, &mut vals); + } + varint(vals.len() as u64, &mut a); + a.extend_from_slice(&vals); + // field 20: type = 7 (INTS) + varint_field(20, 7, &mut a); + len_field(5, &a, &mut n); + } + n + } + + fn leaky_relu_node(inputs: &[&str], output: &str, alpha: f32) -> Vec { + let mut n = Vec::new(); + for i in inputs { + len_field(1, i.as_bytes(), &mut n); + } + len_field(2, output.as_bytes(), &mut n); + len_field(4, b"LeakyRelu", &mut n); + // alpha attribute: field 1=name, field 2=float value (wire type 5), field 20=type=1 (FLOAT) + let mut a = Vec::new(); + len_field(1, b"alpha", &mut a); + // field 2 with wire type 5 (fixed 4-byte float) + varint(2 << 3 | 5, &mut a); + a.extend_from_slice(&alpha.to_le_bytes()); + // field 20: type = 1 (FLOAT) + varint_field(20, 1, &mut a); + len_field(5, &a, &mut n); + n + } + #[test] fn a_u_net_is_read_with_its_layers_fused() { let (tile, depth) = (32usize, 2usize); @@ -324,6 +529,38 @@ mod tests { let _ = std::fs::remove_file(p); } + #[test] + fn add_operator_model_is_accepted() { + // the convolution output added back to the input, as a residual block does + let mut graph = Vec::new(); + len_field(1, &node("Conv", &["data", "w1"], "c1", &[("group", 1)]), &mut graph); + len_field(1, &node("Add", &["c1", "data"], "a1", &[]), &mut graph); + len_field(1, &node("Conv", &["a1", "w2"], "c2", &[("group", 1)]), &mut graph); + let mut depth_to_space = node("DepthToSpace", &["c2"], "rgb", &[("blocksize", 2)]); + let mut mode = Vec::new(); + len_field(1, b"mode", &mut mode); + len_field(4, b"CRD", &mut mode); + varint_field(20, 3, &mut mode); + len_field(5, &mode, &mut depth_to_space); + len_field(1, &depth_to_space, &mut graph); + len_field(5, &tensor("w1", &[4, 4, 1, 1], &[0.1; 16]), &mut graph); + len_field(5, &tensor("w2", &[12, 4, 1, 1], &[0.1; 48]), &mut graph); + len_field(11, &value_info_bytes("data", 1, &[Ok(1), Ok(4), Ok(8), Ok(8)]), &mut graph); + len_field(12, &value_info_bytes("rgb", 1, &[Ok(1), Ok(3), Ok(16), Ok(16)]), &mut graph); + let mut ops = Vec::new(); + len_field(1, b"", &mut ops); + varint_field(2, 13, &mut ops); + let mut model = Vec::new(); + varint_field(1, 8, &mut model); + len_field(7, &graph, &mut model); + len_field(8, &ops, &mut model); + + let net = read_bytes(&model); + assert!(net.is_ok(), "a model with an Add residual was rejected: {:?}", net.err()); + let net = net.unwrap(); + assert_eq!((net.in_channels, net.out_channels()), (4, 3)); + } + #[test] fn a_leaky_relu_alpha_that_is_not_a_float_is_rejected() { let good = unet_onnx(4, 3, 1, 7); @@ -390,4 +627,213 @@ mod tests { // a missing file assert!(read(Path::new("/does/not/exist.onnx")).is_err()); } + + #[test] + fn add_reading_concat_and_oversized_channels_are_unsupported() { + let concat_model = + model(&[node("Concat", &["data", "data"], "joined", &[("axis", 1)]), node("Add", &["joined", "data"], "a1", &[])], 4, "a1"); + assert!(matches!(read_bytes(&concat_model), Err(NetError::Unsupported(_)))); + + let oversized_model = model(&[node("Add", &["data", "data"], "a1", &[])], 4097, "a1"); + assert!(matches!(read_bytes(&oversized_model), Err(NetError::Unsupported(_)))); + + let mut depth = node("DepthToSpace", &["data"], "d", &[("blocksize", 2)]); + let mut mode = Vec::new(); + len_field(1, b"mode", &mut mode); + len_field(4, b"CRD", &mut mode); + varint_field(20, 3, &mut mode); + len_field(5, &mode, &mut depth); + let zero_model = model(&[depth, node("Add", &["d", "d"], "a1", &[])], 3, "a1"); + assert!(matches!(read_bytes(&zero_model), Err(NetError::Invalid(_)))); + } + + #[test] + fn many_adds_on_a_wide_input_are_accepted_up_to_max_ops() { + // 32 Add nodes on 4096 channels should be accepted (32 < MAX_OPS=512, no weight allocation) + let mut nodes = Vec::new(); + let mut prev = "data".to_string(); + for i in 0..32 { + let out = format!("a{i}"); + nodes.push(node("Add", &[prev.as_str(), prev.as_str()], &out, &[])); + prev = out; + } + let wide_model = model(&nodes, 4096, &prev); + assert!(read_bytes(&wide_model).is_ok(), "many Add nodes on wide input should be accepted"); + + // But exceeding MAX_OPS should still be rejected + let mut nodes = Vec::new(); + let mut prev = "data".to_string(); + for i in 0..=MAX_OPS { + let out = format!("a{i}"); + nodes.push(node("Add", &[prev.as_str(), prev.as_str()], &out, &[])); + prev = out; + } + let too_many_model = model(&nodes, 1, &prev); + assert!(matches!(read_bytes(&too_many_model), Err(NetError::Invalid(_)))); + } + + #[test] + fn leaky_relu_with_an_add_residual_branch_is_accepted() { + // the convolution output is read by both the LeakyRelu and the Add residual branch + let mut graph = Vec::new(); + len_field(1, &node("Conv", &["data", "w1"], "c1", &[("group", 1)]), &mut graph); + len_field(1, &node("LeakyRelu", &["c1"], "l1", &[]), &mut graph); + len_field(1, &node("Add", &["c1", "l1"], "a1", &[]), &mut graph); + len_field(1, &node("Conv", &["a1", "w2"], "c2", &[("group", 1)]), &mut graph); + let mut depth_to_space = node("DepthToSpace", &["c2"], "rgb", &[("blocksize", 2)]); + let mut mode = Vec::new(); + len_field(1, b"mode", &mut mode); + len_field(4, b"CRD", &mut mode); + varint_field(20, 3, &mut mode); + len_field(5, &mode, &mut depth_to_space); + len_field(1, &depth_to_space, &mut graph); + len_field(5, &tensor("w1", &[4, 4, 1, 1], &[0.1; 16]), &mut graph); + len_field(5, &tensor("w2", &[12, 4, 1, 1], &[0.1; 48]), &mut graph); + len_field(11, &value_info_bytes("data", 1, &[Ok(1), Ok(4), Ok(8), Ok(8)]), &mut graph); + len_field(12, &value_info_bytes("rgb", 1, &[Ok(1), Ok(3), Ok(16), Ok(16)]), &mut graph); + let mut ops = Vec::new(); + len_field(1, b"", &mut ops); + varint_field(2, 13, &mut ops); + let mut model = Vec::new(); + varint_field(1, 8, &mut model); + len_field(7, &graph, &mut model); + len_field(8, &ops, &mut model); + + let net = read_bytes(&model); + assert!(net.is_ok(), "a LeakyRelu residual model was rejected: {:?}", net.err()); + let net = net.unwrap(); + assert_eq!((net.in_channels, net.out_channels()), (4, 3)); + } + + #[test] + fn leaky_relu_fuses_across_interleaved_nodes() { + // Conv produces "c1", then an unrelated MaxPool (reading "data") comes between, + // then a LeakyRelu consumes "c1". The fusion should still happen. + let mut graph = Vec::new(); + len_field(1, &node("Conv", &["data", "w1"], "c1", &[("group", 1)]), &mut graph); + // Valid MaxPool: 2x2 kernel, stride 2, no padding, no dilation + len_field( + 1, + &node_with_ints( + "MaxPool", + &["data"], + "mp1", + &[("kernel_shape", &[2, 2]), ("strides", &[2, 2]), ("pads", &[0, 0, 0, 0]), ("dilations", &[1, 1])], + ), + &mut graph, + ); + len_field(1, &leaky_relu_node(&["c1"], "l1", 0.2), &mut graph); // alpha=0.2 + let mut depth_to_space = node("DepthToSpace", &["l1"], "rgb", &[("blocksize", 2)]); + let mut mode = Vec::new(); + len_field(1, b"mode", &mut mode); + len_field(4, b"CRD", &mut mode); + varint_field(20, 3, &mut mode); + len_field(5, &mode, &mut depth_to_space); + len_field(1, &depth_to_space, &mut graph); + len_field(5, &tensor("w1", &[12, 4, 1, 1], &[0.1; 48]), &mut graph); + len_field(11, &value_info_bytes("data", 1, &[Ok(1), Ok(4), Ok(8), Ok(8)]), &mut graph); + len_field(12, &value_info_bytes("rgb", 1, &[Ok(1), Ok(3), Ok(16), Ok(16)]), &mut graph); + let mut ops = Vec::new(); + len_field(1, b"", &mut ops); + varint_field(2, 13, &mut ops); + let mut model = Vec::new(); + varint_field(1, 8, &mut model); + len_field(7, &graph, &mut model); + len_field(8, &ops, &mut model); + + let net = read_bytes(&model); + assert!(net.is_ok(), "LeakyRelu across interleaved nodes was rejected: {:?}", net.err()); + let net = net.unwrap(); + assert_eq!((net.in_channels, net.out_channels()), (4, 3)); + // The Conv should have the leaky ReLU fused with alpha=0.2 + let ops = net.ops(); + assert_eq!(ops.len(), 3); // Conv (fused), MaxPool, DepthToSpace + match &ops[0] { + crate::net::Op::Conv(c) => { + assert_eq!(c.leaky, Some(0.2), "LeakyRelu alpha should be fused into Conv"); + } + _ => panic!("first op should be fused Conv"), + } + assert!(matches!(ops[1], crate::net::Op::MaxPool2 { .. })); + assert!(matches!(ops[2], crate::net::Op::DepthToSpace2 { .. })); + } + + #[test] + fn add_with_initializer_operand_is_unsupported() { + let mut graph = Vec::new(); + len_field(1, &node("Add", &["data", "w1"], "a1", &[]), &mut graph); + len_field(5, &tensor("w1", &[4], &[0.1; 4]), &mut graph); + len_field(11, &value_info_bytes("data", 1, &[Ok(1), Ok(4), Ok(8), Ok(8)]), &mut graph); + len_field(12, &value_info_bytes("a1", 1, &[Ok(1), Ok(4), Ok(8), Ok(8)]), &mut graph); + let mut ops = Vec::new(); + len_field(1, b"", &mut ops); + varint_field(2, 13, &mut ops); + let mut model = Vec::new(); + varint_field(1, 8, &mut model); + len_field(7, &graph, &mut model); + len_field(8, &ops, &mut model); + + assert!(matches!(read_bytes(&model), Err(NetError::Unsupported(_)))); + } + + #[test] + fn leaky_relu_with_initializer_operand_is_unsupported() { + let mut graph = Vec::new(); + len_field(1, &node("LeakyRelu", &["w1"], "l1", &[]), &mut graph); + len_field(5, &tensor("w1", &[4], &[0.1; 4]), &mut graph); + len_field(11, &value_info_bytes("data", 1, &[Ok(1), Ok(4), Ok(8), Ok(8)]), &mut graph); + len_field(12, &value_info_bytes("l1", 1, &[Ok(1), Ok(4), Ok(8), Ok(8)]), &mut graph); + let mut ops = Vec::new(); + len_field(1, b"", &mut ops); + varint_field(2, 13, &mut ops); + let mut model = Vec::new(); + varint_field(1, 8, &mut model); + len_field(7, &graph, &mut model); + len_field(8, &ops, &mut model); + + assert!(matches!(read_bytes(&model), Err(NetError::Unsupported(_)))); + } + + #[test] + fn more_than_max_ops_small_adds_are_rejected_as_too_many_layers() { + let mut nodes = Vec::new(); + let mut prev = "data".to_string(); + for i in 0..=MAX_OPS { + let out = format!("a{i}"); + nodes.push(node("Add", &[prev.as_str(), prev.as_str()], &out, &[])); + prev = out; + } + let many_model = model(&nodes, 1, &prev); + assert!(matches!(read_bytes(&many_model), Err(NetError::Invalid(_)))); + } + + #[test] + fn add_operator_model_is_accepted_review_regression_1() { + // An Add residual block: the convolution output is added back to the input. + let mut graph = Vec::new(); + len_field(1, &node("Conv", &["data", "w1"], "c1", &[("group", 1)]), &mut graph); + len_field(1, &node("Add", &["c1", "data"], "a1", &[]), &mut graph); + len_field(1, &node("Conv", &["a1", "w2"], "c2", &[("group", 1)]), &mut graph); + let mut depth_to_space = node("DepthToSpace", &["c2"], "rgb", &[("blocksize", 2)]); + let mut mode = Vec::new(); + len_field(1, b"mode", &mut mode); + len_field(4, b"CRD", &mut mode); + varint_field(20, 3, &mut mode); + len_field(5, &mode, &mut depth_to_space); + len_field(1, &depth_to_space, &mut graph); + len_field(5, &tensor("w1", &[4, 4, 1, 1], &[0.1; 16]), &mut graph); + len_field(5, &tensor("w2", &[12, 4, 1, 1], &[0.1; 48]), &mut graph); + len_field(11, &value_info_bytes("data", 1, &[Ok(1), Ok(4), Ok(8), Ok(8)]), &mut graph); + len_field(12, &value_info_bytes("rgb", 1, &[Ok(1), Ok(3), Ok(16), Ok(16)]), &mut graph); + let mut ops = Vec::new(); + len_field(1, b"", &mut ops); + varint_field(2, 13, &mut ops); + let mut model = Vec::new(); + varint_field(1, 8, &mut model); + len_field(7, &graph, &mut model); + len_field(8, &ops, &mut model); + + let net = read_bytes(&model); + assert!(net.is_ok(), "a model with an Add residual was rejected: {:?}", net.err()); + } } diff --git a/crates/denoise/src/reference.rs b/crates/denoise/src/reference.rs index 488e9a7b7c..351679749b 100644 --- a/crates/denoise/src/reference.rs +++ b/crates/denoise/src/reference.rs @@ -104,6 +104,16 @@ pub fn run(net: &Net, tile: usize, input: &[f32]) -> Result, NetError> } T { channels: c.cout, side: out_side, data } } + Op::Add { src, src2 } => { + let a = get(&tensors, *src)?; + let b = get(&tensors, *src2)?; + let (channels, side) = (tensors[a].channels, tensors[a].side); + let mut data = tensor(channels, side, &mut total)?; + for (d, (&av, &bv)) in data.iter_mut().zip(tensors[a].data.iter().zip(&tensors[b].data)) { + *d = av + bv; + } + T { channels, side, data } + } Op::MaxPool2 { src } => { let a = get(&tensors, *src)?; let (channels, side) = (tensors[a].channels, tensors[a].side / 2); diff --git a/crates/develop/src/presets.rs b/crates/develop/src/presets.rs index 0ea3d12f8c..8ce6fc5c0f 100644 --- a/crates/develop/src/presets.rs +++ b/crates/develop/src/presets.rs @@ -5,8 +5,12 @@ //! computed from the photo's *original* state (its import settings, when known) and the preset's //! value, and replaces the photo's value; every other setting keeps the photo's value (issue //! #2159). `amount` (0..200 %) moves each named number between the original and the preset's -//! value. Copy/paste/sync use the same group selection ([`SettingsGroup`]) and merge into the -//! current settings as before. +//! value; a point curve (a tone curve) moves between the two curves as rendered. Switches and choices +//! (a profile or LUT id, a style, a flag) take the original's value below half amount and the +//! preset's from half amount up, and the strength of a choice the preset changes fades in from 0 +//! there; white balance on another scale is taken whole (see [`interpolate_object`]). +//! Copy/paste/sync use the same group selection ([`SettingsGroup`]) and merge into the current +//! settings as before. //! //! The rendering process ([`crate::ProcessVersion`]) is in no group: copy, paste, sync and presets //! made from a photo never carry it, so the photos they change keep their own. A partial that names @@ -159,42 +163,34 @@ pub fn deep_merge(base: &mut Value, patch: &Value) { } } -/// Interpolate numbers in `patch` towards/away from `base` by `t` (1 = patch as-is); non-numeric -/// values are taken from the patch when `t >= 0.5`. -fn scale_patch(base: &Value, patch: &Value, t: f64) -> Value { - match (base, patch) { - (Value::Object(b), Value::Object(p)) => { - let mut out = Map::new(); - for (k, pv) in p { - let bv = b.get(k).unwrap_or(&Value::Null); - out.insert(k.clone(), scale_patch(bv, pv, t)); - } - Value::Object(out) - } - // Integer fields (the grain seed, ids) are discrete like strings: an interpolated seed would - // not deserialize as an integer, and the whole preset would silently not apply. - (Value::Number(b), Value::Number(p)) if b.is_f64() || p.is_f64() => { - let (b, p) = (b.as_f64().unwrap_or(0.0), p.as_f64().unwrap_or(0.0)); - serde_json::Number::from_f64(b + (p - b) * t).map(Value::Number).unwrap_or(Value::Null) - } - (b, p) => { - if t >= 0.5 { - p.clone() - } else { - b.clone() - } - } - } -} - -/// Apply a partial settings object with an amount (1.0 = 100 %). Out-of-range values are clamped -/// through the control specs, as every merge does ([`DevelopSettings::merged`]). +/// Apply a partial settings object with an amount (1.0 = 100 %): each setting it names is blended +/// from `s`'s value by the same rules as a preset ([`interpolate_object`]). Out-of-range values are +/// clamped through the control specs, as every merge does ([`DevelopSettings::merged`]). At 0 % +/// (or less) nothing changes; at 100 % the partial is merged as it is. pub fn apply_partial(s: &DevelopSettings, partial: &Value, amount: f64) -> DevelopSettings { - let patch = if (amount - 1.0).abs() < 1e-9 { Cow::Borrowed(partial) } else { Cow::Owned(scale_patch(&s.to_json_for_merge(), partial, amount)) }; + if amount.is_nan() || amount <= 0.0 { + return s.clone(); + } + let patch = if (amount - 1.0).abs() < 1e-9 { + Cow::Borrowed(partial) + } else { + let base = blend_base(s); + Cow::Owned(Value::Object(partial.as_object().map(|p| interpolate_object(base.as_object(), p, amount)).unwrap_or_default())) + }; // (a white balance without a scale keeps its old meaning: `DevelopSettings::merged`) s.merged(&patch).unwrap_or_else(|_| s.clone()) } +/// `s` as the base an amount blends from: every group written out, also the ones serialization +/// leaves out while at their defaults (HDR), so their numbers blend from `s`'s values too. +fn blend_base(s: &DevelopSettings) -> Value { + let mut v = s.to_json_for_merge(); + if let (Some(o), Ok(hdr)) = (v.as_object_mut(), serde_json::to_value(s.hdr)) { + o.entry("hdr").or_insert(hdr); + } + v +} + /// Top-level settings keys that hold per-photo pixel repairs: a preset's named repairs compose on /// the photo's own values instead of the original's (masks are added by [`Preset::apply_on`]), and /// a preset without them leaves the photo's alone. @@ -212,7 +208,7 @@ fn compose_named(current: &DevelopSettings, original: &DevelopSettings, settings return current.merged(settings).unwrap_or_else(|_| current.clone()); } let cur = current.to_json(); - let mut base = original.to_json(); + let mut base = blend_base(original); if let (Some(b), Some(c)) = (base.as_object_mut(), cur.as_object()) { for k in REPAIR_KEYS { if let Some(v) = c.get(k) { @@ -229,12 +225,38 @@ fn compose_named(current: &DevelopSettings, original: &DevelopSettings, settings } /// The leaves of `patch` that apply at `t` (below 100 %), each computed from the same place in -/// `base`. A leaf the amount does not reach is left out, so the photo keeps its own value there. +/// `base` ([`interpolate_leaf`]). A leaf the amount does not reach is left out, so the photo keeps +/// its own value there. Two rules look at an object as a whole (issue #2669): +/// +/// - **The `amount` beside a choice.** When the preset changes a choice here (a string such as the +/// profile or LUT id or a style, or the object's `enabled` switch), its `amount` is the strength of +/// that choice, not of the base's: from half amount up, where the preset's choice applies, the +/// amount fades in from 0 (a new profile at 50 % has half the preset's strength, and a profile at +/// 0 % is no look at all); below half amount the base's choice keeps its own amount. +/// - **White balance on another scale.** `temp` / `tint` on a different [`crate::WbScale`] than the +/// base's (Kelvin against the older relative scale; a partial that names no scale is on the +/// relative one, as [`DevelopSettings::merged`] reads it) are in other units and are never +/// blended: below half amount the base's numbers and scale apply, from half amount up the +/// preset's, as for any other choice. fn interpolate_object(base: Option<&Map>, patch: &Map, t: f64) -> Map { + let get = |k: &str| base.and_then(|b| b.get(k)); + let choice_changed = patch.iter().any(|(k, pv)| (pv.is_string() || (k == "enabled" && pv.is_boolean())) && get(k) != Some(pv)); + let scale_of = |o: Option<&Map>| o.and_then(|o| o.get("scale")).and_then(Value::as_str).unwrap_or("legacy").to_string(); + let other_scale = (patch.contains_key("temp") || patch.contains_key("tint")) && scale_of(Some(patch)) != scale_of(base); let mut out = Map::new(); for (k, pv) in patch { - let bv = base.and_then(|b| b.get(k)); + if other_scale && matches!(k.as_str(), "temp" | "tint" | "scale") { + continue; + } + let bv = get(k); let v = match pv { + Value::Number(_) if choice_changed && k == "amount" => { + if t >= 0.5 { + interpolate_leaf(Some(&Value::from(0.0)), pv, t) + } else { + bv.cloned() + } + } Value::Object(p) => Some(Value::Object(interpolate_object(bv.and_then(Value::as_object), p, t))), _ => interpolate_leaf(bv, pv, t), }; @@ -242,18 +264,38 @@ fn interpolate_object(base: Option<&Map>, patch: &Map= 0.5 { Some(patch) } else { base }; + for k in ["temp", "tint"] { + if let Some(v) = patch.get(k).and(side.and_then(|o| o.get(k))) { + out.insert(k.to_string(), v.clone()); + } + } + out.insert("scale".to_string(), Value::from(scale_of(side))); + } out } -/// One leaf at `t`. Numbers move from `base` towards `patch`. Other values switch to the preset's -/// at half amount and up, and below it take the base's value. A null in the base is the baseline -/// value the import state recorded (a cleared option, such as a free crop aspect): below half -/// amount it applies and clears the photo's value, as the amount contract promises. A null the -/// preset writes is a value like any other, so it applies at half amount and up (a preset can -/// clear an option field such as a crop aspect). +/// One leaf at `t`. Numbers move from `base` towards `patch`. Point curves (lists of `{x, y}` +/// points, the tone curves; empty is the identity) move as curves: both are evaluated as the +/// renderer does (monotone cubic) at every control point of either, and the points blend like +/// numbers, `y` kept in `0..1`. Other values switch to the preset's at half amount and up, and +/// below it take the base's value. A null in the base is the baseline value the import state +/// recorded (a cleared option, such as a free crop aspect): below half amount it applies and +/// clears the photo's value, as the amount contract promises. A null the preset writes is a value +/// like any other, so it applies at half amount and up (a preset can clear an option field such as +/// a crop aspect). fn interpolate_leaf(base: Option<&Value>, patch: &Value, t: f64) -> Option { + if t > 0.0 + && let (Some(bc), Some(pc)) = (base.and_then(point_curve), point_curve(patch)) + && !(bc.is_empty() && pc.is_empty()) + { + return Some(blend_curves(&bc, &pc, t)); + } match (base, patch) { - // integer fields (the grain seed, ids) are discrete like strings: see `scale_patch` + // integer fields (the grain seed, ids) are discrete like strings: an interpolated seed would + // not deserialize as an integer, and the whole preset would silently not apply (Some(Value::Number(b)), Value::Number(p)) if b.is_f64() || p.is_f64() => { let (b, p) = (b.as_f64().unwrap_or(0.0), p.as_f64().unwrap_or(0.0)); serde_json::Number::from_f64(b + (p - b) * t).map(Value::Number) @@ -263,6 +305,34 @@ fn interpolate_leaf(base: Option<&Value>, patch: &Value, t: f64) -> Option Option> { + v.as_array()? + .iter() + .map(|q| { + let o = q.as_object().filter(|o| o.len() == 2)?; + Some((o.get("x")?.as_f64()?, o.get("y")?.as_f64()?)) + }) + .collect() +} + +/// Two point curves blended by `t` at the control points of both (see [`interpolate_leaf`]). +fn blend_curves(base: &[(f64, f64)], patch: &[(f64, f64)], t: f64) -> Value { + use lightcraft_color::spline::MonotoneCurve; + let (bc, pc) = (MonotoneCurve::new(base), MonotoneCurve::new(patch)); + let mut xs: Vec = bc.points().into_iter().chain(pc.points()).map(|(x, _)| x.clamp(0.0, 1.0)).collect(); + xs.sort_by(f64::total_cmp); + xs.dedup_by(|a, b| (*a - *b).abs() < 1e-6); + let points = xs + .into_iter() + .map(|x| { + let (yb, yp) = (bc.eval(x), pc.eval(x)); + serde_json::json!({"x": x, "y": (yb + (yp - yb) * t).clamp(0.0, 1.0)}) + }) + .collect(); + Value::Array(points) +} + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Preset { pub id: String, @@ -285,6 +355,11 @@ impl Preset { /// settings (see [`Preset::apply_on`]): right for the import default preset and for scratch /// bases. Masks in the preset are added to the photo's own (ones it already has are skipped), /// their effect scaled by the amount. + /// + /// This knows nothing about the photo's source. A preset that names only one white balance + /// number needs the photo prepared against its as-shot white first, and the result put back on + /// the scale the photo is edited on: callers on a real photo go through the engine's + /// `apply_preset_to_photo`, which does that. pub fn apply(&self, s: &DevelopSettings, amount: f64) -> DevelopSettings { self.apply_on(s, s, amount) } @@ -295,8 +370,15 @@ impl Preset { /// the photo's pixel repairs (masks, spots, red eye), which the preset patches; masks in the /// preset are added to the photo's own (ones it already has are skipped), their effect scaled /// by the amount. A second preset therefore restores what the first one changed in the - /// settings it names (issue #2159), and nothing it leaves out. + /// settings it names (issue #2159), and nothing it leaves out. At 0 % (or less) the settings it + /// names take `original`'s values, so with `current` as the original nothing changes, and its + /// masks are not added (a mask at no strength would only block applying the preset later); a + /// NaN `amount` changes nothing. pub fn apply_on(&self, current: &DevelopSettings, original: &DevelopSettings, amount: f64) -> DevelopSettings { + if amount.is_nan() { + return current.clone(); + } + let amount = amount.max(0.0); let Some(masks) = self.settings.get("masks").and_then(Value::as_array).filter(|m| !m.is_empty()) else { return compose_named(current, original, &self.settings, amount); }; @@ -305,7 +387,9 @@ impl Preset { o.remove("masks"); } let mut out = compose_named(current, original, &rest, amount); - add_masks(&mut out, masks, amount); + if amount > 0.0 { + add_masks(&mut out, masks, amount); + } out } } @@ -391,6 +475,250 @@ mod tests { } } + fn pts(v: &[(f64, f64)]) -> Vec { + v.iter().map(|&(x, y)| lightcraft_geom::Point::new(x, y)).collect() + } + + fn eval(c: &[lightcraft_geom::Point], x: f64) -> f64 { + lightcraft_color::spline::MonotoneCurve::new(&c.iter().map(|p| (p.x, p.y)).collect::>()).eval(x) + } + + fn preset(settings: Value) -> Preset { + Preset { id: "p".into(), name: "P".into(), group: "G".into(), settings, favorite: false, builtin: false } + } + + /// Issue #2669: a preset's tone curve did nothing below 50 % and all of it from 50 % up. + #[test] + fn amount_blends_point_curves() { + let curve = [(0.0, 0.0), (0.25, 0.15), (0.75, 0.85), (1.0, 1.0)]; + let partial = json!({"curve": {"master": pts(&curve)}}); + let base = DevelopSettings::default(); + let mut last = 0.25; + for i in 1..=10 { + let t = f64::from(i) / 10.0; + let out = apply_partial(&base, &partial, t); + let y = eval(&out.curve.master, 0.25); + assert!((y - (0.25 - 0.10 * t)).abs() < 1e-9, "{t}: y(0.25) = {y}"); + assert!(y < last + 1e-12, "{t}: the curve moves steadily towards the preset's"); + last = y; + } + assert!(apply_partial(&base, &partial, 0.0).curve.master.is_empty(), "0 % keeps the photo's curve"); + // 200 % goes twice as far, kept in 0..1 + let more = apply_partial(&base, &partial, 2.0); + assert!((eval(&more.curve.master, 0.25) - 0.05).abs() < 1e-9); + assert!(more.curve.master.iter().all(|p| (0.0..=1.0).contains(&p.y))); + + // a photo whose original has its own curves (other points): at every control point of either + // curve the result is the blend of the original's curve and the preset's as rendered, whatever + // the photo's current curve is + let mut original = DevelopSettings::default(); + original.curve.master = pts(&[(0.0, 0.05), (0.5, 0.6), (1.0, 0.95)]); + original.curve.red = pts(&[(0.0, 0.0), (0.4, 0.5), (1.0, 1.0)]); + let mut current = DevelopSettings::default(); + current.curve.master = pts(&[(0.0, 0.2), (1.0, 0.8)]); + let p = preset(json!({"curve": {"master": pts(&curve), "red": []}})); + let out = p.apply_on(¤t, &original, 0.4); + for x in [0.0, 0.25, 0.5, 0.75, 1.0] { + let want = eval(&original.curve.master, x) * 0.6 + eval(&pts(&curve), x) * 0.4; + assert!((eval(&out.curve.master, x) - want).abs() < 1e-9, "x {x}"); + } + // towards the identity (an empty curve) too + assert!((eval(&out.curve.red, 0.4) - (0.5 * 0.6 + 0.4 * 0.4)).abs() < 1e-9); + } + + /// The profile (and LUT) choice steps to the preset's at half amount, as every choice does + /// (#2207); from there its strength fades in from 0 %, so the look shows in proportion to the + /// amount. The same profile blends its amount from the original's, not the photo's current one. + #[test] + fn amount_fades_in_a_new_profile() { + let p = preset(json!({"profile": {"id": "lc.vivid", "amount": 150.0}})); + let base = DevelopSettings::default(); + for (t, id, amount) in [(0.3, "lc.color", 100.0), (0.5, "lc.vivid", 75.0), (0.8, "lc.vivid", 120.0), (1.0, "lc.vivid", 150.0)] { + let out = p.apply_on(&base, &base, t); + assert_eq!(out.profile.id, id, "{t}"); + assert!((out.profile.amount - amount).abs() < 1e-9, "{t}: amount {}", out.profile.amount); + } + assert_eq!(p.apply_on(&base, &base, 0.0), base, "0 % changes nothing"); + // the same profile: its amount blends from the original's (60 → 150 at 50 % is 105), not + // from the photo's current 20 + let mut original = DevelopSettings::default(); + original.profile.id = "lc.vivid".into(); + original.profile.amount = 60.0; + let mut current = original.clone(); + current.profile.amount = 20.0; + for t in [0.3, 0.5] { + let out = p.apply_on(¤t, &original, t); + assert_eq!(out.profile.id, "lc.vivid"); + assert!((out.profile.amount - (60.0 + 90.0 * t)).abs() < 1e-9, "{t}: {}", out.profile.amount); + } + } + + /// Switches and choices keep the original's value below half amount and take the preset's from + /// half amount up; an `enabled` switch or a style the preset changes brings its amount in from 0 + /// there, and below half amount leaves the original's amount as it is. + #[test] + fn amount_steps_switches_and_choices_at_half_and_fades_in_their_amount() { + let mut original = DevelopSettings::default(); + original.lens_blur.amount = 50.0; + original.optics.lens_profile = true; + let style = serde_json::to_value(crate::VignetteStyle::ColorPriority).unwrap(); + let p = preset(json!({ + "lens_blur": {"enabled": true, "amount": 80.0}, + "treatment": "bw", + "optics": {"lens_profile": false}, + "vignette": {"style": style, "amount": -40.0}, + })); + let mut current = original.clone(); + current.light.exposure = 1.0; + let low = p.apply_on(¤t, &original, 0.25); + assert!(!low.lens_blur.enabled); + assert_eq!(low.lens_blur.amount, 50.0, "below half the original's own amount"); + assert_eq!(low.treatment, original.treatment); + assert!(low.optics.lens_profile); + assert_eq!((low.vignette.style, low.vignette.amount), (original.vignette.style, original.vignette.amount)); + assert_eq!(low.light.exposure, 1.0, "a setting the preset doesn't name keeps the photo's value"); + let half = p.apply_on(¤t, &original, 0.5); + assert!(half.lens_blur.enabled); + assert!((half.lens_blur.amount - 40.0).abs() < 1e-9, "{}", half.lens_blur.amount); + assert_eq!(half.treatment, crate::Treatment::Bw); + assert!(!half.optics.lens_profile); + assert_eq!(half.vignette.style, crate::VignetteStyle::ColorPriority); + assert!((half.vignette.amount + 20.0).abs() < 1e-9, "{}", half.vignette.amount); + assert_eq!(p.apply_on(¤t, &original, 0.0), current, "0 % changes nothing"); + } + + /// HDR is left out of the JSON while at its defaults; its numbers still blend from the original's. + #[test] + fn amount_blends_groups_left_out_at_their_defaults() { + let p = preset(json!({"hdr": {"enabled": true, "sdr_contrast": 40.0}})); + let base = DevelopSettings::default(); + let out = p.apply_on(&base, &base, 0.5); + assert!(out.hdr.enabled); + assert!((out.hdr.sdr_contrast - 20.0).abs() < 1e-9, "{}", out.hdr.sdr_contrast); + let out = apply_partial(&base, &p.settings, 0.3); + assert!(!out.hdr.enabled); + assert!((out.hdr.sdr_contrast - 12.0).abs() < 1e-9, "{}", out.hdr.sdr_contrast); + } + + /// White balance on another scale (Kelvin against the older relative one) is in other units: + /// the original's below half amount and the preset's from half amount up, each whole with its + /// scale, never a blend of the two. + #[test] + fn amount_takes_white_balance_on_another_scale_whole() { + let kelvin = preset(json!({"wb": {"mode": "custom", "temp": 4200.0, "tint": 8.0, "scale": "kelvin"}})); + let photo = DevelopSettings::default(); // relative scale, 6500 / 0 = as shot + for t in [0.01, 0.3, 0.49] { + assert_eq!(kelvin.apply_on(&photo, &photo, t).wb, photo.wb, "{t}"); + } + for t in [0.5, 0.7, 1.5] { + let out = kelvin.apply_on(&photo, &photo, t); + assert_eq!((out.wb.scale, out.wb.temp, out.wb.tint), (crate::WbScale::Kelvin, 4200.0, 8.0), "{t}"); + } + let wb = crate::WhiteBalance { mode: crate::WbMode::Custom, temp: 5000.0, tint: 0.0, scale: crate::WbScale::Kelvin }; + let photo = DevelopSettings { wb, ..DevelopSettings::default() }; + // a partial without a scale is on the relative scale + let relative = preset(json!({"wb": {"temp": 7000.0, "tint": 10.0}})); + assert_eq!(relative.apply_on(&photo, &photo, 0.3).wb, photo.wb); + let out = relative.apply_on(&photo, &photo, 0.6); + assert_eq!((out.wb.scale, out.wb.temp, out.wb.tint), (crate::WbScale::Legacy, 7000.0, 10.0)); + // the same scale blends + let out = kelvin.apply_on(&photo, &photo, 0.5); + assert_eq!((out.wb.scale, out.wb.temp, out.wb.tint), (crate::WbScale::Kelvin, 4600.0, 4.0)); + } + + #[test] + fn zero_amount_mask_preset_leaves_settings_unchanged_and_can_be_applied_later() { + let photo = DevelopSettings { masks: vec![crate::Mask { id: 9, name: "Existing".into(), ..Default::default() }], ..Default::default() }; + let p = preset(json!({"light": {"exposure": 1.0}, "masks": [{"name": "New", "adjust": {"amount": 80.0}}]})); + for amount in [0.0, -0.5, f64::NAN] { + let unchanged = p.apply_on(&photo, &photo, amount); + assert_eq!(unchanged, photo); + let out = p.apply(&unchanged, 1.0); + assert_eq!(out.light.exposure, 1.0); + assert_eq!(out.masks.len(), 2); + assert_eq!(out.masks[0], photo.masks[0]); + assert_eq!(out.masks[1].name, "New"); + assert_eq!(out.masks[1].adjust.amount, 80.0); + } + // with an import state, 0 % is that state for the settings the preset names (#2207), and still + // adds no mask + let mut current = photo.clone(); + current.light.exposure = 2.0; + current.curve.master = pts(&[(0.0, 0.1), (1.0, 0.9)]); + let original = DevelopSettings { light: crate::Light { exposure: -0.5, ..Default::default() }, ..Default::default() }; + let q = + preset(json!({"light": {"exposure": 1.0}, "curve": {"master": pts(&[(0.0, 0.0), (0.5, 0.7), (1.0, 1.0)])}, "masks": [{"name": "New"}]})); + let out = q.apply_on(¤t, &original, 0.0); + assert_eq!(out.light.exposure, -0.5); + assert!(out.curve.master.is_empty(), "the original's curve, point for point"); + assert_eq!(out.masks, current.masks); + } + + /// Every leaf of `v` that is not a number (and every list's length), by path. + fn non_numbers(v: &Value, path: &str, out: &mut Vec<(String, Value)>) { + match v { + Value::Object(o) => o.iter().for_each(|(k, v)| non_numbers(v, &format!("{path}/{k}"), out)), + Value::Array(a) => { + out.push((format!("{path}#len"), Value::from(a.len()))); + a.iter().enumerate().for_each(|(i, v)| non_numbers(v, &format!("{path}/{i}"), out)); + } + Value::Number(_) => {} + v => out.push((path.to_string(), v.clone())), + } + } + + /// Across the whole Amount range a preset has one step, at half amount (#2207): below it the + /// switches, choices and lists stay as at 1 %, from it as at 50 %; the numbers and tone curves + /// move in proportion to the amount throughout, and the strength of a changed choice fades in + /// from 0 once the choice is the preset's. + #[test] + fn amount_has_one_step_at_half_and_blends_the_rest() { + let mut a = DevelopSettings::default(); + a.profile.id = "lc.vivid".into(); + a.profile.amount = 140.0; + a.treatment = crate::Treatment::Bw; + a.light.exposure = 0.8; + a.curve.master = pts(&[(0.0, 0.0), (0.3, 0.2), (0.7, 0.8), (1.0, 1.0)]); + a.curve.green = pts(&[(0.0, 0.05), (1.0, 0.9)]); + a.grain.amount = 30.0; + a.grain.seed = 777; + a.vignette.style = crate::VignetteStyle::ColorPriority; + a.vignette.amount = -25.0; + a.lens_blur = crate::LensBlur { enabled: true, amount: 60.0, focal_distance: 30.0, focal_range: 20.0, ..Default::default() }; + a.optics.remove_ca = true; + let p = Preset::from_settings("p", "P", "User", &a, &SettingsGroup::default_copy()); + let mut original = DevelopSettings::default(); + original.curve.master = pts(&[(0.0, 0.1), (0.5, 0.45), (1.0, 1.0)]); + original.light.exposure = -0.4; + let mut current = original.clone(); + current.light.exposure = 2.0; + let leaves = |t: f64| { + let mut v = Vec::new(); + non_numbers(&p.apply_on(¤t, &original, t).to_json(), "", &mut v); + v + }; + let (below, above) = (leaves(0.01), leaves(0.5)); + assert_ne!(below, above, "the choices step at half amount"); + let y0 = eval(&original.curve.master, 0.3); + for i in 2..=200 { + let t = f64::from(i) / 100.0; + let out = p.apply_on(¤t, &original, t); + if i != 100 { + // (at exactly 100 % the preset is merged as it is: its own curve points) + assert_eq!(leaves(t), if t < 0.5 { below.clone() } else { above.clone() }, "{t}: a switch, choice or list moved off its side"); + } + let want = (-0.4 + 1.2 * t).min(5.0); + assert!((out.light.exposure - want).abs() < 1e-9, "{t}: exposure {}", out.light.exposure); + let (profile, blur) = + if t < 0.5 { (original.profile.amount, original.lens_blur.amount) } else { ((140.0 * t).min(200.0), (60.0 * t).min(100.0)) }; + assert!((out.profile.amount - profile).abs() < 1e-9, "{t}: profile amount {}", out.profile.amount); + assert!((out.lens_blur.amount - blur).abs() < 1e-9, "{t}: lens blur amount {}", out.lens_blur.amount); + let y = eval(&out.curve.master, 0.3); + let want = (y0 + (0.2 - y0) * t).clamp(0.0, 1.0); + assert!((y - want).abs() < 1e-9, "{t}: curve y(0.3) {y}, want {want}"); + } + } + /// A preset changes only the settings it names: a setting in a group it styles but does not /// name keeps the photo's value, and so does a whole group it leaves out. #[test] diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 9897c422cf..d9da971191 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -48,18 +48,18 @@ harfrust = { version = "0.13", default-features = false, features = ["std"] } unicode-normalization = "0.1" unicode-segmentation = "1.13" lightcraft-segment = { workspace = true, optional = true } +chrono = { workspace = true } # model downloads run natively only (the web build fetches no models) [target.'cfg(not(target_arch = "wasm32"))'.dependencies] lightcraft-fetch = { workspace = true } -# capture-time parsing for face recognition (native only) -chrono = { workspace = true } +jiff = { workspace = true } # free space of the drive holding the preview cache (the low-disk alert; pure Rust: rustix / windows-sys) fs4 = { workspace = true } [features] # AI masks with SAM 3 (Object / Describe). Off for the web and CLI builds. -sam = ["dep:lightcraft-segment"] +sam = ["dep:lightcraft-segment", "lightcraft-gpu/sam"] denoise = ["dep:lightcraft-denoise", "lightcraft-denoise/runtime", "lightcraft-gpu/denoise"] rawnind-model = ["denoise", "lightcraft-denoise/rawnind-model", "lightcraft-denoise-core/rawnind-model"] diff --git a/crates/engine/examples/upright_eval.rs b/crates/engine/examples/upright_eval.rs new file mode 100644 index 0000000000..6c2ae565aa --- /dev/null +++ b/crates/engine/examples/upright_eval.rs @@ -0,0 +1,81 @@ +//! Upright on real photos (a developer tool, not part of the app): imports each photo of a manifest into an +//! in-memory library, applies its lens settings, runs Upright the way the app does and writes one JSON line per +//! photo (the transform each mode finds and why a mode found nothing). With `--planes DIR` it also saves the +//! analysis plane of each photo at 2048 px (`.lum`: u32 width, u32 height, f32 samples, little endian), so +//! the detector can be tuned on them without decoding raws again (`lightcraft-pipeline` example +//! `upright_planes`). +//! +//! `cargo run --release -p lightcraft-engine --example upright_eval -- [--planes DIR]` +//! +//! The manifest is a JSON array of `{key, local, optics?, orientation?}` (`local`: a copy of the photo; nothing +//! is written next to it). Ground truth and scoring live outside the repository. +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::io::Write; + +use lightcraft_engine::Session; +use lightcraft_engine::catalog::PhotoId; +use lightcraft_engine::media::SourceLevel; +use serde_json::{Value, json}; + +fn main() { + let args: Vec = std::env::args().skip(1).collect(); + let manifest: Vec = serde_json::from_str(&std::fs::read_to_string(&args[0]).unwrap()).unwrap(); + let mut out = std::fs::File::create(&args[1]).unwrap(); + let planes = args.iter().position(|a| a == "--planes").map(|i| std::path::PathBuf::from(&args[i + 1])); + if let Some(p) = &planes { + std::fs::create_dir_all(p).unwrap(); + } + for m in &manifest { + // a fresh in-memory library per photo, so a few hundred raws fit + let mut s = Session::new().with_fs(); + let key = m["key"].as_str().unwrap().to_string(); + let local = m["local"].as_str().unwrap(); + let r = match s.execute("library.import", &json!({"paths": [local]})) { + Ok(r) => r, + Err(e) => { + eprintln!("{key}: {e}"); + continue; + } + }; + let Some(id) = r["imported"][0].as_u64() else { + eprintln!("{key}: not imported"); + continue; + }; + s.execute("library.select", &json!({"ids": [id], "active": id})).unwrap(); + let mut partial = serde_json::Map::new(); + for k in ["optics", "orientation"] { + if let Some(v) = m.get(k).filter(|v| !v.is_null()) { + partial.insert(k.into(), v.clone()); + } + } + if !partial.is_empty() + && let Err(e) = s.execute("develop.merge", &json!({"settings": partial})) + { + eprintln!("{key}: lens settings: {e}"); + } + let mut line = json!({"key": key}); + for mode in ["vertical", "auto", "full", "level"] { + match s.execute("geometry.upright", &json!({"mode": mode})) { + Ok(r) => line[mode] = json!({"transform": r["transform"], "note": r["note"]}), + Err(e) => line[mode] = json!({"error": e.to_string()}), + } + } + if let Some(dir) = &planes { + let d = s.develop_of(PhotoId(id)).unwrap_or_default(); + let src = s.source_now(PhotoId(id), SourceLevel::Preview).unwrap(); + let info = s.source_info(PhotoId(id)); + let lum = lightcraft_pipeline::upright::analysis_luminance(&src, &info, &d, 2048); + let mut bytes = Vec::with_capacity(8 + lum.data.len() * 4); + bytes.extend_from_slice(&(lum.width as u32).to_le_bytes()); + bytes.extend_from_slice(&(lum.height as u32).to_le_bytes()); + for v in &lum.data { + bytes.extend_from_slice(&v.to_le_bytes()); + } + std::fs::write(dir.join(format!("{key}.lum")), bytes).unwrap(); + line["source"] = json!([src.width, src.height]); + } + writeln!(out, "{line}").unwrap(); + eprintln!("{key} done"); + } +} diff --git a/crates/engine/src/activity.rs b/crates/engine/src/activity.rs index 147d20f3a5..c6b6065b44 100644 --- a/crates/engine/src/activity.rs +++ b/crates/engine/src/activity.rs @@ -7,14 +7,80 @@ //! check between files or photos: the guard adopts it ([`Cancel::Flag`]), so the stack's ✕, `activity.cancel` and the //! job's own Cancel all set the same atomic. Numbers are worded by the frontend from `done`, `total` and [`Unit`]; a //! detail set here is a name (a file, a model), never a sentence, so the frontend can translate everything else. +//! +//! Jobs that must not run side by side share a [`Lane`]. One asked for while its lane is busy can wait in line +//! ([`Activity::enqueue`]): it keeps what it was asked ([`Request`], the command and its parameters) and runs it +//! when the jobs ahead of it are over ([`crate::Session::start_waiting`]), planning its work then, not when it was +//! asked. Nothing waits across another library: the files may have changed meanwhile. use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering}; use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; use serde::Serialize; +use serde_json::Value; /// The longest label or detail kept, in characters (a file name can be anything). const MAX_TEXT: usize = 200; +/// The most tasks waiting in line, in all lanes. +pub const MAX_WAITING: usize = 100; + +/// Jobs that must not run side by side: one waits for those ahead of it to end. Kinds without a lane run as they +/// always did (and are refused while one of their kind runs, where that is the rule). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub enum Lane { + /// Build Previews and Build / Discard Smart Previews: one preview build at a time (`Session::preview_build`). + Previews, +} + +impl Lane { + /// The lane of tasks of `kind` ([`TaskInfo::kind`]). + pub fn of(kind: &str) -> Option { + match kind { + "previews" | "smartPreviews" => Some(Lane::Previews), + _ => None, + } + } +} + +/// What a job was asked: the command and its parameters, with everything that depends on the moment (the +/// selection, the photos in view) written out, so that running it later does the same work. +#[derive(Clone, Debug, PartialEq)] +pub struct Request { + pub command: String, + pub params: Value, +} + +/// A task waiting in line ([`Activity::enqueue`]), as [`Activity::take_ready`] hands it over to be started. +#[derive(Debug)] +pub struct Waiting { + pub id: u64, + pub kind: &'static str, + pub label: String, + pub lane: Lane, + pub request: Request, + queued: web_time::Instant, +} + +impl Waiting { + fn info(&self, place: usize) -> TaskInfo { + TaskInfo { + id: self.id, + kind: self.kind, + label: self.label.clone(), + done: 0, + total: 0, + unit: Unit::Count, + detail: String::new(), + cancellable: true, + cancelling: false, + age_ms: millis(self.queued.elapsed()), + waiting: true, + place, + lane: Some(self.lane), + } + } +} /// The background tasks in flight. Cheap to clone (one `Arc`), so worker threads can hold it. #[derive(Clone, Default)] @@ -26,6 +92,10 @@ pub struct Activity { struct Inner { /// Oldest first. tasks: Mutex>>, + /// The tasks waiting in line, in the order they were asked for. + waiting: Mutex>, + /// The id the waiting task being started keeps (its kind, its id): see [`Activity::take_ready`]. + reserved: Mutex>, next: AtomicU64, } @@ -73,7 +143,7 @@ impl Unit { pub struct TaskInfo { pub id: u64, /// A stable id: `import`, `export`, `scan`, `previews`, `smartPreviews`, `lightroom`, `merge`, `download`, - /// `faces`, `denoise`, `findMissing`, `applePhotos`, `cache`, `focus`. + /// `faces`, `facesGpu`, `denoise`, `findMissing`, `applePhotos`, `cache`, `focus`, `geocode`, `move`, `sync`, `recheck`, `reload`. pub kind: &'static str, /// English; the frontend translates it. pub label: String, @@ -87,6 +157,11 @@ pub struct TaskInfo { /// Cancel was asked for; the job stops at its next check. pub cancelling: bool, pub age_ms: u64, + /// It waits in line for the tasks ahead of it in its lane (nothing done yet: `done` and `total` are 0). + pub waiting: bool, + /// Its place in its lane's line, from 1; 0 for a running task. + pub place: usize, + pub lane: Option, } struct Entry { @@ -162,7 +237,10 @@ impl Entry { detail: lock(&self.detail).clone(), cancellable: self.is_cancellable(), cancelling: self.is_cancelled(), - age_ms: u64::try_from(self.started.elapsed().as_millis()).unwrap_or(u64::MAX), + age_ms: millis(self.started.elapsed()), + waiting: false, + place: 0, + lane: Lane::of(self.kind), } } } @@ -171,7 +249,9 @@ impl Activity { /// Register a task; it is listed until the returned guard is dropped. `label` is English (the frontend /// translates it). pub fn start(&self, kind: &'static str, label: &str, cancel: Cancel) -> TaskGuard { - let id = self.inner.next.fetch_add(1, Ordering::Relaxed).saturating_add(1); + // a task that waited in line keeps the id it had there + let reserved = lock(&self.inner.reserved).take_if(|(k, _)| *k == kind).map(|(_, id)| id); + let id = reserved.unwrap_or_else(|| self.inner.next.fetch_add(1, Ordering::Relaxed).saturating_add(1)); let cancel = match cancel { Cancel::No => None, Cancel::Yes => Some(Arc::new(AtomicBool::new(false))), @@ -194,29 +274,136 @@ impl Activity { TaskGuard { activity: self.clone(), entry } } - /// Every task in flight, oldest first. + /// Every task in flight, oldest first, then those waiting in line, in the order they were asked for. pub fn list(&self) -> Vec { - lock(&self.inner.tasks).iter().map(|e| e.info()).collect() + let mut rows: Vec = lock(&self.inner.tasks).iter().map(|e| e.info()).collect(); + rows.extend(self.waiting()); + rows } - /// Ask task `id` to stop (it stops at its next check). An unknown id (the task may have just ended) or a task - /// that can't be cancelled is an error. + /// The tasks waiting in line, in the order they were asked for, each with its place in its lane. + pub fn waiting(&self) -> Vec { + let waiting = lock(&self.inner.waiting); + let mut ahead: Vec<(Lane, usize)> = Vec::new(); + waiting + .iter() + .map(|w| { + let place = match ahead.iter_mut().find(|(lane, _)| *lane == w.lane) { + Some((_, n)) => { + *n += 1; + *n + } + None => { + ahead.push((w.lane, 1)); + 1 + } + }; + w.info(place) + }) + .collect() + } + + /// Ask task `id` to stop (it stops at its next check), or take it out of the line if it waits. An unknown id + /// (the task may have just ended) or a task that can't be cancelled is an error. pub fn cancel(&self, id: u64) -> Result<(), String> { + { + let mut waiting = lock(&self.inner.waiting); + if let Some(at) = waiting.iter().position(|w| w.id == id) { + waiting.remove(at); + return Ok(()); + } + } let tasks = lock(&self.inner.tasks); let entry = tasks.iter().find(|e| e.id == id).ok_or_else(|| format!("no task {id}"))?; if entry.try_cancel() { Ok(()) } else { Err(format!("{} can't be cancelled", entry.label)) } } - /// Ask every cancellable task to stop; returns how many were asked. + /// Ask every cancellable task to stop, and empty the line (what waits would start as soon as they stopped); + /// returns how many were asked or taken out. pub fn cancel_all(&self) -> usize { + let dropped = std::mem::take(&mut *lock(&self.inner.waiting)).len(); let tasks = lock(&self.inner.tasks); - tasks.iter().filter(|e| e.try_cancel()).count() + dropped + tasks.iter().filter(|e| e.try_cancel()).count() + } + + /// Whether a task of one of `kinds` is in flight. Its guard's lifetime is the answer: a task that + /// ends, fails or panics stops counting. + pub fn any_of(&self, kinds: &[&str]) -> bool { + lock(&self.inner.tasks).iter().any(|e| kinds.contains(&e.kind)) } /// Tasks that quitting would cut short: cancellable ones not already stopping. pub fn running_cancellable(&self) -> Vec { lock(&self.inner.tasks).iter().filter(|e| e.is_cancellable() && !e.is_cancelled()).map(|e| e.info()).collect() } + + /// Put a task of `kind` in line behind the others of its lane; it runs `request` when its turn comes. Returns + /// its id and its place in the line. A kind without a lane, or a line already [`MAX_WAITING`] long, is an error. + pub fn enqueue(&self, kind: &'static str, label: &str, request: Request) -> Result<(u64, usize), String> { + let lane = Lane::of(kind).ok_or_else(|| format!("{kind} tasks don't wait in line"))?; + let mut waiting = lock(&self.inner.waiting); + if waiting.len() >= MAX_WAITING { + return Err(format!("{MAX_WAITING} tasks are waiting already")); + } + let id = self.inner.next.fetch_add(1, Ordering::Relaxed).saturating_add(1); + waiting.push(Waiting { id, kind, label: capped(label), lane, request, queued: web_time::Instant::now() }); + let place = waiting.iter().filter(|w| w.lane == lane).count(); + Ok((id, place)) + } + + /// Whether a task of `lane` runs now. + pub fn lane_busy(&self, lane: Lane) -> bool { + lock(&self.inner.tasks).iter().any(|e| Lane::of(e.kind) == Some(lane)) + } + + /// Whether a task waits in `lane`'s line. + pub fn lane_waiting(&self, lane: Lane) -> bool { + lock(&self.inner.waiting).iter().any(|w| w.lane == lane) + } + + /// Take the first waiting task whose lane is free out of the line, to be started now. The next task of its + /// kind started ([`Activity::start`]) keeps its id, until [`Activity::started`] says the attempt is over. + pub fn take_ready(&self) -> Option { + self.take_ready_if(|_| true) + } + + /// [`Activity::take_ready`] among the tasks whose request `runs` can run: each frontend starts what it knows how to + /// (the engine its commands, the app its own). Only the first in each lane's line is looked at: one the caller + /// can't run holds its lane, as it would if it had started. + pub fn take_ready_if(&self, runs: impl Fn(&Request) -> bool) -> Option { + let mut waiting = lock(&self.inner.waiting); + let mut held: Vec = lock(&self.inner.tasks).iter().filter_map(|e| Lane::of(e.kind)).collect(); + let mut at = None; + for (i, w) in waiting.iter().enumerate() { + if held.contains(&w.lane) { + continue; + } + if runs(&w.request) { + at = Some(i); + break; + } + held.push(w.lane); + } + let w = waiting.remove(at?); + *lock(&self.inner.reserved) = Some((w.kind, w.id)); + Some(w) + } + + /// The attempt to start the task [`Activity::take_ready`] handed over is over (it started, or it could not). + pub fn started(&self) { + *lock(&self.inner.reserved) = None; + } + + /// Another library was opened: what waited in line was about the old one's photos and folders, so the line + /// empties. Returns how many tasks waited. + pub fn library_changed(&self) -> usize { + std::mem::take(&mut *lock(&self.inner.waiting)).len() + } +} + +/// Milliseconds, saturating. +fn millis(d: std::time::Duration) -> u64 { + u64::try_from(d.as_millis()).unwrap_or(u64::MAX) } /// A task's place in the list, held by whoever owns the job; dropping it removes the row. @@ -398,6 +585,26 @@ mod tests { assert_eq!(a.list().len(), 1); } + #[test] + fn any_of_asks_for_the_kinds_in_flight_and_a_dropped_guard_stops_counting() { + let a = Activity::default(); + assert!(!a.any_of(&["scan", "import"])); + let scan = a.start("scan", "Reading photos", Cancel::No); + let other = a.start("export", "Exporting", Cancel::No); + assert!(a.any_of(&["scan", "import"]) && a.any_of(&["export"]) && !a.any_of(&["import", "sync"])); + drop(scan); + assert!(!a.any_of(&["scan", "import"]), "the guard's lifetime is the answer"); + // a task whose thread panics lets go as well + let a2 = a.clone(); + let _ = std::thread::spawn(move || { + let _held = a2.start("import", "Importing", Cancel::No); + panic!("synthetic panic in an import"); + }) + .join(); + assert!(!a.any_of(&["import"])); + drop(other); + } + /// Codex review of #643: a worker that turns cancelling off and then reads the cancel flag /// (an export handing its files to Apple Photos) must either see a cancel that was accepted or /// make it fail, never let one be accepted and then ignored. Here the test holds the task's gate @@ -435,4 +642,93 @@ mod tests { std::thread::spawn(move || h.progress(3, 7)).join().unwrap(); assert_eq!((a.list()[0].done, a.list()[0].total), (3, 7)); } + + fn request(command: &str) -> Request { + Request { command: command.into(), params: serde_json::json!({}) } + } + + #[test] + fn a_task_of_a_kind_without_a_lane_does_not_wait() { + let a = Activity::default(); + let e = a.enqueue("export", "Exporting", request("x")).unwrap_err(); + assert!(e.contains("export"), "{e}"); + assert!(a.list().is_empty()); + } + + #[test] + fn the_line_is_bounded_and_lists_places_per_lane() { + let a = Activity::default(); + for place in 1..=MAX_WAITING { + assert_eq!(a.enqueue("previews", "P", request("x")).unwrap().1, place); + } + assert!(a.enqueue("smartPreviews", "S", request("x")).unwrap_err().contains("100")); + let rows = a.list(); + assert_eq!(rows.len(), MAX_WAITING); + assert!(rows.iter().all(|r| r.waiting && r.lane == Some(Lane::Previews))); + assert_eq!(rows.iter().map(|r| r.place).collect::>(), (1..=MAX_WAITING).collect::>()); + } + + #[test] + fn a_waiting_task_starts_when_its_lane_is_free_and_keeps_its_id() { + let a = Activity::default(); + let ahead = a.start("previews", "P", Cancel::Yes); + let (id, _) = a.enqueue("smartPreviews", "S", request("smart")).unwrap(); + assert!(a.lane_busy(Lane::Previews) && a.lane_waiting(Lane::Previews)); + assert!(a.take_ready().is_none(), "the lane is busy: one preview build at a time"); + drop(ahead); + assert!(!a.lane_busy(Lane::Previews)); + let w = a.take_ready().expect("the lane is free"); + assert_eq!((w.id, w.request.command.as_str()), (id, "smart")); + assert!(!a.lane_waiting(Lane::Previews)); + let g = a.start("smartPreviews", "S", Cancel::Yes); + a.started(); + assert_eq!(g.id(), id, "it keeps the id it had in line"); + assert!(!a.list()[0].waiting); + assert_ne!(a.start("export", "E", Cancel::Yes).id(), id); + } + + #[test] + fn an_attempt_that_did_not_start_a_task_gives_its_id_up() { + let a = Activity::default(); + let (id, _) = a.enqueue("previews", "P", request("x")).unwrap(); + let w = a.take_ready().unwrap(); + assert_eq!(w.id, id); + a.started(); // the command failed before starting anything + assert_ne!(a.start("previews", "P", Cancel::Yes).id(), id, "a later task of the kind doesn't take it"); + } + + #[test] + fn take_ready_if_skips_what_the_caller_cannot_run_but_keeps_its_lane_held() { + let a = Activity::default(); + a.enqueue("previews", "mine", request("engine")).unwrap(); + a.enqueue("previews", "next", request("engine")).unwrap(); + assert!(a.take_ready_if(|r| r.command == "other").is_none(), "the first in the lane isn't ours: it holds the lane"); + assert_eq!(a.take_ready_if(|_| true).map(|w| w.label), Some("mine".to_string())); + } + + #[test] + fn cancelling_a_waiting_task_removes_it_and_cancel_all_empties_the_line() { + let a = Activity::default(); + let _running = a.start("previews", "P", Cancel::Yes); + let (first, _) = a.enqueue("previews", "A", request("x")).unwrap(); + a.enqueue("previews", "B", request("x")).unwrap(); + a.enqueue("smartPreviews", "C", request("x")).unwrap(); + a.cancel(first).unwrap(); + assert!(a.cancel(first).is_err()); + assert_eq!(a.waiting().iter().map(|t| (t.label.as_str(), t.place)).collect::>(), vec![("B", 1), ("C", 2)]); + assert_eq!(a.cancel_all(), 3, "the running one and the two that waited"); + assert!(a.waiting().is_empty() && !a.lane_waiting(Lane::Previews)); + } + + #[test] + fn a_library_change_empties_the_line() { + let a = Activity::default(); + let running = a.start("previews", "P", Cancel::Yes); + a.enqueue("previews", "A", request("x")).unwrap(); + a.enqueue("smartPreviews", "B", request("x")).unwrap(); + assert_eq!(a.library_changed(), 2); + assert_eq!(a.list().len(), 1, "what runs goes on"); + drop(running); + assert!(a.take_ready().is_none()); + } } diff --git a/crates/engine/src/camera_preview.rs b/crates/engine/src/camera_preview.rs index d0ffe33fa7..9847c70018 100644 --- a/crates/engine/src/camera_preview.rs +++ b/crates/engine/src/camera_preview.rs @@ -36,8 +36,8 @@ use hue_sat::{MIN_LUMINANCE_KEPT, NO_LUMINANCE_KEPT, fit_hue_sat, hue_saturation pub(crate) use look_fit::fit_preview; #[cfg(test)] use look_fit::{ - FIT_PREVIEW_MAX_PIXELS, SENSOR_CLIP, at_most, clips_more, correct_vignetting, fit_look, fit_look_with, sony_dro_off_tone, with_dro_off_tone, - without_clipped, + FIT_PREVIEW_MAX_PIXELS, ProxyFrame, SENSOR_CLIP, at_most, camera_vignetting_amount, clips_more, correct_vignetting, fit_dng_tone, fit_look, + fit_look_with, sony_dro_off_tone, vignetting_gains, with_dro_off_tone, with_pooled_tone, with_profile_colour, without_clipped, }; #[cfg(test)] use mono::{fit_dark_tone, fit_tone_only, monochrome, monochrome_look, to_prophoto}; @@ -50,9 +50,10 @@ use pairs::{ pub(crate) use proxy::LensGeometry; #[cfg(test)] use proxy::{ - Cr3Framing, MIN_PREVIEW_FRACTION, alignment, estimate_cr3_framing, into_lens_geometry, proxies, reference_at, sensor_proxy, structure_agrees, + Cr3Framing, MIN_PREVIEW_FRACTION, THIN_TOLERANCE, alignment, estimate_cr3_framing, extend_tone, into_lens_geometry, proxies, reference_at, + samples_from_proxies, sensor_proxy, structure_agrees, }; -pub(crate) use proxy::{fit_profile, lens_geometry, profile_pairs}; +pub(crate) use proxy::{fit_profile, fit_profile_tone, lens_geometry, profile_samples}; #[cfg(test)] use tone::{HighlightCheck, ToneFit, fit_tone, fit_tone_conditional, highlights}; @@ -86,7 +87,14 @@ use tone::{HighlightCheck, ToneFit, fit_tone, fit_tone_conditional, highlights}; /// the warped candidate's alignment leaves out the pixels outside the sensor instead of reading them as black. /// 14: bundled camera profiles also match the Nikon model spellings that differ in case, spacing or the Z8 alias, /// so previews made without the profile are rebuilt. -pub const LOOK_VERSION: u32 = 14; +/// 15: a photo no look fits keeps its camera profile's colour instead of the neutral fallback. +/// 16: a camera profile's pooled tone curve continues a photo's own past what its JPEG showed. +/// 17: only a look with the profile's colour continues along its pooled tone curve. +/// 18: continuing a photo's curve keeps it as it was where its JPEG taught it (`thinned_knots`). +/// 26: a lens database's vignetting correction reaches the sensor proxy only in the share the camera JPEG shows +/// (`camera_vignetting_amount`, ranked within chromaticity classes), not whole: JPEGs that show less of it fitted looks too +/// dark, with skewed colour. The same for a DNG's tone fit; a CR3 proxy gets the gain where its framed pixels come from. +pub const LOOK_VERSION: u32 = 26; #[derive(Clone, Debug)] pub(crate) struct CameraLook { diff --git a/crates/engine/src/camera_preview/look_fit.rs b/crates/engine/src/camera_preview/look_fit.rs index fac4e2df40..a4f63a461b 100644 --- a/crates/engine/src/camera_preview/look_fit.rs +++ b/crates/engine/src/camera_preview/look_fit.rs @@ -1,7 +1,7 @@ use super::colour::{PROXY, file_local_look}; use super::mono::{fit_tone_only_with, monochrome}; use super::pairs::{Attempt, TONE_FITS, fit_attempt, fit_partial, search_ordered}; -use super::proxy::{CLIP_TOLERANCE, LensGeometry, MIN_PREVIEW_FRACTION, proxies, structure_agrees}; +use super::proxy::{CLIP_TOLERANCE, Cr3Framing, LensGeometry, MIN_PREVIEW_FRACTION, extend_tone, framed_proxies, proxies, structure_agrees}; use super::tone::{HighlightCheck, highlights}; use super::{CameraLook, CameraTone, CameraTransform, HsvTable, Mat3, RawImage, Rgb32f, ToneMap, luminance_2020}; @@ -26,18 +26,17 @@ pub(crate) fn fit_preview( // Sony's Dynamic Range Optimizer (on by default) brightens the camera JPEG's darker regions, // not the raw: keep the colour fitted to the JPEG, take the tone curve without DRO. let dro = lightcraft_raw::embedded_preview_dynamic_range_optimized(bytes) == Some(true); - let look = match fit_look_with(&sensor, &reference, &clipped, colour.clone(), dro) { - Some(look) => look, - // A black-and-white JPEG has no colour to fit: the profile's colour and the JPEG's tone curve - // (`monochrome_look` does it without a profile). - None if colour.is_some() && black_and_white => { - let unclipped = without_clipped(&sensor, &clipped); - let bright = HighlightCheck { pairs: highlights(&sensor, &reference), dro, grey: true }; - let Some(look) = fit_tone_only_with(unclipped.as_ref().unwrap_or(&sensor), &reference, colour, &bright) else { return (None, true) }; - look - } - None => return (None, black_and_white), + let pooled = profile.as_ref().and_then(|p| p.tone); + let profile_matrix = colour.as_ref().map(|c| c.0); + let fitted = fit_look_with(&sensor, &reference, &clipped, colour.clone(), dro); + let tone_only = |colour| { + let unclipped = without_clipped(&sensor, &clipped); + let bright = HighlightCheck { pairs: highlights(&sensor, &reference), dro, grey: true }; + fit_tone_only_with(unclipped.as_ref().unwrap_or(&sensor), &reference, Some(colour), &bright) }; + let Some(look) = with_profile_colour(fitted, colour, pooled, tone_only) else { return (None, black_and_white) }; + // the camera's own curve past what this photo's JPEG showed + let look = with_pooled_tone(look, profile_matrix, pooled); let look = if dro { with_dro_off_tone(look) } else { look }; if lightcraft_pipeline::profiling() { eprintln!( @@ -52,6 +51,36 @@ pub(crate) fn fit_preview( (Some(look), black_and_white) } +/// `look` with its tone curve continued along the camera profile's `pooled` one ([`extend_tone`]), when the look +/// takes the profile's colour (`profile_matrix`). A look fitted with the photo's own matrix keeps its curve: the pooled +/// one maps luminance through the profile's matrix, which that photo's colours don't go through. +pub(super) fn with_pooled_tone(look: CameraLook, profile_matrix: Option, pooled: Option) -> CameraLook { + match (pooled, profile_matrix) { + (Some(pooled), Some(matrix)) if look.matrix == matrix => CameraLook { tone: extend_tone(&look.tone, &pooled), ..look }, + _ => look, + } +} + +/// `fitted`, the photo's own look, or when no look fits it (a black-and-white JPEG has no colour; a dark one too few +/// colour pairs) its camera profile's `colour`: with the JPEG's tone curve when [`fit_tone_only`] finds one +/// (`monochrome_look` does it without a profile), else the profile's pooled tone curve, else the default raw one. Dropping the profile there for the +/// neutral fallback left a NIKON D780 frame 3.7 EV under, pushed back up, at 37% of its properly exposed twin's chroma +/// (88-99% with the profile's colour). +pub(super) fn with_profile_colour( + fitted: Option, + colour: Option<(Mat3, Option)>, + pooled: Option, + tone_only: impl FnOnce((Mat3, Option)) -> Option, +) -> Option { + if fitted.is_some() { + return fitted; + } + let colour = colour?; + tone_only(colour.clone()).or_else(|| { + Some(CameraLook { matrix: colour.0, tone: pooled.or_else(lightcraft_pipeline::tone::default_raw_camera_tone)?, hue_sat: colour.1 }) + }) +} + /// Sensor level (normalised, white = 1) at or above which a raw channel counts as clipped, as in /// the render's highlight reconstruction. pub(super) const SENSOR_CLIP: f32 = 0.99; @@ -228,10 +257,14 @@ pub(super) fn fit_dng_tone( let gain = 2f32.powf(transform.baseline_exposure as f32); sensor.map_in_place(|p| tables.apply(p.map(|v| v / gain), gain)); } - correct_vignetting(&mut sensor, lens, raw.orientation); if (sensor.width, sensor.height) != (reference.width, reference.height) { return refuse("preview"); } + // a lens database's correction in the share the camera JPEG shows, as for the other raws (`look_proxies`) + match lens.filter(|l| l.source == lightcraft_develop::LensSource::Database).and_then(|l| l.vignette) { + Some(vignette) => database_vignetting(&mut sensor, &reference, &clipped, &vignette, ProxyFrame::new(raw.orientation)), + None => correct_vignetting(&mut sensor, lens, raw.orientation), + } if !structure_agrees(&sensor, &reference) { return refuse("structure"); } @@ -282,7 +315,183 @@ pub(super) fn look_proxies( lens: Option<&LensGeometry>, embedded: Option<&lightcraft_develop::EmbeddedLens>, ) -> Option<(Rgb32f, Rgb32f, Vec)> { - proxies(raw, bytes, transform, PROXY, 0.0, lens, embedded) + // The file's own vignetting data is what its camera applied to the JPEG. A lens database profile describes the + // lens, not what this camera did: an ILCE-7M3 JPEG with an FE 28mm F2 at f/2 (maker note: vignetting correction + // Auto) shows none of lensfun's correction relative to its raw (the A7CR's shading Auto JPEGs show no consistent + // peripheral brightening either, docs/sony-lens-corrections.md). With the whole profile on the sensor that fit + // learned corners the JPEG doesn't have: 0.062 held-out RMS instead of 0.027, a darker, orange render. So the share + // of the profile the JPEG shows is measured. (Only without a lens warp: the gain goes on the returned proxy, and a + // warped one no longer has each pixel at its source position. A warp comes from the file's own opcodes, and a file + // with its own correction never gets a database profile, `lens_profiles::for_raw`.) + let database = embedded.filter(|e| e.source == lightcraft_develop::LensSource::Database && lens.is_none()); + let Some(vignette) = database.and_then(|e| e.vignette) else { + return proxies(raw, bytes, transform, PROXY, 0.0, lens, embedded); + }; + // A CR3's framing (`estimate_cr3_framing`) is estimated here on the uncorrected sensor, not the corrected one as + // before: it compares edge directions, which a smooth vignetting gain hardly moves. On the 22 corpus CR3s with a + // database profile it came out the same both ways (21 unmoved, the R50 V at scale 0.986). + let (mut sensor, reference, clipped, framing) = framed_proxies(raw, bytes, transform, PROXY, 0.0, lens, None)?; + // CR3 proxies come back oriented like the JPEG (their framing aligned to it), the others in sensor orientation + let orientation = if raw.format == lightcraft_raw::RawFormat::Cr3 { lightcraft_geom::Orientation::Normal } else { raw.orientation }; + database_vignetting(&mut sensor, &reference, &clipped, &vignette, ProxyFrame { orientation, framing }); + Some((sensor, reference, clipped)) +} + +/// Multiply `sensor` by the share of a lens database's `vignette` correction that the camera JPEG `reference` shows +/// ([`camera_vignetting_amount`]). +fn database_vignetting( + sensor: &mut Rgb32f, + reference: &Rgb32f, + clipped: &[bool], + vignette: &lightcraft_develop::EmbeddedVignette, + frame: ProxyFrame, +) { + let amount = camera_vignetting_amount(sensor, reference, clipped, vignette, frame); + apply_vignetting(sensor, vignette, frame, amount); + if lightcraft_pipeline::profiling() { + eprintln!("[profile] camera look: the camera JPEG shows {:.0} % of the lens database's vignetting correction", amount * 100.0); + } +} + +/// Where a sensor proxy's pixels sit in the oriented, cropped frame a lens's vignetting is in: `framing` (a CR3 proxy +/// moved to its camera JPEG's framing, [`framed_proxies`]) takes each pixel to the position it shows, and +/// `orientation` maps that position to the oriented frame. +#[derive(Clone, Copy, Debug)] +pub(super) struct ProxyFrame { + pub(super) orientation: lightcraft_geom::Orientation, + pub(super) framing: Option, +} + +impl ProxyFrame { + /// A proxy whose pixels are where they were sampled, in the frame `orientation` maps to the oriented one. + pub(super) fn new(orientation: lightcraft_geom::Orientation) -> Self { + Self { orientation, framing: None } + } +} + +/// Steps between none and all of a lens database's vignetting correction that [`camera_vignetting_amount`] tries. +const VIGNETTING_STEPS: u32 = 20; + +/// Fewest usable proxy pixels [`camera_vignetting_amount`] measures on; with fewer it keeps the whole correction. +const MIN_VIGNETTING_PIXELS: usize = 256; + +/// Hue sectors of the sensor's chromaticity that [`camera_vignetting_amount`] ranks within, besides the near-neutral +/// class ([`NEUTRAL_CHROMA`]). +const HUE_SECTORS: usize = 8; + +/// Distance from grey (in `r - g`, `(r + g) / 2 - b` of the sensor's rgb chromaticity) below which a pixel counts as +/// near-neutral in [`camera_vignetting_amount`]. +const NEUTRAL_CHROMA: f64 = 0.03; + +/// Fewest pixels a chromaticity class needs to take part in [`camera_vignetting_amount`]. +const MIN_CLASS_PIXELS: usize = 32; + +/// Camera JPEG level at or above which a channel counts as clipped in [`camera_vignetting_amount`], as for the colour +/// pairs (`pairs::colour_pair`): the JPEG's brightness no longer follows the scene there, whether or not the sensor +/// clipped too ([`SENSOR_CLIP`]). +const JPEG_CLIP: f32 = 0.98; + +/// The chromaticity class of a sensor pixel in [`camera_vignetting_amount`]: 0 near-neutral, else 1 + its hue sector. +fn chromaticity_class(p: [f64; 3]) -> usize { + let p = p.map(|v| v.max(0.0)); + let sum = p[0] + p[1] + p[2]; + if sum.is_nan() || sum <= 0.0 { + return 0; + } + let [r, g, b] = p.map(|v| v / sum); + let (a, yb) = (r - g, (r + g) * 0.5 - b); + if a.hypot(yb) < NEUTRAL_CHROMA { + return 0; + } + let sector = ((yb.atan2(a) + std::f64::consts::PI) / std::f64::consts::TAU * HUE_SECTORS as f64) as usize; + 1 + sector.min(HUE_SECTORS - 1) +} + +/// The share (0..=1, as the Vignetting amount slider scales it: `1 + (gain - 1) · amount`) of `vignette` that the +/// camera JPEG `reference` shows relative to the uncorrected `sensor` proxy. The camera's tone curve is monotone, so +/// with the share the camera applied, the corrected sensor orders its pixels by brightness as the JPEG does: the +/// share with the highest rank correlation of luminance. A camera's rendering also brightens or darkens some hues +/// more than others, and where those hues gather toward the corners (a blue sky above, a darker foreground), the +/// ranks across hues would read that as vignetting: the correlation is taken within classes of similar sensor +/// chromaticity ([`chromaticity_class`]), averaged by their pixel counts. Within a class the camera's rendering is +/// taken as alike: two saturations of one hue that it renders differently, one gathered toward the corners, can still +/// read as vignetting. Pixels clipped on the sensor (`clipped`) or in the JPEG ([`JPEG_CLIP`]), black and non-finite +/// pixels are left out. Proxies of different sizes, or fewer than +/// [`MIN_VIGNETTING_PIXELS`] usable pixels, keep the whole correction. +pub(super) fn camera_vignetting_amount( + sensor: &Rgb32f, + reference: &Rgb32f, + clipped: &[bool], + vignette: &lightcraft_develop::EmbeddedVignette, + frame: ProxyFrame, +) -> f64 { + if sensor.data.len() != reference.data.len() { + return 1.0; + } + let gains = vignetting_gains(sensor, vignette, frame); + let usable = |p: &[f32; 3]| p.iter().all(|v| v.is_finite()) && luminance_2020(*p) > 0.0; + let mut classes: Vec> = vec![Vec::new(); HUE_SECTORS + 1]; + for (i, ((s, r), g)) in sensor.data.iter().zip(&reference.data).zip(gains).enumerate() { + if clipped.get(i).copied().unwrap_or(false) || !usable(s) || !usable(r) || r.iter().any(|v| *v >= JPEG_CLIP) { + continue; + } + let s = s.map(f64::from); + if let Some(class) = classes.get_mut(chromaticity_class(s)) { + class.push((g, s, r.map(f64::from))); + } + } + classes.retain(|c| c.len() >= MIN_CLASS_PIXELS); + let total: usize = classes.iter().map(Vec::len).sum(); + if total < MIN_VIGNETTING_PIXELS { + return 1.0; + } + let agreement = |amount: f64| { + let weighted: f64 = classes + .iter() + .map(|class| { + let pairs: Vec<([f64; 3], [f64; 3])> = class.iter().map(|(g, s, r)| (s.map(|v| v * (1.0 + (g - 1.0) * amount)), *r)).collect(); + super::pairs::rank_correlation_ties(&pairs) * class.len() as f64 + }) + .sum(); + weighted / total as f64 + }; + // ties keep the larger share, the correction a camera JPEG usually has (the file's own data always gets all of it) + (0..=VIGNETTING_STEPS) + .map(|s| f64::from(s) / f64::from(VIGNETTING_STEPS)) + .map(|a| (a, agreement(a))) + .fold((1.0, f64::MIN), |best, (a, r)| if r > best.1 + 1e-9 || ((r - best.1).abs() <= 1e-9 && a > best.0) { (a, r) } else { best }) + .0 +} + +/// The render's vignetting gain (`optics::embedded_vignette_gain`) at each pixel of `sensor`, at the position `frame` +/// gives it in the oriented, cropped frame `vignette` is in. +pub(super) fn vignetting_gains(sensor: &Rgb32f, vignette: &lightcraft_develop::EmbeddedVignette, frame: ProxyFrame) -> Vec { + let (w, h) = (sensor.width as f64, sensor.height as f64); + let (ow, oh) = if frame.orientation.swaps_axes() { (h, w) } else { (w, h) }; + let width = sensor.width.max(1); + (0..sensor.data.len()) + .map(|i| { + let (px, py) = ((i % width) as f64 + 0.5, (i / width) as f64 + 0.5); + let (px, py) = match frame.framing { + Some(framing) => { + let (x, y) = framing.source(px as f32, py as f32, sensor.width, sensor.height); + (f64::from(x), f64::from(y)) + } + None => (px, py), + }; + let (x, y) = frame.orientation.map(px, py, w, h); + lightcraft_pipeline::optics::embedded_vignette_gain(vignette, lightcraft_geom::Point::new(x, y), ow, oh) + }) + .collect() +} + +/// Multiply `sensor` by `amount` of `vignette`'s correction, as the Vignetting amount slider scales it. +fn apply_vignetting(sensor: &mut Rgb32f, vignette: &lightcraft_develop::EmbeddedVignette, frame: ProxyFrame, amount: f64) { + let gains = vignetting_gains(sensor, vignette, frame); + for (p, g) in sensor.data.iter_mut().zip(gains) { + let gain = (1.0 + (g - 1.0) * amount) as f32; + *p = p.map(|v| v * gain); + } } /// Multiply the sensor proxy (sensor orientation, default crop) by the embedded vignetting correction, the gain the @@ -290,12 +499,5 @@ pub(super) fn look_proxies( /// camera JPEG has it applied, so a tone fitted without it brightens the render's corners twice. pub(super) fn correct_vignetting(sensor: &mut Rgb32f, lens: Option<&lightcraft_develop::EmbeddedLens>, orientation: lightcraft_geom::Orientation) { let Some(vignette) = lens.and_then(|l| l.vignette) else { return }; - let (w, h) = (sensor.width as f64, sensor.height as f64); - let (ow, oh) = if orientation.swaps_axes() { (h, w) } else { (w, h) }; - let width = sensor.width.max(1); - for (i, p) in sensor.data.iter_mut().enumerate() { - let (x, y) = orientation.map((i % width) as f64 + 0.5, (i / width) as f64 + 0.5, w, h); - let gain = lightcraft_pipeline::optics::embedded_vignette_gain(&vignette, lightcraft_geom::Point::new(x, y), ow, oh) as f32; - *p = p.map(|v| v * gain); - } + apply_vignetting(sensor, &vignette, ProxyFrame::new(orientation), 1.0); } diff --git a/crates/engine/src/camera_preview/proxy.rs b/crates/engine/src/camera_preview/proxy.rs index e5a9cf06cb..520102d786 100644 --- a/crates/engine/src/camera_preview/proxy.rs +++ b/crates/engine/src/camera_preview/proxy.rs @@ -1,8 +1,10 @@ use super::colour::{PROFILE_PROXY, PROXY, file_local_look}; use super::hue_sat::fit_hue_sat; use super::look_fit::{FIT_PREVIEW_MAX_PIXELS, SENSOR_CLIP, clip_mask, correct_vignetting, without_clipped}; -use super::pairs::{collect_pairs, fit_matrix}; -use super::{CameraTransform, Filter, HsvTable, Mat3, RawFormat, RawImage, Rgb32f, fit, luminance_2020, resize}; +use super::mono::monochrome; +use super::pairs::{collect_pairs, fit_matrix, luma}; +use super::tone::fit_tone; +use super::{CameraTone, CameraTransform, Filter, HsvTable, Mat3, RawFormat, RawImage, Rgb32f, fit, luminance_2020, resize}; /// The embedded preview's long edge must be at least this share of the raw's (and 384 px): a DNG whose preview is a /// small thumbnail is not fitted. The fit itself runs on a proxy of at most 384 px, so the 1024 px preview @@ -93,6 +95,20 @@ pub(super) fn proxies( lens: Option<&LensGeometry>, embedded: Option<&lightcraft_develop::EmbeddedLens>, ) -> Option<(Rgb32f, Rgb32f, Vec)> { + framed_proxies(raw, bytes, transform, size, min_fraction, lens, embedded).map(|(sensor, reference, clipped, _)| (sensor, reference, clipped)) +} + +/// [`proxies`], and the CR3 framing the sensor proxy was moved to ([`estimate_cr3_framing`]; `None` when it was not +/// moved): a pixel of the returned CR3 sensor proxy shows the oriented sensor at `framing.source` of its position. +pub(super) fn framed_proxies( + raw: &RawImage, + bytes: &[u8], + transform: &CameraTransform, + size: usize, + min_fraction: f64, + lens: Option<&LensGeometry>, + embedded: Option<&lightcraft_develop::EmbeddedLens>, +) -> Option<(Rgb32f, Rgb32f, Vec, Option)> { let edge = (2 * size).max(384) as u32; let decoded = crate::files::decode_raw_preview( bytes, @@ -127,6 +143,7 @@ pub(super) fn proxies( let k = (crop.width.max(crop.height).div_ceil(edge as usize).max(2)).div_ceil(2) * 2; let mut sensor = sensor_proxy(raw, k, edge as usize)?; let mut clipped = clip_mask(&sensor); + let mut framing = None; correct_vignetting(&mut sensor, embedded, raw.orientation); // The camera may have corrected its JPEG with the lens warp the file carries (Nikon Z lenses always, at up to 9 % // zoom; other cameras when their correction setting is on): the sensor moved into that geometry is a candidate, @@ -144,7 +161,7 @@ pub(super) fn proxies( sensor.map_in_place(to_working); // Canon's JPEG can be cropped differently from the sensor. Estimate only that common // framing from edge directions, independently of the subsequent colour fit. - (sensor, clipped) = align_cr3_framing(sensor, clipped, &reference); + (sensor, clipped, framing) = align_cr3_framing(sensor, clipped, &reference); } let mut sensor = fit(&sensor, size, size, Filter::Box); let mut reference_small = reference_at(&reference, &sensor); @@ -163,7 +180,7 @@ pub(super) fn proxies( if raw.format != RawFormat::Cr3 { sensor.map_in_place(to_working); } - Some((sensor, reference, clipped)) + Some((sensor, reference, clipped, framing)) } /// The camera JPEG at exactly the sensor proxy's size, so the two pair pixel for pixel. Fitting it @@ -299,9 +316,10 @@ pub(super) fn estimate_cr3_framing(sensor: &Rgb32f, reference: &Rgb32f) -> Optio Some(best.1) } -/// The sensor proxy and its clip mask (same size), both moved to the camera JPEG's framing. -fn align_cr3_framing(sensor: Rgb32f, clipped: Rgb32f, reference: &Rgb32f) -> (Rgb32f, Rgb32f) { - let Some(framing) = estimate_cr3_framing(&sensor, reference) else { return (sensor, clipped) }; +/// The sensor proxy and its clip mask (same size), both moved to the camera JPEG's framing, and that framing (`None` +/// when they stay as they are). +fn align_cr3_framing(sensor: Rgb32f, clipped: Rgb32f, reference: &Rgb32f) -> (Rgb32f, Rgb32f, Option) { + let Some(framing) = estimate_cr3_framing(&sensor, reference) else { return (sensor, clipped, None) }; let apply = |image: &Rgb32f| { let (w, h) = (image.width, image.height); let mut aligned = Rgb32f::new(w, h); @@ -311,13 +329,22 @@ fn align_cr3_framing(sensor: Rgb32f, clipped: Rgb32f, reference: &Rgb32f) -> (Rg } aligned }; - (apply(&sensor), apply(&clipped)) + (apply(&sensor), apply(&clipped), Some(framing)) } -/// Colour training pairs of one raw for a camera profile: white-balanced camera RGB (with the -/// baseline exposure) → its camera JPEG (linear Rec.2020). `None` for formats with their own -/// colour matrices, other files or unusable previews. -pub(crate) fn profile_pairs(raw: &RawImage, bytes: &[u8], lens: Option<&LensGeometry>) -> Option> { +/// What one photo contributes to a camera profile ([`profile_samples`]), in white-balanced camera RGB. +pub(crate) struct ProfileSamples { + /// Colour pairs: camera RGB → the camera JPEG's linear Rec.2020 (empty when the photo has too little colour). + pub colour: Vec<([f64; 3], [f64; 3])>, + /// Tone samples: camera RGB → the camera JPEG's luminance, dark pixels included (as the photo's own toe fit takes + /// them, [`fit_tone_with_shadows`](super::pairs::fit_tone_with_shadows)). + pub tone: Vec<([f64; 3], f64)>, +} + +/// A raw's colour and tone samples for a pooled camera profile (`lightcraft-cli calibrate`): white-balanced camera +/// RGB (with the baseline exposure) → its camera JPEG (linear Rec.2020). `None` for formats with their own colour +/// matrices, other files or unusable previews. +pub(crate) fn profile_samples(raw: &RawImage, bytes: &[u8], lens: Option<&LensGeometry>) -> Option { if !file_local_look(raw.format) || lightcraft_raw::color::has_matrix(&raw.color) { return None; } @@ -326,8 +353,130 @@ pub(crate) fn profile_pairs(raw: &RawImage, bytes: &[u8], lens: Option<&LensGeom let to_camera = transform.matrix.inverse()?; // clipped sensor pixels don't record the scene's colour (see `fit_look`) let sensor = without_clipped(&sensor, &clipped).unwrap_or(sensor); - let (pairs, _) = collect_pairs(&sensor, &reference, 0.05, None, false)?; - Some(pairs.into_iter().map(|(x, y)| (to_camera.apply(x), y)).collect()) + samples_from_proxies(&sensor, &reference, &to_camera) +} + +/// [`profile_samples`] from a raw's sensor proxy (clipped pixels left out) and its camera JPEG's, `to_camera` taking the +/// sensor proxy back to white-balanced camera RGB. +pub(super) fn samples_from_proxies(sensor: &Rgb32f, reference: &Rgb32f, to_camera: &Mat3) -> Option { + // a black-and-white JPEG went through a monochrome picture style's own mix and curve: nothing for the profile + if monochrome(reference) { + return None; + } + // a dark or colourless photo has no colour pairs but still shows the shadows the pooled curve needs + let colour = collect_pairs(sensor, reference, 0.05, None, false).map_or_else(Vec::new, |(pairs, _)| pairs); + let tone: Vec<_> = sensor + .data + .iter() + .zip(&reference.data) + .filter(|(input, output)| tone_sample(**input, **output)) + .map(|(input, output)| (to_camera.apply(input.map(f64::from)), f64::from(luminance_2020(*output)))) + .collect(); + if colour.is_empty() && tone.is_empty() { + return None; + } + Some(ProfileSamples { colour: colour.into_iter().map(|(x, y)| (to_camera.apply(x), y)).collect(), tone }) +} + +/// Whether a sensor/JPEG proxy pixel pair can teach the tone curve: every channel above the sensor floor, the JPEG +/// pixel about one 8-bit sRGB code above black (no flat black segment learnt from JPEG compression) and below the +/// highlights (clipped or rolled off). +fn tone_sample(input: [f32; 3], output: [f32; 3]) -> bool { + input.iter().all(|v| v.is_finite() && *v > 0.0001 && *v < 1.5) + && output.iter().all(|v| v.is_finite() && *v >= 0.0) + && (0.0003..0.85).contains(&luminance_2020(output)) +} + +/// A camera profile's tone curve from the tone samples pooled over its photos, through the profile's `matrix`: one +/// curve for the camera, from shadows that only dark photos show to highlights that only bright ones show. Quantile +/// matching ([`fit_tone`]) pools correctly because every photo went through the same camera curve (picture styles and +/// Active D-Lighting aside, which it averages). Luminance is taken with negative channels kept, as the render feeds +/// the curve (raw decoding keeps them, `files::CameraColourModel`). +pub(crate) fn fit_profile_tone(samples: &[([f64; 3], f64)], matrix: &Mat3) -> Option { + fit_tone(samples.iter().map(|(x, y)| (luma(matrix.apply(*x)), *y)).filter(|(x, _)| *x > 0.0).collect()) +} + +/// `photo`'s tone curve where its JPEG taught it, `pooled`'s past that: from the photo's last knot it fades over +/// 1 EV (`EXTEND_FADE_EV`) from its own level onto the camera's pooled curve, instead of the bounded shoulder +/// ([`CameraTone::apply`]) whose rate comes from the photo's last two knots. A dark photo's curve ends in the shadows, +/// and that shoulder rendered it, pushed back up, 4-7 L* darker than a properly exposed photo of the same scene. +/// `photo` unchanged when the pooled curve doesn't reach on past it. +pub(super) fn extend_tone(photo: &CameraTone, pooled: &CameraTone) -> CameraTone { + /// EV over which the extension moves from the photo's level onto the pooled curve. + const EXTEND_FADE_EV: f32 = 1.0; + /// Knots per EV of the extension. + const EXTEND_KNOTS_PER_EV: f32 = 3.0; + let (own, camera) = (photo.knots(), pooled.knots()); + let (end, last) = (own[31], camera[31][0]); + let span = (last / end[0]).log2(); + if !(span.is_finite() && span > 0.2) { + return *photo; + } + // the photo's own knots, the ones its curve needs least dropped to make room: as many extension knots as keep the + // curve within `THIN_TOLERANCE` where the JPEG taught it, at least 2, else the photo keeps its curve as it is + let Some((extra, own)) = + (2..=((span * EXTEND_KNOTS_PER_EV).round() as usize).clamp(2, 16)).rev().find_map(|extra| thinned_knots(own, 32 - extra).map(|k| (extra, k))) + else { + if lightcraft_pipeline::profiling() { + eprintln!("[profile] camera look: the photo's curve can't make room for the pooled one, kept as fitted"); + } + return *photo; + }; + if lightcraft_pipeline::profiling() { + eprintln!("[profile] camera look: pooled tone curve joined with {extra} knots past the photo's"); + } + let at_end = pooled.apply(end[0]); + let ratio = if at_end > 0.0 && end[1] > 0.0 { end[1] / at_end } else { 1.0 }; + let mut knots = [[0.0f32; 2]; 32]; + let kept = 32 - extra; + for (knot, own) in knots.iter_mut().zip(&own) { + *knot = *own; + } + for k in 1..=extra { + let ev = span * k as f32 / extra as f32; + let x = end[0] * ev.exp2(); + let t = (ev / EXTEND_FADE_EV).clamp(0.0, 1.0); + let w = t * t * (3.0 - 2.0 * t); + knots[kept + k - 1] = [x, pooled.apply(x) * ratio.powf(1.0 - w)]; + } + // monotone and below white whatever the two curves do + let mut floor = 0.0f32; + for knot in &mut knots { + knot[1] = knot[1].max(floor).min(0.999); + floor = knot[1]; + } + CameraTone::new(knots).and_then(|tone| tone.with_chroma(*photo.chroma())).unwrap_or(*photo) +} + +/// Largest change, in gamma-encoded display values (1/2.2), that thinning a photo's curve for [`extend_tone`] may make +/// where its JPEG taught it: one 8-bit code. +pub(super) const THIN_TOLERANCE: f32 = 1.0 / 255.0; + +/// `knots` thinned to `keep` (first and last kept), dropping one at a time the knot whose removal changes the curve +/// least (`CameraTone::apply` interpolates linearly, so the change peaks at a dropped knot); `None` when that change +/// would exceed [`THIN_TOLERANCE`]. +fn thinned_knots(knots: &[[f32; 2]; 32], keep: usize) -> Option> { + let encoded = |v: f32| v.max(0.0).powf(1.0 / 2.2); + // the change from leaving out every knot strictly between kept indices `a` and `b` + let gap = |a: usize, b: usize| { + let ([x0, y0], [x1, y1]) = (knots[a], knots[b]); + (a + 1..b) + .map(|i| { + let [x, y] = knots[i]; + let t = if x1 > x0 { (x - x0) / (x1 - x0) } else { 0.0 }; + (encoded(y0 + t * (y1 - y0)) - encoded(y)).abs() + }) + .fold(0.0f32, f32::max) + }; + let mut kept: Vec = (0..knots.len()).collect(); + while kept.len() > keep.max(2) { + let (i, change) = (1..kept.len() - 1).map(|i| (i, gap(kept[i - 1], kept[i + 1]))).min_by(|a, b| a.1.total_cmp(&b.1))?; + if change > THIN_TOLERANCE { + return None; + } + kept.remove(i); + } + Some(kept.into_iter().map(|i| knots[i]).collect()) } /// A camera profile's colour model (matrix from white-balanced camera RGB, hue/saturation table) diff --git a/crates/engine/src/camera_preview/tests.rs b/crates/engine/src/camera_preview/tests.rs index c2e0ad1e01..898c2c568d 100644 --- a/crates/engine/src/camera_preview/tests.rs +++ b/crates/engine/src/camera_preview/tests.rs @@ -2196,6 +2196,58 @@ fn the_colour_look_is_fitted_on_the_vignetting_corrected_sensor() { assert!(uncorrected > corrected + 0.03, "without the correction the curve brightens: {uncorrected} vs {corrected}"); } +/// A lens database profile reaches the fit only as far as the camera JPEG shows it. A camera that left its JPEG +/// uncorrected relative to its raw keeps the curve fitted without any correction: with the whole +/// profile on the sensor the curve darkened and the colour fit bent (an ILCE-7M3 with an FE 28mm F2 at f/2 rendered +/// darker and orange). A camera that corrected its JPEG fully gets the whole correction, as with the file's own data. +#[test] +fn a_lens_database_vignetting_reaches_the_fit_as_far_as_the_camera_jpeg_shows_it() { + use lightcraft_develop::{EmbeddedLens, EmbeddedVignette, LensSource}; + let (w, h) = (192usize, 128usize); + let vignette = EmbeddedVignette { k: [1.0, 0.0, 0.0, 0.0, 0.0], center: lightcraft_geom::Point::new(0.5, 0.5), radius: 0.6 }; + let gain = |x: usize, y: usize| { + let point = lightcraft_geom::Point::new(x as f64 + 0.5, y as f64 + 0.5); + lightcraft_pipeline::optics::embedded_vignette_gain(&vignette, point, w as f64, h as f64) as f32 + }; + let scene = |x: usize, y: usize| 0.01 + 0.5 * (x as f32 / w as f32) * (0.3 + 0.7 * y as f32 / h as f32); + let database = EmbeddedLens { vignette: Some(vignette), source: LensSource::Database, ..Default::default() }; + let camera = 1.0 - (-0.75f32).exp(); + let at_quarter = |raw: &RawImage, bytes: &[u8], embedded: Option<&EmbeddedLens>| { + let t = lightcraft_raw::color::camera_transform(raw, lightcraft_raw::color::as_shot_white_xy(raw)); + let look = monochrome_look(raw, bytes, &t, None, embedded).expect("a tone curve"); + ToneMap::camera(&look.tone, 0.0, 0.0, 0.0).apply(0.25) + }; + + // the camera JPEG of the vignetted sensor, uncorrected + let vignetted = |x: usize, y: usize| scene(x, y) / gain(x, y); + let (raw, bytes) = grey_raw_with_jpeg((w, h), vignetted, vignetted, [1.0; 3]); + let (with_profile, without) = (at_quarter(&raw, &bytes, Some(&database)), at_quarter(&raw, &bytes, None)); + assert!((with_profile - camera).abs() < 0.03, "the camera's curve at 0.25: {with_profile} vs {camera}"); + assert!((with_profile - without).abs() < 0.01, "as without the profile: {with_profile} vs {without}"); + + // the same in colour: the tinted JPEG takes the colour fit, whose curve the whole profile darkened + let tint = [1.0, 0.9, 0.8]; + let (raw, bytes) = grey_raw_with_jpeg((w, h), vignetted, vignetted, tint); + let colour_at_quarter = |raw: &RawImage, bytes: &[u8], embedded: Option<&EmbeddedLens>| { + let (_, _, look) = starting_colour(&mut raw.clone(), bytes, None, embedded); + let look = look.expect("a colour look"); + assert!(look.matrix != Mat3::IDENTITY || look.hue_sat.is_some(), "the colour fit, not the black-and-white one"); + ToneMap::camera(&look.tone, 0.0, 0.0, 0.0).apply(0.25) + }; + let (with_profile, without) = (colour_at_quarter(&raw, &bytes, Some(&database)), colour_at_quarter(&raw, &bytes, None)); + assert!((with_profile - without).abs() < 0.01, "the colour fit's curve as without the profile: {with_profile} vs {without}"); + + // a camera JPEG with the whole correction applied: the whole correction reaches the fit + let (raw, bytes) = grey_raw_with_jpeg((w, h), vignetted, scene, [1.0; 3]); + let corrected = at_quarter(&raw, &bytes, Some(&database)); + assert!((corrected - camera).abs() < 0.03, "the camera's curve at 0.25: {corrected} vs {camera}"); + + // and in colour: the colour fit keeps the database profile, whose correction it would otherwise learn into the curve + let (raw, bytes) = grey_raw_with_jpeg((w, h), vignetted, scene, tint); + let (with_profile, without) = (colour_at_quarter(&raw, &bytes, Some(&database)), colour_at_quarter(&raw, &bytes, None)); + assert!(without > with_profile + 0.03, "without the profile the colour fit's curve brightens: {without} vs {with_profile}"); +} + /// A lens-warped sensor proxy gets the vignetting gain of the position it samples, as the render applies it: the /// vignetted sensor, corrected, gives the proxy of the same sensor without vignetting. #[test] @@ -2448,6 +2500,48 @@ fn dng_tone_gates_follow_the_files_own_tags() { assert!(looked.profile.look_table.is_some() && eligible(RawFormat::Dng, looked), "a look table defines colour, not tone"); } +/// A DNG's tone fit takes a lens database's vignetting correction in the share its camera JPEG shows, as the other +/// raws' fits do: none for a JPEG left uncorrected (the curve as without the profile), all of it for a corrected one. +/// The file's own vignetting data still reaches it whole. +#[test] +fn dng_tone_fit_takes_a_lens_database_vignetting_as_far_as_the_camera_jpeg_shows_it() { + use lightcraft_develop::{EmbeddedLens, EmbeddedVignette, LensSource}; + let (w, h) = (384usize, 256usize); + let vignette = EmbeddedVignette { k: [1.0, 0.0, 0.0, 0.0, 0.0], center: lightcraft_geom::Point::new(0.5, 0.5), radius: 0.6 }; + let gain = |x: usize, y: usize| { + let point = lightcraft_geom::Point::new(x as f64 + 0.5, y as f64 + 0.5); + lightcraft_pipeline::optics::embedded_vignette_gain(&vignette, point, w as f64, h as f64) as f32 + }; + // a gradient with blocks of texture, so the preview shows the same picture (`structure_agrees`) + let texture = |x: usize, y: usize| ((x / 6).wrapping_mul(2_654_435_761) ^ (y / 6).wrapping_mul(40_503)) % 7; + let scene = |x: usize, y: usize| (0.01 + 0.5 * (x as f32 / w as f32) * (0.3 + 0.7 * y as f32 / h as f32)) * (0.55 + 0.075 * texture(x, y) as f32); + let vignetted = |x: usize, y: usize| scene(x, y) / gain(x, y); + let database = EmbeddedLens { vignette: Some(vignette), source: LensSource::Database, ..Default::default() }; + let at_quarter = |jpeg_scene: &dyn Fn(usize, usize) -> f32, embedded: Option<&EmbeddedLens>| { + // tinted: a fit's pairs need some colour (`collect_pairs`) + let (mut raw, bytes) = grey_raw_with_jpeg((w, h), vignetted, jpeg_scene, [1.0, 0.95, 0.9]); + raw.format = RawFormat::Dng; + // a camera whose RGB is linear sRGB (XYZ to sRGB under D65): the grey sensor stays grey + let xyz_to_camera = Mat3([[3.2406, -1.5372, -0.4986], [-0.9689, 1.8758, 0.0415], [0.0557, -0.2040, 1.0570]]); + raw.color = lightcraft_raw::ColorData { illuminant: [21, 0], color_matrix: [Some(xyz_to_camera), None], ..Default::default() }; + let t = lightcraft_raw::color::camera_transform(&raw, lightcraft_raw::color::as_shot_white_xy(&raw)); + assert!(dng_tone_eligible(&raw, &t), "a DNG whose tone the fit defines"); + let look = fit_dng_tone(&raw, &bytes, &t, embedded).expect("a DNG tone fit"); + ToneMap::camera(&look.tone, 0.0, 0.0, 0.0).apply(0.25) + }; + let (with_profile, without) = (at_quarter(&vignetted, Some(&database)), at_quarter(&vignetted, None)); + assert!((with_profile - without).abs() < 0.01, "an uncorrected JPEG, as without the profile: {with_profile} vs {without}"); + let (with_profile, without) = (at_quarter(&scene, Some(&database)), at_quarter(&scene, None)); + assert!(without > with_profile + 0.03, "a corrected JPEG: without the profile the curve brightens: {without} vs {with_profile}"); + + // the file's own vignetting data is what its camera applied: it reaches the fit whole, whatever the JPEG shows + let file = EmbeddedLens { source: LensSource::File, ..database }; + let with_file = at_quarter(&scene, Some(&file)); + assert!((with_file - with_profile).abs() < 0.01, "a corrected JPEG, as with the measured share: {with_file} vs {with_profile}"); + let (with_file, without) = (at_quarter(&vignetted, Some(&file)), at_quarter(&vignetted, None)); + assert!(without > with_file + 0.03, "an uncorrected JPEG still gets the file's whole correction: {without} vs {with_file}"); +} + /// The 1024 px preview Lightroom Classic writes into a 7008 px DNG is fitted; a 256 px thumbnail is not. #[test] fn dng_tone_fit_takes_lightroom_sized_previews() { @@ -2457,6 +2551,171 @@ fn dng_tone_fit_takes_lightroom_sized_previews() { assert!(1024.0 >= floor(9504.0), "a 61 MP raw too"); } +#[test] +fn a_photo_no_look_fits_keeps_its_camera_profiles_colour() { + let colour = ( + Mat3([[1.8, -0.6, -0.2], [-0.3, 1.5, -0.2], [0.0, -0.4, 1.4]]), + dro_test_look(&std::array::from_fn(|i| 0.01 + i as f32 * 0.01), &|x| x).hue_sat, + ); + // too dark for any look, no tone either: the profile's colour, the default raw tone curve + let look = with_profile_colour(None, Some(colour.clone()), None, |_| None).expect("the profile's colour"); + assert_eq!((look.matrix, look.hue_sat.is_some()), (colour.0, true)); + assert_eq!(look.tone, lightcraft_pipeline::tone::default_raw_camera_tone().unwrap()); + // the JPEG's tone curve when it has one + let toned = dro_test_look(&std::array::from_fn(|i| 0.01 + i as f32 * 0.01), &|x| 0.9 * x); + let look = with_profile_colour(None, Some(colour.clone()), None, |c| Some(CameraLook { matrix: c.0, ..toned.clone() })).unwrap(); + assert_eq!((look.matrix, look.tone), (colour.0, toned.tone)); + // a photo's own look wins; without a profile there is nothing to keep (the neutral fallback follows) + let own = with_profile_colour(Some(toned.clone()), Some(colour), None, |_| panic!("the photo's own look is used")).unwrap(); + assert_eq!(own.matrix, toned.matrix); + assert!(with_profile_colour(None, None, None, |_| panic!("no colour to fit")).is_none()); +} + +/// A camera curve: a toe, then a shoulder toward 0.95, the shape camera JPEG curves have. +fn camera_curve(x: f32) -> f32 { + 0.95 * (x / (x + 0.12)).powf(1.3) * 1.1 +} + +fn sampled(curve: impl Fn(f32) -> f32, from: f32, to: f32) -> CameraTone { + CameraTone::new(std::array::from_fn(|i| { + let x = from * (to / from).powf(i as f32 / 31.0); + [x, curve(x)] + })) + .unwrap() +} + +#[test] +fn a_dark_photos_curve_goes_on_along_the_cameras_pooled_one() { + let pooled = sampled(camera_curve, 0.0005, 0.9); + // a dark photo's JPEG showed the curve up to 0.02, 10% darker than the camera's (a picture style) + let photo = sampled(|x| 0.9 * camera_curve(x), 0.0005, 0.02).with_chroma([1.4, 1.2, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]).unwrap(); + let tone = extend_tone(&photo, &pooled); + assert_eq!(tone.chroma(), photo.chroma()); + // its own curve where its JPEG taught it, the pooled one from 1 EV past that, a monotone fade in between + for x in [0.001f32, 0.005, 0.01, 0.019] { + assert!((tone.apply(x) - photo.apply(x)).abs() < 0.02 * photo.apply(x), "{x}: {} vs {}", tone.apply(x), photo.apply(x)); + } + for x in [0.05f32, 0.1, 0.3, 0.8] { + assert!((tone.apply(x) - pooled.apply(x)).abs() < 0.01, "{x}: {} vs {}", tone.apply(x), pooled.apply(x)); + } + assert!(tone.knots().windows(2).all(|k| k[1][0] > k[0][0] && k[1][1] >= k[0][1])); + // a photo that already reaches as far keeps its curve + let bright = sampled(|x| 0.9 * camera_curve(x), 0.0005, 0.85); + assert_eq!(extend_tone(&bright, &pooled), bright); +} + +#[test] +fn extending_a_photos_curve_keeps_it_where_its_jpeg_taught_it() { + let pooled = sampled(camera_curve, 0.0005, 0.9); + let encoded = |v: f32| v.max(0.0).powf(1.0 / 2.2); + // a smooth dark curve, and one with a sharp toe (flat, then a steep rise over two knots) + let smooth = sampled(|x| 0.9 * camera_curve(x), 0.0005, 0.02); + let toe = CameraTone::new(std::array::from_fn(|i| { + let x = 0.0005 * 40f32.powf(i as f32 / 31.0); + [ + x, + if i < 9 { + 0.001 + 0.0001 * i as f32 + } else if i < 11 { + 0.004 + 0.012 * (i - 8) as f32 + } else { + 0.03 + 0.004 * (i - 10) as f32 + }, + ] + })) + .unwrap(); + for photo in [smooth, toe] { + let tone = extend_tone(&photo, &pooled); + for [x, _] in photo.knots() { + let change = (encoded(tone.apply(*x)) - encoded(photo.apply(*x))).abs(); + assert!(change <= THIN_TOLERANCE + 1e-5, "{x}: {} vs {} ({change})", tone.apply(*x), photo.apply(*x)); + } + } + // the smooth one still goes on along the pooled curve + assert!((extend_tone(&smooth, &pooled).apply(0.3) - pooled.apply(0.3)).abs() < 0.01); +} + +#[test] +fn a_pooled_tone_curve_spans_dark_and_bright_photos() { + // camera RGB grey (white balanced): a dark photo's pixels and a bright one's, through one camera curve + let matrix = Mat3::IDENTITY; + let samples: Vec<([f64; 3], f64)> = (0..4000) + .map(|i| { + let x = if i % 2 == 0 { 0.0005 * 40f64.powf((i / 2) as f64 / 2000.0) } else { 0.02 * 40f64.powf((i / 2) as f64 / 2000.0) }; + ([x; 3], f64::from(camera_curve(x as f32))) + }) + .collect(); + let tone = fit_profile_tone(&samples, &matrix).unwrap(); + for x in [0.001f32, 0.01, 0.05, 0.2, 0.6] { + assert!((tone.apply(x) - camera_curve(x)).abs() < 0.01 + 0.03 * camera_curve(x), "{x}: {} vs {}", tone.apply(x), camera_curve(x)); + } + assert!(fit_profile_tone(&samples[..64], &matrix).is_none(), "too few samples"); +} + +#[test] +fn a_photo_too_dark_for_colour_pairs_still_gives_the_pooled_curve_its_shadows() { + // a scene of saturated colours, its camera JPEG a linear map of the sensor; `level` sets the exposure + let colours = [[0.9, 0.2, 0.1], [0.1, 0.8, 0.2], [0.2, 0.3, 0.9], [0.8, 0.7, 0.1], [0.6, 0.2, 0.7], [0.5, 0.5, 0.5]]; + let scene = |level: f32| { + let sensor = Rgb32f::from_fn(64, 64, |x, y| colours[(x / 8 + y / 8) % colours.len()].map(|v| v * level * (1.0 + (x % 8) as f32 / 16.0))); + let reference = Rgb32f::from_fn(64, 64, |x, y| sensor.data[y * 64 + x].map(|v| v * 0.8)); + (sensor, reference) + }; + let (sensor, reference) = scene(0.3); + let bright = samples_from_proxies(&sensor, &reference, &Mat3::IDENTITY).unwrap(); + assert!(!bright.colour.is_empty() && !bright.tone.is_empty()); + // every JPEG channel under the colour-pair floor, its luminance still above the tone floor + let (sensor, reference) = scene(0.003); + assert!(reference.data.iter().all(|p| p.iter().all(|v| *v < 0.004))); + let dark = samples_from_proxies(&sensor, &reference, &Mat3::IDENTITY).expect("tone samples from a dark photo"); + assert!(dark.colour.is_empty() && dark.tone.len() > 1000, "{} colour pairs, {} tone samples", dark.colour.len(), dark.tone.len()); + // a black-and-white camera JPEG gives nothing + let grey = Rgb32f::from_fn(64, 64, |x, y| [luminance_2020(reference.data[y * 64 + x]) * 100.0; 3]); + assert!(samples_from_proxies(&scene(0.3).0, &grey, &Mat3::IDENTITY).is_none()); +} + +#[test] +fn a_pooled_tone_curve_takes_luminance_with_negative_channels_as_the_render_does() { + // a saturating matrix sends this magenta's green channel negative; the render keeps it, so the curve's input + // is the unclamped luminance (clamped, the magenta samples read 30% brighter and pull the pooled quantiles) + let matrix = Mat3([[1.3, -0.2, -0.1], [-0.1, 1.2, -0.1], [-0.1, -0.5, 1.6]]); + let magenta = [0.9, 0.05, 0.9]; + assert!(matrix.apply(magenta)[1] < 0.0); + let samples: Vec<([f64; 3], f64)> = (0..4000) + .map(|i| { + let colour = if i % 2 == 0 { magenta } else { [1.0; 3] }; + let x = colour.map(|v| v * 0.001 * 500f64.powf(f64::from(i / 2) / 2000.0)); + (x, f64::from(camera_curve(luma(matrix.apply(x)) as f32))) + }) + .collect(); + let tone = fit_profile_tone(&samples, &matrix).unwrap(); + for x in [0.002f32, 0.02, 0.1, 0.3] { + assert!((tone.apply(x) - camera_curve(x)).abs() < 0.01 + 0.03 * camera_curve(x), "{x}: {} vs {}", tone.apply(x), camera_curve(x)); + } +} + +#[test] +fn only_a_look_with_the_profiles_colour_continues_along_its_pooled_curve() { + let profile = Mat3([[1.2, -0.1, -0.1], [-0.1, 1.1, 0.0], [0.0, -0.2, 1.2]]); + let pooled = sampled(camera_curve, 0.0005, 0.9); + let dark = sampled(|x| 0.9 * camera_curve(x), 0.0005, 0.02); + let with = |matrix| CameraLook { matrix, tone: dark, hue_sat: None }; + // the profile's colour: the curve goes on along the pooled one + assert_eq!(with_pooled_tone(with(profile), Some(profile), Some(pooled)).tone, extend_tone(&dark, &pooled)); + // the photo's own matrix (the profile's colour rejected): its curve as fitted + assert_eq!(with_pooled_tone(with(Mat3::IDENTITY), Some(profile), Some(pooled)).tone, dark); + assert_eq!(with_pooled_tone(with(profile), None, Some(pooled)).tone, dark); + assert_eq!(with_pooled_tone(with(profile), Some(profile), None).tone, dark); +} + +#[test] +fn a_photo_no_look_fits_takes_the_profiles_pooled_tone_curve() { + let colour = (Mat3::IDENTITY, None); + let pooled = sampled(camera_curve, 0.0005, 0.9); + let look = with_profile_colour(None, Some(colour), Some(pooled), |_| None).unwrap(); + assert_eq!(look.tone, pooled); +} + /// Pairs whose scene luminance spans `ratio` from the darkest to the brightest pixel, mapped /// to the JPEG through a steep camera curve (a hazy scene the camera stretches). fn low_contrast_pairs(ratio: f64) -> Vec<(f64, f64)> { @@ -2633,3 +2892,251 @@ fn a_narrow_black_and_white_curve_that_darkens_the_bright_areas_is_refused() { assert!(sky > 0.8, "an accepted curve must not darken what the camera renders at 0.93: {sky}"); } } + +/// A lens database's vignetting correction reaches the fit in the share the camera JPEG shows: a JPEG with none, part +/// or all of it is measured as such, and a JPEG without enough usable pixels keeps the whole correction. +#[test] +fn camera_vignetting_amount_measures_the_share_the_jpeg_shows() { + use lightcraft_develop::EmbeddedVignette; + let vignette = EmbeddedVignette { k: [2.0, 1.0, 0.0, 0.0, 0.0], center: lightcraft_geom::Point::new(0.5, 0.5), radius: 0.6 }; + let (w, h) = (96, 64); + let gain = |i: usize| { + lightcraft_pipeline::optics::embedded_vignette_gain( + &vignette, + lightcraft_geom::Point::new((i % w) as f64 + 0.5, (i / w) as f64 + 0.5), + w as f64, + h as f64, + ) as f32 + }; + // a scene of unrelated brightnesses (no gradient for the vignetting to hide in), darkened by the lens + let mut seed = 12345u32; + let mut sensor = Rgb32f::new(w, h); + for (i, p) in sensor.data.iter_mut().enumerate() { + seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + let v = 0.02 + 0.4 * (seed >> 8) as f32 / (1u32 << 24) as f32; + *p = [v, v * 0.9, v * 0.7].map(|c| c / gain(i)); + } + let clipped = vec![false; w * h]; + for shown in [0.0, 0.4, 1.0] { + let mut reference = sensor.clone(); + for (i, p) in reference.data.iter_mut().enumerate() { + let g = 1.0 + (gain(i) - 1.0) * shown; + *p = p.map(|c| (c * g).powf(1.0 / 2.2).min(1.0)); + } + let amount = camera_vignetting_amount(&sensor, &reference, &clipped, &vignette, ProxyFrame::new(lightcraft_geom::Orientation::Normal)); + assert!((amount - f64::from(shown)).abs() < 0.051, "the JPEG shows {shown}, measured {amount}"); + } + // too few pixels to measure on: the whole correction, although this JPEG shows none of it + let (tw, th) = (8, 8); + let mut tiny = Rgb32f::new(tw, th); + for (i, p) in tiny.data.iter_mut().enumerate() { + let g = lightcraft_pipeline::optics::embedded_vignette_gain( + &vignette, + lightcraft_geom::Point::new((i % tw) as f64 + 0.5, (i / tw) as f64 + 0.5), + tw as f64, + th as f64, + ) as f32; + let v = 0.05 + 0.05 * ((i * 7) % 8) as f32; + *p = [v, v * 0.9, v * 0.7].map(|c| c / g); + } + let mut tiny_reference = tiny.clone(); + tiny_reference.map_in_place(|p| p.map(|c| c.powf(1.0 / 2.2))); + let frame = ProxyFrame::new(lightcraft_geom::Orientation::Normal); + assert_eq!(camera_vignetting_amount(&tiny, &tiny_reference, &[false; 64], &vignette, frame), 1.0); +} + +/// A camera that renders some hues brighter than others doesn't read as vignetting where those hues gather toward +/// the corners: the JPEG without any correction, whose blue pixels (more of them toward the corners) the camera +/// renders brighter, is measured as showing none of it. +#[test] +fn camera_vignetting_amount_is_not_misled_by_hues_gathered_in_the_corners() { + use lightcraft_develop::EmbeddedVignette; + let vignette = EmbeddedVignette { k: [2.0, 1.0, 0.0, 0.0, 0.0], center: lightcraft_geom::Point::new(0.5, 0.5), radius: 0.6 }; + let (w, h) = (96, 64); + let mut seed = 54321u32; + let mut random = || { + seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + (seed >> 8) as f32 / (1u32 << 24) as f32 + }; + let mut sensor = Rgb32f::new(w, h); + let mut reference = Rgb32f::new(w, h); + for (i, (s, r)) in sensor.data.iter_mut().zip(reference.data.iter_mut()).enumerate() { + let point = lightcraft_geom::Point::new((i % w) as f64 + 0.5, (i / w) as f64 + 0.5); + let gain = lightcraft_pipeline::optics::embedded_vignette_gain(&vignette, point, w as f64, h as f64) as f32; + let radius = ((point.x / w as f64 - 0.5).hypot(point.y / h as f64 - 0.5) / 0.5f64.hypot(0.5)) as f32; + let v = (0.02 + 0.4 * random()) / gain; + let blue = random() < radius; + *s = if blue { [0.4 * v, 0.6 * v, v] } else { [v, 0.6 * v, 0.4 * v] }; + let brightness = if blue { 1.6 } else { 1.0 }; + *r = s.map(|c| (c * brightness).powf(1.0 / 2.2).min(1.0)); + } + let clipped = vec![false; w * h]; + let amount = camera_vignetting_amount(&sensor, &reference, &clipped, &vignette, ProxyFrame::new(lightcraft_geom::Orientation::Normal)); + assert!(amount < 0.051, "the JPEG shows no correction, measured {amount}"); +} + +/// A CR3 sensor proxy moved to its camera JPEG's framing gets the vignetting gain of the position each pixel shows, +/// not of where it lands. +#[test] +fn the_vignetting_gain_of_a_framed_proxy_is_taken_where_its_pixels_come_from() { + use lightcraft_develop::EmbeddedVignette; + let vignette = EmbeddedVignette { k: [2.0, 1.0, 0.0, 0.0, 0.0], center: lightcraft_geom::Point::new(0.5, 0.5), radius: 0.6 }; + let (w, h) = (96, 64); + let framing = Cr3Framing { scale: 0.92, offset: [0.02, -0.015] }; + let frame = ProxyFrame { orientation: lightcraft_geom::Orientation::Normal, framing: Some(framing) }; + let gains = vignetting_gains(&Rgb32f::new(w, h), &vignette, frame); + for i in [0, w - 1, w * h / 2 + w / 3, w * h - 1] { + let (x, y) = framing.source((i % w) as f32 + 0.5, (i / w) as f32 + 0.5, w, h); + let expected = lightcraft_pipeline::optics::embedded_vignette_gain( + &vignette, + lightcraft_geom::Point::new(f64::from(x), f64::from(y)), + w as f64, + h as f64, + ); + assert!((gains[i] - expected).abs() < 1e-9, "pixel {i}: {} vs {expected}", gains[i]); + } +} + +/// What `camera_vignetting_amount` can't measure on keeps the whole correction: proxies of different sizes, and a flat +/// scene, where every share ranks alike (a tie keeps the larger share, the correction a camera JPEG usually has). +/// Clipped and black pixels are left out: here they sit where the correction would brighten or darken them most and +/// would pull the share of a JPEG without any correction up. A JPEG clips highlights the sensor doesn't, so pixels +/// clipped in the JPEG are left out without the sensor's clip mask too. Non-finite pixels don't spoil the measurement. +#[test] +fn camera_vignetting_amount_falls_back_and_leaves_out_what_it_cannot_measure() { + use lightcraft_develop::EmbeddedVignette; + let vignette = EmbeddedVignette { k: [2.0, 1.0, 0.0, 0.0, 0.0], center: lightcraft_geom::Point::new(0.5, 0.5), radius: 0.6 }; + let (w, h) = (96, 64); + let gains: Vec = (0..w * h) + .map(|i| { + let point = lightcraft_geom::Point::new((i % w) as f64 + 0.5, (i / w) as f64 + 0.5); + lightcraft_pipeline::optics::embedded_vignette_gain(&vignette, point, w as f64, h as f64) as f32 + }) + .collect(); + let measure = |sensor: &Rgb32f, reference: &Rgb32f, clipped: &[bool]| { + camera_vignetting_amount(sensor, reference, clipped, &vignette, ProxyFrame::new(lightcraft_geom::Orientation::Normal)) + }; + let unclipped = vec![false; w * h]; + + let mut flat = Rgb32f::new(w, h); + flat.data.fill([0.2, 0.18, 0.14]); + assert_eq!(measure(&flat, &flat, &unclipped), 1.0, "a tie keeps the whole correction"); + assert_eq!(measure(&flat, &Rgb32f::new(w, h / 2), &unclipped), 1.0, "proxies of different sizes"); + + // a scene of unrelated brightnesses, darkened by the lens, and its JPEG without any correction + let mut seed = 777u32; + let mut sensor = Rgb32f::new(w, h); + for (p, g) in sensor.data.iter_mut().zip(&gains) { + seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + let v = 0.02 + 0.4 * (seed >> 8) as f32 / (1u32 << 24) as f32; + *p = [v, v * 0.9, v * 0.7].map(|c| c / g); + } + let mut reference = sensor.clone(); + reference.data.iter_mut().for_each(|p| *p = p.map(|c| c.powf(1.0 / 2.2))); + assert!(measure(&sensor, &reference, &unclipped) < 0.051); + let mut sorted = gains.clone(); + sorted.sort_by(f32::total_cmp); + let (low, high) = (sorted[w * h / 4], sorted[w * h * 3 / 4]); + + // the quarter the correction brightens most, clipped white in the JPEG + let corners: Vec = gains.iter().map(|g| *g >= high).collect(); + let mut clipped_reference = reference.clone(); + clipped_reference.data.iter_mut().zip(&corners).filter(|(_, c)| **c).for_each(|(p, _)| *p = [1.0; 3]); + let amount = measure(&sensor, &clipped_reference, &corners); + assert!(amount < 0.051, "clipped pixels are left out: measured {amount}"); + let amount = measure(&sensor, &clipped_reference, &unclipped); + assert!(amount < 0.051, "pixels clipped in the JPEG alone are left out: measured {amount}"); + let mut bright_reference = reference.clone(); + bright_reference.data.iter_mut().zip(&corners).filter(|(_, c)| **c).for_each(|(p, _)| *p = [0.97; 3]); + let amount = measure(&sensor, &bright_reference, &unclipped); + assert!(amount > 0.1, "the same pixels, just below the clip, would have pulled the share up: {amount}"); + + // the quarter it brightens least, black in the JPEG + let mut dark_reference = reference.clone(); + let darkened = |level: f32| { + let mut r = dark_reference.clone(); + r.data.iter_mut().zip(&gains).filter(|(_, g)| **g <= low).for_each(|(p, _)| *p = [level; 3]); + r + }; + let amount = measure(&sensor, &darkened(0.0), &unclipped); + assert!(amount < 0.051, "black pixels are left out: measured {amount}"); + let amount = measure(&sensor, &darkened(1e-3), &unclipped); + assert!(amount > 0.1, "the same pixels, measurable, would have pulled the share up: {amount}"); + + // non-finite pixels in either proxy + for i in (0..w * h).step_by(37) { + sensor.data[i] = [f32::NAN, 0.1, 0.1]; + dark_reference.data[i + 1] = [f32::INFINITY; 3]; + } + let amount = measure(&sensor, &dark_reference, &unclipped); + assert!(amount < 0.051, "non-finite pixels are left out: measured {amount}"); +} + +/// A sensor proxy of a photo turned upright gets the gain of where each pixel lands in the upright frame the lens +/// profile describes: with the optical centre off the middle, pixel (x, y) of a 96 × 64 sensor turned a quarter +/// clockwise takes the gain at (64 - y, x) of the 64 × 96 upright frame, and turned anticlockwise at (y, 96 - x). +#[test] +fn the_vignetting_gain_of_a_turned_proxy_is_taken_in_the_upright_frame() { + use lightcraft_develop::EmbeddedVignette; + use lightcraft_geom::{Orientation, Point}; + let vignette = EmbeddedVignette { k: [2.0, 1.0, 0.0, 0.0, 0.0], center: Point::new(0.3, 0.6), radius: 0.6 }; + let (w, h) = (96usize, 64usize); + let (wf, hf) = (w as f64, h as f64); + let normal = vignetting_gains(&Rgb32f::new(w, h), &vignette, ProxyFrame::new(Orientation::Normal)); + for (orientation, upright) in [ + (Orientation::Rotate90, (|x: f64, y: f64, _: f64, h: f64| (h - y, x)) as fn(f64, f64, f64, f64) -> (f64, f64)), + (Orientation::Rotate270, |x, y, w, _| (y, w - x)), + ] { + let gains = vignetting_gains(&Rgb32f::new(w, h), &vignette, ProxyFrame::new(orientation)); + let mut differ = 0; + for i in 0..w * h { + let (x, y) = upright((i % w) as f64 + 0.5, (i / w) as f64 + 0.5, wf, hf); + let expected = lightcraft_pipeline::optics::embedded_vignette_gain(&vignette, Point::new(x, y), hf, wf); + assert!((gains[i] - expected).abs() < 1e-9, "{orientation:?}, pixel {i}: {} vs {expected}", gains[i]); + differ += usize::from((gains[i] - normal[i]).abs() > 1e-3); + } + assert!(differ > w * h / 2, "{orientation:?}: the turn matters for this lens ({differ} pixels differ)"); + } +} + +/// A CR3 sensor proxy moved to its camera JPEG's framing is measured with the gain of where its pixels come from: the +/// share a JPEG with the whole correction shows is found with the framing, and missed without it. +#[test] +fn camera_vignetting_amount_follows_a_cr3_proxys_framing() { + use lightcraft_develop::EmbeddedVignette; + use lightcraft_geom::{Orientation, Point}; + let vignette = EmbeddedVignette { k: [2.0, 1.0, 0.0, 0.0, 0.0], center: Point::new(0.5, 0.5), radius: 0.6 }; + let (w, h) = (96usize, 64usize); + let framing = Cr3Framing { scale: 0.8, offset: [0.08, -0.06] }; + // a scene of unrelated brightnesses, one per sensor pixel + let scene = |x: f32, y: f32| { + let seed = (x.floor() as u32).wrapping_mul(73_856_093) ^ (y.floor() as u32).wrapping_mul(19_349_663); + 0.02 + 0.4 * (seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223) >> 8) as f32 / (1u32 << 24) as f32 + }; + // the framed proxy: pixel q shows the vignetted sensor at `framing.source(q)` + let mut sensor = Rgb32f::new(w, h); + let mut source_gains = Vec::with_capacity(w * h); + for (i, p) in sensor.data.iter_mut().enumerate() { + let (x, y) = framing.source((i % w) as f32 + 0.5, (i / w) as f32 + 0.5, w, h); + let g = lightcraft_pipeline::optics::embedded_vignette_gain(&vignette, Point::new(f64::from(x), f64::from(y)), w as f64, h as f64) as f32; + let v = scene(x, y) / g; + *p = [v, v * 0.9, v * 0.7]; + source_gains.push(g); + } + let clipped = vec![false; w * h]; + let measure = |reference: &Rgb32f, framing: Option| { + camera_vignetting_amount(&sensor, reference, &clipped, &vignette, ProxyFrame { orientation: Orientation::Normal, framing }) + }; + for shown in [0.0f32, 0.75, 1.0] { + let mut reference = sensor.clone(); + for (p, g) in reference.data.iter_mut().zip(&source_gains) { + *p = p.map(|c| (c * (1.0 + (g - 1.0) * shown)).powf(1.0 / 2.2)); + } + let framed = measure(&reference, Some(framing)); + assert!((framed - f64::from(shown)).abs() < 0.051, "the JPEG shows {shown}, measured {framed} with the framing"); + if shown == 1.0 { + let unframed = measure(&reference, None); + assert!(unframed < 0.9, "without the framing the gains are taken at the wrong places: {unframed}"); + } + } +} diff --git a/crates/engine/src/camera_profiles.rs b/crates/engine/src/camera_profiles.rs index ed6e601cd2..26386134a4 100644 --- a/crates/engine/src/camera_profiles.rs +++ b/crates/engine/src/camera_profiles.rs @@ -12,6 +12,7 @@ //! in; a damaged or hostile file is ignored with a warning. They hold aggregate colour statistics //! only, never image content. use lightcraft_color::Mat3; +use lightcraft_pipeline::tone::CameraTone; use lightcraft_raw::profile::HsvTable; use serde::{Deserialize, Serialize}; use std::collections::HashMap; @@ -50,11 +51,21 @@ pub struct CameraProfile { matrix: [[f64; 3]; 3], /// Hue/saturation/value correction after `matrix` (linear ProPhoto RGB). pub hue_sat: Option, + /// The camera's tone curve pooled over the photos (scene luminance after `matrix` → the camera JPEG's): a photo + /// follows it past what its own JPEG shows, and takes it whole when its JPEG teaches no curve. Absent in profiles + /// fitted before it existed. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub tone: Option, } impl CameraProfile { pub fn new(model: &str, files: usize, samples: usize, matrix: Mat3, hue_sat: Option) -> CameraProfile { - CameraProfile { version: VERSION, model: model.to_owned(), files, samples, matrix: matrix.0, hue_sat } + CameraProfile { version: VERSION, model: model.to_owned(), files, samples, matrix: matrix.0, hue_sat, tone: None } + } + + /// The profile with its pooled tone curve. + pub fn with_tone(self, tone: Option) -> CameraProfile { + CameraProfile { tone, ..self } } pub fn matrix(&self) -> Mat3 { @@ -263,31 +274,62 @@ fn cache_key_for(directory: Option<&Path>) -> u64 { h.finish().0 as u64 } -/// Per camera model: the photos read and their pooled colour pairs. +/// Per camera model: the photos read and their pooled colour pairs and tone samples. #[derive(Default)] pub struct Pool { - models: HashMap)>, + models: HashMap, } -/// Most colour pairs kept per photo, so a few busy photos can't dominate a profile. +#[derive(Default)] +struct Model { + /// Photos that gave colour pairs (the colour fit's photo count). + files: usize, + /// Photos that gave tone samples only (too dark or colourless for colour pairs). + tone_files: usize, + pairs: Vec<([f64; 3], [f64; 3])>, + tone: Vec<([f64; 3], f64)>, +} + +/// What [`Pool::add`] took from one raw file. +#[derive(Clone, Debug, PartialEq)] +pub struct Added { + pub model: String, + /// Whether it gave colour pairs; `false`: tone samples only, not counted toward a profile's photos. + pub colour: bool, +} + +/// Most colour pairs (and, separately, tone samples) kept per photo, so a few busy photos can't dominate a profile. const PAIRS_PER_FILE: usize = 4000; +/// Every `n`-th item, `n` chosen to keep at most [`PAIRS_PER_FILE`]. +fn thinned(items: Vec) -> impl Iterator { + let step = items.len().div_ceil(PAIRS_PER_FILE).max(1); + items.into_iter().step_by(step) +} + impl Pool { - /// Add one raw file's colour pairs. `Ok(None)` when the file can't contribute (not an ARW, - /// NEF or RAF without colour matrices, no usable camera JPEG, too little colour). - pub fn add(&mut self, bytes: &[u8]) -> Result, String> { + /// Add one raw file's colour pairs and tone samples. A photo too dark or colourless for colour pairs still gives + /// its tone samples (the shadows the pooled curve needs) without counting toward the profile's photos. `Ok(None)` + /// when the file can't contribute (not an ARW, NEF or RAF without colour matrices, no usable or a black-and-white + /// camera JPEG). + pub fn add(&mut self, bytes: &[u8]) -> Result, String> { let mut raw = lightcraft_raw::decode(bytes).map_err(|e| e.to_string())?; // colour only: geometric lens corrections would stop the sensor proxy from binning (the pairs still follow // the warp the camera applied to its JPEG) let lens = crate::camera_preview::lens_geometry(&raw.opcodes.list3); raw.opcodes.list3.retain(|op| !op.is_lens_correction()); let Some(model) = raw.metadata.model.as_deref().map(str::trim).filter(|m| !m.is_empty()) else { return Ok(None) }; - let Some(pairs) = crate::camera_preview::profile_pairs(&raw, bytes, lens.as_ref()) else { return Ok(None) }; - let step = pairs.len().div_ceil(PAIRS_PER_FILE).max(1); + let Some(samples) = crate::camera_preview::profile_samples(&raw, bytes, lens.as_ref()) else { return Ok(None) }; let entry = self.models.entry(model.to_owned()).or_default(); - entry.0 += 1; - entry.1.extend(pairs.into_iter().step_by(step)); - Ok(Some(model.to_owned())) + let colour = !samples.colour.is_empty(); + if colour { + entry.files += 1; + entry.pairs.extend(thinned(samples.colour)); + } else { + entry.tone_files += 1; + } + entry.tone.extend(thinned(samples.tone)); + Ok(Some(Added { model: model.to_owned(), colour })) } /// Fit a profile per model with at least `min_files` photos. @@ -296,26 +338,29 @@ impl Pool { models.sort_by(|a, b| a.0.cmp(b.0)); models .into_iter() - .filter(|(_, (files, _))| *files >= min_files) - .map(|(model, (files, pairs))| { - let (matrix, hue_sat) = crate::camera_preview::fit_profile(pairs).ok_or_else(|| format!("{model}: no usable colour fit"))?; - Ok(CameraProfile::new(model, *files, pairs.len(), matrix, hue_sat)) + .filter(|(_, m)| m.files >= min_files) + .map(|(model, m)| { + let (matrix, hue_sat) = crate::camera_preview::fit_profile(&m.pairs).ok_or_else(|| format!("{model}: no usable colour fit"))?; + let tone = crate::camera_preview::fit_profile_tone(&m.tone, &matrix); + Ok(CameraProfile::new(model, m.files, m.pairs.len(), matrix, hue_sat).with_tone(tone)) }) .collect() } /// Add another pool's photos and pairs (pools filled on separate threads). pub fn merge(&mut self, other: Pool) { - for (model, (files, pairs)) in other.models { + for (model, m) in other.models { let entry = self.models.entry(model).or_default(); - entry.0 += files; - entry.1.extend(pairs); + entry.files += m.files; + entry.tone_files += m.tone_files; + entry.pairs.extend(m.pairs); + entry.tone.extend(m.tone); } } /// Photos read per model. pub fn files(&self) -> Vec<(String, usize)> { - let mut v: Vec<_> = self.models.iter().map(|(m, (n, _))| (m.clone(), *n)).collect(); + let mut v: Vec<_> = self.models.iter().map(|(name, m)| (name.clone(), m.files)).collect(); v.sort(); v } @@ -355,6 +400,14 @@ mod tests { let mut p = profile(); p.version = 99; assert!(bad(p), "unknown version"); + // a pooled tone curve round-trips; a broken one (knots going backwards) is a damaged file + let toned = profile().with_tone(lightcraft_pipeline::tone::default_raw_camera_tone()); + let path = save(&toned, &dir).unwrap(); + assert_eq!(load(&path).unwrap(), toned); + let mut json: serde_json::Value = serde_json::to_value(&toned).unwrap(); + json["tone"]["knots"][3][0] = serde_json::json!(5.0); + std::fs::write(dir.join("bad.json"), serde_json::to_vec(&json).unwrap()).unwrap(); + assert!(load(&dir.join("bad.json")).is_err(), "invalid tone curve"); std::fs::write(dir.join("junk.json"), b"{not json").unwrap(); assert!(load(&dir.join("junk.json")).is_err()); assert!(load(&dir.join("missing.json")).is_err()); diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 72b2dce09a..f15576228c 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -14,6 +14,7 @@ pub mod curves; pub mod dcp_profiles; pub(crate) mod denoise; mod develop; +pub(crate) use develop::{prepare_photo_for_wb_partial, wb_partial_names_one_field}; mod edit; mod export; pub(crate) mod face_detect; diff --git a/crates/engine/src/cmd/activity.rs b/crates/engine/src/cmd/activity.rs index ed4e8d35c7..3fa99b488a 100644 --- a/crates/engine/src/cmd/activity.rs +++ b/crates/engine/src/cmd/activity.rs @@ -11,7 +11,7 @@ pub fn specs() -> Vec { "Background Tasks", [], None, - "{} → {tasks: [{id, kind, label, done, total, unit: count|bytes|percent, detail, cancellable, cancelling, ageMs}]} — the long-running tasks in flight (imports, exports, preview builds, downloads, the face scan…), oldest first; total 0 = not known yet", + "{} → {tasks: [{id, kind, label, done, total, unit: count|bytes|percent, detail, cancellable, cancelling, ageMs, waiting, place, lane}]} — the long-running tasks in flight (imports, exports, preview builds, downloads, the face scan…), oldest first, then those waiting in line for a task of their lane (waiting: true, place: 1 = next in its lane, lane: previews; done and total 0); total 0 = not known yet", always, |s, _| Ok(json!({"tasks": s.activity.list()})) ), @@ -20,7 +20,7 @@ pub fn specs() -> Vec { "Cancel Background Task", [], None, - "{id} | {all: true} → {cancelled: n} — ask a task (or every cancellable task) to stop; it stops at its next file or photo (a preview build also stops between a photo's own previews). An unknown id (it may have just finished) or a task that can't be cancelled is an error", + "{id} | {all: true} → {cancelled: n} — ask a task (or every cancellable task) to stop; it stops at its next file or photo (a preview build also stops between a photo's own previews). A task waiting in line is taken out of it and never runs; all also empties the line. An unknown id (it may have just finished) or a task that can't be cancelled is an error", always, |s, p| { const C: &str = "activity.cancel"; diff --git a/crates/engine/src/cmd/before.rs b/crates/engine/src/cmd/before.rs index a6de32c46e..62cad69e81 100644 --- a/crates/engine/src/cmd/before.rs +++ b/crates/engine/src/cmd/before.rs @@ -80,28 +80,16 @@ pub fn specs() -> Vec { has_active, set_before ), - cmd!( - "beforeAfter.copyAfterToBefore", - "Copy After's Settings to Before", - ["View", "Before/After Settings"], - None, - "{}", - has_active, - |s, _| { set_before(s, &json!({"source": "current"})) } - ), - cmd!( - "beforeAfter.copyBeforeToAfter", - "Copy Before's Settings to After", - ["View", "Before/After Settings"], - None, - "{}", - has_active, - |s, _| { before_to_after(s, false) } - ), - cmd!("beforeAfter.swap", "Swap Before and After Settings", ["View", "Before/After Settings"], None, "{}", has_active, |s, _| { + cmd!("beforeAfter.copyAfterToBefore", "Copy After's Settings to Before", ["View", "Before/After"], None, "{}", has_active, |s, _| { + set_before(s, &json!({"source": "current"})) + }), + cmd!("beforeAfter.copyBeforeToAfter", "Copy Before's Settings to After", ["View", "Before/After"], None, "{}", has_active, |s, _| { + before_to_after(s, false) + }), + cmd!("beforeAfter.swap", "Swap Before and After Settings", ["View", "Before/After"], None, "{}", has_active, |s, _| { before_to_after(s, true) }), - cmd!("beforeAfter.resetBefore", "Reset Before to Import State", ["View", "Before/After Settings"], None, "{}", has_active, |s, _| { + cmd!("beforeAfter.resetBefore", "Reset Before to Import State", ["View", "Before/After"], None, "{}", has_active, |s, _| { set_before(s, &json!({"source": "import"})) }), ] diff --git a/crates/engine/src/cmd/browse.rs b/crates/engine/src/cmd/browse.rs index 470b00bbd9..685fcb16b6 100644 --- a/crates/engine/src/cmd/browse.rs +++ b/crates/engine/src/cmd/browse.rs @@ -10,7 +10,7 @@ //! browse also forgets at once the untouched records of the folder's files that are gone from //! the disk (deleted or moved by another app), so the folder shows what is on disk. -use std::path::Path; +use std::path::{Path, PathBuf}; use lightcraft_catalog::query::in_folder; use lightcraft_catalog::{Op, PhotoId, Source}; @@ -261,6 +261,7 @@ pub fn specs() -> Vec { |s, p| { let from = str_param(p, "path").ok_or_else(|| bad("folder.rename", "missing path"))?.trim_end_matches(['/', '\\']).to_string(); refuse_protected_place("folder.rename", &from)?; + let from = rewrite_case_only_library_path(s, &from); let name = str_param(p, "name") .map(str::trim) .filter(|n| !n.is_empty() && !n.contains(['/', '\\']) && *n != "." && *n != "..") @@ -280,9 +281,11 @@ pub fn specs() -> Vec { |s, p| { let from = str_param(p, "path").ok_or_else(|| bad("folder.move", "missing path"))?.trim_end_matches(['/', '\\']).to_string(); refuse_protected_place("folder.move", &from)?; + let from = rewrite_case_only_library_path(s, &from); let into = str_param(p, "into").ok_or_else(|| bad("folder.move", "missing into"))?; + let into = spelling_in_open_library(s, into, false).map_err(|e| bad("folder.move", e))?; let name = Path::new(&from).file_name().ok_or_else(|| bad("folder.move", "bad path"))?; - let to = Path::new(into).join(name).to_string_lossy().to_string(); + let to = Path::new(&into).join(name).to_string_lossy().to_string(); let n = move_folder(s, &from, &to).map_err(|e| bad("folder.move", e))?; Ok(json!({"path": to, "relinked": n})) } @@ -481,20 +484,29 @@ fn move_to_folder(s: &mut Session, p: &Value) -> Result { Ok(json!({"moved": n, "folder": folder})) } +/// Names below `from` in `path`. Letter case is ignored only when `fold_case` is set (a folder inside the open +/// library, whose prefix may be stored with a different spelling). Other folders keep an exact match, so +/// `/work/trip` is not `/work/Trip` on a case-sensitive volume. +fn rest_under(path: &Path, from: &Path, fold_case: bool) -> Option { + path.strip_prefix(from).ok().map(|rel| rel.to_path_buf()).or_else(|| fold_case.then(|| strip_prefix_ignore_case(path, from)).flatten()) +} + /// After a folder moved from `from` to `to`: a browsed folder at or below it follows. pub(crate) fn follow_folder(s: &mut Session, from: &str, to: &str) { // a library folder chosen at or below it follows too, as a source or as a filter - follow_library_folder(&mut s.library_folder, from, to); - follow_library_folder(&mut s.filter.library_folder, from, to); - follow_library_folder(&mut s.filter.folder, from, to); + // letter case in a library prefix may differ; a folder outside the library is matched as written + let fold_case = s.library.as_ref().is_some_and(|l| Path::new(from).starts_with(&l.dir)); + follow_library_folder(&mut s.library_folder, from, to, fold_case); + follow_library_folder(&mut s.filter.library_folder, from, to, fold_case); + follow_library_folder(&mut s.filter.folder, from, to, fold_case); if let Some(f) = s.shelved_filter.as_mut() { - follow_library_folder(&mut f.library_folder, from, to); - follow_library_folder(&mut f.folder, from, to); + follow_library_folder(&mut f.library_folder, from, to, fold_case); + follow_library_folder(&mut f.folder, from, to, fold_case); } if let Some(b) = &mut s.browse - && let Ok(rel) = Path::new(&b.path).strip_prefix(from) + && let Some(rel) = rest_under(Path::new(&b.path), Path::new(from), fold_case) { - b.path = Path::new(to).join(rel).to_string_lossy().to_string(); + b.path = if rel.as_os_str().is_empty() { to.to_string() } else { Path::new(to).join(rel).to_string_lossy().to_string() }; // with filters off the filter stays empty: Cmd+L brings back the one put aside if s.shelved_filter.is_none() { let f = b.path.clone(); @@ -506,40 +518,208 @@ pub(crate) fn follow_folder(s: &mut Session, from: &str, to: &str) { /// A chosen library folder at or below `from` becomes the same place below `to`. Compared the /// way the filter does, by folder identity, so a differently spelled choice is not widened to /// the folder itself. -fn follow_library_folder(chosen: &mut Option, from: &str, to: &str) { +fn follow_library_folder(chosen: &mut Option, from: &str, to: &str, fold_case: bool) { let Some(c) = chosen.as_deref() else { return }; - if let Some(rest) = lightcraft_catalog::query::folder_rest(c, from) { + let rest = lightcraft_catalog::query::folder_rest(c, from).or_else(|| { + fold_case + .then(|| rest_under(Path::new(c), Path::new(from), true).map(|rel| rel.iter().map(|n| n.to_string_lossy().into_owned()).collect())) + .flatten() + }); + if let Some(rest) = rest { // joined by the platform, so the result is spelled like `to` and like a path read from disk - *chosen = Some(rest.iter().fold(std::path::PathBuf::from(to), |p, name| p.join(name)).to_string_lossy().to_string()); + *chosen = Some(rest.iter().fold(PathBuf::from(to), |p, name| p.join(name)).to_string_lossy().to_string()); } } +/// The library's own spelling of `path` when it differs only in letter case. A path that only reaches the library +/// through a link is left as given, so the caller can refuse the library's own folders first and then the link. +fn rewrite_case_only_library_path(s: &Session, path: &str) -> String { + match spelling_in_open_library(s, path, true) { + Ok(spelled) => spelled, + Err(_) => path.to_string(), + } +} + +/// If `path` is a folder inside the open library, the same folder spelled the way the library stores it. Letter +/// case in the library prefix is ignored (`LIB/Originals/day` is `lib/Originals/day`). When `refuse_link` is set +/// (the path being renamed or moved), a path that only reaches the library through a link or a junction is +/// refused; a destination that may not exist yet is only rewritten when it is the library's path with letter +/// case changed. +fn spelling_in_open_library(s: &Session, path: &str, refuse_link: bool) -> std::result::Result { + let Some(lib) = s.library.as_ref().map(|l| l.dir.clone()) else { + return Ok(path.to_string()); + }; + let src = Path::new(path); + let (lib_on_disk, chosen) = (lib.canonicalize().unwrap_or_else(|_| lib.clone()), src.canonicalize().unwrap_or_else(|_| src.to_path_buf())); + let inside_on_disk = chosen.starts_with(&lib_on_disk); + let as_library = library_spelling(src, &lib); + let refused = || format!("{path}: give the folder's path inside the library as {}", lib.display()); + if inside_on_disk { + if src.starts_with(&lib) { + return Ok(path.to_string()); + } + if let Some(spelled) = as_library { + if refuse_link && foreign_link_in_library_prefix(src, &lib) { + return Err(refused()); + } + return Ok(spelled.to_string_lossy().into_owned()); + } + if refuse_link { + return Err(refused()); + } + return Ok(path.to_string()); + } + // a destination that may not exist yet: rewrite only when its library-length prefix is the open library on disk + // (on a case-sensitive volume, `LIB` can be a different folder and must be left alone) + Ok(match as_library { + Some(spelled) if !refuse_link && prefix_is_the_open_library(src, &lib) => spelled.to_string_lossy().into_owned(), + _ => path.to_string(), + }) +} + +/// `path` as `root` plus the names below it, when they share a prefix if letter case is ignored. +fn library_spelling(path: &Path, root: &Path) -> Option { + if !path_starts_with_ignore_case(path, root) { + return None; + } + Some(path.components().skip(root.components().count()).fold(root.to_path_buf(), |p, c| p.join(c))) +} + +/// Whether `path` lies at or under `root` when each component is compared in Unicode lowercase. +fn path_starts_with_ignore_case(path: &Path, root: &Path) -> bool { + let fold = |c: std::path::Component<'_>| c.as_os_str().to_string_lossy().to_lowercase(); + let root: Vec<_> = root.components().map(fold).collect(); + let path: Vec<_> = path.components().map(fold).collect(); + path.starts_with(&root) +} + +/// The names below `prefix` in `path`, when they share a prefix if letter case is ignored. +fn strip_prefix_ignore_case(path: &Path, prefix: &Path) -> Option { + path.strip_prefix(prefix) + .ok() + .map(|rel| rel.to_path_buf()) + .or_else(|| path_starts_with_ignore_case(path, prefix).then(|| path.components().skip(prefix.components().count()).collect())) +} + +/// Whether the library-length prefix of `path` is, on disk, the open library (following links). A missing prefix is +/// not the library; a different directory whose name only differs in letter case is not either. +fn prefix_is_the_open_library(path: &Path, lib: &Path) -> bool { + if !path_starts_with_ignore_case(path, lib) { + return false; + } + let prefix: PathBuf = path.components().take(lib.components().count()).collect(); + matches!((prefix.canonicalize(), lib.canonicalize()), (Ok(a), Ok(b)) if a == b) +} + +fn is_link(path: &Path) -> bool { + std::fs::symlink_metadata(path).is_ok_and(|meta| meta.file_type().is_symlink() || is_reparse_point(&meta)) +} + +#[cfg(windows)] +fn is_reparse_point(meta: &std::fs::Metadata) -> bool { + use std::os::windows::fs::MetadataExt; + const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x400; + meta.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0 +} + +#[cfg(not(windows))] +fn is_reparse_point(_meta: &std::fs::Metadata) -> bool { + false +} + +fn same_dir_entry(a: &Path, b: &Path) -> bool { + match (std::fs::symlink_metadata(a), std::fs::symlink_metadata(b)) { + (Ok(am), Ok(bm)) => { + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + am.dev() == bm.dev() && am.ino() == bm.ino() + } + #[cfg(windows)] + { + // std's volume serial / file index on Metadata needs nightly `windows_by_handle` (see opened_folder.rs) + let _ = (am, bm); + let a = std::path::absolute(a).unwrap_or_else(|_| a.to_path_buf()); + let b = std::path::absolute(b).unwrap_or_else(|_| b.to_path_buf()); + path_starts_with_ignore_case(&a, &b) && path_starts_with_ignore_case(&b, &a) + } + #[cfg(not(any(unix, windows)))] + { + let _ = (am, bm); + a == b + } + } + _ => a == b, + } +} + +/// Whether `src` walks through a link that is not the library's own path. The check covers every +/// component, including those below the library root, so a distinct `LIB` folder whose `Originals` +/// is a link into the library is refused. A differently-cased spelling of the same folder is not a +/// different path. +fn foreign_link_in_library_prefix(src: &Path, lib: &Path) -> bool { + let lib_comps: Vec<_> = lib.components().collect(); + let src_comps: Vec<_> = src.components().collect(); + if src_comps.len() < lib_comps.len() { + return false; + } + let mut src_p = PathBuf::new(); + let mut lib_p = PathBuf::new(); + for (i, s) in src_comps.iter().enumerate() { + src_p.push(*s); + if i < lib_comps.len() { + lib_p.push(lib_comps[i]); + } else { + lib_p.push(*s); + } + if is_link(&src_p) && !same_dir_entry(&src_p, &lib_p) { + return true; + } + } + false +} + /// Rename or move a folder on disk (everything in it goes along, sidecars included) and relink /// the photos inside, as one undo step: undo renames the folder back and restores the photos' /// paths, redo repeats the move — each refused (and reported) when the destination is taken. pub(crate) fn move_folder(s: &mut Session, from: &str, to: &str) -> std::result::Result { - let (src, dst) = (Path::new(from), Path::new(to)); + let src = Path::new(from); if !src.is_dir() { return Err(format!("{from} is not a folder")); } - // compared as the folders are on disk (a differently spelled or linked path to the library - // names the same folder), with the spelling as a fallback where that can't be told + // `a/../b` names a folder without spelling it, which the checks below and the relink can't see + if src.components().any(|c| matches!(c, std::path::Component::ParentDir)) { + return Err(format!("{from}: give the folder's path without '..'")); + } + // the library folder itself (and its parents), and its own top-level folders (`Originals`, `thumbs`), stay + // where the library expects them; folders below those (an import's date folders) can be renamed. Compared as + // the folders are on disk (a differently spelled or linked path to the library names the same folder), with + // the spelling as a fallback where that can't be told let same_folder = |l: &Path| { let (lib, chosen) = (l.canonicalize().unwrap_or_else(|_| l.to_path_buf()), src.canonicalize().unwrap_or_else(|_| src.to_path_buf())); - lib.starts_with(&chosen) || chosen.starts_with(&lib) || l.starts_with(src) || src.starts_with(l) + lib.starts_with(&chosen) || chosen.parent() == Some(lib.as_path()) || l.starts_with(src) || src.parent() == Some(l) }; if s.library.as_ref().is_some_and(|l| same_folder(&l.dir)) { return Err("the library's own folders can't be moved here".into()); } + // a folder inside the library reached through a link would move on disk, but its photos are stored under the + // library's own spelling, so the relink below couldn't find them. A path that differs only in letter case is + // the library's own folder: rewrite it so relink matches, and do the same for the destination. + let from = spelling_in_open_library(s, from, true)?; + let to = spelling_in_open_library(s, to, false)?; + let (src, dst) = (Path::new(&from), Path::new(&to)); // Repairs retain their exact old paths, including those on surviving history entries. // Complete them before the directory moves; an unavailable repair leaves it in place. s.repair_sidecars_with(&crate::rename::RealFs).map_err(|e| e.to_string())?; - rename_folder_on_disk(from, to)?; + rename_folder_on_disk(&from, &to)?; let mut ops: Vec = s .catalog .photos() .filter_map(|p| match &p.source { - lightcraft_catalog::Source::File { path } => Path::new(path).strip_prefix(src).ok().map(|rel| (p.id, p.file_name.clone(), dst.join(rel))), + lightcraft_catalog::Source::File { path } => { + let fold_case = s.library.as_ref().is_some_and(|l| src.starts_with(&l.dir)); + rest_under(Path::new(path), src, fold_case).map(|rel| (p.id, p.file_name.clone(), dst.join(rel))) + } _ => None, }) .map(|(id, file_name, np)| Op::Relink { @@ -551,17 +731,21 @@ pub(crate) fn move_folder(s: &mut Session, from: &str, to: &str) -> std::result: .collect(); let n = ops.len(); // what the library knows about the folder (and those inside it) goes along, in the same step - ops.extend(s.catalog.folder_records_follow(from, to)); - let name = Path::new(to).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default(); + ops.extend(s.catalog.folder_records_follow(&from, &to)); + let name = Path::new(&to).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default(); let renamed = src.parent() == dst.parent(); let label = if renamed { format!("Rename Folder to “{name}”") } else { format!("Move Folder “{name}”") }; let folder = crate::FolderMove { from: to.to_string(), to: from.to_string(), on_disk: true }; if let Err(e) = s.commit_with_folder(&label, Op::Batch { ops }, folder) { + if matches!(e, crate::EngineError::Catalog(lightcraft_catalog::CatalogError::PartlyApplied { .. })) { + // part of it stays, and the undo step that takes it back renames the folder: it stays where it is + return Err(e.to_string()); + } // the catalog didn't take it: put the folder back where the photos still point - let back = rename_folder_on_disk(to, from).err().map(|b| format!("; moving it back failed too: {b}")).unwrap_or_default(); + let back = rename_folder_on_disk(&to, &from).err().map(|b| format!("; moving it back failed too: {b}")).unwrap_or_default(); return Err(format!("{e}{back}")); } - follow_folder(s, from, to); + follow_folder(s, &from, &to); Ok(n) } @@ -639,8 +823,43 @@ fn refuse_protected_place_in(command: &str, from: &str, home: Option<&Path>) -> #[cfg(test)] mod tests { - use super::{is_protected_place, refuse_protected_place_in}; - use std::path::Path; + use super::{is_protected_place, library_spelling, path_starts_with_ignore_case, refuse_protected_place_in, strip_prefix_ignore_case}; + use std::path::{Path, PathBuf}; + + #[test] + fn a_path_that_differs_only_in_letter_case_is_the_librarys_spelling() { + let lib = Path::new("/Users/Foo/Pictures/Lib"); + let src = Path::new("/users/foo/pictures/lib/Originals/2026-10-16"); + assert!(path_starts_with_ignore_case(src, lib), "case-folded components match"); + assert!(!src.starts_with(lib), "Path::starts_with is case-sensitive: this is the refusal #3016 got wrong"); + let spelled = library_spelling(src, lib).expect("rewritten under the library's own path"); + assert_eq!(spelled, Path::new("/Users/Foo/Pictures/Lib/Originals/2026-10-16")); + // Unicode case folding (É / é), so a typographic capital is not a different folder + let cafe = Path::new("/data/Café/Originals/day"); + assert!(path_starts_with_ignore_case(cafe, Path::new("/data/CAFÉ"))); + assert_eq!(library_spelling(cafe, Path::new("/data/CAFÉ")).unwrap(), Path::new("/data/CAFÉ/Originals/day")); + } + + #[test] + fn strip_prefix_ignore_case_keeps_the_names_below_a_flipped_prefix() { + let rel = strip_prefix_ignore_case( + Path::new("/users/foo/pictures/lib/Originals/2026-10-16/a.jpg"), + Path::new("/Users/Foo/Pictures/Lib/Originals/2026-10-16"), + ) + .expect("case-folded prefix matches"); + assert_eq!(rel, PathBuf::from("a.jpg")); + assert!(strip_prefix_ignore_case(Path::new("/Users/Foo/Pictures/lib-link/day"), Path::new("/Users/Foo/Pictures/Lib")).is_none()); + } + + #[test] + fn a_linked_spelling_is_not_the_librarys_own_path() { + let lib = Path::new("/Users/Foo/Pictures/Lib"); + let linked = Path::new("/Users/Foo/Pictures/lib-link/Originals/2026-10-16"); + assert!(!path_starts_with_ignore_case(linked, lib)); + assert!(library_spelling(linked, lib).is_none()); + // a different prefix must not match as a string prefix of a component + assert!(!path_starts_with_ignore_case(Path::new("/Users/Foo/Pictures/Library/day"), lib)); + } #[test] fn the_home_folder_and_its_standard_places_are_protected() { diff --git a/crates/engine/src/cmd/color.rs b/crates/engine/src/cmd/color.rs index 111159e7a2..3fef87a274 100644 --- a/crates/engine/src/cmd/color.rs +++ b/crates/engine/src/cmd/color.rs @@ -129,16 +129,26 @@ fn targeted(s: &mut Session, p: &Value) -> Result { } } "hue" | "sat" | "lum" => { - // the hue the colour mixer sees there (the mixer and everything after it neutralized) + // (a B&W profile, as the Color Mixer panel shows it: its B&W mix) + let bw = d.treatment == Treatment::Bw || d.profile.id == "lc.mono" || d.profile.id.starts_with("lc.bw."); + // the hue the colour mixer sees there (the mixer and everything after it neutralized); the B&W mix + // comes after the mixer, so for it the mixer's own adjustments stay let e = probe(s, c, x, y, |d| { - d.mixer = Default::default(); + if !bw { + d.mixer = Default::default(); + } + // (a B&W profile turns the render grey again: sample the source colour, with the profile's own + // adjustments before the mixer, its contrast say, and its other options kept) + if d.profile.id == "lc.mono" || d.profile.id.starts_with("lc.bw.") { + *d = lightcraft_pipeline::profiles::effective(d).into_owned(); + d.profile.id = "lc.color".into(); + } d.bw_mix = Default::default(); after_mixer_neutral(d); })?; let [_, _, h] = encoded_to_oklch(e); let w = lightcraft_pipeline::colorops::band_weights(h); let top = w.iter().cloned().fold(0.0f32, f32::max).max(1e-6); - let bw = d.treatment == Treatment::Bw || d.profile.id == "lc.mono"; label = if bw { "B&W Mix" } else { "Color Mixer" }; for (i, band) in MIXER_BANDS.iter().enumerate() { let k = (w[i] / top) as f64; diff --git a/crates/engine/src/cmd/convert.rs b/crates/engine/src/cmd/convert.rs index af81d3cae4..cf0991f4e3 100644 --- a/crates/engine/src/cmd/convert.rs +++ b/crates/engine/src/cmd/convert.rs @@ -294,7 +294,7 @@ fn legacy_shutter_text(t: f64) -> Option { /// what import gave it, the lens correction is turned on as import would; an edited photo keeps /// its settings. pub(crate) fn lens_ops(id: lightcraft_catalog::PhotoId, ph: &lightcraft_catalog::Photo, info: &crate::media::ProbeInfo) -> Vec { - if info.embedded_lens == ph.embedded_lens { + if info.embedded_lens.as_ref() == ph.embedded_lens.as_deref() { return Vec::new(); } let mut ops = vec![Op::SetEmbeddedLens { id, lens: info.embedded_lens.map(Box::new) }]; @@ -601,7 +601,7 @@ mod tests { c.apply(op).unwrap(); } let after = c.photo(lightcraft_catalog::PhotoId(1)).unwrap(); - assert_eq!(after.embedded_lens, Some(lens())); + assert_eq!(after.embedded_lens, Some(Box::new(lens()))); assert!(!after.is_edited()); assert_eq!(*after.develop, after.camera_defaults()); assert!(lens_ops(after.id, after, &info).is_empty(), "nothing more to do the second time"); @@ -622,7 +622,7 @@ mod tests { #[test] fn reload_leaves_a_photo_whose_user_switched_the_correction_off_alone() { let mut ph = old_rw2(); - ph.embedded_lens = Some(lens()); + ph.embedded_lens = Some(Box::new(lens())); let mut d = ph.camera_defaults(); d.optics.lens_profile = false; ph.develop = std::sync::Arc::new(d); diff --git a/crates/engine/src/cmd/cull.rs b/crates/engine/src/cmd/cull.rs index 664683a513..325b7ffb52 100644 --- a/crates/engine/src/cmd/cull.rs +++ b/crates/engine/src/cmd/cull.rs @@ -29,10 +29,14 @@ fn analyze(s: &mut Session, p: &Value) -> Result { let reject_below = p.get("rejectBelow").and_then(Value::as_f64).map(|v| v as f32); let pick_best = p.get("pickBest").and_then(Value::as_bool).unwrap_or(false); let (gap, same) = burst_params(p)?; - let stack_groups = match p.get("stackGroups") { - None | Some(Value::Null) => false, - Some(v) => v.as_bool().ok_or_else(|| super::bad("photo.analyze", "`stackGroups` must be true or false"))?, + let flag_param = |key: &str| -> Result { + match p.get(key) { + None | Some(Value::Null) => Ok(false), + Some(v) => v.as_bool().ok_or_else(|| super::bad("photo.analyze", format!("`{key}` must be true or false"))), + } }; + let stack_groups = flag_param("stackGroups")?; + let reset = flag_param("resetBursts")?; // measure (thumbnail-level sources: fast, and enough for focus at 512 px) let mut rows: Vec<(PhotoId, Option, f32, f32, [f32; 64])> = Vec::new(); let mut failed = Vec::new(); @@ -48,17 +52,25 @@ fn analyze(s: &mut Session, p: &Value) -> Result { } // bursts: consecutive (by capture time) look-alike shots rows.sort_by_key(|r| (r.1.unwrap_or(i64::MAX), r.0)); + // A photo whose burst was arranged by hand keeps it (burst, place, pick): only its scores + // are measured again. The others are grouped among themselves, in bursts numbered after + // every burst that stays (earlier runs on other photos, the ones arranged by hand). + let by_hand = |id: PhotoId| -> Option { s.catalog.photo(id).and_then(|p| p.analysis).filter(|a| !reset && a.by_hand()) }; + let kept: Vec> = rows.iter().map(|r| by_hand(r.0)).collect(); + let auto: Vec = (0..rows.len()).filter(|i| kept[*i].is_none()).collect(); + let regrouped: std::collections::HashSet = auto.iter().map(|i| rows[*i].0).collect(); + let mut next = s.catalog.photos().filter(|p| !regrouped.contains(&p.id)).filter_map(|p| p.analysis.and_then(|a| a.group)).max().unwrap_or(0) + 1; let mut group_of: Vec> = vec![None; rows.len()]; - let mut next = 1u32; - for i in 1..rows.len() { - let (a, b) = (&rows[i - 1], &rows[i]); + for w in auto.windows(2) { + let (i, j) = (w[0], w[1]); + let (a, b) = (&rows[i], &rows[j]); let close = matches!((a.1, b.1), (Some(x), Some(y)) if (y.saturating_sub(x)).unsigned_abs() as f64 <= gap); if close && lightcraft_pipeline::cull::similarity(&a.4, &b.4) >= same { - let g = *group_of[i - 1].get_or_insert_with(|| { + let g = *group_of[i].get_or_insert_with(|| { next += 1; next - 1 }); - group_of[i] = Some(g); + group_of[j] = Some(g); } } let mut best: std::collections::HashMap = Default::default(); @@ -74,9 +86,16 @@ fn analyze(s: &mut Session, p: &Value) -> Result { let (mut rejected, mut picked) = (0, 0); let mut out = Vec::new(); for (i, (id, _, sharp, clip, _)) in rows.iter().enumerate() { - let g = group_of[i]; - let is_best = g.is_some_and(|g| best.get(&g).is_some_and(|b| b.0 == i)); - ops.push(Op::SetAnalysis { id: *id, analysis: Some(Analysis { sharpness: *sharp, clipped: *clip, group: g, best: is_best }) }); + let analysis = match kept[i] { + Some(k) => Analysis { sharpness: *sharp, clipped: *clip, ..k }, + None => { + let g = group_of[i]; + let is_best = g.is_some_and(|g| best.get(&g).is_some_and(|b| b.0 == i)); + Analysis { sharpness: *sharp, clipped: *clip, group: g, best: is_best, rank: None } + } + }; + let (g, is_best) = (analysis.group, analysis.best); + ops.push(Op::SetAnalysis { id: *id, analysis: Some(analysis) }); let flag = s.catalog.photo(*id).map(|p| p.flag).unwrap_or_default(); if reject_below.is_some_and(|t| *sharp < t) && flag != Flag::Reject { ops.push(Op::SetFlag { id: *id, flag: Flag::Reject }); @@ -85,29 +104,49 @@ fn analyze(s: &mut Session, p: &Value) -> Result { ops.push(Op::SetFlag { id: *id, flag: Flag::Pick }); picked += 1; } - out.push(json!({"id": id.0, "sharpness": (sharp * 10.0).round() / 10.0, "clipped": clip, "group": g, "best": is_best})); + out.push(json!({"id": id.0, "sharpness": (sharp * 10.0).round() / 10.0, "clipped": clip, "group": g, "best": is_best, "byHand": kept[i].is_some()})); } let mut stacks = 0; if stack_groups { // Photos already in a stack stay where they are (like `stack.auto`): a burst is stacked - // from its other photos when two or more remain, with the sharpest of those on top. + // from its other photos when two or more remain. A burst culling grouped has the sharpest + // of those on top; a burst arranged by hand keeps its order, its pick (place 0) on top. let index = s.catalog.stack_index(); let mut members: std::collections::BTreeMap> = Default::default(); - for (i, g) in group_of.iter().enumerate() { - if let (Some(g), Some(r)) = (g, rows.get(i)) - && !index.contains_key(&r.0) - && s.catalog.photo(r.0).is_some_and(|ph| !ph.deleted) - { - members.entry(*g).or_default().push((r.0, r.2)); + let mut arranged: std::collections::BTreeMap> = Default::default(); + for (i, r) in rows.iter().enumerate() { + if index.contains_key(&r.0) || !s.catalog.photo(r.0).is_some_and(|ph| !ph.deleted) { + continue; + } + match kept[i] { + Some(k) => { + if let Some(g) = k.group { + arranged.entry(g).or_default().push((k.rank.unwrap_or(u32::MAX), r.0)); + } + } + None => { + if let Some(g) = group_of[i] { + members.entry(g).or_default().push((r.0, r.2)); + } + } } } + let mut orders: Vec> = Vec::new(); for group in members.values() { let Some(top) = group.iter().fold(None::<(PhotoId, f32)>, |b, m| if b.is_none_or(|b| m.1 > b.1) { Some(*m) } else { b }) else { continue; }; - let photos: Vec = group.iter().map(|m| m.0).collect(); + let mut photos = vec![top.0]; + photos.extend(group.iter().map(|m| m.0).filter(|p| *p != top.0)); + orders.push(photos); + } + for group in arranged.values_mut() { + group.sort(); + orders.push(group.iter().map(|m| m.1).collect()); + } + for photos in orders { if photos.len() >= 2 - && let Some(op) = s.catalog.group_ops(top.0, &photos, true) + && let Some(op) = s.catalog.group_ops(photos[0], &photos, true) { ops.push(op); stacks += 1; @@ -118,22 +157,188 @@ fn analyze(s: &mut Session, p: &Value) -> Result { s.commit("Assisted Culling", Op::Batch { ops })?; } if stacks > 0 { - // a photo now hidden inside a collapsed stack must not stay the active one: its stack's - // top takes over, and the rest of the selection (what was culled) stays selected - let vis = s.visible_cloned(); - if let Some(a) = s.selection.active - && !vis.contains(&a) - && let Some(st) = s.catalog.stack_of(a) - { - let top = vis.iter().copied().find(|p| st.photos.contains(p)).unwrap_or(st.top()); - s.selection.ids.retain(|id| vis.contains(id)); - if !s.selection.ids.contains(&top) { - s.selection.ids.push(top); + keep_active_shown(s); + } + let kept = kept.iter().filter(|k| k.is_some()).count(); + Ok(json!({"photos": out, "groups": best.len(), "kept": kept, "stacks": stacks, "rejected": rejected, "picked": picked, "failed": failed})) +} + +/// A photo now hidden inside a collapsed stack must not stay the active one: its stack's top +/// takes over, and the rest of the selection stays selected. +fn keep_active_shown(s: &mut Session) { + let vis = s.visible_cloned(); + if let Some(a) = s.selection.active + && !vis.contains(&a) + && let Some(st) = s.catalog.stack_of(a) + { + let top = vis.iter().copied().find(|p| st.photos.contains(p)).unwrap_or(st.top()); + s.selection.ids.retain(|id| vis.contains(id)); + if !s.selection.ids.contains(&top) { + s.selection.ids.push(top); + } + s.selection.active = Some(top); + } +} + +/// Where `photo.moveToBurst` puts the photos. +#[derive(Clone, Copy, PartialEq)] +enum Dest { + Burst(u32), + New, + Nowhere, +} + +/// Arrange bursts by hand: `ids` go into a burst at `index` (0 = the pick), into a new burst, or +/// out of every burst. Every burst touched is then arranged by hand ([`Analysis::rank`]), so +/// culling run again keeps it. What marks a burst's pick follows its first photo: `best` (the +/// Best of Similar Shots rule), the Pick flag when culling's pick had it, and the top of the +/// burst's stack when the burst is stacked. One undo step. +fn move_to_burst(s: &mut Session, p: &Value) -> Result { + use std::collections::{BTreeMap, HashMap}; + const C: &str = "photo.moveToBurst"; + let mut ids = s.targets(p)?; + let mut seen = std::collections::HashSet::new(); + ids.retain(|id| seen.insert(*id)); + if ids.is_empty() { + return Err(super::bad(C, "no photos")); + } + for id in &ids { + match s.catalog.photo(*id) { + Some(ph) if ph.deleted => return Err(super::bad(C, format!("“{}” is deleted", ph.file_name))), + Some(ph) if ph.analysis.is_none() => { + return Err(super::bad(C, format!("“{}” has no culling scores yet: run Assisted Culling on it first", ph.file_name))); } - s.selection.active = Some(top); + Some(_) => {} + None => return Err(super::bad(C, format!("no photo {}", id.0))), } } - Ok(json!({"photos": out, "groups": best.len(), "stacks": stacks, "rejected": rejected, "picked": picked, "failed": failed})) + let group = |s: &Session, id: PhotoId| s.catalog.photo(id).and_then(|p| p.analysis).and_then(|a| a.group); + let index = s.catalog.burst_index(); + let into = match p.get("burst") { + None => Dest::Burst(group(s, ids[0]).ok_or_else(|| super::bad(C, "the photo isn't in a burst: say which `burst` it goes to"))?), + Some(Value::Null) => Dest::Nowhere, + Some(Value::String(n)) if n == "new" => Dest::New, + Some(v) => match v.as_u64().and_then(|n| u32::try_from(n).ok()) { + Some(n) if index.contains_key(&n) => Dest::Burst(n), + Some(n) => return Err(super::bad(C, format!("there is no burst {n}"))), + None => return Err(super::bad(C, "`burst` must be a burst number, \"new\" or null")), + }, + }; + let at = match p.get("index") { + None | Some(Value::Null) => usize::MAX, + Some(v) => v.as_u64().map(|n| n as usize).ok_or_else(|| super::bad(C, "`index` must be a place in the burst: 0 (the pick), 1, …"))?, + }; + // the bursts touched, before and after + let target = match into { + Dest::Burst(g) => Some(g), + Dest::New => Some(s.catalog.next_burst_id()), + Dest::Nowhere => None, + }; + let mut old: BTreeMap> = BTreeMap::new(); + for g in ids.iter().filter_map(|id| group(s, *id)).chain(target) { + old.entry(g).or_insert_with(|| index.get(&g).cloned().unwrap_or_default()); + } + let mut new = old.clone(); + for members in new.values_mut() { + members.retain(|m| !ids.contains(m)); + } + if let Some(g) = target { + let members = new.entry(g).or_default(); + let at = at.min(members.len()); + members.splice(at..at, ids.iter().copied()); + } + // each photo's burst, place and pick: a burst a move leaves with one photo is no burst (the + // burst moved into stays one, so a new burst may start with one photo for more to join) + let remains = |g: u32, members: &Vec| members.len() >= 2 || (target == Some(g) && !members.is_empty()); + let mut placed: HashMap, u32, bool)> = ids.iter().map(|id| (*id, (None, 0, false))).collect(); + for (g, members) in &new { + let stays = remains(*g, members); + for (i, m) in members.iter().enumerate() { + placed.insert(*m, if stays { (Some(*g), i as u32, i == 0) } else { (None, 0, false) }); + } + } + let mut ops = Vec::new(); + let mut by_id: Vec<_> = placed.iter().collect(); + by_id.sort_by_key(|(id, _)| **id); + for (id, (g, rank, best)) in by_id { + let Some(was) = s.catalog.photo(*id).and_then(|p| p.analysis) else { continue }; + let now = Analysis { group: *g, rank: Some(*rank), best: *best, ..was }; + if now != was { + ops.push(Op::SetAnalysis { id: *id, analysis: Some(now) }); + } + } + // what the target burst holds now + let members: Option> = target.and_then(|g| new.get(&g).filter(|m| remains(g, m))).map(|m| m.iter().map(|p| p.0).collect()); + let report = |changed: bool| json!({"burst": members.as_ref().and(target), "pick": members.as_ref().and_then(|m| m.first()), "photos": members, "changed": changed}); + if ops.is_empty() { + return Ok(report(false)); + } + // the Pick culling gave a burst's pick goes to its new pick + let is_pick = |id: PhotoId| placed.get(&id).is_some_and(|p| p.2); + let flag = |s: &Session, id: PhotoId| s.catalog.photo(id).map(|p| p.flag).unwrap_or_default(); + let mut flags: BTreeMap = BTreeMap::new(); + for (g, before) in &old { + let Some(old_pick) = before.iter().copied().find(|m| s.catalog.photo(*m).and_then(|p| p.analysis).is_some_and(|a| a.best)) else { continue }; + let new_pick = new.get(g).filter(|m| remains(*g, m)).and_then(|m| m.first()).copied(); + if flag(s, old_pick) != Flag::Pick || new_pick == Some(old_pick) { + continue; + } + if !is_pick(old_pick) { + flags.insert(old_pick, Flag::None); + } + // the new pick was chosen by hand: it takes the Pick even over a Reject + if let Some(n) = new_pick { + flags.insert(n, Flag::Pick); + } + } + ops.extend(flags.into_iter().map(|(id, flag)| Op::SetFlag { id, flag })); + // a stacked burst (a stack of exactly its photos, as culling stacks them) follows it: its stack + // shrinks, grows or goes, in the burst's order. Shrinking first: a photo is in one stack at a time. + let (mut shrink, mut grow) = (Vec::new(), Vec::new()); + let mut grows_target = false; + let mut followed = std::collections::HashSet::new(); + for (g, before) in old.iter().filter(|(_, m)| m.len() >= 2) { + let Some(st) = s.catalog.stack_of(before[0]).filter(|st| st.photos.len() == before.len() && before.iter().all(|m| st.photos.contains(m))) + else { + continue; + }; + followed.insert(st.id); + let after = new.get(g).filter(|m| m.len() >= 2); + match after { + None => shrink.push(Op::RemoveStack { id: st.id }), + Some(after) if after == &st.photos => {} + Some(after) => { + let op = Op::SetStack { id: st.id, photos: after.clone(), collapsed: st.collapsed }; + if after.iter().all(|m| st.photos.contains(m)) { + shrink.push(op) + } else { + grows_target = true; + grow.push(op) + } + } + } + } + if grows_target { + // photos joining a stacked burst leave any other stack they are in + let strays: Vec = ids.iter().copied().filter(|id| s.catalog.stack_of(*id).is_some_and(|st| !followed.contains(&st.id))).collect(); + shrink.extend(s.catalog.remove_from_stacks_ops(&strays)); + } + let restacked = !shrink.is_empty() || !grow.is_empty(); + ops.extend(shrink); + ops.extend(grow); + let same = matches!(into, Dest::Burst(g) if ids.iter().all(|id| group(s, *id) == Some(g))); + let label = match into { + Dest::Burst(_) if same && at == 0 => "Choose Burst Pick", + Dest::Burst(_) if same => "Rearrange Burst", + Dest::Burst(_) => "Move to Burst", + Dest::New => "New Burst", + Dest::Nowhere => "Remove from Burst", + }; + s.commit(label, Op::Batch { ops })?; + if restacked { + keep_active_shown(s); + } + Ok(report(true)) } /// `burstGap` (seconds, 0..=a day) and `similarity` (0..=1) of `photo.analyze`, refused before @@ -168,9 +373,18 @@ pub fn specs() -> Vec { "Assisted Culling", [], None, - "{ids?, rejectBelow?: sharpness 0..100, pickBest?: bool, stackGroups?: bool (false), burstGap?: seconds 0..86400 (10), similarity?: 0..1 (0.93)} — score the selected photos (else all in view) for focus (0..100) and clipping, group look-alike shots (signature similarity at least `similarity`) taken at most `burstGap` seconds apart and mark the sharpest of each; optionally reject blurry photos, pick each group's best and, with `stackGroups`, stack each burst collapsed with its sharpest photo on top (photos already in a stack stay put: the rest of a burst is stacked when two or more remain); one undo step → {photos: [{id, sharpness, clipped, group, best}], groups, stacks, rejected, picked, failed}", + "{ids?, rejectBelow?: sharpness 0..100, pickBest?: bool, stackGroups?: bool (false), burstGap?: seconds 0..86400 (10), similarity?: 0..1 (0.93), resetBursts?: bool (false)} — score the selected photos (else all in view) for focus (0..100) and clipping, group look-alike shots (signature similarity at least `similarity`) taken at most `burstGap` seconds apart and mark the sharpest of each; optionally reject blurry photos, pick each group's best and, with `stackGroups`, stack each burst collapsed with its sharpest photo on top (photos already in a stack stay put: the rest of a burst is stacked when two or more remain). Photos whose burst was arranged by hand (`photo.moveToBurst`) keep their burst, place and pick and are only scored again, unless `resetBursts`; one undo step → {photos: [{id, sharpness, clipped, group, best, byHand}], groups, kept, stacks, rejected, picked, failed}", always, analyze ), + cmd!( + "photo.moveToBurst", + "Move to Burst", + [], + None, + "{ids?, burst?: number | \"new\" | null (default: the first photo's burst), index?: place (0 = the pick; default last)} — arrange Assisted Culling's bursts by hand (Window ▸ Bursts): the photos go into that burst at `index`, into a new burst, or (null) out of every burst; reordering within a burst is the same call. A burst left with one photo is no burst. The pick follows the first place: Best of Similar Shots, the Pick flag culling gave the old pick, and the top of the burst's stack. Every burst touched is kept as arranged when culling runs again (`photo.analyze` `resetBursts` forgets it). Photos must have been culled; one undo step → {burst, photos, pick, changed}", + always, + move_to_burst + ), ] } diff --git a/crates/engine/src/cmd/develop.rs b/crates/engine/src/cmd/develop.rs index dc89e3a9c3..4821e6fcd1 100644 --- a/crates/engine/src/cmd/develop.rs +++ b/crates/engine/src/cmd/develop.rs @@ -88,7 +88,7 @@ fn recipe_partial(recipe: &[(String, f64)]) -> Option { /// The longest name or group a saved recipe preset may have (characters). const MAX_PRESET_TEXT: usize = 100; -fn crop_dims(s: &Session, id: PhotoId) -> (f64, f64) { +pub(super) fn crop_dims(s: &Session, id: PhotoId) -> (f64, f64) { let p = s.catalog.photo(id); let (w, h) = p.map(|p| (p.width.max(1) as f64, p.height.max(1) as f64)).unwrap_or((3.0, 2.0)); let o = p.map(|p| p.develop.orientation).unwrap_or_default(); @@ -120,13 +120,11 @@ fn wb_mode_ignores_its_numbers(mode: WbMode, info: &lightcraft_pipeline::SourceI /// numbers, neither, or a mode of its own. [`merge_settings_for_photo`] and `preset.apply` both start here, and /// both finish with `normalize_wb` so the photo ends on the scale it is edited on. pub(crate) fn prepare_photo_for_wb_partial(d: &DevelopSettings, partial: &Value, info: &lightcraft_pipeline::SourceInfo) -> Option { - let mut d = (*d).clone(); - let wb = partial.get("wb").and_then(Value::as_object); - // the partial names one of the two numbers, and not both or neither - let one_field = wb.is_some_and(|wb| wb.contains_key("temp") != wb.contains_key("tint")); - if !one_field { + if !wb_partial_names_one_field(partial) { return None; } + let mut d = (*d).clone(); + let wb = partial.get("wb").and_then(Value::as_object); // a photo whose source is edited in Kelvin is the one with two scales to trip over let kelvin_source = info.raw && !info.relative_wb; // the scale the partial's numbers are written on: an unmentioned scale means the relative scale, as `merged` reads it @@ -154,6 +152,12 @@ pub(crate) fn prepare_photo_for_wb_partial(d: &DevelopSettings, partial: &Value, Some(d) } +/// Whether `partial`'s white balance names one of the two numbers, and not both or neither: the partials +/// [`prepare_photo_for_wb_partial`] prepares the photo for. +pub(crate) fn wb_partial_names_one_field(partial: &Value) -> bool { + partial.get("wb").and_then(Value::as_object).is_some_and(|wb| wb.contains_key("temp") != wb.contains_key("tint")) +} + /// Merge a partial settings JSON into a photo's settings (issue #2910). `DevelopSettings::merged` keeps a white /// balance that names no scale on the relative scale; on a photo edited in Kelvin the field the partial does not /// name (a partial with only `temp`, or only `tint`) would then be read on the other scale, giving a white neither @@ -1068,19 +1072,22 @@ pub fn specs() -> Vec { "Perspective Correction", [], None, - "{mode: off|auto|guided|level|vertical|full} — analyses the photo (line segments → vanishing points) and stores the correction; run again to update after lens changes", + "{mode: off|auto|guided|level|vertical|full} — analyses the photo (line segments → vanishing points) and stores the correction; run again to update after lens changes → {mode, transform, note (why the mode corrects less than it says, and what it did instead, when it does)}", has_active, |s, p| { let mode: Upright = serde_json::from_value(p.get("mode").cloned().unwrap_or(json!("auto"))).map_err(|e| bad("geometry.upright", e.to_string()))?; let id = active(s, "geometry.upright")?; let d = s.develop_of(id).unwrap_or_default(); - let transform = match mode { - Upright::Off | Upright::Guided => None, + let (transform, note, family, instead) = match mode { + Upright::Off | Upright::Guided => (None, None, "", None), m => { let src = s.source_now(id, SourceLevel::Preview).map_err(|e| bad("geometry.upright", e))?; let info = s.source_info(id); - Some(lightcraft_pipeline::upright::auto_transform(&src, &info, &d, m)) + let a = lightcraft_pipeline::upright::analyze_source(&src, &info, &d); + let family = lightcraft_pipeline::upright::guided_hint(m, &a); + let instead = lightcraft_pipeline::upright::fallback(m, &a); + (Some(lightcraft_pipeline::upright::solve(m, &a)), lightcraft_pipeline::upright::shortfall(m, &a), family, instead) } }; edit(s, "geometry.upright", "Perspective Correction", |d| { @@ -1088,7 +1095,19 @@ pub fn specs() -> Vec { d.geometry.upright_transform = transform; Ok(()) })?; - Ok(json!({"mode": mode, "transform": transform})) + // say why when the mode can't do what it says, instead of nothing happening + let note = note.map(|why| { + let what = match mode { + Upright::Level => "No level correction", + Upright::Vertical => "No vertical correction", + Upright::Full => "No full correction", + _ => "No perspective correction", + }; + // (and what it did instead, when it fell back to a lesser correction: "nothing" is only said of none) + let instead = instead.map(|i| format!(" {i}.")).unwrap_or_default(); + format!("{what}: {why}.{instead} Try Guided: draw {family}.") + }); + Ok(json!({"mode": mode, "transform": transform, "note": note})) } ), cmd!( @@ -1323,24 +1342,10 @@ pub fn specs() -> Vec { let ops = ids .iter() .filter_map(|id| s.develop_of(*id).map(|d| (*id, d))) - .filter_map(|(id, d)| { - // a hand-written preset may name one white balance number only, and then it means the same as - // a partial: bring the photo onto that scale first, with its own as-shot white, and put the - // result back on the scale the photo is edited on (issue #2910) — the merge `develop.merge` uses - let info = s.source_info(id); - let prepared = prepare_photo_for_wb_partial(&d, &preset.settings, &info); - let on_kelvin_scale = prepared.is_some() && info.raw && !info.relative_wb; - let base: &DevelopSettings = prepared.as_ref().unwrap_or(&d); - // Amount is measured from the import look only when the photo has one. - // Otherwise the current settings (on the partial's WB scale) are its baseline. - let imported = s.catalog.photo(id).filter(|p| p.import_look.is_some() && amount != 1.0).map(|p| p.import_defaults()); - let prepared_import = - imported.as_ref().map(|d| prepare_photo_for_wb_partial(d, &preset.settings, &info).unwrap_or_else(|| d.clone())); - let original = prepared_import.as_ref().unwrap_or(base); - let mut next = preset.apply_on(base, original, amount); - if on_kelvin_scale { - lightcraft_pipeline::local::normalize_wb(&mut next, &info); - } + .filter_map(|(id, _)| { + // the same composition, white balance preparation and final scale as previews and import + // (`Session::preset_applied`, issues #2159 and #2910) + let next = s.preset_applied(id, &preset, amount)?; s.develop_op(id, next, &format!("Preset: {}", preset.name)) }) .collect::>(); diff --git a/crates/engine/src/cmd/face_detect.rs b/crates/engine/src/cmd/face_detect.rs index 611a841033..5f04230845 100644 --- a/crates/engine/src/cmd/face_detect.rs +++ b/crates/engine/src/cmd/face_detect.rs @@ -302,7 +302,7 @@ pub fn specs() -> Vec { cmd!( "faces.detect", "Detect Faces", - ["Photo"], + ["Photo", "Metadata"], None, "{ids?, apply?: bool (default true), score?: 0.6, nmsIou?: 0.3, maxFaces?} → {photos: [{id, faces: [{rect, score, landmarks}]}]}. Finds faces with the YuNet detector (download it first: `faces.models.download {id: \"yunet-2023mar\"}`) and, unless `apply` is false, adds them as unnamed face regions (one undo step), replacing earlier detections but never regions from XMP or ones you named; the sidecar is not touched", has_selection, diff --git a/crates/engine/src/cmd/focus.rs b/crates/engine/src/cmd/focus.rs index efe1d1b7f6..2f44f2685b 100644 --- a/crates/engine/src/cmd/focus.rs +++ b/crates/engine/src/cmd/focus.rs @@ -1,4 +1,4 @@ -//! Focus points for photos already in the library: `photo.readFocusPoints` (Photo ▸ Read Focus Points) and the +//! Focus points for photos already in the library: `photo.readFocusPoints` (Photo ▸ Metadata ▸ Read Focus Points) and the //! per-frame `focus.pump` that keeps the background job going. The job itself is `crate::focus_scan`. use serde_json::Value; @@ -31,7 +31,7 @@ pub fn specs() -> Vec { cmd!( "photo.readFocusPoints", "Read Focus Points", - ["Photo"], + ["Photo", "Metadata"], None, "{ids?, wait?: false} → {queued, running, last?: {total, done, found, none, unavailable, bytesRead, seconds, cancelled}} — read the camera's focus point for photos imported before it was read (Sony α1 and A7S III raws and JPEGs), from the few KB of each file that hold it, on a background job with a row in the activity stack. Without `ids`, every photo in the library not looked at yet; with `ids`, those photos, looked at again. Photos that have a point keep it. No undo step and no sidecar write. `wait: true` returns when all are read (scripts)", super::always, diff --git a/crates/engine/src/cmd/geocode.rs b/crates/engine/src/cmd/geocode.rs index 8d36dcd750..28b16b13ce 100644 --- a/crates/engine/src/cmd/geocode.rs +++ b/crates/engine/src/cmd/geocode.rs @@ -145,7 +145,8 @@ fn reverse(s: &mut Session, p: &Value) -> Result { return Err(bad(C, "none of these photos has a GPS position")); } let dir = dataset_dir(p).ok_or_else(|| bad(C, "no settings folder: give `dataset`"))?; - let names = s.place_names.load(&dir).map_err(|e| bad(C, format!("{e}: download the place names first (Photo → Download Place Names)")))?; + let names = + s.place_names.load(&dir).map_err(|e| bad(C, format!("{e}: download the place names first (Photo → Metadata → Download Place Names)")))?; // a large selection shows in the activity stack and can be stopped let task = (todo.len() > 1).then(|| s.activity.start("geocode", "Looking up places", Cancel::Yes)); let mut ops = Vec::new(); @@ -311,7 +312,7 @@ pub fn specs() -> Vec { cmd!( "metadata.reverseGeocode", "Fill Location from GPS", - ["Photo"], + ["Photo", "Metadata"], None, "{ids?, overwrite?: bool (also replace place fields that already have text; default false: only empty ones are filled), dryRun?, dataset?: folder, maxDistance?: metres (past this distance from the town found, City is left empty and the town is given as nearestCity)} → {looked, found, changed, photos: [{id, place: {sublocation, city, state, country, iso, distance}, nearestCity?}], attribution} — fills City / State / Country (and Sublocation when known) from GPS with the offline GeoNames place names (download them first); one undo step. The place names list towns of 15 000 people or more (GeoNames cities15000): a photo taken in a smaller town gets the nearest larger one, up to 50 km away (`distance` says how far); `maxDistance` keeps such a town out of City", has_selection, @@ -323,7 +324,7 @@ pub fn specs() -> Vec { v.push(cmd!( "metadata.downloadPlaceNames", "Download Place Names (GeoNames)", - ["Photo"], + ["Photo", "Metadata"], None, "{} → {started, path, attribution} — downloads the GeoNames cities list (CC-BY 4.0, ~3 MB, from download.geonames.org) in the background for Fill Location from GPS, always into `geonames` in the settings folder (a folder or server named by the caller is refused); no photo data is sent", always, diff --git a/crates/engine/src/cmd/keywords.rs b/crates/engine/src/cmd/keywords.rs index 56f2609be5..80b4ece904 100644 --- a/crates/engine/src/cmd/keywords.rs +++ b/crates/engine/src/cmd/keywords.rs @@ -66,6 +66,40 @@ fn info_from(p: &Value, base: KeywordInfo) -> KeywordInfo { } } +/// `keyword.move`'s `parent`: a keyword, or null for the top level. +fn move_parent(p: &Value) -> Result> { + match p.get("parent") { + Some(Value::String(k)) => Ok(Some(k.clone())), + Some(Value::Null) => Ok(None), + _ => Err(bad("keyword.move", "`parent` is a keyword, or null for the top level")), + } +} + +/// How many keywords one call may name (far more than a person chooses in a list). +const MAX_KEYWORDS: usize = 10_000; + +/// The keywords a command names in `keywords`: a list of them, each once (whatever its case), +/// none empty. +fn keyword_list(p: &Value, command: &str) -> Result> { + let list = p.get("keywords").and_then(Value::as_array).ok_or_else(|| bad(command, "`keywords` must be a list of keywords"))?; + if list.len() > MAX_KEYWORDS { + return Err(bad(command, format!("`keywords` names more than {MAX_KEYWORDS} keywords"))); + } + let mut out: Vec = Vec::new(); + let mut seen = std::collections::HashSet::new(); + for k in list { + let k = + k.as_str().map(clean).filter(|k| !k.is_empty()).ok_or_else(|| bad(command, format!("`keywords` must be a list of keywords, not {k}")))?; + if seen.insert(k.to_lowercase()) { + out.push(k); + } + } + if out.is_empty() { + return Err(bad(command, "`keywords` names no keyword")); + } + Ok(out) +} + /// The keyword a command names (`keyword`), as the library writes it. fn named_keyword(s: &Session, p: &Value, command: &str) -> Result { let k = str_param(p, "keyword").ok_or_else(|| bad(command, "missing `keyword`"))?; @@ -493,15 +527,23 @@ pub fn specs() -> Vec { "Move Keyword", [], None, - "{keyword, parent: keyword | null (the top level), merge?: bool} — with the keywords below it; onto a name that is taken only with `merge: true`", + "{keyword, parent: keyword | null (the top level), merge?: bool} — with the keywords below it; onto a name that is taken only with `merge: true`. Several at once: {keywords: [keyword], parent} as one undo step (of a keyword and one below it the upper one moves); nothing merges then: a name that is taken, or two of them with one name, refuses the whole move", always, |s, p| { + if p.get("keywords").is_some_and(|k| !k.is_null()) { + let parent = move_parent(p)?; + let keywords = keyword_list(p, "keyword.move")?; + let (op, moves) = s + .catalog + .move_keywords_ops(&keywords, parent.as_deref()) + .map_err(|e| refused("keyword.move", e, ": moving would merge the two (move that one by itself, with merge: true)"))?; + let label = if moves.len() == 1 { "Move Keyword".to_string() } else { format!("Move {} Keywords", moves.len()) }; + return commit_keywords(s, &label, op, |k| { + Some(moves.iter().find(|(f, _)| is_under(k, f)).map_or_else(|| k.to_string(), |(f, t)| reparent(k, f, t))) + }); + } let from = named_keyword(s, p, "keyword.move")?; - let parent = match p.get("parent") { - Some(Value::String(k)) => Some(k.clone()), - Some(Value::Null) => None, - _ => return Err(bad("keyword.move", "`parent` is a keyword, or null for the top level")), - }; + let parent = move_parent(p)?; // where it lands, as the catalog spells it: a parent that doesn't exist yet is made let leaf = from.rsplit('|').next().unwrap_or(&from).to_string(); let to = match parent.as_deref().map(|k| s.catalog.keyword_path(k).unwrap_or_else(|| clean(k))).filter(|k| !k.is_empty()) { @@ -621,9 +663,16 @@ pub fn specs() -> Vec { "Delete Keyword", [], None, - "{keyword} — removes it (and the keywords below it) from every photo", + "{keyword} — removes it (and the keywords below it) from every photo. Several at once: {keywords: [keyword]}, as one undo step", always, |s, p| { + if p.get("keywords").is_some_and(|k| !k.is_null()) { + let keywords = keyword_list(p, "keyword.delete")?; + let op = s.catalog.delete_keywords_ops(&keywords).map_err(|e| bad("keyword.delete", e.to_string()))?; + let gone: Vec = keywords.iter().map(|k| clean(k)).collect(); + let label = if gone.len() == 1 { "Delete Keyword".to_string() } else { format!("Delete {} Keywords", gone.len()) }; + return commit_keywords(s, &label, op, |f| (!gone.iter().any(|g| is_under(f, g))).then(|| f.to_string())); + } let k = str_param(p, "keyword").ok_or_else(|| bad("keyword.delete", "missing `keyword`"))?.to_string(); let op = s.catalog.delete_keyword_ops(&k).map_err(|e| bad("keyword.delete", e.to_string()))?; let c = clean(&k); diff --git a/crates/engine/src/cmd/lens_refresh.rs b/crates/engine/src/cmd/lens_refresh.rs index 350522b6c4..c5b03ad834 100644 --- a/crates/engine/src/cmd/lens_refresh.rs +++ b/crates/engine/src/cmd/lens_refresh.rs @@ -33,7 +33,7 @@ pub struct Missing { pub fn missing(cat: &Catalog, db: &lightcraft_lensdb::LensDb, ids: Option<&[PhotoId]>, again: bool) -> Vec { // a photo and its virtual copies list the photo once, in library order let mut seen = std::collections::HashSet::new(); - let from_database = |p: &Photo| p.embedded_lens.is_some_and(|l| l.source == LensSource::Database); + let from_database = |p: &Photo| p.embedded_lens.as_deref().is_some_and(|l| l.source == LensSource::Database); cat.photos() .filter(|p| ids.is_none_or(|ids| ids.contains(&p.id) || p.copy_of.is_some_and(|c| ids.contains(&c)))) .map(|p| p.copy_of.and_then(|c| cat.photo(c)).map_or(&**p, |orig| &**orig)) @@ -46,7 +46,7 @@ pub fn missing(cat: &Catalog, db: &lightcraft_lensdb::LensDb, ids: Option<&[Phot Some(_) => again && from_database(p), } }) - .filter_map(|p| crate::cmd::missing::checked_path(p).map(|path| Missing { id: p.id, path: path.to_string() })) + .filter_map(|p| p.library_file().map(|path| Missing { id: p.id, path: path.to_string() })) .filter(|m| seen.insert(m.id)) .collect() } @@ -75,14 +75,14 @@ pub fn apply(s: &mut Session, results: Vec<(Missing, std::result::Result u64 { (lightcraft_catalog::mix64(prev.wrapping_add(1)) ^ t) & (MAX_SEED - 1) } +/// `album.move` for several albums and folders (`ids`) at once: everything is checked first, then +/// they move as one undo step. +fn move_albums(s: &mut Session, p: &Value) -> Result { + const C: &str = "album.move"; + let ids = album_ids(p.get("ids").unwrap_or(&Value::Null), C)?; + if ids.is_empty() { + return Err(bad(C, "`ids` names no album")); + } + if let Some(gone) = ids.iter().find(|a| s.catalog.album(**a).is_none()) { + return Err(bad(C, format!("no such album {}", gone.0))); + } + let parent = opt_album_param(p, "parent", C)?; + if let Some(folder) = parent + && !s.catalog.album(folder).is_some_and(|a| a.folder) + { + return Err(bad(C, format!("album {} is not a folder of albums", folder.0))); + } + // where `parent` sits: itself and the folders above it (a ring, in a damaged library, ends the walk) + let mut above: Vec = Vec::new(); + let mut cur = parent; + while let Some(c) = cur.filter(|c| !above.contains(c)) { + above.push(c); + cur = s.catalog.album(c).and_then(|a| a.parent); + } + // of a folder and what is inside it, the folder moves + let inside_another = |id: AlbumId| { + let mut seen: Vec = Vec::new(); + let mut cur = s.catalog.album(id).and_then(|a| a.parent); + while let Some(c) = cur.filter(|c| !seen.contains(c)) { + if ids.contains(&c) { + return true; + } + seen.push(c); + cur = s.catalog.album(c).and_then(|a| a.parent); + } + false + }; + let moving: Vec = ids.iter().copied().filter(|id| !inside_another(*id)).collect(); + for id in &moving { + let name = s.catalog.album(*id).map(|a| a.name.clone()).unwrap_or_default(); + if above.contains(id) { + return Err(bad(C, format!("“{name}” can't go inside itself"))); + } + } + let ops: Vec = moving.iter().map(|id| Op::MoveAlbum { id: *id, parent }).collect(); + let label = if moving.len() == 1 { "Move Album".to_string() } else { format!("Move {} Albums", moving.len()) }; + s.commit(&label, Op::Batch { ops })?; + Ok(json!({"moved": moving.len()})) +} + +/// How many albums or folders one call may name: far more than a person +/// chooses in a sidebar, and a bound on what one call can make the engine check. +pub(crate) const MAX_SOURCES: usize = 1000; + +/// A command's `ids`: album ids, each once (named twice, the last naming counts). +fn album_ids(v: &Value, c: &str) -> Result> { + let list = v.as_array().ok_or_else(|| bad(c, "`ids` must be a list of album ids"))?; + if list.len() > MAX_SOURCES { + return Err(bad(c, format!("`ids` names more than {MAX_SOURCES} albums"))); + } + let mut out: Vec = Vec::new(); + for x in list { + let id = AlbumId(x.as_u64().ok_or_else(|| bad(c, format!("`ids` must be a list of album ids, not {x}")))?); + out.retain(|o| *o != id); + out.push(id); + } + Ok(out) +} + +/// A command's `paths`: folder paths, each folder once (named twice, the last counts). +fn folder_paths(v: &Value, c: &str) -> Result> { + let list = v.as_array().ok_or_else(|| bad(c, "`paths` must be a list of folder paths"))?; + if list.len() > MAX_SOURCES { + return Err(bad(c, format!("`paths` names more than {MAX_SOURCES} folders"))); + } + let mut out: Vec = Vec::new(); + for x in list { + let path = x.as_str().ok_or_else(|| bad(c, format!("`paths` must be a list of folder paths, not {x}")))?; + let key = lightcraft_catalog::query::folder_key(path); + out.retain(|o| lightcraft_catalog::query::folder_key(o) != key); + out.push(path.to_string()); + } + Ok(out) +} + pub fn specs() -> Vec { vec![ // ---- view source / filter / sort @@ -128,35 +213,52 @@ pub fn specs() -> Vec { "Remove Folder from Library", [], None, - "{path, disk?: bool} — move the library photos imported from this folder (and the folders inside it) to Recently Deleted; one undo step, no file is touched. A whole disk or share (`/Volumes/nas`, `C:\\`, `\\\\srv\\share`) goes only with `disk: true`, the startup disk never → {removed}", + "{path, disk?: bool} — move the library photos imported from this folder (and the folders inside it) to Recently Deleted; one undo step, no file is touched. A whole disk or share (`/Volumes/nas`, `C:\\`, `\\\\srv\\share`) goes only with `disk: true`, the startup disk never → {removed}. Several at once: {paths: [path]}, still one undo step; one that can't be removed refuses the whole call", always, |s, p| { const C: &str = "library.removeFolder"; - let path = str_param(p, "path").filter(|d| !d.trim().is_empty()).ok_or_else(|| bad(C, "missing `path`"))?; - if lightcraft_catalog::query::folder_key(path).is_empty() { - return Err(bad(C, format!("{path}: not a folder"))); + let several = p.get("paths").is_some_and(|v| !v.is_null()); + let paths = match p.get("paths") { + Some(v) if several => folder_paths(v, C)?, + _ => vec![str_param(p, "path").filter(|d| !d.trim().is_empty()).ok_or_else(|| bad(C, "missing `path`"))?.to_string()], + }; + if paths.is_empty() { + return Err(bad(C, "`paths` names no folder")); } - if lightcraft_catalog::folders::is_startup_disk(path) { - return Err(bad(C, "choose a folder, not the whole startup disk")); + // every folder is checked before a photo leaves; a photo in two of them leaves once + let mut ids: Vec = Vec::new(); + let mut seen = std::collections::HashSet::new(); + for path in &paths { + let path = path.as_str(); + if path.trim().is_empty() || lightcraft_catalog::query::folder_key(path).is_empty() { + return Err(bad(C, format!("{path}: not a folder"))); + } + if lightcraft_catalog::folders::is_startup_disk(path) { + return Err(bad(C, "choose a folder, not the whole startup disk")); + } + if lightcraft_catalog::folders::is_disk_root(path) && !bool_or(p, "disk", false) { + return Err(bad(C, format!("{path} is a whole disk or share: pass `disk: true` to remove everything on it"))); + } + let f = Filter { library_folder: Some(path.to_string()), ..Default::default() }; + let found = s.catalog.query(&f, &Sort::default()); + if found.is_empty() { + return Err(bad(C, format!("{path}: no photo in the library was imported from it"))); + } + if covers_other_disks(s, path, &found) && !bool_or(p, "disk", false) { + return Err(bad(C, format!("{path} holds whole disks: pass `disk: true` to remove everything on them"))); + } + ids.extend(found.into_iter().filter(|id| seen.insert(*id))); } - if lightcraft_catalog::folders::is_disk_root(path) && !bool_or(p, "disk", false) { - return Err(bad(C, format!("{path} is a whole disk or share: pass `disk: true` to remove everything on it"))); - } - let f = Filter { library_folder: Some(path.to_string()), ..Default::default() }; - let ids = s.catalog.query(&f, &Sort::default()); - if ids.is_empty() { - return Err(bad(C, format!("{path}: no photo in the library was imported from it"))); - } - if covers_other_disks(s, path, &ids) && !bool_or(p, "disk", false) { - return Err(bad(C, format!("{path} holds whole disks: pass `disk: true` to remove everything on them"))); - } - mark_deleted(s, &ids, "Remove Folder from Library")?; - if s.filter.library_folder.as_deref().is_some_and(|c| lightcraft_catalog::query::folder_within(c, path)) { + let label = + if paths.len() == 1 { "Remove Folder from Library".to_string() } else { format!("Remove {} Folders from Library", paths.len()) }; + mark_deleted(s, &ids, &label)?; + let within = |c: &str| paths.iter().any(|path| lightcraft_catalog::query::folder_within(c, path)); + if s.filter.library_folder.as_deref().is_some_and(within) { s.filter.library_folder = None; } // a filter put aside by Enable Filters must not bring the removed folder back if let Some(f) = s.shelved_filter.as_mut() - && f.library_folder.as_deref().is_some_and(|c| lightcraft_catalog::query::folder_within(c, path)) + && f.library_folder.as_deref().is_some_and(within) { f.library_folder = None; } @@ -164,7 +266,7 @@ pub fn specs() -> Vec { s.shelved_filter = None; } // the folder being shown is gone: back to everything, as for a deleted album - if s.library_folder.as_deref().is_some_and(|c| lightcraft_catalog::query::folder_within(c, path)) { + if s.library_folder.as_deref().is_some_and(within) { s.library_folder = None; if s.source == LibrarySource::LibraryFolder { s.source = LibrarySource::All; @@ -180,26 +282,46 @@ pub fn specs() -> Vec { "Set Folder Color Label", [], None, - "{path, label: red|yellow|green|blue|purple|none} — give a folder of the library (one its photos were imported from, see library.folders) a colour label, or take it off (also once its photos are gone); one undo step. The label follows the folder when it is renamed or moved with folder.rename / folder.move → {path, label}", + "{path, label: red|yellow|green|blue|purple|none} — give a folder of the library (one its photos were imported from, see library.folders) a colour label, or take it off (also once its photos are gone); one undo step. The label follows the folder when it is renamed or moved with folder.rename / folder.move → {path, label}. Several at once: {paths: [path], label}, as one undo step", always, |s, p| { const C: &str = "folder.label"; - let path = str_param(p, "path").filter(|d| !d.trim().is_empty()).ok_or_else(|| bad(C, "missing `path`"))?; + let several = p.get("paths").is_some_and(|v| !v.is_null()); + let paths = match p.get("paths") { + Some(v) if several => folder_paths(v, C)?, + _ => vec![str_param(p, "path").filter(|d| !d.trim().is_empty()).ok_or_else(|| bad(C, "missing `path`"))?.to_string()], + }; + if paths.is_empty() { + return Err(bad(C, "`paths` names no folder")); + } let label = match str_param(p, "label").ok_or_else(|| bad(C, "missing `label` (red|yellow|green|blue|purple|none)"))? { "none" => None, x => Some(ColorLabel::parse(x).ok_or_else(|| bad(C, format!("unknown label {x:?}")))?), }; - // taking a label off always works, also once the folder's photos are gone - let f = Filter { library_folder: Some(path.to_string()), ..Default::default() }; - if label.is_some() && s.catalog.query(&f, &Sort::default()).is_empty() { - return Err(bad(C, format!("{path}: no photo in the library was imported from it"))); + let mut ops = Vec::new(); + for path in &paths { + if path.trim().is_empty() { + return Err(bad(C, "missing `path`")); + } + // taking a label off always works, also once the folder's photos are gone + let f = Filter { library_folder: Some(path.clone()), ..Default::default() }; + if label.is_some() && s.catalog.query(&f, &Sort::default()).is_empty() { + return Err(bad(C, format!("{path}: no photo in the library was imported from it"))); + } + if label.is_some() || s.catalog.folder_record(path).is_some() { + ops.push(s.catalog.folder_label_op(path, label)); + } } - if label.is_none() && s.catalog.folder_record(path).is_none() { - return Ok(json!({"path": path, "label": label})); + let name = if label.is_some() { "Set Folder Color Label" } else { "Remove Folder Color Label" }; + match (ops.len(), ops.pop()) { + (0, _) | (_, None) => {} + (1, Some(op)) => s.commit(name, op)?, + (_, Some(last)) => { + ops.push(last); + s.commit(name, Op::Batch { ops })? + } } - let op = s.catalog.folder_label_op(path, label); - s.commit(if label.is_some() { "Set Folder Color Label" } else { "Remove Folder Color Label" }, op)?; - Ok(json!({"path": path, "label": label})) + if several { Ok(json!({"paths": paths, "label": label})) } else { Ok(json!({"path": paths.first(), "label": label})) } } ), cmd!("library.clearFilter", "Clear Filters", ["View"], None, "{}", always, |s, _| { @@ -257,7 +379,7 @@ pub fn specs() -> Vec { cmd!( "library.refresh", "Refresh View", - ["View"], + ["View", "Sort"], None, "{} — show what matches now: a view that holds its photos (`library.holdView`) lets go of the ones that stopped matching a smart album's rules, Picks or the filter bar since it was opened, sorted or last refreshed", always, @@ -269,7 +391,7 @@ pub fn specs() -> Vec { cmd!( "library.holdView", "Hold View Until Refreshed", - ["View"], + ["View", "Sort"], None, "{on?: bool (toggles when omitted)} → {hold} — when on, an edit that makes a photo stop matching the view (a keyword given in a smart album of photos without keywords, a flag taken off in Picks, a rating under the filter bar's) keeps it in the view until `library.refresh`, Reshuffle, or another source, filter or sort; photos that start matching still appear at once, and deleting a photo or taking it out of the album or folder shown still takes it out of the view. Changing a smart album's rules is another view too. Off (the default): the view follows every edit. Kept with the library's preferences; asking for the state it already has changes nothing", always, @@ -382,7 +504,7 @@ pub fn specs() -> Vec { cmd!(query "library.devices", "Cameras and Cards", [], None, "{} → [{name, path (its DCIM folder), root}] — mounted volumes with a DCIM folder", always, |_, _| { Ok(serde_json::to_value(crate::devices::devices_now()).unwrap_or_default()) }), - cmd!(query "photo.copyMetadata", "Copy Metadata", ["Photo"], Some("Cmd+Alt+Shift+C"), "{} — title, caption, copyright (notice, status, usage terms, info URL), creator, location and keywords of the active photo", has_active, |s, _| { + cmd!(query "photo.copyMetadata", "Copy Metadata", ["Photo", "Metadata"], Some("Cmd+Alt+Shift+C"), "{} — title, caption, copyright (notice, status, usage terms, info URL), creator, location and keywords of the active photo", has_active, |s, _| { let id = s.active().ok_or_else(|| bad("photo.copyMetadata", "no active photo"))?; let m = &s.catalog.photo(id).ok_or_else(|| bad("photo.copyMetadata", "no photo"))?.meta; let v = json!({"title": m.title, "caption": m.caption, "altText": m.alt_text, "extendedDescription": m.extended_description, @@ -395,7 +517,7 @@ pub fn specs() -> Vec { cmd!( "photo.pasteMetadata", "Paste Metadata", - ["Photo"], + ["Photo", "Metadata"], Some("Cmd+Alt+Shift+V"), "{ids?, fields?: [title|caption|copyright|copyrightStatus|usageTerms|copyrightUrl|creator|location|keywords] (default: all copied)}", has_selection, @@ -942,11 +1064,22 @@ pub fn specs() -> Vec { "Delete Album", [], None, - "{id} — deletes the album or folder and its descendants, keeping photos in the library; one undo step", + "{id} — deletes the album or folder and its descendants, keeping photos in the library; one undo step. Several at once: {ids: [albumId]} → {deleted}, still one undo step; one that does not exist refuses the whole call", always, |s, p| { - let id = album_param(p, "id", "album.delete")?; - let folder = s.catalog.album(id).ok_or_else(|| bad("album.delete", "no such album"))?.folder; + const C: &str = "album.delete"; + let several = p.get("ids").is_some_and(|v| !v.is_null()); + let ids = match p.get("ids") { + Some(v) if several => album_ids(v, C)?, + _ => vec![album_param(p, "id", C)?], + }; + if ids.is_empty() { + return Err(bad(C, "`ids` names no album")); + } + if let Some(gone) = ids.iter().find(|a| s.catalog.album(**a).is_none()) { + return Err(bad(C, if several { format!("no such album {}", gone.0) } else { "no such album".into() })); + } + let folder = ids.first().and_then(|id| s.catalog.album(*id)).is_some_and(|a| a.folder); let mut children = std::collections::BTreeMap::>::new(); for album in s.catalog.albums() { if let Some(parent) = album.parent { @@ -956,32 +1089,61 @@ pub fn specs() -> Vec { // Iterative traversal: even a malformed cycle is rejected before any change. // Reverse parent-first order removes children first; the batch inverse restores // parents first, including memberships, smart rules, covers and manual ordering. - let mut pending = vec![id]; let mut order = Vec::new(); let mut removed = std::collections::BTreeSet::new(); - while let Some(next) = pending.pop() { - if !removed.insert(next) { - return Err(bad("album.delete", "cycle in album folders")); + for id in &ids { + // inside one named before it: it goes with that one + if removed.contains(id) { + continue; } - order.push(next); - if let Some(nested) = children.remove(&next) { - pending.extend(nested); + let mut pending = vec![*id]; + let mut seen = std::collections::BTreeSet::new(); + while let Some(next) = pending.pop() { + if !seen.insert(next) { + return Err(bad(C, "cycle in album folders")); + } + // one named before, now found inside this one: it is listed once, here + if removed.insert(next) { + order.push(next); + } else if let Some(at) = order.iter().position(|o| *o == next) { + let moved = order.remove(at); + order.push(moved); + } + if let Some(nested) = children.get(&next) { + pending.extend(nested.iter().copied()); + } } } let ops = order.into_iter().rev().map(|id| Op::RemoveAlbum { id }).collect(); - s.commit(if folder { "Delete Folder" } else { "Delete Album" }, Op::Batch { ops })?; + let label = match (ids.len(), folder) { + (1, true) => "Delete Folder".to_string(), + (1, false) => "Delete Album".to_string(), + (n, _) => format!("Delete {n} Albums"), + }; + s.commit(&label, Op::Batch { ops })?; if matches!(s.source, LibrarySource::Album(current) if removed.contains(¤t)) { s.source = LibrarySource::All; } + if several { Ok(json!({"deleted": ids.len()})) } else { ok() } + } + ), + cmd!( + "album.move", + "Move Album", + [], + None, + "{id, parent?: folderId|null} — into a folder, or to the top level. Several at once: {ids: [albumId], parent} as one undo step (of a folder and an album inside it the folder moves); one that can't go there refuses the whole call", + always, + |s, p| { + if p.get("ids").is_some_and(|v| !v.is_null()) { + return move_albums(s, p); + } + let id = album_param(p, "id", "album.move")?; + let parent = p.get("parent").and_then(Value::as_u64).map(AlbumId); + s.commit("Move Album", Op::MoveAlbum { id, parent })?; ok() } ), - cmd!("album.move", "Move Album", [], None, "{id, parent?: folderId|null}", always, |s, p| { - let id = album_param(p, "id", "album.move")?; - let parent = p.get("parent").and_then(Value::as_u64).map(AlbumId); - s.commit("Move Album", Op::MoveAlbum { id, parent })?; - ok() - }), cmd!( "album.reorder", "Reorder Album", diff --git a/crates/engine/src/cmd/masks.rs b/crates/engine/src/cmd/masks.rs index e4017f4003..9eb14f4155 100644 --- a/crates/engine/src/cmd/masks.rs +++ b/crates/engine/src/cmd/masks.rs @@ -324,7 +324,7 @@ pub fn specs() -> Vec { "Brush Stroke", [], None, - "{id?: maskId, points: [[x,y],…] normalized, size?: fraction of long edge (0.03), feather?, flow?, density?, erase?: bool, autoMask?: bool, pressure?: [p,…] pen pressure 0..1 per point (scales each dab's size and flow; omitted: full), connect?: bool — start from the last point of the mask's last stroke (⇧-click), size / feather / flow tapering from that stroke's to these} → {activeMask, connected}", + "{id?: maskId, points: [[x,y],…] normalized, size?: fraction of long edge (0.03), feather?, flow?, density?, erase?: bool, autoMask?: bool, pressure?: [p,…] pen pressure 0..1 per point (scales each dab's size and flow; omitted: full), connect?: bool — start from the last point of the mask's last stroke (⇧-click), size / feather / flow tapering from that stroke's to these, continue?: bool — the stroke being painted, sent again as it grows: it replaces the mask's last stroke, so its effect shows while painting} → {activeMask, connected}", has_active, |s, p| { let pts: Vec = p @@ -347,6 +347,7 @@ pub fn specs() -> Vec { pressure: pressure_list(p.get("pressure"), pts_len)?, }; let connect = bool_or(p, "connect", false); + let again = bool_or(p, "continue", false); let mut connected = false; let next = s.active().and_then(|id| s.develop_of(id)).map(|d| d.next_mask_id()).unwrap_or(1); let want = optional_mask_id(p, "mask.brushStroke")?.or(s.active_mask); @@ -384,7 +385,11 @@ pub fn specs() -> Vec { strokes.extend(connected_strokes(from, &last, stroke)); connected = true; } - None => strokes.push(stroke), + // the stroke being painted, sent again as it grew: it replaces itself + None => match strokes.last_mut() { + Some(last) if again => *last = stroke, + _ => strokes.push(stroke), + }, } } else { m.components.push(MaskComponent { @@ -581,7 +586,7 @@ pub fn specs() -> Vec { "AI Mask Model Status", [], None, - "{} — whether this build has AI masks, whether the SAM 3 model is installed (and where), loaded, busy, and the download's progress → {available, installed, dir, loaded, busy, analyzing, sizeBytes, license, licenseUrl, mirrors, download: {running, done, total, file, error, finished}}", + "{} — whether this build has AI masks, whether the SAM 3 model is installed (and where), loaded, busy, where it runs and how long the last photo took, and the download's progress → {available, installed, dir, loaded, busy, analyzing, runOn (auto | cpu: segment.settings), backend: {device (what runs the backbone: a GPU's name, Metal GPU or CPU; null until loaded), runtime (wgpu|candle), heads (CPU|Metal GPU, and which of the parts after the backbone the GPU accelerator runs, e.g. `CPU; the necks on the GPU`), fallback (why the backbone is not on the GPU), encodeMs (last backbone run), analyzeMs (last photo's analysis before the first click)}, sizeBytes, license, licenseUrl, mirrors, download: {running, done, total, file, error, finished}}", super::always, |s, _| { let g = &s.segmenter; @@ -593,6 +598,8 @@ pub fn specs() -> Vec { "loaded": g.loaded(), "busy": g.busy(), "analyzing": g.analyzing(), + "runOn": g.run_on().name(), + "backend": g.backend(), "sizeBytes": crate::segment::MODEL_BYTES, "license": crate::segment::LICENSE_NAME, "licenseUrl": crate::segment::LICENSE_URL, @@ -601,6 +608,22 @@ pub fn specs() -> Vec { })) } ), + cmd!( + query "segment.settings", + "AI Mask Settings", + [], + None, + "{runOn?: auto | cpu} → {runOn} — where SAM 3 runs (Settings ▸ Performance ▸ AI masks): `auto` (the default) the GPU when there is one (Metal on macOS; elsewhere the parts LightCraft's wgpu kernels run, while GPU rendering is allowed, and the rest on the CPU: `segment.model.status` → `backend` says which), `cpu` all of it on the CPU on every platform (for a GPU that can't run it). Local inference only: a remote worker (`LIGHTCRAFT_SAM3_REMOTE`) runs on its Mac's Metal device either way. Kept with the app's settings; a loaded model moves at its next request", + super::always, + |s, p| { + let c = "segment.settings"; + if let Some(v) = p.get("runOn") { + let run_on = v.as_str().and_then(crate::segment::RunOn::parse).ok_or_else(|| bad(c, "`runOn` must be auto or cpu"))?; + s.segmenter.set_run_on(run_on).map_err(ai_err)?; + } + Ok(json!({"runOn": s.segmenter.run_on().name()})) + } + ), cmd!( query "segment.model.download", "Download AI Mask Model", @@ -924,15 +947,16 @@ pub fn specs() -> Vec { return Err(bad("spot.add", "missing points")); } let d = Spot::default(); + let size = f64_or(p, "size", d.size).clamp(SPOT_SIZE.0, SPOT_SIZE.1); + let id = s.active().ok_or_else(|| bad("spot.add", "no active photo"))?; let mut spot = Spot { mode, - points: pts, - size: f64_or(p, "size", d.size).clamp(SPOT_SIZE.0, SPOT_SIZE.1), + points: thin_spot_points(&pts, size, super::develop::crop_dims(s, id)), + size, feather: f64_or(p, "feather", d.feather).clamp(0.0, 100.0), opacity: f64_or(p, "opacity", d.opacity).clamp(0.0, 100.0), source_offset: point(p, "source"), }; - let id = s.active().ok_or_else(|| bad("spot.add", "no active photo"))?; let mut dd = (*s.develop_of(id).unwrap_or_default()).clone(); if spot.source_offset.is_none() && spot.mode != SpotMode::Fill { // resolve the automatic source now: it gets a pin and stays put at every size @@ -1125,6 +1149,38 @@ fn spots_edit(s: &mut Session, c: &str, label: &str, f: impl FnOnce(&mut Vec Vec { + let long = w.max(h).max(1e-9); + let (kx, ky) = (w / long, h / long); + let dist = |a: Point, b: Point| ((b.x - a.x) * kx).hypot((b.y - a.y) * ky); + let spacing = size / 4.0; + let mut out: Vec = Vec::with_capacity(pts.len().min(64)); + for &q in pts { + // `> 0.0` as well: with a zero size an exact repeat would otherwise count as a step + if out.last().is_none_or(|&last| dist(last, q) > 0.0 && dist(last, q) >= spacing) { + out.push(q); + } + } + // the stroke reaches where it ended: a last point closer than the spacing takes the place of the one + // before it (so a hold at the end doesn't leave a bump), unless it is at that one already + if let Some(&end) = pts.last() + && let Some(&last) = out.last() + && dist(last, end) > 0.0 + { + match out.len() { + 1 if dist(last, end) < spacing / 2.0 => {} + 1 => out.push(end), + n => out[n - 1] = end, + } + } + out +} + /// An automatic source for `spot` on photo `id` (a small proxy of the photo, framed by `d`). fn pick_source(s: &mut Session, id: crate::PhotoId, d: &lightcraft_develop::DevelopSettings, spot: &Spot, avoid: Option) -> Option { let src = s.source_now(id, crate::media::SourceLevel::Thumb).ok()?; @@ -1204,3 +1260,68 @@ mod tests_color_range { assert_eq!(samples.len(), MAX_COLOR_RANGE_SAMPLES); } } + +#[cfg(test)] +mod tests { + use super::*; + + /// The thinning measures in long-edge units: on a portrait photo the y axis is the long one (issue #2359). + #[test] + fn spot_thinning_respects_the_aspect_ratio() { + let pts: Vec = (0..100).map(|i| Point::new(0.1, 0.1 + 0.002 * f64::from(i))).collect(); + // size 0.04: one point per 0.01 long-edge units, which is 0.01 of y on a portrait photo but 0.015 on a landscape one + let tall = thin_spot_points(&pts, 0.04, (2.0, 3.0)); + let wide = thin_spot_points(&pts, 0.04, (3.0, 2.0)); + assert!(tall.len() > wide.len(), "{} vs {}", tall.len(), wide.len()); + // 0.198 of y: 19.8 spacings of 0.01 (portrait), 13.2 of 0.015 (landscape), plus the first point + assert!((tall.len() as f64 - 21.0).abs() <= 2.0, "{}", tall.len()); + assert!((wide.len() as f64 - 14.0).abs() <= 2.0, "{}", wide.len()); + assert_eq!(tall.first(), pts.first()); + assert_eq!(tall.last(), pts.last()); + assert_eq!(wide.last(), pts.last()); + } + + #[test] + fn thinning_keeps_clicks_and_degenerate_input() { + let one = vec![Point::new(0.5, 0.5)]; + assert_eq!(thin_spot_points(&one, 0.05, (3.0, 2.0)), one); + assert_eq!(thin_spot_points(&[one[0], one[0], one[0]], 0.05, (3.0, 2.0)), one); + assert!(thin_spot_points(&[], 0.05, (3.0, 2.0)).is_empty()); + // a zero-sized photo doesn't divide by zero + assert_eq!(thin_spot_points(&[one[0], Point::new(0.6, 0.6)], 0.05, (0.0, 0.0)).len(), 1); + } + + /// A long straight stroke keeps about one point per spacing, leaves no gap wider than a spacing plus one + /// recorded step (two spacings at the end), and still ends where the stroke ended, also after a hold there. + #[test] + fn a_long_stroke_is_thinned_without_gaps() { + let step = 0.0008; + let mut pts: Vec = (0..=1000).map(|i| Point::new(0.1 + step * f64::from(i), 0.5)).collect(); + // the pointer rests at the end for a few frames + pts.extend([*pts.last().unwrap(); 5]); + let (size, dims) = (0.04, (3.0, 2.0)); + let thin = thin_spot_points(&pts, size, dims); + // 0.8 long-edge units at one point per 0.01, plus the first + assert!((70..=82).contains(&thin.len()), "{}", thin.len()); + assert_eq!(thin.first(), pts.first()); + assert_eq!(thin.last(), pts.last()); + let gaps: Vec = thin.windows(2).map(|w| w[1].x - w[0].x).collect(); + let spacing = size / 4.0; + for &gap in &gaps[..gaps.len() - 1] { + assert!(gap > 0.0 && gap <= spacing + step + 1e-12, "gap {gap}"); + } + // the end takes the place of the last point kept, so the last gap may reach two spacings + let end_gap = gaps[gaps.len() - 1]; + assert!(end_gap > 0.0 && end_gap < 2.0 * spacing + step, "end gap {end_gap}"); + } + + /// A zero or tiny brush thins nothing but exact repeats: every distinct point is kept, in order. + #[test] + fn a_zero_or_tiny_size_keeps_every_distinct_point() { + let pts: Vec = (0..50).map(|i| Point::new(0.2 + 0.001 * f64::from(i), 0.3)).collect(); + let doubled: Vec = pts.iter().flat_map(|&q| [q, q]).collect(); + for size in [0.0, 1e-9] { + assert_eq!(thin_spot_points(&doubled, size, (3.0, 2.0)), pts, "size {size}"); + } + } +} diff --git a/crates/engine/src/cmd/missing.rs b/crates/engine/src/cmd/missing.rs index c9d1ea78d1..167c501a1e 100644 --- a/crates/engine/src/cmd/missing.rs +++ b/crates/engine/src/cmd/missing.rs @@ -12,28 +12,15 @@ use serde_json::{Value, json}; use super::{CommandSpec, always, bad, cmd, str_param}; use crate::{Result, Session}; -/// The file Missing Photos checks for `p`, if it is in scope: a library photo (not in Recently -/// Deleted, not a Local-only record seen while browsing a folder) whose original is a file. -/// -/// Local browse records are out of scope on purpose: browsing can leave tens of thousands of -/// them in the catalog, they never show in library views (Missing Photos included), and a -/// folder that is gone is simply not browsed again. The sidebar count, the Missing Photos view, -/// `library.missing` and Find Missing Photos all use this one rule. -pub fn checked_path(p: &Photo) -> Option<&str> { - match &p.source { - Source::File { path } if p.in_library() => Some(path), - _ => None, - } -} - -/// Every in-scope photo's file ([`checked_path`]), without touching the disk. +/// Every in-scope photo's file ([`Photo::library_file`]: the rule the sidebar count, the Missing +/// Photos view, `library.missing` and Find Missing Photos all use), without touching the disk. pub fn candidates(cat: &Catalog) -> Vec { - cat.photos().filter_map(|p| checked_path(p).map(str::to_string)).collect() + cat.photos().filter_map(|p| p.library_file().map(str::to_string)).collect() } /// [`missing`] with the existence check supplied (tests count the file-system calls). pub fn missing_with(cat: &Catalog, mut exists: impl FnMut(&str) -> bool) -> Vec<(PhotoId, String)> { - cat.photos().filter_map(|p| checked_path(p).filter(|f| !exists(f)).map(|f| (p.id, f.to_string()))).collect() + cat.photos().filter_map(|p| p.library_file().filter(|f| !exists(f)).map(|f| (p.id, f.to_string()))).collect() } /// Library photos whose original file can't be found: (id, path). @@ -45,11 +32,11 @@ pub fn missing(s: &Session) -> Vec<(PhotoId, String)> { missing_with(&s.catalog, |f| exists(f)) } -/// Every in-scope photo with its file ([`checked_path`]), without touching the disk: what a +/// Every in-scope photo with its file ([`Photo::library_file`]), without touching the disk: what a /// sweep ([`sweep`]) goes through, so a caller can take the list on its own thread and check /// the files on another. pub fn checked(cat: &Catalog) -> Vec<(PhotoId, String)> { - cat.photos().filter_map(|p| checked_path(p).map(|f| (p.id, f.to_string()))).collect() + cat.photos().filter_map(|p| p.library_file().map(|f| (p.id, f.to_string()))).collect() } fn fingerprint_of<'a>(entries: impl Iterator) -> u64 { @@ -66,7 +53,7 @@ fn fingerprint_of<'a>(entries: impl Iterator) -> u64 /// files on another thread compares it with [`fingerprint_of_checked`] to know whether the photos /// changed meanwhile. pub fn fingerprint(cat: &Catalog) -> u64 { - fingerprint_of(cat.photos().filter_map(|p| checked_path(p).map(|f| (p.id, f)))) + fingerprint_of(cat.photos().filter_map(|p| p.library_file().map(|f| (p.id, f)))) } /// [`fingerprint`] of the list [`checked`] gave. @@ -78,7 +65,7 @@ pub fn fingerprint_of_checked(files: &[(PhotoId, String)]) -> u64 { /// photos still in scope that still point at the file that was not found. A photo removed, moved to /// Recently Deleted or relinked since is not reported as missing; one added since was not checked. pub fn still_missing(cat: &Catalog, gone: Vec<(PhotoId, String)>) -> Vec<(PhotoId, String)> { - gone.into_iter().filter(|(id, file)| cat.photo(*id).and_then(|p| checked_path(p)) == Some(file.as_str())).collect() + gone.into_iter().filter(|(id, file)| cat.photo(*id).and_then(|p| p.library_file()) == Some(file.as_str())).collect() } /// How many files [`sweep`] checks between two reports of its progress. @@ -118,7 +105,7 @@ pub fn missing_json(gone: Vec<(PhotoId, String)>) -> Value { /// the photos its query already narrowed to). In the app `avail` answers from its cache (files /// not checked yet count as present until the background check finds them gone). pub fn is_missing(cat: &Catalog, avail: &crate::availability::Availability, id: PhotoId) -> bool { - !cfg!(target_arch = "wasm32") && cat.photo(id).and_then(|p| checked_path(p)).is_some_and(|f| avail.is_offline(f)) + !cfg!(target_arch = "wasm32") && cat.photo(id).and_then(|p| p.library_file()).is_some_and(|f| avail.is_offline(f)) } pub(crate) fn relink_op(id: PhotoId, path: &str) -> Op { @@ -240,7 +227,7 @@ mod tests { } } -/// An in-scope photo ([`checked_path`]) as Find Missing Photos sees it: its file, the size and +/// An in-scope photo ([`Photo::library_file`]) as Find Missing Photos sees it: its file, the size and /// content hash the library knows (0 / `None` = unknown). #[derive(Clone, Debug, PartialEq, Eq)] pub struct FindCandidate { @@ -256,7 +243,7 @@ pub struct FindCandidate { pub fn find_candidates(cat: &Catalog) -> Vec { cat.photos() .filter_map(|p| { - checked_path(p).map(|f| FindCandidate { id: p.id, path: f.to_string(), size: p.file_size, hash: stored_hash(p).map(str::to_string) }) + p.library_file().map(|f| FindCandidate { id: p.id, path: f.to_string(), size: p.file_size, hash: stored_hash(p).map(str::to_string) }) }) .collect() } @@ -455,7 +442,7 @@ pub fn plan_find_missing(candidates: &[FindCandidate], folder: &str) -> std::res /// used (that photo stays missing). `missing` is the plan's count, corrected for what changed /// among the photos the plan names. fn commit_find(s: &mut Session, plan: FindPlan) -> Result { - let still_at = |cat: &Catalog, id: PhotoId, from: &str| cat.photo(id).and_then(|p| checked_path(p)) == Some(from); + let still_at = |cat: &Catalog, id: PhotoId, from: &str| cat.photo(id).and_then(|p| p.library_file()) == Some(from); let mut in_use: HashSet = candidates(&s.catalog).into_iter().collect(); let mut found = Vec::new(); let mut missing = plan.missing; diff --git a/crates/engine/src/cmd/previews.rs b/crates/engine/src/cmd/previews.rs index 404e3fbdc8..2d487fcdb3 100644 --- a/crates/engine/src/cmd/previews.rs +++ b/crates/engine/src/cmd/previews.rs @@ -9,7 +9,7 @@ use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use serde_json::{Value, json}; use super::{CommandSpec, always, bad, cmd, str_param}; -use crate::activity::{Cancel, TaskGuard}; +use crate::activity::{Cancel, Lane, Request, TaskGuard}; use crate::media::{RenderJob, THUMB_SIZES}; use crate::{Result, Session}; @@ -25,6 +25,9 @@ pub struct PreviewBuild { /// Shared with the build's row in the activity stack (its ✕ sets it). pub cancel: Arc, pub finished: AtomicBool, + /// A frontend announced how it ended (the app's toast); one that ended and was not announced is kept when the next + /// build replaces it ([`Session::take_unreported_builds`]). + pub reported: AtomicBool, /// Damaged smart previews rebuilt (Build Smart Previews only). pub repaired: AtomicUsize, /// What is built ("" = previews; "smart previews" — Build Smart Previews runs the same way). @@ -194,19 +197,97 @@ impl Drop for Building { } } -/// The build's row in the activity stack (`what` as in [`PreviewBuild::what`]). -fn task_for(s: &Session, state: &PreviewBuild) -> TaskGuard { - let (kind, label) = match state.what { - "" if state.background => ("previews", "Preparing photos in the background"), +/// The row in the activity stack of a build of `what` (as in [`PreviewBuild::what`]), `background`: the background +/// preparation's build ([`PreviewBuild::background`]): its kind and its label. +fn row_of(what: &str, background: bool) -> (&'static str, &'static str) { + match what { + "" if background => ("previews", "Preparing photos in the background"), "" => ("previews", "Building previews"), "smart previews" => ("smartPreviews", "Building smart previews"), _ => ("smartPreviews", "Discarding smart previews"), - }; + } +} + +/// The build's row in the activity stack. +fn task_for(s: &Session, state: &PreviewBuild) -> TaskGuard { + let (kind, label) = row_of(state.what, state.background); let task = s.activity.start(kind, label, Cancel::Flag(state.cancel.clone())); task.progress(0, state.total as u64); task } +/// A build's state and its row, which go together. However the build ends (it finishes, its worker panics, or the +/// worker can't be started) the state reads as finished first, and then the row goes: a build waiting in line starts +/// when the row is gone, and is refused if the state still said a build runs. A build that did not mark itself +/// finished did not end well: it says so, instead of reading as one that built nothing. +/// (A build asked for with `row: false` has no row: the job that asked shows it.) +struct Running { + state: Arc, + task: Option, +} + +impl Drop for Running { + fn drop(&mut self) { + if !self.state.finished.load(Ordering::Relaxed) { + self.state + .error + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .get_or_insert_with(|| "the build stopped unexpectedly".to_string()); + } + self.state.finished.store(true, Ordering::Relaxed); + } +} + +/// Make `state` the session's current build. A build that ended and was not announced yet ([`PreviewBuild::reported`]) +/// is kept for the frontend to announce ([`Session::take_unreported_builds`]), so that starting the next one right +/// after it (as a build waiting in line does) does not lose its result, its failed count or its error. +fn set_current(s: &mut Session, state: Arc) { + if let Some(old) = s.preview_build.replace(state) + && old.finished.load(Ordering::Relaxed) + && !old.reported.load(Ordering::Relaxed) + { + s.keep_unreported_build(old); + } +} + +/// What a build of `ids` was asked, as it runs later (from the line): the photos written out (the selection or the +/// view may have changed by then), in the background (nothing waits for it then), and not queued again. +fn request_for(command: &str, p: &Value, ids: &[lightcraft_catalog::PhotoId]) -> Request { + let mut params = p.as_object().cloned().unwrap_or_default(); + for key in ["id", "queue", "wait"] { + params.remove(key); + } + params.insert("ids".into(), ids.iter().map(|id| id.0).collect()); + Request { command: command.into(), params: Value::Object(params) } +} + +/// The refusal of a build while another runs, unless the call asks to `queue`. +const REFUSED: &str = "a preview build is already running"; + +/// Builds wait in line ahead of one asked for now (not counting the line a build is being started from). +fn line_ahead(s: &Session) -> bool { + !s.starting_waiting && s.activity.lane_waiting(Lane::Previews) +} + +fn queue_param(p: &Value) -> bool { + p.get("queue").and_then(Value::as_bool).unwrap_or(false) +} + +/// A build asked for with `queue`: while one runs (`busy`: one that does not give way to this one) or others already +/// wait, this one waits in line behind them → `{queued: id, place}`. `None`: nothing is ahead of it, so it starts now. +fn wait_in_line(s: &Session, c: &str, p: &Value, what: &str, busy: bool, request: &Request) -> Option> { + if !busy && !s.activity.lane_waiting(Lane::Previews) { + return None; + } + if p.get("wait").and_then(Value::as_bool) == Some(true) { + return Some(Err(bad(c, "a build that waits in line can't also be waited for: leave out wait"))); + } + let background = p.get("background").and_then(Value::as_bool).unwrap_or(false); + let (kind, label) = row_of(what, background); + Some(s.activity.enqueue(kind, label, request.clone()).map(|(id, place)| json!({"queued": id, "place": place})).map_err(|e| bad(c, e))) +} + /// Render one photo's jobs in order. The source the first job decodes serves the ones after it /// (the grid thumbnail is made from the view's source instead of decoding the file again). /// `None` when `cancel` was asked for before a job started: that photo is not counted as done. @@ -494,18 +575,26 @@ fn build(s: &mut Session, p: &Value) -> Result { let force = p.get("force").and_then(Value::as_bool).unwrap_or(false); // (`row: false`: the job that asked shows the progress in its own row) let row = p.get("row").and_then(Value::as_bool).unwrap_or(true); + let queue = queue_param(p); // the background preparation gives way to a build that was asked for; nothing replaces a build // that was asked for (it carries on, and the photos it built are skipped by the next). The // background one is stopped only once this request is known to be good (below): a request // with bad ids leaves it running (CodeRabbit on #3544) let mut gives_way = None; + // (a build that runs and does not give way: this one is refused, or waits in line) + let mut busy = false; if let Some(b) = s.preview_build.as_ref().filter(|b| b.running()) { if b.background && !background { gives_way = Some(b.cancel.clone()); } else { - return Err(bad(C, "a preview build is already running")); + busy = true; } } + // (nor ahead of builds already waiting: the line starts them after this command, in the order asked; the build + // `start_waiting` is starting itself is not held back by the line it came out of) + if !queue && (busy || line_ahead(s)) { + return Err(bad(C, REFUSED)); + } s.fit_disk_cache(); // explicit ids, else the selected photos (more than one: as the menu says), else everything in // view (a single photo selected is the one open, not a choice of photos: "Visible" in the menu) @@ -514,6 +603,9 @@ fn build(s: &mut Session, p: &Value) -> Result { } else { s.visible_cloned() }; + if queue && let Some(queued) = wait_in_line(s, C, p, "", busy, &request_for(C, p, &ids)) { + return queued; + } let jobs: Vec = ids.iter().map(|id| (id.0, jobs_for(s, *id, edge))).filter(|j| !j.1.is_empty()).collect(); // the background build stays the session's until this one has started (a worker that can't // start leaves it running and in place: CodeRabbit on #3544) @@ -529,8 +621,8 @@ fn build(s: &mut Session, p: &Value) -> Result { if let Some(at) = p.get("from").and_then(Value::as_u64) { state.focus_on(lightcraft_catalog::PhotoId(at), p.get("backward").and_then(Value::as_bool).unwrap_or(false)); } - s.preview_build = Some(state.clone()); - let task = row.then(|| task_for(s, &state)); + set_current(s, state.clone()); + let run = Running { task: row.then(|| task_for(s, &state)), state: state.clone() }; // the background preparation leaves most of the machine to the photo on screen and the user let lanes = if background { crate::prep::background_lanes() } else { lanes(jobs.len(), edge.is_none()) }; let wait = p.get("wait").and_then(Value::as_bool).unwrap_or(false) || cfg!(target_arch = "wasm32"); @@ -538,22 +630,22 @@ fn build(s: &mut Session, p: &Value) -> Result { if let Some(cancel) = gives_way { cancel.store(true, Ordering::Relaxed); } - run_all(jobs, &state, task.as_ref(), lanes, force); + run_all(jobs, &run.state, run.task.as_ref(), lanes, force); return Ok(state.json()); } #[cfg(not(target_arch = "wasm32"))] { // the row stays while the worker runs (it is dropped with the closure, however that ends) - let st = state.clone(); #[cfg(test)] let started = if test_gate::take_fail_spawn() { - drop(task); + drop(run); Err(std::io::Error::other("no thread (test)")) } else { - std::thread::Builder::new().name("lc-build-previews".into()).spawn(move || run_all(jobs, &st, task.as_ref(), lanes, force)) + std::thread::Builder::new().name("lc-build-previews".into()).spawn(move || run_all(jobs, &run.state, run.task.as_ref(), lanes, force)) }; #[cfg(not(test))] - let started = std::thread::Builder::new().name("lc-build-previews".into()).spawn(move || run_all(jobs, &st, task.as_ref(), lanes, force)); + let started = + std::thread::Builder::new().name("lc-build-previews".into()).spawn(move || run_all(jobs, &run.state, run.task.as_ref(), lanes, force)); if let Err(e) = started { // never started: not left "running", which would hold every later build back, and the // build it was to replace carries on @@ -767,15 +859,24 @@ fn smart(s: &mut Session, p: &Value) -> Result { // (as Build Previews: the photos named, or the selected ones when more than one is, else // everything in view; read first, so a request with bad ids stops nothing: CodeRabbit on #3577) let ids = if p.get("ids").is_some() || p.get("id").is_some() || s.selection.ids.len() > 1 { s.targets(p)? } else { s.visible_cloned() }; + let queue = background && queue_param(p); // (the background preparation gives way, as to Build Previews: once this one's worker has started) let mut gives_way = None; + let mut busy = false; if background && let Some(b) = s.preview_build.as_ref().filter(|b| b.running()) { if b.background { gives_way = Some(b.cancel.clone()); } else { - return Err(bad(C, "a preview build is already running")); + busy = true; } } + if background && !queue && (busy || line_ahead(s)) { + return Err(bad(C, REFUSED)); + } + let what = if discard { "discarding smart previews" } else { "smart previews" }; + if queue && let Some(queued) = wait_in_line(s, C, p, what, busy, &request_for(C, p, &ids)) { + return queued; + } let mut jobs: Vec = Vec::new(); for id in ids { let Some(ph) = s.catalog.photo(id).cloned() else { continue }; @@ -790,17 +891,17 @@ fn smart(s: &mut Session, p: &Value) -> Result { } let custom = s.smart_previews_dir.is_some(); if background { - let what = if discard { "discarding smart previews" } else { "smart previews" }; let state = Arc::new(PreviewBuild { total: jobs.len(), what, ..Default::default() }); - let previous = s.preview_build.replace(state.clone()); - let task = task_for(s, &state); - let st = state.clone(); + let previous = s.preview_build.clone(); + set_current(s, state.clone()); + // (this build always has its row) + let run = Running { task: Some(task_for(s, &state)), state: state.clone() }; let work = move || { - if let Err(e) = smart_run(&dir, custom, discard, jobs, Some((&st, &task))) { + if let Err(e) = smart_run(&dir, custom, discard, jobs, run.task.as_ref().map(|task| (&*run.state, task))) { log::warn!("{C}: {e}"); - *st.error.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(e); + *run.state.error.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(e); } - st.finished.store(true, Ordering::Relaxed); + run.state.finished.store(true, Ordering::Relaxed); }; #[cfg(test)] let started = if test_gate::take_fail_spawn() { @@ -958,7 +1059,7 @@ pub fn specs() -> Vec { "Build Smart Previews", [], None, - "{ids?, discard?: bool, background?: bool} — build (or discard) the smart previews of the selected photos (when more than one is selected; else all in view): compact proxies in the library that keep photos editable and exportable (at proxy size) while their originals are offline; a damaged proxy (cut short) is rebuilt → {built, repaired, refreshed, staleKept, newerKept, removed, failed}; with background (the app's menu) the files are read and written on a worker thread → {total, done, failed, repaired, running, what} like library.buildPreviews (progress: library.previewProgress, stop: library.cancelPreviews)", + "{ids?, discard?: bool, background?: bool, queue?: bool} — build (or discard) the smart previews of the selected photos (when more than one is selected; else all in view): compact proxies in the library that keep photos editable and exportable (at proxy size) while their originals are offline; a damaged proxy (cut short) is rebuilt → {built, repaired, refreshed, staleKept, newerKept, removed, failed}; with background (the app's menu) the files are read and written on a worker thread → {total, done, failed, repaired, running, what} like library.buildPreviews (progress: library.previewProgress, stop: library.cancelPreviews). A background one while a preview build runs is refused, or with queue waits in line for it, as library.buildPreviews does → {queued, place}", always, smart ), @@ -985,7 +1086,7 @@ pub fn specs() -> Vec { "Build Previews", [], None, - "{size?: standard (2048 px, or the loupe's size when bigger, or `edge`) | full (1:1), ids?, wait?: bool, force?: bool, from?: id, backward?: bool, background?: bool, row?: bool} — render the grid thumbnail and loupe view of the selected photos (when more than one is selected; else all in view) into the preview cache (memory and disk), in the background unless `wait`. Photos whose previews are there already (big enough) are skipped unless `force`; the photos nearest `from` go first. `background`: the background preparation's build (two lanes, waits while the photo on screen renders; a build asked for replaces it). `row: false`: no row of its own in the activity stack (the caller's row shows it) → {total, done, failed, skipped, shared, running}", + "{size?: standard (2048 px, or the loupe's size when bigger, or `edge`) | full (1:1), ids?, wait?: bool, force?: bool, from?: id, backward?: bool, background?: bool, row?: bool, queue?: bool} — render the grid thumbnail and loupe view of the selected photos (when more than one is selected; else all in view) into the preview cache (memory and disk), in the background unless `wait`. Photos whose previews are there already (big enough) are skipped unless `force`; the photos nearest `from` go first. `background`: the background preparation's build (two lanes, waits while the photo on screen renders; a build asked for replaces it). `row: false`: no row of its own in the activity stack (the caller's row shows it) → {total, done, failed, skipped, shared, running}. One build runs at a time (this, or Build / Discard Smart Previews in the background; the background preparation gives way to a build asked for): while one runs another is refused, or with queue waits in line for it and starts by itself when the builds ahead of it end → {queued: its activity id, place: 1 = next}. It builds the photos chosen when it was asked; activity.list shows it waiting, activity.cancel takes it out of the line. Not with wait while one runs", always, build ), @@ -1088,4 +1189,38 @@ mod tests { assert_eq!(r["total"], json!(ids.len())); assert_eq!(r["failed"], json!(0)); } + // Given a build whose worker dies (or can't start), the build reads as finished and its row goes, so that a + // build waiting in line starts instead of being refused as "already running" + #[test] + fn a_build_whose_worker_dies_reads_as_finished_before_its_row_goes() { + use std::sync::Arc; + use std::sync::atomic::Ordering; + + let s = Session::with_demo(); + let state = Arc::new(super::PreviewBuild::default()); + let run = super::Running { task: Some(super::task_for(&s, &state)), state: state.clone() }; + assert!(s.activity.lane_busy(crate::activity::Lane::Previews)); + let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || { + let _run = run; + panic!("synthetic worker panic"); + })); + assert!(r.is_err()); + assert!(state.finished.load(Ordering::Relaxed)); + assert_eq!(state.error().as_deref(), Some("the build stopped unexpectedly"), "a crash is not a success that built nothing"); + assert!(!s.activity.lane_busy(crate::activity::Lane::Previews)); + } + + // Given a build that marked itself finished, its row going leaves no error + #[test] + fn a_build_that_finished_leaves_no_error() { + use std::sync::Arc; + use std::sync::atomic::Ordering; + + let s = Session::with_demo(); + let state = Arc::new(super::PreviewBuild::default()); + let run = super::Running { task: Some(super::task_for(&s, &state)), state: state.clone() }; + state.finished.store(true, Ordering::Relaxed); + drop(run); + assert!(state.error().is_none()); + } } diff --git a/crates/engine/src/cmd/recheck.rs b/crates/engine/src/cmd/recheck.rs index a7d40a8370..359f588ae5 100644 --- a/crates/engine/src/cmd/recheck.rs +++ b/crates/engine/src/cmd/recheck.rs @@ -36,9 +36,7 @@ impl Stale { /// The photo is still as it was listed: same file, flag and stamp. fn current(&self, p: &Photo) -> bool { - crate::cmd::missing::checked_path(p) == Some(self.path.as_str()) - && p.preview_only == self.preview_only - && p.preview_checked == self.preview_checked + p.library_file() == Some(self.path.as_str()) && p.preview_only == self.preview_only && p.preview_checked == self.preview_checked } } @@ -48,7 +46,7 @@ impl Stale { pub fn stale(cat: &Catalog, all: bool) -> Vec { cat.photos() .filter(|p| p.copy_of.is_none() && (p.preview_only_stale() || (all && (p.preview_only.is_some() || p.format.eq_ignore_ascii_case("orf"))))) - .filter_map(|p| crate::cmd::missing::checked_path(p).map(|path| Stale::of(p, path))) + .filter_map(|p| p.library_file().map(|path| Stale::of(p, path))) .collect() } diff --git a/crates/engine/src/cmd/xmp.rs b/crates/engine/src/cmd/xmp.rs index d48ca3cd24..49922ce992 100644 --- a/crates/engine/src/cmd/xmp.rs +++ b/crates/engine/src/cmd/xmp.rs @@ -84,7 +84,7 @@ pub fn specs() -> Vec { cmd!( "photo.saveMetadataToFile", "Save Metadata to File", - ["Photo"], + ["Photo", "Metadata"], Some("Cmd+S"), "{ids?} — writes each photo's XMP sidecar (metadata + develop settings) next to the original, merged into an existing one (other apps' data kept; an unreadable one is backed up first) → {written: [path], merged: [path], backups: [{path, backup}], failed}", has_selection, @@ -93,7 +93,7 @@ pub fn specs() -> Vec { cmd!( "photo.readMetadataFromFile", "Read Metadata from File", - ["Photo"], + ["Photo", "Metadata"], None, "{ids?} — reads each photo's XMP sidecar, or embedded XMP in raw/DNG and JPEG files when no sidecar exists: metadata and develop settings, one undo step; never writes the sidecar, even with auto-write on; JPEG uses the first complete standard XMP APP1 before SOS/EOI, within 16 MiB of headers and 4096 marker/fill steps; an unreadable sidecar fails without embedded fallback → {read, failed, warnings?: [{path, code, profile?, mode?, fields?}]}", has_selection, diff --git a/crates/engine/src/config.rs b/crates/engine/src/config.rs index 8519f89bf0..7d010774d5 100644 --- a/crates/engine/src/config.rs +++ b/crates/engine/src/config.rs @@ -164,11 +164,14 @@ fn sam3_dir(var: Option, config: Option) -> Option< } impl Session { - /// Look for the SAM 3 model in the shared default folder ([`default_sam3_dir`]), and for the user's - /// download mirrors in `/models/sam3-mirrors.txt`. + /// Look for the SAM 3 model in the shared default folder ([`default_sam3_dir`]), for the user's + /// download mirrors in `/models/sam3-mirrors.txt` and for where it runs in + /// `/models/sam3-settings.json`. pub fn with_default_sam3_model(mut self) -> Self { self.segmenter.dir = default_sam3_dir(); self.segmenter.mirrors_file = config_dir().map(|d| d.join("models").join("sam3-mirrors.txt")); + self.segmenter.settings_file = config_dir().map(|d| d.join("models").join("sam3-settings.json")); + self.segmenter.load_settings(); self } diff --git a/crates/engine/src/demo.rs b/crates/engine/src/demo.rs index c89f29e0aa..4b085dfd63 100644 --- a/crates/engine/src/demo.rs +++ b/crates/engine/src/demo.rs @@ -31,7 +31,7 @@ pub fn load(s: &mut Session) { ..Default::default() }; // one demo photo carries a camera focus point (as a Sony raw would), on the bloom's centre, so - // View ▸ Focus Point and Zoom to Focus Point can be tried without a camera file + // View ▸ Loupe Overlay ▸ Focus Point and Zoom to Focus Point can be tried without a camera file if sc.name == "Cosmos bloom" { p.meta.focus = Some(lightcraft_meta::FocusPoint { rect: lightcraft_geom::Rect { x0: 0.42, y0: 0.433, x1: 0.50, y1: 0.487 }, diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index 8ba08021f5..aef3547745 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -39,7 +39,7 @@ pub use params::{ }; #[cfg(test)] use place::Placer; -pub use place::{write_file, write_file_durable, write_file_new}; +pub use place::{clean_album_name, clean_subfolder, expand_subfolder, write_file, write_file_durable, write_file_new}; pub use prepare::{ AfterExport, Destination, DngCompression, Exported, PreparedExport, export_batch, export_photo, output_size, prepare_batch, prepare_export, }; @@ -74,7 +74,10 @@ pub struct ExportOptions { pub start_number: u32, /// A specific folder for the whole batch, or each photo's own folder. pub destination_mode: DestinationMode, - /// Created inside the destination folder (empty = none). + /// Created inside the destination folder (empty = none). Supports `{album}`, `{date}` + /// (YYYYMMDD) and `{hour}` (HHMM, both in local time) variables, expanded during batch preparation + /// once per batch using the active album view (or empty outside an album view). Presets store + /// the raw template. pub subfolder: String, /// When a file of the same name exists in the destination folder. pub conflict: Conflict, diff --git a/crates/engine/src/export/batch.rs b/crates/engine/src/export/batch.rs index b5d45b1254..86853dd7a5 100644 --- a/crates/engine/src/export/batch.rs +++ b/crates/engine/src/export/batch.rs @@ -51,12 +51,13 @@ pub(super) fn run_batch_with( if !progress(i, &item.file_name) { break; } - let (photo, name, guard, source_dir) = (item.photo, item.file_name.clone(), item.guard.clone(), item.source_dir.clone()); - placer.place(photo, name, source_dir.as_deref(), &guard, run_gated(item))?; + let (photo, name, guard, source_dir, subfolder) = + (item.photo, item.file_name.clone(), item.guard.clone(), item.source_dir.clone(), item.subfolder.clone()); + placer.place(photo, name, source_dir.as_deref(), Some(&subfolder), &guard, run_gated(item))?; } return Ok(std::mem::take(&mut placer.out)); } - let heads: Vec<_> = items.iter().map(|i| (i.photo, i.file_name.clone(), i.guard.clone(), i.source_dir.clone())).collect(); + let heads: Vec<_> = items.iter().map(|i| (i.photo, i.file_name.clone(), i.guard.clone(), i.source_dir.clone(), i.subfolder.clone())).collect(); let queue = Queue { lane: std::sync::Mutex::new(Lane { items: items.into_iter().map(Some).collect(), next: 0, placed: 0, stop: false, done: Default::default() }), cv: std::sync::Condvar::new(), @@ -74,12 +75,12 @@ pub(super) fn run_batch_with( } } let placed = || { - for (i, (photo, name, guard, source_dir)) in heads.into_iter().enumerate() { + for (i, (photo, name, guard, source_dir, subfolder)) in heads.into_iter().enumerate() { if !progress(i, &name) { break; } let e = queue.result(i); - placer.place(photo, name, source_dir.as_deref(), &guard, e)?; + placer.place(photo, name, source_dir.as_deref(), Some(&subfolder), &guard, e)?; } Ok::<_, String>(()) }; diff --git a/crates/engine/src/export/encoding.rs b/crates/engine/src/export/encoding.rs index 957b932104..7f88982852 100644 --- a/crates/engine/src/export/encoding.rs +++ b/crates/engine/src/export/encoding.rs @@ -6,7 +6,7 @@ use super::{ }; use std::borrow::Cow; -/// Unsharp mask on an 8-bit image (separable box-blur approximation of a small Gaussian). +/// Output sharpening of an 8-bit image: an unsharp mask on its luma ([`unsharp`]). pub fn output_sharpen(img: &mut Rgba8, target: SharpenFor, amount: SharpenAmount) { if !sharpens(img.width, img.height, target) { return; @@ -37,7 +37,8 @@ pub fn output_sharpen_deep(img: &mut DeepImage, target: SharpenFor, amount: Shar } } DeepSamples::F32(v) => { - let src: Vec<[f32; 3]> = v.as_chunks::<3>().0.iter().map(|c| [c[0], c[1], c[2]]).collect(); + // A NaN or infinite sample would poison its neighbours' blur and local range; treat it as black. + let src: Vec<[f32; 3]> = v.as_chunks::<3>().0.iter().map(|c| [c[0], c[1], c[2]].map(|x| if x.is_finite() { x } else { 0.0 })).collect(); if let Some(out) = unsharp(w, h, &src, target, amount) { for (d, s) in v.iter_mut().zip(out.as_flattened()) { *d = s.max(0.0); @@ -52,47 +53,72 @@ fn sharpens(w: usize, h: usize, target: SharpenFor) -> bool { target != SharpenFor::None && w >= 3 && h >= 3 } -/// The sharpened values of `src` (`w × h`), or `None` when nothing is to be done. +/// How far a sharpened pixel may pass the darkest and lightest of its 3×3 neighbours, as a share +/// of their difference: enough for crisp edges, too little for the light and dark rims (halos) +/// a plain unsharp mask draws along strong edges. +const SHARPEN_OVERSHOOT: f32 = 0.1; + +/// The sharpened values of `src` (`w × h`), or `None` when nothing is to be done: an unsharp mask +/// at the output's own pixel scale (a Gaussian of radius `sigma` output pixels), on luma only (no +/// colour fringes), with its overshoot past the local range limited ([`SHARPEN_OVERSHOOT`]). Print +/// media blur more than a screen and get a wider, stronger mask. The values may be on any scale. fn unsharp(w: usize, h: usize, src: &[[f32; 3]], target: SharpenFor, amount: SharpenAmount) -> Option> { - let (radius, base) = match target { + let (sigma, base) = match target { SharpenFor::None => return None, - SharpenFor::Screen => (1usize, 0.35f32), - SharpenFor::Matte => (2, 0.6), - SharpenFor::Glossy => (1, 0.5), + SharpenFor::Screen => (0.7f32, 0.65f32), + SharpenFor::Glossy => (0.8, 0.85), + SharpenFor::Matte => (1.0, 1.05), }; let k = base * match amount { - SharpenAmount::Low => 0.6, + SharpenAmount::Low => 0.5, SharpenAmount::Standard => 1.0, - SharpenAmount::High => 1.5, + SharpenAmount::High => 1.6, }; if w < 3 || h < 3 { return None; } - let r = radius as isize; - let box_pass = |inp: &[[f32; 3]], horizontal: bool| -> Vec<[f32; 3]> { - let mut out = vec![[0.0; 3]; inp.len()]; - // rows in parallel: each output pixel is computed on its own, so the bits don't depend on the split - lightcraft_raster::par_rows(&mut out, w, |y, row| { - for (x, o) in row.iter_mut().enumerate() { - let mut acc = [0.0f32; 3]; - for d in -r..=r { - let (sx, sy) = if horizontal { - ((x as isize + d).clamp(0, w as isize - 1) as usize, y) - } else { - (x, (y as isize + d).clamp(0, h as isize - 1) as usize) - }; - let p = inp[sy * w + sx]; - acc = [acc[0] + p[0], acc[1] + p[1], acc[2] + p[2]]; - } - let n = (2 * r + 1) as f32; - *o = acc.map(|v| v / n); - } - }); - out - }; - let blur = box_pass(&box_pass(src, true), false); - Some(src.iter().zip(&blur).map(|(s, b)| std::array::from_fn(|c| s[c] + (s[c] - b[c]) * k)).collect()) + let luma: Vec = src.iter().map(|p| 0.299 * p[0] + 0.587 * p[1] + 0.114 * p[2]).collect(); + let r = (3.0 * sigma).ceil() as isize; + let taps: Vec = (-r..=r).map(|d| (-((d * d) as f32) / (2.0 * sigma * sigma)).exp()).collect(); + let norm: f32 = taps.iter().sum(); + let taps: Vec = taps.iter().map(|t| t / norm).collect(); + let gauss = |acc: f32, d: isize, v: f32| acc + v * taps[(d + r) as usize]; + let blur = separable(&separable(&luma, w, h, r, true, 0.0, gauss), w, h, r, false, 0.0, gauss); + let lo = |acc: f32, _: isize, v: f32| acc.min(v); + let hi = |acc: f32, _: isize, v: f32| acc.max(v); + let lo = separable(&separable(&luma, w, h, 1, true, f32::INFINITY, lo), w, h, 1, false, f32::INFINITY, lo); + let hi = separable(&separable(&luma, w, h, 1, true, f32::NEG_INFINITY, hi), w, h, 1, false, f32::NEG_INFINITY, hi); + Some( + src.iter() + .enumerate() + .map(|(i, p)| { + let (y, margin) = (luma[i], (hi[i] - lo[i]) * SHARPEN_OVERSHOOT); + // max/min rather than clamp: never panics, even on bounds a non-finite input left inverted or NaN. + let sharp = (y + (y - blur[i]) * k).max(lo[i] - margin).min(hi[i] + margin); + p.map(|v| v + sharp - y) + }) + .collect(), + ) +} + +/// One pass of a separable filter over a `w × h` plane: each value folds (`f(acc, offset, value)`, +/// from `init`) its neighbours up to `reach` away along a row (`horizontal`) or a column, edges repeated. +fn separable(inp: &[f32], w: usize, h: usize, reach: isize, horizontal: bool, init: f32, f: impl Fn(f32, isize, f32) -> f32 + Sync) -> Vec { + let mut out = vec![0.0; inp.len()]; + lightcraft_raster::par_rows(&mut out, w, |y, row| { + for (x, o) in row.iter_mut().enumerate() { + *o = (-reach..=reach).fold(init, |acc, d| { + let i = if horizontal { + y * w + (x as isize + d).clamp(0, w as isize - 1) as usize + } else { + (y as isize + d).clamp(0, h as isize - 1) as usize * w + x + }; + f(acc, d, inp[i]) + }); + } + }); + out } /// Encode a rendered display-referred image according to `o` (its pixels must already be in diff --git a/crates/engine/src/export/place.rs b/crates/engine/src/export/place.rs index c36f5e26bc..a77f47a592 100644 --- a/crates/engine/src/export/place.rs +++ b/crates/engine/src/export/place.rs @@ -63,11 +63,106 @@ fn join_path(a: &str, b: &str) -> String { /// A subfolder that stays inside the destination folder (issue #2571): `\`, `:` and NUL become `_` /// (so no drive, root or Windows separator), and empty, `.` and `..` parts are dropped; `a/b` still /// nests. Applied where the folder is used, so presets and the Export dialog's field are covered too. -pub(super) fn clean_subfolder(s: &str) -> String { +pub fn clean_subfolder(s: &str) -> String { let s = s.trim().replace(['\\', ':', '\0'], "_"); s.split('/').map(str::trim).filter(|p| !p.is_empty() && *p != "." && *p != "..").collect::>().join("/") } +/// Clean an album name so it is safe to use as a directory or path component. +/// +/// Characters `/ \ : * ? " < > | \0` and control characters become `_`, and surrounding +/// whitespace and dots are trimmed. Windows-reserved device names (`CON`, `PRN`, `AUX`, `NUL`, +/// `COM1`–`COM9`, `LPT1`–`LPT9`, plus superscript forms `COM¹`–`COM³`, `LPT¹`–`LPT³`, case-insensitive) +/// get `_` inserted after the base component so they remain usable directory components. The result +/// may be empty if the album name consisted entirely of dots or whitespace. +pub fn clean_album_name(album: &str) -> String { + let mut s: String = album + .chars() + .map(|c| if matches!(c, '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|' | '\0') || c.is_control() { '_' } else { c }) + .collect(); + loop { + let trimmed = s.trim().trim_matches('.'); + if trimmed == s { + break; + } + s = trimmed.to_string(); + } + let base = s.split('.').next().unwrap_or(&s); + let upper = base.to_uppercase(); + if matches!( + upper.as_str(), + "CON" + | "PRN" + | "AUX" + | "NUL" + | "COM1" + | "COM2" + | "COM3" + | "COM4" + | "COM5" + | "COM6" + | "COM7" + | "COM8" + | "COM9" + | "LPT1" + | "LPT2" + | "LPT3" + | "LPT4" + | "LPT5" + | "LPT6" + | "LPT7" + | "LPT8" + | "LPT9" + | "COM¹" + | "COM²" + | "COM³" + | "LPT¹" + | "LPT²" + | "LPT³" + ) { + s.insert(base.len(), '_'); + } + s +} + +/// Expand `{album}`, `{date}`, `{hour}` variables in a subfolder template, and clean the result +/// so it stays safely inside the destination folder. +/// +/// `{date}` and `{hour}` are expanded before `{album}`, so an album name that contains token-like +/// text (such as `{date}` or `{hour}`) is never double-expanded. +/// +/// - `album`: the active album name, cleaned with [`clean_album_name`]; `None` expands `{album}` to `""`. +/// - `now`: the local date and time for `{date}` (YYYYMMDD) and `{hour}` (HHMM), as the person's clock shows it +/// ([`local_now`]); `None` uses the time now. +/// - Unknown tokens are left unchanged. The result passes through [`clean_subfolder`]. +/// +/// E.g. `"{album}/{date}_{hour}"` with album `"Vacation"` produces `"Vacation/20261107_0230"`. +/// +/// Returns immediately without timestamp formatting or album lookup if `template` is empty or has no `{`. +pub fn expand_subfolder(template: &str, album: Option<&str>, now: Option) -> String { + if template.is_empty() || !template.contains('{') { + return clean_subfolder(template); + } + let now = now.or_else(local_now).unwrap_or_default(); + let date_str = now.format("%Y%m%d").to_string(); + let hour_str = now.format("%H%M").to_string(); + let album_str = album.map(clean_album_name).unwrap_or_default(); + + let res = template.replace("{date}", &date_str).replace("{hour}", &hour_str).replace("{album}", &album_str); + + clean_subfolder(&res) +} + +/// The date and time now on the person's clock, for `{date}` and `{hour}`: the host's zone, with the offset in force +/// now ([`crate::import::local_civil`]; the web build has no zone to read and uses UTC). A folder named by its +/// export date is named by the day the person exported on, not by UTC's, which is the next or the previous day +/// for part of every day away from UTC. +pub(super) fn local_now() -> Option { + let since = web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).unwrap_or_default(); + let secs = i64::try_from(since.as_secs()).unwrap_or(i64::MAX); + chrono::NaiveDateTime::parse_from_str(&crate::import::local_civil(secs), "%Y-%m-%dT%H:%M:%S").ok() +} + impl<'a> Placer<'a> { pub(super) fn new( o: &'a ExportOptions, @@ -82,7 +177,7 @@ impl<'a> Placer<'a> { /// The folder photo `name` (its original in `source_dir`) is written to: the batch's folder or /// the photo's own ([`DestinationMode`]), plus the subfolder. An error for a photo with no /// folder of its own, or whose folder is gone: never a file written somewhere else instead. - fn folder_for(&self, name: &str, source_dir: Option<&str>) -> Result { + fn folder_for(&self, name: &str, source_dir: Option<&str>, subfolder: Option<&str>) -> Result { let base = match self.o.destination_mode { DestinationMode::SpecificFolder => self.to.dir.clone(), DestinationMode::SameAsOriginal => { @@ -97,7 +192,7 @@ impl<'a> Placer<'a> { d.to_string() } }; - let sub = clean_subfolder(&self.o.subfolder); + let sub = subfolder.map(clean_subfolder).unwrap_or_else(|| expand_subfolder(&self.o.subfolder, None, None)); Ok(if sub.is_empty() { base } else { join_path(&base, &sub) }) } @@ -108,12 +203,13 @@ impl<'a> Placer<'a> { photo: lightcraft_catalog::PhotoId, name: String, source_dir: Option<&str>, + subfolder: Option<&str>, guard: &crate::originals::OriginalGuard, e: Result, ) -> Result<(), String> { use serde_json::json; // an exact file path needs no folder - let dir = if self.to.exact.is_some() && self.single { Ok(String::new()) } else { self.folder_for(&name, source_dir) }; + let dir = if self.to.exact.is_some() && self.single { Ok(String::new()) } else { self.folder_for(&name, source_dir, subfolder) }; let (o, exists) = (self.o, self.exists); let (dir, e) = match dir.and_then(|dir| e.map(|e| (dir, e))) { Ok(v) => v, diff --git a/crates/engine/src/export/prepare.rs b/crates/engine/src/export/prepare.rs index 997ae03e52..e2bfa6c79c 100644 --- a/crates/engine/src/export/prepare.rs +++ b/crates/engine/src/export/prepare.rs @@ -44,6 +44,9 @@ pub struct PreparedExport { /// The folder of the photo's original on disk ([`DestinationMode::SameAsOriginal`]); `None` /// for a demo photo or one in the browser's storage. pub source_dir: Option, + /// The already-expanded, cleaned subfolder path for this item. Resolved once per batch at + /// preparation time; no raw variable tokens are present. + pub subfolder: String, work: Work, /// The library's originals, which [`run_batch`] never writes over (shared by a batch). pub(super) guard: std::sync::Arc, @@ -88,13 +91,23 @@ pub fn prepare_export( seq: usize, ) -> Result { let guard = std::sync::Arc::new(session.original_guard()); - prepare_guarded(session, id, o, seq, guard) + let album_name = match session.source { + crate::LibrarySource::Album(aid) => session.catalog.album(aid).map(|a| a.name.clone()), + _ => None, + }; + prepare_guarded(session, id, o, seq, guard, None, album_name.as_deref()) } /// [`prepare_export`] for each of `ids` in order (`{seq}` = position, from 1). pub fn prepare_batch(session: &mut crate::Session, ids: &[lightcraft_catalog::PhotoId], o: &ExportOptions) -> Result, String> { let guard = std::sync::Arc::new(session.original_guard()); - ids.iter().enumerate().map(|(i, id)| prepare_guarded(session, *id, o, i + 1, guard.clone())).collect() + // the whole batch goes to one dated folder: the time is read once + let now = super::place::local_now(); + let album_name = match session.source { + crate::LibrarySource::Album(aid) => session.catalog.album(aid).map(|a| a.name.clone()), + _ => None, + }; + ids.iter().enumerate().map(|(i, id)| prepare_guarded(session, *id, o, i + 1, guard.clone(), now, album_name.as_deref())).collect() } fn prepare_guarded( @@ -103,10 +116,13 @@ fn prepare_guarded( o: &ExportOptions, seq: usize, guard: std::sync::Arc, + now: Option, + album: Option<&str>, ) -> Result { let p = session.catalog.photo(id).ok_or("no such photo")?; let file_name = o.file_name_for(p, seq); let source_dir = original_folder(&p.source); + let subfolder = super::place::expand_subfolder(&o.subfolder, album, now); // HDR output only for photos edited in HDR; the rest of the batch exports as usual let sdr_opts; let o = if o.hdr && !p.develop.hdr.enabled { @@ -162,7 +178,7 @@ fn prepare_guarded( }; (work, weight) }; - Ok(PreparedExport { photo: id, file_name, source_dir, work, guard, weight }) + Ok(PreparedExport { photo: id, file_name, source_dir, subfolder, work, guard, weight }) } /// The folder a photo's original is in, for [`DestinationMode::SameAsOriginal`]. None for a demo diff --git a/crates/engine/src/export/tests.rs b/crates/engine/src/export/tests.rs index c4dc644fd6..4af8bab03c 100644 --- a/crates/engine/src/export/tests.rs +++ b/crates/engine/src/export/tests.rs @@ -209,7 +209,7 @@ fn sharpen_increases_edge_contrast() { assert!(img.data[3][0] < 80 && img.data[4][0] > 170); } -/// Output sharpening's pixels for every target and amount, pinned (its box blurs run row-parallel, which must not +/// Output sharpening's pixels for every target and amount, pinned (its separable passes run row-parallel, which must not /// change a bit), on 8- and 16-bit images; with no target the image is left as it is. #[test] fn sharpened_pixels_are_pinned() { @@ -234,17 +234,66 @@ fn sharpened_pixels_are_pinned() { assert_eq!(img, test_image()); } const SHARPENED: [u64; 9] = [ - 0x1494_273e_0bdc_a61c, - 0x3fbb_40c4_74f4_b0c3, - 0xa27f_8ff5_82a0_99f9, - 0x6550_6571_a38d_4d9f, - 0x5e28_f4f3_fc8a_9685, - 0xdc2b_6f65_9138_3b1d, - 0x8ce6_f0b8_d8ed_8026, - 0x92d8_12e7_4b2e_81fe, - 0x139f_6d78_b1f2_a910, + 0x1a04_82d5_edaa_37c8, + 0xcb78_18b7_938e_beda, + 0x0490_bb9e_2b64_3d00, + 0x1662_0293_b8a2_2538, + 0xa3f7_7957_1af3_1b39, + 0x30b0_919c_7c6a_705b, + 0x27ef_4e5b_42e6_d1ed, + 0x1dc3_3b96_b2f9_c1b6, + 0xdab7_1280_a47a_ffeb, ]; +/// Output sharpening (#2970): each step crisper than the one before, Screen / Standard roughly a +/// typical web export's, and no wide light or dark rim along a strong edge (overshoot stays +/// within a tenth of the edge's contrast). Colour is left alone: a grey edge stays grey. +#[test] +fn sharpen_steps_are_crisper_without_halos() { + let edge = || { + let mut img = Rgba8::new(32, 8); + for (i, p) in img.data.iter_mut().enumerate() { + let v = if i % 32 < 16 { 40 } else { 220 }; + *p = [v, v, v, 255]; + } + img + }; + let mut last = 0u8; + for amount in [SharpenAmount::Low, SharpenAmount::Standard, SharpenAmount::High] { + let mut img = edge(); + output_sharpen(&mut img, SharpenFor::Screen, amount); + let (dark, light) = (img.data[15], img.data[16]); + let spread = (40 - dark[0]).max(light[0] - 220); + assert!(spread >= last && spread > 0, "{amount:?}: {dark:?} {light:?}"); + assert!(dark[0] >= 40 - 18 && light[0] <= 220 + 18, "{amount:?}: {dark:?} {light:?}"); + assert!(dark[0] == dark[1] && dark[1] == dark[2] && light[0] == light[2], "grey stays grey"); + assert_eq!(img.data[0][0], 40, "{amount:?}: flat areas untouched"); + last = spread; + } + let mut none = edge(); + output_sharpen(&mut none, SharpenFor::None, SharpenAmount::High); + assert_eq!(none.data, edge().data); +} + +/// Output sharpening of a float image with NaN and infinite samples does not panic (#2970 review): +/// they are sharpened as black and every result is finite. +#[test] +fn sharpen_deep_survives_non_finite_samples() { + let (nan, inf) = (f32::NAN, f32::INFINITY); + let mut samples = vec![0.5f32; 27]; + samples[..9].copy_from_slice(&[nan, nan, nan, inf, inf, inf, -inf, nan, inf]); + samples[12] = nan; + samples[20] = inf; + for target in [SharpenFor::Screen, SharpenFor::Glossy, SharpenFor::Matte] { + let mut img = DeepImage { width: 3, height: 3, space: OutputSpace::Srgb, samples: DeepSamples::F32(samples.clone()) }; + output_sharpen_deep(&mut img, target, SharpenAmount::High); + let DeepSamples::F32(out) = &img.samples else { panic!("expected F32 samples") }; + assert!(out.iter().all(|v| v.is_finite() && *v >= 0.0), "{target:?}: {out:?}"); + } + let mut all_nan = DeepImage { width: 3, height: 3, space: OutputSpace::Srgb, samples: DeepSamples::F32(vec![nan; 27]) }; + output_sharpen_deep(&mut all_nan, SharpenFor::Screen, SharpenAmount::Standard); +} + /// Exported files carry keywords as Lightroom Classic writes them: names flat in `dc:subject` /// (with the keywords containing them), full paths in `lr:hierarchicalSubject`, and nothing of /// a keyword left out of export. They used to carry the `a|b` paths in `dc:subject`. @@ -1526,6 +1575,114 @@ fn export_weights_follow_the_source_and_output_sizes() { assert!(render_weight(usize::MAX, 1, SourceLevel::Full, usize::MAX) > 0, "no overflow"); } +/// A raw's linear Rec.2020 near black as decoding leaves it since it stopped clamping channels at zero: a flat dark +/// patch with sensor noise through a saturating camera matrix (a NIKON D780 profile's), so many channels are +/// negative, and a few strongly out-of-gamut pixels. `clamped` is the same frame as decoding left it before. +fn dark_frame_with_negative_channels(clamped: bool) -> lightcraft_raster::Rgb32f { + let m = [[3.48f32, -2.41, -0.06], [-0.41, 1.57, -0.16], [0.32, -1.86, 2.58]]; + // ±0.004 of noise per channel, a hash of the position + let noise = |x: usize, y: usize, c: usize| { + let h = ((x * 7919 + y * 104_729 + c * 1_299_709) as u32).wrapping_mul(2_654_435_761); + (h >> 8) as f32 / (1u32 << 24) as f32 * 0.008 - 0.004 + }; + lightcraft_raster::Rgb32f::from_fn(192, 128, |x, y| { + let rgb = if (x * 3 + y) % 97 == 0 { + [-0.05, 0.01, -0.02] + } else { + let cam: [f32; 3] = std::array::from_fn(|c| 0.002 + noise(x, y, c)); + std::array::from_fn(|i| m[i][0] * cam[0] + m[i][1] * cam[1] + m[i][2] * cam[2]) + }; + if clamped { rgb.map(|v: f32| v.max(0.0)) } else { rgb } + }) +} + +/// Exports `src` pushed +4 EV at half its size, rendered as an export renders it (the options' depth and colour +/// space, a separate HDR render for a gain map JPEG) and written by the export's own encoders. +fn export_dark_frame(src: &lightcraft_raster::Rgb32f, o: &ExportOptions) -> Vec { + let info = lightcraft_pipeline::SourceInfo { raw: true, ..Default::default() }; + let mut s = lightcraft_develop::DevelopSettings::default(); + s.light.exposure = 4.0; + s.hdr.enabled = o.hdr; + let render = |depth| { + let req = lightcraft_pipeline::RenderRequest { depth, space: o.effective_space(), ..lightcraft_pipeline::RenderRequest::fit(96, 96) }; + lightcraft_pipeline::render(src, &info, &s, &req) + }; + let r = render(o.effective_depth()); + if o.hdr_output() && o.format == ExportFormat::Jpeg { + let hdr = render(OutputDepth::F32Hdr).deep.expect("an HDR render has float samples"); + encode_gain_map_jpeg(&r.image, &hdr, o, None).unwrap() + } else { + encode_rendered(&r, o, None).unwrap() + } +} + +/// Mean 8-bit sRGB of a decoded export. +fn mean_srgb8(d: &lightcraft_codecs::Decoded) -> [f64; 3] { + let img = d.to_srgb8(); + let n = img.data.len().max(1) as f64; + std::array::from_fn(|c| img.data.iter().map(|p| f64::from(p[c])).sum::() / n) +} + +/// Negative channels from decoding reach the export encoders: a dark frame pushed +4 EV exports in every rendered +/// format, depth and HDR mode as a file that decodes to the right size with finite samples (AVIF, which LightCraft +/// can't decode, and the linear DNG are checked for their structure), and comes out less tinted than the same frame +/// with its channels clamped at decoding. (At full size the white-balance clamp before noise reduction still zeroes +/// them, #2598; the half-size export averages them first.) +#[test] +fn dark_frame_with_negative_channels_exports_in_every_format() { + let src = dark_frame_with_negative_channels(false); + assert!(src.data.iter().flatten().filter(|v| **v < 0.0).count() > src.data.len() / 4, "the source has few negatives"); + let cases = [ + (ExportFormat::Jpeg, None, false), + (ExportFormat::Jpeg, None, true), + (ExportFormat::Png, Some(8), false), + (ExportFormat::Png, Some(16), false), + (ExportFormat::Png, None, true), + (ExportFormat::Tiff, Some(8), false), + (ExportFormat::Tiff, Some(16), false), + (ExportFormat::Tiff, Some(32), false), + (ExportFormat::Tiff, Some(32), true), + (ExportFormat::Psd, Some(8), false), + (ExportFormat::Psd, Some(16), false), + (ExportFormat::Webp, None, false), + (ExportFormat::Avif, Some(8), false), + (ExportFormat::Avif, Some(10), false), + (ExportFormat::Avif, None, true), + (ExportFormat::Jxl, Some(8), false), + (ExportFormat::Jxl, Some(16), false), + (ExportFormat::Jxl, None, true), + (ExportFormat::RenderedDng, None, false), + (ExportFormat::RenderedDng, None, true), + ]; + for (format, bit_depth, hdr) in cases { + let what = format!("{format:?}, {bit_depth:?} bits, HDR {hdr}"); + let bytes = export_dark_frame(&src, &ExportOptions { format, bit_depth, hdr, ..Default::default() }); + match format { + ExportFormat::Avif => assert_eq!(bytes.get(4..8), Some(&b"ftyp"[..]), "{what}"), + ExportFormat::RenderedDng => { + let dng = lightcraft_raw::decode(&bytes).unwrap_or_else(|e| panic!("{what}: {e}")); + assert_eq!((dng.width, dng.height), (96, 64), "{what}"); + } + _ => { + let d = lightcraft_codecs::decode(&bytes, Default::default()).unwrap_or_else(|e| panic!("{what}: {e}")); + assert_eq!((d.width, d.height), (96, 64), "{what}"); + assert!(d.image.data.iter().flatten().all(|v| v.is_finite()), "{what}: non-finite samples"); + if format == ExportFormat::Jpeg && hdr { + let gm = lightcraft_codecs::gainmap::read_jpeg(&bytes).unwrap_or_else(|| panic!("{what}: no gain map")); + assert!(gm.meta.alternate_headroom.is_finite(), "{what}: gain map headroom"); + } + } + } + } + let jpeg = ExportOptions::default(); + let tint = |src| { + let m = mean_srgb8(&lightcraft_codecs::decode(&export_dark_frame(src, &jpeg), Default::default()).unwrap()); + m.iter().copied().fold(f64::MIN, f64::max) - m.iter().copied().fold(f64::MAX, f64::min) + }; + let (kept, clamped) = (tint(&src), tint(&dark_frame_with_negative_channels(true))); + assert!(kept < clamped / 2.0, "kept negatives tint the export by {kept:.1} codes, clamped ones by {clamped:.1}"); +} + /// A catalog's file name never adds a folder level through the empty-naming fallback or the original's extension. #[test] fn file_name_fallback_and_extension_are_one_path_component() { diff --git a/crates/engine/src/files.rs b/crates/engine/src/files.rs index 819c6c01bc..a327d0c111 100644 --- a/crates/engine/src/files.rs +++ b/crates/engine/src/files.rs @@ -84,7 +84,7 @@ impl CameraColourModel<'_> { } let out = hue_sat.apply_lanes(rgb); for (l, p) in chunk.iter_mut().enumerate() { - *p = [out[0][l], out[1][l], out[2][l]].map(|v| v.max(0.0)); + *p = finite([out[0][l], out[1][l], out[2][l]]); } } }); @@ -106,10 +106,22 @@ impl CameraColourModel<'_> { Some(tables) => tables.apply(rgb, gain), None => rgb.map(|v| v * gain), }; - self.hue_sat.map_or(rgb, |h| h.apply(rgb)).map(|v| v.max(0.0)) + finite(self.hue_sat.map_or(rgb, |h| h.apply(rgb))) } } +/// `rgb` (linear Rec.2020) as decoding leaves it for the stages after: negative channels kept, non-finite ones zero. +/// Near black, negative channels are sensor noise through the colour matrix, and keeping them keeps the noise zero-mean +/// until noise reduction and the output's gamut mapping (which moves a colour toward its luminance until it is in +/// range) deal with it. Clamping each channel at zero here kept only the positive half of every channel's noise: +/// through a saturating camera matrix (red row 3.5, −2.4, −0.1 on a NIKON D780 profile) red and blue have the widest +/// noise, so pushed shadows and dark frames came out magenta (a black frame pushed 4 EV rendered at sRGB (64, 28, 65) +/// in its darkest 40%, (2, 4, 4) without the clamp). Moving each such colour toward its luminance instead still left +/// it pink, at (34, 14, 22): any per-pixel rule that treats pixels by the sign of their noise biases the mean. +fn finite(rgb: [f32; 3]) -> [f32; 3] { + rgb.map(|v| if v.is_finite() { v } else { 0.0 }) +} + /// Remove Hot Pixels leaves a raw alone when more than this share of its photosites would be replaced (Settings ▸ /// Performance ▸ Hot pixel limit, `app.hotPixelLimit`), as `f64` bits. Process-wide, like the GPU switch. static HOT_PIXEL_LIMIT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(lightcraft_raw::HOT_PIXEL_MAX_SHARE.to_bits()); diff --git a/crates/engine/src/files/fs.rs b/crates/engine/src/files/fs.rs index bb25aff888..b547c18033 100644 --- a/crates/engine/src/files/fs.rs +++ b/crates/engine/src/files/fs.rs @@ -117,11 +117,12 @@ fn fs_load(path: &str, max_edge: usize, load: impl FnOnce(Vec) -> Result< } /// The modification time in `meta` as ISO 8601 (see [`ProbeInfo::file_modified`]); `None` when the -/// filesystem doesn't say or the time is before 1970. +/// filesystem doesn't say or the time is before 1970. In the host's time zone, like every date the +/// catalog stores: this is the capture date of a file that carries none of its own. fn modified_iso(meta: &std::fs::Metadata) -> Option { let t = meta.modified().ok()?; let secs = i64::try_from(t.duration_since(std::time::UNIX_EPOCH).ok()?.as_secs()).ok()?; - Some(crate::import::civil(secs)) + Some(crate::import::local_civil(secs)) } impl crate::Session { diff --git a/crates/engine/src/files/probe.rs b/crates/engine/src/files/probe.rs index a9d262074e..4bdf22afa9 100644 --- a/crates/engine/src/files/probe.rs +++ b/crates/engine/src/files/probe.rs @@ -121,6 +121,23 @@ pub fn embedded_lens(raw: &lightcraft_raw::RawInfo) -> Option bool { + lightcraft_meta::parse_xmp(x).ok().and_then(|d| d.metadata.rating).is_some() +} + +fn embedded_or_exif_xmp(bytes: &[u8], m: &lightcraft_meta::Metadata) -> Option { + match lightcraft_meta::embedded(bytes).xmp { + Some(x) if !xmp_has_rating(&x) && m.rating.is_some() => { + let fresh = lightcraft_meta::write_xmp(m, None); + lightcraft_meta::merge_xmp(&x, &fresh, lightcraft_meta::MergeRules { owned_if_present: &["xmp:Rating"], ..Default::default() }) + .ok() + .or(Some(x)) + } + Some(x) => Some(x), + None => m.rating.map(|_| lightcraft_meta::write_xmp(m, None)), + } +} + fn ext_upper(name: &str) -> String { std::path::Path::new(name).extension().map(|e| e.to_string_lossy().to_uppercase()).unwrap_or_default() } @@ -133,6 +150,7 @@ pub fn probe_bytes(name: &str, bytes: &[u8]) -> Result { let content_hash = Some(lightcraft_preview::hash_bytes(bytes).to_string()); let m = lightcraft_meta::extract(bytes); let (meta, captured) = meta_of(&m); + let xmp = embedded_or_exif_xmp(bytes, &m); if lightcraft_raw::probe(bytes).is_some() { let raw = match lightcraft_raw::probe_info(bytes).map_err(|e| preview_reason(bytes, e)) { Ok(r) => r, @@ -149,7 +167,7 @@ pub fn probe_bytes(name: &str, bytes: &[u8]) -> Result { meta, as_shot_wb: None, content_hash, - xmp: lightcraft_meta::embedded(bytes).xmp, + xmp, orientation: m.orientation, preview_only: Some(why), ..Default::default() @@ -184,7 +202,7 @@ pub fn probe_bytes(name: &str, bytes: &[u8]) -> Result { meta, as_shot_wb, content_hash, - xmp: lightcraft_meta::embedded(bytes).xmp, + xmp, orientation: Some(raw.orientation), preview_only: None, }); @@ -230,7 +248,7 @@ pub fn probe_bytes(name: &str, bytes: &[u8]) -> Result { as_shot_wb: None, content_hash, embedded_lens: None, - xmp: None, + xmp, orientation: m.orientation, preview_only: None, }) diff --git a/crates/engine/src/files/tests.rs b/crates/engine/src/files/tests.rs index 92bf874f09..1f724fdd1c 100644 --- a/crates/engine/src/files/tests.rs +++ b/crates/engine/src/files/tests.rs @@ -469,8 +469,16 @@ fn undated_files_take_the_file_date() { let path = dir.join("export.jpg"); std::fs::write(&path, &jpeg).unwrap(); let path = path.to_string_lossy().to_string(); + // The case reported in issue #2284: a JPEG that went through a messenger keeps no capture + // date, only a modification time, here 2026-10-18 20:15:11 in UTC-5. Pinning it also dates + // the file in the other half of the year from "now", so a zone with summer time is read at + // the right instant and not at today's offset. + let shot = lightcraft_meta::DateTime::parse_iso("2026-10-19T01:15:11Z").unwrap().unix_seconds(); + let when = std::time::UNIX_EPOCH + std::time::Duration::from_secs(u64::try_from(shot).unwrap()); + std::fs::File::options().write(true).open(&path).unwrap().set_modified(when).unwrap(); let mtime = std::fs::metadata(&path).unwrap().modified().unwrap().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs(); - let want = crate::import::civil(mtime as i64); + assert_eq!(mtime as i64, shot, "the file date is the one the test set"); + let want = crate::import::local_civil(mtime as i64); let (_, probe) = fs_hooks(); let info = probe(&path).unwrap(); assert_eq!(info.captured, None, "the file itself has no date"); @@ -1235,6 +1243,40 @@ fn yellowing_look() -> lightcraft_color::Mat3 { lightcraft_color::Mat3([[0.42, 0.548, 0.04], [0.246, 0.728, 0.033], [-0.247, 0.679, 0.447]]) } +/// Decoding passes finite values through, negative ones included, and zeroes NaN and infinities. +#[test] +fn decoding_keeps_negative_channels_and_zeroes_non_finite_ones() { + assert_eq!(finite([0.6, 0.05, -0.04]), [0.6, 0.05, -0.04]); + assert_eq!(finite([f32::NAN, -0.1, f32::INFINITY]), [0.0, -0.1, 0.0]); +} + +/// Dark sensor noise through a saturating camera matrix (a NIKON D780 profile's) averages to a neutral colour: the +/// per-channel clamp at zero decoding had kept red's and blue's wider positive halves and turned it magenta. +#[test] +fn dark_noise_through_a_saturating_matrix_stays_neutral() { + let matrix = lightcraft_color::Mat3([[3.48, -2.41, -0.06], [-0.41, 1.57, -0.16], [0.32, -1.86, 2.58]]); + let colour = CameraColourModel { wb: [1.0; 3], matrix, gain: 1.0, tables: None, hue_sat: None }; + // a grey 0.002 above black with ±0.004 of noise per channel (a deterministic sequence) + let mut state = 12345u32; + let mut noise = || { + state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + (state >> 8) as f32 / (1u32 << 24) as f32 * 0.008 - 0.004 + }; + let mut img = Rgb32f::new(200, 200); + for p in img.data.iter_mut() { + *p = [0.002 + noise(), 0.002 + noise(), 0.002 + noise()]; + } + colour.apply(&mut img); + let mut mean = [0.0f64; 3]; + for p in &img.data { + for (m, v) in mean.iter_mut().zip(p) { + *m += f64::from(*v); + } + } + let (hi, lo) = (mean[0].max(mean[1]).max(mean[2]), mean[0].min(mean[1]).min(mean[2])); + assert!(lo > 0.0 && hi / lo < 1.2, "mean {mean:?} is tinted"); +} + /// A fitted camera look applied in lanes, on rows that aren't a whole number of them, gives the bits of the /// pixel-by-pixel path, awkward pixels (black, negative, huge, NaN, infinite) included. #[test] @@ -2070,7 +2112,7 @@ fn rw2_and_dng_defaults_unchanged() { let name = format!("x.{format}"); let mut p = Photo::new(PhotoId(1), Source::File { path: format!("/{name}") }, &name, format, 64, 48, ""); p.kind = MediaKind::Raw; - p.embedded_lens = embedded; + p.embedded_lens = embedded.map(Box::new); crate::import::apply_import_defaults(&s, &mut p); assert_eq!(p.develop.optics.lens_profile, embedded.is_some(), "{format} {embedded:?}"); } diff --git a/crates/engine/src/import.rs b/crates/engine/src/import.rs index c90035eb6c..8136cc4db3 100644 --- a/crates/engine/src/import.rs +++ b/crates/engine/src/import.rs @@ -46,7 +46,7 @@ mod types; pub(crate) use commit::start_from_file; #[cfg(not(target_arch = "wasm32"))] pub(crate) use commit::workers; -pub use commit::{batch_size, civil, commit_prepared, system_clock}; +pub use commit::{batch_size, civil, commit_prepared, local_civil, local_instant, system_clock}; pub use defaults::{CameraDefault, ImportDefaults, apply_import_defaults, has_import_look, import_defaults}; #[cfg(test)] use files::expand_knowing; diff --git a/crates/engine/src/import/commit.rs b/crates/engine/src/import/commit.rs index 1a14297249..c3edf265cf 100644 --- a/crates/engine/src/import/commit.rs +++ b/crates/engine/src/import/commit.rs @@ -224,16 +224,31 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare let mut purged: std::collections::HashSet = Default::default(); for it in prepared.items { match it { - PreparedItem::Promote(id) => { + PreparedItem::Promote(id, fresh) => { + // the file was replaced since it was browsed: the record takes what it is now before it joins the library + if let Some(info) = &fresh { + crate::cmd::convert::reload_ops(&s.catalog, id, info, &mut ops, &mut Vec::new()); + } if s.catalog.photo(id).is_some_and(|p| p.local) { ops.push(Op::SetLocal { id, local: false }); } + // "Import as new": a trashed photo with the same content is replaced, as for a new file + let content = + fresh.as_ref().and_then(|i| i.content_hash.clone()).or_else(|| s.catalog.photo(id).and_then(|p| p.content_hash.clone())); + if let Some(old) = content.as_ref().and_then(|h| trash_hash.get(h)) + && purged.insert(*old) + { + purge.push(*old); + } report.imported.push(id.0); } PreparedItem::Duplicate { path, existing, reason, hash, file } => { let existing = existing.or_else(|| { let h = hash?; - new_hash.get(&h).copied().or_else(|| s.catalog.photos().find(|p| p.content_hash.as_deref() == Some(h.as_str())).map(|p| p.id)) + new_hash + .get(&h) + .copied() + .or_else(|| s.catalog.photos().find(|p| !p.local && p.content_hash.as_deref() == Some(h.as_str())).map(|p| p.id)) }); let trashed = existing.filter(|id| s.catalog.photo(*id).is_some_and(|p| p.deleted)); match trashed { @@ -243,7 +258,11 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare ops.push(Op::SetDeleted { id, deleted: false }); // matched by content from another path, and the file the record // points at is gone (moved, renamed): the photo follows the file - if reason == "content" && trashed_file_is_gone(&s.catalog, id) { + // (not onto a path another record holds, a file only browsed in Local) + if reason == "content" + && trashed_file_is_gone(&s.catalog, id) + && !s.catalog.photos().any(|p| matches!(&p.source, Source::File { path: held } if *held == path)) + { ops.push(crate::cmd::missing::relink_op(id, &path)); } report.restored.push(id.0); @@ -275,7 +294,7 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare p.file_size = info.file_size; p.as_shot_wb = info.as_shot_wb; p.content_hash = info.content_hash; - p.embedded_lens = info.embedded_lens; + p.embedded_lens = info.embedded_lens.map(Box::new); p.set_preview_only(info.preview_only.clone()); if let Some(sc) = start_from_file(s, &mut p, FileFacts { meta: info.meta, captured: info.captured, orientation: info.orientation, sidecar }, &now) @@ -296,7 +315,7 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare } } if let Some(preset) = &opts.preset { - let d = std::sync::Arc::new(preset.apply(&p.develop, 1.0)); + let d = std::sync::Arc::new(crate::presets::apply_preset_to_photo(preset, &p.develop, None, 1.0, &crate::media::source_info(&p))); let label = format!("Preset: {}", preset.name); p.develop = d.clone(); p.edited = Some(now.clone()); @@ -388,7 +407,7 @@ pub fn system_clock() -> String { #[cfg(not(target_arch = "wasm32"))] { let secs = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs() as i64).unwrap_or(0); - civil(secs) + local_civil(secs) } #[cfg(target_arch = "wasm32")] { @@ -400,3 +419,146 @@ pub fn system_clock() -> String { pub fn civil(secs: i64) -> String { lightcraft_catalog::dates::civil(secs) } + +/// Unix seconds → `YYYY-MM-DDTHH:MM:SS` in the host's time zone: the local civil time every date +/// the catalog stores is in (`captured`, `imported`, an album's `created`, an edit's `edited`). +/// +/// The offset is the one in force *at that instant*, not today's, so a photo from July keeps +/// summer time when it is read in January. A host whose zone cannot be read falls back to UTC, as +/// the web build does (issue #2284: a file with no capture date was dated by its modification time +/// in UTC, which put an evening photo on the next day). +#[cfg(not(target_arch = "wasm32"))] +pub fn local_civil(secs: i64) -> String { + civil_in(secs, &system_zone()) +} + +/// The host's zone. It holds the whole rule set, so each instant still gets the offset that was in +/// force then. jiff keeps the zone it read for five minutes (a cheap shared handle, so an import +/// does not re-read the system database per file) and reads it again after that, so a host whose +/// zone is changed while LightCraft runs dates its files in the new zone from then on, not in the +/// one it started in. +#[cfg(not(target_arch = "wasm32"))] +fn system_zone() -> jiff::tz::TimeZone { + jiff::tz::TimeZone::system() +} + +/// [`local_civil`] in a given zone. `jiff::TimeZone::system` falls back to a zone that behaves +/// like UTC when the host has none to read, and an instant outside the range it can represent +/// (far outside the range of a file date) keeps its UTC reading rather than failing an import. +#[cfg(not(target_arch = "wasm32"))] +fn civil_in(secs: i64, zone: &jiff::tz::TimeZone) -> String { + let offset = jiff::Timestamp::from_second(secs).map(|t| i64::from(zone.to_offset_info(t).offset().seconds())).unwrap_or(0); + civil(secs.saturating_add(offset)) +} + +#[cfg(target_arch = "wasm32")] +pub fn local_civil(secs: i64) -> String { + civil(secs) +} + +/// The instant at which the host's zone reads `civil` (`YYYY-MM-DDTHH:MM:SS`): the inverse of +/// [`local_civil`]. Tests pin a file's modification time with it, so that an undated file takes +/// the local date they mean whatever zone the machine is in. +#[cfg(not(target_arch = "wasm32"))] +pub fn local_instant(civil: &str) -> Option { + instant_in(civil, &system_zone()) +} + +/// [`local_instant`] in a given zone. `None` when the text is not a civil date-time, or when the +/// zone has no such moment: an hour a spring-forward removes is not a time anything happened at, +/// and jiff's ordinary conversion would answer with the instant an hour later, which reads back as +/// a different time and so is not an inverse at all. An hour a fall-back repeats takes the first +/// of the two. +#[cfg(not(target_arch = "wasm32"))] +fn instant_in(civil: &str, zone: &jiff::tz::TimeZone) -> Option { + let when: jiff::civil::DateTime = civil.trim().parse().ok()?; + let ambiguous = zone.to_ambiguous_zoned(when); + match ambiguous.offset() { + jiff::tz::AmbiguousOffset::Gap { .. } => None, + _ => ambiguous.earlier().ok().map(|z| z.timestamp().as_second()), + } +} + +#[cfg(target_arch = "wasm32")] +pub fn local_instant(civil: &str) -> Option { + lightcraft_catalog::dates::iso_seconds(civil) +} + +// (the clock is the host's only natively: the web build's is UTC, and has no jiff) +#[cfg(all(test, not(target_arch = "wasm32")))] +mod clock_tests { + use super::*; + + /// Issue #2284: an instant becomes the civil time the host's own zone shows for it, with the + /// offset in force *then*. The reported case is a JPEG with no capture date whose modification + /// time is 2026-10-18 20:15:11 in UTC-5: dated by `civil` it read 01:15 the next day. + #[test] + fn local_civil_reads_the_hosts_zone_at_that_instant() { + let zone = jiff::tz::TimeZone::system(); + // the report, then one in each half of the year (so a zone with DST uses both offsets), + // one on a year boundary, and one before the epoch + for iso in ["2026-10-19T01:15:11Z", "2026-07-04T12:00:00Z", "2026-01-15T23:30:00Z", "2027-01-01T00:00:00Z", "1969-12-31T23:59:59Z"] { + let secs = lightcraft_meta::DateTime::parse_iso(iso).expect("a test timestamp").unix_seconds(); + let zoned = jiff::Timestamp::from_second(secs).expect("in range").to_zoned(zone.clone()); + assert_eq!(local_civil(secs), zoned.strftime("%Y-%m-%dT%H:%M:%S").to_string(), "{iso}"); + } + } + + /// The reported numbers, against a fixed UTC-5 zone, so they are checked on any host: a CI + /// runner set to UTC would make the test above agree with itself and prove nothing. + #[test] + fn an_evening_in_utc_minus_5_stays_that_evening() { + let secs = lightcraft_meta::DateTime::parse_iso("2026-10-19T01:15:11Z").expect("a test timestamp").unix_seconds(); + assert_eq!(civil(secs), "2026-10-19T01:15:11", "the UTC reading the file used to be dated by"); + let zone = jiff::tz::TimeZone::fixed(jiff::tz::offset(-5)); + assert_eq!(civil_in(secs, &zone), "2026-10-18T20:15:11"); + // and the other way, so the sign cannot be read backwards + assert_eq!(civil_in(secs, &jiff::tz::TimeZone::fixed(jiff::tz::offset(2))), "2026-10-19T03:15:11"); + } + + /// `local_instant` undoes `local_civil`, so a fixture can pin a file to a local date. + #[test] + fn local_instant_is_the_inverse_of_local_civil() { + for iso in ["2026-01-14T05:58:48", "2026-07-04T12:00:00", "2026-10-18T20:15:11"] { + let secs = local_instant(iso).expect("a local instant"); + assert_eq!(local_civil(secs), iso); + } + assert_eq!(local_instant("not a date"), None); + } + + /// The hour a spring-forward removes is no instant at all, so there is nothing to answer with: + /// jiff's ordinary conversion returns the hour after the gap, which would pin a file to a time + /// it does not read back as. The hour a fall-back repeats takes the first of the two. + #[test] + fn a_local_time_a_spring_forward_removed_has_no_instant() { + let Ok(zone) = jiff::tz::TimeZone::get("America/New_York") else { + lightcraft_testkit::skip!(System, "no IANA time zone database to read America/New_York from"); + return; + }; + // 2026-03-08: 02:00 becomes 03:00, so nothing happened at 02:30 + assert_eq!(instant_in("2026-03-08T02:30:00", &zone), None); + // the hours either side of the gap are ordinary, and round-trip + for iso in ["2026-03-08T01:30:00", "2026-03-08T03:30:00"] { + let secs = instant_in(iso, &zone).expect("either side of the gap"); + assert_eq!(civil_in(secs, &zone), iso); + } + // 2026-11-01: 02:00 becomes 01:00, so 01:30 happens twice; the first is the one in summer + // time, 05:30 UTC, and it reads back as what was asked for + let fold = instant_in("2026-11-01T01:30:00", &zone).expect("the repeated hour"); + assert_eq!(fold, lightcraft_meta::DateTime::parse_iso("2026-11-01T05:30:00Z").expect("a test timestamp").unix_seconds()); + assert_eq!(civil_in(fold, &zone), "2026-11-01T01:30:00"); + } + + /// Whatever the host's zone, what it produces is a date the rest of the catalog can read back, + /// and it differs from UTC only by a whole number of minutes no larger than a real offset. + #[test] + fn local_civil_is_a_catalog_date_within_a_real_offset_of_utc() { + let secs = lightcraft_meta::DateTime::parse_iso("2026-10-19T01:15:11Z").expect("a test timestamp").unix_seconds(); + let local = local_civil(secs); + let read = lightcraft_catalog::dates::iso_seconds(&local).expect("a date the catalog can read"); + let shift = read - secs; + assert_eq!(shift % 60, 0, "{local}"); + assert!(shift.abs() <= 18 * 3600, "{local}"); + assert_eq!(lightcraft_catalog::dates::normalize_iso(&local).as_deref(), Some(local.as_str())); + } +} diff --git a/crates/engine/src/import/defaults.rs b/crates/engine/src/import/defaults.rs index 6fd3feb007..72e4019d22 100644 --- a/crates/engine/src/import/defaults.rs +++ b/crates/engine/src/import/defaults.rs @@ -87,7 +87,7 @@ pub fn apply_import_defaults(s: &Session, p: &mut Photo) { let preset = s.import_defaults.preset_for(raw, &p.meta.camera).and_then(|id| s.presets.iter().find(|x| x.id == id)); match preset { Some(pr) => { - let look = std::sync::Arc::new(pr.apply(&base, 1.0)); + let look = std::sync::Arc::new(crate::presets::apply_preset_to_photo(pr, &base, None, 1.0, &crate::media::source_info(p))); p.develop = look.clone(); p.import_look = (*look != base).then_some(look); } diff --git a/crates/engine/src/import/files.rs b/crates/engine/src/import/files.rs index 074df065e9..7d49220301 100644 --- a/crates/engine/src/import/files.rs +++ b/crates/engine/src/import/files.rs @@ -487,6 +487,44 @@ pub(super) fn reusable_probes( held.into_iter().map(|h| h.filter(|info| seen.next().is_some_and(|s| s != Seen::Unchecked && ok(s, info)))).collect() } +/// What looking at the file of a browsed (Local) record found ([`browsed_files_changed`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum BrowsedFile { + /// As it was browsed, or not to be told: a record without a size, and a file that can't be read (one that is + /// gone is the record's own business) count as unchanged. + Unchanged, + /// Its size on disk is not the recorded one: another application replaced it since it was browsed (the check the + /// probes kept from a scan go by). + Changed, + /// Not looked at: `cancel` was set first. + Unchecked, +} + +/// Look at the file of each of `files` (path, the size its browsed record has), several at once ([`stat_all`]: one +/// at a time, each is a round trip to a network share, and thousands of browsed photos waited minutes for them). +/// The answers come in the order of `files`; a record with no size is not asked about. +pub(super) fn browsed_files_changed(files: &[(&str, u64)], cancel: &std::sync::atomic::AtomicBool) -> Vec { + // (the web's files are not std::fs files) + if cfg!(target_arch = "wasm32") { + return vec![BrowsedFile::Unchanged; files.len()]; + } + let asked: Vec<&str> = files.iter().filter(|(_, recorded)| *recorded > 0).map(|(path, _)| *path).collect(); + let mut seen = stat_all(&asked, cancel, stat_file).into_iter(); + files + .iter() + .map(|(_, recorded)| { + if *recorded == 0 { + return BrowsedFile::Unchanged; + } + match seen.next() { + Some(Seen::At { is_file: true, len }) if len != *recorded => BrowsedFile::Changed, + Some(Seen::Unchecked) | None => BrowsedFile::Unchecked, + Some(_) => BrowsedFile::Unchanged, + } + }) + .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 @@ -725,6 +763,32 @@ mod prepared_tests { assert!(seen.iter().all(|s| matches!(s, Seen::Gone | Seen::Unchecked))); } + /// The files of browsed records are looked at together, and only a file of another size than its record has is changed: + /// a record with no size, a file that is gone and a folder in its place count as unchanged, and ✕ leaves them all unchecked. + #[test] + fn browsed_files_are_told_changed_by_their_size() { + let dir = temp_dir("browsed-sizes"); + let name = |n: &str| dir.join(n).to_string_lossy().into_owned(); + std::fs::write(dir.join("same.jpg"), [0u8; 10]).unwrap(); + std::fs::write(dir.join("bigger.jpg"), [0u8; 20]).unwrap(); + std::fs::write(dir.join("unsized.jpg"), [0u8; 5]).unwrap(); + std::fs::create_dir(dir.join("folder.jpg")).unwrap(); + let names = ["same.jpg", "bigger.jpg", "unsized.jpg", "gone.jpg", "folder.jpg"].map(name); + let files: Vec<(&str, u64)> = names.iter().map(String::as_str).zip([10, 10, 0, 10, 10]).collect(); + let cancel = std::sync::atomic::AtomicBool::new(false); + let found = browsed_files_changed(&files, &cancel); + use BrowsedFile::{Changed, Unchanged, Unchecked}; + assert_eq!(found, [Unchanged, Changed, Unchanged, Unchanged, Unchanged]); + cancel.store(true, std::sync::atomic::Ordering::Relaxed); + let found = browsed_files_changed(&files, &cancel); + assert_eq!( + found, + [Unchecked, Unchecked, Unchanged, Unchecked, Unchecked], + "a record with no size isn't asked about, so ✕ doesn't matter to it" + ); + let _ = std::fs::remove_dir_all(dir); + } + /// A probe a scan left is used again for a file that is as it was, and only for it: a file that /// changed size, one that is gone and one with no probe are read. #[test] diff --git a/crates/engine/src/import/job.rs b/crates/engine/src/import/job.rs index c7c35e91e1..0426af5ba9 100644 --- a/crates/engine/src/import/job.rs +++ b/crates/engine/src/import/job.rs @@ -1,5 +1,5 @@ use super::commit::{How, Plan, Slot, Transfer, commit_prepared, name_family, run_transfers, system_clock}; -use super::files::{Seen, expand_knowing, probe_all, reusable_probes, sidecars_of}; +use super::files::{BrowsedFile, Seen, browsed_files_changed, expand_knowing, probe_all, reusable_probes, sidecars_of}; use super::types::{FileFacts, ImportCandidate, ImportMode, ImportOptions, ImportReport, Kept, OnDeleted}; use super::{HashMap, ListedFolders, MediaKind, Path, PathBuf, Photo, PhotoId, ProbeInfo, Session, Source}; @@ -38,7 +38,10 @@ pub struct ImportJob { /// as the options said when the import was set up). pub(super) library: Option<(lightcraft_catalog::Catalog, bool)>, /// path → (photo, a Local browse record?) - pub(super) by_path: HashMap, + pub(super) by_path: HashMap)>, + /// path → the size the record of a browsed (Local) file has: a file of another size has been replaced since + /// it was browsed ([`super::files::browsed_files_changed`]) + local_sizes: HashMap, /// content hash → the photo that has it (`None`: a file earlier in this import) pub(super) by_hash: HashMap>, pub(super) probe: Option, @@ -69,8 +72,9 @@ pub struct Prepared { #[derive(Debug)] pub(super) enum PreparedItem { - /// A Local (browsed) record imported for real. - Promote(PhotoId), + /// A Local (browsed) record imported for real; with what its file is now when the file was replaced since it was + /// browsed (the record is brought up to date). + Promote(PhotoId, Option>), Duplicate { path: String, existing: Option, @@ -195,6 +199,7 @@ impl ImportJob { copy_root, library: Some((s.catalog.clone(), fresh)), by_path: HashMap::new(), + local_sizes: HashMap::new(), by_hash: HashMap::new(), probe: s.media.file_probe.clone(), file_bytes: s.media.file_bytes.clone(), @@ -268,15 +273,72 @@ impl ImportJob { continue; } if let Source::File { path } = &p.source { - self.by_path.insert(path.clone(), (p.id, p.local)); + self.by_path.insert(path.clone(), (p.id, p.local, p.content_hash.clone())); + if p.local { + self.local_sizes.insert(path.clone(), p.file_size); + } } - if let Some(h) = &p.content_hash { + // (a copy that was only browsed in Local isn't in the library) + if !p.local + && let Some(h) = &p.content_hash + { self.by_hash.insert(h.clone(), Some(p.id)); } } Some(library) } + /// The batch's files the library already knows of, by path: a duplicate, a browsed file promoted (or a replaced + /// one probed again, noted in `changed`), the others left in `todo` to be probed. + fn sort_by_library( + &mut self, + files: Vec, + verdicts: Vec>, + local: bool, + out: &mut Prepared, + changed: &mut HashMap, + todo: &mut Vec, + ) { + use std::sync::atomic::Ordering::Relaxed; + for (f, verdict) in files.into_iter().zip(verdicts) { + match self.by_path.get(f.as_str()).cloned() { + Some((id, true, hash)) if !local => match verdict { + // ✕ before its size was looked at: nothing is decided about it, so it isn't promoted + Some(BrowsedFile::Unchecked) => {} + Some(BrowsedFile::Changed) => { + changed.insert(f.clone(), id); + todo.push(f); + } + Some(BrowsedFile::Unchanged) | None => { + out.items.push(self.promote_browsed(f, id, hash)); + self.done.fetch_add(1, Relaxed); + } + }, + Some((id, _, _)) => { + out.items.push(PreparedItem::Duplicate { path: f, existing: Some(id), reason: "path", hash: None, file: None }); + self.done.fetch_add(1, Relaxed); + } + None => todo.push(f), + } + } + } + + /// A browsed file this import brings into the library (its size unchanged): a duplicate of a library photo with + /// the same content, or promoted (and from then on the library's). + fn promote_browsed(&mut self, f: String, id: PhotoId, hash: Option) -> PreparedItem { + // a library photo with the same content comes first, and a file promoted earlier + // (here or in a previous batch) counts as the library's from then on + if let Some(h) = &hash { + if let Some(existing) = self.by_hash.get(h) { + return PreparedItem::Duplicate { path: f, existing: *existing, reason: "content", hash, file: None }; + } + self.by_hash.insert(h.clone(), Some(id)); + } + // a file that was only browsed (Local) joins the library when it is imported for real + self.by_path.insert(f, (id, false, hash)); + PreparedItem::Promote(id, None) + } + /// [`ImportJob::prepare`] for files [`ImportJob::expand`] returned. pub fn prepare_files(&mut self, files: Vec, cancel: &std::sync::atomic::AtomicBool) -> Prepared { use std::sync::atomic::Ordering::Relaxed; @@ -287,21 +349,16 @@ impl ImportJob { let mode = self.mode; let mut out = Prepared { scanned: files.len(), items: Vec::new() }; let mut todo = Vec::new(); - for f in files { - match self.by_path.get(f.as_str()).copied() { - Some((id, true)) if !opts.local => { - // a file that was only browsed (Local) joins the library when it is imported for real - self.by_path.insert(f, (id, false)); - out.items.push(PreparedItem::Promote(id)); - self.done.fetch_add(1, Relaxed); - } - Some((id, _)) => { - out.items.push(PreparedItem::Duplicate { path: f, existing: Some(id), reason: "path", hash: None, file: None }); - self.done.fetch_add(1, Relaxed); - } - None => todo.push(f), - } - } + // browsed files replaced since: probed again with `todo`, their records brought up to date as they join the library + let mut changed: HashMap = HashMap::new(); + // the sizes of the browsed files this import would promote, looked at together before they are decided one by one + // (a file promoted in an earlier batch isn't asked about again; one path twice in a batch is, and its second answer is unused) + let is_browsed = |f: &String| !opts.local && matches!(self.by_path.get(f.as_str()), Some((_, true, _))); + let browsed: Vec<(&str, u64)> = + files.iter().filter(|f| is_browsed(f)).map(|f| (f.as_str(), self.local_sizes.get(f.as_str()).copied().unwrap_or(0))).collect(); + let mut looked_at = browsed_files_changed(&browsed, cancel).into_iter(); + let verdicts: Vec> = files.iter().map(|f| is_browsed(f).then(|| looked_at.next()).flatten()).collect(); + self.sort_by_library(files, verdicts, opts.local, &mut out, &mut changed, &mut todo); // files a preceding scan already probed are not read again (a network share is slow to read), // as long as they are still there, as they were: a file gone or changed since is probed again @@ -372,22 +429,62 @@ impl ImportJob { // when the import makes a record of it, once it is read as a file import reads it) let duplicate_of = info.content_hash.as_ref().filter(|_| !opts.local).and_then(|h| self.by_hash.get(h).map(|existing| (h.clone(), *existing))); - // the XMP sidecar (or a raw's embedded XMP), read before copying: its capture time files + // a browsed file replaced since it was browsed, and not a copy of what the library has: its record takes what the + // file is now (size, dimensions, content) as it joins the library + if duplicate_of.is_none() + && let Some(id) = changed.remove(&path) + { + if let Some(h) = &info.content_hash { + self.by_hash.insert(h.clone(), Some(id)); + } + self.by_path.insert(path, (id, false, info.content_hash.clone())); + self.done.fetch_add(1, Relaxed); + plan.slots.push(Slot::Item(PreparedItem::Promote(id, Some(Box::new(info))))); + continue; + } + // the XMP sidecar (or a file's embedded XMP), read before copying: its capture time files // and names the copy when the file itself has none (a skipped duplicate needs only that time) let raw = info.kind == MediaKind::Raw; - let packet = if duplicate_of.is_some() && info.captured.is_some() && !opts.read_duplicates { + let has_embedded_xmp = raw || matches!(info.format.to_ascii_uppercase().as_str(), "JPEG" | "JPG" | "TIFF" | "TIF" | "PNG" | "WEBP"); + let skip_sidecar = duplicate_of.is_some() && info.captured.is_some() && !opts.read_duplicates; + let target = crate::crs::Target::for_file(info.kind, &info.format, info.preview_only.is_some(), &info.meta.camera); + let mut embedded_sidecar = if skip_sidecar { None } else { - found_sidecar.and_then(|f| std::fs::read_to_string(f).ok()).or_else(|| info.xmp.clone().filter(|_| raw)) + info.xmp.as_deref().filter(|_| has_embedded_xmp).and_then(|x| match crate::sidecar::parse_sidecar(x, target) { + Ok(sc) => Some(sc), + Err(e) => { + log::warn!("import {path}: embedded XMP: {e}"); + None + } + }) }; - let target = crate::crs::Target::for_file(info.kind, &info.format, info.preview_only.is_some(), &info.meta.camera); - let sidecar = packet.and_then(|x| match crate::sidecar::parse_sidecar(&x, target) { - Ok(sc) => Some(sc), - Err(e) => { - log::warn!("import {path}: XMP: {e}"); - None + // Embedded XMP on a rendered file (JPEG, TIFF, PNG, WebP) has develop adjustments + // already baked into the pixels; only raws/DNGs keep foreign develop settings from embedded XMP. + if !raw && let Some(sc) = &mut embedded_sidecar { + sc.develop = None; + sc.warnings.clear(); + } + let external_sidecar = if skip_sidecar { + None + } else { + found_sidecar.and_then(|f| std::fs::read_to_string(f).ok()).and_then(|x| match crate::sidecar::parse_sidecar(&x, target) { + Ok(sc) => Some(sc), + Err(e) => { + log::warn!("import {path}: XMP: {e}"); + None + } + }) + }; + let sidecar = match (embedded_sidecar, external_sidecar) { + (Some(mut embedded), Some(external)) => { + embedded.override_with(external); + Some(embedded) } - }); + (Some(embedded), None) => Some(embedded), + (None, Some(external)) => Some(external), + (None, None) => None, + }; if info.captured.is_none() { info.captured = sidecar.as_ref().and_then(|sc| sc.captured.clone()); } @@ -416,6 +513,9 @@ impl ImportJob { let mut q = Photo::new(PhotoId(0), Source::File { path: path.clone() }, &own, &info.format, 0, 0, &self.now); q.captured = info.captured.clone(); q.meta = info.meta.clone(); + if let Some(sc) = &sidecar { + crate::sidecar::merge_into(&mut q, sc, &self.now); + } let name = if let Some(template) = opts.rename.as_deref().filter(|t| !t.trim().is_empty()) { let Some(seq) = self.seq else { self.done.fetch_add(1, Relaxed); @@ -518,7 +618,7 @@ impl Session { p.kind = c.kind; if let Some(info) = self.import_probes.get(&c.path) { p.as_shot_wb = info.as_shot_wb; - p.embedded_lens = info.embedded_lens; + p.embedded_lens = info.embedded_lens.map(Box::new); p.preview_only = info.preview_only.clone(); } p.develop = std::sync::Arc::new(p.import_defaults()); diff --git a/crates/engine/src/import/scan.rs b/crates/engine/src/import/scan.rs index 5941d83194..8e322f726e 100644 --- a/crates/engine/src/import/scan.rs +++ b/crates/engine/src/import/scan.rs @@ -1,4 +1,4 @@ -use super::files::{Seen, expand, expand_report_knowing, is_supported, probe_all, reusable_probes}; +use super::files::{BrowsedFile, Seen, browsed_files_changed, expand, expand_report_knowing, is_supported, probe_all, reusable_probes}; use super::types::ImportCandidate; use super::{HashMap, ListedFolders, Path, PathBuf, PhotoId, ProbeInfo, Session, Source}; @@ -19,7 +19,7 @@ pub struct ScanInput { /// The library's photos of `files`: path → (photo, its summary as a candidate that is there /// already). One pass over the library, and a record only for a file that was found: a folder of /// a hundred files in a library of millions costs a hundred records. -pub(super) fn library_files(library: &lightcraft_catalog::Catalog, files: &[String]) -> HashMap { +pub(super) fn library_files(library: &lightcraft_catalog::Catalog, files: &[String]) -> HashMap)> { let found: std::collections::HashSet<&Path> = files.iter().map(Path::new).collect(); let mut by_path = HashMap::new(); if found.is_empty() { @@ -37,18 +37,21 @@ pub(super) fn library_files(library: &lightcraft_catalog::Catalog, files: &[Stri height: p.height, file_size: p.file_size, captured: p.captured.clone(), - duplicate: Some("path".into()), + // a file that was only browsed (Local) is not in the library: importing it promotes it + // (a trashed browse record still counts as the path's) + duplicate: (!p.local || p.deleted).then(|| "path".into()), existing: Some(p.id.0), + local: p.local && !p.deleted, ..Default::default() }; - by_path.insert(PathBuf::from(path), (p.id, c)); + by_path.insert(PathBuf::from(path), (p.id, c, p.content_hash.clone())); } } by_path } /// Which photo of the library has each of the contents `hashes` (the later one where several -/// have it). One pass over the library, and an entry only for a content that was asked about. +/// have it; a copy that was only browsed in Local isn't in the library). One pass over the library, and an entry only for a content that was asked about. pub(super) fn library_hashes<'a>(library: &lightcraft_catalog::Catalog, hashes: impl Iterator) -> HashMap { let wanted: std::collections::HashSet<&str> = hashes.collect(); let mut by_hash = HashMap::new(); @@ -56,7 +59,8 @@ pub(super) fn library_hashes<'a>(library: &lightcraft_catalog::Catalog, hashes: return by_hash; } for p in library.photos() { - if let Some(h) = &p.content_hash + if !p.local + && let Some(h) = &p.content_hash && wanted.contains(h.as_str()) { by_hash.insert(h.clone(), p.id); @@ -340,7 +344,28 @@ pub fn scan_with(mut input: ScanInput, paths: &[String], progress: &ScanProgress /// them ([`expand_report`](super::files::expand_report)). pub(crate) fn scan_files(mut input: ScanInput, files: Vec, progress: &ScanProgress) -> ScanOutput { use std::sync::atomic::Ordering::Relaxed; - let by_path = library_files(&input.library, &files); + let mut by_path = library_files(&input.library, &files); + // a browsed file that was replaced since is not the one its record describes: it is read again like a new file + // (the record's stored content, kept from the browse, would give the wrong answer against the library), and + // its candidate still names the record and says it was only browsed, unless the library has that content. + // Their sizes are looked at together; ✕ while that goes on leaves the files not reached to be read (and so + // reported as not probed) like the ones after them, never vouched for as the record's own. + let mut replaced: HashMap = HashMap::new(); + let browsed: Vec<(&str, u64)> = + files.iter().filter_map(|f| by_path.get(Path::new(f)).filter(|(_, c, _)| c.local).map(|(_, c, _)| (f.as_str(), c.file_size))).collect(); + for ((f, _), checked) in browsed.iter().zip(browsed_files_changed(&browsed, &progress.cancel)) { + match checked { + BrowsedFile::Unchanged => {} + BrowsedFile::Changed => { + if let Some((id, ..)) = by_path.remove(Path::new(f)) { + replaced.insert(PathBuf::from(f), id); + } + } + BrowsedFile::Unchecked => { + by_path.remove(Path::new(f)); + } + } + } let todo: Vec = files.iter().filter(|f| !by_path.contains_key(Path::new(f))).cloned().collect(); progress.total.store(todo.len(), Relaxed); // probes from a preceding `scan` are reused when the file is unchanged (same size); a file that @@ -359,15 +384,39 @@ pub(crate) fn scan_files(mut input: ScanInput, files: Vec, progress: &Sc crate::memory::release(); let mut probes: HashMap> = todo.into_iter().zip(probed).collect(); // (who in the library has a content that was probed: asked once the probes are in) - let probed_hashes = probes.values().filter_map(|r| r.as_ref().ok()).filter_map(|info| info.content_hash.as_deref()); + let probed_hashes = probes + .values() + .filter_map(|r| r.as_ref().ok()) + .filter_map(|info| info.content_hash.as_deref()) + // (and the browsed files the library has by path: they are offered unless it has the content too) + .chain(by_path.values().filter(|(_, c, _)| c.local).filter_map(|(_, _, h)| h.as_deref())); let mut seen_hash: HashMap> = library_hashes(&input.library, probed_hashes).into_iter().map(|(h, id)| (h, Some(id.0))).collect(); let mut out = Vec::with_capacity(files.len()); let mut kept = HashMap::new(); + // (a content's browsed first copy: its path, until the first file of its own with that content stands in for it) + let mut browsed_first: HashMap = HashMap::new(); for f in files { - if let Some((_, c)) = by_path.get(Path::new(&f)) { + if let Some((_, c, hash)) = by_path.get(Path::new(&f)) { let mut c = c.clone(); c.name = Path::new(&f).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| f.clone()); + // a browsed file the library has the content of (or an earlier file here promotes) is a duplicate + if c.local + && let Some(h) = hash + { + match seen_hash.get(h) { + Some(existing) => { + c.duplicate = Some("content".into()); + c.existing = *existing; + } + None => { + // (the library doesn't have it: a browsed record isn't a library photo, and + // the import looks the library up when it runs) + seen_hash.insert(h.clone(), None); + browsed_first.insert(h.clone(), f.clone()); + } + } + } out.push(c); continue; } @@ -385,12 +434,28 @@ pub(crate) fn scan_files(mut input: ScanInput, files: Vec, progress: &Sc Some(existing) => { c.duplicate = Some("content".into()); c.existing = *existing; + // (the first copy of a browsed photo that is a file of its own stands in for it when + // copying leaves the browsed one out: said once per content; a browsed file doesn't) + if existing.is_none() && !replaced.contains_key(Path::new(&f)) { + c.browsed_twin = browsed_first.remove(h); + } } None => { seen_hash.insert(h.clone(), None); } } } + if let Some(id) = replaced.get(Path::new(&f)) { + // still the browsed record's file, as for one that is as browsed: Copy and Move leave it out, and the + // first twin of its own stands in for it there + c.local = true; + if c.duplicate.is_none() { + c.existing = Some(id.0); + if let Some(h) = &info.content_hash { + browsed_first.insert(h.clone(), f.clone()); + } + } + } kept.insert(f, info); } Some(Err(e)) => c.error = Some(e), diff --git a/crates/engine/src/import/tests_known.rs b/crates/engine/src/import/tests_known.rs index 9adadca8a3..3814dc5440 100644 --- a/crates/engine/src/import/tests_known.rs +++ b/crates/engine/src/import/tests_known.rs @@ -28,7 +28,7 @@ fn a_scan_knows_the_library_photos_of_the_files_it_found() { let files: Vec = ["/pics/007/a.jpg", "/pics/007/b.jpg", "/pics/007/new.jpg", "/pics/007//c.jpg"].map(String::from).to_vec(); let known = library_files(&c, &files); assert_eq!(known.len(), 3, "the three the library has (a path is compared as a path, not as text)"); - let (id, as_found) = known.get(Path::new("/pics/007/b.jpg")).expect("b"); + let (id, as_found, _) = known.get(Path::new("/pics/007/b.jpg")).expect("b"); let p = c.photo(*id).unwrap(); assert_eq!((as_found.path.as_str(), as_found.existing, as_found.duplicate.as_deref()), ("/pics/007/b.jpg", Some(id.0), Some("path"))); assert_eq!((as_found.format.as_str(), as_found.width, as_found.height, as_found.file_size), (p.format.as_str(), p.width, p.height, p.file_size)); @@ -39,7 +39,7 @@ fn a_scan_knows_the_library_photos_of_the_files_it_found() { let copy = c.alloc_photo_id(); c.apply(Op::AddPhoto { photo: Box::new(Photo::new(copy, Source::File { path: "/pics/007/a.jpg".into() }, "a.jpg", "JPEG", 6, 4, "2026-01-02")) }) .unwrap(); - assert_eq!(library_files(&c, &files).get(Path::new("/pics/007/a.jpg")).map(|(id, _)| *id), Some(copy)); + assert_eq!(library_files(&c, &files).get(Path::new("/pics/007/a.jpg")).map(|(id, _, _)| *id), Some(copy)); } /// Given a library and a folder on disk that holds a file the library has by its path, one it diff --git a/crates/engine/src/import/types.rs b/crates/engine/src/import/types.rs index 298ff98746..1e9a3b5ce5 100644 --- a/crates/engine/src/import/types.rs +++ b/crates/engine/src/import/types.rs @@ -141,8 +141,19 @@ pub struct ImportCandidate { /// `"path"` (already in the library), `"content"` (same bytes in the library or earlier in this /// list): skipped by the import. pub duplicate: Option, - /// The photo that already has it. + /// The photo that already has it. On a browsed candidate (`local`): its record. pub existing: Option, + /// The file was only browsed in Local: the library has a record of it (`existing`) that is not in + /// the library, so it is not a duplicate and importing it promotes that record. + #[serde(skip_serializing_if = "std::ops::Not::not")] + pub local: bool, + /// On the first `"content"` duplicate that is a file of its own, when no library photo has its + /// bytes but a browsed candidate (`local`) earlier in this list does: the path of that browsed + /// candidate. Adding in place the browsed photo is the one brought in, and this is a copy in the + /// source; copying and moving leave the browsed photo out (the engine would add it where it is), + /// and this file is what they bring in instead. + #[serde(skip_serializing_if = "Option::is_none")] + pub browsed_twin: Option, /// Not readable. pub error: Option, /// A raw variant that can't be decoded yet (why): it imports as preview only. diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 5189c7f50f..da9b2d74c3 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -96,7 +96,7 @@ use std::sync::Arc; pub use cmd::{CommandInfo, CommandSpec, command_specs, find_command}; pub use errors::{AiModel, ErrorKind}; pub use fonts::{CRAFT_FONTS, CraftFont}; -use lightcraft_catalog::{Catalog, Filter, Op, PhotoId, Sort}; +use lightcraft_catalog::{Catalog, CatalogError, Filter, Op, PhotoId, Sort}; use lightcraft_develop::DevelopSettings; pub use media::{RenderJob, SourceLevel}; use serde_json::Value; @@ -355,6 +355,8 @@ pub struct Session { /// Current time provider (ISO 8601); injectable for tests and wasm. pub clock: Box String + Send>, depth: u32, + /// [`Session::start_waiting`] is starting tasks (the commands it runs don't start more themselves). + starting_waiting: bool, /// Selected mask (Masking panel), by mask id. pub active_mask: Option, /// AI masks (SAM 3): the model and the last photo prepared for it. @@ -434,6 +436,9 @@ pub struct Session { /// The long edge (px) the loupe renders at on this screen, as the frontend last said /// (0: not known). Standard previews are built at least this big, so the loupe can use them. pub loupe_edge: usize, + /// Builds that ended and were replaced by the next one before a frontend announced them + /// ([`Session::take_unreported_builds`]). + unreported_builds: Vec>, /// Develop defaults applied on import (persisted in prefs.json). pub import_defaults: import::ImportDefaults, /// Disk budget of the library's thumbnail cache in MB (0 = default; persisted in prefs.json). @@ -545,6 +550,7 @@ impl Session { media: media::MediaCache::default(), clock: Box::new(|| "2026-09-30T12:00:00".to_string()), depth: 0, + starting_waiting: false, active_mask: None, segmenter: segment::Segmenter::default(), active_spot: None, @@ -578,6 +584,7 @@ impl Session { preview_build: None, prep: Default::default(), loupe_edge: 0, + unreported_builds: Vec::new(), slideshow_export: None, import_defaults: import::ImportDefaults::default(), cache_mb: 0, @@ -610,6 +617,15 @@ impl Session { /// Run a command by id. THE entry point for every frontend. pub fn execute(&mut self, id: &str, params: &Value) -> Result { + let r = self.dispatch(id, params, true); + // a task this command freed the lane of starts now, not at the next frame + self.start_waiting(); + r + } + + /// [`Session::execute`] without starting waiting tasks; `journal`: record the call when the command is journaled + /// (not for a task that waited: the call that asked for it is recorded already). + fn dispatch(&mut self, id: &str, params: &Value, journal: bool) -> Result { let spec = find_command(id).ok_or_else(|| EngineError::UnknownCommand(id.to_string()))?; // a command that validates the photos a call names isn't held back by the selection if !(spec.explicit_targets && cmd::names_photos(params)) { @@ -617,13 +633,49 @@ impl Session { } let empty = Value::Object(Default::default()); let params = if params.is_null() { &empty } else { params }; - self.run_command(id, spec.journal.then_some(params), |s| (spec.run)(s, params)).map_err(|e| match e { + self.run_command(id, (journal && spec.journal).then_some(params), |s| (spec.run)(s, params)).map_err(|e| match e { // a shared parameter check ([`Session::targets`]) names the command it ran for EngineError::BadParams { cmd, msg } if cmd.is_empty() => EngineError::BadParams { cmd: id.to_string(), msg }, e => e, }) } + /// A build that ended is replaced by the next one before a frontend announced it: keep it (at most 16; the oldest + /// goes first) for [`Session::take_unreported_builds`]. + pub(crate) fn keep_unreported_build(&mut self, build: std::sync::Arc) { + const KEEP: usize = 16; + if self.unreported_builds.len() >= KEEP { + self.unreported_builds.remove(0); + } + self.unreported_builds.push(build); + } + + /// The builds that ended and were replaced before a frontend announced them, oldest first, once. The frontend + /// announces each (and sets its `reported`) like the current build's end. + pub fn take_unreported_builds(&mut self) -> Vec> { + std::mem::take(&mut self.unreported_builds) + } + + /// Start the tasks waiting in line whose lane is free ([`crate::activity`]), each by running the command it was + /// asked with. One that can't start is logged and the next in line goes on. Every frontend gets this after each + /// command; the app also calls it every frame, for a lane that frees while nothing is asked. + pub fn start_waiting(&mut self) { + if self.depth > 0 || self.starting_waiting { + return; + } + self.starting_waiting = true; + // (bounded: each turn takes one task out of a line that is at most this long) + for _ in 0..activity::MAX_WAITING { + let Some(w) = self.activity.take_ready() else { break }; + let r = self.dispatch(&w.request.command, &w.request.params, false); + self.activity.started(); + if let Err(e) = r { + log::warn!("{}: a task that waited could not start: {e}", w.request.command); + } + } + self.starting_waiting = false; + } + /// Run `f` as command `id` with what [`Session::execute`] does around every command: the /// panic guard, auto versions, XMP sidecar auto-write and the durable save (a failed save is /// `NotSaved`). Not journaled. The app's import task commits its batches this way. @@ -686,13 +738,25 @@ impl Session { /// Apply an op as one undoable step. A new edit: one that would make a smart album include /// itself is refused here, whichever command, task or caller asked ([`Catalog::apply_new`]); /// undo, redo and opening a library bring back what was and are not held to that. + /// + /// A batch that fails and cannot be rolled back whole ([`CatalogError::PartlyApplied`]) did change the catalog, so + /// it is journaled all the same (replaying it leaves the same changes), and what is left of its rollback is the + /// undo step: undoing it finishes the rollback. The error still reaches the caller. pub fn commit(&mut self, label: &str, op: Op) -> Result<()> { let fwd = op.clone(); - let inv = self.apply_through(op, Catalog::apply_new)?; + let (inv, failure) = match self.apply_through(op, Catalog::apply_new) { + Ok(inv) => (inv, None), + Err(EngineError::Catalog(CatalogError::PartlyApplied { cause, remaining })) => { + let remaining = *remaining; + (remaining.clone(), Some(EngineError::Catalog(CatalogError::PartlyApplied { cause, remaining: Box::new(remaining) }))) + } + Err(e) => return Err(e), + }; // A committed edit of the photo a drag is previewing comes after the drag's snapshot: what // it leaves is where the interaction comes back to, and the drag's own previews from then // on are drawn on top of it (CodeRabbit #4750). - if let Some(id) = self.interaction.as_ref().filter(|i| sets_develop(&fwd, i.photo)).map(|i| i.photo) { + let changed = if failure.is_some() { &inv } else { &fwd }; + if let Some(id) = self.interaction.as_ref().filter(|i| sets_develop(changed, i.photo)).map(|i| i.photo) { let after = self.develop_of(id); let edited = self.catalog.photo(id).and_then(|photo| photo.edited.clone()); if let (Some(after), Some(i)) = (after, self.interaction.as_mut()) { @@ -709,7 +773,7 @@ impl Session { for mut dropped in self.redo.drain(..) { self.pending_sidecar_repairs.append(&mut dropped.retry_sidecars); } - Ok(()) + failure.map_or(Ok(()), Err) } /// [`Catalog::apply`] for what brings back what was (an undo or a redo). @@ -738,7 +802,11 @@ impl Session { _ => {} } } - let inv = apply(&mut self.catalog, op)?; + // (a batch that was only partly taken back changed the catalog all the same: what hangs on its photos goes too) + let applied = apply(&mut self.catalog, op); + if applied.is_err() && !matches!(applied, Err(CatalogError::PartlyApplied { .. })) { + return applied.map_err(Into::into); + } for id in invalidated { self.media.forget(id); } @@ -748,17 +816,20 @@ impl Session { } #[cfg(target_arch = "wasm32")] let _ = replaced; - Ok(inv) + Ok(applied?) } /// [`Session::commit`] for an op that goes with a folder already renamed on disk; the undo /// step renames it back (`folder` is the undo direction: current place → old place). pub(crate) fn commit_with_folder(&mut self, label: &str, op: Op, folder: FolderMove) -> Result<()> { - self.commit(label, op)?; - if let Some(e) = self.undo.last_mut() { + let result = self.commit(label, op); + // (a batch only partly taken back is journaled and has its undo step too: that step moves the folder back) + if (result.is_ok() || matches!(result, Err(EngineError::Catalog(CatalogError::PartlyApplied { .. })))) + && let Some(e) = self.undo.last_mut() + { e.folder = Some(folder); } - Ok(()) + result } /// The box to cut a face's picture from: the detector's, when the scan has looked at the face (every face is then shown @@ -777,8 +848,12 @@ impl Session { /// an undo step, and it leaves the redo stack alone. pub(crate) fn apply_system(&mut self, op: Op) -> Result<()> { let fwd = op.clone(); - self.catalog.apply(op)?; - self.pending_log.push(fwd); + let applied = self.catalog.apply(op); + if applied.is_ok() || matches!(applied, Err(CatalogError::PartlyApplied { .. })) { + // (a batch only partly taken back changed the catalog all the same: the journal has to say so) + self.pending_log.push(fwd); + } + applied?; Ok(()) } @@ -849,7 +924,12 @@ impl Session { let redo = match self.apply_with_files(&mut e, fs) { Ok(r) => r, Err(err) => { - self.undo.push(e); + // (a step that was only partly applied cannot be tried again: what is left of it goes to the other + // stack, where taking it back returns the catalog to where it was before the attempt) + match self.rest_of_partial_step(&mut e, &err) { + Some(rest) => self.redo.push(rest), + None => self.undo.push(e), + } return Err(err); } }; @@ -865,6 +945,24 @@ impl Session { Ok(e.label) } + /// The step that takes back what an undo or redo step (`e`) left in the catalog when it failed part-way + /// ([`CatalogError::PartlyApplied`]); `None` when it failed without changing anything. The step itself cannot be + /// tried again from where the catalog now is, so its sidecars to repair are handed on. + fn rest_of_partial_step(&mut self, e: &mut UndoEntry, err: &EngineError) -> Option { + let EngineError::Catalog(CatalogError::PartlyApplied { remaining, .. }) = err else { return None }; + self.pending_sidecar_repairs.append(&mut e.retry_sidecars); + // (the inverses of path corrections it kept come after what is left, as when a step succeeds) + let op = match (**remaining).clone() { + op if e.retry_inverse.is_empty() => op, + Op::Batch { mut ops } => { + ops.append(&mut e.retry_inverse); + Op::Batch { ops } + } + op => Op::Batch { ops: std::iter::once(op).chain(std::mem::take(&mut e.retry_inverse)).collect() }, + }; + Some(UndoEntry { label: e.label.clone(), op, folder: None, retry_inverse: Vec::new(), retry_sidecars: Vec::new() }) + } + pub fn redo_step(&mut self) -> Result { self.redo_step_with(&rename::RealFs) } @@ -874,7 +972,10 @@ impl Session { let undo = match self.apply_with_files(&mut e, fs) { Ok(r) => r, Err(err) => { - self.redo.push(e); + match self.rest_of_partial_step(&mut e, &err) { + Some(rest) => self.undo.push(rest), + None => self.redo.push(e), + } return Err(err); } }; @@ -966,10 +1067,32 @@ impl Session { } } Err(e) => { + if matches!(e, EngineError::Catalog(CatalogError::PartlyApplied { .. })) { + // the step changed the catalog in part: the journal has to say so + self.pending_log.push(entry.op.clone()); + } let back: Vec<(String, String)> = moves.iter().rev().map(|(a, b)| (b.clone(), a.clone())).collect(); - if let Err(mut be) = rename::move_all(fs, &back) { + let moved_back = rename::move_all(fs, &back); + // (what is left of a rollback that failed part-way must follow the files as far as they went back, + // not move them again) + let e = match e { + EngineError::Catalog(CatalogError::PartlyApplied { cause, remaining }) => EngineError::Catalog(CatalogError::PartlyApplied { + cause, + remaining: Box::new(rename::rest_after_move_back(*remaining, &moved_back)), + }), + e => e, + }; + if let Err(mut be) = moved_back { entry.retry_sidecars.append(&mut be.pending_sidecars); - return Err(EngineError::Other(format!("{e}; the files could not all be moved back: {}", be.message))); + let moved = format!("the files could not all be moved back: {}", be.message); + return Err(match e { + // (what is left of the rollback must reach the undo and redo stacks all the same) + EngineError::Catalog(CatalogError::PartlyApplied { cause, remaining }) => EngineError::Catalog(CatalogError::PartlyApplied { + cause: Box::new(CatalogError::Invalid(format!("{cause}; {moved}"))), + remaining, + }), + e => EngineError::Other(format!("{e}; {moved}")), + }); } undo_folder(); Err(e) @@ -1039,7 +1162,7 @@ impl Session { photo.height.max(1) as usize, &d, true, - photo.embedded_lens.as_ref(), + photo.embedded_lens.as_deref(), ); d.crop.geometry.rect = frame.crop.rect; d @@ -1164,7 +1287,7 @@ impl Session { p.height.max(1) as usize, &d.effective(), false, - p.embedded_lens.as_ref(), + p.embedded_lens.as_deref(), )) } @@ -1528,6 +1651,8 @@ pub fn json_delta(old: &Value, new: &Value) -> Option { } } +#[cfg(test)] +mod lightroom_fixture; #[cfg(test)] mod tests; #[cfg(test)] diff --git a/crates/engine/src/library.rs b/crates/engine/src/library.rs index daca499f6f..2664526102 100644 --- a/crates/engine/src/library.rs +++ b/crates/engine/src/library.rs @@ -360,7 +360,9 @@ fn presets_json(s: &Session) -> String { /// Finish a background compaction that is done (cheap otherwise). A failed one lost nothing (the /// log is kept whole) and is retried later; it is reported like other persistence errors. fn poll_compaction(lib: &mut Library) { - if let Err(e) = lib.journal.poll() { + let polled = lib.journal.poll(); + note_upgrade_kept(lib); + if let Err(e) = polled { log::error!("library: compaction: {e}"); lib.last_error = Some(format!("compaction: {e}")); } @@ -368,6 +370,16 @@ fn poll_compaction(lib: &mut Library) { lib.log_held = lib.journal.unwritten(); } +/// A snapshot that upgraded a library left in an older format at open kept the files it was: +/// tell so once, like the open does ([`kept_note`]). Cheap when nothing was kept. +fn note_upgrade_kept(lib: &mut Library) { + let kept = lib.journal.take_kept(); + if let Some(note) = kept_note(&kept, None) { + lib.settings_warnings.push(note); + lib.report.kept.extend(kept); + } +} + /// How long the frame loop waits before retrying a failed append (commands retry at once). const RETRY_BACKOFF: std::time::Duration = std::time::Duration::from_secs(2); @@ -411,6 +423,20 @@ struct SettingsLoad { blocked: Vec<&'static str>, } +/// What to tell the person when opening the library upgraded it: the files it was are kept +/// beside it (as large as it was), and are theirs to delete. +fn kept_note(kept: &[String], damaged: Option<&String>) -> Option { + if kept.is_empty() && damaged.is_none() { + return None; + } + // (a library whose log was damaged: that log is the other half of what it was) + let kept: Vec<&str> = kept.iter().chain(damaged).map(String::as_str).collect(); + Some(format!( + "This library was upgraded for this version of LightCraft, and earlier versions can't open it now. The library as it was is kept beside it as {}: delete it once the earlier version is no longer wanted (docs/catalog-persistence.md, \"Going back to an older version\").", + kept.join(" and ") + )) +} + impl SettingsLoad { fn read(&mut self, store: &mut dyn Store, name: &'static str) -> Option { let bytes = match store.read(name) { @@ -609,6 +635,11 @@ impl Session { static LOADS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); catalog.revision = LOADS.fetch_add(1, std::sync::atomic::Ordering::Relaxed).wrapping_add(1) << 32; self.catalog = catalog; + // nor do tasks waiting in line carry over: they name the old library's photos and folders + let dropped = self.activity.library_changed(); + if dropped > 0 { + log::info!("library: {dropped} task(s) waiting in line were dropped with the old library"); + } // (nothing of the list the last library showed is this one's) self.refresh_view(); self.library_generation = crate::LIBRARY_GEN.fetch_add(1, std::sync::atomic::Ordering::Relaxed); @@ -721,6 +752,8 @@ impl Session { self.tidy_thumbnail_cache(); } let view_written = self.view_json(); + // (a damaged log is only part of "what the library was" when opening upgraded it, and the store keeps what an upgrade replaces: a library in this format that lost its log's tail was not upgraded, and the browser's store keeps no snapshot for the log to go with) + let kept = kept_note(&report.kept, report.damaged.as_ref().filter(|_| report.upgraded_from.is_some() && report.kept_files)); self.library = Some(Library { dir, on_disk, @@ -735,7 +768,7 @@ impl Session { forgot_local: None, presets_saved, view_written, - settings_warnings: unlocked_warning(lock.as_ref()).into_iter().chain(settings.warnings).collect(), + settings_warnings: unlocked_warning(lock.as_ref()).into_iter().chain(kept).chain(settings.warnings).collect(), warnings_reported: 0, blocked: settings.blocked, folder, @@ -753,6 +786,13 @@ impl Session { lib.forgot_local = Some(plan); } } + // keywords read whole from a list a line long (before they were split) become one each + let journaled = self.pending_log.len(); + if (self.split_multiline_keywords() > 0 || self.pending_log.len() > journaled) + && let Err(e) = self.persist() + { + log::error!("library: {e}"); + } // smart previews written by an older camera-look fit are brought up to date in the background #[cfg(not(target_arch = "wasm32"))] if on_disk { @@ -765,6 +805,68 @@ impl Session { Ok(()) } + /// Photos whose keywords hold line breaks (a camera preset's whole keyword list read as one + /// keyword by an earlier version) get one keyword a line, journaled, not an undo step. Returns + /// how many photos changed. A listed keyword with line breaks hands its options to the names it + /// splits into (a name listed already keeps its own, but is left out of export when either was), + /// and with automatic XMP writing on, the repaired photos' sidecars are written as a command's are. + pub fn split_multiline_keywords(&mut self) -> usize { + let breaks = |k: &str| k.contains(['\r', '\n', '\u{2028}', '\u{2029}']); + let log_start = self.pending_log.len(); + let listed: Vec<(String, lightcraft_catalog::keywords::KeywordInfo)> = + self.catalog.listed_keywords().filter(|k| breaks(&k.path)).map(|k| (k.path.clone(), k.info.clone())).collect(); + for (path, info) in listed { + let mut ops = Vec::new(); + for (i, name) in lightcraft_catalog::keywords::from_file(std::slice::from_ref(&path), &[]).into_iter().enumerate() { + // where new keywords go stays one keyword: the first name it splits into, listed already or not + let parent = info.new_keywords_inside && i == 0; + let moved = match self.catalog.keyword_info(&name) { + Some(kept) => { + let mut kept = kept.clone(); + kept.include_on_export &= info.include_on_export; + kept.new_keywords_inside |= parent; + kept + } + None => lightcraft_catalog::keywords::KeywordInfo { new_keywords_inside: parent, ..info.clone() }, + }; + ops.push(lightcraft_catalog::Op::SetKeyword { path: name, info: Some(moved) }); + } + ops.push(lightcraft_catalog::Op::SetKeyword { path, info: None }); + for op in ops { + match self.catalog.apply(op.clone()) { + Ok(_) => self.pending_log.push(op), + Err(e) => log::warn!("split keywords: {e}"), + } + } + } + let fix: Vec<(lightcraft_catalog::PhotoId, lightcraft_catalog::Meta)> = self + .catalog + .photos() + .filter(|p| p.meta.keywords.iter().any(|k| breaks(k))) + .map(|p| { + let mut meta = p.meta.clone(); + meta.keywords = lightcraft_catalog::keywords::from_file(&meta.keywords, &[]); + (p.id, meta) + }) + .collect(); + let n = fix.len(); + for (id, meta) in fix { + let op = lightcraft_catalog::Op::SetMeta { id, meta: Box::new(meta) }; + match self.catalog.apply(op.clone()) { + Ok(_) => self.pending_log.push(op), + Err(e) => log::warn!("split keywords: {e}"), + } + } + if n > 0 { + log::info!("split the line-separated keywords of {n} photo(s) into one keyword a line"); + } + // not run through a command, so the sidecars are written here, as after a command + if self.xmp.auto_write && self.pending_log.len() > log_start { + self.auto_write_sidecars_since(log_start); + } + n + } + /// Write pending ops to the log (fsynced, or handed to the log's own thread natively), compact when due, and save changed presets. /// Called after every top-level command; cheap when nothing changed. Fails (with /// [`EngineError::NotSaved`]) only when the queued ops couldn't be written; they stay queued. @@ -1050,6 +1152,7 @@ impl Session { log::error!("library: compaction: {e}"); lib.last_error = Some(format!("compaction: {e}")); } + note_upgrade_kept(lib); } /// Compact the log into a snapshot now. @@ -1059,7 +1162,9 @@ impl Session { return Err(EngineError::Other("can't compact during an interaction".into())); } if let Some(lib) = self.library.as_mut() { - lib.journal.snapshot(&self.catalog)?; + let snapshot = lib.journal.snapshot(&self.catalog); + note_upgrade_kept(lib); + snapshot?; } Ok(()) } diff --git a/crates/engine/src/lightroom_archive.rs b/crates/engine/src/lightroom_archive.rs index 511f81f308..4af75bb1a9 100644 --- a/crates/engine/src/lightroom_archive.rs +++ b/crates/engine/src/lightroom_archive.rs @@ -2,10 +2,10 @@ //! //! Archives use a deterministic JSON representation wrapped in zlib. The JSON //! writer streams through a bounded compressor, so an import cannot first build -//! an unbounded archive buffer. Blob columns are omitted by the catalog reader; -//! decoded XMP, -//! settings, history, snapshots, identities, paths, collections & membership -//! remain available for recovery. +//! an unbounded archive buffer. The catalog reader decodes Lightroom's compressed +//! XMP and history-step and snapshot settings and omits other blob columns, so +//! decoded XMP, settings, history, snapshots, identities, paths, collections & +//! membership remain available for recovery. use std::collections::BTreeMap; use std::fs::{self, File}; @@ -29,6 +29,41 @@ pub const MAX_TOTAL_ARCHIVE_BYTES: u64 = 128 * 1024 * 1024; /// Maximum number of managed archives retained. pub const MAX_MANAGED_ARCHIVES: usize = 8; +/// Why [`store`] stored no archive. +#[derive(Debug)] +pub enum StoreError { + /// The archive would pass [`MAX_ARCHIVE_BYTES`], as JSON or on disk. + TooBig, + /// Anything else, such as a folder or file that can't be written. + Failed(String), +} + +impl From for StoreError { + fn from(why: String) -> Self { + Self::Failed(why) + } +} + +impl std::fmt::Display for StoreError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::TooBig => write!(f, "{TooBig}"), + Self::Failed(why) => f.write_str(why), + } + } +} + +/// What [`store_best_effort`] kept. +#[derive(Debug, PartialEq, Eq)] +pub enum Kept { + /// The whole archive. + All(PathBuf), + /// The archive without history-step and snapshot settings (`text`): with them it passed [`MAX_ARCHIVE_BYTES`]. + WithoutSettings(PathBuf), + /// No archive: it passed [`MAX_ARCHIVE_BYTES`] even without them. + Nothing, +} + const FORMAT_VERSION: u8 = 1; const HEADER: &[u8] = b"LC-LRARCH\0\x01Z"; const NAME_PREFIX: &str = "lightroom-import-"; @@ -44,13 +79,18 @@ const IO_BUFFER: usize = 16 * 1024; /// most [`MAX_MANAGED_ARCHIVES`] and [`MAX_TOTAL_ARCHIVE_BYTES`]. Legacy /// `lightroom-import-*.json` files are deliberately ignored and preserved for /// an explicit caller warning. -pub fn store(directory: &Path, data: &CatalogImport) -> Result { +pub fn store(directory: &Path, data: &CatalogImport) -> Result { + store_with(directory, data, true) +} + +/// [`store`], with the `text` of history steps and snapshots only when `settings`. +fn store_with(directory: &Path, data: &CatalogImport, settings: bool) -> Result { prepare_directory(directory)?; let mut managed = managed_files(directory)?; managed.sort_by_key(|entry| entry.index); let temporary = temporary_path(directory)?; - write_archive(&temporary, data).inspect_err(|_| { + write_archive(&temporary, data, settings).inspect_err(|_| { let _ = remove_managed_file(&temporary); })?; @@ -60,7 +100,7 @@ pub fn store(directory: &Path, data: &CatalogImport) -> Result Ok(same) => same, Err(error) => { let _ = remove_managed_file(&temporary); - return Err(error.to_string()); + return Err(error.to_string().into()); } }; if same { @@ -75,20 +115,20 @@ pub fn store(directory: &Path, data: &CatalogImport) -> Result let index = managed.last().map_or(0, |entry| entry.index.saturating_add(1)); if managed.last().is_some_and(|entry| entry.index == u64::MAX) { let _ = remove_managed_file(&temporary); - return Err("managed Lightroom archive index is exhausted".into()); + return Err(StoreError::Failed("managed Lightroom archive index is exhausted".into())); } let destination = match next_destination(directory, index) { Ok(path) => path, Err(error) => { let _ = remove_managed_file(&temporary); - return Err(error); + return Err(error.into()); } }; let size = match fs::metadata(&temporary) { Ok(meta) => meta.len(), Err(error) => { let _ = remove_managed_file(&temporary); - return Err(error.to_string()); + return Err(error.to_string().into()); } }; let new_entry = Managed { index, path: destination.clone(), size }; @@ -99,40 +139,46 @@ pub fn store(directory: &Path, data: &CatalogImport) -> Result Ok(retirees) => retirees, Err(error) => { let _ = remove_managed_file(&temporary); - return Err(error); + return Err(error.into()); } }; let quarantined = match quarantine(&retirees) { Ok(quarantined) => quarantined, Err(error) => { let _ = remove_managed_file(&temporary); - return Err(error); + return Err(error.into()); } }; if let Err(error) = publish_new(&temporary, &destination) { rollback_quarantine(&quarantined); let _ = remove_managed_file(&temporary); - return Err(error.to_string()); + return Err(error.to_string().into()); } if let Err(error) = remove_managed_file(&temporary) { - return Err(format!("archive published but temporary cleanup failed: {error}")); + return Err(StoreError::Failed(format!("archive published but temporary cleanup failed: {error}"))); } for (old, held) in quarantined { if let Err(error) = remove_managed_file(&held) { - return Err(format!("archive published but could not retire {}: {error}", old.display())); + return Err(StoreError::Failed(format!("archive published but could not retire {}: {error}", old.display()))); } } Ok(destination) } -/// Store source data when possible. An archive that reaches its bounded size is -/// omitted with a warning so catalog import can still complete. -pub fn store_best_effort(directory: &Path, data: &CatalogImport) -> Result, String> { +/// Store source data when possible, so catalog import can still complete. An archive past +/// [`MAX_ARCHIVE_BYTES`] is stored again without the history-step and snapshot settings, which +/// can be most of a catalog's data; one still too big is not stored at all. +pub fn store_best_effort(directory: &Path, data: &CatalogImport) -> Result { match store(directory, data) { - Ok(path) => Ok(Some(path)), - Err(error) if error.contains("Lightroom archive exceeds 32 MiB") => Ok(None), - Err(error) => Err(error), + Ok(path) => return Ok(Kept::All(path)), + Err(StoreError::TooBig) => {} + Err(StoreError::Failed(why)) => return Err(why), + } + match store_with(directory, data, false) { + Ok(path) => Ok(Kept::WithoutSettings(path)), + Err(StoreError::TooBig) => Ok(Kept::Nothing), + Err(StoreError::Failed(why)) => Err(why), } } @@ -213,21 +259,25 @@ fn next_destination(directory: &Path, mut index: u64) -> Result Err("no safe managed archive name available".into()) } -fn write_archive(path: &Path, data: &CatalogImport) -> Result<(), String> { +fn write_archive(path: &Path, data: &CatalogImport, settings: bool) -> Result<(), StoreError> { lightcraft_catalog::safe_file::write_atomic_with(path, &mut |raw| { let mut bounded = BoundedWriter { inner: raw, total: 0 }; bounded.write_all(HEADER)?; let mut compressor = ZlibWriter::new(&mut bounded); - serde_json::to_writer(&mut compressor, &ArchiveRef(data)).map_err(json_io)?; + serde_json::to_writer(&mut compressor, &ArchiveRef(data, settings)).map_err(json_io)?; compressor.finish()?; Ok(()) }) .map(|_| ()) - .map_err(|error| format!("could not write Lightroom archive: {error}")) + .map_err(|error| match error.get_ref().is_some_and(|inner| inner.is::()) { + true => StoreError::TooBig, + false => StoreError::Failed(format!("could not write Lightroom archive: {error}")), + }) } +/// A write error from the archive writers keeps its own `io::Error`, so [`TooBig`] can still be told apart. fn json_io(error: serde_json::Error) -> io::Error { - io::Error::new(io::ErrorKind::InvalidData, error.to_string()) + io::Error::from(error) } struct BoundedWriter<'a> { @@ -251,8 +301,20 @@ impl Write for BoundedWriter<'_> { } } +/// The archive writers' error when the archive would pass [`MAX_ARCHIVE_BYTES`]. +#[derive(Debug)] +struct TooBig; + +impl std::fmt::Display for TooBig { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "Lightroom archive exceeds {} MiB", MAX_ARCHIVE_BYTES >> 20) + } +} + +impl std::error::Error for TooBig {} + fn limit_error() -> io::Error { - io::Error::new(io::ErrorKind::InvalidData, "Lightroom archive exceeds 32 MiB") + io::Error::new(io::ErrorKind::InvalidData, TooBig) } struct ZlibWriter<'a, 'b> { @@ -435,67 +497,70 @@ fn remove_managed_file(path: &Path) -> io::Result<()> { fs::remove_file(path) } -struct ArchiveRef<'a>(&'a CatalogImport); +/// The archive of a catalog import, with the `text` of history steps and snapshots only when `.1`. +struct ArchiveRef<'a>(&'a CatalogImport, bool); impl Serialize for ArchiveRef<'_> { fn serialize(&self, serializer: S) -> Result { let mut out = serializer.serialize_struct("CatalogImportArchive", 7)?; out.serialize_field("version", &FORMAT_VERSION)?; out.serialize_field("source", &self.0.source)?; - out.serialize_field("photos", &PhotoSeq(&self.0.photos))?; - out.serialize_field("collections", &RowSeq(&self.0.collections))?; - out.serialize_field("members", &RowSeq(&self.0.members))?; - out.serialize_field("collection_content", &RowSeq(&self.0.collection_content))?; + out.serialize_field("photos", &PhotoSeq(&self.0.photos, self.1))?; + out.serialize_field("collections", &RowSeq(&self.0.collections, None))?; + out.serialize_field("members", &RowSeq(&self.0.members, None))?; + out.serialize_field("collection_content", &RowSeq(&self.0.collection_content, None))?; out.serialize_field("warnings", &self.0.warnings)?; out.end() } } -struct PhotoSeq<'a>(&'a [CatalogPhoto]); +struct PhotoSeq<'a>(&'a [CatalogPhoto], bool); impl Serialize for PhotoSeq<'_> { fn serialize(&self, serializer: S) -> Result { let mut out = serializer.serialize_seq(Some(self.0.len()))?; for photo in self.0 { - out.serialize_element(&PhotoRef(photo))?; + out.serialize_element(&PhotoRef(photo, self.1))?; } out.end() } } -struct PhotoRef<'a>(&'a CatalogPhoto); +struct PhotoRef<'a>(&'a CatalogPhoto, bool); impl Serialize for PhotoRef<'_> { fn serialize(&self, serializer: S) -> Result { let p = self.0; + let skip = (!self.1).then_some("text"); let mut out = serializer.serialize_struct("CatalogPhotoArchive", 8)?; out.serialize_field("source_id", &p.source_id)?; out.serialize_field("uuid", &p.uuid)?; out.serialize_field("path", &p.path)?; - out.serialize_field("image", &RowRef(&p.image))?; + out.serialize_field("image", &RowRef(&p.image, None))?; out.serialize_field("settings", &p.settings)?; out.serialize_field("xmp", &p.xmp)?; out.serialize_field("keywords", &p.keywords)?; - out.serialize_field("history", &RowSeq(&p.history))?; - out.serialize_field("snapshots", &RowSeq(&p.snapshots))?; + out.serialize_field("history", &RowSeq(&p.history, skip))?; + out.serialize_field("snapshots", &RowSeq(&p.snapshots, skip))?; out.end() } } -struct RowSeq<'a>(&'a [BTreeMap]); +/// Rows, each without the column `.1` names. +struct RowSeq<'a>(&'a [BTreeMap], Option<&'a str>); impl Serialize for RowSeq<'_> { fn serialize(&self, serializer: S) -> Result { let mut out = serializer.serialize_seq(Some(self.0.len()))?; for row in self.0 { - out.serialize_element(&RowRef(row))?; + out.serialize_element(&RowRef(row, self.1))?; } out.end() } } -struct RowRef<'a>(&'a BTreeMap); +struct RowRef<'a>(&'a BTreeMap, Option<&'a str>); impl Serialize for RowRef<'_> { fn serialize(&self, serializer: S) -> Result { let mut out = serializer.serialize_map(None)?; - for (key, value) in self.0 { + for (key, value) in self.0.iter().filter(|(key, _)| Some(key.as_str()) != self.1) { out.serialize_entry(key, value)?; } out.end() @@ -608,40 +673,84 @@ mod tests { fn rejects_oversize_before_creating_archive() { let path = tempdir(); let input = data("x".repeat((MAX_ARCHIVE_BYTES as usize) + 1)); - assert!(store(&path, &input).is_err()); + assert!(matches!(store(&path, &input), Err(StoreError::TooBig)), "an oversize archive is told apart by its error"); assert_eq!(managed_count(&path), 0); fs::remove_dir_all(path).unwrap(); } - #[test] - fn large_catalog_history_is_best_effort_and_does_not_abort_import() { - let path = tempdir(); + /// 5,000 photos with 8 KiB of history settings each: about 40 MiB of JSON. + fn large_catalog(history: bool) -> CatalogImport { let mut input = data("catalog.lrcat".into()); input.photos = (0..5_000) - .map(|index| CatalogPhoto { - source_id: index, - uuid: format!("photo-{index}"), - path: format!("/photos/{index}.raw"), - image: BTreeMap::new(), - settings: String::new(), - xmp: String::new(), - keywords: Vec::new(), - history: vec![BTreeMap::from([("text".into(), serde_json::json!(format!("history-{index}-{}", "x".repeat(8 * 1024))))])], - snapshots: Vec::new(), - original: crate::lightroom_catalog::Original::Local, + .map(|index| { + let bulk = format!("history-{index}-{}", "x".repeat(8 * 1024)); + CatalogPhoto { + source_id: index, + uuid: format!("photo-{index}"), + path: format!("/photos/{index}.raw"), + image: BTreeMap::new(), + settings: if history { String::new() } else { bulk.clone() }, + xmp: String::new(), + keywords: Vec::new(), + history: vec![BTreeMap::from([ + ("name".into(), serde_json::json!("Exposure")), + ("text".into(), serde_json::json!(if history { bulk.as_str() } else { "s = {}" })), + ])], + snapshots: vec![BTreeMap::from([("name".into(), serde_json::json!("Before")), ("text".into(), serde_json::json!("s = {}"))])], + original: crate::lightroom_catalog::Original::Local, + } }) .collect(); - assert_eq!(store_best_effort(&path, &input).unwrap(), None); + input + } + + #[test] + fn an_archive_too_big_with_its_history_settings_is_kept_without_them() { + let path = tempdir(); + let kept = store_best_effort(&path, &large_catalog(true)).unwrap(); + let Kept::WithoutSettings(archive) = kept else { panic!("the archive should be kept without settings, not {kept:?}") }; + let decoded = crate::lightroom_fixture::read_archive(&archive); + let photos = decoded["photos"].as_array().unwrap(); + assert_eq!(photos.len(), 5_000, "every photo is still archived"); + assert_eq!(photos[7]["uuid"], serde_json::json!("photo-7")); + assert_eq!(photos[7]["history"], serde_json::json!([{"name": "Exposure"}]), "history steps keep everything but their settings"); + assert_eq!(photos[7]["snapshots"], serde_json::json!([{"name": "Before"}]), "and so do snapshots"); + assert_eq!(fs::read_dir(&path).unwrap().count(), 1, "the first, too big try leaves nothing behind"); + fs::remove_dir_all(path).unwrap(); + } + + #[test] + fn large_catalog_is_best_effort_and_does_not_abort_import() { + let path = tempdir(); + assert_eq!(store_best_effort(&path, &large_catalog(false)).unwrap(), Kept::Nothing, "too big even without history settings"); assert_eq!(managed_count(&path), 0); fs::remove_dir_all(path).unwrap(); } + /// Only the size limit leads to a smaller archive or none: any other failure is reported as such. + #[test] + fn a_write_failure_is_not_taken_for_an_oversize_archive() { + let path = tempdir(); + let file = path.join("not-a-folder"); + fs::write(&file, b"x").unwrap(); + assert!(matches!(store(&file, &rich_data()), Err(StoreError::Failed(_))), "a folder that can't be made"); + let folder = path.join("Interop"); + { + let _full = lightcraft_catalog::safe_file::fail_writes_after(0); + assert!(matches!(store(&folder, &rich_data()), Err(StoreError::Failed(_))), "a full disk while writing"); + assert!(store_best_effort(&folder, &rich_data()).is_err(), "a failure is an error, not a skipped archive"); + } + assert_eq!(fs::read_dir(&folder).unwrap().count(), 0, "a failed write leaves nothing behind"); + fs::remove_dir_all(path).unwrap(); + } + #[test] fn archive_roundtrips_zlib_payload_and_preserves_numeric_arrays() { let path = tempdir(); let archive = store(&path, &rich_data()).unwrap(); let bytes = fs::read(archive).unwrap(); assert!(bytes.starts_with(HEADER)); + assert_eq!(crate::lightroom_fixture::ARCHIVE_HEADER, HEADER, "the fixture reads archives with this module's header"); let json = miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(&bytes[HEADER.len()..], MAX_ARCHIVE_BYTES as usize).unwrap(); let decoded: Value = serde_json::from_slice(&json).unwrap(); assert_eq!(decoded["version"], serde_json::json!(FORMAT_VERSION)); diff --git a/crates/engine/src/lightroom_catalog.rs b/crates/engine/src/lightroom_catalog.rs index d6692d58d3..914c70c7c9 100644 --- a/crates/engine/src/lightroom_catalog.rs +++ b/crates/engine/src/lightroom_catalog.rs @@ -48,8 +48,31 @@ struct Reader { db: Database, tables: Vec, } +/// Most bytes of history-step or snapshot settings decoded from one table. They are only archived, and an archive +/// holds at most [`crate::lightroom_archive::MAX_ARCHIVE_BYTES`] of JSON, so this keeps all a catalog can archive while +/// a hostile one can't make the reader allocate without bound (each row alone may decode to 16 MiB). +const MAX_DECODED_SETTINGS: usize = crate::lightroom_archive::MAX_ARCHIVE_BYTES as usize; + +/// The column of table `name` that Lightroom Classic 13 and later store as compressed text (see [`decode_compressed`]), +/// and what a warning calls one and several of its rows. +fn compressed_settings(name: &str) -> Option<(&'static str, &'static str, &'static str)> { + match name { + "Adobe_libraryImageDevelopHistoryStep" => Some(("text", "history step", "history steps")), + "Adobe_libraryImageDevelopSnapshot" => Some(("text", "snapshot", "snapshots")), + _ => None, + } +} + impl Reader { - fn table(&self, name: &str, required: bool) -> Result, String> { + fn table(&self, name: &str, required: bool, warnings: &mut Vec) -> Result, String> { + self.table_within(name, required, MAX_DECODED_SETTINGS, warnings) + } + + /// The rows of table `name`. Its compressed settings column ([`compressed_settings`]) is decoded within `budget` + /// bytes for the whole table: each value is charged its declared length before it is inflated, even one that then + /// fails to decode. A value that can't be decoded is left out of its row with a warning naming the image, and + /// those past the budget with one warning for all. Other BLOB columns are always left out. + fn table_within(&self, name: &str, required: bool, budget: usize, warnings: &mut Vec) -> Result, String> { let Some(t) = self.tables.iter().find(|t| t.name == name) else { return if required { Err(format!("unsupported Lightroom catalog: missing {name}")) } else { Ok(Vec::new()) }; }; @@ -58,37 +81,69 @@ impl Reader { if rows.len() > 1_000_000 { return Err(format!("{name}: more than one million records")); } - Ok(rows - .into_iter() - .map(|r| { - columns - .iter() - .cloned() - .zip(r.values.into_iter().map(|v| match v { - SqlValue::Null => Some(Value::Null), - SqlValue::Integer(n) => Some(json!(n)), - SqlValue::Real(n) => Some(json!(n)), - SqlValue::Text(s) => Some(json!(s)), - // Opaque Lightroom payloads never become JSON byte arrays. - SqlValue::Blob(_) => None, - })) - .filter_map(|(column, value)| value.map(|value| (column, value))) - .collect() - }) - .collect()) + let compressed = compressed_settings(name); + let mut left = budget; + let mut over_budget = 0usize; + let mut out = Vec::with_capacity(rows.len()); + for r in rows { + let mut row = Row::new(); + let mut settings = None; + for (column, value) in columns.iter().zip(r.values) { + let value = match value { + SqlValue::Null => Value::Null, + SqlValue::Integer(n) => json!(n), + SqlValue::Real(n) => json!(n), + SqlValue::Text(s) => json!(s), + SqlValue::Blob(bytes) => { + if compressed.is_some_and(|(settings_column, _, _)| settings_column == column) { + settings = Some((column, bytes)); + } + // Other opaque Lightroom payloads never become JSON byte arrays. + continue; + } + }; + row.insert(column.clone(), value); + } + if let (Some((column, bytes)), Some((_, what, _))) = (settings, compressed) { + // charged at its declared length before it is inflated (which never goes past that length), so + // a row that then fails to decode counts too; past the budget, the rest aren't inflated at all + let declared = compressed_len(&bytes); + if declared.is_some_and(|n| over_budget > 0 || n > left) { + over_budget += 1; + } else { + left -= declared.unwrap_or(0); + match decode_compressed(&bytes, "settings") { + Ok(text) => { + row.insert(column.clone(), Value::String(text)); + } + Err(why) => warnings.push(format!( + "image {}: {what} {}: {why}; archived without its settings", + number(&row, "image"), + number(&row, "id_local") + )), + } + } + } + out.push(row); + } + if let (Some((_, one, many)), 1..) = (compressed, over_budget) { + let what = if over_budget == 1 { one } else { many }; + warnings.push(format!("{over_budget} {what} archived without their settings: more than {} MiB of settings in {name}", budget >> 20)); + } + Ok(out) } /// The catalog's `Adobe_storeProviderID` (a UUID), kept by Lightroom in its backups; `None` /// when the table or the value is missing or doesn't look like an id. fn catalog_id(&self) -> Option { - let rows = self.table("Adobe_variablesTable", false).ok()?; + let rows = self.table("Adobe_variablesTable", false, &mut Vec::new()).ok()?; let row = rows.iter().find(|r| text(r, "name") == "Adobe_storeProviderID")?; let id = text(row, "value").trim(); (!id.is_empty() && id.len() <= 128 && id.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')).then(|| id.to_string()) } fn optional_table(&self, name: &str, warnings: &mut Vec) -> Result, String> { - match self.table(name, false) { + match self.table(name, false, warnings) { Ok(rows) => Ok(rows), Err(error) => { warnings.push(format!("skipping optional Lightroom table {name}: {error}")); @@ -125,7 +180,7 @@ impl Reader { SqlValue::Integer(n) => Some(json!(n)), SqlValue::Real(n) => Some(json!(n)), SqlValue::Text(s) => Some(json!(s)), - SqlValue::Blob(bytes) if column == "xmp" => match decode_xmp_bytes(&bytes) { + SqlValue::Blob(bytes) if column == "xmp" => match decode_compressed(&bytes, "XMP") { Ok(packet) => Some(Value::String(packet)), Err(error) => { warnings.push(format!("image {image}: {error}")); @@ -352,17 +407,27 @@ fn xmp(v: Option<&Value>) -> Result { } } -fn decode_xmp_bytes(bytes: &[u8]) -> Result { - let size = bytes.get(..4).and_then(|s| <[u8; 4]>::try_from(s).ok()).map(u32::from_be_bytes).ok_or("truncated XMP header")?; - if size > 16 << 20 { - return Err("XMP packet exceeds 16 MiB".into()); +/// The decoded length [`decode_compressed`] reads from `bytes`' header, when it has one of at most 16 MiB. +fn compressed_len(bytes: &[u8]) -> Option { + let size = bytes.get(..4).and_then(|s| <[u8; 4]>::try_from(s).ok()).map(u32::from_be_bytes)?; + usize::try_from(size).ok().filter(|size| *size <= 16 << 20) +} + +/// Lightroom's compressed text (`Adobe_AdditionalMetadata.xmp`, and history-step and snapshot settings since Lightroom +/// Classic 13): the decoded length as 4 big-endian bytes, then a zlib stream, at most 16 MiB decoded. Errors name it +/// `what`. +fn decode_compressed(bytes: &[u8], what: &str) -> Result { + if bytes.len() < 4 { + return Err(format!("truncated {what} header")); } - let decoded = miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(bytes.get(4..).ok_or("truncated XMP")?, 16 << 20) - .map_err(|_| "invalid compressed XMP")?; - if decoded.len() != size as usize { - return Err("XMP packet length mismatch".into()); + let size = compressed_len(bytes).ok_or_else(|| format!("{what} longer than 16 MiB"))?; + // inflated no further than its declared length: a stream that goes on is invalid, at no more cost than a valid one + let decoded = miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(bytes.get(4..).ok_or_else(|| format!("truncated {what}"))?, size) + .map_err(|_| format!("invalid compressed {what}"))?; + if decoded.len() != size { + return Err(format!("{what} length mismatch")); } - String::from_utf8(decoded).map_err(|e| e.to_string()) + String::from_utf8(decoded).map_err(|e| format!("{what} not UTF-8: {e}")) } // SQLite file format §4: validate the live checksum chain in constant space, then overlay @@ -482,9 +547,9 @@ fn read_file(path: &Path, document: &Path, source: &Path, cancel: &AtomicBool, d } let reader = Reader { tables: db.live_tables()?, db }; let mut warnings = Vec::new(); - let table = |name: &str, required: bool| -> Result, String> { + let table = |name: &str, required: bool, warnings: &mut Vec| -> Result, String> { ensure_read_active(cancel)?; - let rows = reader.table(name, required)?; + let rows = reader.table(name, required, warnings)?; done.fetch_add(1, Ordering::Relaxed); Ok(rows) }; @@ -494,9 +559,9 @@ fn read_file(path: &Path, document: &Path, source: &Path, cancel: &AtomicBool, d done.fetch_add(1, Ordering::Relaxed); Ok(rows) }; - let roots: HashMap<_, _> = table("AgLibraryRootFolder", true)?.into_iter().map(|r| (number(&r, "id_local"), r)).collect(); - let folders: HashMap<_, _> = table("AgLibraryFolder", true)?.into_iter().map(|r| (number(&r, "id_local"), r)).collect(); - let files: HashMap<_, _> = table("AgLibraryFile", true)?.into_iter().map(|r| (number(&r, "id_local"), r)).collect(); + let roots: HashMap<_, _> = table("AgLibraryRootFolder", true, &mut warnings)?.into_iter().map(|r| (number(&r, "id_local"), r)).collect(); + let folders: HashMap<_, _> = table("AgLibraryFolder", true, &mut warnings)?.into_iter().map(|r| (number(&r, "id_local"), r)).collect(); + let files: HashMap<_, _> = table("AgLibraryFile", true, &mut warnings)?.into_iter().map(|r| (number(&r, "id_local"), r)).collect(); let develops: HashMap<_, _> = optional_table("Adobe_imageDevelopSettings", &mut warnings)? .into_iter() .map(|r| (number(&r, "image"), text(&r, "text").to_string())) @@ -580,7 +645,7 @@ fn read_file(path: &Path, document: &Path, source: &Path, cancel: &AtomicBool, d // these behind and ignores them); they and their virtual copies are skipped and reported // instead of failing the import let mut orphans = HashSet::new(); - for image in table("Adobe_images", true)? { + for image in table("Adobe_images", true, &mut out.warnings)? { ensure_read_active(cancel)?; let id = number(&image, "id_local"); let record = files.get(&number(&image, "rootFile")).ok_or(SkipReason::MissingFile).and_then(|file| { @@ -947,7 +1012,7 @@ fn apply(s: &mut crate::Session, data: CatalogImport, update_existing: bool) -> let archive_dir = s.library.as_ref().filter(|l| l.on_disk).map(|l| l.dir.join("Interop")); let index_path = archive_dir.as_ref().map(|p| p.join("lightroom-index.json")); let mut index = load_index(index_path.as_deref())?; - let archive_path = archive_dir.as_ref().map(|dir| crate::lightroom_archive::store(dir, &data).map_err(error)).transpose()?; + let archive_path = archive_dir.as_ref().map(|dir| crate::lightroom_archive::store(dir, &data).map_err(|e| error(e.to_string()))).transpose()?; let undo0 = s.undo.len(); let existing: HashMap<_, _> = s.catalog.photos().filter(|p| p.copy_of.is_none()).filter_map(|p| source_path(p).map(|path| (key(path), p.id))).collect(); @@ -1272,7 +1337,7 @@ pub(crate) fn apply_prepared(s: &mut crate::Session, mut data: CatalogImport, co p.duration = duplicate.duration; p.as_shot_wb = duplicate.as_shot_wb; p.content_hash = duplicate.content_hash.clone(); - p.embedded_lens = duplicate.embedded_lens; + p.embedded_lens = duplicate.embedded_lens.clone(); p.preview_only = duplicate.preview_only.clone(); p.preview_checked = duplicate.preview_checked.clone(); let file = file.cloned().unwrap_or_else(|| { diff --git a/crates/engine/src/lightroom_catalog/tests.rs b/crates/engine/src/lightroom_catalog/tests.rs index 0bdef04326..3503960858 100644 --- a/crates/engine/src/lightroom_catalog/tests.rs +++ b/crates/engine/src/lightroom_catalog/tests.rs @@ -265,7 +265,7 @@ fn a_content_duplicate_raw_starts_from_its_camera_defaults() { p.format = "DNG".into(); p.kind = lightcraft_catalog::MediaKind::Raw; p.as_shot_wb = Some((5200.0, 4.0)); - p.embedded_lens = Some(lightcraft_develop::EmbeddedLens::default()); + p.embedded_lens = Some(Box::default()); }); let mut data = sample(); data.photos.retain(|p| number(&p.image, "masterImage") == 0); @@ -2012,3 +2012,62 @@ fn oversized_optional_table_warns_and_is_skipped() { assert!(rows.is_empty()); assert!(warnings.iter().any(|warning| warning.contains("optional_history"))); } + +/// A catalog whose settings decode to more than the budget keeps every row, archives the settings that fit, and +/// says once how many it left out, instead of allocating whatever its BLOBs inflate to. +#[test] +fn settings_past_the_decode_budget_are_left_out_with_one_warning() { + use crate::lightroom_fixture::{self as fixture, Field, Table}; + let dir = fixture::dir("history-budget"); + let catalog = dir.join("test.lrcat"); + let big = "x".repeat(512 << 10); + let rows = (1..=4).map(|id| fixture::history_step(id, 1, id as f64, "Step", Field::Blob(fixture::compressed(&big)))).collect(); + fixture::write(&catalog, &[Table { name: "Adobe_libraryImageDevelopHistoryStep", columns: fixture::HISTORY_COLUMNS, rows }]); + let db = Database::open_file_with_wal(FileSource::open(&catalog).unwrap(), &[]).unwrap(); + let reader = Reader { tables: db.live_tables().unwrap(), db }; + let mut warnings = Vec::new(); + let rows = reader.table_within("Adobe_libraryImageDevelopHistoryStep", true, 1 << 20, &mut warnings).unwrap(); + assert_eq!(rows.len(), 4, "every step is still read"); + assert_eq!(rows.iter().filter(|r| r.contains_key("text")).count(), 2, "the two steps within 1 MiB keep their settings"); + assert_eq!(warnings, ["2 history steps archived without their settings: more than 1 MiB of settings in Adobe_libraryImageDevelopHistoryStep"]); + let _ = std::fs::remove_dir_all(dir); +} + +/// A stream that inflates past the length its header declares is stopped there, not inflated up to 16 MiB first. +#[test] +fn a_stream_longer_than_its_declared_length_is_stopped_at_that_length() { + let mut bytes = 10u32.to_be_bytes().to_vec(); + bytes.extend(miniz_oxide::deflate::compress_to_vec_zlib(&[b'x'; 1024], 6)); + assert_eq!(decode_compressed(&bytes, "settings"), Err("invalid compressed settings".to_string())); + let mut exact = 1024u32.to_be_bytes().to_vec(); + exact.extend(miniz_oxide::deflate::compress_to_vec_zlib(&[b'x'; 1024], 6)); + assert_eq!(decode_compressed(&exact, "settings").map(|text| text.len()), Ok(1024), "exactly its length decodes"); +} + +/// Settings that fail to decode still cost their declared length, so a catalog of damaged rows can't make the +/// reader inflate without bound: past the budget, the rest are left out without being inflated. +#[test] +fn settings_that_fail_to_decode_still_count_against_the_budget() { + use crate::lightroom_fixture::{self as fixture, Field, Table}; + let dir = fixture::dir("history-budget-bad"); + let catalog = dir.join("test.lrcat"); + let mut damaged = (512u32 << 10).to_be_bytes().to_vec(); + damaged.extend([1, 2, 3]); + let rows = (1..=4).map(|id| fixture::history_step(id, 1, id as f64, "Step", Field::Blob(damaged.clone()))).collect(); + fixture::write(&catalog, &[Table { name: "Adobe_libraryImageDevelopHistoryStep", columns: fixture::HISTORY_COLUMNS, rows }]); + let db = Database::open_file_with_wal(FileSource::open(&catalog).unwrap(), &[]).unwrap(); + let reader = Reader { tables: db.live_tables().unwrap(), db }; + let mut warnings = Vec::new(); + let rows = reader.table_within("Adobe_libraryImageDevelopHistoryStep", true, 1 << 20, &mut warnings).unwrap(); + assert_eq!(rows.len(), 4, "every step is still read"); + assert_eq!( + warnings, + [ + "image 1: history step 1: invalid compressed settings; archived without its settings", + "image 1: history step 2: invalid compressed settings; archived without its settings", + "2 history steps archived without their settings: more than 1 MiB of settings in Adobe_libraryImageDevelopHistoryStep", + ], + "the two damaged steps within 1 MiB are tried; the other two aren't" + ); + let _ = std::fs::remove_dir_all(dir); +} diff --git a/crates/engine/src/lightroom_fixture.rs b/crates/engine/src/lightroom_fixture.rs new file mode 100644 index 0000000000..ce8325a91e --- /dev/null +++ b/crates/engine/src/lightroom_fixture.rs @@ -0,0 +1,259 @@ +//! Synthetic Lightroom catalogs for tests: a small SQLite file written page by page, so the catalog reader is tested +//! on the bytes it reads in the field (text and BLOB cells, Lightroom's compressed encoding) with no SQLite library. +//! Each table is one leaf page; rows must fit in it without overflow pages. + +use std::path::{Path, PathBuf}; + +const PAGE_SIZE: usize = 4096; +/// The largest record a 4096-byte table leaf holds without an overflow page (SQLite file format §1.6: U - 35). +const MAX_LOCAL: usize = PAGE_SIZE - 35; + +#[derive(Clone, Debug)] +pub(crate) enum Field { + Null, + Integer(i64), + Real(f64), + Text(String), + Blob(Vec), +} + +pub(crate) fn text(s: &str) -> Field { + Field::Text(s.into()) +} + +pub(crate) struct Table { + pub name: &'static str, + /// The column list of its `CREATE TABLE`, as Lightroom writes it. + pub columns: &'static str, + pub rows: Vec>, +} + +/// Lightroom Classic's compressed text (as in `Adobe_AdditionalMetadata.xmp`, and history steps and snapshots since +/// Lightroom Classic 13): the decoded length as 4 big-endian bytes, then the zlib stream. +pub(crate) fn compressed(text: &str) -> Vec { + compressed_bytes(text.as_bytes()) +} + +/// [`compressed`] for any bytes, including ones that aren't UTF-8. +pub(crate) fn compressed_bytes(bytes: &[u8]) -> Vec { + let mut out = u32::try_from(bytes.len()).unwrap().to_be_bytes().to_vec(); + out.extend(miniz_oxide::deflate::compress_to_vec_zlib(bytes, 6)); + out +} + +pub(crate) const HISTORY_COLUMNS: &str = "id_local INTEGER PRIMARY KEY, id_global UNIQUE NOT NULL, dateCreated, digest, \ + hasBigData INTEGER NOT NULL DEFAULT 0, hasDevelopAdjustments, image INTEGER, name, relValueString, text, valueString"; +pub(crate) const SNAPSHOT_COLUMNS: &str = "id_local INTEGER PRIMARY KEY, id_global UNIQUE NOT NULL, digest, \ + hasBigData INTEGER NOT NULL DEFAULT 0, hasDevelopAdjustments, image INTEGER, locked, name, snapshotID, text"; + +/// A history step row for image `image` (columns as in [`HISTORY_COLUMNS`]); `settings` is a text or BLOB field. +pub(crate) fn history_step(id: i64, image: i64, date: f64, name: &str, settings: Field) -> Vec { + vec![ + Field::Integer(id), + text(&format!("history-{id}")), + Field::Real(date), + Field::Null, + Field::Integer(0), + Field::Integer(1), + Field::Integer(image), + text(name), + Field::Null, + settings, + Field::Null, + ] +} + +/// A snapshot row for image `image` (columns as in [`SNAPSHOT_COLUMNS`]); `settings` is a text or BLOB field. +pub(crate) fn snapshot(id: i64, image: i64, name: &str, settings: Field) -> Vec { + vec![ + Field::Integer(id), + text(&format!("snapshot-{id}")), + Field::Null, + Field::Integer(0), + Field::Integer(1), + Field::Integer(image), + Field::Null, + text(name), + Field::Null, + settings, + ] +} + +/// The tables of a catalog with one photo, image 1 (`/Photos/test.ARW`, not created), with the develop +/// settings `settings`. Add history, snapshot or other tables and pass them all to [`write`]. +pub(crate) fn one_photo(originals: &Path, settings: &str) -> Vec { + let mut root = originals.to_string_lossy().into_owned(); + if !root.ends_with('/') { + root.push('/'); + } + vec![ + Table { + name: "AgLibraryRootFolder", + columns: "id_local INTEGER PRIMARY KEY, id_global UNIQUE NOT NULL, absolutePath UNIQUE NOT NULL DEFAULT '', name NOT NULL DEFAULT '', relativePathFromCatalog", + rows: vec![vec![Field::Integer(1), text("root-1"), Field::Text(root), text("originals"), Field::Null]], + }, + Table { + name: "AgLibraryFolder", + columns: "id_local INTEGER PRIMARY KEY, id_global UNIQUE NOT NULL, pathFromRoot NOT NULL DEFAULT '', rootFolder INTEGER NOT NULL DEFAULT 0", + rows: vec![vec![Field::Integer(1), text("folder-1"), text("Photos/"), Field::Integer(1)]], + }, + Table { + name: "AgLibraryFile", + columns: "id_local INTEGER PRIMARY KEY, id_global UNIQUE NOT NULL, baseName NOT NULL DEFAULT '', extension NOT NULL DEFAULT '', folder INTEGER NOT NULL DEFAULT 0, idx_filename NOT NULL DEFAULT ''", + rows: vec![vec![Field::Integer(1), text("file-1"), text("test"), text("ARW"), Field::Integer(1), text("test.ARW")]], + }, + Table { + name: "Adobe_images", + columns: "id_local INTEGER PRIMARY KEY, id_global UNIQUE NOT NULL, fileFormat NOT NULL DEFAULT 'unset', fileHeight, fileWidth, masterImage INTEGER, pick NOT NULL DEFAULT 0, rating, rootFile INTEGER NOT NULL DEFAULT 0", + rows: vec![vec![ + Field::Integer(1), + text("image-1"), + text("RAW"), + Field::Integer(10), + Field::Integer(20), + Field::Null, + Field::Integer(0), + Field::Null, + Field::Integer(1), + ]], + }, + Table { + name: "Adobe_imageDevelopSettings", + columns: "id_local INTEGER PRIMARY KEY, image INTEGER, text", + rows: vec![vec![Field::Integer(1), Field::Integer(1), text(settings)]], + }, + ] +} + +/// The format header an import archive starts with (`lightroom_archive`'s), before its zlib-compressed JSON. +pub(crate) const ARCHIVE_HEADER: &[u8] = b"LC-LRARCH\0\x01Z"; + +/// The JSON the import archive at `path` holds, for tests that check what an import kept. The JSON itself is capped +/// at `MAX_ARCHIVE_BYTES` too, so that is the most it can inflate to. +pub(crate) fn read_archive(path: &Path) -> serde_json::Value { + let bytes = std::fs::read(path).unwrap(); + let json = bytes.strip_prefix(ARCHIVE_HEADER).unwrap_or_else(|| panic!("{} is not an import archive", path.display())); + serde_json::from_slice( + &miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(json, crate::lightroom_archive::MAX_ARCHIVE_BYTES as usize).unwrap(), + ) + .unwrap() +} + +/// A new, empty folder for one test's catalog. +pub(crate) fn dir(tag: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("lightcraft-lrcat-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d +} + +/// Write `tables` as a SQLite database at `path`: page 1 holds the schema, table `i` page `i + 2`. +pub(crate) fn write(path: &Path, tables: &[Table]) { + let mut schema = Vec::new(); + let mut pages = Vec::new(); + for (i, table) in tables.iter().enumerate() { + let root = i64::try_from(i + 2).unwrap(); + schema.push(vec![ + text("table"), + text(table.name), + text(table.name), + Field::Integer(root), + Field::Text(format!("CREATE TABLE {}({})", table.name, table.columns)), + ]); + pages.push(leaf(0, &table.rows, table.name)); + } + let mut first = leaf(100, &schema, "sqlite_master"); + first[..16].copy_from_slice(b"SQLite format 3\0"); + first[16..18].copy_from_slice(&u16::try_from(PAGE_SIZE).unwrap().to_be_bytes()); + first[18] = 1; // legacy journal mode: no WAL file is read unless it exists + first[19] = 1; + first[21] = 64; + first[22] = 32; + first[23] = 32; + first[24..28].copy_from_slice(&1u32.to_be_bytes()); + first[28..32].copy_from_slice(&u32::try_from(pages.len() + 1).unwrap().to_be_bytes()); + first[40..44].copy_from_slice(&1u32.to_be_bytes()); + first[44..48].copy_from_slice(&4u32.to_be_bytes()); + first[56..60].copy_from_slice(&1u32.to_be_bytes()); // UTF-8 + first[92..96].copy_from_slice(&1u32.to_be_bytes()); + first[96..100].copy_from_slice(&3_045_000u32.to_be_bytes()); + let mut bytes = first; + for page in pages { + bytes.extend(page); + } + std::fs::write(path, bytes).unwrap(); +} + +fn leaf(base: usize, rows: &[Vec], table: &str) -> Vec { + let mut page = vec![0u8; PAGE_SIZE]; + page[base] = 0x0d; + page[base + 3..base + 5].copy_from_slice(&u16::try_from(rows.len()).unwrap().to_be_bytes()); + let mut end = PAGE_SIZE; + for (i, values) in rows.iter().enumerate() { + let payload = record(values); + assert!(payload.len() <= MAX_LOCAL, "{table} row {i}: {} bytes needs an overflow page, which the fixture doesn't write", payload.len()); + let rowid = match values.first() { + Some(Field::Integer(id)) => u64::try_from(*id).unwrap(), + _ => u64::try_from(i + 1).unwrap(), + }; + let mut cell = varint(u64::try_from(payload.len()).unwrap()); + cell.extend(varint(rowid)); + cell.extend(payload); + let pointers_end = base + 8 + (i + 1) * 2; + end = end.checked_sub(cell.len()).filter(|e| *e >= pointers_end).unwrap_or_else(|| panic!("{table}: rows don't fit in one page")); + page[end..end + cell.len()].copy_from_slice(&cell); + page[pointers_end - 2..pointers_end].copy_from_slice(&u16::try_from(end).unwrap().to_be_bytes()); + } + page[base + 5..base + 7].copy_from_slice(&u16::try_from(end).unwrap().to_be_bytes()); + page +} + +/// A record (SQLite file format §2.1). An `INTEGER PRIMARY KEY` column's value is the rowid, stored as NULL. +fn record(values: &[Field]) -> Vec { + let mut serials = Vec::new(); + let mut body = Vec::new(); + for (i, value) in values.iter().enumerate() { + let serial = match value { + Field::Integer(_) if i == 0 => 0, + Field::Null => 0, + Field::Integer(n) => { + body.extend(n.to_be_bytes()); + 6 + } + Field::Real(n) => { + body.extend(n.to_be_bytes()); + 7 + } + Field::Text(s) => { + body.extend(s.as_bytes()); + 13 + 2 * u64::try_from(s.len()).unwrap() + } + Field::Blob(b) => { + body.extend(b); + 12 + 2 * u64::try_from(b.len()).unwrap() + } + }; + serials.extend(varint(serial)); + } + // the header length counts its own varint + let mut header_len = serials.len() + 1; + if varint(u64::try_from(header_len).unwrap()).len() > 1 { + header_len += 1; + } + let mut out = varint(u64::try_from(header_len).unwrap()); + out.extend(serials); + out.extend(body); + out +} + +/// SQLite's big-endian varint (values below 2^56, which is all a fixture needs). +fn varint(mut value: u64) -> Vec { + let mut out = vec![(value & 0x7f) as u8]; + value >>= 7; + while value != 0 { + out.push((value & 0x7f) as u8 | 0x80); + value >>= 7; + } + out.reverse(); + out +} diff --git a/crates/engine/src/lightroom_job.rs b/crates/engine/src/lightroom_job.rs index 7a039fe0f1..695398bcc6 100644 --- a/crates/engine/src/lightroom_job.rs +++ b/crates/engine/src/lightroom_job.rs @@ -31,11 +31,20 @@ fn cancelled() -> crate::EngineError { } fn stage_archive(archive_dir: Option<&Path>, data: &mut CatalogImport) -> crate::Result> { - let archive_path = archive_dir.map(|dir| crate::lightroom_archive::store_best_effort(dir, data).map_err(error)).transpose()?.flatten(); - if archive_dir.is_some() && archive_path.is_none() { - data.warnings.push("Lightroom source archive exceeded 32 MiB; archive skipped".into()); - } - Ok(archive_path) + use crate::lightroom_archive::{Kept, MAX_ARCHIVE_BYTES}; + let Some(dir) = archive_dir else { return Ok(None) }; + let limit = MAX_ARCHIVE_BYTES >> 20; + Ok(match crate::lightroom_archive::store_best_effort(dir, data).map_err(error)? { + Kept::All(path) => Some(path), + Kept::WithoutSettings(path) => { + data.warnings.push(format!("Lightroom source archive exceeded {limit} MiB; archived without history-step and snapshot settings")); + Some(path) + } + Kept::Nothing => { + data.warnings.push(format!("Lightroom source archive exceeded {limit} MiB; archive skipped")); + None + } + }) } /// Memory identity of the library which owns a prepared completion. @@ -521,59 +530,67 @@ mod tests { assert_eq!(session.undo.len(), 3); } + /// 5,000 photos with 8 KiB each of history settings (`in_history`) or develop settings: about 40 MiB of JSON. An + /// archive too big with its history settings is kept without them; one too big even then is skipped. Either + /// way the import goes on and says so. #[test] - fn oversized_history_archive_keeps_prepared_import_successful_with_warning() { - let archive_dir = std::env::temp_dir().join(format!("lightcraft-lr-prepared-scale-{}", std::process::id())); - let mut data = empty_data(); - data.photos = (0..5_000) - .map(|source_id| { - let image = std::collections::BTreeMap::from([ - ("id_local".into(), serde_json::json!(source_id)), - ("fileFormat".into(), serde_json::json!("JPG")), - ("fileWidth".into(), serde_json::json!(1)), - ("fileHeight".into(), serde_json::json!(1)), - ]); - lightroom_catalog::CatalogPhoto { - source_id, - uuid: format!("scale-{source_id}"), - path: format!("/missing/scale-{source_id}.jpg"), - image, - settings: String::new(), - xmp: String::new(), - keywords: Vec::new(), - history: vec![std::collections::BTreeMap::from([( - "text".into(), - serde_json::json!(format!("history-{source_id}-{}", "x".repeat(8 * 1024))), - )])], - snapshots: Vec::new(), - original: lightroom_catalog::Original::Local, - } - }) - .collect(); - let archive_path = stage_archive(Some(&archive_dir), &mut data).unwrap(); - assert!(archive_path.is_none()); - let mut session = crate::Session::new(); - let token = LightroomLibraryToken::capture(&session); - let prepared = PreparedLightroom { - data, - normal: Prepared::default(), - index: ImportIndex::default(), - archive_path, - token, - missing_sources: HashSet::new(), - update_existing: false, - now: "2026-01-01T00:00:00".into(), - cancelled: false, - }; - let completion = commit_prepared(&mut session, prepared).unwrap(); - assert_eq!(completion.report["photos"], 5_000); - assert!( - completion.report["warnings"] - .as_array() - .is_some_and(|warnings| warnings.iter().any(|warning| warning == "Lightroom source archive exceeded 32 MiB; archive skipped")) - ); - assert_eq!(session.catalog.len(), 5_000); - std::fs::remove_dir_all(archive_dir).unwrap(); + fn oversized_archive_keeps_prepared_import_successful_with_warning() { + for (in_history, warning, archived) in [ + (true, "Lightroom source archive exceeded 32 MiB; archived without history-step and snapshot settings", true), + (false, "Lightroom source archive exceeded 32 MiB; archive skipped", false), + ] { + let archive_dir = std::env::temp_dir().join(format!("lightcraft-lr-prepared-scale-{in_history}-{}", std::process::id())); + let mut data = empty_data(); + data.photos = (0..5_000) + .map(|source_id| { + let image = std::collections::BTreeMap::from([ + ("id_local".into(), serde_json::json!(source_id)), + ("fileFormat".into(), serde_json::json!("JPG")), + ("fileWidth".into(), serde_json::json!(1)), + ("fileHeight".into(), serde_json::json!(1)), + ]); + let bulk = format!("history-{source_id}-{}", "x".repeat(8 * 1024)); + lightroom_catalog::CatalogPhoto { + source_id, + uuid: format!("scale-{source_id}"), + path: format!("/missing/scale-{source_id}.jpg"), + image, + settings: if in_history { String::new() } else { bulk.clone() }, + xmp: String::new(), + keywords: Vec::new(), + history: vec![std::collections::BTreeMap::from([( + "text".into(), + serde_json::json!(if in_history { bulk } else { String::new() }), + )])], + snapshots: Vec::new(), + original: lightroom_catalog::Original::Local, + } + }) + .collect(); + let archive_path = stage_archive(Some(&archive_dir), &mut data).unwrap(); + assert_eq!(archive_path.is_some(), archived, "{warning}"); + let mut session = crate::Session::new(); + let token = LightroomLibraryToken::capture(&session); + let prepared = PreparedLightroom { + data, + normal: Prepared::default(), + index: ImportIndex::default(), + archive_path, + token, + missing_sources: HashSet::new(), + update_existing: false, + now: "2026-01-01T00:00:00".into(), + cancelled: false, + }; + let completion = commit_prepared(&mut session, prepared).unwrap(); + assert_eq!(completion.report["photos"], 5_000); + assert!( + completion.report["warnings"].as_array().is_some_and(|warnings| warnings.iter().any(|w| w == warning)), + "the report should say: {warning}" + ); + assert_eq!(session.catalog.len(), 5_000); + std::fs::remove_dir_all(archive_dir).unwrap(); + } } #[test] diff --git a/crates/engine/src/media/quick.rs b/crates/engine/src/media/quick.rs index c3d9047d3f..3bc6c163e9 100644 --- a/crates/engine/src/media/quick.rs +++ b/crates/engine/src/media/quick.rs @@ -209,7 +209,7 @@ fn header_info(p: &Photo) -> SourceInfo { raw: true, as_shot_temp: temp, as_shot_tint: tint, - lens: p.embedded_lens, + lens: p.embedded_lens.as_deref().copied(), relative_wb: relative, // (a fitted-look raw edited in Kelvin: its camera's matrices give the scale, see `files::WbScaleOf`) legacy_relative_wb: p.fitted_look() && !relative, diff --git a/crates/engine/src/media/session.rs b/crates/engine/src/media/session.rs index 4bf40bbf57..8e0cd85f5a 100644 --- a/crates/engine/src/media/session.rs +++ b/crates/engine/src/media/session.rs @@ -367,7 +367,7 @@ impl crate::Session { p.height.max(1) as usize, &job.settings, apply_crop, - p.embedded_lens.as_ref(), + p.embedded_lens.as_deref(), ); let ppl = frame.px_per_long(full_w); lightcraft_pipeline::spots::window_for_reads_checked(&job.settings, &frame, full_w, full_h, ppl, window.clamped(full_w, full_h))?; @@ -601,7 +601,10 @@ impl crate::Session { } job.request.space = space; job.request.depth = depth; - job.key ^= (space as u64 + 1).wrapping_mul(0xa076_1d64_78bd_642f) ^ (depth as u64 + 1).wrapping_mul(0xe703_7ed1_a0b4_28db); + // an export shrinks with a sharp filter: a preview's soft one leaves a small export blurred (#2970) + job.request.downscale = lightcraft_pipeline::Downscale::Sharp; + job.key ^= + (space as u64 + 1).wrapping_mul(0xa076_1d64_78bd_642f) ^ (depth as u64 + 1).wrapping_mul(0xe703_7ed1_a0b4_28db) ^ 0x9e37_79b9_7f4a_7c15; Ok(job) } diff --git a/crates/engine/src/media/source.rs b/crates/engine/src/media/source.rs index d1946de179..1312843158 100644 --- a/crates/engine/src/media/source.rs +++ b/crates/engine/src/media/source.rs @@ -1,9 +1,12 @@ use super::{Arc, DcpProfile, Deserialize, DevelopSettings, MediaKind, Photo, Rgb32f, Rgba8, Serialize, SourceInfo}; /// Bump when the pipeline's output changes, to invalidate cached thumbnails. +/// 87: a lens database's vignetting correction reaches the look fit only in the share the camera JPEG shows +/// (#3943, which had reserved 83: taken after 86, so a later bump counting up from here can't meet an older cache). +/// 86: pushed shadows keep the camera profile's colour and tone (#2092). +/// 85: raw decoding keeps negative channels (#2278). /// 84: full-size raw demosaic runs on the white-balanced mosaic with a clip mask (#1328). -/// 83 is reserved by open #3943. -pub const RENDER_CACHE_VERSION: u64 = 84; +pub const RENDER_CACHE_VERSION: u64 = 87; /// Thumbnails render at one of these long edges (so window/cell size changes reuse the cache). pub const THUMB_SIZES: [usize; 4] = [128, 256, 384, 512]; diff --git a/crates/engine/src/merge.rs b/crates/engine/src/merge.rs index 76bcfd7f29..70ad1328fb 100644 --- a/crates/engine/src/merge.rs +++ b/crates/engine/src/merge.rs @@ -430,29 +430,72 @@ impl Session { /// apply Auto Settings / the auto crop. Returns `{id, path, …info}`. pub fn finish_merge(&mut self, job: &MergeJob, out: MergeOutput) -> Result { let first = &job.sources.first().ok_or_else(|| EngineError::Other("nothing merged".into()))?.1; - // a new file under a free name (never replacing one), complete and synced before it appears - let path = lightcraft_catalog::safe_file::write_new_unique(&mut output_names(first, job.kind.suffix()), &out.dng) - .map_err(|e| EngineError::Other(format!("could not write the merged DNG next to {first}: {e}")))? - .to_string_lossy() - .to_string(); - let report = crate::import::import(self, std::slice::from_ref(&path), crate::import::ImportMode::Add)?; - let id = report - .imported - .first() - .copied() - .map(PhotoId) - .ok_or_else(|| EngineError::Other(format!("the merged file {path} could not be imported: {:?}", report.failed)))?; - if job.finish.stack { + let output_hash = lightcraft_preview::hash_bytes(&out.dng).to_string(); + // Import deduplicates by content. Reuse an existing merge only while its live source has + // matching bytes; stale, missing or deleted rows fail before another file is published. + let candidates: Vec<(PhotoId, String, bool)> = self + .catalog + .photos() + .filter_map(|p| { + if p.content_hash.as_deref() != Some(output_hash.as_str()) { + return None; + } + let Source::File { path } = &p.source else { return None }; + Some((p.id, path.clone(), p.deleted)) + }) + .collect(); + let valid_existing = candidates + .iter() + .find(|(_, path, deleted)| { + if *deleted { + return false; + } + let bytes = match &self.media.file_bytes { + Some(read) => read(path).ok(), + None => std::fs::read(path).ok(), + }; + bytes.is_some_and(|bytes| lightcraft_preview::hash_bytes(&bytes).to_string() == output_hash) + }) + .cloned(); + let (id, path, reused) = if let Some((id, path, _)) = valid_existing { + (id, path, true) + } else if let Some((id, path, deleted)) = candidates.first() { + let state = if *deleted { "deleted" } else { "missing or changed" }; + return Err(EngineError::Other(format!( + "existing merge result {id:?} has a {state} source at {path}; relink or remove it before repeating the merge" + ))); + } else { + // A new file under a free name (never replacing one), complete and synced before it appears. + let path = lightcraft_catalog::safe_file::write_new_unique(&mut output_names(first, job.kind.suffix()), &out.dng) + .map_err(|e| EngineError::Other(format!("could not write the merged DNG next to {first}: {e}")))? + .to_string_lossy() + .to_string(); + let report = match crate::import::import(self, std::slice::from_ref(&path), crate::import::ImportMode::Add) { + Ok(report) => report, + Err(e) => { + let _ = std::fs::remove_file(&path); + return Err(e); + } + }; + if let Some(id) = report.imported.first().copied().map(PhotoId) { + (id, path, false) + } else { + let _ = std::fs::remove_file(&path); + return Err(EngineError::Other(format!("the merged file {path} could not be imported: {:?}", report.failed))); + } + }; + if !reused && job.finish.stack { let sources: Vec = job.sources.iter().map(|(p, _)| *p).collect(); if let Some(op) = self.catalog.stack_with_ops(id, &sources) { self.commit("Stack with Sources", op)?; } } self.selection = crate::Selection::single(id); - if job.finish.auto_settings { + if !reused && job.finish.auto_settings { self.execute("develop.auto", &json!({}))?; } - if let Some(c) = out.crop + if !reused + && let Some(c) = out.crop && let Some(d) = self.develop_of(id) { let mut d = (*d).clone(); @@ -463,6 +506,7 @@ impl Session { info["id"] = json!(id.0); info["path"] = json!(path); info["bytes"] = json!(out.dng.len()); + info["reused"] = json!(reused); Ok(info) } diff --git a/crates/engine/src/presets.rs b/crates/engine/src/presets.rs index a1aa603c83..d43dbd2f58 100644 --- a/crates/engine/src/presets.rs +++ b/crates/engine/src/presets.rs @@ -178,21 +178,18 @@ impl Session { /// from an XMP sidecar or a catalog import, which record none) composes them on its current /// settings instead, since the camera defaults are not its import state. Either way, the /// settings the preset does not name keep the photo's values (issue #2159). The `preset.apply` - /// command and the UI's hover previews share this, so hovering shows exactly what a click commits. + /// command and the UI's hover previews and thumbnails share this, so hovering shows exactly what + /// a click commits, white balance preparation included ([`apply_preset_to_photo`]). pub fn preset_applied(&self, id: PhotoId, preset: &Preset, amount: f64) -> Option { let current = self.develop_of(id)?; let photo = self.catalog.photo(id)?; // The original is read only below 100 %: the panel asks for every visible row at 100 % on // every frame, and then neither the import state nor a copy of the photo's settings is built. - let look; - let original: &DevelopSettings = match &photo.import_look { - Some(_) if (amount - 1.0).abs() >= 1e-9 => { - look = photo.import_defaults(); - &look - } - _ => ¤t, - }; - Some(preset.apply_on(¤t, original, amount)) + let original = photo.import_look.as_ref().filter(|_| (amount - 1.0).abs() >= 1e-9).map(|_| photo.import_defaults()); + // the photo's source is read only for a preset that needs it (one white balance number): + // the panel asks for every visible row on every frame + let info = if crate::cmd::wb_partial_names_one_field(&preset.settings) { self.source_info(id) } else { Default::default() }; + Some(apply_preset_to_photo(preset, ¤t, original.as_ref(), amount, &info)) } /// Add imported presets. Identical presets (same name, group and settings) already present are @@ -634,6 +631,41 @@ impl Session { } } +/// Apply `preset` to a photo's settings `current` at `amount` (1.0 = 100 %), composing on +/// `original` (the photo's import state; `None`: `current` itself, see [`Preset::apply_on`]): the +/// one path every caller that puts a preset on a photo takes (the `preset.apply` command, +/// thumbnails and hover previews through [`Session::preset_applied`], importing with a preset, +/// import defaults), so all of them show and store the same result. +/// +/// `info` is the photo's source: a hand-written preset may name one white balance number only, and +/// then it means what a one-field partial means (`prepare_photo_for_wb_partial`, shared with +/// `develop.merge`, issue #2910): the photo (and its original) are brought onto the preset's scale +/// with the photo's own as-shot white first, and the result is put back on the scale the photo is +/// edited on. Without an import state a zero (or negative) `amount` returns `current` exactly as it +/// was, before any preparation, so a preview at nothing never turns As Shot into Custom; with one, +/// 0 % is the import state's value for each setting the preset names ([`Preset::apply_on`]). A NaN +/// `amount` changes nothing. +pub fn apply_preset_to_photo( + preset: &Preset, + current: &DevelopSettings, + original: Option<&DevelopSettings>, + amount: f64, + info: &lightcraft_pipeline::SourceInfo, +) -> DevelopSettings { + if amount.is_nan() || (amount <= 0.0 && original.is_none()) { + return current.clone(); + } + let prepared = crate::cmd::prepare_photo_for_wb_partial(current, &preset.settings, info); + let on_kelvin_scale = prepared.is_some() && info.raw && !info.relative_wb; + let base = prepared.as_ref().unwrap_or(current); + let prepared_original = original.map(|o| crate::cmd::prepare_photo_for_wb_partial(o, &preset.settings, info).unwrap_or_else(|| o.clone())); + let mut next = preset.apply_on(base, prepared_original.as_ref().unwrap_or(base), amount); + if on_kelvin_scale { + lightcraft_pipeline::local::normalize_wb(&mut next, info); + } + next +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/engine/src/rename.rs b/crates/engine/src/rename.rs index d1677498ea..4cb0dacdc2 100644 --- a/crates/engine/src/rename.rs +++ b/crates/engine/src/rename.rs @@ -26,7 +26,7 @@ use std::collections::{HashMap, HashSet}; use std::path::{Path, PathBuf}; use lightcraft_catalog::dates::MONTHS; -use lightcraft_catalog::{Op, Photo, PhotoId, Source}; +use lightcraft_catalog::{CatalogError, Op, Photo, PhotoId, Source}; use serde::Serialize; use crate::sidecar::SidecarNaming; @@ -41,10 +41,10 @@ mod tokens; #[cfg(test)] use fs::{LIST_FOLDER_AT, ListedSources, folded_path, same_contents}; pub(crate) use fs::{MoveFs, RealFs}; -pub(crate) use moves::move_all; #[cfg(test)] pub(crate) use moves::move_file_with; pub use moves::{MoveError, move_file}; +pub(crate) use moves::{move_all, rest_after_move_back}; pub use plan::{plan_rename_photos, rename_photos}; #[cfg(test)] pub(crate) use sidecar::PacketVersion; diff --git a/crates/engine/src/rename/moves.rs b/crates/engine/src/rename/moves.rs index 88ffc75fb1..2567ba352c 100644 --- a/crates/engine/src/rename/moves.rs +++ b/crates/engine/src/rename/moves.rs @@ -1,6 +1,6 @@ use super::fs::{ListedSources, MoveFs, RealFs, folded_path, is_respelling, move_one, sidecars}; use super::sidecar::{RetainedPacket, SidecarMove, advance_packets, note_companions, packet_aliases}; -use super::{HashMap, HashSet, Op, Path, PathBuf, SidecarNaming, Source}; +use super::{HashMap, HashSet, Op, Path, PathBuf, PhotoId, SidecarNaming, Source}; /// Why [`move_file`] failed, and what it left behind. #[derive(Clone, Debug, PartialEq)] @@ -151,6 +151,41 @@ pub(crate) fn move_all(fs: &dyn MoveFs, moves: &[(String, String)]) -> std::resu Ok(()) } +/// `rest`, what is left of a rollback that failed part-way, once the files were moved back (`moved_back`, the result of +/// `move_all` on the moves back): the `SetFile`s of a photo whose file did go back become `Relink`s, the same change to the +/// catalog that moves no file; those of a photo whose file stayed where it went keep moving it. A photo is judged by the +/// path its last `SetFile` points to, as `Session::file_moves` plans its move. +pub(crate) fn rest_after_move_back(rest: Op, moved_back: &std::result::Result<(), BatchMoveError>) -> Op { + fn targets<'a>(op: &'a Op, out: &mut HashMap) { + match op { + Op::Batch { ops } => ops.iter().for_each(|op| targets(op, out)), + Op::SetFile { id, source: Source::File { path }, .. } => { + out.insert(*id, path); + } + _ => {} + } + } + fn rewrite(op: Op, back: &HashSet) -> Op { + match op { + Op::Batch { ops } => Op::Batch { ops: ops.into_iter().map(|op| rewrite(op, back)).collect() }, + Op::SetFile { id, file_name, source } if back.contains(&id) => Op::Relink { id, file_name, source, format: None }, + op => op, + } + } + let mut to = HashMap::new(); + targets(&rest, &mut to); + // (on a failed move back, `stuck` holds the moves back that stayed done: those files are at their old path) + let back: HashSet = to + .into_iter() + .filter(|(_, path)| match moved_back { + Ok(()) => true, + Err(e) => e.stuck.iter().any(|m| Path::new(&m.1) == Path::new(path)), + }) + .map(|(id, _)| id) + .collect(); + rewrite(rest, &back) +} + /// Final `SetFile` per photo (nested batches included), filtered by destination only afterward. pub(super) fn set_file_ops_to(op: &Op, to: &HashSet<&str>, out: &mut Vec) { let mut pending = vec![op]; diff --git a/crates/engine/src/rename/plan.rs b/crates/engine/src/rename/plan.rs index 924fc9a95e..69505dcdce 100644 --- a/crates/engine/src/rename/plan.rs +++ b/crates/engine/src/rename/plan.rs @@ -1,8 +1,8 @@ use super::fs::{MoveFs, RealFs, folded_path}; -use super::moves::{BatchMoveError, move_all, set_file_ops_to}; +use super::moves::{BatchMoveError, move_all, rest_after_move_back, set_file_ops_to}; use super::sidecar::{PacketVersion, retry_sidecars, retry_sidecars_for_paths}; use super::tokens::{expand, split_ext}; -use super::{EngineError, HashMap, HashSet, Op, Path, PathBuf, Photo, PhotoId, RenamePlan, Result, Session, Source}; +use super::{CatalogError, EngineError, HashMap, HashSet, Op, Path, PathBuf, Photo, PhotoId, RenamePlan, Result, Session, Source}; /// The photos among `ids` a rename handles, in order: photos sharing one file (virtual copies) /// rename once. No file-system calls. @@ -220,7 +220,26 @@ impl Session { && let Err(err) = self.commit(&label(n), op) { let back: Vec<(String, String)> = moves.iter().rev().map(|(a, b)| (b.clone(), a.clone())).collect(); - if let Err(e) = move_all(fs, &back) { + let moved_back = move_all(fs, &back); + if matches!(err, EngineError::Catalog(CatalogError::PartlyApplied { .. })) + && let Some(rest) = self.undo.last().map(|step| step.op.clone()) + { + // (what is left of the rollback must follow the files as far as they went back, not move them again) + let rest = rest_after_move_back(rest, &moved_back); + if let Some(step) = self.undo.last_mut() { + step.op = rest; + } + } + if let Err(e) = moved_back { + // sidecars left apart from their photo are repaired later: with the partial step (undo retries them) or, + // when the catalog changed nothing, with the next rename + if matches!(err, EngineError::Catalog(CatalogError::PartlyApplied { .. })) + && let Some(step) = self.undo.last_mut() + { + step.retry_sidecars.extend(e.pending_sidecars); + } else { + self.pending_sidecar_repairs.extend(e.pending_sidecars); + } return Err(EngineError::Other(format!("{err}; the renamed files could not all be moved back: {}", e.message))); } return Err(err); diff --git a/crates/engine/src/rename/tests.rs b/crates/engine/src/rename/tests.rs index e0326eb548..f5243a04c9 100644 --- a/crates/engine/src/rename/tests.rs +++ b/crates/engine/src/rename/tests.rs @@ -50,6 +50,10 @@ pub(crate) struct FakeFs { pub ci: bool, pub files: RefCell)>>, pub fail: RefCell>, + /// Renames made so far, and the numbers (from 0) of the ones that fail: a failure at a given moment, which a + /// source path alone cannot name (a file moved back is renamed from the path it was first moved from). + pub renames: std::cell::Cell, + pub fail_renames: RefCell>, } impl FakeFs { @@ -58,6 +62,8 @@ impl FakeFs { ci, files: RefCell::new(files.iter().map(|(p, c)| (p.to_string(), c.as_bytes().to_vec())).collect()), fail: RefCell::new(Vec::new()), + renames: std::cell::Cell::new(0), + fail_renames: RefCell::new(Vec::new()), } } /// The model volume spells paths with `/`; the code under test joins them with the host's separator. @@ -94,7 +100,9 @@ impl MoveFs for FakeFs { self.idx(a).is_some() && self.idx(a) == self.idx(b) } fn rename_no_replace(&self, a: &Path, b: &Path) -> std::io::Result<()> { - if self.fail.borrow().iter().any(|f| Self::norm(a).contains(&f.replace('\\', "/"))) { + let nth = self.renames.get(); + self.renames.set(nth + 1); + if self.fail_renames.borrow().contains(&nth) || self.fail.borrow().iter().any(|f| Self::norm(a).contains(&f.replace('\\', "/"))) { return Err(std::io::Error::other("injected failure")); } if self.exists(b) { diff --git a/crates/engine/src/segment.rs b/crates/engine/src/segment.rs index 9c479cb176..3d1ff691ad 100644 --- a/crates/engine/src/segment.rs +++ b/crates/engine/src/segment.rs @@ -120,12 +120,57 @@ pub struct DownloadStatus { pub finished: bool, } +/// Where SAM 3 runs (Settings ▸ Performance ▸ AI masks; `segment.settings {runOn}`, kept in +/// [`Segmenter::settings_file`]). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum RunOn { + /// The GPU when there is one: Metal on macOS, elsewhere the image encoder through wgpu unless + /// the GPU is switched off ("Use the GPU for rendering", `LIGHTCRAFT_GPU=0`, …). + #[default] + Auto, + /// The CPU for all of it, on every platform (on macOS candle's CPU device instead of Metal). + Cpu, +} + +impl RunOn { + pub fn parse(name: &str) -> Option { + match name { + "auto" => Some(RunOn::Auto), + "cpu" => Some(RunOn::Cpu), + _ => None, + } + } + + pub fn name(self) -> &'static str { + match self { + RunOn::Auto => "auto", + RunOn::Cpu => "cpu", + } + } +} + +/// Why the model runs on the CPU when [`RunOn::Cpu`] is chosen (`segment.model.status` → +/// `backend.fallback`). +pub const CPU_CHOSEN: &str = "the CPU is chosen in Settings (AI masks)"; + +/// The settings file's contents (`sam3-settings.json`). +#[derive(Default, serde::Serialize, serde::Deserialize)] +#[serde(default, rename_all = "camelCase")] +struct Settings { + /// `auto` or `cpu` (`None` or anything else: `auto`). + run_on: Option, +} + /// The model (on its worker thread), the download, and AI mask requests in flight. pub struct Segmenter { /// Where the `facebook/sam3` files live (set by the app; `None`: no AI masks). pub dir: Option, /// The user's list of download mirrors (one base URL per line), if any. pub mirrors_file: Option, + /// Where [`Segmenter::run_on`] is kept (`/models/sam3-settings.json` in the app; `None`: + /// only for this session). + pub settings_file: Option, + run_on: RunOn, /// Run requests in the background and apply them in [`Session::segment_poll`] (the /// desktop app); otherwise commands wait for their result (CLI, MCP, tests). pub background: bool, @@ -146,6 +191,8 @@ impl Default for Segmenter { Segmenter { dir: None, mirrors_file: None, + settings_file: None, + run_on: RunOn::Auto, background: false, pending: None, messages: Vec::new(), @@ -163,6 +210,33 @@ impl Segmenter { /// Whether this build can compute AI masks at all. pub const AVAILABLE: bool = cfg!(feature = "sam"); + /// Where SAM 3 runs: the user's choice. + pub fn run_on(&self) -> RunOn { + self.run_on + } + + /// Read the choice of where SAM 3 runs from [`Segmenter::settings_file`] (a missing or damaged + /// file is [`RunOn::Auto`]). + pub fn load_settings(&mut self) { + let read = self.settings_file.as_deref().and_then(|f| crate::denoise::read_capped(f, 4096)); + let st: Settings = read.and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default(); + self.run_on = st.run_on.as_deref().and_then(RunOn::parse).unwrap_or_default(); + } + + /// Choose where SAM 3 runs, and keep the choice in [`Segmenter::settings_file`]. A loaded model + /// moves at its next request (it loads again). + pub fn set_run_on(&mut self, run_on: RunOn) -> Result<(), String> { + if let Some(f) = &self.settings_file { + if let Some(parent) = f.parent() { + std::fs::create_dir_all(parent).map_err(|e| format!("could not create {}: {e}", parent.display()))?; + } + let st = Settings { run_on: Some(run_on.name().to_string()) }; + crate::denoise::write_atomic(f, &serde_json::to_vec_pretty(&st).map_err(|e| e.to_string())?)?; + } + self.run_on = run_on; + Ok(()) + } + pub fn remote_endpoint(&self) -> Option { #[cfg(feature = "sam")] return lightcraft_segment::remote::configured(); @@ -195,6 +269,28 @@ impl Segmenter { false } + /// Where the model runs and how long the last photo took (`segment.model.status` → `backend`): + /// `{device, runtime, heads, fallback, encodeMs, analyzeMs}` (see `worker::Backend`; `device` + /// is `null` until the model first loads, and `fallback` then says whether the GPU is switched + /// off), or `null` in a build without AI masks. + pub fn backend(&self) -> serde_json::Value { + #[cfg(feature = "sam")] + { + let mut b = self.worker.backend(); + if b.device.is_none() { + b.fallback = match self.run_on { + RunOn::Cpu => Some(CPU_CHOSEN.into()), + // macOS: Metal, unless the environment switches the GPU off (the preference is wgpu's) + RunOn::Auto if cfg!(target_os = "macos") => lightcraft_gpu::env_off_reason().map(Into::into), + RunOn::Auto => lightcraft_gpu::switched_off(), + }; + } + serde_json::to_value(b).unwrap_or_default() + } + #[cfg(not(feature = "sam"))] + serde_json::Value::Null + } + /// Whether a zoomed-in detail pass is queued or running. pub fn detail_busy(&self) -> bool { #[cfg(feature = "sam")] @@ -452,7 +548,8 @@ impl Session { job } }; - Ok(worker::Job { dir, key: if region.is_some() { 0 } else { key }, render: Some(render), missing, kind, tag, reply }) + let cpu = self.segmenter.run_on == RunOn::Cpu; + Ok(worker::Job { dir, cpu, key: if region.is_some() { 0 } else { key }, render: Some(render), missing, kind, tag, reply }) } /// Send a request and wait for its result (CLI, MCP, tests; or when not in background mode). diff --git a/crates/engine/src/segment/worker.rs b/crates/engine/src/segment/worker.rs index 8b90382b8e..81d5773ceb 100644 --- a/crates/engine/src/segment/worker.rs +++ b/crates/engine/src/segment/worker.rs @@ -8,24 +8,33 @@ //! counters are decremented by drop guards, so they can't stay stuck. The model is unloaded //! after [`IDLE_UNLOAD`] without requests (it holds several GB). //! -//! Where the model can run on the GPU (Metal on macOS), a job that fails there (a panic or an -//! error from candle, e.g. a kernel the GPU's compiler can't build, issue #1974) frees the -//! model and runs once more on the CPU. When that works, the model stays on the CPU for the rest -//! of the session and the job's outcome says so; when it fails too, the GPU wasn't the cause and -//! the next job uses it again. `LIGHTCRAFT_GPU=0` or `LIGHTCRAFT_GPU_BACKEND=off` keep the model on -//! the CPU from the start. +//! Where the model runs ([`Placement`]): on macOS candle runs all of it on the GPU through Metal. +//! Elsewhere candle runs on the CPU, and the backbone (most of the work) on the GPU with +//! `lightcraft-gpu`'s wgpu kernels, unless the GPU is switched off (`LIGHTCRAFT_GPU=0`, +//! `LIGHTCRAFT_GPU_BACKEND=off`, or Settings ▸ Performance ▸ Use the GPU for rendering, as for AI +//! Denoise and faces); a GPU that can't be used or fails on a photo leaves the backbone to the CPU. +//! Settings ▸ Performance ▸ AI masks ▸ CPU ([`Job::cpu`]) puts all of it on the CPU, on every +//! platform, and so do `LIGHTCRAFT_GPU=0` and `LIGHTCRAFT_GPU_BACKEND=off` (macOS included, as +//! for AI Denoise and the face models). +//! +//! Where candle runs the model on the GPU (Metal on macOS), a job that fails there (a panic or an +//! error from candle, e.g. a kernel the GPU's compiler can't build, issue #1974) frees the model +//! and runs once more on the CPU. When that works, the model stays on the CPU for the rest of the +//! session and the job's outcome says so; when it fails too, the GPU wasn't the cause and the next +//! job uses it again. (The wgpu backbone elsewhere falls back to candle by itself, part by part.) +//! [`Backend`] tells the session where it ran and how long the last photo took. use std::collections::VecDeque; use std::panic::AssertUnwindSafe; -use std::path::PathBuf; -use std::sync::Arc; +use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::mpsc::{self, RecvTimeoutError}; +use std::sync::{Arc, Mutex, PoisonError}; use std::time::Duration; use lightcraft_develop::SegMask; use lightcraft_segment::{ - Encoded, Sam3, + BackboneAccel, Device, Encoded, Sam3, WeightReader, remote::{self, Operation, Request, text_logits}, }; @@ -68,6 +77,8 @@ pub enum Kind { pub struct Job { /// The model folder. pub dir: PathBuf, + /// The user chose the CPU for SAM 3 (Settings ▸ Performance ▸ AI masks). + pub cpu: bool, /// Which photo and look the request is about (the encode cache's key). pub key: u64, /// Renders the model input when the cache doesn't hold `key` (always for a detail pass). @@ -93,29 +104,6 @@ pub struct Outcome { pub const GPU_FAILED: &str = "The GPU couldn't run the AI mask model, so it runs on the CPU until LightCraft restarts (slower). Details are in the log."; -/// Where the model is loaded. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Placement { - /// On the GPU when there is one (Metal on macOS); a job that fails there is retried on the CPU. - Gpu, - /// On the CPU: this build has no GPU path, the environment switches the GPU off, or the model - /// failed on it. - Cpu, -} - -impl Placement { - fn initial() -> Self { - if !lightcraft_segment::GPU_BUILD { - return Placement::Cpu; - } - if let Some(why) = lightcraft_gpu::env_off_reason() { - log::info!("SAM 3 runs on the CPU ({why})"); - return Placement::Cpu; - } - Placement::Gpu - } -} - /// Why a job failed. #[derive(Debug)] enum Failure { @@ -162,6 +150,142 @@ pub struct Shared { pub loaded: AtomicBool, /// Loading the model or encoding a photo right now (the slow parts). pub encoding: AtomicBool, + /// Where the model runs and how long the last photo took. + pub backend: Mutex, +} + +/// Where the model runs, and how long the last photo took (`segment.model.status` → `backend`, +/// Settings ▸ Performance ▸ AI masks). +#[derive(Clone, Debug, Default, PartialEq, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Backend { + /// What the backbone (the 32-layer ViT, most of the work) runs on: a GPU's name ("NVIDIA + /// GeForce RTX 5070 (Vulkan)"), "Metal GPU" or "CPU". `None` until the model first loads. + pub device: Option, + /// What runs the backbone: "wgpu" (LightCraft's GPU kernels) or "candle". + pub runtime: Option, + /// What runs the rest (the necks and the click and text heads): "CPU" or "Metal GPU", with the parts the GPU + /// accelerator runs ("CPU; the necks on the GPU"). + pub heads: Option, + /// Why the backbone runs on the CPU where it could use the GPU: the GPU is switched off, there + /// is no usable one, or it failed on a photo. + pub fallback: Option, + /// The last photo's backbone run, in milliseconds. + pub encode_ms: Option, + /// The last photo's whole analysis before the first click (backbone and click features), in + /// milliseconds. + pub analyze_ms: Option, +} + +/// Where the model runs on this machine. +#[derive(Clone, Debug, PartialEq)] +enum Placement { + /// All of it in candle on its best device (Metal on macOS). + Best, + /// The backbone on the GPU (wgpu), the rest in candle on the CPU. + GpuBackbone, + /// All of it in candle on the CPU: the CPU is chosen, or the GPU is switched off (why). + Cpu(String), +} + +/// Where the model runs, for candle's best device being the CPU (`best_is_cpu`), the GPU switched +/// off (`switched_off`: why) or not, and the CPU chosen in Settings (`cpu`) or not. The choice wins +/// on every platform; the GPU switches only govern the wgpu backbone (macOS keeps Metal). +fn placement(best_is_cpu: bool, switched_off: Option, cpu: bool) -> Placement { + match (cpu, best_is_cpu, switched_off) { + (true, _, _) => Placement::Cpu(super::CPU_CHOSEN.into()), + (false, false, _) => Placement::Best, + (false, true, None) => Placement::GpuBackbone, + (false, true, Some(why)) => Placement::Cpu(why), + } +} + +/// Where the model is to run now: [`placement`], unless candle's GPU failed on it this session (`failed`: why; +/// the CPU until LightCraft restarts) or the environment switches the GPU off (`LIGHTCRAFT_GPU=0`, +/// `LIGHTCRAFT_GPU_BACKEND=off`), which keeps it off Metal too. +fn wanted(best_is_cpu: bool, cpu: bool, failed: Option<&str>) -> Placement { + if cpu { + return placement(best_is_cpu, None, true); + } + if let Some(why) = failed { + return Placement::Cpu(why.into()); + } + if let Some(why) = lightcraft_gpu::env_off_reason() { + return Placement::Cpu(why.into()); + } + placement(best_is_cpu, lightcraft_gpu::switched_off(), false) +} + +/// Whether a model loaded for `loaded` runs somewhere else than `wanted` (it must load again), candle's best device +/// being the CPU or not (`best_is_cpu`). Two reasons for the CPU are the same place, and so is candle's best device +/// when that is the CPU. +fn moves(loaded: &Placement, wanted: &Placement, best_is_cpu: bool) -> bool { + #[derive(PartialEq)] + enum Runs { + Cpu, + Metal, + Wgpu, + } + let runs = |p: &Placement| match p { + Placement::Best if best_is_cpu => Runs::Cpu, + Placement::Best => Runs::Metal, + Placement::GpuBackbone => Runs::Wgpu, + Placement::Cpu(_) => Runs::Cpu, + }; + runs(loaded) != runs(wanted) +} + +/// Builds the GPU backbone from the checkpoint (`lightcraft_gpu::sam3::backbone`; tests use fakes). +type MakeAccel = fn(&WeightReader) -> Result, String>; + +/// Load the model in `dir` as `placement` says, on `best` (candle's best device). +fn load(dir: &Path, best: Device, placement: &Placement, make: MakeAccel) -> lightcraft_segment::Result { + match placement { + Placement::Best => Sam3::load_on(dir, best), + Placement::Cpu(_) => Sam3::load_on(dir, Device::Cpu), + Placement::GpuBackbone => Sam3::load_accelerated(dir, Device::Cpu, make), + } +} + +/// Note where the model `m`, just loaded for `placement`, runs. +fn note_loaded(shared: &Shared, m: &Sam3, placement: &Placement) { + let mut b = shared.backend.lock().unwrap_or_else(PoisonError::into_inner); + *b = Backend { + device: Some(m.backbone_device()), + runtime: Some(if m.accelerated() { "wgpu" } else { "candle" }.into()), + heads: Some(m.heads_device()), + fallback: match placement { + Placement::Cpu(why) => Some(why.clone()), + _ => m.backbone_fallback(), + }, + encode_ms: None, + analyze_ms: None, + }; +} + +/// Note where the backbone ran a photo (it may have moved to the CPU on the way) and, when it +/// succeeded, how long it took (`encode`). +fn note_run(shared: &Shared, m: &Sam3, encode: Option) { + let mut b = shared.backend.lock().unwrap_or_else(PoisonError::into_inner); + b.device = Some(m.backbone_device()); + b.runtime = Some(if m.accelerated() { "wgpu" } else { "candle" }.into()); + b.heads = Some(m.heads_device()); + if let Some(why) = m.backbone_fallback() { + b.fallback = Some(why); + } + if let Some(d) = encode { + b.encode_ms = Some(millis(d)); + } +} + +/// Note where the backbone ran a detail pass (a zoomed-in region): not how long it took, since the last photo's +/// times are its whole analysis and the backbone run in it. +fn note_detail(shared: &Shared, m: &Sam3) { + note_run(shared, m, None); +} + +fn millis(d: Duration) -> u64 { + u64::try_from(d.as_millis()).unwrap_or(u64::MAX) } /// Decrements a counter when dropped (also when unwinding). @@ -224,6 +348,11 @@ impl Worker { !self.dead() && self.shared.loaded.load(Ordering::SeqCst) } + /// Where the model runs (ran, once unloaded) and how long the last photo took. + pub fn backend(&self) -> Backend { + self.shared.backend.lock().unwrap_or_else(PoisonError::into_inner).clone() + } + /// Queue `job`; returns at once. pub fn submit(&mut self, job: Job) -> Result<(), String> { if self.dead() { @@ -243,7 +372,7 @@ impl Worker { // (re)start the thread let (tx, rx) = mpsc::channel(); let shared = self.shared.clone(); - match std::thread::Builder::new().name("sam3".into()).spawn(move || run(&rx, &shared, IDLE_UNLOAD, Placement::initial())) { + match std::thread::Builder::new().name("sam3".into()).spawn(move || run(&rx, &shared, IDLE_UNLOAD, lightcraft_segment::GPU_BUILD)) { Ok(t) => { self.thread = Some(t); self.tx = Some(tx.clone()); @@ -261,6 +390,8 @@ impl Worker { #[derive(Default)] struct State { model: Option<(PathBuf, Sam3)>, + /// Where the model was loaded to run, and whether candle's best device was the CPU then. + placement: Option<(Placement, bool)>, cache: Option<(u64, Encoded)>, remote: Option, } @@ -275,8 +406,12 @@ fn supersedes(later: &Job, job: &Job) -> bool { } } -fn run(rx: &mpsc::Receiver, shared: &Shared, idle: Duration, mut placement: Placement) { +/// The worker's loop. `metal`: candle may run the model on a GPU here (macOS), so a job that fails is retried on +/// the CPU. +fn run(rx: &mpsc::Receiver, shared: &Shared, idle: Duration, metal: bool) { let mut state = State::default(); + // why the model runs on the CPU for the rest of the session: it failed on the GPU and works on the CPU + let mut gpu_failed: Option = None; let mut queue: VecDeque = VecDeque::new(); loop { if queue.is_empty() { @@ -306,24 +441,26 @@ fn run(rx: &mpsc::Receiver, shared: &Shared, idle: Duration, mut placement: let _ = job.reply.send(Outcome { tag: job.tag, result: Ok(None), superseded: true, notice: None }); continue; } - // what a retry on the CPU needs (running the job takes them) - let retry = (placement == Placement::Gpu && remote::configured().is_none()).then(|| (job.kind.clone(), job.render.clone())); - let mut result = attempt(&mut state, shared, &mut job, placement); + // on candle's GPU: what a retry on the CPU needs (running the job takes them) + let on_gpu = metal && gpu_failed.is_none() && !job.cpu && lightcraft_gpu::env_off_reason().is_none() && remote::configured().is_none(); + let retry = on_gpu.then(|| (job.kind.clone(), job.render.clone())); + let mut result = attempt(&mut state, shared, &mut job, gpu_failed.as_deref()); let mut notice = None; - let gpu_failed = match &result { + let failed_why = match &result { Err(Failure::Model(why)) => Some(why.clone()), _ => None, }; - if let (Some(why), Some((kind, render))) = (gpu_failed, retry) { + if let (Some(why), Some((kind, render))) = (failed_why, retry) { // the GPU may be the cause (e.g. a kernel its compiler can't build, issue #1974): free // the model there and try once on the CPU log::warn!("SAM 3 failed on the GPU ({why}); trying the CPU"); state = State::default(); (job.kind, job.render) = (kind, render); - match attempt(&mut state, shared, &mut job, Placement::Cpu) { + let reason = format!("the GPU couldn't run it ({why}); the CPU until LightCraft restarts"); + match attempt(&mut state, shared, &mut job, Some(&reason)) { Ok(r) => { log::warn!("SAM 3 runs on the CPU from now on: it failed on the GPU and works on the CPU"); - placement = Placement::Cpu; + gpu_failed = Some(reason); notice = Some(GPU_FAILED.to_string()); result = Ok(r); } @@ -344,10 +481,10 @@ fn run(rx: &mpsc::Receiver, shared: &Shared, idle: Duration, mut placement: } } -/// Run `job` with the model on `placement`. A panic is a [`Failure::Model`] and drops what the -/// model kept. -fn attempt(state: &mut State, shared: &Shared, job: &mut Job, placement: Placement) -> Result, Failure> { - match std::panic::catch_unwind(AssertUnwindSafe(|| run_job(state, shared, job, placement))) { +/// Run `job`, on the CPU when `failed` says the GPU failed this session. A panic is a [`Failure::Model`] and drops +/// what the model kept. +fn attempt(state: &mut State, shared: &Shared, job: &mut Job, failed: Option<&str>) -> Result, Failure> { + match std::panic::catch_unwind(AssertUnwindSafe(|| run_job(state, shared, job, failed))) { Ok(r) => r, Err(p) => { let why = p.downcast_ref::<&str>().map(|s| s.to_string()).or_else(|| p.downcast_ref::().cloned()).unwrap_or_default(); @@ -359,19 +496,38 @@ fn attempt(state: &mut State, shared: &Shared, job: &mut Job, placement: Placeme } } -/// The model for `dir`, loading it on `placement` when needed. -fn model<'a>(state: &'a mut State, shared: &Shared, dir: &std::path::Path, placement: Placement) -> Result<&'a mut Sam3, Failure> { - if state.model.as_ref().is_none_or(|(d, _)| d != dir) { +/// The model for `dir`, loading it when needed (and again when the GPU was switched on or off, or +/// the CPU chosen or not: `cpu`; `failed`: the GPU failed this session, see [`wanted`]). +fn model<'a>(state: &'a mut State, shared: &Shared, dir: &Path, cpu: bool, failed: Option<&str>) -> Result<&'a mut Sam3, Failure> { + let now = state.placement.as_ref().map(|(_, best_is_cpu)| wanted(*best_is_cpu, cpu, failed)); + let stale = state.placement.as_ref().zip(now.as_ref()).is_some_and(|((p, best_is_cpu), now)| moves(p, now, *best_is_cpu)); + if let (false, Some((p, _)), Some(now)) = (stale, state.placement.as_mut(), now) { + // the same device for another reason (the choice, a GPU switch): the model stays, the reason it shows changes + if *p != now { + shared.backend.lock().unwrap_or_else(PoisonError::into_inner).fallback = match &now { + Placement::Cpu(why) => Some(why.clone()), + _ => None, + }; + *p = now; + } + } + if stale || state.model.as_ref().is_none_or(|(d, _)| d != dir) { state.model = None; + state.placement = None; state.cache = None; let _busy = Flag::raise(&shared.encoding); let t = web_time::Instant::now(); - let m = match placement { - Placement::Gpu => Sam3::load(dir)?, - Placement::Cpu => Sam3::load_cpu(dir)?, - }; - log::info!("SAM 3 loaded in {:?} ({})", t.elapsed(), if m.device().is_cpu() { "CPU" } else { "GPU" }); + // with the CPU chosen (or forced) candle's best device isn't asked for (on macOS that sets up Metal): + // it counts as Metal on macOS and the CPU elsewhere when the choice changes back + let skip = cpu || failed.is_some() || lightcraft_gpu::env_off_reason().is_some(); + let best = if skip { Device::Cpu } else { lightcraft_segment::best_device() }; + let best_is_cpu = if skip { !cfg!(target_os = "macos") } else { best.is_cpu() }; + let placement = wanted(best_is_cpu, cpu, failed); + let m = load(dir, best, &placement, lightcraft_gpu::sam3::backbone)?; + log::info!("SAM 3 loaded in {:?}: the backbone on the {}, the rest on the {}", t.elapsed(), m.backbone_device(), m.heads_device()); + note_loaded(shared, &m, &placement); state.model = Some((dir.to_path_buf(), m)); + state.placement = Some((placement, best_is_cpu)); shared.loaded.store(true, Ordering::SeqCst); } state.model.as_mut().map(|(_, m)| m).ok_or_else(|| "the model did not load".into()) @@ -396,17 +552,33 @@ fn render(job: &mut Job) -> Result { } /// The model and the encoded photo `job.key` (rendering and encoding it when needed). -fn encoded<'a>(state: &'a mut State, shared: &Shared, job: &mut Job, placement: Placement) -> Result<(&'a mut Sam3, &'a mut Encoded), Failure> { - model(state, shared, &job.dir, placement)?; +fn encoded<'a>(state: &'a mut State, shared: &Shared, job: &mut Job, failed: Option<&str>) -> Result<(&'a mut Sam3, &'a mut Encoded), Failure> { + model(state, shared, &job.dir, job.cpu, failed)?; if state.cache.as_ref().is_none_or(|(k, _)| *k != job.key) { state.cache = None; let input = render(job)?; let _busy = Flag::raise(&shared.encoding); let m = state.model.as_mut().map(|(_, m)| m).ok_or("the model did not load")?; let t = web_time::Instant::now(); - let mut enc = m.encode(&input.rgb, input.w, input.h)?; + let enc = m.encode(&input.rgb, input.w, input.h); + let encode = t.elapsed(); + note_run(shared, m, None); + let mut enc = enc?; m.prepare_clicks(&mut enc)?; - log::info!("SAM 3 encoded {}×{} in {:?}", input.w, input.h, t.elapsed()); + let analyze = t.elapsed(); + // both times together, once the whole analysis worked: never one photo's encoder with another's total + { + let mut b = shared.backend.lock().unwrap_or_else(PoisonError::into_inner); + (b.encode_ms, b.analyze_ms) = (Some(millis(encode)), Some(millis(analyze))); + } + log::info!( + "SAM 3 analyzed {}×{} in {analyze:?}: backbone {encode:?} on the {}, click features {:?} on the {}", + input.w, + input.h, + m.backbone_device(), + analyze.saturating_sub(encode), + m.heads_device() + ); state.cache = Some((job.key, enc)); } let State { model, cache, .. } = state; @@ -464,7 +636,7 @@ fn remote_job(state: &mut State, shared: &Shared, job: &mut Job, endpoint: &str) })) } -fn run_job(state: &mut State, shared: &Shared, job: &mut Job, placement: Placement) -> Result, Failure> { +fn run_job(state: &mut State, shared: &Shared, job: &mut Job, failed: Option<&str>) -> Result, Failure> { if let Some(endpoint) = remote::configured() { let result = remote_job(state, shared, job, &endpoint); if result.is_err() { @@ -475,38 +647,46 @@ fn run_job(state: &mut State, shared: &Shared, job: &mut Job, placement: Placeme let side = lightcraft_segment::MASK_SIDE; match std::mem::replace(&mut job.kind, Kind::Prepare) { Kind::Prepare => { - encoded(state, shared, job, placement)?; + encoded(state, shared, job, failed)?; Ok(None) } Kind::Clicks(clicks) => { - let (m, enc) = encoded(state, shared, job, placement)?; + let (m, enc) = encoded(state, shared, job, failed)?; let p = m.segment_clicks(enc, &clicks)?; Ok(Some(SegMask::from_logits(side, &p.logits))) } Kind::Text(text) => { - let (m, enc) = encoded(state, shared, job, placement)?; - Ok(text_logits(m, enc, &text)?.map(|l| SegMask::from_logits(side, &l))) + let (m, enc) = encoded(state, shared, job, failed)?; + let logits = text_logits(m, enc, &text)?; + // the text heads may have moved to the CPU on the way (a failure on the GPU) + shared.backend.lock().unwrap_or_else(PoisonError::into_inner).heads = Some(m.heads_device()); + Ok(logits.map(|l| SegMask::from_logits(side, &l))) } Kind::Subject { focus } => { - let (m, enc) = encoded(state, shared, job, placement)?; + let (m, enc) = encoded(state, shared, job, failed)?; // (the reference score threshold, as Describe uses) - Ok(m.segment_subject(enc, focus, 0.5)?.map(|p| SegMask::from_logits(side, &p.logits))) + let subject = m.segment_subject(enc, focus, 0.5)?; + // the text heads may have moved to the CPU on the way (a failure on the GPU), as for Describe + shared.backend.lock().unwrap_or_else(PoisonError::into_inner).heads = Some(m.heads_device()); + Ok(subject.map(|p| SegMask::from_logits(side, &p.logits))) } #[cfg(test)] #[allow(clippy::panic)] Kind::Panic => panic!("a test panic"), #[cfg(test)] #[allow(clippy::panic)] - Kind::FailOnGpu { panic } => match placement { - Placement::Gpu if panic => panic!("a test panic on the GPU"), - Placement::Gpu => Err(Failure::Model("a test error on the GPU".into())), - Placement::Cpu => Ok(None), + Kind::FailOnGpu { panic } => match failed.is_some() || job.cpu { + false if panic => panic!("a test panic on the GPU"), + false => Err(Failure::Model("a test error on the GPU".into())), + true => Ok(None), }, Kind::Detail { prompt, region } => { let input = render(job)?; - let m = model(state, shared, &job.dir, placement)?; + let m = model(state, shared, &job.dir, job.cpu, failed)?; let t = web_time::Instant::now(); - let mut enc = m.encode(&input.rgb, input.w, input.h)?; + let enc = m.encode(&input.rgb, input.w, input.h); + note_detail(shared, m); + let mut enc = enc?; let (rw, rh) = (region[2] - region[0], region[3] - region[1]); if !(rw > 0.0 && rh > 0.0) { return Ok(None); @@ -539,7 +719,7 @@ mod tests { fn job(tag: Tag, reply: &mpsc::Sender) -> Job { // an empty folder: loading fails with an error (no model files) let dir = std::env::temp_dir().join(format!("lc-sam3-worker-none-{}", std::process::id())); - Job { dir, key: 1, render: None, missing: None, kind: Kind::Prepare, tag, reply: reply.clone() } + Job { dir, cpu: false, key: 1, render: None, missing: None, kind: Kind::Prepare, tag, reply: reply.clone() } } #[test] @@ -572,7 +752,7 @@ mod tests { jtx.send(job(Tag::Wait, &tx)).unwrap(); shared.pending.store(2, Ordering::SeqCst); drop(jtx); - run(&jrx, &shared, Duration::from_secs(60), Placement::Cpu); + run(&jrx, &shared, Duration::from_secs(60), false); let first = rx.recv().unwrap(); assert!(first.result.unwrap_err().contains("failed unexpectedly")); let second = rx.recv().unwrap(); @@ -581,72 +761,6 @@ mod tests { assert!(!shared.encoding.load(Ordering::SeqCst)); } - /// Run `kinds` in turn on a worker that starts on `placement`; their outcomes. - fn run_kinds(placement: Placement, kinds: Vec) -> Vec { - let (tx, rx) = mpsc::channel(); - let (jtx, jrx) = mpsc::channel(); - let shared = Shared::default(); - shared.pending.store(kinds.len(), Ordering::SeqCst); - for kind in kinds { - let mut j = job(Tag::Wait, &tx); - j.kind = kind; - jtx.send(j).unwrap(); - } - drop(jtx); - run(&jrx, &shared, Duration::from_secs(60), placement); - assert_eq!(shared.pending.load(Ordering::SeqCst), 0, "counters reset"); - assert!(!shared.encoding.load(Ordering::SeqCst)); - rx.try_iter().collect() - } - - #[test] - fn a_job_that_panics_on_the_gpu_runs_on_the_cpu_and_so_do_the_next_ones() { - // issue #1974: candle panics compiling a Metal kernel the GPU's compiler can't build - let out = run_kinds(Placement::Gpu, vec![Kind::FailOnGpu { panic: true }, Kind::FailOnGpu { panic: true }]); - assert_eq!(out.len(), 2); - assert!(matches!(out[0].result, Ok(None)), "retried on the CPU: {:?}", out[0].result.as_ref().err()); - assert_eq!(out[0].notice.as_deref(), Some(GPU_FAILED)); - assert!(matches!(out[1].result, Ok(None)), "the next job starts on the CPU"); - assert_eq!(out[1].notice, None, "said once"); - } - - #[test] - fn a_model_error_on_the_gpu_is_retried_on_the_cpu_too() { - let out = run_kinds(Placement::Gpu, vec![Kind::FailOnGpu { panic: false }]); - assert!(matches!(out[0].result, Ok(None))); - assert_eq!(out[0].notice.as_deref(), Some(GPU_FAILED)); - } - - #[test] - fn a_job_that_fails_on_the_cpu_too_keeps_the_gpu() { - let out = run_kinds(Placement::Gpu, vec![Kind::Panic, Kind::FailOnGpu { panic: true }]); - assert!(out[0].result.as_ref().unwrap_err().contains("failed unexpectedly")); - assert_eq!(out[0].notice, None); - // not the GPU's fault: the next job tries the GPU first again - assert!(matches!(out[1].result, Ok(None))); - assert_eq!(out[1].notice.as_deref(), Some(GPU_FAILED)); - } - - #[test] - fn a_worker_on_the_cpu_never_tries_the_gpu() { - // no GPU in this build, or LIGHTCRAFT_GPU=0 / LIGHTCRAFT_GPU_BACKEND=off - let out = run_kinds(Placement::Cpu, vec![Kind::FailOnGpu { panic: true }]); - assert!(matches!(out[0].result, Ok(None))); - assert_eq!(out[0].notice, None); - if !lightcraft_segment::GPU_BUILD { - assert_eq!(Placement::initial(), Placement::Cpu); - } - } - - #[test] - fn missing_model_files_are_not_retried_on_the_cpu() { - let out = run_kinds(Placement::Gpu, vec![Kind::Prepare]); - assert!(out[0].result.as_ref().unwrap_err().contains("not found")); - assert_eq!(out[0].notice, None); - let missing = lightcraft_segment::Error::Missing(PathBuf::from("models")); - assert!(matches!(Failure::from(missing), Failure::Other(_))); - } - #[test] fn a_newer_request_for_the_same_selection_supersedes_a_queued_one() { let (tx, rx) = mpsc::channel(); @@ -664,10 +778,298 @@ mod tests { drop(jtx); let shared = Shared::default(); shared.pending.store(3, Ordering::SeqCst); - run(&jrx, &shared, Duration::from_secs(60), Placement::Cpu); + run(&jrx, &shared, Duration::from_secs(60), false); let out: Vec = rx.try_iter().collect(); assert_eq!(out.len(), 3); assert!(out[0].superseded && out[1].superseded && !out[2].superseded); assert_eq!(shared.pending.load(Ordering::SeqCst), 0); } + + /// A model folder whose checkpoint holds no tensors: it loads with an accelerator, never in candle. + #[allow(clippy::unwrap_used)] + fn empty_model(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("lc-sam3-worker-{name}-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let mut st = 2u64.to_le_bytes().to_vec(); + st.extend_from_slice(b"{}"); + std::fs::write(dir.join(lightcraft_segment::WEIGHTS_FILE), st).unwrap(); + std::fs::write(dir.join("vocab.json"), "{}").unwrap(); + std::fs::write(dir.join("merges.txt"), "").unwrap(); + dir + } + + /// A GPU backbone that answers with zeros, or fails on every photo. + struct FakeGpu(bool); + + impl BackboneAccel for FakeGpu { + fn forward(&self, _: &[f32]) -> Result, String> { + if self.0 { Err("device lost".into()) } else { Ok(vec![0.0; 1024 * 72 * 72]) } + } + fn device(&self) -> String { + "Fake GPU (Vulkan)".into() + } + } + + fn fake_gpu(_: &WeightReader) -> Result, String> { + Ok(Box::new(FakeGpu(false))) + } + + fn failing_gpu(_: &WeightReader) -> Result, String> { + Ok(Box::new(FakeGpu(true))) + } + + fn no_gpu(_: &WeightReader) -> Result, String> { + Err("no GPU adapter".into()) + } + + #[allow(clippy::panic)] + fn never(_: &WeightReader) -> Result, String> { + panic!("the GPU backbone was built") + } + + #[allow(clippy::unwrap_used)] + fn backend(shared: &Shared) -> Backend { + shared.backend.lock().unwrap().clone() + } + + #[test] + fn the_backbone_goes_to_the_gpu_only_where_candle_has_none_and_the_gpu_is_on() { + // macOS: candle runs everything on Metal, as before (the GPU switches are wgpu's) + assert_eq!(placement(false, None, false), Placement::Best); + assert_eq!(placement(false, Some("disabled by LIGHTCRAFT_GPU=0".into()), false), Placement::Best); + // elsewhere: the backbone on the GPU unless it is switched off + assert_eq!(placement(true, None, false), Placement::GpuBackbone); + let off = "disabled by the GPU rendering preference (app.gpu)"; + assert_eq!(placement(true, Some(off.into()), false), Placement::Cpu(off.into())); + } + + #[test] + fn the_cpu_chosen_in_settings_wins_on_every_platform() { + let chosen = Placement::Cpu(super::super::CPU_CHOSEN.into()); + // macOS (Metal) and elsewhere, the GPU on or off + for best_is_cpu in [false, true] { + for off in [None, Some("disabled by LIGHTCRAFT_GPU=0".to_string())] { + assert_eq!(placement(best_is_cpu, off.clone(), true), chosen, "{best_is_cpu} {off:?}"); + } + } + assert_eq!(super::super::CPU_CHOSEN, "the CPU is chosen in Settings (AI masks)"); + } + + #[test] + fn switching_the_gpu_or_the_choice_reloads_only_a_model_it_moves() { + let cpu = |why: &str| Placement::Cpu(why.into()); + let chosen = || placement(true, None, true); + // the GPU switch: Metal stays; the wgpu backbone goes to the CPU and back + assert!(!moves(&Placement::Best, &placement(false, Some("off".into()), false), false)); + assert!(moves(&Placement::GpuBackbone, &placement(true, Some("off".into()), false), true)); + assert!(moves(&cpu("off"), &placement(true, None, false), true)); + // without a GPU backbone candle's best device is the CPU: the GPU switch moves nothing + assert!(!moves(&Placement::Best, &cpu("off"), true)); + assert!(!moves(&cpu("off"), &Placement::Best, true)); + // the choice: Metal (macOS) or the GPU backbone to the CPU and back + assert!(moves(&Placement::Best, &placement(false, None, true), false)); + assert!(moves(&placement(false, None, true), &placement(false, None, false), false)); + assert!(moves(&Placement::GpuBackbone, &chosen(), true)); + // the CPU for one reason or the other: it stays loaded + assert!(!moves(&cpu("disabled by LIGHTCRAFT_GPU=0"), &chosen(), true)); + assert!(!moves(&chosen(), &cpu("disabled by LIGHTCRAFT_GPU=0"), false)); + assert!(!moves(&Placement::GpuBackbone, &placement(true, None, false), true)); + } + + #[test] + fn with_the_cpu_chosen_the_gpu_backbone_is_never_built() { + let dir = empty_model("chosen"); + // candle loads on the CPU (and fails: the checkpoint is empty), without touching the GPU + assert!(load(&dir, Device::Cpu, &placement(true, None, true), never).is_err()); + assert!(load(&dir, Device::Cpu, &placement(false, None, true), never).is_err()); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn the_gpu_backbone_loads_and_reports_where_it_runs() { + let dir = empty_model("gpu"); + let m = load(&dir, Device::Cpu, &Placement::GpuBackbone, fake_gpu).unwrap(); + let shared = Shared::default(); + note_loaded(&shared, &m, &Placement::GpuBackbone); + let b = backend(&shared); + assert_eq!( + (b.device.as_deref(), b.runtime.as_deref(), b.heads.as_deref(), b.fallback.as_deref()), + (Some("Fake GPU (Vulkan)"), Some("wgpu"), Some("CPU"), None) + ); + let enc = m.encode(&[0; 8 * 8 * 3], 8, 8); + note_run(&shared, &m, enc.is_ok().then_some(Duration::from_millis(812))); + assert_eq!(backend(&shared).encode_ms, Some(812)); + let json = serde_json::to_value(backend(&shared)).unwrap(); + assert_eq!(json["device"], "Fake GPU (Vulkan)"); + assert_eq!(json["encodeMs"], 812); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn with_the_gpu_switched_off_the_gpu_backbone_is_never_built() { + let dir = empty_model("off"); + let off = Placement::Cpu("disabled by LIGHTCRAFT_GPU_BACKEND=off".into()); + // candle loads (and fails: the checkpoint is empty), without touching the GPU + assert!(load(&dir, Device::Cpu, &off, never).is_err()); + assert!(load(&dir, Device::Cpu, &Placement::Best, never).is_err()); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn a_gpu_that_cannot_be_used_leaves_the_backbone_to_the_cpu() { + let dir = empty_model("nogpu"); + // without an adapter candle loads the backbone (failing here only for the empty checkpoint) + let e = load(&dir, Device::Cpu, &Placement::GpuBackbone, no_gpu).err().unwrap(); + assert!(!e.to_string().contains("no GPU adapter"), "{e}"); + // a GPU that fails on a photo: the CPU takes over, and the status says why + let m = load(&dir, Device::Cpu, &Placement::GpuBackbone, failing_gpu).unwrap(); + let shared = Shared::default(); + note_loaded(&shared, &m, &Placement::GpuBackbone); + assert_eq!(backend(&shared).runtime.as_deref(), Some("wgpu")); + let enc = m.encode(&[0; 8 * 8 * 3], 8, 8); + note_run(&shared, &m, enc.is_ok().then_some(Duration::from_millis(1))); + let b = backend(&shared); + assert_eq!((b.device.as_deref(), b.runtime.as_deref()), (Some("CPU"), Some("candle"))); + assert!(b.fallback.as_deref().is_some_and(|f| f.contains("device lost")), "{b:?}"); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn the_environment_switches_and_a_failed_gpu_keep_the_model_on_the_cpu_also_on_macos() { + // candle's GPU failed this session: the CPU, with the reason, wherever candle has a GPU or not + for best_is_cpu in [false, true] { + assert_eq!(wanted(best_is_cpu, false, Some("the GPU couldn't run it")), Placement::Cpu("the GPU couldn't run it".into())); + } + // the CPU chosen in Settings still says so + assert_eq!(wanted(false, true, Some("x")), Placement::Cpu(super::super::CPU_CHOSEN.into())); + // otherwise as `placement`, with the environment switches deciding for Metal too + let want = match lightcraft_gpu::env_off_reason() { + Some(why) => Placement::Cpu(why.into()), + None => Placement::Best, + }; + assert_eq!(wanted(false, false, None), want); + } + + /// Run `kinds` in turn on a worker where candle has a GPU (`metal`) or not, the CPU chosen or not; their outcomes. + fn run_kinds(metal: bool, cpu: bool, kinds: Vec) -> Vec { + let (tx, rx) = mpsc::channel(); + let (jtx, jrx) = mpsc::channel(); + let shared = Shared::default(); + shared.pending.store(kinds.len(), Ordering::SeqCst); + for kind in kinds { + let mut j = job(Tag::Wait, &tx); + j.kind = kind; + j.cpu = cpu; + jtx.send(j).unwrap(); + } + drop(jtx); + run(&jrx, &shared, Duration::from_secs(60), metal); + assert_eq!(shared.pending.load(Ordering::SeqCst), 0, "counters reset"); + assert!(!shared.encoding.load(Ordering::SeqCst)); + rx.try_iter().collect() + } + + /// The tests of the CPU fallback assume the GPU isn't switched off in the environment (it never is tried then). + fn gpu_allowed() -> bool { + let ok = lightcraft_gpu::env_off_reason().is_none(); + if !ok { + lightcraft_testkit::skip!(Gpu, "the GPU is switched off in the environment"); + } + ok + } + + #[test] + fn a_job_that_panics_on_the_gpu_runs_on_the_cpu_and_so_do_the_next_ones() { + if !gpu_allowed() { + return; + } + // issue #1974: candle panics compiling a Metal kernel the GPU's compiler can't build + let out = run_kinds(true, false, vec![Kind::FailOnGpu { panic: true }, Kind::FailOnGpu { panic: true }]); + assert_eq!(out.len(), 2); + assert!(matches!(out[0].result, Ok(None)), "retried on the CPU: {:?}", out[0].result.as_ref().err()); + assert_eq!(out[0].notice.as_deref(), Some(GPU_FAILED)); + assert!(matches!(out[1].result, Ok(None)), "the next job starts on the CPU"); + assert_eq!(out[1].notice, None, "said once"); + } + + #[test] + fn a_model_error_on_the_gpu_is_retried_on_the_cpu_too() { + if !gpu_allowed() { + return; + } + let out = run_kinds(true, false, vec![Kind::FailOnGpu { panic: false }]); + assert!(matches!(out[0].result, Ok(None))); + assert_eq!(out[0].notice.as_deref(), Some(GPU_FAILED)); + } + + #[test] + fn a_job_that_fails_on_the_cpu_too_keeps_the_gpu() { + if !gpu_allowed() { + return; + } + let out = run_kinds(true, false, vec![Kind::Panic, Kind::FailOnGpu { panic: true }]); + assert!(out[0].result.as_ref().unwrap_err().contains("failed unexpectedly"), "reported as before"); + assert_eq!(out[0].notice, None); + // the next job still starts on the GPU, fails there and works on the CPU + assert!(matches!(out[1].result, Ok(None))); + assert_eq!(out[1].notice.as_deref(), Some(GPU_FAILED)); + } + + #[test] + fn missing_model_files_are_not_retried_on_the_cpu() { + let out = run_kinds(true, false, vec![Kind::Prepare]); + assert!(out[0].result.as_ref().unwrap_err().contains("not found")); + assert_eq!(out[0].notice, None); + } + + #[test] + fn a_worker_on_the_cpu_never_tries_the_gpu() { + // the CPU chosen in Settings, and a build where candle has no GPU + for (metal, cpu) in [(true, true), (false, true)] { + let out = run_kinds(metal, cpu, vec![Kind::FailOnGpu { panic: true }]); + assert!(matches!(out[0].result, Ok(None))); + assert_eq!(out[0].notice, None); + } + // no GPU path (not macOS): a failure is reported, not retried + let out = run_kinds(false, false, vec![Kind::FailOnGpu { panic: false }]); + assert!(out[0].result.is_err()); + assert_eq!(out[0].notice, None); + } + + #[test] + fn a_cpu_model_kept_for_another_reason_shows_that_reason() { + let dir = empty_model("reason"); + let shared = Shared::default(); + let mut state = State::default(); + let chosen = Placement::Cpu(super::super::CPU_CHOSEN.into()); + // loaded with the CPU chosen (put there by hand: the empty checkpoint doesn't load) + state.placement = Some((chosen.clone(), true)); + shared.backend.lock().unwrap().fallback = Some(super::super::CPU_CHOSEN.into()); + // the choice goes back to Automatic while the CPU stays for another reason: the new reason shows (the reload + // that follows here is only because no model was in memory) + let why = "the GPU couldn't run it"; + let _ = model(&mut state, &shared, &dir, false, Some(why)); + assert_eq!(backend(&shared).fallback.as_deref(), Some(why)); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn a_detail_pass_leaves_the_last_photos_times_alone() { + let dir = empty_model("detail"); + let m = load(&dir, Device::Cpu, &Placement::GpuBackbone, failing_gpu).unwrap(); + let shared = Shared::default(); + note_loaded(&shared, &m, &Placement::GpuBackbone); + { + let mut b = shared.backend.lock().unwrap(); + (b.encode_ms, b.analyze_ms) = (Some(812), Some(900)); + } + // the zoomed-in region: the GPU fails on it, and the status says where the backbone runs now + let _ = m.encode(&[0; 8 * 8 * 3], 8, 8); + note_detail(&shared, &m); + let b = backend(&shared); + assert_eq!((b.device.as_deref(), b.runtime.as_deref()), (Some("CPU"), Some("candle"))); + assert!(b.fallback.as_deref().is_some_and(|f| f.contains("device lost")), "{b:?}"); + assert_eq!((b.encode_ms, b.analyze_ms), (Some(812), Some(900)), "the last photo's times"); + std::fs::remove_dir_all(dir).unwrap(); + } } diff --git a/crates/engine/src/sidecar.rs b/crates/engine/src/sidecar.rs index 1e89b7d537..b46f1a0d04 100644 --- a/crates/engine/src/sidecar.rs +++ b/crates/engine/src/sidecar.rs @@ -379,6 +379,78 @@ impl SidecarData { self } + /// Overlay fields supplied by `other` onto `self`: any field present in `other` + /// replaces the one in `self`. + pub fn override_with(&mut self, other: SidecarData) { + if other.rating.is_some() { + self.rating = other.rating; + if self.flag == Some(Flag::Reject) && other.flag.is_none() { + self.flag = Some(Flag::None); + } + } + if other.flag.is_some() { + self.flag = other.flag; + } + if other.label.is_some() { + self.label = other.label; + self.label_text = other.label_text; + } + if other.title.is_some() { + self.title = other.title; + } + if other.caption.is_some() { + self.caption = other.caption; + } + if other.copyright.is_some() { + self.copyright = other.copyright; + } + if other.copyright_marked.is_some() { + self.copyright_marked = other.copyright_marked; + } + if other.usage_terms.is_some() { + self.usage_terms = other.usage_terms; + } + if other.copyright_url.is_some() { + self.copyright_url = other.copyright_url; + } + if other.creator.is_some() { + self.creator = other.creator; + } + if other.location.is_some() { + self.location = other.location; + } + if other.city.is_some() { + self.city = other.city; + } + if other.state.is_some() { + self.state = other.state; + } + if other.country.is_some() { + self.country = other.country; + } + if other.alt_text.is_some() { + self.alt_text = other.alt_text; + } + if other.extended_description.is_some() { + self.extended_description = other.extended_description; + } + if other.keywords.is_some() { + self.keywords = other.keywords; + } + if other.regions.is_some() { + self.regions = other.regions; + } + if other.captured.is_some() { + self.captured = other.captured; + } + if other.develop.is_some() { + self.develop = other.develop; + self.warnings = other.warnings; + } else { + self.warnings.extend(other.warnings); + } + } + /// Take the orientation of the photo file at `original` (LightCraft shows the photo turned by it, and the packet /// may not repeat it) when the regions need it: they were drawn on a stated size ([`SidecarData::regions_drawn_on`]). /// Only then is the file read ([`file_orientation`]). diff --git a/crates/engine/src/slide.rs b/crates/engine/src/slide.rs index 009a2e2ac3..4ddf6cca6e 100644 --- a/crates/engine/src/slide.rs +++ b/crates/engine/src/slide.rs @@ -87,7 +87,7 @@ impl crate::Session { p.height.max(1) as usize, &p.develop, true, - p.embedded_lens.as_ref(), + p.embedded_lens.as_deref(), ); let a = frame.aspect(); Some(if a.is_finite() && a > 0.0 { a } else { 1.5 }) diff --git a/crates/engine/src/sync.rs b/crates/engine/src/sync.rs index 7ad8715a44..04db8219dc 100644 --- a/crates/engine/src/sync.rs +++ b/crates/engine/src/sync.rs @@ -7,7 +7,7 @@ //! - **new** files: supported files the library doesn't have, by path or by content (the import //! scan's duplicate rules, [`crate::import::scan_with`]); //! - **missing** photos: library photos in the folder whose file is gone (the Missing Photos rule, -//! [`crate::cmd::missing::checked_path`]); +//! [`lightcraft_catalog::Photo::library_file`]); //! - **metadata** updates: photos whose XMP sidecar file was saved after the photo came into the //! library or was last edited here, and says something the library doesn't (rating, flag, //! label, metadata, capture time or develop settings). Reading one makes the sidecar win, as @@ -267,7 +267,7 @@ pub fn scan_with(input: SyncInput, progress: &SyncProgress) -> FolderChanges { ); let mut changes = FolderChanges { path: folder, seen, ..Default::default() }; for ((p, _), check) in photos.iter().zip(checks) { - let Some(file) = crate::cmd::missing::checked_path(p) else { continue }; + let Some(file) = p.library_file() else { continue }; let found = FolderPhoto { id: p.id.0, path: file.to_string() }; match check { Check::Missing => changes.missing.push(found), @@ -280,14 +280,12 @@ pub fn scan_with(input: SyncInput, progress: &SyncProgress) -> FolderChanges { if moved_from.values().any(|to| *to == c.path) { continue; } - let browsed = c.existing.and_then(|id| labels.photo(PhotoId(id))).is_some_and(|p| p.local && !p.deleted); match (c.duplicate.as_deref(), &c.error) { - // a file only looked at in Local is not in the library yet: it is new - (Some("path"), _) if browsed => changes.new.push(ImportCandidate { duplicate: None, existing: None, ..c }), (Some("path"), _) => {} (Some(_), _) => changes.duplicates += 1, (None, Some(_)) => changes.unreadable.push(c), - (None, None) => changes.new.push(c), + // (a file only looked at in Local is not in the library yet: it is new) + (None, None) => changes.new.push(ImportCandidate { existing: None, local: false, ..c }), } } let missing = std::mem::take(&mut changes.missing); @@ -346,7 +344,7 @@ fn match_moved( by_hash.entry(base_hash(h)).or_default().push_back(path); } } - let usable = |c: &&ImportCandidate| c.error.is_none() && c.duplicate.as_deref() != Some("path"); + let usable = |c: &&ImportCandidate| c.error.is_none() && c.duplicate.as_deref() != Some("path") && !c.local; let mut moved: HashMap = HashMap::new(); for c in candidates.iter().filter(usable) { let hash = probes.get(&c.path).and_then(|i| i.content_hash.as_deref()); @@ -512,7 +510,7 @@ impl Listing { } fn check_photo(p: &Photo, naming: SidecarLookup, labels: &Catalog, listing: &Listing) -> Check { - let Some(file) = crate::cmd::missing::checked_path(p) else { return Check::Nothing }; + let Some(file) = p.library_file() else { return Check::Nothing }; let file = Path::new(file); if !listing.or_ask(listing.exists(file), || file.exists()) { Check::Missing @@ -895,3 +893,7 @@ impl SyncCommit { #[cfg(test)] #[path = "sync/tests_listing.rs"] mod tests_listing; + +#[cfg(test)] +#[path = "sync/tests_browsed.rs"] +mod tests_browsed; diff --git a/crates/engine/src/sync/tests_browsed.rs b/crates/engine/src/sync/tests_browsed.rs new file mode 100644 index 0000000000..fa66ec3373 --- /dev/null +++ b/crates/engine/src/sync/tests_browsed.rs @@ -0,0 +1,22 @@ +//! Synchronize Folder's "moved" match never takes a file that is only browsed in Local as the new +//! place of a missing photo: that file already has a record of its own. +use super::*; +use lightcraft_catalog::{Catalog, Op}; + +/// Given a missing photo with no hash on record and one file of the folder with its size and +/// dimensions, when the files are matched, then the file is its new place, unless the file is one +/// the library only browsed. +#[test] +fn a_browsed_file_is_not_where_a_missing_photo_went() { + let mut c = Catalog::new(); + let id = c.alloc_photo_id(); + let mut p = Photo::new(id, Source::File { path: "/pics/old.jpg".into() }, "old.jpg", "JPEG", 6, 4, "2026-01-01"); + p.file_size = 1000; + c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + let missing = [FolderPhoto { id: id.0, path: "/pics/old.jpg".into() }]; + let mut found = ImportCandidate { path: "/pics/new.jpg".into(), width: 6, height: 4, file_size: 1000, existing: Some(99), ..Default::default() }; + let moved = match_moved(&missing, std::slice::from_ref(&found), &HashMap::new(), &c); + assert_eq!(moved.get("/pics/old.jpg").map(String::as_str), Some("/pics/new.jpg"), "a new file is where it went"); + found.local = true; + assert!(match_moved(&missing, &[found], &HashMap::new(), &c).is_empty(), "a browsed file has a record already"); +} diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 38617f011a..2d5d9df4d5 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -8,6 +8,8 @@ mod album_order; mod album_remove; mod albums_local; mod autosync_wb; +mod batch_sidebar; +mod bursts; mod color; mod constrain_crop; mod crop_angle; @@ -36,6 +38,7 @@ mod lens_refresh; mod libops; mod library; mod lightroom_folder; +mod lightroom_history; mod mask_effects; mod mask_geometry; mod merge; @@ -60,6 +63,7 @@ mod slideshow_export; mod slow_drive; mod spots; mod sync; +mod task_queue; mod view_follow; pub(super) mod xmp; @@ -504,6 +508,24 @@ fn connected_brush_strokes_start_where_the_last_one_ended() { assert_eq!(strokes(&s).len(), 2); } +/// A stroke sent again as it grows (its effect shows while painting) replaces itself; earlier strokes stay. +#[test] +fn a_stroke_sent_again_as_it_grows_replaces_itself() { + let mut s = demo(); + s.execute("mask.add", &json!({"kind": "brush"})).unwrap(); + s.execute("mask.brushStroke", &json!({"points": [[0.1, 0.1]]})).unwrap(); + s.execute("mask.brushStroke", &json!({"points": [[0.2, 0.2], [0.3, 0.2]]})).unwrap(); + for n in [3, 4] { + let pts: Vec<[f64; 2]> = (0..n).map(|i| [0.2 + 0.1 * i as f64, 0.2]).collect(); + s.execute("mask.brushStroke", &json!({"points": pts, "continue": true})).unwrap(); + } + let dev = active_dev(&s); + let Some(lightcraft_develop::MaskShape::Brush { strokes }) = dev.masks.first().and_then(|m| m.components.first()).map(|c| &c.shape) else { + panic!("a brush mask") + }; + assert_eq!(strokes.iter().map(|s| s.points.len()).collect::>(), vec![1, 4], "the earlier stroke stays, the live one is replaced"); +} + #[test] fn a_mask_id_at_the_limit_does_not_overflow_the_next_masks() { let mut s = demo(); @@ -2396,3 +2418,26 @@ mod interaction_edit_metadata { attachment(None); } } + +/// Upright that finds nothing to correct says why instead of silently doing nothing. +#[test] +fn upright_says_why_it_found_nothing_to_correct() { + let mut s = demo(); + let mut noted = 0; + for id in s.visible().iter().copied().take(4).collect::>() { + s.execute("library.select", &json!({"ids": [id.0]})).unwrap(); + let r = s.execute("geometry.upright", &json!({"mode": "vertical"})).unwrap(); + let identity = r["transform"] == serde_json::to_value(lightcraft_geom::Homography::IDENTITY).unwrap(); + match r["note"].as_str() { + Some(note) => { + noted += 1; + assert!(identity || note.contains(" instead."), "a correction was applied but the note doesn't say which: {r}"); + assert!(note.starts_with("No vertical correction: "), "{note}"); + } + None => assert!(!identity, "a vertical correction was found: {r}"), + } + } + assert!(noted > 0, "the demo's natural scenes have no verticals to correct"); + let r = s.execute("geometry.upright", &json!({"mode": "off"})).unwrap(); + assert!(r["note"].is_null()); +} diff --git a/crates/engine/src/tests/batch_sidebar.rs b/crates/engine/src/tests/batch_sidebar.rs new file mode 100644 index 0000000000..1568ae58e7 --- /dev/null +++ b/crates/engine/src/tests/batch_sidebar.rs @@ -0,0 +1,301 @@ +//! Acting on several sidebar rows at once: the commands a context menu runs when several albums, +//! folders or keywords are chosen. Each is one step to undo, checks everything before it changes +//! anything, and a refusal names what it refused. +//! +//! Scenarios: +//! - Given three albums, when two are deleted at once (`album.delete {ids}`), then both are gone, +//! the third stays, and one undo brings both back. +//! - Given a folder of albums and an album inside it both named, then deleting them deletes the +//! folder with what is in it, once. +//! - An album that does not exist among those to delete is refused by name, and nothing is deleted. +//! - Given two albums, when both are moved into a folder (`album.move {ids, parent}`), then both +//! are inside it, and one undo puts both back; a folder is not moved into itself, and then +//! nothing moves. +//! - Given keywords on photos, when several are deleted at once (`keyword.delete {keywords}`), +//! then every photo loses them and one undo gives them back; one that is no keyword refuses the +//! whole call and nothing is deleted (one keyword that is no keyword still changes nothing). +//! - Given several keywords, when they are moved inside another (`keyword.move {keywords, +//! parent}`), then each is nested there with its photos, as one undo step; a name that is taken +//! there, or two of them with one name, is refused and nothing moves. +//! - Given two folders of the library, when both are removed at once (`library.removeFolder +//! {paths}`), then their photos go to Recently Deleted as one undo step; one that is not a +//! folder of the library refuses the whole call. +//! - Given two folders, when both get a colour label at once (`folder.label {paths}`), then both +//! show it, and one undo takes both off. + +use lightcraft_catalog::{AlbumId, Op, Photo, PhotoId, Source}; +use serde_json::json; + +use crate::Session; + +fn photos(s: &mut Session, n: u64) -> Vec { + (1..=n) + .map(|day| { + let id = s.catalog.alloc_photo_id(); + let mut p = Photo::new(id, Source::Demo { scene: 1 }, &format!("p{day}.jpg"), "JPEG", 60, 40, "2026-02-01T10:00:00"); + p.captured = Some(format!("2026-01-{day:02}T10:00:00")); + s.commit("Add Photo", Op::AddPhoto { photo: Box::new(p) }).unwrap(); + id.0 + }) + .collect() +} + +fn album(s: &mut Session, params: serde_json::Value) -> u64 { + s.execute("album.create", ¶ms).unwrap()["id"].as_u64().unwrap() +} + +fn has_album(s: &Session, id: u64) -> bool { + s.catalog.album(AlbumId(id)).is_some() +} + +fn parent_of(s: &Session, id: u64) -> Option { + s.catalog.album(AlbumId(id)).unwrap().parent.map(|p| p.0) +} + +fn tag(s: &mut Session, id: u64, keywords: &[&str]) { + // the command wants a selection to be enabled, whatever `ids` says + s.selection.ids = vec![PhotoId(id)]; + s.execute("photo.setMeta", &json!({"ids": [id], "addKeywords": keywords})).unwrap(); + s.selection.ids.clear(); +} + +fn keywords_of(s: &Session, id: u64) -> Vec { + let mut k = s.catalog.photo(PhotoId(id)).unwrap().meta.keywords.clone(); + k.sort(); + k +} + +fn undo(s: &mut Session) { + s.execute("edit.undo", &json!({})).unwrap(); +} + +#[test] +fn several_albums_are_deleted_as_one_step() { + let mut s = Session::new(); + let (a, b, c) = (album(&mut s, json!({"name": "A"})), album(&mut s, json!({"name": "B"})), album(&mut s, json!({"name": "C"}))); + let steps = s.undo.len(); + let r = s.execute("album.delete", &json!({"ids": [a, c]})).unwrap(); + assert_eq!(r["deleted"], 2); + assert_eq!((has_album(&s, a), has_album(&s, b), has_album(&s, c)), (false, true, false)); + assert_eq!(s.undo.len(), steps + 1, "one step"); + assert_eq!(s.undo.last().unwrap().label, "Delete 2 Albums"); + undo(&mut s); + assert!(has_album(&s, a) && has_album(&s, c)); +} + +#[test] +fn a_folder_and_an_album_inside_it_are_deleted_once() { + let mut s = Session::new(); + let folder = album(&mut s, json!({"name": "Trips", "folder": true})); + let inside = album(&mut s, json!({"name": "Alps", "parent": folder})); + let other = album(&mut s, json!({"name": "Other"})); + s.execute("album.delete", &json!({"ids": [inside, folder, other]})).unwrap(); + assert!(!has_album(&s, folder) && !has_album(&s, inside) && !has_album(&s, other)); + undo(&mut s); + assert_eq!(parent_of(&s, inside), Some(folder), "back where it was"); + assert!(has_album(&s, other)); +} + +#[test] +fn deleting_several_albums_checks_them_all_first() { + let mut s = Session::new(); + let a = album(&mut s, json!({"name": "A"})); + let steps = s.undo.len(); + let e = s.execute("album.delete", &json!({"ids": [a, 4242]})).unwrap_err().to_string(); + assert!(e.contains("4242"), "{e}"); + assert!(has_album(&s, a), "nothing was deleted"); + assert_eq!(s.undo.len(), steps); + for bad in [json!([]), json!("a"), json!([a, "b"])] { + assert!(s.execute("album.delete", &json!({"ids": bad})).is_err(), "{bad}"); + } + assert!(has_album(&s, a)); + // one alone, the way it always was + s.execute("album.delete", &json!({"id": a})).unwrap(); + assert!(!has_album(&s, a)); + assert_eq!(s.undo.last().unwrap().label, "Delete Album"); +} + +#[test] +fn several_albums_move_into_a_folder_as_one_step() { + let mut s = Session::new(); + let (a, b) = (album(&mut s, json!({"name": "A"})), album(&mut s, json!({"name": "B"}))); + let folder = album(&mut s, json!({"name": "Trips", "folder": true})); + let steps = s.undo.len(); + s.execute("album.move", &json!({"ids": [a, b], "parent": folder})).unwrap(); + assert_eq!((parent_of(&s, a), parent_of(&s, b)), (Some(folder), Some(folder))); + assert_eq!(s.undo.len(), steps + 1); + assert_eq!(s.undo.last().unwrap().label, "Move 2 Albums"); + undo(&mut s); + assert_eq!((parent_of(&s, a), parent_of(&s, b)), (None, None)); + // back to the top level, both at once + s.execute("album.move", &json!({"ids": [a, b], "parent": folder})).unwrap(); + s.execute("album.move", &json!({"ids": [a, b], "parent": null})).unwrap(); + assert_eq!((parent_of(&s, a), parent_of(&s, b)), (None, None)); +} + +#[test] +fn moving_several_albums_checks_them_all_first() { + let mut s = Session::new(); + let a = album(&mut s, json!({"name": "A"})); + let folder = album(&mut s, json!({"name": "Trips", "folder": true})); + let inner = album(&mut s, json!({"name": "Inner", "folder": true, "parent": folder})); + // a folder can't go inside itself or inside a folder it holds: then nothing moves + for parent in [folder, inner] { + let e = s.execute("album.move", &json!({"ids": [a, folder], "parent": parent})).unwrap_err().to_string(); + assert!(e.contains("Trips"), "the refusal names it: {e}"); + assert_eq!(parent_of(&s, a), None, "nothing moved"); + } + // into something that is not a folder, or not there + assert!(s.execute("album.move", &json!({"ids": [folder], "parent": a})).is_err()); + assert!(s.execute("album.move", &json!({"ids": [a], "parent": 4242})).is_err()); + assert!(s.execute("album.move", &json!({"ids": [a, 4242], "parent": folder})).is_err()); + assert_eq!(parent_of(&s, a), None); + // a folder and an album already inside it: the folder moves, and the album with it + let outer = album(&mut s, json!({"name": "Outer", "folder": true})); + let within = album(&mut s, json!({"name": "Within", "parent": inner})); + s.execute("album.move", &json!({"ids": [within, inner], "parent": outer})).unwrap(); + assert_eq!((parent_of(&s, inner), parent_of(&s, within)), (Some(outer), Some(inner))); +} + +#[test] +fn several_keywords_are_deleted_as_one_step() { + let mut s = Session::new(); + let ids = photos(&mut s, 2); + tag(&mut s, ids[0], &["alps", "beach", "trips|italy"]); + tag(&mut s, ids[1], &["beach", "town"]); + let steps = s.undo.len(); + let r = s.execute("keyword.delete", &json!({"keywords": ["alps", "beach", "trips"]})).unwrap(); + assert_eq!(r["changed"], 2); + assert_eq!(keywords_of(&s, ids[0]), Vec::::new()); + assert_eq!(keywords_of(&s, ids[1]), vec!["town"]); + assert_eq!(s.undo.len(), steps + 1); + assert_eq!(s.undo.last().unwrap().label, "Delete 3 Keywords"); + undo(&mut s); + assert_eq!(keywords_of(&s, ids[0]), vec!["alps", "beach", "trips|italy"]); + assert_eq!(keywords_of(&s, ids[1]), vec!["beach", "town"]); + // nothing named: refused, as is something that is no keyword + for bad in [json!([]), json!([""]), json!(7), json!(["alps", 7])] { + assert!(s.execute("keyword.delete", &json!({"keywords": bad})).is_err(), "{bad}"); + } + assert_eq!(keywords_of(&s, ids[1]), vec!["beach", "town"]); +} + +#[test] +fn deleting_several_keywords_checks_them_all_first() { + let mut s = Session::new(); + let ids = photos(&mut s, 1); + tag(&mut s, ids[0], &["alps", "trips|italy"]); + let steps = s.undo.len(); + let e = s.execute("keyword.delete", &json!({"keywords": ["alps", "nowhere"]})).unwrap_err().to_string(); + assert!(e.contains("no keyword") && e.contains("nowhere"), "names the one that is missing: {e}"); + assert_eq!(keywords_of(&s, ids[0]), vec!["alps", "trips|italy"]); + assert_eq!(s.undo.len(), steps); + // a keyword that is only the upper level of one, in another case, is there + s.execute("keyword.delete", &json!({"keywords": ["ALPS", "Trips"]})).unwrap(); + assert_eq!(keywords_of(&s, ids[0]), Vec::::new()); + // one keyword that is not there is still a no-op, as before + let steps = s.undo.len(); + s.execute("keyword.delete", &json!({"keyword": "nowhere"})).unwrap(); + assert_eq!(s.undo.len(), steps); +} + +#[test] +fn several_keywords_move_inside_another_as_one_step() { + let mut s = Session::new(); + let ids = photos(&mut s, 2); + tag(&mut s, ids[0], &["alps", "beach"]); + tag(&mut s, ids[1], &["beach", "places"]); + let steps = s.undo.len(); + let r = s.execute("keyword.move", &json!({"keywords": ["alps", "beach"], "parent": "places"})).unwrap(); + assert_eq!(r["changed"], 2); + assert_eq!(keywords_of(&s, ids[0]), vec!["places|alps", "places|beach"]); + assert_eq!(keywords_of(&s, ids[1]), vec!["places", "places|beach"]); + assert_eq!(s.undo.len(), steps + 1); + assert_eq!(s.undo.last().unwrap().label, "Move 2 Keywords"); + undo(&mut s); + assert_eq!(keywords_of(&s, ids[0]), vec!["alps", "beach"]); + // …and back out to the top level + s.execute("keyword.move", &json!({"keywords": ["alps", "beach"], "parent": "places"})).unwrap(); + s.execute("keyword.move", &json!({"keywords": ["places|alps", "places|beach"], "parent": null})).unwrap(); + assert_eq!(keywords_of(&s, ids[0]), vec!["alps", "beach"]); +} + +#[test] +fn moving_several_keywords_checks_them_all_first() { + let mut s = Session::new(); + let ids = photos(&mut s, 2); + tag(&mut s, ids[0], &["alps", "europe|alps", "beach", "asia|beach", "places"]); + let before = keywords_of(&s, ids[0]); + let steps = s.undo.len(); + // a name that is taken where they go: moving would merge the two, which is not done in a batch + let e = s.execute("keyword.move", &json!({"keywords": ["beach", "alps"], "parent": "europe"})).unwrap_err().to_string(); + assert!(e.contains("europe|alps"), "names the one in the way: {e}"); + // two of them with one name + let e = s.execute("keyword.move", &json!({"keywords": ["beach", "asia|beach"], "parent": "places"})).unwrap_err().to_string(); + assert!(e.to_lowercase().contains("beach"), "{e}"); + // inside one of themselves; one that is no keyword + assert!(s.execute("keyword.move", &json!({"keywords": ["places", "alps"], "parent": "places"})).is_err()); + assert!(s.execute("keyword.move", &json!({"keywords": ["alps", "nope"], "parent": "places"})).is_err()); + assert!(s.execute("keyword.move", &json!({"keywords": [], "parent": "places"})).is_err()); + assert_eq!(keywords_of(&s, ids[0]), before, "nothing moved"); + assert_eq!(s.undo.len(), steps); + // a keyword and one below it: the upper one moves, and the lower with it + s.execute("keyword.move", &json!({"keywords": ["europe|alps", "europe"], "parent": "places"})).unwrap(); + assert!(keywords_of(&s, ids[0]).contains(&"places|europe|alps".to_string())); +} + +fn add_file(s: &mut Session, path: &str) -> u64 { + let id = s.catalog.alloc_photo_id(); + let p = Photo::new(id, Source::File { path: path.into() }, "x.jpg", "JPEG", 60, 40, "2026-01-01T10:00:00"); + s.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + id.0 +} + +fn deleted(s: &Session, id: u64) -> bool { + s.catalog.photo(PhotoId(id)).unwrap().deleted +} + +#[test] +fn several_folders_leave_the_library_as_one_step() { + let mut s = Session::new(); + let alps = add_file(&mut s, "/pics/2025/alps/a.jpg"); + let beach = add_file(&mut s, "/pics/2026/beach/c.jpg"); + let town = add_file(&mut s, "/pics/2026/town/d.jpg"); + let steps = s.undo.len(); + // refused as a whole when one is not a folder of the library + let e = s.execute("library.removeFolder", &json!({"paths": ["/pics/2025/alps", "/nowhere"]})).unwrap_err().to_string(); + assert!(e.contains("/nowhere"), "{e}"); + assert!(!deleted(&s, alps)); + let r = s.execute("library.removeFolder", &json!({"paths": ["/pics/2025/alps", "/pics/2026/beach"]})).unwrap(); + assert_eq!(r["removed"], 2); + assert_eq!((deleted(&s, alps), deleted(&s, beach), deleted(&s, town)), (true, true, false)); + assert_eq!(s.undo.len(), steps + 1); + assert_eq!(s.undo.last().unwrap().label, "Remove 2 Folders from Library"); + undo(&mut s); + assert!(!deleted(&s, alps) && !deleted(&s, beach)); + // a folder and one inside it: each photo once + add_file(&mut s, "/pics/2025/alps/day1/b.jpg"); + let r = s.execute("library.removeFolder", &json!({"paths": ["/pics/2025/alps/day1", "/pics/2025/alps"]})).unwrap(); + assert_eq!(r["removed"], 2); +} + +#[test] +fn several_folders_get_a_colour_label_as_one_step() { + let mut s = Session::new(); + add_file(&mut s, "/pics/2025/alps/a.jpg"); + add_file(&mut s, "/pics/2026/beach/c.jpg"); + let label = |s: &Session, path: &str| s.catalog.folder_record(path).and_then(|r| r.label); + let steps = s.undo.len(); + let e = s.execute("folder.label", &json!({"paths": ["/pics/2025/alps", "/nowhere"], "label": "red"})).unwrap_err().to_string(); + assert!(e.contains("/nowhere"), "{e}"); + assert!(label(&s, "/pics/2025/alps").is_none(), "nothing was labelled"); + s.execute("folder.label", &json!({"paths": ["/pics/2025/alps", "/pics/2026/beach"], "label": "red"})).unwrap(); + assert!(label(&s, "/pics/2025/alps").is_some() && label(&s, "/pics/2026/beach").is_some()); + assert_eq!(s.undo.len(), steps + 1); + undo(&mut s); + assert!(label(&s, "/pics/2025/alps").is_none() && label(&s, "/pics/2026/beach").is_none()); + // taking the labels off, both at once + s.execute("folder.label", &json!({"paths": ["/pics/2025/alps", "/pics/2026/beach"], "label": "blue"})).unwrap(); + s.execute("folder.label", &json!({"paths": ["/pics/2025/alps", "/pics/2026/beach"], "label": "none"})).unwrap(); + assert!(label(&s, "/pics/2025/alps").is_none() && label(&s, "/pics/2026/beach").is_none()); +} diff --git a/crates/engine/src/tests/bursts.rs b/crates/engine/src/tests/bursts.rs new file mode 100644 index 0000000000..04f2706624 --- /dev/null +++ b/crates/engine/src/tests/bursts.rs @@ -0,0 +1,262 @@ +//! Bursts arranged by hand (`photo.moveToBurst`): a photo moved within its burst, into another, +//! into a new one or out of every burst; the pick follows the first place, and with it the +//! Best of Similar Shots rule, the Pick flag culling set and the burst's stack. Culling run again +//! keeps what was arranged by hand. + +use lightcraft_catalog::{Analysis, Flag, Op, Photo, PhotoId, Source, Stack}; +use serde_json::{Value, json}; + +use crate::Session; + +/// A photo culled into `group` (`None`: culled, in no burst; `best`: its pick), or never culled. +fn add(s: &mut Session, name: &str, when: &str, culled: Option<(Option, f32, bool)>) -> PhotoId { + let id = s.catalog.alloc_photo_id(); + let mut p = Photo::new(id, Source::File { path: format!("/nowhere/{name}") }, name, "JPEG", 40, 30, "2026-05-01T12:00:00"); + p.captured = Some(when.into()); + p.analysis = culled.map(|(group, sharpness, best)| Analysis { sharpness, group, best, ..Default::default() }); + s.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + id +} + +fn an(s: &Session, id: PhotoId) -> Analysis { + s.catalog.photo(id).unwrap().analysis.unwrap() +} + +fn flag(s: &Session, id: PhotoId) -> Flag { + s.catalog.photo(id).unwrap().flag +} + +fn mv(s: &mut Session, p: Value) -> Value { + s.execute("photo.moveToBurst", &p).unwrap_or_else(|e| panic!("{p}: {e}")) +} + +/// Burst 1 (a best and picked, b, c), burst 2 (d best, e), x culled in no burst, y never culled. +fn library() -> (Session, [PhotoId; 7]) { + let mut s = Session::new(); + let a = add(&mut s, "a.jpg", "2026-05-01T10:00:00", Some((Some(1), 80.0, true))); + let b = add(&mut s, "b.jpg", "2026-05-01T10:00:01", Some((Some(1), 60.0, false))); + let c = add(&mut s, "c.jpg", "2026-05-01T10:00:02", Some((Some(1), 40.0, false))); + let d = add(&mut s, "d.jpg", "2026-05-01T11:00:00", Some((Some(2), 70.0, true))); + let e = add(&mut s, "e.jpg", "2026-05-01T11:00:01", Some((Some(2), 30.0, false))); + let x = add(&mut s, "x.jpg", "2026-05-01T12:00:00", Some((None, 50.0, false))); + let y = add(&mut s, "y.jpg", "2026-05-01T13:00:00", None); + s.catalog.apply(Op::SetFlag { id: a, flag: Flag::Pick }).unwrap(); + (s, [a, b, c, d, e, x, y]) +} + +#[test] +fn a_photo_dragged_to_the_front_of_its_burst_becomes_the_pick() { + let (mut s, [a, b, c, ..]) = library(); + assert_eq!(s.catalog.burst(1), vec![a, b, c]); + let commits = s.commits(); + // the softest shot is the one the person likes best + let r = mv(&mut s, json!({"ids": [c.0], "index": 0})); + assert_eq!((r["burst"].clone(), r["photos"].clone(), r["pick"].clone()), (json!(1), json!([c.0, a.0, b.0]), json!(c.0)), "{r}"); + assert_eq!(s.catalog.burst(1), vec![c, a, b]); + assert!(an(&s, c).best && !an(&s, a).best); + assert_eq!([an(&s, c).rank, an(&s, a).rank, an(&s, b).rank], [Some(0), Some(1), Some(2)], "the whole burst is now arranged by hand"); + // the Pick culling gave the old best goes with it + assert_eq!((flag(&s, c), flag(&s, a)), (Flag::Pick, Flag::None)); + // and so does Best of Similar Shots + s.execute("library.filter", &json!({"ruleSet": {"rules": [{"field": "bestOfGroup", "op": "is", "value": true}]}})).unwrap(); + let shown = s.visible_cloned(); + assert!(shown.contains(&c) && !shown.contains(&a), "{shown:?}"); + // one undo step + assert_eq!(s.commits(), commits + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.catalog.burst(1), vec![a, b, c]); + assert!(an(&s, a).best && an(&s, a).rank.is_none()); + assert_eq!((flag(&s, a), flag(&s, c)), (Flag::Pick, Flag::None)); + // reordering further back: the pick stays, the order is kept + mv(&mut s, json!({"ids": [b.0], "index": 2})); + assert_eq!(s.catalog.burst(1), vec![a, c, b]); + assert!(an(&s, a).best); + assert_eq!(flag(&s, a), Flag::Pick); + // a rejected shot dragged to the front was chosen by hand: it takes the Pick + s.catalog.apply(Op::SetFlag { id: b, flag: Flag::Reject }).unwrap(); + mv(&mut s, json!({"ids": [b.0], "index": 0})); + assert_eq!((flag(&s, b), flag(&s, a)), (Flag::Pick, Flag::None)); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!((flag(&s, b), flag(&s, a)), (Flag::Reject, Flag::Pick)); + // placing a photo where it already is changes nothing and makes no undo step + let commits = s.commits(); + let r = mv(&mut s, json!({"ids": [a.0], "index": 0})); + assert_eq!(r["changed"], false, "{r}"); + assert_eq!(s.commits(), commits); +} + +#[test] +fn photos_move_between_bursts_into_new_ones_and_out() { + let (mut s, [a, b, c, d, e, x, y]) = library(); + // e joins burst 1 in second place; burst 2 keeps only d, which is then in no burst + let r = mv(&mut s, json!({"ids": [e.0], "burst": 1, "index": 1})); + assert_eq!(r["photos"], json!([a.0, e.0, b.0, c.0]), "{r}"); + assert_eq!(an(&s, e).group, Some(1)); + assert!(s.catalog.burst(2).is_empty()); + assert_eq!((an(&s, d).group, an(&s, d).best, an(&s, d).by_hand()), (None, false, true)); + // without an index it goes last; a culled loose photo can join too + mv(&mut s, json!({"ids": [x.0], "burst": 1})); + assert_eq!(s.catalog.burst(1), vec![a, e, b, c, x]); + // two photos make a new burst, in the order named + let r = mv(&mut s, json!({"ids": [c.0, b.0], "burst": "new"})); + let new = r["burst"].as_u64().unwrap() as u32; + assert_ne!(new, 1, "a number no photo uses: {r}"); + assert_eq!(s.catalog.burst(new), vec![c, b]); + assert!(an(&s, c).best); + assert_eq!(s.catalog.burst(1), vec![a, e, x]); + // out of every burst: the photo left alone in its burst is out too + let r = mv(&mut s, json!({"ids": [b.0], "burst": null})); + assert_eq!(r["burst"], Value::Null, "{r}"); + assert!(s.catalog.burst(new).is_empty()); + assert!([b, c].iter().all(|p| an(&s, *p).group.is_none() && !an(&s, *p).best && an(&s, *p).by_hand())); + // a whole burst dropped on another merges them, the target's pick first + mv(&mut s, json!({"ids": [b.0, c.0], "burst": "new"})); + let merged = s.catalog.burst(1); + let theirs = s.catalog.bursts_among(&[b], None)[0].clone(); + mv(&mut s, json!({"ids": theirs.1.iter().map(|p| p.0).collect::>(), "burst": 1})); + assert_eq!(s.catalog.burst(1), [merged, theirs.1].concat()); + assert!(s.catalog.burst(theirs.0).is_empty()); + // refused, with nothing changed: a photo never culled, a burst that isn't there, a bad index + let commits = s.commits(); + for (p, why) in [ + (json!({"ids": [y.0], "burst": 1}), "Assisted Culling"), + (json!({"ids": [a.0], "burst": 99}), "no burst 99"), + (json!({"ids": [a.0], "index": -1}), "index"), + (json!({"ids": [a.0], "burst": "first"}), "burst"), + (json!({"ids": [d.0]}), "isn't in a burst"), + (json!({"ids": []}), "no photos"), + ] { + let err = s.execute("photo.moveToBurst", &p).expect_err(&p.to_string()).to_string(); + assert!(err.contains(why), "{p}: {err}"); + } + assert_eq!(s.commits(), commits); + // a new burst may start with one photo, for more to join + let r = mv(&mut s, json!({"ids": [d.0], "burst": "new"})); + let solo = r["burst"].as_u64().unwrap() as u32; + assert_eq!(s.catalog.burst(solo), vec![d]); + assert!(an(&s, d).best); + mv(&mut s, json!({"ids": [x.0], "burst": solo, "index": 0})); + assert_eq!(s.catalog.burst(solo), vec![x, d]); +} + +#[test] +fn a_stacked_burst_follows_its_pick_and_its_members() { + let (mut s, [a, b, c, d, e, ..]) = library(); + // as Assisted Culling with "Stack each burst" leaves them: collapsed, the best on top + s.catalog.apply(Op::AddStack { stack: Stack { id: lightcraft_catalog::StackId(1), photos: vec![a, b, c], collapsed: true } }).unwrap(); + s.catalog.apply(Op::AddStack { stack: Stack { id: lightcraft_catalog::StackId(2), photos: vec![d, e], collapsed: true } }).unwrap(); + mv(&mut s, json!({"ids": [c.0], "index": 0})); + let st = s.catalog.stack_of(c).unwrap(); + assert_eq!((st.photos.clone(), st.collapsed), (vec![c, a, b], true), "the new pick tops the stack"); + // d moves into burst 1: its stack (now just e) goes, burst 1's stack takes it in + s.selection = crate::Selection::single(d); + mv(&mut s, json!({"ids": [d.0], "burst": 1, "index": 1})); + assert_eq!(s.catalog.stack_of(c).unwrap().photos, vec![c, d, a, b]); + assert!(s.catalog.stack_of(e).is_none()); + // d is hidden in the collapsed stack now: the stack's top is the active photo + assert_eq!(s.selection.active, Some(c)); + // one undo brings both stacks back as they were + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.catalog.stack_of(e).unwrap().photos, vec![d, e]); + assert_eq!(s.catalog.stack_of(c).unwrap().photos, vec![c, a, b]); + // a photo stacked with something else than its burst keeps that stack when it goes to an unstacked burst + let (mut s, [a, b, c, _, e, x, _]) = library(); + s.catalog.apply(Op::AddStack { stack: Stack { id: lightcraft_catalog::StackId(5), photos: vec![x, e], collapsed: false } }).unwrap(); + mv(&mut s, json!({"ids": [e.0], "burst": 1})); + assert_eq!(s.catalog.stack_of(e).unwrap().photos, vec![x, e]); + assert_eq!(s.catalog.burst(1), vec![a, b, c, e]); +} + +/// Look-alike PNGs (a scene and two softer copies) for the culling runs below. +fn burst_files(tag: &str, scene: usize) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("lc-bursts-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let img = lightcraft_scenes::demo_library()[scene].render(480, 320); + let soften = |img: &lightcraft_raster::Rgb32f, r: usize| { + let (w, h) = (img.width, img.height); + let mut out = img.clone(); + for y in 0..h { + for x in 0..w { + let (mut acc, mut n) = ([0f32; 3], 0.0); + for yy in y.saturating_sub(r)..(y + r + 1).min(h) { + for xx in x.saturating_sub(r)..(x + r + 1).min(w) { + let c = img.data[yy * w + xx]; + acc = [acc[0] + c[0], acc[1] + c[1], acc[2] + c[2]]; + n += 1.0; + } + } + out.data[y * w + x] = acc.map(|v| v / n); + } + } + out + }; + for (name, im) in [("1_sharp.png", img.clone()), ("2_soft.png", soften(&img, 3)), ("3_softer.png", soften(&img, 6))] { + let data: Vec<[u8; 4]> = im + .data + .iter() + .map(|c| { + let e = |v: f32| (lightcraft_color::transfer::linear_to_srgb(v.clamp(0.0, 1.0)) * 255.0).round() as u8; + [e(c[0]), e(c[1]), e(c[2]), 255] + }) + .collect(); + let png = lightcraft_codecs::encode_png( + &lightcraft_codecs::EncodeImage::rgba8(&lightcraft_raster::Rgba8 { width: im.width, height: im.height, data }), + &Default::default(), + ) + .unwrap(); + std::fs::write(dir.join(format!("s{scene}_{name}")), png).unwrap(); + } + dir +} + +#[test] +fn culling_again_keeps_bursts_arranged_by_hand() { + let (one, two) = (burst_files("keep-1", 0), burst_files("keep-2", 7)); + let mut s = Session::new().with_fs(); + let import = |s: &mut Session, dir: &std::path::Path, hour: u32| -> Vec { + let r = s.execute("library.import", &json!({"paths": [dir.to_string_lossy()]})).unwrap(); + let mut ids: Vec = r["imported"].as_array().unwrap().iter().filter_map(Value::as_u64).map(PhotoId).collect(); + ids.sort_by_key(|id| s.catalog.photo(*id).unwrap().file_name.clone()); + for (i, id) in ids.iter().enumerate() { + s.commit("t", Op::SetCaptured { id: *id, captured: Some(format!("2026-05-01T{hour:02}:00:0{i}")) }).unwrap(); + } + ids + }; + let first = import(&mut s, &one, 10); + let second = import(&mut s, &two, 14); + let ids = |v: &[PhotoId]| v.iter().map(|p| p.0).collect::>(); + // two runs on different photos number their bursts apart + s.execute("photo.analyze", &json!({"ids": ids(&first), "pickBest": true})).unwrap(); + s.execute("photo.analyze", &json!({"ids": ids(&second)})).unwrap(); + let (g1, g2) = (an(&s, first[0]).group.unwrap(), an(&s, second[0]).group.unwrap()); + assert_ne!(g1, g2, "each run's bursts get numbers of their own"); + assert_eq!(s.catalog.burst(g1), first, "sharpest first"); + // the softest is the person's pick + let softest = first[2]; + mv(&mut s, json!({"ids": [softest.0], "index": 0})); + assert_eq!(flag(&s, softest), Flag::Pick); + // culling the whole view again keeps that burst as arranged, with fresh scores + let r = s.execute("photo.analyze", &json!({"ids": ids(&[first.clone(), second.clone()].concat()), "pickBest": true})).unwrap(); + assert_eq!(r["kept"], 3, "{r}"); + assert_eq!(s.catalog.burst(g1), vec![first[2], first[0], first[1]]); + assert!(an(&s, softest).best && !an(&s, first[0]).best); + assert_eq!(flag(&s, first[0]), Flag::None, "pickBest picks the pick chosen by hand, not the sharpest"); + let g2_again = an(&s, second[0]).group.unwrap(); + assert_ne!(g2_again, g1, "an automatic burst never takes a hand-made burst's number"); + assert_eq!(s.catalog.burst(g2_again), second); + // stacking each burst stacks the one arranged by hand too, in its order, the pick on top + let r = s.execute("photo.analyze", &json!({"ids": ids(&[first.clone(), second.clone()].concat()), "stackGroups": true})).unwrap(); + assert_eq!(r["stacks"], 2, "{r}"); + let st = s.catalog.stack_of(softest).expect("the hand-arranged burst is stacked"); + assert_eq!(st.photos, vec![first[2], first[0], first[1]], "in the order set by hand, its pick on top"); + assert_eq!(s.catalog.stack_of(second[0]).map(|st| st.top()), Some(second[0]), "an automatic burst: the sharpest on top"); + // asked to regroup, culling forgets the order set by hand + s.execute("photo.analyze", &json!({"ids": ids(&first), "resetBursts": true})).unwrap(); + let g = an(&s, first[0]).group.unwrap(); + assert_eq!(s.catalog.burst(g), first); + assert!(first.iter().all(|p| !an(&s, *p).by_hand())); + assert!(s.execute("photo.analyze", &json!({"ids": ids(&first), "resetBursts": "yes"})).is_err()); + let _ = std::fs::remove_dir_all(&one); + let _ = std::fs::remove_dir_all(&two); +} diff --git a/crates/engine/src/tests/color.rs b/crates/engine/src/tests/color.rs index 4805c70ece..5727ebb2ce 100644 --- a/crates/engine/src/tests/color.rs +++ b/crates/engine/src/tests/color.rs @@ -125,7 +125,31 @@ fn targeted_adjustment_on_curve_and_mixer() { assert!(!o.is_empty() && o.keys().all(|k| k.starts_with("mixer.") && k.ends_with(".sat")), "{r}"); assert!(o.values().any(|v| v.as_f64() == Some(-30.0)), "{r}"); assert!(o.values().all(|v| v.as_f64().unwrap() < 0.0)); + let top_band = |o: &serde_json::Map| { + let (k, _) = o.iter().max_by(|a, b| a.1.as_f64().unwrap().abs().total_cmp(&b.1.as_f64().unwrap().abs())).unwrap(); + k.split('.').nth(1).unwrap().to_string() + }; + let sky_band = top_band(o); assert!(s.execute("develop.targeted", &json!({"target": "nope", "x": 0.5, "y": 0.5, "delta": 1})).is_err()); + // a B&W profile's photo: the Luminance targeted adjustment moves its B&W mix, as the panel shows + s.execute("develop.profile", &json!({"id": "lc.bw.mono-rich"})).unwrap(); + let r = s.execute("develop.targeted", &json!({"target": "lum", "x": 0.5, "y": 0.1, "delta": 10})).unwrap(); + let o = r.as_object().unwrap(); + assert!(!o.is_empty() && o.keys().all(|k| k.starts_with("bw.")), "{r}"); + // ... the band of the sky's own colour, not of the grey the profile renders + assert_eq!(top_band(o), sky_band, "{r}"); + // the B&W mix comes after the colour mixer: a mixer hue shift moves the colour the B&W mix sees there, so the + // same drag shares itself out over the bands differently + let neutral = o.clone(); + let zero: serde_json::Map = neutral.keys().map(|k| (k.clone(), json!(0))).collect(); + s.execute("develop.set", &json!({ "values": zero })).unwrap(); + let shift: serde_json::Map = + lightcraft_develop::MIXER_BANDS.iter().map(|b| (format!("mixer.{b}.hue"), json!(100))).collect(); + s.execute("develop.set", &json!({ "values": shift })).unwrap(); + let r = s.execute("develop.targeted", &json!({"target": "lum", "x": 0.5, "y": 0.1, "delta": 10})).unwrap(); + let shifted = r.as_object().unwrap(); + assert!(shifted.keys().all(|k| k.starts_with("bw.")), "{r}"); + assert_ne!(shifted, &neutral, "the mixer's hue shift is part of what the B&W mix sees"); } /// Issue #730: on a raw whose camera has measured colour matrices the white-balance commands write Kelvin, mark @@ -470,3 +494,116 @@ fn one_field_wb_preset_apply_keeps_the_other_field_on_its_scale() { let back = (*s.develop_of(kelvin).unwrap()).clone(); assert_eq!(back.wb, look.wb, "a preset made from the photo puts its whole white balance back: {:?} vs {:?}", back.wb, look.wb); } + +/// A preset applied to a photo goes through one function whether it is the `preset.apply` command, a thumbnail or +/// hover preview, or an import: a hand-written preset naming one white balance number (either one, on either +/// scale) gives the same settings in all three, on a photo edited in Kelvin and on one edited relative to its +/// as-shot white. Before, the previews (`Session::preset_applied`) and import called the source-free +/// `Preset::apply_on` / `Preset::apply` directly, which stored the number without the photo's as-shot white. +#[test] +fn one_field_wb_preset_gives_the_same_result_in_command_preview_and_import() { + use lightcraft_catalog::{MediaKind, Op, Photo, Source}; + use lightcraft_develop::{Preset, WbMode, WbScale}; + let as_shot = (4986.0, -2.0); + let photo = |camera: &str| { + let mut p = Photo::new( + lightcraft_catalog::PhotoId(1), + Source::File { path: "/photos/one-field.arw".into() }, + "one-field.arw", + "ARW", + 64, + 64, + "2026-01-01T00:00:00", + ); + p.kind = MediaKind::Raw; + p.meta.camera = camera.into(); + p.as_shot_wb = Some(as_shot); + p.develop = std::sync::Arc::new(p.camera_defaults()); + p + }; + let one_field = |name: &str, wb: serde_json::Value| Preset { + id: format!("user.{name}"), + name: name.into(), + group: "User".into(), + settings: json!({ "wb": wb }), + favorite: false, + builtin: false, + }; + let presets = [ + one_field("temp-only", json!({"temp": 5800.0})), + one_field("tint-only", json!({"tint": 9.0})), + // the reverse scale: numbers written in Kelvin on a photo edited relative to as shot, and the relative + // scale named outright on a photo edited in Kelvin + one_field("kelvin-temp", json!({"scale": "kelvin", "temp": 6500.0})), + one_field("kelvin-tint", json!({"scale": "kelvin", "tint": 6.0})), + one_field("relative-temp", json!({"scale": "legacy", "temp": 6800.0})), + ]; + for (camera, kelvin_photo) in [("SONY ILCE-7M3", true), ("Nobody X1", false)] { + assert_eq!(photo(camera).relative_wb(), !kelvin_photo, "{camera}"); + for preset in &presets { + let mut s = Session::new(); + let p = photo(camera); + let id = p.id; + s.catalog.apply(Op::AddPhoto { photo: Box::new(p.clone()) }).unwrap(); + s.presets.push(preset.clone()); + let why = format!("{camera}, {}", preset.name); + let before = (*s.develop_of(id).unwrap()).clone(); + assert_eq!(before.wb.mode, WbMode::AsShot, "{why}"); + + // preview / hover + let preview = s.preset_applied(id, preset, 1.0).unwrap(); + // command + s.execute("library.select", &json!({"ids": [id.0], "active": id.0})).unwrap(); + s.execute("preset.apply", &json!({"id": preset.id})).unwrap(); + let command = (*s.develop_of(id).unwrap()).clone(); + // import (the photo is not in a catalog yet) + let mut imported = p; + s.import_defaults.raw_preset = Some(preset.id.clone()); + crate::import::apply_import_defaults(&s, &mut imported); + + assert_eq!(preview, command, "{why}: preview and command"); + assert_eq!(*imported.develop, command, "{why}: import and command"); + assert_eq!(command.wb.mode, WbMode::Custom, "{why}: the preset's number replaces As Shot: {:?}", command.wb); + // a photo edited in Kelvin ends there; a relative one keeps the scale the preset names (as `develop.merge` does) + let want_scale = if kelvin_photo || preset.name.starts_with("kelvin") { WbScale::Kelvin } else { WbScale::Legacy }; + assert_eq!(command.wb.scale, want_scale, "{why}: the photo stays on the scale it is edited on: {:?}", command.wb); + assert_ne!(command.wb, before.wb, "{why}"); + } + } +} + +/// Zero Amount changes nothing, and not by being applied and undone: the photo keeps As Shot mode and every +/// setting, through the command and the preview, even for a preset whose preparation would write Custom values. +#[test] +fn zero_amount_preset_keeps_as_shot_mode_and_settings() { + use lightcraft_catalog::{MediaKind, Op, Photo, Source}; + use lightcraft_develop::{Preset, WbMode}; + let mut s = Session::new(); + let id = s.catalog.alloc_photo_id(); + let mut p = Photo::new(id, Source::File { path: "/photos/zero.arw".into() }, "zero.arw", "ARW", 64, 64, "2026-01-01T00:00:00"); + p.kind = MediaKind::Raw; + p.meta.camera = "SONY ILCE-7M3".into(); + p.as_shot_wb = Some((4986.0, -2.0)); + p.develop = std::sync::Arc::new(p.camera_defaults()); + s.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + let preset = Preset { + id: "user.zero".into(), + name: "Zero".into(), + group: "User".into(), + settings: json!({"wb": {"temp": 5800.0}, "light": {"exposure": 1.0}}), + favorite: false, + builtin: false, + }; + s.presets.push(preset.clone()); + s.execute("library.select", &json!({"ids": [id.0], "active": id.0})).unwrap(); + let before = (*s.develop_of(id).unwrap()).clone(); + assert_eq!(before.wb.mode, WbMode::AsShot); + for amount in [0.0, -1.0, f64::NAN] { + assert_eq!(crate::presets::apply_preset_to_photo(&preset, &before, None, amount, &s.source_info(id)), before, "preview at {amount}"); + assert_eq!(s.preset_applied(id, &preset, amount).unwrap(), before, "panel preview at {amount}"); + } + s.execute("preset.apply", &json!({"id": preset.id, "amount": 0})).unwrap(); + let after = (*s.develop_of(id).unwrap()).clone(); + assert_eq!(after, before); + assert_eq!(after.wb.mode, WbMode::AsShot); +} diff --git a/crates/engine/src/tests/constrain_crop.rs b/crates/engine/src/tests/constrain_crop.rs index 9f01ed05d6..a07ad2fea7 100644 --- a/crates/engine/src/tests/constrain_crop.rs +++ b/crates/engine/src/tests/constrain_crop.rs @@ -17,7 +17,7 @@ fn fits(s: &Session) -> bool { let p = s.catalog.photo(s.active().unwrap()).unwrap(); let mut d = (*p.develop).clone(); d.geometry.constrain_crop = true; - let f = Frame::with_lens(p.width as usize, p.height as usize, &d, true, p.embedded_lens.as_ref()); + let f = Frame::with_lens(p.width as usize, p.height as usize, &d, true, p.embedded_lens.as_deref()); let (a, b) = (f.crop.rect, p.develop.crop.geometry.rect); [a.x0 - b.x0, a.y0 - b.y0, a.x1 - b.x1, a.y1 - b.y1].iter().all(|d| d.abs() < 1e-9) } diff --git a/crates/engine/src/tests/export.rs b/crates/engine/src/tests/export.rs index 4eb8faf147..6a74aab8ea 100644 --- a/crates/engine/src/tests/export.rs +++ b/crates/engine/src/tests/export.rs @@ -280,6 +280,147 @@ fn a_subfolder_never_leaves_the_destination_folder() { assert_eq!(o.subfolder, "up"); } +#[test] +fn clean_album_name_sanitizes_reserved_names_and_illegal_chars() { + use crate::export::clean_album_name; + + assert_eq!(clean_album_name("Summer 2026"), "Summer 2026"); + assert_eq!(clean_album_name("Trip: Tokyo / Kyoto * 2026?"), "Trip_ Tokyo _ Kyoto _ 2026_"); + assert_eq!(clean_album_name("..hidden.."), "hidden"); + assert_eq!(clean_album_name("..."), ""); + assert_eq!(clean_album_name(" "), ""); + // Windows reserved device names (bare and with extension, ASCII and superscript) + assert_eq!(clean_album_name("CON"), "CON_"); + assert_eq!(clean_album_name("con"), "con_"); + assert_eq!(clean_album_name("con.txt"), "con_.txt"); + assert_eq!(clean_album_name("PRN"), "PRN_"); + assert_eq!(clean_album_name("AUX"), "AUX_"); + assert_eq!(clean_album_name("NUL"), "NUL_"); + assert_eq!(clean_album_name("COM1"), "COM1_"); + assert_eq!(clean_album_name("com9"), "com9_"); + assert_eq!(clean_album_name("LPT1"), "LPT1_"); + assert_eq!(clean_album_name("lpt9"), "lpt9_"); + assert_eq!(clean_album_name("NUL.tar.gz"), "NUL_.tar.gz"); + assert_eq!(clean_album_name("COM¹"), "COM¹_"); + assert_eq!(clean_album_name("com²"), "com²_"); + assert_eq!(clean_album_name("lpt³"), "lpt³_"); + assert_eq!(clean_album_name("com¹.backup"), "com¹_.backup"); +} + +/// `{date}` and `{hour}` are the person's local date and time (the host's zone), not UTC's: an evening export west +/// of UTC, or a morning one east of it, goes to that day's folder. +#[test] +fn subfolder_date_and_hour_are_local_time() { + use crate::export::expand_subfolder; + let secs = i64::try_from(web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).unwrap().as_secs()).unwrap(); + let local = crate::import::local_civil(secs); + let expected = format!("{}/{}", local.get(..10).unwrap().replace('-', ""), local.get(11..16).unwrap().replace(':', "")); + let got = expand_subfolder("{date}/{hour}", None, None); + // (a minute may turn between the two readings) + let next = crate::import::local_civil(secs + 60); + let later = format!("{}/{}", next.get(..10).unwrap().replace('-', ""), next.get(11..16).unwrap().replace(':', "")); + assert!(got == expected || got == later, "{got} is not the local {expected}"); +} + +#[test] +fn expand_subfolder_variables_and_ordering() { + use crate::export::expand_subfolder; + + let fixed_time = chrono::NaiveDate::from_ymd_opt(2026, 11, 5).unwrap().and_hms_opt(14, 30, 0); + assert_eq!(expand_subfolder("{album}", Some("Vacation"), fixed_time), "Vacation"); + assert_eq!(expand_subfolder("{album}", None, fixed_time), ""); + assert_eq!(expand_subfolder("{date}", None, fixed_time), "20261105"); + assert_eq!(expand_subfolder("{hour}", None, fixed_time), "1430"); + assert_eq!(expand_subfolder("{album}/{date}_{hour}", Some("Portraits / 2026"), fixed_time), "Portraits _ 2026/20261105_1430"); + assert_eq!(expand_subfolder("Exports/{album}/{date}", None, fixed_time), "Exports/20261105"); + + // Token replacement order: album named literally {date} or {hour} is not double-expanded + assert_eq!(expand_subfolder("{album}", Some("{date}"), fixed_time), "{date}"); + assert_eq!(expand_subfolder("{album}/{date}", Some("{date}"), fixed_time), "{date}/20261105"); + assert_eq!(expand_subfolder("{album}/{hour}", Some("{hour}"), fixed_time), "{hour}/1430"); +} + +#[test] +fn export_presets_persist_subfolder_variables() { + let mut s = Session::with_demo(); + s.execute( + "export.savePreset", + &json!({ + "name": "Date & Album", + "params": { + "format": "jpeg", + "subfolder": "{album}/{date}_{hour}" + } + }), + ) + .unwrap(); + let loaded = s.export_params(&json!({"preset": "Date & Album"})).unwrap(); + assert_eq!(loaded["subfolder"], "{album}/{date}_{hour}"); + let opts = ExportOptions::from_json(&loaded); + assert_eq!(opts.subfolder, "{album}/{date}_{hour}"); +} + +#[test] +fn export_batch_subfolder_expansion_in_and_outside_album_view() { + use crate::export::{Destination, export_batch}; + + let mut s = Session::with_demo(); + let opts = ExportOptions::from_json(&json!({ + "format": "jpeg", + "subfolder": "{album}/{date}_{hour}" + })); + + // Export batch with active album view + let id = s.active().unwrap(); + let album_id = s.execute("album.create", &json!({"name": "Holiday: Spain", "addSelected": true})).unwrap()["id"].as_u64().unwrap(); + s.source = crate::LibrarySource::Album(lightcraft_catalog::AlbumId(album_id)); + + let to = Destination { dir: "out".into(), exact: None }; + let mut written = Vec::new(); + let mut write = |p: &str, _: &[u8]| { + written.push(p.to_string()); + Ok(()) + }; + export_batch(&mut s, &[id], &opts, &to, &mut write, &|_| false).unwrap(); + assert_eq!(written.len(), 1); + assert!(written[0].starts_with("out/Holiday_ Spain/"), "actual: {}", written[0]); + assert!(!written[0].contains("{date}"), "date not expanded: {}", written[0]); + assert!(!written[0].contains("{hour}"), "hour not expanded: {}", written[0]); + + // Multi-photo batch: verify both photos resolve date and hour, use the exact same batch timestamp + // and do not cross minute boundaries + let mut written_multi = Vec::new(); + let mut write_multi = |p: &str, _: &[u8]| { + written_multi.push(p.to_string()); + Ok(()) + }; + export_batch(&mut s, &[id, id], &opts, &to, &mut write_multi, &|_| false).unwrap(); + assert_eq!(written_multi.len(), 2); + // Both items must have identical subfolder paths + let sub0 = written_multi[0].strip_prefix("out/Holiday_ Spain/").unwrap_or(""); + let sub1 = written_multi[1].strip_prefix("out/Holiday_ Spain/").unwrap_or(""); + let dir0 = sub0.split('/').next().unwrap_or(""); + let dir1 = sub1.split('/').next().unwrap_or(""); + assert_eq!(dir0, dir1, "batch items must share the exact same timestamp subfolder"); + let (d, h) = dir0.split_once('_').unwrap_or(("", "")); + assert_eq!(d.len(), 8, "date segment must be YYYYMMDD (8 digits): {d}"); + assert_eq!(h.len(), 4, "hour segment must be HHMM (4 digits): {h}"); + assert!(d.chars().all(|c| c.is_ascii_digit()), "date must be digits: {d}"); + assert!(h.chars().all(|c| c.is_ascii_digit()), "hour must be digits: {h}"); + + // Outside album view: {album} expands to empty string, not an arbitrary first album + s.source = crate::LibrarySource::All; + let mut written_outside = Vec::new(); + let mut write_outside = |p: &str, _: &[u8]| { + written_outside.push(p.to_string()); + Ok(()) + }; + export_batch(&mut s, &[id], &opts, &to, &mut write_outside, &|_| false).unwrap(); + assert_eq!(written_outside.len(), 1); + assert!(!written_outside[0].contains("Holiday"), "outside album view should not use album name: {}", written_outside[0]); + assert!(!written_outside[0].contains("//"), "clean_subfolder prevents double slashes: {}", written_outside[0]); +} + #[test] fn prepared_exports_run_on_another_thread() { fn send(_: &T) {} diff --git a/crates/engine/src/tests/filesystem_history.rs b/crates/engine/src/tests/filesystem_history.rs index e4e150c252..94786a067b 100644 --- a/crates/engine/src/tests/filesystem_history.rs +++ b/crates/engine/src/tests/filesystem_history.rs @@ -546,3 +546,245 @@ fn merged_rename_failure_keeps_rolled_back_photo_identity() { assert_eq!(path, "/p/d.jpg", "photo 2 rolled back physically and must still identify d.jpg"); assert_eq!(files.iter().find(|(file, _)| *file == path).map(|(_, bytes)| bytes.as_str()), Some("Photo 2")); } + +/// A step of history that renames a file and then fails part-way in the catalog, with the file then refusing to go +/// back, still hands what is left of its rollback to the other stack, and the journal says what the catalog now holds. +/// (Where the file stayed is not followed: that is as it is for a step that fails whole.) +#[test] +fn a_partly_applied_step_whose_files_cannot_be_moved_back_keeps_what_is_left_of_it() { + use crate::rename::tests::FakeFs; + use lightcraft_catalog::{CatalogError, Stack}; + + for redo in [false, true] { + let store = lightcraft_catalog::MemStore::new(); + let mut s = memory_library(&store); + let fs = FakeFs::new(false, &[("/p/a.jpg", "A"), ("/p/b.jpg", "B")]); + let ops = ["/p/a.jpg", "/p/b.jpg"] + .iter() + .enumerate() + .map(|(i, path)| { + let name = std::path::Path::new(path).file_name().unwrap().to_string_lossy(); + let path = path.replace('/', std::path::MAIN_SEPARATOR_STR); + Op::AddPhoto { photo: Box::new(Photo::new(PhotoId(i as u64 + 1), Source::File { path }, &name, "JPEG", 16, 16, "")) } + }) + .collect(); + s.commit("Photos", Op::Batch { ops }).unwrap(); + let stack = s.catalog.alloc_stack_id(); + s.commit("Stack", Op::AddStack { stack: Stack { id: stack, photos: vec![PhotoId(1), PhotoId(2)], collapsed: false } }).unwrap(); + s.persist().unwrap(); + s.undo.clear(); + // the file is renamed, the photo and its stack go, and an op fails: the stack cannot be put back before its photo + let renamed = "/p/renamed.jpg".replace('/', std::path::MAIN_SEPARATOR_STR); + let step = Op::Batch { + ops: vec![ + Op::SetFile { id: PhotoId(1), file_name: "renamed.jpg".into(), source: Source::File { path: renamed } }, + Op::RemovePhoto { id: PhotoId(2) }, + Op::RemoveStack { id: stack }, + Op::SetRating { id: PhotoId(9_999), rating: 1 }, + ], + }; + let entry = crate::UndoEntry { label: "Broken".into(), op: step, folder: None, retry_inverse: Vec::new(), retry_sidecars: Vec::new() }; + if redo { + s.redo.push(entry); + } else { + s.undo.push(entry); + } + // the file goes forward and then refuses to come back + *fs.fail.borrow_mut() = vec!["renamed.jpg".into()]; + let error = file_history_step(&mut s, &fs, redo).unwrap_err(); + assert!(matches!(&error, crate::EngineError::Catalog(CatalogError::PartlyApplied { .. })), "{error:?}"); + assert!(error.to_string().contains("could not all be moved back"), "{error}"); + let (this, other) = if redo { (&s.redo, &s.undo) } else { (&s.undo, &s.redo) }; + assert_eq!((this.len(), other.len()), (0, 1), "what is left of the step goes to the other stack"); + let torn = s.catalog.to_snapshot(); + let replayed = { + let mut again = memory_library(&store); + again.persist().unwrap(); + again.catalog.to_snapshot() + }; + assert_eq!(replayed, torn, "the journal and the memory agree"); + } +} + +/// A photo whose old file name is empty cannot be put back by `SetFile` (it refuses an empty name), so a rename that +/// fails part-way leaves that inverse in what is left of the rollback. The files are back where they were by then, so +/// the step that finishes the rollback points the photo at them and moves nothing. +#[test] +fn what_is_left_of_a_rollback_moves_no_file_that_is_already_back() { + use crate::rename::tests::FakeFs; + use lightcraft_catalog::CatalogError; + + let sep = |p: &str| p.replace('/', std::path::MAIN_SEPARATOR_STR); + let photo = |id: u64, path: &str, name: &str| Photo::new(PhotoId(id), Source::File { path: sep(path) }, name, "JPEG", 16, 16, ""); + + // through an Undo whose catalog part fails after the file went + for redo in [false, true] { + let store = lightcraft_catalog::MemStore::new(); + let mut s = memory_library(&store); + let fs = FakeFs::new(false, &[("/p/a.jpg", "A")]); + s.commit("Photo", Op::AddPhoto { photo: Box::new(photo(1, "/p/a.jpg", "")) }).unwrap(); + s.undo.clear(); + let step = Op::Batch { + ops: vec![ + Op::SetFile { id: PhotoId(1), file_name: "b.jpg".into(), source: Source::File { path: sep("/p/b.jpg") } }, + Op::SetRating { id: PhotoId(9_999), rating: 1 }, + ], + }; + let entry = crate::UndoEntry { label: "Broken".into(), op: step, folder: None, retry_inverse: Vec::new(), retry_sidecars: Vec::new() }; + if redo { + s.redo.push(entry); + } else { + s.undo.push(entry); + } + let error = file_history_step(&mut s, &fs, redo).unwrap_err(); + assert!(matches!(&error, crate::EngineError::Catalog(CatalogError::PartlyApplied { .. })), "{error:?}"); + assert_eq!(fs.listing(), vec![("/p/a.jpg".to_string(), "A".to_string())], "the file went and came back"); + // finishing the rollback, the other way, must not look for the file at the new path + file_history_step(&mut s, &fs, !redo).unwrap(); + assert_eq!(fs.listing(), vec![("/p/a.jpg".to_string(), "A".to_string())]); + assert_eq!(file_source(&s, 1), "/p/a.jpg"); + } +} + +/// The same for a rename whose catalog part fails after the files went (see the test above). +#[test] +fn what_is_left_of_a_failed_rename_moves_no_file_that_is_already_back() { + use crate::rename::tests::FakeFs; + use lightcraft_catalog::CatalogError; + + let sep = |p: &str| p.replace('/', std::path::MAIN_SEPARATOR_STR); + let photo = |id: u64, path: &str, name: &str| Photo::new(PhotoId(id), Source::File { path: sep(path) }, name, "JPEG", 16, 16, ""); + let store = lightcraft_catalog::MemStore::new(); + let mut s = memory_library(&store); + let fs = FakeFs::new(false, &[("/p/a.jpg", "A"), ("/p/c.jpg", "C")]); + s.commit( + "Photos", + Op::Batch { + ops: vec![Op::AddPhoto { photo: Box::new(photo(1, "/p/a.jpg", "")) }, Op::AddPhoto { photo: Box::new(photo(2, "/p/c.jpg", "c.jpg")) }], + }, + ) + .unwrap(); + s.undo.clear(); + let plan = |id: u64, from: &str, to: &str, from_path: &str, to_path: &str| crate::rename::RenamePlan { + id, + from: from.into(), + to: to.into(), + from_path: Some(sep(from_path)), + to_path: Some(sep(to_path)), + }; + // the second photo's new name is empty, which the catalog refuses + let plans = [plan(1, "", "b.jpg", "/p/a.jpg", "/p/b.jpg"), plan(2, "c.jpg", "", "/p/c.jpg", "/p/d.jpg")]; + let before = fs.listing(); + let error = s.apply_rename_with(&fs, &plans).unwrap_err(); + assert!(matches!(&error, crate::EngineError::Catalog(CatalogError::PartlyApplied { .. })), "{error:?}"); + assert_eq!(fs.listing(), before, "the files are back"); + file_history_step(&mut s, &fs, false).unwrap(); + assert_eq!(fs.listing(), before); + assert_eq!(file_source(&s, 1), "/p/a.jpg"); +} + +/// The files go, the catalog fails on a later op and cannot put three photos back (each has an empty old file name, which +/// `SetFile` refuses), then the files are moved back and one of the moves fails while undoing the move before it fails +/// too: the first file stays back, the others stay where they went. What is left of the rollback must follow each file. +fn three_photos_whose_old_names_are_empty(redo: bool, through_rename: bool) { + use crate::rename::tests::FakeFs; + let sep = |p: &str| p.replace('/', std::path::MAIN_SEPARATOR_STR); + let store = lightcraft_catalog::MemStore::new(); + let mut s = memory_library(&store); + let fs = FakeFs::new(false, &[("/p/a.jpg", "A"), ("/p/c.jpg", "C"), ("/p/e.jpg", "E")]); + let ops = [("/p/a.jpg", 1), ("/p/c.jpg", 2), ("/p/e.jpg", 3)] + .iter() + .map(|(path, id)| Op::AddPhoto { photo: Box::new(Photo::new(PhotoId(*id), Source::File { path: sep(path) }, "", "JPEG", 16, 16, "")) }) + .chain(std::iter::once(Op::AddPhoto { + photo: Box::new(Photo::new(PhotoId(4), Source::File { path: sep("/p/g.jpg") }, "g.jpg", "JPEG", 16, 16, "")), + })) + .collect(); + s.commit("Photos", Op::Batch { ops }).unwrap(); + s.undo.clear(); + // calls 0 to 2 move the files; then the first move back works, the second fails and undoing the first fails too + *fs.fail_renames.borrow_mut() = vec![4, 5]; + let error = if through_rename { + // the fourth photo's new name is empty, which the catalog refuses + let plan = |id: u64, from: &str, to: &str, from_path: &str, to_path: &str| crate::rename::RenamePlan { + id, + from: from.into(), + to: to.into(), + from_path: Some(sep(from_path)), + to_path: Some(sep(to_path)), + }; + let plans = [ + plan(1, "", "b.jpg", "/p/a.jpg", "/p/b.jpg"), + plan(2, "", "d.jpg", "/p/c.jpg", "/p/d.jpg"), + plan(3, "", "f.jpg", "/p/e.jpg", "/p/f.jpg"), + plan(4, "g.jpg", "", "/p/g.jpg", "/p/g.jpg"), + ]; + s.apply_rename_with(&fs, &plans).unwrap_err() + } else { + let to = |name: &str| Source::File { path: sep(&format!("/p/{name}")) }; + let step = Op::Batch { + ops: vec![ + Op::SetFile { id: PhotoId(1), file_name: "b.jpg".into(), source: to("b.jpg") }, + Op::SetFile { id: PhotoId(2), file_name: "d.jpg".into(), source: to("d.jpg") }, + Op::SetFile { id: PhotoId(3), file_name: "f.jpg".into(), source: to("f.jpg") }, + Op::SetRating { id: PhotoId(9_999), rating: 1 }, + ], + }; + let entry = crate::UndoEntry { label: "Broken".into(), op: step, folder: None, retry_inverse: Vec::new(), retry_sidecars: Vec::new() }; + if redo { + s.redo.push(entry); + } else { + s.undo.push(entry); + } + file_history_step(&mut s, &fs, redo).unwrap_err() + }; + let moved = |list: Vec<(String, String)>| list.into_iter().map(|(p, _)| p).collect::>(); + assert_eq!(moved(fs.listing()), ["/p/b.jpg", "/p/d.jpg", "/p/e.jpg"], "two files stayed where they went, one is back: {error}"); + assert!(error.to_string().contains("could not all be moved back"), "{error}"); + // what is left of the rollback follows every file where it is: the one that went back points at it, the others still move + let step = if through_rename || redo { s.undo.last() } else { s.redo.last() }; + let Some(Op::Batch { ops }) = step.map(|e| e.op.clone()) else { panic!("what is left is a batch") }; + let kinds: Vec<(&str, u64)> = ops + .iter() + .map(|op| match op { + Op::Relink { id, .. } => ("relink", id.0), + Op::SetFile { id, .. } => ("move", id.0), + other => panic!("unexpected {other:?}"), + }) + .collect(); + assert_eq!(kinds, [("relink", 3), ("move", 2), ("move", 1)], "{ops:?}"); +} + +#[test] +fn what_is_left_of_a_rollback_follows_each_file_as_far_as_it_went_back() { + three_photos_whose_old_names_are_empty(false, false); + three_photos_whose_old_names_are_empty(true, false); +} + +#[test] +fn what_is_left_of_a_failed_rename_follows_each_file_as_far_as_it_went_back() { + three_photos_whose_old_names_are_empty(false, true); +} + +/// The files of a rename moved, then the catalog refused the change, then moving them back failed for the photo and +/// stranded a sidecar: the sidecar's repair is kept (the next rename or a retry puts it back), not dropped with the +/// error text. +#[test] +fn a_refused_rename_whose_files_cannot_all_go_back_keeps_the_stranded_sidecar_repair() { + use crate::rename::tests::FakeFs; + let store = lightcraft_catalog::MemStore::new(); + let mut s = memory_library(&store); + let fs = FakeFs::new(false, &[("/p/a.jpg", "Photo"), ("/p/a.xmp", "Edits")]); + let photo = Photo::new(PhotoId(1), Source::File { path: "/p/a.jpg".into() }, "a.jpg", "JPEG", 16, 16, ""); + s.commit("Synthetic File", Op::AddPhoto { photo: Box::new(photo) }).unwrap(); + s.persist().unwrap(); + s.undo.clear(); + select(&mut s, &[1], 1); + let mut plans = s.plan_rename_with(&fs, &[PhotoId(1)], "Trip", 1); + // the catalog refuses an empty file name, after the files moved (renames 0: the photo, 1: its sidecar) + plans[0].to = String::new(); + // moving back: the photo goes (2), its sidecar can't (3), and the photo can't be put where it was (4) + *fs.fail_renames.borrow_mut() = vec![3, 4]; + let error = slash(&s.apply_rename_with(&fs, &plans).unwrap_err().to_string()); + assert!(error.contains("the renamed files could not all be moved back"), "{error}"); + assert_eq!(s.pending_sidecar_repairs.len(), 1, "the stranded sidecar is kept for a repair: {error}"); +} diff --git a/crates/engine/src/tests/folders.rs b/crates/engine/src/tests/folders.rs index 6877572768..bbfc7369ee 100644 --- a/crates/engine/src/tests/folders.rs +++ b/crates/engine/src/tests/folders.rs @@ -16,6 +16,7 @@ use lightcraft_catalog::{Op, Photo, Source}; use serde_json::json; +use std::path::Path; use crate::{LibrarySource, Session, filter_chips}; @@ -702,6 +703,287 @@ fn a_destination_without_write_permission_reports_an_error_and_keeps_everything( std::fs::set_permissions(dir.0.join("ro"), std::fs::Permissions::from_mode(0o755)).unwrap(); } +#[test] +fn a_date_folder_inside_the_library_can_be_renamed_but_the_librarys_own_folders_cannot() { + let dir = Scratch::new("in-library"); + let lib = dir.0.join("lib"); + let mut s = Session::new(); + s.open_library(&lib, false).unwrap(); + let day = lib.join("Originals").join("2026-10-16"); + std::fs::create_dir_all(&day).unwrap(); + let photo = day.join("a.jpg"); + std::fs::write(&photo, b"jpeg").unwrap(); + add(&mut s, &photo.to_string_lossy()); + let paths = |s: &Session| -> Vec { + s.catalog + .photos() + .filter_map(|p| match &p.source { + Source::File { path } => Some(path.clone()), + _ => None, + }) + .collect() + }; + let day = day.to_string_lossy().to_string(); + let r = s.execute("folder.rename", &json!({"path": day, "name": "Beach"})).unwrap(); + assert_eq!(r["relinked"], 1, "the photo inside is relinked"); + assert!(lib.join("Originals/Beach").is_dir(), "the imported date folder is renamed"); + assert!(!Path::new(&day).exists()); + let moved = lib.join("Originals").join("Beach").join("a.jpg"); + assert_eq!(paths(&s), [moved.to_string_lossy().to_string()], "the catalog follows the photo"); + assert!(moved.is_file()); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(Path::new(&day).is_dir(), "undo names it back"); + assert_eq!(paths(&s), [photo.to_string_lossy().to_string()], "and points the photo back, in one step"); + assert!(photo.is_file()); + for own in ["Originals", "thumbs"] { + std::fs::create_dir_all(lib.join(own)).unwrap(); + let path = lib.join(own).to_string_lossy().to_string(); + assert!(s.execute("folder.rename", &json!({"path": path, "name": "x"})).is_err(), "{own} stays put"); + } + assert!(s.execute("folder.rename", &json!({"path": lib.to_string_lossy(), "name": "x"})).is_err(), "and so does the library"); + let alias = lib.join("Originals").join("..").join("Originals").to_string_lossy().to_string(); + assert!(s.execute("folder.rename", &json!({"path": alias, "name": "x"})).is_err(), "even named through '..'"); + assert!(lib.join("Originals").is_dir()); +} + +/// A date folder inside the library named through a link to the library would move on disk while its photos, +/// stored under the library's own path, kept pointing at the old folder: it is refused and nothing moves. +#[cfg(unix)] +#[test] +fn a_folder_inside_the_library_named_through_a_link_is_refused_and_its_photos_keep_their_paths() { + let dir = Scratch::new("in-library-link"); + let lib = dir.0.join("lib"); + let mut s = Session::new(); + s.open_library(&lib, false).unwrap(); + let day = lib.join("Originals").join("2026-10-16"); + std::fs::create_dir_all(&day).unwrap(); + let photo = day.join("a.jpg").to_string_lossy().to_string(); + std::fs::write(&photo, b"jpeg").unwrap(); + add(&mut s, &photo); + std::os::unix::fs::symlink(&lib, dir.0.join("lib-link")).unwrap(); + let linked = dir.0.join("lib-link").join("Originals").join("2026-10-16").to_string_lossy().to_string(); + assert!(s.execute("folder.rename", &json!({"path": linked, "name": "Beach"})).is_err(), "a linked spelling is refused"); + assert!(day.is_dir() && !lib.join("Originals/Beach").exists(), "nothing moved on disk"); + let paths: Vec<_> = s + .catalog + .photos() + .filter_map(|p| match &p.source { + Source::File { path } => Some(path.clone()), + _ => None, + }) + .collect(); + assert!(paths.iter().all(|p| Path::new(p).exists()), "every photo still points at a file: {paths:?}"); +} + +/// A date folder inside the library named with only letter case changed is the library's own spelling: +/// it can be renamed and its photos are relinked under the library's path. On a case-sensitive volume +/// the flipped path is not a folder, so the command is not reached; the spelling check itself is +/// covered by `a_path_that_differs_only_in_letter_case_is_the_librarys_spelling`. +#[test] +fn a_date_folder_named_with_different_letter_case_can_be_renamed() { + let dir = Scratch::new("in-library-case"); + let lib = dir.0.join("lib"); + let mut s = Session::new(); + s.open_library(&lib, false).unwrap(); + let day = lib.join("Originals").join("2026-10-16"); + std::fs::create_dir_all(&day).unwrap(); + let photo = day.join("a.jpg"); + std::fs::write(&photo, b"jpeg").unwrap(); + add(&mut s, &photo.to_string_lossy()); + let flipped = dir.0.join("LIB").join("Originals").join("2026-10-16"); + if !flipped.is_dir() { + // case-sensitive volume: this path is not the library folder, so the #3016 refusal does not arise + assert!(!Path::new(&flipped).starts_with(&lib) || flipped == day); + return; + } + let r = s.execute("folder.rename", &json!({"path": flipped.to_string_lossy(), "name": "Beach"})).unwrap(); + assert_eq!(r["relinked"], 1, "the photo inside is relinked"); + let moved = lib.join("Originals").join("Beach").join("a.jpg"); + assert!(moved.is_file(), "renamed on disk under the library's own spelling"); + let paths: Vec<_> = s + .catalog + .photos() + .filter_map(|p| match &p.source { + Source::File { path } => Some(path.clone()), + _ => None, + }) + .collect(); + assert_eq!(paths, [moved.to_string_lossy().to_string()], "the catalog uses the library's spelling, not the flipped case"); + assert_eq!(r["path"], moved.parent().unwrap().to_string_lossy().as_ref(), "the returned path also uses the library's spelling"); +} + +/// A link whose name is only a case change of the library folder is still a link: refused, nothing moves. +#[cfg(unix)] +#[test] +fn a_folder_named_through_a_link_that_differs_only_in_letter_case_is_still_refused() { + let dir = Scratch::new("in-library-case-link"); + let lib = dir.0.join("lib"); + let mut s = Session::new(); + s.open_library(&lib, false).unwrap(); + let day = lib.join("Originals").join("2026-10-16"); + std::fs::create_dir_all(&day).unwrap(); + let photo = day.join("a.jpg").to_string_lossy().to_string(); + std::fs::write(&photo, b"jpeg").unwrap(); + add(&mut s, &photo); + // on a case-insensitive volume this name is the library folder itself, so there is no separate link to refuse + if dir.0.join("LIB").exists() { + return; + } + std::os::unix::fs::symlink(&lib, dir.0.join("LIB")).unwrap(); + let linked = dir.0.join("LIB").join("Originals").join("2026-10-16").to_string_lossy().to_string(); + assert!(s.execute("folder.rename", &json!({"path": linked, "name": "Beach"})).is_err(), "a case-variant link is still refused"); + assert!(day.is_dir() && !lib.join("Originals/Beach").exists(), "nothing moved on disk"); + let paths: Vec<_> = s + .catalog + .photos() + .filter_map(|p| match &p.source { + Source::File { path } => Some(path.clone()), + _ => None, + }) + .collect(); + assert!(paths.iter().all(|p| Path::new(p).exists()), "every photo still points at a file: {paths:?}"); +} + +/// On a case-sensitive volume, a destination named like the library with only letter case changed +/// can be a different folder: a move into it must not be rewritten into the open library. +#[test] +fn a_destination_whose_name_differs_only_in_letter_case_is_left_alone_when_it_is_another_folder() { + let dir = Scratch::new("dest-other-case"); + let lib = dir.0.join("lib"); + let other = dir.0.join("LIB"); + let mut s = Session::new(); + s.open_library(&lib, false).unwrap(); + if other.exists() { + // the volume treats lib and LIB as one folder: the distinct-directory case does not arise + return; + } + std::fs::create_dir_all(&other).unwrap(); + std::fs::create_dir_all(dir.0.join("work/Trip")).unwrap(); + let photo = dir.0.join("work/Trip/a.jpg"); + std::fs::write(&photo, b"jpeg").unwrap(); + add(&mut s, &photo.to_string_lossy()); + s.execute("folder.move", &json!({"path": dir.path("work/Trip"), "into": other.to_string_lossy()})).unwrap(); + assert!(other.join("Trip").is_dir(), "the folder moved into the destination as given"); + assert!(!lib.join("Trip").exists(), "it was not rewritten into the open library"); +} + +/// Imports keep the path as given, so a photo may be stored under a flipped library prefix. Renaming +/// the date folder still relinks it, and a browsed path that used that prefix follows too. +#[test] +fn a_photo_stored_under_a_differently_cased_library_path_is_relinked() { + let dir = Scratch::new("catalog-case"); + let lib = dir.0.join("lib"); + let mut s = Session::new(); + s.open_library(&lib, false).unwrap(); + let day = lib.join("Originals").join("2026-10-16"); + std::fs::create_dir_all(&day).unwrap(); + let photo = day.join("a.jpg"); + std::fs::write(&photo, b"jpeg").unwrap(); + let flipped_photo = dir.0.join("LIB").join("Originals").join("2026-10-16").join("a.jpg"); + add(&mut s, &flipped_photo.to_string_lossy()); + s.browse = Some(crate::Browse { path: dir.0.join("LIB").join("Originals").join("2026-10-16").to_string_lossy().to_string(), subfolders: false }); + let r = s.execute("folder.rename", &json!({"path": day.to_string_lossy(), "name": "Beach"})).unwrap(); + assert_eq!(r["relinked"], 1, "the photo stored under the flipped spelling is relinked"); + let moved = lib.join("Originals").join("Beach").join("a.jpg"); + let paths: Vec<_> = s + .catalog + .photos() + .filter_map(|p| match &p.source { + Source::File { path } => Some(path.clone()), + _ => None, + }) + .collect(); + assert_eq!(paths, [moved.to_string_lossy().to_string()], "the catalog path uses the library's spelling"); + assert!(moved.is_file()); + assert_eq!( + s.browse.as_ref().expect("browse follows").path, + moved.parent().unwrap().to_string_lossy().as_ref(), + "the browsed folder follows the resolved path" + ); +} + +/// A distinct folder whose name only differs in letter case, with a link below it into the library, +/// must not be rewritten as the library's own path. Otherwise renaming it would move the real folder. +#[cfg(unix)] +#[test] +fn a_folder_reached_through_a_link_below_a_case_distinct_prefix_is_still_refused() { + let dir = Scratch::new("link-below-case-prefix"); + let lib = dir.0.join("lib"); + let mut s = Session::new(); + s.open_library(&lib, false).unwrap(); + let day = lib.join("Originals").join("2026-10-16"); + std::fs::create_dir_all(&day).unwrap(); + let photo = day.join("a.jpg"); + std::fs::write(&photo, b"jpeg").unwrap(); + add(&mut s, &photo.to_string_lossy()); + let other = dir.0.join("LIB"); + if other.exists() { + // the volume treats lib and LIB as one folder: the distinct-directory case does not arise + return; + } + std::fs::create_dir_all(&other).unwrap(); + std::os::unix::fs::symlink(lib.join("Originals"), other.join("Originals")).unwrap(); + let linked = other.join("Originals").join("2026-10-16").to_string_lossy().to_string(); + let err = s.execute("folder.rename", &json!({"path": linked, "name": "Beach"})).unwrap_err().to_string(); + assert!(err.contains("give the folder's path inside the library"), "{err}"); + assert!(day.is_dir() && !lib.join("Originals").join("Beach").exists(), "the library folder was not renamed"); + let paths: Vec<_> = s + .catalog + .photos() + .filter_map(|p| match &p.source { + Source::File { path } => Some(path.clone()), + _ => None, + }) + .collect(); + assert_eq!(paths, [photo.to_string_lossy().to_string()], "the catalog path is unchanged"); +} + +/// On a case-sensitive volume, `trip` and `Trip` are different folders. Renaming one outside the +/// library must not relink a photo in the other, or follow a browse of it. +#[test] +fn a_folder_that_differs_only_in_letter_case_is_left_alone_when_it_is_outside_the_library() { + let dir = Scratch::new("outside-case"); + let lib = dir.0.join("lib"); + let mut s = Session::new(); + s.open_library(&lib, false).unwrap(); + let trip = dir.0.join("work/trip"); + let trip_cap = dir.0.join("work/Trip"); + std::fs::create_dir_all(&trip).unwrap(); + if trip_cap.exists() { + // the volume treats trip and Trip as one folder: the distinct-directory case does not arise + return; + } + std::fs::create_dir_all(&trip_cap).unwrap(); + let photo = trip.join("a.jpg"); + std::fs::write(&photo, b"jpeg").unwrap(); + add(&mut s, &photo.to_string_lossy()); + let other = trip_cap.join("b.jpg"); + std::fs::write(&other, b"jpeg").unwrap(); + add(&mut s, &other.to_string_lossy()); + s.browse = Some(crate::Browse { path: trip.to_string_lossy().to_string(), subfolders: false }); + s.execute("folder.rename", &json!({"path": trip_cap.to_string_lossy(), "name": "Beach"})).unwrap(); + let mut paths: Vec<_> = s + .catalog + .photos() + .filter_map(|p| match &p.source { + Source::File { path } => Some(path.clone()), + _ => None, + }) + .collect(); + paths.sort(); + let moved = dir.0.join("work").join("Beach").join("b.jpg"); + let mut expected = vec![photo.to_string_lossy().to_string(), moved.to_string_lossy().to_string()]; + expected.sort(); + assert_eq!(paths, expected, "the photo in trip stays; only the renamed folder is relinked"); + assert!(photo.is_file()); + assert!(moved.is_file()); + assert_eq!( + s.browse.as_ref().expect("browse stays on trip").path, + trip.to_string_lossy().as_ref(), + "browsing trip is unchanged when a distinct Trip folder is renamed" + ); +} + #[cfg(unix)] #[test] fn the_library_folder_is_protected_however_its_path_is_spelled() { diff --git a/crates/engine/src/tests/import.rs b/crates/engine/src/tests/import.rs index a9ef56ebe2..e8d6772427 100644 --- a/crates/engine/src/tests/import.rs +++ b/crates/engine/src/tests/import.rs @@ -20,16 +20,25 @@ fn temp_dir(tag: &str) -> std::path::PathBuf { d } +/// The clock these tests run on; an undated file is pinned to it too (see `write_png`). +const CLOCK: &str = "2026-01-14T05:58:48"; + /// A small procedural PNG (distinct per seed). fn write_png(path: &Path, seed: u8) { - let (w, h) = (48usize, 32usize); + write_png_sized(path, seed, 48, 32); +} + +/// [`write_png`] of another size: a replaced file is noticed by its size, as probes kept from a scan are. +fn write_png_sized(path: &Path, seed: u8, w: usize, h: usize) { let data: Vec<[u8; 4]> = (0..w * h).map(|i| [(i % w * 5) as u8, (i / w * 7) as u8, seed, 255]).collect(); let img = lightcraft_raster::Rgba8 { width: w, height: h, data }; let bytes = lightcraft_codecs::encode_png(&lightcraft_codecs::EncodeImage::rgba8(&img), &lightcraft_codecs::EncodeMeta::default()).unwrap(); std::fs::create_dir_all(path.parent().unwrap()).unwrap(); std::fs::write(path, bytes).unwrap(); - // undated files take the file's date: the tests' clock time (2026-01-14T05:58:48) - let t = std::time::UNIX_EPOCH + std::time::Duration::from_secs(1_768_370_328); + // Undated files take the file's date, read in the host's zone (issue #2284), so the file is + // pinned to the instant this machine reads as the tests' clock time rather than to a fixed one. + let secs = crate::import::local_instant(CLOCK).and_then(|s| u64::try_from(s).ok()).unwrap_or(0); + let t = std::time::UNIX_EPOCH + std::time::Duration::from_secs(secs); std::fs::File::options().write(true).open(path).unwrap().set_modified(t).unwrap(); } @@ -57,7 +66,8 @@ fn write_png_with_metadata(path: &Path, seed: u8, exif: Option<&[u8]>, xmp: Opti std::fs::create_dir_all(path.parent().unwrap()).unwrap(); std::fs::write(path, bytes).unwrap(); // Keep the same known file-date fallback as write_png, distinct from the regression timestamp. - let t = std::time::UNIX_EPOCH + std::time::Duration::from_secs(1_768_370_328); + let secs = crate::import::local_instant(CLOCK).and_then(|s| u64::try_from(s).ok()).unwrap_or(0); + let t = std::time::UNIX_EPOCH + std::time::Duration::from_secs(secs); std::fs::File::options().write(true).open(path).unwrap().set_modified(t).unwrap(); } @@ -86,6 +96,383 @@ fn recursive_discovery_includes_sony_sr2_and_srf_case_insensitively() { std::fs::remove_dir_all(src).unwrap(); } +/// A file that was only browsed (Local) is not "already in the library": the scan offers it, and +/// importing it brings the browsed record (with its edits) into the library. +#[test] +fn a_browsed_photos_own_file_is_offered_and_joins_the_library_when_imported() { + let src = temp_dir("browsed-own"); + let f = src.join("a.png"); + write_png(&f, 75); + let mut s = Session::new().with_fs(); + let r = s.execute("library.import", &json!({"paths": [f], "local": true})).unwrap(); + let id = r["imported"][0].as_u64().unwrap(); + s.execute("photo.rate", &json!({"ids": [id], "rating": 3})).unwrap(); + let scan = s.execute("library.importPreview", &json!({"paths": [f]})).unwrap(); + assert_eq!(scan["duplicates"], 0, "{scan}"); + assert_eq!(scan["candidates"][0]["duplicate"], Value::Null, "{scan}"); + assert_eq!(scan["candidates"][0]["existing"], id, "the candidate still names the browsed record: {scan}"); + assert_eq!(scan["candidates"][0]["local"], true, "and says it was only browsed: {scan}"); + let r = s.execute("library.import", &json!({"paths": [f]})).unwrap(); + assert_eq!(r["imported"], json!([id]), "{r}"); + let p = s.catalog.photo(lightcraft_catalog::PhotoId(id)).unwrap(); + assert!(!p.local && p.rating == 3, "the same record, now in the library, edits kept"); + let scan = s.execute("library.importPreview", &json!({"paths": [f]})).unwrap(); + assert_eq!(scan["duplicates"], 1, "now it is in the library: {scan}"); + let _ = std::fs::remove_dir_all(src); +} + +/// A browse record in Recently Deleted still counts as the path's: the scan lists the file as it did, +/// not as a new browsed file. +#[test] +fn a_deleted_browse_record_still_counts_as_the_files_own() { + let src = temp_dir("browsed-deleted"); + let f = src.join("a.png"); + write_png(&f, 76); + let mut s = Session::new().with_fs(); + let r = s.execute("library.import", &json!({"paths": [f], "local": true})).unwrap(); + let id = r["imported"][0].as_u64().unwrap(); + s.execute("photo.delete", &json!({"ids": [id]})).unwrap(); + let scan = s.execute("library.importPreview", &json!({"paths": [f]})).unwrap(); + assert_eq!(scan["candidates"][0]["duplicate"], "path", "{scan}"); + assert_eq!(scan["candidates"][0].get("local"), None, "{scan}"); + let _ = std::fs::remove_dir_all(src); +} + +/// A browsed file that another application replaced since (it has another size) is not what its record says: the scan +/// reads it again, so the content stored at the browse (the old file's, which the library also has) doesn't make it a +/// duplicate, and importing it brings the record up to date as it joins the library. +#[test] +fn a_browsed_file_replaced_since_is_read_again_before_it_joins_the_library() { + let src = temp_dir("browsed-replaced"); + let (a, b) = (src.join("a.png"), src.join("b.png")); + write_png(&a, 75); + std::fs::copy(&a, &b).unwrap(); + let mut s = Session::new().with_fs(); + // b is in the library; a was only browsed, with the same bytes + s.execute("library.import", &json!({"paths": [b]})).unwrap(); + let r = s.execute("library.import", &json!({"paths": [a], "local": true})).unwrap(); + let id = r["imported"][0].as_u64().unwrap(); + let old = s.catalog.photo(lightcraft_catalog::PhotoId(id)).unwrap().content_hash.clone(); + let scan = s.execute("library.importPreview", &json!({"paths": [a]})).unwrap(); + assert_eq!(scan["candidates"][0]["duplicate"], "content", "the file is what was browsed, and the library has its bytes: {scan}"); + write_png_sized(&a, 9, 64, 40); + let scan = s.execute("library.importPreview", &json!({"paths": [a]})).unwrap(); + assert!(scan["candidates"][0]["duplicate"].is_null(), "the file that is there now is new to the library: {scan}"); + assert_eq!(scan["candidates"][0]["width"], 64, "{scan}"); + assert_eq!(scan["candidates"][0]["local"], true, "it still says it was only browsed (Copy and Move leave it out): {scan}"); + assert_eq!(scan["candidates"][0]["existing"], id, "and names the record: {scan}"); + let r = s.execute("library.import", &json!({"paths": [a]})).unwrap(); + assert_eq!(r["imported"], json!([id]), "the same record joins the library: {r}"); + let p = s.catalog.photo(lightcraft_catalog::PhotoId(id)).unwrap(); + assert!(!p.local, "it is in the library now"); + assert_eq!((p.width, p.height, p.file_size), (64, 40, std::fs::metadata(&a).unwrap().len()), "the record describes the file it has now"); + assert_ne!(p.content_hash, old, "and holds its content, not the old file's"); + let _ = std::fs::remove_dir_all(src); +} + +/// A browsed file replaced by a copy of a photo the library has is a duplicate of that photo, and its record stays +/// browsed. +#[test] +fn a_browsed_file_replaced_by_a_copy_of_a_library_photo_is_a_duplicate() { + let src = temp_dir("browsed-replaced-dup"); + let (a, c) = (src.join("a.png"), src.join("c.png")); + write_png(&a, 75); + write_png_sized(&c, 9, 64, 40); + let mut s = Session::new().with_fs(); + let r = s.execute("library.import", &json!({"paths": [c]})).unwrap(); + let library_id = r["imported"][0].as_u64().unwrap(); + let r = s.execute("library.import", &json!({"paths": [a], "local": true})).unwrap(); + let id = r["imported"][0].as_u64().unwrap(); + std::fs::copy(&c, &a).unwrap(); + let scan = s.execute("library.importPreview", &json!({"paths": [a]})).unwrap(); + assert_eq!(scan["candidates"][0]["duplicate"], "content", "{scan}"); + assert_eq!(scan["candidates"][0]["existing"], library_id, "of the library's photo: {scan}"); + assert_eq!(scan["candidates"][0]["local"], true, "it is still the browsed record's file (Copy and Move leave it out): {scan}"); + let r = s.execute("library.import", &json!({"paths": [a]})).unwrap(); + assert_eq!(ids(&r, "imported"), 0, "{r}"); + assert_eq!(r["duplicates"][0]["existing"], library_id, "{r}"); + assert!(s.catalog.photo(lightcraft_catalog::PhotoId(id)).unwrap().local, "the record was not brought in"); + let _ = std::fs::remove_dir_all(src); +} + +/// ✕ while the sizes of browsed files are checked: a file that wasn't checked is not promoted (it stays a browsed record), +/// where the check used to run for every file whatever the ✕ said. +#[test] +fn a_cancelled_import_does_not_promote_a_browsed_file_it_did_not_check() { + use crate::import::{ImportJob, ImportOptions, commit_prepared}; + let src = temp_dir("browsed-cancel-import"); + let a = src.join("a.png"); + write_png(&a, 75); + let mut s = Session::new().with_fs(); + let r = s.execute("library.import", &json!({"paths": [a], "local": true})).unwrap(); + let id = r["imported"][0].as_u64().unwrap(); + let mut job = ImportJob::new(&mut s, ImportOptions::default()).unwrap(); + let cancel = std::sync::atomic::AtomicBool::new(true); + let prepared = job.prepare(&[a.to_string_lossy().to_string()], &cancel); + let report = commit_prepared(&mut s, &job.opts, job.now(), prepared).unwrap(); + assert!(report.imported.is_empty() && report.duplicates.is_empty(), "nothing was decided about the file: {report:?}"); + assert!(s.catalog.photo(lightcraft_catalog::PhotoId(id)).unwrap().local, "the record is still only browsed"); + let _ = std::fs::remove_dir_all(src); +} + +/// ✕ while a scan checks the sizes of browsed files: a file that wasn't checked is not offered as the record's own (it is +/// one of the files the scan didn't reach, like the ones after it). +#[test] +fn a_cancelled_scan_does_not_vouch_for_a_browsed_file_it_did_not_check() { + use crate::import::{ScanInput, ScanProgress, scan_with}; + let src = temp_dir("browsed-cancel-scan"); + let a = src.join("a.png"); + write_png(&a, 75); + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [a], "local": true})).unwrap(); + let (input, paths) = ScanInput::new(&mut s, &[a.to_string_lossy().to_string()]); + let progress = ScanProgress::default(); + progress.cancel.store(true, std::sync::atomic::Ordering::Relaxed); + let out = scan_with(input, &paths, &progress); + assert_eq!(out.candidates.len(), 1); + assert!(!out.candidates[0].local && out.candidates[0].error.is_some(), "not vouched for as the browsed record's file: {:?}", out.candidates[0]); + let _ = std::fs::remove_dir_all(src); +} + +/// A file of its own with the new content of a replaced browsed file stands in for it when copying leaves it out. +#[test] +fn a_twin_of_a_replaced_browsed_file_stands_in_for_it_when_copying() { + let src = temp_dir("browsed-replaced-twin"); + let (a, d) = (src.join("a.png"), src.join("d.png")); + write_png(&a, 75); + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [a], "local": true})).unwrap(); + write_png_sized(&a, 9, 64, 40); + std::fs::copy(&a, &d).unwrap(); + let scan = s.execute("library.importPreview", &json!({"paths": [a, d]})).unwrap(); + let found = scan["candidates"].as_array().unwrap(); + assert_eq!(found[0]["local"], true, "{scan}"); + assert_eq!(found[1]["duplicate"], "content", "{scan}"); + assert_eq!(found[1]["browsedTwin"], found[0]["path"], "{scan}"); + let _ = std::fs::remove_dir_all(src); +} + +/// A browsed file replaced by a copy of another browsed file isn't a stand-in: the first file of its own is. +#[test] +fn a_replaced_browsed_file_does_not_take_the_stand_in_of_another_browsed_file() { + let src = temp_dir("browsed-replaced-standin"); + let (a, b, d) = (src.join("a.png"), src.join("b.png"), src.join("d.png")); + write_png(&a, 75); + write_png_sized(&b, 9, 64, 40); + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [a, b], "local": true})).unwrap(); + std::fs::copy(&a, &b).unwrap(); + std::fs::copy(&a, &d).unwrap(); + let scan = s.execute("library.importPreview", &json!({"paths": [a, b, d]})).unwrap(); + let found = scan["candidates"].as_array().unwrap(); + assert!(found[1]["browsedTwin"].is_null(), "a browsed file doesn't stand in: {scan}"); + assert_eq!(found[2]["browsedTwin"], found[0]["path"], "the file of its own does: {scan}"); + let _ = std::fs::remove_dir_all(src); +} + +/// "Import as new" replaces the trashed library photo with the same content when the browsed twin +/// is promoted, as it does for a new file. +#[test] +fn promoting_a_browsed_twin_as_new_replaces_the_trashed_library_photo() { + let src = temp_dir("browsed-fresh"); + let original = src.join("original.png"); + let twin = src.join("browsed.png"); + write_png(&original, 77); + std::fs::copy(&original, &twin).unwrap(); + let mut s = Session::new().with_fs(); + let r = s.execute("library.import", &json!({"paths": [original]})).unwrap(); + let old = r["imported"][0].as_u64().unwrap(); + let r = s.execute("library.import", &json!({"paths": [twin], "local": true})).unwrap(); + let local = r["imported"][0].as_u64().unwrap(); + s.execute("photo.delete", &json!({"ids": [old]})).unwrap(); + let r = s.execute("library.import", &json!({"paths": [twin], "onDeleted": "fresh"})).unwrap(); + assert_eq!(r["imported"], json!([local]), "{r}"); + let trashed = s.catalog.photos().filter(|p| p.deleted).count(); + assert_eq!(trashed, 0, "the trashed twin is gone"); + assert!(s.catalog.photo(lightcraft_catalog::PhotoId(local)).is_some_and(|p| p.in_library())); + let _ = std::fs::remove_dir_all(src); +} + +/// Restoring a trashed library photo by the content of a browsed file doesn't relink it onto the +/// path the browse record holds: that would leave two records on one file. +#[test] +fn restoring_by_a_browsed_twin_does_not_relink_onto_its_path() { + let src = temp_dir("browsed-restore"); + let original = src.join("original.png"); + let renamed = src.join("renamed.png"); + write_png(&original, 78); + let mut s = Session::new().with_fs(); + let r = s.execute("library.import", &json!({"paths": [original]})).unwrap(); + let old = r["imported"][0].as_u64().unwrap(); + std::fs::rename(&original, &renamed).unwrap(); + s.execute("photo.delete", &json!({"ids": [old]})).unwrap(); + let r = s.execute("library.import", &json!({"paths": [renamed], "local": true})).unwrap(); + let local = r["imported"][0].as_u64().unwrap(); + let r = s.execute("library.import", &json!({"paths": [renamed]})).unwrap(); + assert_eq!(r["restored"], json!([old]), "{r}"); + let on_path = s.catalog.photos().filter(|p| matches!(&p.source, lightcraft_catalog::Source::File { path } if Path::new(path) == renamed)).count(); + assert_eq!(on_path, 1, "one record holds the renamed file"); + assert!(s.catalog.photo(lightcraft_catalog::PhotoId(local)).is_some_and(|p| p.local), "the browse record is left alone"); + let _ = std::fs::remove_dir_all(src); +} + +#[test] +fn local_twin_does_not_block_reimport_after_permanent_delete_and_restart() { + use lightcraft_catalog::PhotoId; + for mode in ["add", "copy"] { + let src = temp_dir(&format!("local-twin-src-{mode}")); + let lib = temp_dir(&format!("local-twin-lib-{mode}")); + let original = src.join("original.png"); + let twin = src.join("browsed.png"); + write_png(&original, 71); + std::fs::copy(&original, &twin).unwrap(); + let bytes = std::fs::read(&original).unwrap(); + let mut s = Session::new().with_fs(); + s.open_library(&lib, false).unwrap(); + let r = s.execute("library.import", &json!({"paths": [original], "mode": mode})).unwrap(); + let old = r["imported"][0].as_u64().unwrap(); + let r = s.execute("library.import", &json!({"paths": [twin], "local": true})).unwrap(); + let local = PhotoId(r["imported"][0].as_u64().unwrap()); + let before = s.catalog.photo(local).unwrap().clone(); + s.execute("photo.delete", &json!({"ids": [old]})).unwrap(); + s.execute("library.source", &json!({"kind": "recentlyDeleted"})).unwrap(); + s.execute("library.select", &json!({"ids": [old]})).unwrap(); + s.execute("photo.deletePermanently", &json!({"ids": [old]})).unwrap(); + s.close_library().unwrap(); + s.open_library(&lib, false).unwrap(); + let scan = s.execute("library.importPreview", &json!({"paths": [original]})).unwrap(); + assert_eq!(scan["duplicates"], 0, "a browsed copy is not a library duplicate: {scan}"); + let r = s.execute("library.import", &json!({"paths": [original], "mode": mode})).unwrap(); + assert_eq!(ids(&r, "imported"), 1, "{r}"); + assert_eq!(ids(&r, "restored"), 0); + assert_eq!(ids(&r, "duplicates"), 0); + assert_ne!(r["imported"][0], old); + assert_eq!(s.catalog.photo(local).unwrap(), &before, "leave the other path's browse record alone"); + assert_eq!(s.catalog.photos().filter(|p| p.in_library()).count(), 1); + let scan = s.execute("library.importPreview", &json!({"paths": [original]})).unwrap(); + assert_eq!(scan["duplicates"], 1, "the actual library photo still counts"); + assert_eq!(std::fs::read(&original).unwrap(), bytes); + assert_eq!(std::fs::read(&twin).unwrap(), bytes); + s.close_library().unwrap(); + let _ = std::fs::remove_dir_all(src); + let _ = std::fs::remove_dir_all(lib); + } +} + +#[test] +fn local_twin_import_matches_the_library_photo_before_promoting() { + use lightcraft_catalog::PhotoId; + let src = temp_dir("local-twin-priority"); + let original = src.join("original.png"); + let twin = src.join("browsed.png"); + write_png(&original, 72); + std::fs::copy(&original, &twin).unwrap(); + let mut s = Session::new().with_fs(); + let r = s.execute("library.import", &json!({"paths": [original]})).unwrap(); + let id = r["imported"][0].as_u64().unwrap(); + s.execute("photo.rate", &json!({"ids": [id], "rating": 5})).unwrap(); + let r = s.execute("library.import", &json!({"paths": [twin], "local": true})).unwrap(); + let local = PhotoId(r["imported"][0].as_u64().unwrap()); + let scan = s.execute("library.importPreview", &json!({"paths": [twin]})).unwrap(); + assert_eq!(scan["duplicates"], 1, "{scan}"); + assert_eq!(scan["candidates"][0]["existing"], id); + let r = s.execute("library.import", &json!({"paths": [twin]})).unwrap(); + assert_eq!(ids(&r, "imported"), 0); + assert_eq!(r["duplicates"][0]["existing"], id); + s.execute("photo.delete", &json!({"ids": [id]})).unwrap(); + let r = s.execute("library.import", &json!({"paths": [twin], "onDeleted": "skip"})).unwrap(); + assert_eq!(ids(&r, "imported"), 0, "skip must not promote the local twin: {r}"); + assert_eq!(r["duplicates"][0]["existingDeleted"], true); + let r = s.execute("library.import", &json!({"paths": [twin]})).unwrap(); + assert_eq!(r["restored"], json!([id])); + assert!(s.catalog.photo(local).unwrap().local); + assert_eq!(s.catalog.photo(PhotoId(id)).unwrap().rating, 5); + let _ = std::fs::remove_dir_all(src); +} + +#[test] +fn local_twins_are_deduplicated_when_promoted_in_one_import() { + let src = temp_dir("local-twin-batch"); + let a = src.join("a.png"); + let b = src.join("b.png"); + let c = src.join("c.png"); + write_png(&a, 73); + std::fs::copy(&a, &b).unwrap(); + std::fs::copy(&a, &c).unwrap(); + let mut s = Session::new().with_fs(); + let r = s.execute("library.import", &json!({"paths": [a, b], "local": true})).unwrap(); + assert_eq!(ids(&r, "imported"), 2, "browsing shows both paths: {r}"); + let scan = s.execute("library.importPreview", &json!({"paths": [a, b, c]})).unwrap(); + assert_eq!(scan["duplicates"], 2, "only one candidate per content: {scan}"); + let r = s.execute("library.import", &json!({"paths": [a, b, c]})).unwrap(); + assert_eq!(ids(&r, "imported"), 1, "{r}"); + assert_eq!(ids(&r, "duplicates"), 2); + assert_eq!(s.catalog.photos().filter(|p| p.in_library()).count(), 1); + assert_eq!(s.catalog.photos().filter(|p| p.local).count(), 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.catalog.photos().filter(|p| p.in_library()).count(), 0); + assert_eq!(s.catalog.photos().filter(|p| p.local).count(), 2); + let _ = std::fs::remove_dir_all(src); +} + +#[test] +fn twins_of_a_browsed_photo_are_copies_in_the_source_not_library_duplicates() { + let src = temp_dir("local-twin-scan"); + let a = src.join("a.png"); + let b = src.join("b.png"); + let c = src.join("c.png"); + let d = src.join("d.png"); + write_png(&a, 75); + std::fs::copy(&a, &b).unwrap(); + std::fs::copy(&a, &c).unwrap(); + std::fs::copy(&a, &d).unwrap(); + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [a, b], "local": true})).unwrap(); + let scan = s.execute("library.importPreview", &json!({"paths": [a, b, c, d]})).unwrap(); + let found = scan["candidates"].as_array().unwrap(); + assert_eq!(found.len(), 4, "{scan}"); + assert_eq!(found[0]["local"], true, "{scan}"); + assert!(found[0]["duplicate"].is_null(), "the first browsed copy is offered: {scan}"); + for twin in &found[1..] { + assert_eq!(twin["duplicate"], "content", "{scan}"); + assert!(twin["existing"].is_null(), "no library photo has these bytes, a browsed record isn't one: {scan}"); + } + // (copying leaves the browsed photo out: the first file of its own stands in for it, once) + assert!(found[1]["browsedTwin"].is_null(), "a browsed twin doesn't: {scan}"); + assert_eq!(found[2]["browsedTwin"], found[0]["path"], "{scan}"); + assert!(found[3]["browsedTwin"].is_null(), "{scan}"); + let _ = std::fs::remove_dir_all(src); +} + +#[test] +fn local_twin_promotion_counts_across_background_import_batches() { + use crate::import::{ImportJob, ImportOptions, commit_prepared}; + let src = temp_dir("local-twin-worker"); + let a = src.join("a.png"); + let b = src.join("b.png"); + let c = src.join("c.png"); + write_png(&a, 74); + std::fs::copy(&a, &b).unwrap(); + std::fs::copy(&a, &c).unwrap(); + let mut s = Session::new().with_fs(); + let r = s.execute("library.import", &json!({"paths": [a, b], "local": true})).unwrap(); + let id = r["imported"][0].as_u64().unwrap(); + s.execute("photo.rate", &json!({"ids": [id], "rating": 4})).unwrap(); + let mut job = ImportJob::new(&mut s, ImportOptions::default()).unwrap(); + let cancel = std::sync::atomic::AtomicBool::new(false); + let first = job.prepare(&[a.to_string_lossy().to_string()], &cancel); + let report = commit_prepared(&mut s, &job.opts, job.now(), first).unwrap(); + assert_eq!(report.imported, [id], "promote the existing record with its edits"); + assert_eq!(s.catalog.photo(lightcraft_catalog::PhotoId(id)).unwrap().rating, 4); + let next = job.prepare(&[b.to_string_lossy().to_string(), c.to_string_lossy().to_string()], &cancel); + let report = commit_prepared(&mut s, &job.opts, job.now(), next).unwrap(); + assert!(report.imported.is_empty()); + assert_eq!(report.duplicates.len(), 2); + assert!(report.duplicates.iter().all(|d| d.existing == Some(id))); + assert_eq!(s.catalog.photos().filter(|p| p.in_library()).count(), 1); + let _ = std::fs::remove_dir_all(src); +} + #[test] fn recursive_import_with_duplicates() { let src = temp_dir("src"); @@ -3519,6 +3906,295 @@ fn presets_apply_the_imported_profile_they_name() { let _ = std::fs::remove_dir_all(&src); } +#[test] +fn import_preserves_embedded_xmp_rating_and_label() { + use lightcraft_codecs::{ChromaSubsampling, EncodeImage, EncodeMeta, Samples, encode_jpeg}; + let src = temp_dir("embedded-xmp-rating-test"); + let px = [128u8; 40 * 30 * 3]; + let xmp = r#""#; + let meta = EncodeMeta { xmp: Some(xmp), ..Default::default() }; + let bytes = encode_jpeg(&EncodeImage::new(40, 30, 3, Samples::U8(&px)), 90, ChromaSubsampling::S444, &meta).unwrap(); + std::fs::write(src.join("photo.jpg"), &bytes).unwrap(); + + let mut s = Session::new().with_fs(); + let r = s.execute("library.import", &json!({"paths": [src.join("photo.jpg").to_string_lossy()]})).unwrap(); + assert_eq!(ids(&r, "imported"), 1); + let p = s.catalog.photos().next().unwrap(); + assert_eq!(p.rating, 5); + assert_eq!(p.flag, lightcraft_catalog::Flag::None); + assert_eq!(p.label, Some(lightcraft_catalog::ColorLabel::Blue)); + + let _ = std::fs::remove_dir_all(&src); +} + +#[test] +fn import_preserves_embedded_exif_rating() { + use lightcraft_codecs::{ChromaSubsampling, EncodeImage, EncodeMeta, Samples, encode_jpeg}; + let src = temp_dir("embedded-exif-rating-test"); + let px = [128u8; 40 * 30 * 3]; + let exif = lightcraft_meta::write_exif(&lightcraft_meta::Metadata { rating: Some(3), ..Default::default() }); + let meta = EncodeMeta { exif: Some(&exif), ..Default::default() }; + let bytes = encode_jpeg(&EncodeImage::new(40, 30, 3, Samples::U8(&px)), 90, ChromaSubsampling::S444, &meta).unwrap(); + std::fs::write(src.join("exif_rating.jpg"), &bytes).unwrap(); + + let mut s = Session::new().with_fs(); + let r = s.execute("library.import", &json!({"paths": [src.join("exif_rating.jpg").to_string_lossy()]})).unwrap(); + assert_eq!(ids(&r, "imported"), 1); + let p = s.catalog.photos().next().unwrap(); + assert_eq!(p.rating, 3); + assert_eq!(p.flag, lightcraft_catalog::Flag::None); + + let _ = std::fs::remove_dir_all(&src); +} + +#[test] +fn import_preserves_embedded_rejected_rating() { + use lightcraft_codecs::{ChromaSubsampling, EncodeImage, EncodeMeta, Samples, encode_jpeg}; + let src = temp_dir("embedded-rejected-rating-test"); + let px = [128u8; 40 * 30 * 3]; + + // Case 1: EXIF rating -1 + let exif = lightcraft_meta::write_exif(&lightcraft_meta::Metadata { rating: Some(-1), ..Default::default() }); + let meta = EncodeMeta { exif: Some(&exif), ..Default::default() }; + let bytes = encode_jpeg(&EncodeImage::new(40, 30, 3, Samples::U8(&px)), 90, ChromaSubsampling::S444, &meta).unwrap(); + std::fs::write(src.join("exif_rejected.jpg"), &bytes).unwrap(); + + // Case 2: XMP rating -1 + let xmp = r#""#; + let meta = EncodeMeta { xmp: Some(xmp), ..Default::default() }; + let bytes = encode_jpeg(&EncodeImage::new(40, 30, 3, Samples::U8(&px)), 90, ChromaSubsampling::S444, &meta).unwrap(); + std::fs::write(src.join("xmp_rejected.jpg"), &bytes).unwrap(); + + let mut s = Session::new().with_fs(); + let r = s.execute("library.import", &json!({"paths": [src.to_string_lossy()]})).unwrap(); + assert_eq!(ids(&r, "imported"), 2); + let exif_p = s.catalog.photos().find(|p| p.file_name == "exif_rejected.jpg").unwrap(); + assert_eq!(exif_p.rating, 0); + assert_eq!(exif_p.flag, lightcraft_catalog::Flag::Reject); + + let xmp_p = s.catalog.photos().find(|p| p.file_name == "xmp_rejected.jpg").unwrap(); + assert_eq!(xmp_p.rating, 0); + assert_eq!(xmp_p.flag, lightcraft_catalog::Flag::Reject); + + let _ = std::fs::remove_dir_all(&src); +} + +#[test] +fn import_preserves_embedded_xmp_png_and_webp() { + use lightcraft_catalog::ColorLabel; + use lightcraft_codecs::{EncodeImage, EncodeMeta, Samples, encode_png, encode_webp_lossless}; + let src = temp_dir("embedded-xmp-png-webp-test"); + let px = [128u8; 40 * 30 * 3]; + + // PNG with embedded XMP rating and label + let png_xmp = r#""#; + let png_meta = EncodeMeta { xmp: Some(png_xmp), ..Default::default() }; + let png_bytes = encode_png(&EncodeImage::new(40, 30, 3, Samples::U8(&px)), &png_meta).unwrap(); + std::fs::write(src.join("embedded.png"), &png_bytes).unwrap(); + + // WebP with embedded XMP rating and label + let webp_xmp = r#""#; + let webp_meta = EncodeMeta { xmp: Some(webp_xmp), ..Default::default() }; + let webp_bytes = encode_webp_lossless(&EncodeImage::new(40, 30, 3, Samples::U8(&px)), &webp_meta).unwrap(); + std::fs::write(src.join("embedded.webp"), &webp_bytes).unwrap(); + + let mut s = Session::new().with_fs(); + let r = s.execute("library.import", &json!({"paths": [src.to_string_lossy()]})).unwrap(); + assert_eq!(ids(&r, "imported"), 2); + + let png_photo = s.catalog.photos().find(|p| p.file_name == "embedded.png").unwrap(); + assert_eq!(png_photo.rating, 4); + assert_eq!(png_photo.label, Some(ColorLabel::Red)); + + let webp_photo = s.catalog.photos().find(|p| p.file_name == "embedded.webp").unwrap(); + assert_eq!(webp_photo.rating, 2); + assert_eq!(webp_photo.label, Some(ColorLabel::Blue)); + + let _ = std::fs::remove_dir_all(&src); +} + +#[test] +fn import_preserves_exif_rating_when_xmp_has_unrelated_rating_text() { + use lightcraft_codecs::{ChromaSubsampling, EncodeImage, EncodeMeta, Samples, encode_jpeg}; + let src = temp_dir("exif-rating-unrelated-xmp-test"); + let px = [128u8; 40 * 30 * 3]; + + let exif = lightcraft_meta::write_exif(&lightcraft_meta::Metadata { rating: Some(5), ..Default::default() }); + let xmp = r#"100Rating guide mentioning xmp:Rating"#; + let meta = EncodeMeta { exif: Some(&exif), xmp: Some(xmp), ..Default::default() }; + let bytes = encode_jpeg(&EncodeImage::new(40, 30, 3, Samples::U8(&px)), 90, ChromaSubsampling::S444, &meta).unwrap(); + std::fs::write(src.join("iso_and_desc_rating.jpg"), &bytes).unwrap(); + + let mut s = Session::new().with_fs(); + let r = s.execute("library.import", &json!({"paths": [src.join("iso_and_desc_rating.jpg").to_string_lossy()]})).unwrap(); + assert_eq!(ids(&r, "imported"), 1); + let p = s.catalog.photos().next().unwrap(); + assert_eq!(p.rating, 5); + + let _ = std::fs::remove_dir_all(&src); +} + +#[test] +fn import_rendered_file_ignores_embedded_develop_settings() { + use lightcraft_codecs::{ChromaSubsampling, EncodeImage, EncodeMeta, Samples, encode_jpeg}; + let src = temp_dir("embedded-rendered-develop-test"); + let px = [128u8; 40 * 30 * 3]; + + // A JPEG with embedded XMP containing rating and crs:Exposure2012="+1.00" + let xmp = r#""#; + let meta = EncodeMeta { xmp: Some(xmp), ..Default::default() }; + let bytes = encode_jpeg(&EncodeImage::new(40, 30, 3, Samples::U8(&px)), 90, ChromaSubsampling::S444, &meta).unwrap(); + std::fs::write(src.join("rendered_with_crs.jpg"), &bytes).unwrap(); + + let mut s = Session::new().with_fs(); + let r = s.execute("library.import", &json!({"paths": [src.join("rendered_with_crs.jpg").to_string_lossy()]})).unwrap(); + assert_eq!(ids(&r, "imported"), 1); + let p = s.catalog.photos().next().unwrap(); + // Rating is imported from embedded XMP + assert_eq!(p.rating, 3); + // Develop settings from embedded XMP are ignored for rendered files (already baked into pixels) + assert_eq!(p.develop.light.exposure, 0.0); + assert_eq!(p.develop, std::sync::Arc::new(p.camera_defaults())); + + let _ = std::fs::remove_dir_all(&src); +} + +#[test] +fn import_embedded_metadata_and_field_specific_sidecar_precedence() { + use lightcraft_catalog::ColorLabel; + use lightcraft_codecs::{ChromaSubsampling, EncodeImage, EncodeMeta, Samples, encode_jpeg}; + let src = temp_dir("embedded-sidecar-precedence-test"); + let px = [128u8; 40 * 30 * 3]; + + // Case 1: JPEG with embedded Rating 4 and Label Blue, external sidecar with only Label Red + let xmp = r#""#; + let meta = EncodeMeta { xmp: Some(xmp), ..Default::default() }; + let bytes1 = encode_jpeg(&EncodeImage::new(40, 30, 3, Samples::U8(&px)), 90, ChromaSubsampling::S444, &meta).unwrap(); + std::fs::write(src.join("partial.jpg"), &bytes1).unwrap(); + let partial_sidecar = r#""#; + std::fs::write(src.join("partial.xmp"), partial_sidecar).unwrap(); + + // Case 2: JPEG with embedded Rating 4 and Label Blue, without sidecar + let px2 = [129u8; 40 * 30 * 3]; + let bytes2 = encode_jpeg(&EncodeImage::new(40, 30, 3, Samples::U8(&px2)), 90, ChromaSubsampling::S444, &meta).unwrap(); + std::fs::write(src.join("no_sidecar.jpg"), &bytes2).unwrap(); + + // Case 3: JPEG with embedded Rating 4 and Label Blue, complete sidecar override with Rating 1 and Label Red + let px3 = [130u8; 40 * 30 * 3]; + let bytes3 = encode_jpeg(&EncodeImage::new(40, 30, 3, Samples::U8(&px3)), 90, ChromaSubsampling::S444, &meta).unwrap(); + std::fs::write(src.join("complete.jpg"), &bytes3).unwrap(); + let complete_sidecar = r#""#; + std::fs::write(src.join("complete.xmp"), complete_sidecar).unwrap(); + + let mut s = Session::new().with_fs(); + let r = s.execute("library.import", &json!({"paths": [src.to_string_lossy()]})).unwrap(); + assert_eq!(ids(&r, "imported"), 3); + + let partial_p = s.catalog.photos().find(|p| p.file_name == "partial.jpg").unwrap(); + assert_eq!(partial_p.rating, 4); + assert_eq!(partial_p.label, Some(ColorLabel::Red)); + + let no_sidecar_p = s.catalog.photos().find(|p| p.file_name == "no_sidecar.jpg").unwrap(); + assert_eq!(no_sidecar_p.rating, 4); + assert_eq!(no_sidecar_p.label, Some(ColorLabel::Blue)); + + let complete_p = s.catalog.photos().find(|p| p.file_name == "complete.jpg").unwrap(); + assert_eq!(complete_p.rating, 1); + assert_eq!(complete_p.label, Some(ColorLabel::Red)); + + let _ = std::fs::remove_dir_all(&src); +} + +#[test] +fn import_partial_sidecar_override_with_rendered_develop() { + use lightcraft_catalog::ColorLabel; + use lightcraft_codecs::{ChromaSubsampling, EncodeImage, EncodeMeta, Samples, encode_jpeg}; + let src = temp_dir("embedded-sidecar-rendered-develop-test"); + let px = [128u8; 40 * 30 * 3]; + + // JPEG with embedded Rating 4, Label Blue, and crs:Exposure2012="+2.00" + let xmp = r#""#; + let meta = EncodeMeta { xmp: Some(xmp), ..Default::default() }; + let bytes = encode_jpeg(&EncodeImage::new(40, 30, 3, Samples::U8(&px)), 90, ChromaSubsampling::S444, &meta).unwrap(); + std::fs::write(src.join("photo.jpg"), &bytes).unwrap(); + + // Sidecar overriding Label to Red and explicitly setting Exposure to +1.00 (no rating tag) + let sidecar_xmp = r#""#; + std::fs::write(src.join("photo.xmp"), sidecar_xmp).unwrap(); + + let mut s = Session::new().with_fs(); + let r = s.execute("library.import", &json!({"paths": [src.join("photo.jpg").to_string_lossy()]})).unwrap(); + assert_eq!(ids(&r, "imported"), 1); + let p = s.catalog.photos().next().unwrap(); + // Rating 4 from embedded is kept + assert_eq!(p.rating, 4); + // Label Red from sidecar overrides Blue + assert_eq!(p.label, Some(ColorLabel::Red)); + // External sidecar's develop settings apply; embedded exposure +2 stays suppressed + assert_eq!(p.develop.light.exposure, 1.0); + + let _ = std::fs::remove_dir_all(&src); +} + +#[test] +fn import_raw_with_embedded_develop_and_partial_sidecar() { + use lightcraft_catalog::ColorLabel; + let src = temp_dir("raw-embedded-develop-sidecar-test"); + let xmp = r#""#; + + // Case 1: Raw with embedded develop + rating + label, external sidecar has only Label Red + write_raw_with_xmp(&src.join("raw1.NEF"), xmp, 1); + let sidecar1 = r#""#; + std::fs::write(src.join("raw1.xmp"), sidecar1).unwrap(); + + // Case 2: Raw with embedded develop, external sidecar overrides develop settings to Exposure +0.50 and Rating 5 + write_raw_with_xmp(&src.join("raw2.NEF"), xmp, 2); + let sidecar2 = r#""#; + std::fs::write(src.join("raw2.xmp"), sidecar2).unwrap(); + + let mut s = Session::new().with_fs(); + let r = s.execute("library.import", &json!({"paths": [src.to_string_lossy()]})).unwrap(); + assert_eq!(ids(&r, "imported"), 2); + + let p1 = s.catalog.photos().find(|p| p.file_name == "raw1.NEF").unwrap(); + assert_eq!(p1.rating, 2, "rating from embedded XMP is preserved"); + assert_eq!(p1.label, Some(ColorLabel::Red), "label is overridden by external sidecar"); + assert_eq!(p1.develop.light.exposure, 1.5, "raw keeps embedded develop when sidecar provides none"); + + let p2 = s.catalog.photos().find(|p| p.file_name == "raw2.NEF").unwrap(); + assert_eq!(p2.rating, 5, "rating is overridden by external sidecar"); + assert_eq!(p2.label, Some(ColorLabel::Blue), "label from embedded XMP is preserved"); + assert_eq!(p2.develop.light.exposure, 0.5, "external sidecar develop overrides embedded develop"); + + let _ = std::fs::remove_dir_all(&src); +} + +/// A raw container LightCraft shows by its embedded JPEG: a TIFF whose IFD0 points at one, +/// optionally with an embedded XMP packet in tag 700. +fn write_raw_with_xmp(path: &Path, xmp: &str, seed: u8) { + use lightcraft_codecs::{ChromaSubsampling, EncodeImage, EncodeMeta, Samples, encode_jpeg}; + let px: Vec = (0..48 * 32).flat_map(|i| [(i % 251) as u8, 91, seed]).collect(); + let j = encode_jpeg(&EncodeImage::new(48, 32, 3, Samples::U8(&px)), 90, ChromaSubsampling::S444, &EncodeMeta::default()).unwrap(); + let xmp_bytes = xmp.as_bytes(); + let xmp_off = 8 + 2 + 36 + 4; + let jpeg_off = xmp_off + xmp_bytes.len(); + let mut f = b"II*\0\x08\0\0\0\x03\0".to_vec(); + for (tag, v) in [(513u16, jpeg_off as u32), (514, j.len() as u32)] { + f.extend_from_slice(&tag.to_le_bytes()); + f.extend_from_slice(&[4, 0, 1, 0, 0, 0]); + f.extend_from_slice(&v.to_le_bytes()); + } + f.extend_from_slice(&700u16.to_le_bytes()); + f.extend_from_slice(&[1, 0]); + f.extend_from_slice(&(xmp_bytes.len() as u32).to_le_bytes()); + f.extend_from_slice(&(xmp_off as u32).to_le_bytes()); + f.extend_from_slice(&[0, 0, 0, 0]); + f.extend_from_slice(xmp_bytes); + f.extend_from_slice(&j); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, f).unwrap(); +} + /// A raw container LightCraft shows by its embedded JPEG: a TIFF whose IFD0 points at one. fn write_raw(path: &Path) { use lightcraft_codecs::{ChromaSubsampling, EncodeImage, EncodeMeta, Samples, encode_jpeg}; diff --git a/crates/engine/src/tests/import_move.rs b/crates/engine/src/tests/import_move.rs index e35f853ba8..c4e9c52522 100644 --- a/crates/engine/src/tests/import_move.rs +++ b/crates/engine/src/tests/import_move.rs @@ -15,6 +15,9 @@ fn temp_dir(tag: &str) -> PathBuf { d } +/// The clock these tests run on; an undated file is pinned to it too (see `write_png`). +const CLOCK: &str = "2026-01-14T05:58:48"; + pub(super) fn write_png(path: &Path, seed: u8) { let (w, h) = (40usize, 24usize); let data: Vec<[u8; 4]> = (0..w * h).map(|i| [(i % w * 5) as u8, (i / w * 7) as u8, seed, 255]).collect(); @@ -22,8 +25,10 @@ pub(super) fn write_png(path: &Path, seed: u8) { let bytes = lightcraft_codecs::encode_png(&lightcraft_codecs::EncodeImage::rgba8(&img), &lightcraft_codecs::EncodeMeta::default()).unwrap(); std::fs::create_dir_all(path.parent().unwrap()).unwrap(); std::fs::write(path, bytes).unwrap(); - // undated files take the file's date: the tests' clock time (2026-01-14T05:58:48) - let t = std::time::UNIX_EPOCH + std::time::Duration::from_secs(1_768_370_328); + // Undated files take the file's date, read in the host's zone (issue #2284), so the file is + // pinned to the instant this machine reads as the tests' clock time rather than to a fixed one. + let secs = crate::import::local_instant(CLOCK).and_then(|s| u64::try_from(s).ok()).unwrap_or(0); + let t = std::time::UNIX_EPOCH + std::time::Duration::from_secs(secs); std::fs::File::options().write(true).open(path).unwrap().set_modified(t).unwrap(); } diff --git a/crates/engine/src/tests/keyword_list.rs b/crates/engine/src/tests/keyword_list.rs index f2e12385bc..c40c7e3a0d 100644 --- a/crates/engine/src/tests/keyword_list.rs +++ b/crates/engine/src/tests/keyword_list.rs @@ -537,3 +537,73 @@ fn importing_keywords_reads_a_list() { assert!(s.execute("keyword.import", &json!({})).is_err(), "a path or text"); let _ = std::fs::remove_dir_all(&dir); } + +/// A library whose photos got a whole keyword list as one keyword (line breaks inside) is +/// repaired when it opens: one keyword a line, journaled. +#[test] +fn line_separated_keywords_are_split_when_the_library_opens() { + let mut s = Session::with_demo(); + let id = s.visible_cloned()[0]; + let mut meta = s.catalog.photo(id).unwrap().meta.clone(); + meta.keywords = vec!["Bride\r\n Groom\r\n Happy Couple".into()]; + s.catalog.apply(lightcraft_catalog::Op::SetMeta { id, meta: Box::new(meta) }).unwrap(); + assert_eq!(s.split_multiline_keywords(), 1); + assert_eq!(s.catalog.photo(id).unwrap().meta.keywords, vec!["Bride", "Groom", "Happy Couple"]); + assert_eq!(s.split_multiline_keywords(), 0, "nothing left to split"); +} + +/// A listed keyword with line breaks hands its options to the names it splits into, so a keyword left +/// out of export stays out (CodeRabbit on #2922); a name listed already keeps its own options but is +/// left out of export when either was. +#[test] +fn a_split_keyword_keeps_its_export_options() { + use lightcraft_catalog::Op; + use lightcraft_catalog::keywords::KeywordInfo; + let mut s = Session::with_demo(); + let id = s.visible_cloned()[0]; + let hidden = KeywordInfo { include_on_export: false, ..KeywordInfo::default() }; + let groom = KeywordInfo { person: true, ..KeywordInfo::default() }; + s.catalog.apply(Op::SetKeyword { path: "Bride\nGroom".into(), info: Some(hidden) }).unwrap(); + s.catalog.apply(Op::SetKeyword { path: "Groom".into(), info: Some(groom) }).unwrap(); + let mut meta = s.catalog.photo(id).unwrap().meta.clone(); + meta.keywords = vec!["Bride\nGroom".into()]; + s.catalog.apply(Op::SetMeta { id, meta: Box::new(meta) }).unwrap(); + assert_eq!(s.split_multiline_keywords(), 1); + let bride = s.catalog.keyword_info("Bride").expect("Bride is listed with the options it came with"); + assert!(!bride.include_on_export, "{bride:?}"); + let groom = s.catalog.keyword_info("Groom").unwrap(); + assert!(!groom.include_on_export && groom.person, "kept its own options, left out of export: {groom:?}"); + assert!(s.catalog.keyword_info("Bride\nGroom").is_none(), "the multi-line record is gone"); +} + +/// A split keyword that is where new keywords go hands that to one of its names only, so there is still one +/// default parent (CodeRabbit on #2922). +#[test] +fn a_split_default_parent_stays_one_keyword() { + use lightcraft_catalog::Op; + use lightcraft_catalog::keywords::KeywordInfo; + let mut s = Session::with_demo(); + let inside = KeywordInfo { new_keywords_inside: true, ..KeywordInfo::default() }; + s.catalog.apply(Op::SetKeyword { path: "Ceremony\nReception".into(), info: Some(inside) }).unwrap(); + s.split_multiline_keywords(); + let parents: Vec<&str> = s.catalog.listed_keywords().filter(|k| k.info.new_keywords_inside).map(|k| k.path.as_str()).collect(); + assert_eq!(parents, ["Ceremony"]); + assert_eq!(s.catalog.default_keyword_parent().as_deref(), Some("Ceremony")); +} + +/// The first name a default parent splits into stays the default parent when it is listed already (its other +/// options are its own). +#[test] +fn a_split_default_parent_stays_one_when_its_first_name_is_listed() { + use lightcraft_catalog::Op; + use lightcraft_catalog::keywords::KeywordInfo; + let mut s = Session::with_demo(); + let own = KeywordInfo { include_on_export: true, ..KeywordInfo::default() }; + s.catalog.apply(Op::SetKeyword { path: "Ceremony".into(), info: Some(own) }).unwrap(); + let inside = KeywordInfo { new_keywords_inside: true, ..KeywordInfo::default() }; + s.catalog.apply(Op::SetKeyword { path: "Ceremony\nReception".into(), info: Some(inside) }).unwrap(); + s.split_multiline_keywords(); + let parents: Vec<&str> = s.catalog.listed_keywords().filter(|k| k.info.new_keywords_inside).map(|k| k.path.as_str()).collect(); + assert_eq!(parents, ["Ceremony"]); + assert_eq!(s.catalog.default_keyword_parent().as_deref(), Some("Ceremony")); +} diff --git a/crates/engine/src/tests/lens_refresh.rs b/crates/engine/src/tests/lens_refresh.rs index d3bf3a3574..a00406a910 100644 --- a/crates/engine/src/tests/lens_refresh.rs +++ b/crates/engine/src/tests/lens_refresh.rs @@ -19,7 +19,7 @@ fn lens(k: f64) -> EmbeddedLens { } fn lens_of(s: &Session, id: PhotoId) -> Option { - s.catalog.photo(id).and_then(|p| p.embedded_lens) + s.catalog.photo(id).and_then(|p| p.embedded_lens.as_deref().copied()) } /// Two demo photos "taken with different lenses". @@ -157,7 +157,7 @@ fn photos_get_their_profile_when_the_database_arrives() { } fn with_lens(mut p: Photo, l: Option, on: bool) -> Photo { - p.embedded_lens = l; + p.embedded_lens = l.map(Box::new); let mut d = (*p.develop).clone(); d.optics.lens_profile = on; p.develop = Arc::new(d); diff --git a/crates/engine/src/tests/lightroom_history.rs b/crates/engine/src/tests/lightroom_history.rs new file mode 100644 index 0000000000..d1fa044186 --- /dev/null +++ b/crates/engine/src/tests/lightroom_history.rs @@ -0,0 +1,136 @@ +//! Lightroom history steps and snapshots read from a catalog file into the import archive: stored as text +//! (Lightroom 6) or as compressed BLOBs (history steps since Lightroom Classic 13, which also converts an upgraded +//! catalog's steps). + +use crate::lightroom_fixture::{self as fixture, Field, Table}; +use serde_json::{Value, json}; + +const CURRENT: &str = "s = { Exposure2012 = 1.25, Contrast2012 = 17 }"; +const FIRST: &str = "s = { Exposure2012 = 1.25 }"; + +/// Write a one-photo catalog with `extra` tables, read it, archive it, and return the archive's JSON. +fn archive(tag: &str, extra: Vec
) -> Value { + let dir = fixture::dir(tag); + let mut tables = fixture::one_photo(&dir.join("originals"), CURRENT); + tables.extend(extra); + let catalog = dir.join("test.lrcat"); + fixture::write(&catalog, &tables); + let data = crate::lightroom_catalog::read(&catalog).unwrap(); + let stored = crate::lightroom_archive::store(&dir.join("Interop"), &data).unwrap(); + let archived = fixture::read_archive(&stored); + let _ = std::fs::remove_dir_all(dir); + archived +} + +fn steps(settings: impl Fn(&str) -> Field) -> Table { + Table { + name: "Adobe_libraryImageDevelopHistoryStep", + columns: fixture::HISTORY_COLUMNS, + rows: vec![fixture::history_step(3, 1, 20.0, "Contrast", settings(CURRENT)), fixture::history_step(2, 1, 10.0, "Exposure", settings(FIRST))], + } +} + +/// `(name, dateCreated, text)` of each archived row, in the order the archive holds them. +fn rows(archive: &Value, key: &str) -> Vec<(Value, Value, Value)> { + let rows = archive["photos"][0][key].as_array().unwrap_or_else(|| panic!("the archive should list {key}: {archive}")); + rows.iter().map(|r| (r["name"].clone(), r["dateCreated"].clone(), r["text"].clone())).collect() +} + +#[test] +fn compressed_history_steps_keep_their_settings_in_the_archive() { + let archived = archive("history-blob", vec![steps(|t| Field::Blob(fixture::compressed(t)))]); + let mut steps = rows(&archived, "history"); + steps.sort_by(|a, b| a.1.as_f64().partial_cmp(&b.1.as_f64()).unwrap()); + assert_eq!( + steps, + [(json!("Exposure"), json!(10.0), json!(FIRST)), (json!("Contrast"), json!(20.0), json!(CURRENT))], + "each compressed step should be archived with its decoded settings: {archived}" + ); + assert_eq!(archived["warnings"], json!([]), "no step should be reported unreadable"); +} + +#[test] +fn text_history_steps_are_archived_as_before() { + let archived = archive("history-text", vec![steps(fixture::text)]); + let mut steps = rows(&archived, "history"); + steps.sort_by(|a, b| a.1.as_f64().partial_cmp(&b.1.as_f64()).unwrap()); + assert_eq!(steps, [(json!("Exposure"), json!(10.0), json!(FIRST)), (json!("Contrast"), json!(20.0), json!(CURRENT))], "{archived}"); + assert_eq!(archived["warnings"], json!([])); +} + +#[test] +fn compressed_and_text_snapshots_keep_their_settings_in_the_archive() { + let snapshots = Table { + name: "Adobe_libraryImageDevelopSnapshot", + columns: fixture::SNAPSHOT_COLUMNS, + rows: vec![ + fixture::snapshot(5, 1, "Bright", Field::Blob(fixture::compressed("s = { Exposure2012 = 2 }"))), + fixture::snapshot(6, 1, "Plain", fixture::text("s = { Contrast2012 = 30 }")), + ], + }; + let archived = archive("snapshot-blob", vec![snapshots]); + let mut kept: Vec<_> = rows(&archived, "snapshots").into_iter().map(|(name, _, text)| (name, text)).collect(); + kept.sort_by_key(|(name, _)| name.to_string()); + assert_eq!( + kept, + [(json!("Bright"), json!("s = { Exposure2012 = 2 }")), (json!("Plain"), json!("s = { Contrast2012 = 30 }"))], + "compressed and text snapshots should both be archived with their settings: {archived}" + ); + assert_eq!(archived["warnings"], json!([])); +} + +/// A hostile or damaged catalog: each bad BLOB costs only its own row's settings, with a warning naming the image. +#[test] +fn a_malformed_settings_blob_is_archived_without_its_settings_and_warned_about() { + let mut mismatch = fixture::compressed(FIRST); + mismatch[3] = mismatch[3].wrapping_add(1); + let mut over_cap = fixture::compressed(FIRST); + over_cap[..4].copy_from_slice(&((16u32 << 20) + 1).to_be_bytes()); + let bad = [ + ("Short", vec![0, 0]), + ("Not zlib", vec![0, 0, 0, 5, 1, 2, 3, 4, 5]), + ("Wrong length", mismatch), + ("Too big", over_cap), + ("Not UTF-8", fixture::compressed_bytes(&[0xff, 0xfe])), + ]; + let mut history = steps(|t| Field::Blob(fixture::compressed(t))); + for (i, (name, bytes)) in bad.iter().enumerate() { + let id = 10 + i64::try_from(i).unwrap(); + history.rows.push(fixture::history_step(id, 1, 30.0 + id as f64, name, Field::Blob(bytes.clone()))); + } + let snapshots = Table { + name: "Adobe_libraryImageDevelopSnapshot", + columns: fixture::SNAPSHOT_COLUMNS, + rows: vec![fixture::snapshot(5, 1, "Broken", Field::Blob(vec![0, 0, 0, 9, 9]))], + }; + let archived = archive("history-bad", vec![history, snapshots]); + assert_eq!(archived["photos"].as_array().map(Vec::len), Some(1), "the photo is still read: {archived}"); + let steps = rows(&archived, "history"); + assert_eq!(steps.len(), 7, "every step is still archived: {archived}"); + for (name, _, text) in &steps { + let good = name == "Exposure" || name == "Contrast"; + assert_eq!(text.is_string(), good, "{name}: only the good steps keep settings: {archived}"); + } + assert_eq!(rows(&archived, "snapshots")[0].2, Value::Null, "the broken snapshot is archived without settings"); + let warnings: Vec<_> = archived["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).collect(); + assert_eq!(warnings.len(), bad.len() + 1, "one warning per bad step and snapshot: {warnings:?}"); + assert!(warnings.iter().all(|w| w.starts_with("image 1: ")), "each warning names the image: {warnings:?}"); + assert!(warnings.iter().any(|w| w.contains("history step 10")), "a warning names the step: {warnings:?}"); + assert!(warnings.iter().any(|w| w.contains("snapshot 5")), "a warning names the snapshot: {warnings:?}"); +} + +/// Only the settings column is decoded; any other BLOB (even one in Lightroom's compressed encoding) stays out of +/// the archive, as before. +#[test] +fn other_blob_columns_never_reach_the_archive() { + let mut history = steps(|t| Field::Blob(fixture::compressed(t))); + for row in &mut history.rows { + row[3] = Field::Blob(vec![1, 2, 3, 4]); // digest + row[10] = Field::Blob(fixture::compressed("s = { Exposure2012 = 3 }")); // valueString + } + let archived = archive("history-other-blobs", vec![history]); + for step in archived["photos"][0]["history"].as_array().unwrap() { + assert!(step.get("digest").is_none() && step.get("valueString").is_none(), "other BLOB columns leaked: {step}"); + assert!(step["text"].is_string(), "the settings are still decoded: {step}"); + } +} diff --git a/crates/engine/src/tests/merge.rs b/crates/engine/src/tests/merge.rs index ed524ae3d2..2d82c20570 100644 --- a/crates/engine/src/tests/merge.rs +++ b/crates/engine/src/tests/merge.rs @@ -40,6 +40,7 @@ fn hdr_merge_command_creates_and_imports_a_dng() { let r = s.execute("merge.hdr", &json!({"ids": ids, "autoSettings": true, "stack": true})).unwrap(); let path = r["path"].as_str().unwrap(); assert!(path.ends_with("IMG_0-HDR.dng"), "{path}"); + assert_eq!(r["reused"].as_bool(), Some(false)); let id = lightcraft_catalog::PhotoId(r["id"].as_u64().unwrap()); let p = s.catalog.photo(id).unwrap().clone(); assert_eq!((p.width, p.height), (480, 320)); @@ -55,15 +56,25 @@ fn hdr_merge_command_creates_and_imports_a_dng() { assert_eq!(st.photos[1..].iter().map(|p| p.0).collect::>(), ids); assert!(st.collapsed); assert_eq!(s.visible_cloned(), vec![id]); - // the second merge doesn't overwrite the first - let r2 = s.execute("merge.hdr", &json!({"ids": ids, "autoSettings": false})).unwrap(); - assert!(r2["path"].as_str().unwrap().ends_with("IMG_0-HDR-2.dng")); - let id2 = lightcraft_catalog::PhotoId(r2["id"].as_u64().unwrap()); - assert!(s.catalog.stack_of(id2).is_none(), "no stack without the option"); + // A repeated deterministic merge reuses the existing content instead of publishing an + // unimported uniquely named orphan. + s.execute("develop.set", &json!({"control": "light.exposure", "value": 0.73})).unwrap(); + let edited = s.develop_of(id).unwrap().as_ref().clone(); + let stack_before = s.catalog.stack_of(id).unwrap().clone(); + let undo_before = s.undo.len(); + let r2 = s.execute("merge.hdr", &json!({"ids": ids, "autoSettings": true, "stack": true})).unwrap(); + assert_eq!(r2["id"].as_u64(), Some(id.0)); + assert_eq!(r2["reused"].as_bool(), Some(true)); + assert_eq!(r2["path"].as_str(), Some(path)); + assert!(!dir.join("IMG_0-HDR-2.dng").exists(), "duplicate merge left an orphan"); + assert_eq!(s.catalog.photos().count(), 4); + assert_eq!(s.undo.len(), undo_before, "reusing merge content added an undo step"); + assert_eq!(s.develop_of(id).unwrap().as_ref(), &edited, "reusing merge content changed edits"); + assert_eq!(s.catalog.stack_of(id), Some(&stack_before), "reusing merge content changed stack"); // the type filter finds merge results (and only them) s.execute("library.filter", &json!({"merged": "hdr"})).unwrap(); let found: std::collections::HashSet<_> = s.catalog.query(&s.filter, &Default::default()).into_iter().collect(); - assert_eq!(found, [id, id2].into_iter().collect()); + assert_eq!(found, [id].into_iter().collect()); let _ = std::fs::remove_dir_all(&dir); } @@ -100,8 +111,8 @@ fn hdr_merge_keeps_the_reference_frames_lens_corrections() { let reference = s.catalog.photo(lightcraft_catalog::PhotoId(ids[1])).unwrap().clone(); let expect = if orientation == Orientation::Normal { (452, 304) } else { (304, 452) }; assert_eq!(((merged.width, merged.height), (reference.width, reference.height)), (expect, expect)); - let a = reference.embedded_lens.expect("the source's correction"); - let b = merged.embedded_lens.expect("the merged DNG carries the reference frame's correction"); + let a = reference.embedded_lens.as_deref().copied().expect("the source's correction"); + let b = merged.embedded_lens.as_deref().copied().expect("the merged DNG carries the reference frame's correction"); let (wa, wb) = (a.warp.unwrap(), b.warp.unwrap()); let (va, vb) = (a.vignette.unwrap(), b.vignette.unwrap()); let (w, h) = (expect.0 as f64, expect.1 as f64); @@ -143,6 +154,55 @@ fn a_merge_of_raws_without_colour_matrices_keeps_their_colour() { let _ = std::fs::remove_dir_all(&dir); } +#[test] +fn hdr_merge_refuses_stale_result_before_writing() { + let dir = temp_dir("hdr-stale"); + let mut paths = Vec::new(); + for (i, b) in lightcraft_merge::synth::bracket_dngs(240, 160, &[-2.0, 0.0, 2.0]).unwrap().into_iter().enumerate() { + let p = dir.join(format!("IMG_{i}.dng")); + std::fs::write(&p, b).unwrap(); + paths.push(p.to_string_lossy().to_string()); + } + let mut s = Session::new().with_fs(); + let ids = import(&mut s, paths.clone()); + let first = s.execute("merge.hdr", &json!({"ids": ids, "autoSettings": false})).unwrap(); + let id = lightcraft_catalog::PhotoId(first["id"].as_u64().unwrap()); + let path = first["path"].as_str().unwrap().to_string(); + s.execute("develop.set", &json!({"control": "light.exposure", "value": 0.73})).unwrap(); + let edited = s.develop_of(id).unwrap().as_ref().clone(); + let stack_before = s.catalog.stack_of(id).cloned(); + + std::fs::remove_file(&path).unwrap(); + let undo_before = s.undo.len(); + let missing = s.execute("merge.hdr", &json!({"ids": ids, "autoSettings": true})); + assert!(missing.as_ref().unwrap_err().to_string().contains("missing or changed")); + assert!(!std::path::Path::new(&path).exists()); + assert!(!dir.join("IMG_0-HDR-2.dng").exists()); + assert_eq!(s.undo.len(), undo_before); + assert_eq!(s.develop_of(id).unwrap().as_ref(), &edited, "repair changed edits"); + assert_eq!(s.catalog.stack_of(id).cloned(), stack_before); + + std::fs::write(&path, std::fs::read(&paths[0]).unwrap()).unwrap(); + let changed_bytes = std::fs::read(&path).unwrap(); + let changed = s.execute("merge.hdr", &json!({"ids": ids, "autoSettings": true})); + assert!(changed.as_ref().unwrap_err().to_string().contains("missing or changed")); + assert_eq!(std::fs::read(&path).unwrap(), changed_bytes); + assert!(!dir.join("IMG_0-HDR-2.dng").exists()); + assert_eq!(s.undo.len(), undo_before); + assert_eq!(s.develop_of(id).unwrap().as_ref(), &edited, "changed-source repair changed edits"); + assert_eq!(s.catalog.stack_of(id).cloned(), stack_before); + + s.execute("photo.delete", &json!({"ids": [id.0]})).unwrap(); + let deleted_bytes = std::fs::read(&path).unwrap(); + let undo_after_delete = s.undo.len(); + let failed = s.execute("merge.hdr", &json!({"ids": ids, "autoSettings": false})); + assert!(failed.as_ref().unwrap_err().to_string().contains("deleted")); + assert_eq!(std::fs::read(&path).unwrap(), deleted_bytes); + assert!(!dir.join("IMG_0-HDR-3.dng").exists(), "failed import left an orphan"); + assert_eq!(s.undo.len(), undo_after_delete); + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn panorama_command_with_auto_crop() { let dir = temp_dir("pano"); diff --git a/crates/engine/src/tests/persist.rs b/crates/engine/src/tests/persist.rs index 7ebf8464bf..7e789de8d3 100644 --- a/crates/engine/src/tests/persist.rs +++ b/crates/engine/src/tests/persist.rs @@ -216,3 +216,314 @@ fn a_preset_that_cannot_be_written_counts_as_unsaved_until_it_is() { assert!(s.unsaved().is_none(), "written once the disk works again"); assert!(String::from_utf8_lossy(&stored(&files)).contains("Mine")); } + +/// Given a library saved by an earlier version, when it is opened, then the person is told once +/// that it was upgraded and where the library as it was is kept (the files are theirs to +/// delete), and `library.info` lists it; a library that was not upgraded says nothing. +#[test] +fn an_upgraded_library_says_where_what_it_was_is_kept() { + let dir = std::env::temp_dir().join(format!("lightcraft-kept-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("catalog.snap"), include_str!("../../../catalog/src/fixtures/v6-catalog.snap.json")).unwrap(); + std::fs::write(dir.join("catalog.log"), include_str!("../../../catalog/src/fixtures/v6-catalog.log.jsonl")).unwrap(); + let mut s = Session::new(); + s.open_library(&dir, false).unwrap(); + let told = s.take_library_warnings(); + assert!(told.iter().any(|w| w.contains("catalog.snap.v6-8") && w.contains("catalog.log.v6-8") && w.contains("delete")), "{told:?}"); + assert!(dir.join("catalog.snap.v6-8").exists() && dir.join("catalog.log.v6-8").exists()); + let info = s.execute("library.info", &serde_json::json!({})).unwrap(); + assert!(info["settingsWarnings"].to_string().contains("catalog.snap.v6-8"), "{info}"); + s.close_library().unwrap(); + s.open_library(&dir, false).unwrap(); + assert!(!s.take_library_warnings().iter().any(|w| w.contains("upgraded"))); + s.close_library().unwrap(); + let _ = std::fs::remove_dir_all(&dir); +} + +/// The v6 fixture's log with its second record replaced by garbage (a record after it is still good, so it is damage, not a torn tail). +fn damaged_v6_log() -> String { + let log = include_str!("../../../catalog/src/fixtures/v6-catalog.log.jsonl"); + log.lines().enumerate().map(|(i, l)| if i == 1 { "not a record" } else { l }).collect::>().join("\n") + "\n" +} + +/// Given a library from an earlier version that has only a damaged log, when it is opened and upgraded, then the person is told +/// where the damaged log is kept (there is no kept snapshot to name it beside). +#[test] +fn an_upgraded_library_with_only_a_damaged_log_says_where_the_log_is_kept() { + let dir = std::env::temp_dir().join(format!("lightcraft-kept-dmg-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("catalog.log"), damaged_v6_log()).unwrap(); + let mut s = Session::new(); + s.open_library(&dir, false).unwrap(); + let told = s.take_library_warnings(); + assert!(told.iter().any(|w| w.contains("upgraded") && w.contains("catalog.log.damaged-")), "{told:?}"); + s.close_library().unwrap(); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A library already in this version's format whose log was damaged was not upgraded: it is not told it was. +#[test] +fn a_current_library_with_a_damaged_log_is_not_told_it_was_upgraded() { + let dir = std::env::temp_dir().join(format!("lightcraft-cur-dmg-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let mut s = Session::new(); + s.open_library(&dir, true).unwrap(); + s.execute("photo.rate", &serde_json::json!({"rating": 3})).unwrap(); + s.execute("photo.rate", &serde_json::json!({"rating": 4})).unwrap(); + s.execute("photo.rate", &serde_json::json!({"rating": 5})).unwrap(); + drop(s); + let log = std::fs::read_to_string(dir.join("catalog.log")).unwrap(); + let broken: Vec<&str> = log.lines().enumerate().map(|(i, l)| if i == 1 { "not a record" } else { l }).collect(); + std::fs::write(dir.join("catalog.log"), broken.join("\n") + "\n").unwrap(); + let mut s = Session::new(); + let damaged = s.open_library(&dir, false).unwrap().damaged.clone(); + assert!(damaged.is_some_and(|name| dir.join(name).exists()), "the log was found damaged and kept"); + let told = s.take_library_warnings(); + assert!(!told.iter().any(|w| w.contains("upgraded")), "{told:?}"); + s.close_library().unwrap(); + let _ = std::fs::remove_dir_all(&dir); +} + +/// The browser's storage: it keeps no copy of a library an upgrade replaces. +struct KeepsNothing(MemStore); + +impl Store for KeepsNothing { + fn read(&mut self, name: &str) -> std::io::Result>> { + self.0.read(name) + } + fn write_atomic(&mut self, name: &str, data: &[u8]) -> std::io::Result<()> { + self.0.write_atomic(name, data) + } + fn append(&mut self, name: &str, data: &[u8]) -> std::io::Result<()> { + self.0.append(name, data) + } + fn truncate(&mut self, name: &str, len: u64) -> std::io::Result<()> { + self.0.truncate(name, len) + } + fn keeps_replaced_formats(&self) -> bool { + false + } + fn describe(&self) -> String { + "keeps nothing".into() + } +} + +/// Given a store that keeps no replaced files (the browser's) and an older library with a damaged log, when it is opened and +/// upgraded, then the damaged log set aside is not presented as "the library as it was": there is no snapshot to go with it. +#[test] +fn a_store_that_keeps_no_files_does_not_tell_of_a_kept_damaged_log() { + let m = MemStore::new(); + m.set("catalog.snap", include_bytes!("../../../catalog/src/fixtures/v6-catalog.snap.json").to_vec()); + m.set("catalog.log", damaged_v6_log().into_bytes()); + let mut s = Session::new(); + let stores = + LibraryStores { dir: "browser".into(), catalog: Box::new(KeepsNothing(m.clone())), files: Box::new(MemStore::new()), on_disk: false }; + let report = s.open_library_in(stores, false).unwrap(); + assert!(report.damaged.is_some() && report.upgraded_from == Some(6), "the log was found damaged and the library upgraded: {report:?}"); + let told = s.take_library_warnings(); + assert!(!told.iter().any(|w| w.contains("upgraded") || w.contains("catalog.log.damaged-")), "{told:?}"); +} + +/// The same library on a store that does keep files, with no snapshot (only the damaged log): the person is told where the log is kept. +#[test] +fn a_store_that_keeps_files_tells_of_a_kept_damaged_log() { + let m = MemStore::new(); + m.set("catalog.log", damaged_v6_log().into_bytes()); + let mut s = Session::new(); + let stores = LibraryStores { dir: "kept".into(), catalog: Box::new(m.clone()), files: Box::new(MemStore::new()), on_disk: false }; + s.open_library_in(stores, false).unwrap(); + let told = s.take_library_warnings(); + assert!(told.iter().any(|w| w.contains("upgraded") && w.contains("catalog.log.damaged-")), "{told:?}"); +} + +/// An older library (format 6) that could not keep its files at open: a directory sits where the +/// first kept file goes. +fn library_that_could_not_keep_its_files(name: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("lightcraft-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join("catalog.snap.v6-8")).unwrap(); + std::fs::write(dir.join("catalog.snap.v6-8").join("in the way"), b"x").unwrap(); + std::fs::write(dir.join("catalog.snap"), include_str!("../../../catalog/src/fixtures/v6-catalog.snap.json")).unwrap(); + std::fs::write(dir.join("catalog.log"), include_str!("../../../catalog/src/fixtures/v6-catalog.log.jsonl")).unwrap(); + dir +} + +/// The names of the files kept for format 6 in `dir`. +fn kept_for_v6(dir: &std::path::Path, prefix: &str) -> Vec { + let mut names: Vec = std::fs::read_dir(dir) + .unwrap() + .map(|e| e.unwrap()) + .filter(|e| e.path().is_file()) + .map(|e| e.file_name().to_string_lossy().into_owned()) + .filter(|n| n.starts_with(prefix)) + .collect(); + names.sort(); + names +} + +/// Given an older library that could not keep its files at open, when a later compaction upgrades +/// it (the files can be kept now), then the person is told once where the library as it was is +/// kept, as when the open upgrades it, and a later compaction tells nothing more. +#[test] +fn a_later_upgrade_says_where_what_it_was_is_kept() { + let dir = library_that_could_not_keep_its_files("kept-later"); + let mut s = Session::new(); + s.open_library(&dir, false).unwrap(); + assert!(s.take_library_warnings().iter().all(|w| !w.contains("upgraded")), "not upgraded at open"); + assert!(s.compact_library().is_err(), "its files can't be kept yet"); + std::fs::remove_dir_all(dir.join("catalog.snap.v6-8")).unwrap(); + s.compact_library().unwrap(); + let (snap, log) = (kept_for_v6(&dir, "catalog.snap.v6-"), kept_for_v6(&dir, "catalog.log.v6-")); + assert_eq!((snap.len(), log.len()), (1, 1), "the files as they were are kept"); + let told = s.take_library_warnings(); + assert!(told.iter().any(|w| w.contains(&snap[0]) && w.contains(&log[0]) && w.contains("delete")), "{told:?}"); + let info = s.execute("library.info", &serde_json::json!({})).unwrap(); + assert!(info["settingsWarnings"].to_string().contains(&snap[0]), "{info}"); + s.compact_library().unwrap(); + assert!(s.take_library_warnings().is_empty(), "told once"); + s.close_library().unwrap(); + let _ = std::fs::remove_dir_all(&dir); +} + +/// The same, when the compaction is written by the background worker: the person is told once its +/// result is taken (the frame loop's `persist`), not before. +#[test] +fn a_background_upgrade_says_where_what_it_was_is_kept() { + let dir = library_that_could_not_keep_its_files("kept-background"); + let mut s = Session::new(); + s.open_library(&dir, false).unwrap(); + let _ = s.take_library_warnings(); + std::fs::remove_dir_all(dir.join("catalog.snap.v6-8")).unwrap(); + s.compact_soon(); + let started = std::time::Instant::now(); + let mut told = Vec::new(); + while told.is_empty() && started.elapsed() < std::time::Duration::from_secs(30) { + std::thread::sleep(std::time::Duration::from_millis(10)); + s.persist().unwrap(); + told = s.take_library_warnings(); + } + let (snap, log) = (kept_for_v6(&dir, "catalog.snap.v6-"), kept_for_v6(&dir, "catalog.log.v6-")); + assert_eq!((snap.len(), log.len()), (1, 1)); + assert!(told.iter().any(|w| w.contains(&snap[0]) && w.contains(&log[0])), "{told:?}"); + s.persist().unwrap(); + assert!(s.take_library_warnings().is_empty(), "told once"); + s.close_library().unwrap(); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A batch that fails and whose rollback then fails halfway leaves the catalog changed. The change must reach the +/// journal (a restart finds what the session had) and the person must be able to take it back. +#[test] +fn a_batch_that_cannot_be_rolled_back_whole_is_journaled_and_undoable() { + use lightcraft_catalog::{CatalogError, Op, PhotoId, Stack}; + + let store = Flaky::default(); + let mut s = open(&store, true); + let ids: Vec = s.catalog.photos().map(|p| p.id).take(2).collect(); + let stack = s.catalog.alloc_stack_id(); + s.commit("Stack", Op::AddStack { stack: Stack { id: stack, photos: ids.clone(), collapsed: false } }).unwrap(); + s.persist().unwrap(); + let before = s.catalog.to_snapshot(); + + // the photo goes, then its stack, then an op fails: putting the stack back needs the photo, which comes later + let batch = + Op::Batch { ops: vec![Op::RemovePhoto { id: ids[0] }, Op::RemoveStack { id: stack }, Op::SetRating { id: PhotoId(9_999), rating: 1 }] }; + let undo_steps = s.undo.len(); + let e = s.execute_fn("test.batch", |s| s.commit("Delete", batch).map(|()| json!({}))).unwrap_err(); + assert!(matches!(e, EngineError::Catalog(CatalogError::PartlyApplied { .. })), "{e:?}"); + assert!(e.to_string().contains("partly"), "the error says the change stayed in part: {e}"); + let torn = s.catalog.to_snapshot(); + assert_ne!(torn, before, "the rollback went only part of the way"); + assert!(s.catalog.photo(ids[0]).is_some() && s.catalog.stack(stack).is_none()); + + // a restart in the middle finds what the session had + assert_eq!(open(&store.crash_copy(), true).catalog.to_snapshot(), torn, "the journal and the memory agree"); + assert_eq!(s.undo.len(), undo_steps + 1, "what is left of the batch is one undo step"); + + // undo finishes the rollback, and that too is journaled + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.catalog.to_snapshot(), before); + assert_eq!(open(&store.crash_copy(), true).catalog.to_snapshot(), before); +} + +/// An undo whose catalog step fails and cannot be rolled back whole is journaled as well, and what is left of it is a +/// step on the other stack that takes it back. +#[test] +fn an_undo_step_that_cannot_be_rolled_back_whole_is_journaled_and_can_be_taken_back() { + use lightcraft_catalog::{CatalogError, Op, PhotoId, Stack}; + + let store = Flaky::default(); + let mut s = open(&store, true); + let ids: Vec = s.catalog.photos().map(|p| p.id).take(2).collect(); + let stack = s.catalog.alloc_stack_id(); + s.commit("Stack", Op::AddStack { stack: Stack { id: stack, photos: ids.clone(), collapsed: false } }).unwrap(); + s.persist().unwrap(); + let before = s.catalog.to_snapshot(); + let torn = + Op::Batch { ops: vec![Op::RemovePhoto { id: ids[0] }, Op::RemoveStack { id: stack }, Op::SetRating { id: PhotoId(9_999), rating: 1 }] }; + s.undo.push(crate::UndoEntry { label: "Broken".into(), op: torn, folder: None, retry_inverse: Vec::new(), retry_sidecars: Vec::new() }); + let (undo_len, redo_len) = (s.undo.len(), s.redo.len()); + + let e = s.execute("edit.undo", &json!({})).unwrap_err(); + assert!(matches!(e, EngineError::Catalog(CatalogError::PartlyApplied { .. })), "{e:?}"); + let torn_state = s.catalog.to_snapshot(); + assert_ne!(torn_state, before); + assert_eq!((s.undo.len(), s.redo.len()), (undo_len - 1, redo_len + 1), "the step is not left to fail again"); + assert_eq!(open(&store.crash_copy(), true).catalog.to_snapshot(), torn_state, "the journal and the memory agree"); + + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.catalog.to_snapshot(), before); + assert_eq!(open(&store.crash_copy(), true).catalog.to_snapshot(), before); +} + +/// A folder step whose catalog part is only partly taken back keeps the folder move in its undo step. +#[test] +fn a_partly_applied_folder_step_keeps_its_folder_move() { + use lightcraft_catalog::{CatalogError, Op, PhotoId, Stack}; + + let store = Flaky::default(); + let mut s = open(&store, true); + let ids: Vec = s.catalog.photos().map(|p| p.id).take(2).collect(); + let stack = s.catalog.alloc_stack_id(); + s.commit("Stack", Op::AddStack { stack: Stack { id: stack, photos: ids.clone(), collapsed: false } }).unwrap(); + let torn = + || Op::Batch { ops: vec![Op::RemovePhoto { id: ids[0] }, Op::RemoveStack { id: stack }, Op::SetRating { id: PhotoId(9_999), rating: 1 }] }; + + // the folder was renamed before the commit: the step that takes the change back renames it back + let folder = crate::FolderMove { from: "/new".into(), to: "/old".into(), on_disk: true }; + let e = s.commit_with_folder("Rename Folder", torn(), folder.clone()).unwrap_err(); + assert!(matches!(e, EngineError::Catalog(CatalogError::PartlyApplied { .. })), "{e:?}"); + assert_eq!(s.undo.last().and_then(|u| u.folder.clone()), Some(folder)); + // (a failure that changed nothing leaves no step, so no folder to put on one) + let steps = s.undo.len(); + assert!( + s.commit_with_folder( + "Rename Folder", + Op::SetRating { id: PhotoId(9_999), rating: 1 }, + crate::FolderMove { from: "/a".into(), to: "/b".into(), on_disk: true } + ) + .is_err() + ); + assert_eq!(s.undo.len(), steps); +} + +/// An undo step that fails part-way keeps the inverses of the path corrections it carried: they follow what is left, +/// as when a step succeeds. +#[test] +fn a_partly_applied_undo_step_keeps_its_retry_inverses() { + use lightcraft_catalog::{Op, PhotoId, Stack}; + + let mut s = open(&Flaky::default(), true); + let ids: Vec = s.catalog.photos().map(|p| p.id).take(2).collect(); + let fix = Op::SetRating { id: ids[1], rating: 4 }; + let stack = s.catalog.alloc_stack_id(); + s.commit("Stack", Op::AddStack { stack: Stack { id: stack, photos: ids.clone(), collapsed: false } }).unwrap(); + let step = + Op::Batch { ops: vec![Op::RemovePhoto { id: ids[0] }, Op::RemoveStack { id: stack }, Op::SetRating { id: PhotoId(9_999), rating: 1 }] }; + s.undo.push(crate::UndoEntry { label: "Broken".into(), op: step, folder: None, retry_inverse: vec![fix.clone()], retry_sidecars: Vec::new() }); + assert!(s.execute("edit.undo", &json!({})).is_err()); + let Some(Op::Batch { ops }) = s.redo.last().map(|r| r.op.clone()) else { panic!("the step that takes it back is a batch") }; + assert_eq!(ops.last(), Some(&fix)); +} diff --git a/crates/engine/src/tests/segment.rs b/crates/engine/src/tests/segment.rs index 51d6e26e8f..57ee15a3b5 100644 --- a/crates/engine/src/tests/segment.rs +++ b/crates/engine/src/tests/segment.rs @@ -50,6 +50,17 @@ fn status_and_model_commands_without_the_model() { assert_eq!(st["installed"], false); assert_eq!(st["download"]["running"], false); assert!(st["license"].as_str().unwrap().contains("SAM License")); + // where it runs: nowhere yet (no model loaded), and nothing timed + if Segmenter::AVAILABLE { + let b = &st["backend"]; + assert!(b["device"].is_null() && b["encodeMs"].is_null() && b["analyzeMs"].is_null(), "{b}"); + // the GPU switches show before the model loads (macOS: Metal, which only the environment switches govern) + let off = if cfg!(target_os = "macos") { lightcraft_gpu::env_off_reason().map(str::to_string) } else { lightcraft_gpu::switched_off() }; + assert_eq!(b["fallback"].as_str(), off.as_deref(), "{b}"); + } else { + assert!(st["backend"].is_null()); + } + assert_eq!(st["runOn"], "auto"); // downloading needs the user's consent, and names the size and the licence let e = s.execute("segment.model.download", &json!({})).unwrap_err().to_string(); assert!(e.contains("acknowledged") && e.contains("SAM License") && e.contains("GB"), "{e}"); @@ -332,3 +343,37 @@ fn a_missing_model_is_model_missing_by_kind() { } } } + +/// Where SAM 3 runs is the user's choice (`segment.settings`), shown by `segment.model.status`, kept in the settings +/// file and read back by the next session; a bad value is refused and changes nothing. +#[test] +fn the_choice_of_where_ai_masks_run_is_kept() { + let dir = tmp("runon"); + let file = dir.join("models").join("sam3-settings.json"); + let mut s = Session::with_demo(); + s.segmenter.settings_file = Some(file.clone()); + assert_eq!(s.execute("segment.settings", &json!({})).unwrap()["runOn"], "auto"); + assert_eq!(s.execute("segment.settings", &json!({"runOn": "cpu"})).unwrap()["runOn"], "cpu"); + let st = s.execute("segment.model.status", &json!({})).unwrap(); + assert_eq!(st["runOn"], "cpu"); + if Segmenter::AVAILABLE { + assert_eq!(st["backend"]["fallback"], crate::segment::CPU_CHOSEN, "{st}"); + } + let e = s.execute("segment.settings", &json!({"runOn": "gpu"})).unwrap_err().to_string(); + assert!(e.contains("auto or cpu"), "{e}"); + assert_eq!(s.segmenter.run_on(), crate::segment::RunOn::Cpu); + let saved: serde_json::Value = serde_json::from_slice(&std::fs::read(&file).unwrap()).unwrap(); + assert_eq!(saved["runOn"], "cpu"); + // the next session reads it; a damaged file is Automatic + let mut again = Session::with_demo(); + again.segmenter.settings_file = Some(file.clone()); + again.segmenter.load_settings(); + assert_eq!(again.segmenter.run_on(), crate::segment::RunOn::Cpu); + std::fs::write(&file, b"{not json").unwrap(); + again.segmenter.load_settings(); + assert_eq!(again.segmenter.run_on(), crate::segment::RunOn::Auto); + // without a settings file the choice holds for the session + let mut memory = Session::with_demo(); + assert_eq!(memory.execute("segment.settings", &json!({"runOn": "cpu"})).unwrap()["runOn"], "cpu"); + let _ = std::fs::remove_dir_all(dir); +} diff --git a/crates/engine/src/tests/spots.rs b/crates/engine/src/tests/spots.rs index 28a9fca0b1..57d99a31e0 100644 --- a/crates/engine/src/tests/spots.rs +++ b/crates/engine/src/tests/spots.rs @@ -321,3 +321,39 @@ fn mask_and_spot_targets_preserve_explicit_defaults_and_selection_clearing() { s.execute("mask.brushStroke", &json!({"points": [[0.5, 0.5]]})).unwrap(); assert_eq!(s.develop_of(s.active().unwrap()).unwrap().masks.len(), 3); } + +/// A brushed stroke recorded a point per frame (issue #2359): stationary repeats and points closer than a +/// quarter of the size collapse, the ends stay, and a click is still one point. +#[test] +fn spot_add_thins_a_stroke_to_a_quarter_of_the_size() { + let mut s = Session::with_demo(); + let size = 0.04; + // 60 samples along x (a point every 0.001), with 5 stationary repeats at the start and end + let mut pts: Vec<[f64; 2]> = vec![[0.3, 0.5]; 5]; + pts.extend((0..60).map(|i| [0.3 + 0.001 * f64::from(i), 0.5])); + pts.extend(vec![[0.359, 0.5]; 5]); + s.execute("spot.add", &json!({"mode": "heal", "points": pts, "size": size, "source": [0.1, 0.0]})).unwrap(); + let p = spots(&s)[0].points.clone(); + // the demo photo's shape decides how far a quarter of the size is along x + let dims = { + let ph = s.catalog.photo(s.active().unwrap()).unwrap(); + let (w, h) = (f64::from(ph.width), f64::from(ph.height)); + if ph.develop.orientation.swaps_axes() { (h, w) } else { (w, h) } + }; + let long = dims.0.max(dims.1); + let steps = 0.059 * dims.0 / long / (size / 4.0); + assert!((p.len() as f64 - (steps + 1.0)).abs() <= 2.0, "a stroke of {steps:.1} spacings is about {} points, got {p:?}", steps + 1.0); + assert!(p.len() < 20, "60 samples and 10 repeats collapse: {}", p.len()); + assert_eq!((p[0].x, p[0].y), (0.3, 0.5), "first point kept"); + assert!((p.last().unwrap().x - 0.359).abs() < 1e-9, "last point kept: {p:?}"); + // the spacing counts in long-edge units, so no two neighbours are closer than size/4 (bar the last) + for w in p.windows(2).take(p.len().saturating_sub(2)) { + let d = ((w[1].x - w[0].x) * dims.0 / long).hypot((w[1].y - w[0].y) * dims.1 / long); + assert!(d >= size / 4.0 - 1e-12, "spacing {d} between {w:?}"); + } + // a click and a held click stay one point + s.execute("spot.add", &json!({"points": [[0.5, 0.5]], "size": size, "source": [0.1, 0.0]})).unwrap(); + assert_eq!(spots(&s)[1].points.len(), 1); + s.execute("spot.add", &json!({"points": [[0.5, 0.5], [0.5, 0.5], [0.5001, 0.5]], "size": size, "source": [0.1, 0.0]})).unwrap(); + assert_eq!(spots(&s)[2].points.len(), 1, "a jitter below the spacing is the same spot"); +} diff --git a/crates/engine/src/tests/task_queue.rs b/crates/engine/src/tests/task_queue.rs new file mode 100644 index 0000000000..939c2d3042 --- /dev/null +++ b/crates/engine/src/tests/task_queue.rs @@ -0,0 +1,318 @@ +//! Tasks waiting in line for their lane (see `crate::activity`), with the preview builds. +//! +//! Scenarios, in the words of an agent building previews for several shoots: +//! +//! * Build Previews while a build runs: without `queue` it is refused, as it always was. With `queue` it waits +//! behind the build, `activity.list` says it is next, and it builds the photos chosen when it was asked. +//! * It starts by itself when the build ahead of it ends. +//! * `activity.cancel` on it takes it out of the line: it never runs; `all` empties the line. +//! * The line is bounded. +//! * Another library: nothing waits for it. +//! +//! These go through commands and `activity.list` only, so that they describe what a control or MCP client sees. + +use std::path::PathBuf; +use std::sync::Arc; +use std::sync::atomic::Ordering; + +use serde_json::{Value, json}; + +use crate::Session; +use crate::activity::{Cancel, MAX_WAITING, TaskGuard}; +use crate::cmd::previews::PreviewBuild; + +fn temp_dir(tag: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("lc-task-queue-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d +} + +/// A preview build that holds the lane until [`release`]: its row runs, and the build reads as unfinished. +struct Hold { + _row: TaskGuard, + build: Arc, +} + +fn hold(s: &mut Session) -> Hold { + let build = Arc::new(PreviewBuild::default()); + s.preview_build = Some(build.clone()); + Hold { _row: s.activity.start("previews", "Building previews", Cancel::Yes), build } +} + +/// The held build ends as a real one does: finished first, then its row goes. +fn release(h: Hold) { + h.build.finished.store(true, Ordering::Release); + drop(h); +} + +/// Wait (at most a minute) until no task runs or waits. +fn settle(s: &mut Session) { + let t0 = std::time::Instant::now(); + loop { + // any command lets a waiting task whose lane is free start (the app's frame loop does too) + let rows = tasks(s); + if rows.is_empty() { + return; + } + assert!(t0.elapsed().as_secs() < 60, "tasks still listed: {rows:?}"); + std::thread::sleep(std::time::Duration::from_millis(10)); + } +} + +fn tasks(s: &mut Session) -> Vec { + s.execute("activity.list", &json!({})).unwrap()["tasks"].as_array().cloned().unwrap_or_default() +} + +fn build_ids(s: &Session, n: usize) -> Vec { + s.catalog.photos().take(n).map(|p| p.id.0).collect() +} + +/// Given a preview build running and two photos chosen, when Build Previews is asked for with `queue`, then it waits +/// behind the build, first in line, with nothing done. When other photos are chosen meanwhile and the build ahead +/// ends, then it starts by itself and builds the two photos chosen when it was asked. +#[test] +fn a_build_asked_for_while_one_runs_waits_behind_it_and_builds_the_photos_chosen_then() { + let mut s = Session::with_demo(); + let ids = build_ids(&s, 3); + s.execute("library.select", &json!({"ids": [ids[0], ids[1]]})).unwrap(); + let h = hold(&mut s); + let r = s.execute("library.buildPreviews", &json!({"edge": 256, "queue": true})).unwrap(); + let id = r["queued"].as_u64().expect("an id while it waits"); + assert_eq!(r["place"], 1); + let rows = tasks(&mut s); + assert_eq!(rows.len(), 2, "the running build, then the waiting one: {rows:?}"); + assert_eq!(rows[1]["id"], id); + assert_eq!((rows[1]["waiting"].as_bool(), rows[1]["place"].as_u64(), rows[1]["lane"].as_str()), (Some(true), Some(1), Some("previews"))); + assert_eq!((rows[1]["done"].as_u64(), rows[1]["total"].as_u64()), (Some(0), Some(0))); + assert_eq!(rows[1]["label"], "Building previews"); + assert_eq!((rows[0]["waiting"].as_bool(), rows[0]["place"].as_u64()), (Some(false), Some(0)), "the running one is not in line"); + s.execute("library.select", &json!({"ids": [ids[2]]})).unwrap(); + release(h); + settle(&mut s); + let progress = s.execute("library.previewProgress", &json!({})).unwrap(); + assert_eq!((progress["total"].as_u64(), progress["done"].as_u64()), (Some(2), Some(2)), "{progress}"); + // the journal has the call that asked for it, once: starting it was not a second call + assert_eq!(s.journal.iter().filter(|(c, _)| c == "library.buildPreviews").count(), 1, "{:?}", s.journal); +} + +/// Given a preview build running, when a build is asked for without `queue`, then it is refused as before, and +/// nothing waits. +#[test] +fn a_build_asked_for_while_one_runs_is_refused_unless_it_asks_to_queue() { + let mut s = Session::with_demo(); + let h = hold(&mut s); + let e = s.execute("library.buildPreviews", &json!({"edge": 256})).unwrap_err().to_string(); + assert!(e.contains("a preview build is already running"), "{e}"); + let e = s.execute("library.buildPreviews", &json!({"edge": 256, "queue": false})).unwrap_err().to_string(); + assert!(e.contains("a preview build is already running"), "{e}"); + assert_eq!(tasks(&mut s).len(), 1, "only the running build is listed"); + release(h); + assert!(tasks(&mut s).is_empty()); +} + +/// Given no build running, when a build is asked for with `queue`, then it starts at once, as one without it does. +#[test] +fn a_build_that_asks_to_queue_starts_at_once_when_nothing_is_ahead_of_it() { + let mut s = Session::with_demo(); + let ids = build_ids(&s, 2); + let r = s.execute("library.buildPreviews", &json!({"ids": ids, "edge": 256, "queue": true, "wait": true})).unwrap(); + assert!(r.get("queued").is_none(), "{r}"); + assert_eq!((r["total"].as_u64(), r["done"].as_u64()), (Some(2), Some(2)), "{r}"); +} + +/// Given a build waiting behind another, when `activity.cancel` is asked for it, then it leaves the line and never +/// runs. +#[test] +fn a_waiting_build_taken_out_of_the_line_never_runs() { + let mut s = Session::with_demo(); + let ids = build_ids(&s, 1); + let h = hold(&mut s); + let held = h.build.clone(); + let id = s.execute("library.buildPreviews", &json!({"ids": ids, "edge": 256, "queue": true})).unwrap()["queued"].as_u64().unwrap(); + assert_eq!(s.execute("activity.cancel", &json!({"id": id})).unwrap()["cancelled"], 1); + assert_eq!(tasks(&mut s).len(), 1, "only the running build is left"); + assert!(s.execute("activity.cancel", &json!({"id": id})).is_err(), "it is gone: an unknown id"); + release(h); + settle(&mut s); + assert!(s.preview_build.as_ref().is_some_and(|b| Arc::ptr_eq(b, &held)), "no build started after the held one"); +} + +/// Given builds waiting, when every task is cancelled, then the line is empty and the count includes the waiting ones, +/// so that nothing starts as soon as the running build stops. +#[test] +fn cancelling_every_task_empties_the_line() { + let mut s = Session::with_demo(); + let ids = build_ids(&s, 1); + let h = hold(&mut s); + let held = h.build.clone(); + for _ in 0..2 { + s.execute("library.buildPreviews", &json!({"ids": ids, "edge": 256, "queue": true})).unwrap(); + } + assert_eq!(tasks(&mut s).len(), 3); + assert_eq!(s.execute("activity.cancel", &json!({"all": true})).unwrap()["cancelled"], 3, "the running one and the two waiting"); + assert_eq!(tasks(&mut s).len(), 1, "only the running (stopping) build is listed"); + release(h); + settle(&mut s); + assert!(s.preview_build.as_ref().is_some_and(|b| Arc::ptr_eq(b, &held)), "nothing started after it"); +} + +/// Given a full line, when one more build is asked for, then it is refused and says why; the line is as it was. +#[test] +fn the_line_is_bounded() { + let mut s = Session::with_demo(); + let ids = build_ids(&s, 1); + let h = hold(&mut s); + for place in 1..=MAX_WAITING { + let r = s.execute("library.buildPreviews", &json!({"ids": ids, "edge": 256, "queue": true})).unwrap(); + assert_eq!(r["place"].as_u64(), Some(place as u64)); + } + let e = s.execute("library.buildPreviews", &json!({"ids": ids, "edge": 256, "queue": true})).unwrap_err().to_string(); + assert!(e.contains(&MAX_WAITING.to_string()), "{e}"); + assert_eq!(tasks(&mut s).len(), MAX_WAITING + 1); + s.execute("activity.cancel", &json!({"all": true})).unwrap(); + release(h); +} + +/// Build Smart Previews in the background waits in the same line (one preview build at a time). +#[test] +fn smart_previews_wait_behind_a_preview_build() { + let dir = temp_dir("smart"); + let mut s = Session::new(); + s.open_library(&dir, true).unwrap(); + let ids = build_ids(&s, 2); + let h = hold(&mut s); + let e = s.execute("library.smartPreviews", &json!({"ids": ids, "background": true})).unwrap_err().to_string(); + assert!(e.contains("already running"), "{e}"); + let r = s.execute("library.smartPreviews", &json!({"ids": ids, "background": true, "queue": true})).unwrap(); + assert!(r["queued"].is_u64(), "{r}"); + let rows = tasks(&mut s); + assert_eq!( + (rows[1]["kind"].as_str(), rows[1]["waiting"].as_bool(), rows[1]["lane"].as_str()), + (Some("smartPreviews"), Some(true), Some("previews")) + ); + release(h); + settle(&mut s); + let progress = s.execute("library.previewProgress", &json!({})).unwrap(); + // (the demo photos aren't files, so it has nothing to build: that it ran at all is what counts) + assert_eq!(progress["what"], "smart previews", "{progress}"); + assert_eq!(progress["running"], false, "{progress}"); + s.close_library().unwrap(); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Two builds waiting, the first of which can't start (here: it was asked for a size no build accepts, as if what it +/// needs went away while it waited): the second still runs. +#[test] +fn a_build_that_can_not_start_does_not_hold_up_the_line() { + let mut s = Session::with_demo(); + let ids = build_ids(&s, 1); + let h = hold(&mut s); + let bad = crate::activity::Request { command: "library.buildPreviews".into(), params: json!({"size": "huge"}) }; + s.activity.enqueue("previews", "Building previews", bad).unwrap(); + s.execute("library.buildPreviews", &json!({"ids": ids, "edge": 256, "queue": true})).unwrap(); + release(h); + settle(&mut s); + let progress = s.execute("library.previewProgress", &json!({})).unwrap(); + assert_eq!((progress["total"].as_u64(), progress["done"].as_u64()), (Some(1), Some(1)), "{progress}"); +} + +/// `queue` with `wait` while a build runs: the call can't both wait in line and return when the build is done. +#[test] +fn a_build_that_would_wait_for_its_turn_and_its_end_is_refused() { + let mut s = Session::with_demo(); + let h = hold(&mut s); + let e = s.execute("library.buildPreviews", &json!({"edge": 256, "queue": true, "wait": true})).unwrap_err().to_string(); + assert!(e.contains("wait"), "{e}"); + assert_eq!(tasks(&mut s).len(), 1); + release(h); +} + +/// Given a build waiting and one still running, when another library is opened, then nothing waits any more: the +/// build asked for was about the old library's photos. +#[test] +fn another_library_drops_what_waits() { + let dir = temp_dir("switch"); + let mut s = Session::with_demo(); + let ids = build_ids(&s, 1); + let h = hold(&mut s); + s.execute("library.buildPreviews", &json!({"ids": ids, "edge": 256, "queue": true})).unwrap(); + assert_eq!(tasks(&mut s).len(), 2); + s.open_library(&dir, false).unwrap(); + let rows = tasks(&mut s); + assert_eq!(rows.len(), 1, "only the old library's running build: {rows:?}"); + assert_eq!(rows[0]["waiting"], false); + release(h); + settle(&mut s); + s.close_library().unwrap(); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Given a build that ended and a build waiting behind it, when the next command starts the waiting one before the +/// app announced the first, then the first is kept (once, with its counts) for the frontend to announce, and the +/// new build is the current one. +#[test] +fn a_build_replaced_by_the_one_waiting_behind_it_is_kept_until_it_is_announced() { + let mut s = Session::with_demo(); + let ids = build_ids(&s, 1); + let h = hold(&mut s); + let first = h.build.clone(); + first.done.store(2, Ordering::Relaxed); + first.failed.store(1, Ordering::Relaxed); + s.execute("library.buildPreviews", &json!({"ids": ids, "edge": 256, "queue": true})).unwrap(); + release(h); + tasks(&mut s); // the command that ends up starting the waiting build + assert!(s.preview_build.as_ref().is_some_and(|b| !Arc::ptr_eq(b, &first)), "the waiting build is the current one"); + let kept = s.take_unreported_builds(); + assert_eq!(kept.len(), 1); + assert!(Arc::ptr_eq(&kept[0], &first)); + assert_eq!((kept[0].done.load(Ordering::Relaxed), kept[0].failed.load(Ordering::Relaxed)), (2, 1)); + assert!(s.take_unreported_builds().is_empty(), "once"); + settle(&mut s); +} + +/// A build the frontend announced already is not kept when the next one replaces it. +#[test] +fn a_build_that_was_announced_is_not_kept_when_the_next_one_replaces_it() { + let mut s = Session::with_demo(); + let ids = build_ids(&s, 1); + let h = hold(&mut s); + h.build.reported.store(true, Ordering::Relaxed); + s.execute("library.buildPreviews", &json!({"ids": ids, "edge": 256, "queue": true})).unwrap(); + release(h); + tasks(&mut s); + assert!(s.take_unreported_builds().is_empty()); + settle(&mut s); +} + +/// Given a build that ended and a build waiting in line behind it that has not been started yet, when Build Previews is +/// asked for without `queue`, then it is refused, as it is while a build runs: it does not start ahead of the one +/// waiting, which the line starts after this command. +#[test] +fn a_build_asked_for_without_queue_does_not_go_ahead_of_one_waiting_in_line() { + let mut s = Session::with_demo(); + let ids = build_ids(&s, 1); + let running = hold(&mut s); + s.execute("library.buildPreviews", &json!({"ids": ids, "edge": 256, "queue": true})).unwrap()["queued"].as_u64().expect("it waits"); + // the build ends, and nothing has started the one waiting yet (no command or frame since) + release(running); + let refused = s.execute("library.buildPreviews", &json!({"ids": ids, "edge": 256})).unwrap_err().to_string(); + assert!(refused.contains("preview build"), "{refused}"); + settle(&mut s); +} + +/// Given a build running and two builds waiting behind it, when the build ends, then both start in turn, each one when +/// the lane is free (the line is not "ahead" of the build it is starting). +#[test] +fn builds_waiting_in_line_all_start_in_turn() { + let mut s = Session::with_demo(); + let ids = build_ids(&s, 1); + let running = hold(&mut s); + for _ in 0..2 { + s.execute("library.buildPreviews", &json!({"ids": ids, "edge": 256, "queue": true})).unwrap()["queued"].as_u64().expect("it waits"); + } + release(running); + settle(&mut s); + // the held build, and the first of the two, were replaced by the next: three builds ran in all + assert_eq!(s.take_unreported_builds().len(), 2, "both waiting builds started"); +} diff --git a/crates/engine/src/tests/view_follow.rs b/crates/engine/src/tests/view_follow.rs index 88e365d554..115eaaacd6 100644 --- a/crates/engine/src/tests/view_follow.rs +++ b/crates/engine/src/tests/view_follow.rs @@ -7,17 +7,26 @@ use serde_json::{Value, json}; use crate::Session; /// A small generator of numbers that is the same on every run. -struct Dice(u64); +struct Dice { + state: u64, + /// How many photos the edits moved to Local. + to_local: usize, +} impl Dice { + fn new(seed: u64) -> Self { + Dice { state: seed, to_local: 0 } + } + fn roll(&mut self, sides: usize) -> usize { - self.0 = lightcraft_catalog::mix64(self.0); - (self.0 % sides.max(1) as u64) as usize + self.state = lightcraft_catalog::mix64(self.state); + (self.state % sides.max(1) as u64) as usize } } /// A library of `n` photos in three folders, with ratings, flags, keywords and dates spread over them, an album -/// holding every third photo, a smart album of the photos without keywords, and a stack. +/// holding every third photo, a smart album of the photos without keywords, and a stack. About one photo in four +/// has the content of another (some as a Duplicate's `:dup` key), and a few have no content hash. fn library(n: usize) -> (Session, Vec, u64, u64) { let mut s = Session::new(); let mut ids = Vec::new(); @@ -34,6 +43,11 @@ fn library(n: usize) -> (Session, Vec, u64, u64) { &format!("2026-01-{:02}T10:00:00", 1 + i % 9), ); p.captured = Some(format!("2025-{:02}-{:02}T10:00:{:02}", 1 + i % 12, 1 + i % 28, i % 60)); + p.content_hash = match i % 13 { + 0 => None, + 5 => Some(format!("{:032x}:dup{}", (i * 7) % (n * 4 / 5).max(1), id.0)), + _ => Some(format!("{:032x}", (i * 7) % (n * 4 / 5).max(1))), + }; s.commit("Add", Op::AddPhoto { photo: Box::new(p) }).unwrap(); ids.push(id); } @@ -56,8 +70,9 @@ fn library(n: usize) -> (Session, Vec, u64, u64) { } /// One edit at random: most touch a photo or a few (what it is rated, flagged, keyworded, developed; when it was -/// taken; where its file is; whether it is in the library at all), some change an album, a stack or the library's -/// past, and now and then a photo is added or removed for good. +/// taken; where its file is and what is in it; whether it is in the library at all), some change an album, a stack +/// or the library's past, and now and then a photo is added (at times with the content of one the library has) or +/// removed for good. fn edit(s: &mut Session, dice: &mut Dice, ids: &mut Vec, album: u64) { let chosen: Vec = (0..1 + dice.roll(3)).map(|_| ids[dice.roll(ids.len())].0).collect(); let one = PhotoId(chosen[0]); @@ -80,6 +95,7 @@ fn edit(s: &mut Session, dice: &mut Dice, ids: &mut Vec, album: u64) { let name = format!("NEW_{n:04}.jpg"); let mut p = Photo::new(id, Source::File { path: format!("/pics/{}/{name}", n % 3) }, &name, "JPEG", 60, 40, "2026-02-01T10:00:00"); p.captured = Some(format!("2025-{:02}-11T09:00:00", 1 + n % 12)); + p.content_hash = s.catalog.photo(ids[dice.roll(ids.len())]).and_then(|q| q.content_hash.clone()).filter(|_| n.is_multiple_of(8)); if s.commit("Add", Op::AddPhoto { photo: Box::new(p) }).is_ok() { ids.push(id); } @@ -89,8 +105,29 @@ fn edit(s: &mut Session, dice: &mut Dice, ids: &mut Vec, album: u64) { let _ = s.commit("Remove", Op::RemovePhoto { id: one }); return; } + 2 if n % 4 == 2 => { + // the file's content changed (Reload): it is now the same as another photo's, or has no hash + let content_hash = s.catalog.photo(ids[dice.roll(ids.len())]).and_then(|q| q.content_hash.clone()).filter(|_| n % 8 == 2); + if let Some(p) = s.catalog.photo(one) { + let op = Op::SetContent { + id: one, + width: p.width, + height: p.height, + file_size: p.file_size, + content_hash, + preview_only: p.preview_only.clone(), + preview_checked: p.preview_checked.clone(), + }; + let _ = s.commit("Reload", op); + } + return; + } 2 => { - let _ = s.commit("Local", Op::SetLocal { id: one, local: n.is_multiple_of(2) }); + // (n % 4 is 3 here: its quotient decides, or no photo would ever move to Local) + let local = (n / 4).is_multiple_of(2); + if s.commit("Local", Op::SetLocal { id: one, local }).is_ok() && local { + dice.to_local += 1; + } return; } _ => {} @@ -133,7 +170,7 @@ fn relative_clock_session(captures: &[&str]) -> (Session, std::sync::Arc 400, "followed {} times, worked out {} times", s.view_followed, s.view_worked_out); + // (and the edits did move photos to Local, a case of its own for what the view keeps) + assert!(dice.to_local > 0, "no photo moved to Local"); } #[test] @@ -403,6 +448,9 @@ fn the_albums_counts_followed_through_edits_are_the_counts_made_from_every_photo json!({"edited": true}), json!({"dateFrom": "2025-06-01"}), json!({"text": "REN"}), + // whether another photo has the same content: an edit to one photo changes it for others + json!({"ruleSet": {"match": "all", "rules": [{"field": "sameContent", "op": "is", "value": true}]}}), + json!({"ruleSet": {"match": "all", "rules": [{"field": "sameContent", "op": "is", "value": false}]}}), ] { let made = s.execute("album.createSmart", &json!({"name": "More", "rules": rules})); assert!(made.is_ok(), "{rules}: {made:?}"); @@ -420,7 +468,7 @@ fn the_albums_counts_followed_through_edits_are_the_counts_made_from_every_photo }; let mut tally = AlbumTally::of(&s.catalog); assert_eq!(shown(&tally), fresh(&s)); - let mut dice = Dice(23); + let mut dice = Dice::new(23); let (mut followed, mut whole) = (0, 0); for step in 0..900 { edit(&mut s, &mut dice, &mut ids, album); @@ -441,6 +489,7 @@ fn the_albums_counts_followed_through_edits_are_the_counts_made_from_every_photo assert_eq!(shown(&tally), fresh(&s), "after edit {step}"); } assert!(followed > 300 && whole > 20, "followed {followed} times, counted whole {whole} times"); + assert!(dice.to_local > 0, "no photo moved to Local"); // a photo deleted: the album of chosen photos it is in counts one less, without every photo being asked let in_album = s .catalog diff --git a/crates/engine/src/tests/xmp.rs b/crates/engine/src/tests/xmp.rs index cc79b5165c..c17ec5bc6b 100644 --- a/crates/engine/src/tests/xmp.rs +++ b/crates/engine/src/tests/xmp.rs @@ -263,6 +263,25 @@ fn reading_metadata_leaves_the_sidecar_alone_with_auto_write_on() { let _ = std::fs::remove_dir_all(&src); } +/// The open-time keyword repair runs outside a command, so it writes the repaired photos' sidecars itself +/// when automatic XMP writing is on (CodeRabbit on #2922): another app reading the sidecar sees one keyword a line. +#[test] +fn the_keyword_repair_writes_the_sidecar_with_auto_write_on() { + let src = temp_dir("split-keywords-autowrite"); + write_png(&src.join("frame.png"), 6); + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [src.to_string_lossy()]})).unwrap(); + s.execute("library.xmpPreferences", &json!({"autoWrite": true})).unwrap(); + let id = only(&s); + let mut meta = s.catalog.photo(id).unwrap().meta.clone(); + meta.keywords = vec!["Bride\r\nGroom".into()]; + s.catalog.apply(lightcraft_catalog::Op::SetMeta { id, meta: Box::new(meta) }).unwrap(); + assert_eq!(s.split_multiline_keywords(), 1); + let xmp = std::fs::read_to_string(src.join("frame.xmp")).expect("the sidecar is written"); + assert!(xmp.contains(">Bride<") && xmp.contains(">Groom<") && !xmp.contains("Bride\r") && !xmp.contains("Bride\n"), "{xmp}"); + let _ = std::fs::remove_dir_all(&src); +} + /// Issue #934, the round trip the write-back broke: after a read with auto-write on, another app /// changes `crs:Exposure2012` from 0.5 to 1.2 (keeping the rest of the file), and the next read /// takes 1.2. diff --git a/crates/fetch/src/lib.rs b/crates/fetch/src/lib.rs index 1554852402..1a4922e7fc 100644 --- a/crates/fetch/src/lib.rs +++ b/crates/fetch/src/lib.rs @@ -51,12 +51,18 @@ const MAX_REDIRECTS: usize = 8; /// The mirrors to try, in order: `env`'s (base URLs separated by commas, spaces or newlines), then /// the mirrors file's (one base URL per line, `#` comments), then `defaults`; duplicates and -/// unusable URLs dropped, at most 16. +/// unusable URLs dropped, at most 16. A mirror can be `http(s)://`, `file://` or an +/// absolute folder path: files from a local folder are copied (then checked like a download). pub fn mirrors(env: Option<&str>, file: Option<&Path>, defaults: &[&str]) -> Vec { let mut out: Vec = Vec::new(); let mut add = |s: &str| { - let s = s.trim().trim_end_matches('/'); - if !s.is_empty() && Url::parse(s).is_ok() && !out.iter().any(|m| m == s) && out.len() < MAX_MIRRORS { + let s = s.trim(); + // a local folder (an absolute path) is the same as its `file://` URL + let s = if Path::new(s).is_absolute() { format!("file://{}", s.replace('%', "%25")) } else { s.to_string() }; + let s = keep_root(s.trim_end_matches('/')); + let s = s.as_str(); + let usable = local_path(s).is_some() || Url::parse(s).is_ok(); + if !s.is_empty() && usable && !out.iter().any(|m| m == s) && out.len() < MAX_MIRRORS { out.push(s.to_string()); } }; @@ -197,13 +203,13 @@ fn download_source( let mut errors = Vec::new(); let mut ok = false; 'mirrors: for m in mirrors { - let url = if exact_urls { m.clone() } else { format!("{m}/{}", f.name) }; + let url = if exact_urls { m.clone() } else { file_url_in(m, f.name) }; for _ in 0..opts.attempts.clamp(1, 16) { if cancel.load(Ordering::Relaxed) { return Err(DownloadError::Cancelled); } let mut report = |n: u64, announced: u64| { - let mirror = Url::parse(m).map(|u| u.display()).unwrap_or_default(); + let mirror = short(m); progress(&Progress { file: f.name.to_string(), done: before.saturating_add(n), @@ -284,6 +290,9 @@ fn bearer<'a>(token: Option<&'a str>, url: &Url, origin: &str) -> Option<&'a str /// A mirror for messages (no query string: it may hold a token). fn short(m: &str) -> String { + if local_path(m).is_some() { + return m.to_string(); + } Url::parse(m).map(|u| u.display()).unwrap_or_else(|_| "mirror".into()) } @@ -345,8 +354,11 @@ fn fetch_file(f: &FileSpec<'_>, url: &str, dir: &Path, opts: &Options, cancel: & } Err(_) => 0, }; - let fetched = f.size != Some(have) || have == 0; - if fetched { + let local = local_path(url); + let fetched = local.is_some() || f.size != Some(have) || have == 0; + if let Some(src) = local { + copy_local(&src, &part, limit, f.size, cancel, report)?; + } else if fetched { let limits = Limits { connect: opts.connect_timeout, stall: opts.stall_timeout, cancel }; let mut url = Url::parse(url).map_err(|e| Fail::NextMirror(e.to_string()))?; let origin = url.host.clone(); @@ -455,6 +467,103 @@ fn fetch_file(f: &FileSpec<'_>, url: &str, dir: &Path, opts: &Options, cancel: & Ok(()) } +/// The local path of a `file://` URL (absolute only; `file:///C:/x` → `C:/x` on Windows). +/// A mirror with its trailing separators taken off, except a filesystem root's: `file:///` and `file:///D:/` stay +/// as they are (without it neither is an absolute path). +fn keep_root(s: &str) -> String { + match s { + "file:" => "file:///".to_string(), + s if s.starts_with("file://") && s.ends_with(':') => format!("{s}/"), + s => s.to_string(), + } +} + +/// The URL of file `name` on mirror `m`: one separator between them (a root mirror already ends with one), and on a +/// local mirror the name's own `%` escaped, so the decoded path is that very name. +fn file_url_in(m: &str, name: &str) -> String { + let name = if local_path(m).is_some() { name.replace('%', "%25") } else { name.to_string() }; + if m.ends_with('/') { format!("{m}{name}") } else { format!("{m}/{name}") } +} + +fn local_path(url: &str) -> Option { + let rest = url.strip_prefix("file://")?; + let rest = if rest.get(2..3) == Some(":") { rest.strip_prefix('/').unwrap_or(rest) } else { rest }; + let rest = percent_decode(rest)?; + let p = PathBuf::from(&rest); + if p.is_absolute() && !rest.chars().any(char::is_control) { Some(p) } else { None } +} + +/// Decode `%XX` escapes (a `file://` URL's path); `None` for a broken escape or non-UTF-8 result. +fn percent_decode(s: &str) -> Option { + let b = s.as_bytes(); + let mut out = Vec::with_capacity(b.len()); + let mut i = 0; + while let Some(&c) = b.get(i) { + if c == b'%' { + let hex = std::str::from_utf8(b.get(i + 1..i + 3)?).ok()?; + out.push(u8::from_str_radix(hex, 16).ok()?); + i += 3; + } else { + out.push(c); + i += 1; + } + } + String::from_utf8(out).ok() +} + +/// Copy a file from a local mirror into `part` (from the start; it is checked afterwards like a download). +fn copy_local(src: &Path, part: &Path, limit: u64, size: Option, cancel: &AtomicBool, report: &mut dyn FnMut(u64, u64)) -> Result<(), Fail> { + let disk = |e: std::io::Error| Fail::Disk(format!("{}: {e}", part.display())); + let meta = std::fs::metadata(src).map_err(|e| Fail::NextMirror(format!("{}: {e}", src.display())))?; + if !meta.is_file() { + return Err(Fail::NextMirror(format!("{} is not a file", src.display()))); + } + if meta.len() > limit || size.is_some_and(|s| s != meta.len()) { + return Err(Fail::NextMirror(format!("{} has the wrong size ({} bytes)", src.display(), meta.len()))); + } + let mut input = File::open(src).map_err(|e| Fail::NextMirror(format!("{}: {e}", src.display())))?; + // (a fresh file: an old one at that name may be a hard link to the source, which truncating would empty) + let mut out = new_part(part).map_err(disk)?; + let announced = size.unwrap_or(meta.len()); + let mut have = 0u64; + report(0, announced); + let mut buf = vec![0u8; 1 << 20]; + loop { + if cancel.load(Ordering::Relaxed) { + drop(out); + let _ = std::fs::remove_file(part); + return Err(Fail::Cancelled); + } + let n = match input.read(&mut buf) { + Ok(n) => n, + Err(e) => { + drop(out); + let _ = std::fs::remove_file(part); + return Err(Fail::NextMirror(format!("{}: {e}", src.display()))); + } + }; + if n == 0 { + break; + } + if have.saturating_add(n as u64) > limit { + drop(out); + let _ = std::fs::remove_file(part); + return Err(Fail::NextMirror(format!("{} grew past the expected {limit} bytes", src.display()))); + } + out.write_all(buf.get(..n).unwrap_or_default()).map_err(disk)?; + have = have.saturating_add(n as u64); + report(have, announced); + } + // a source rewritten (or cut short) after its size was read: what was copied is not that file, and a partial + // left behind would be resumed by the next mirror, failing its hash; so it goes, and the next mirror starts over + if have != announced { + drop(out); + let _ = std::fs::remove_file(part); + return Err(Fail::NextMirror(format!("{} changed while it was copied ({have} of {announced} bytes)", src.display()))); + } + out.sync_all().map_err(disk) +} + fn http_fail(e: HttpError) -> Fail { match e { HttpError::Cancelled => Fail::Cancelled, diff --git a/crates/fetch/src/tests.rs b/crates/fetch/src/tests.rs index d144e08d29..8803a4c207 100644 --- a/crates/fetch/src/tests.rs +++ b/crates/fetch/src/tests.rs @@ -426,6 +426,131 @@ fn hostile_file_specs_are_rejected_before_touching_disk() { } } +#[test] +fn copies_from_a_local_folder_mirror_and_checks_the_hash() { + let src = tmp("local-src"); + let dst = tmp("local-dst"); + std::fs::create_dir_all(&src).unwrap(); + std::fs::write(src.join("model.bin"), payload()).unwrap(); + // a bare absolute path and a file:// URL are both mirrors (passed as a default, which is not split on spaces + // or commas the way the environment's list is: the temp folder may hold either) + let m = mirrors(None, None, &[src.to_str().unwrap()]); + assert_eq!(m, vec![file_url(&src)]); + let (r, prog) = run(&[pinned()], &m, &dst, &AtomicBool::new(false)); + r.unwrap(); + assert_eq!(std::fs::read(dst.join("model.bin")).unwrap(), payload()); + assert!(prog.last().is_some_and(|p| p.done == p.total)); + + // a damaged local copy is rejected and never moved into place + let bad = tmp("local-bad"); + std::fs::create_dir_all(&bad).unwrap(); + let mut damaged = payload(); + damaged[7] ^= 1; + std::fs::write(bad.join("model.bin"), damaged).unwrap(); + let dst2 = tmp("local-dst2"); + let (r, _) = run(&[pinned()], &[file_url(&bad)], &dst2, &AtomicBool::new(false)); + assert!(matches!(r, Err(DownloadError::AllMirrorsFailed { .. })), "{r:?}"); + assert!(!dst2.join("model.bin").exists() && !dst2.join("model.bin.part").exists()); + + // a missing folder, a relative path and a directory in place of a file are errors, not panics + let (r, _) = run(&[pinned()], &["file:///nonexistent/model-mirror".to_string()], &dst2, &AtomicBool::new(false)); + assert!(r.is_err()); + assert!(mirrors(Some("file://relative/dir"), None, &[]).is_empty()); + std::fs::create_dir_all(src.join("dir.bin")).unwrap(); + let dir_spec = FileSpec { name: "dir.bin", size: None, sha256: None, max: 10 }; + let (r, _) = run(&[dir_spec], &[file_url(&src)], &dst2, &AtomicBool::new(false)); + assert!(r.is_err()); + for d in [&src, &dst, &bad, &dst2] { + let _ = std::fs::remove_dir_all(d); + } +} + +/// The `file://` URL of a local folder (its own `%` escaped, as [`mirrors`] does: the temp folder may hold one). +fn file_url(p: &Path) -> String { + format!("file://{}", p.display().to_string().replace('%', "%25")) +} + +/// A filesystem root is a usable mirror, and a file in it is found under one separator (CodeRabbit on #3010). +#[test] +fn a_root_folder_mirror_keeps_its_separator() { + assert_eq!(keep_root("file:"), "file:///"); + assert_eq!(keep_root("file:///D:"), "file:///D:/"); + assert_eq!(keep_root("file:///models"), "file:///models"); + assert_eq!(file_url_in("file:///", "model.bin"), "file:///model.bin"); + #[cfg(unix)] + { + assert_eq!(mirrors(None, None, &["/"]), ["file:///"]); + assert_eq!(local_path("file:///model.bin"), Some(PathBuf::from("/model.bin"))); + } +} + +/// A file name with a literal `%20` in it is copied from a local mirror under that very name, not as a space +/// (CodeRabbit on #3010). +#[test] +fn a_local_mirror_keeps_a_file_names_percent_signs() { + let src = tmp("local-percent-src"); + let dst = tmp("local-percent-dst"); + std::fs::create_dir_all(&src).unwrap(); + std::fs::write(src.join("model%20.bin"), payload()).unwrap(); + let p = payload(); + let spec = FileSpec { name: "model%20.bin", size: Some(p.len() as u64), sha256: Some(leak(sha_hex(&p))), max: p.len() as u64 }; + let (r, _) = run(&[spec], &[file_url(&src)], &dst, &AtomicBool::new(false)); + r.unwrap(); + assert_eq!(std::fs::read(dst.join("model%20.bin")).unwrap(), payload()); + for d in [&src, &dst] { + let _ = std::fs::remove_dir_all(d); + } +} + +/// A leftover `.part` that is a hard link to the local mirror's file is replaced, never truncated through: the +/// mirror's file keeps its bytes (CodeRabbit on #3010). +#[cfg(unix)] +#[test] +fn a_hard_linked_part_never_empties_the_local_source() { + let src = tmp("local-link-src"); + let dst = tmp("local-link-dst"); + std::fs::create_dir_all(&src).unwrap(); + std::fs::create_dir_all(&dst).unwrap(); + std::fs::write(src.join("model.bin"), payload()).unwrap(); + std::fs::hard_link(src.join("model.bin"), dst.join("model.bin.part")).unwrap(); + let (r, _) = run(&[pinned()], &[file_url(&src)], &dst, &AtomicBool::new(false)); + r.unwrap(); + assert_eq!(std::fs::read(src.join("model.bin")).unwrap(), payload(), "the mirror's file is untouched"); + assert_eq!(std::fs::read(dst.join("model.bin")).unwrap(), payload()); + for d in [&src, &dst] { + let _ = std::fs::remove_dir_all(d); + } +} + +/// A local source whose length on reading differs from the one its metadata gave (here a /proc file, whose size +/// reads as 0: as a file rewritten after its size was checked) is not kept as a partial for the next mirror to +/// resume (CodeRabbit on #3010). +#[cfg(target_os = "linux")] +#[test] +fn a_local_copy_that_comes_out_another_length_leaves_no_partial() { + let dst = tmp("local-changed-dst"); + std::fs::create_dir_all(&dst).unwrap(); + let part = dst.join("status.part"); + let r = copy_local(Path::new("/proc/self/status"), &part, 1 << 20, None, &AtomicBool::new(false), &mut |_, _| {}); + assert!(matches!(r, Err(Fail::NextMirror(_))), "the next mirror is tried"); + assert!(!part.exists(), "the partial is removed"); + let _ = std::fs::remove_dir_all(&dst); +} + +#[test] +fn file_urls_are_percent_decoded_but_bare_paths_keep_their_percent_signs() { + // (absolute on every platform: `/models/…` has no drive on Windows, where it is not an absolute path) + let percent = std::env::temp_dir().join("50%20off"); + let bare = mirrors(None, None, &[percent.to_str().unwrap()]); + assert_eq!(bare.len(), 1); + assert_eq!(local_path(&bare[0]), Some(percent)); + let spaced = std::env::temp_dir().join("my sam3"); + assert_eq!(local_path(&format!("file://{}", spaced.to_str().unwrap().replace('%', "%25").replace(' ', "%20"))), Some(spaced)); + for hostile in ["file:///x%", "file:///x%2", "file:///x%zz", "file:///x%ff", "file:///x%0a"] { + assert_eq!(local_path(hostile), None, "{hostile}"); + } +} + #[test] fn names_differing_only_in_case_are_one_file() { let spec = |name| FileSpec { name, size: Some(1), sha256: None, max: 1 }; diff --git a/crates/gpu/Cargo.toml b/crates/gpu/Cargo.toml index 02edcefd1b..689d0e64ed 100644 --- a/crates/gpu/Cargo.toml +++ b/crates/gpu/Cargo.toml @@ -24,13 +24,25 @@ log = { workspace = true } wgpu = { workspace = true } pollster = { workspace = true } bytemuck = { workspace = true } +# the SAM 3 backbone kernels (`sam` feature) implement `lightcraft_segment::BackboneAccel` +lightcraft-segment = { workspace = true, optional = true } [features] default = [] denoise = ["dep:lightcraft-denoise", "lightcraft-denoise/runtime"] +# SAM 3's vision backbone on the GPU (`sam3`); the engine's `sam` feature turns it on +sam = ["dep:lightcraft-segment"] [dev-dependencies] # tests record why they skip (`cargo xtask ci` lists the skips) lightcraft-testkit = { workspace = true } lightcraft-scenes = { workspace = true } lightcraft-raw = { workspace = true } + +[target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies] +# the SAM 3 backbone test and benchmark compare against the candle backbone +candle-core = { workspace = true } + +[[example]] +name = "sam3_backbone_bench" +required-features = ["sam"] diff --git a/crates/gpu/examples/sam3_backbone_bench.rs b/crates/gpu/examples/sam3_backbone_bench.rs new file mode 100644 index 0000000000..eec3de8314 --- /dev/null +++ b/crates/gpu/examples/sam3_backbone_bench.rs @@ -0,0 +1,217 @@ +//! Times the SAM 3 backbone and both necks on the GPU (wgpu) against the candle backbone on the CPU, on a procedural +//! photo. +//! +//! `cargo run --release -p lightcraft-gpu --features sam --example sam3_backbone_bench -- [--f16] [--runs N] [--no-cpu]` +//! +//! The model directory is `LIGHTCRAFT_SAM3_DIR`, else `~/.config/lightcraft/models/sam3`. Prints the device and +//! kernel creation, the weight upload, the first and the warm forward passes, each neck's first run (which builds +//! it) and warm runs, the text detector's mask decoder (first and warm, on made-up inputs), the CPU forward pass and +//! how far the two outputs are apart. `--app` then times what the app does per photo, with the model loaded as the +//! app loads it (GPU backbone, necks, DETR encoder and mask decoder, the rest in candle on the CPU): encode, click +//! features, first click, first and second Describe (`--cpu-necks`: with the necks in candle, as before they ran on +//! the GPU; `--cpu-masks`: with the mask decoder in candle). + +use std::path::PathBuf; +use std::time::Instant; + +use lightcraft_gpu::sam3::{self, Precision}; +use lightcraft_segment::{BackboneAccel, INPUT, NeckKind, Sam3, WeightReader}; + +fn model_dir() -> Option { + let dir = match std::env::var_os("LIGHTCRAFT_SAM3_DIR").filter(|v| !v.is_empty()) { + Some(d) => PathBuf::from(d), + None => PathBuf::from(std::env::var_os("HOME")?).join(".config/lightcraft/models/sam3"), + }; + lightcraft_segment::is_model_dir(&dir).then_some(dir) +} + +fn main() -> Result<(), String> { + let args: Vec = std::env::args().skip(1).collect(); + let precision = if args.iter().any(|a| a == "--f16") { Precision::F16 } else { Precision::F32 }; + let runs: usize = match args.iter().position(|a| a == "--runs").map(|i| args.get(i + 1).and_then(|v| v.parse().ok())) { + None => 5, + Some(Some(n)) if n > 0 => n, + Some(_) => return Err("--runs needs a positive number".into()), + }; + let cpu = !args.iter().any(|a| a == "--no-cpu"); + let app = args.iter().any(|a| a == "--app"); + let cpu_necks = args.iter().any(|a| a == "--cpu-necks"); + let cpu_masks = args.iter().any(|a| a == "--cpu-masks"); + let dir = model_dir().ok_or("no SAM 3 model: set LIGHTCRAFT_SAM3_DIR")?; + + let scene = &lightcraft_scenes::demo_library()[0]; + let img = scene.render_fit(1600).to_srgb8(); + let rgb: Vec = img.data.iter().flat_map(|p| [p[0], p[1], p[2]]).collect(); + let pixels = lightcraft_segment::mask::preprocess(&rgb, img.width, img.height, INPUT).map_err(|e| e.to_string())?; + + let t = Instant::now(); + let adapter = sam3::adapter()?; + println!("device + kernels: {:7.1} ms ({adapter})", t.elapsed().as_secs_f64() * 1e3); + let reader = WeightReader::open(&dir).map_err(|e| e.to_string())?; + let t = Instant::now(); + let gpu = sam3::load(&reader, precision)?; + println!( + "weight upload: {:7.1} ms ({:.0} MB weights, {:.0} MB work buffers, {precision:?})", + t.elapsed().as_secs_f64() * 1e3, + gpu.weight_bytes() as f64 / 1e6, + gpu.work_bytes() as f64 / 1e6 + ); + let t = Instant::now(); + let out = gpu.forward(&pixels)?; + println!("first forward: {:7.1} ms", t.elapsed().as_secs_f64() * 1e3); + let mut best = f64::MAX; + let mut sum = 0.0; + for _ in 0..runs { + let t = Instant::now(); + gpu.forward(&pixels)?; + let ms = t.elapsed().as_secs_f64() * 1e3; + best = best.min(ms); + sum += ms; + } + println!("warm forward: {:7.1} ms (mean of {runs}: {:.1} ms)", best, sum / runs.max(1) as f64); + // a head that fails here is reported, and the `--app` run below still measures its fallback to candle + for which in [NeckKind::Tracker, NeckKind::Detector] { + match timed(runs, || gpu.neck(which, &out, 3).map(drop)) { + Ok((first, best, mean)) => println!("{which:?} neck: first {first:7.1} ms, warm {best:.1} ms (mean of {runs}: {mean:.1} ms)"), + Err(e) => println!("{which:?} neck failed on the GPU: {e}"), + } + } + println!("neck device memory: {:.0} MB", gpu.neck_bytes() as f64 / 1e6); + { + let (memory, text, valid) = (vec![0.1f32; 5184 * 256], vec![0.3f32; 32 * 256], vec![true; 32]); + let (l1, l0) = (vec![0.2f32; 256 * 144 * 144], vec![0.4f32; 256 * 288 * 288]); + let (rows, bias) = (vec![0.01f32; 200 * 256], vec![0.5f32; 200]); + match timed(runs, || gpu.mask_decoder(&memory, &text, &valid, [&l1, &l0], &rows, &bias).map(drop)) { + Ok((first, best, mean)) => { + let (w, b) = gpu.mask_decoder_bytes().unwrap_or_default(); + println!( + "mask decoder (200 queries): first {first:7.1} ms, warm {best:.1} ms (mean of {runs}: {mean:.1} ms); {:.0} MB weights, {:.0} MB work buffers", + w as f64 / 1e6, + b as f64 / 1e6 + ); + } + Err(e) => println!("mask decoder failed on the GPU: {e}"), + } + } + + if cpu { + let model = Sam3::load_on(&dir, candle_core::Device::Cpu).map_err(|e| e.to_string())?; + let px = candle_core::Tensor::from_vec(pixels.clone(), (1, 3, INPUT, INPUT), &candle_core::Device::Cpu).map_err(|e| e.to_string())?; + let t = Instant::now(); + let enc = model.encode_pixels(&px).map_err(|e| e.to_string())?; + println!("CPU (candle): {:7.1} ms", t.elapsed().as_secs_f64() * 1e3); + let want = enc.backbone().flatten_all().and_then(|t| t.to_vec1::()).map_err(|e| e.to_string())?; + let scale = want.iter().fold(0f32, |m, v| m.max(v.abs())); + let (mut max, mut sum) = (0f32, 0f64); + for (a, b) in out.iter().zip(&want) { + max = max.max((a - b).abs()); + sum += f64::from((a - b).abs()); + } + println!( + "GPU vs CPU: max abs {max:.3e}, max rel {:.3e} (scale {scale:.2}), mean abs {:.3e}", + max / scale.max(1e-6), + sum / want.len().max(1) as f64 + ); + } + drop(gpu); + if app { + as_the_app(&dir, &rgb, (img.width, img.height), runs, (cpu_necks, cpu_masks))?; + } + // no GPU work in flight when the process ends (issue #620) + lightcraft_gpu::begin_shutdown(); + lightcraft_gpu::wait_idle(std::time::Duration::from_secs(5)); + Ok(()) +} + +/// `f` once (its first run, in ms), then `runs` times: (first, best, mean) in milliseconds; the first error ends it. +fn timed(runs: usize, mut f: impl FnMut() -> Result<(), String>) -> Result<(f64, f64, f64), String> { + let t = Instant::now(); + f()?; + let first = t.elapsed().as_secs_f64() * 1e3; + let (mut best, mut sum) = (f64::MAX, 0.0); + for _ in 0..runs { + let t = Instant::now(); + f()?; + let ms = t.elapsed().as_secs_f64() * 1e3; + best = best.min(ms); + sum += ms; + } + Ok((first, best, sum / runs.max(1) as f64)) +} + +fn ms(t: Instant) -> String { + format!("{:.0} ms", t.elapsed().as_secs_f64() * 1e3) +} + +/// The model's GPU accelerator with the necks (`--cpu-necks`) or the mask decoder (`--cpu-masks`) left to candle. +struct Heads { + gpu: Box, + necks: bool, + masks: bool, +} + +impl BackboneAccel for Heads { + fn forward(&self, pixels: &[f32]) -> Result, String> { + self.gpu.forward(pixels) + } + fn device(&self) -> String { + self.gpu.device() + } + fn runs_necks(&self) -> bool { + self.necks && self.gpu.runs_necks() + } + fn runs_detr_encoder(&self) -> bool { + self.gpu.runs_detr_encoder() + } + fn runs_mask_decoder(&self) -> bool { + self.masks && self.gpu.runs_mask_decoder() + } + fn neck(&self, which: NeckKind, backbone: &[f32], n: usize) -> Result>, String> { + self.gpu.neck(which, backbone, n) + } + fn detr_encoder(&self, image: &[f32], pos: &[f32], text: &[f32], valid: &[bool]) -> Result, String> { + self.gpu.detr_encoder(image, pos, text, valid) + } + fn mask_decoder( + &self, + memory: &[f32], + text: &[f32], + valid: &[bool], + levels: [&[f32]; 2], + rows: &[f32], + bias: &[f32], + ) -> Result, String> { + self.gpu.mask_decoder(memory, text, valid, levels, rows, bias) + } +} + +/// The model as the app loads it, timed per photo: encode, click features, a click, two Describes. +fn as_the_app(dir: &std::path::Path, rgb: &[u8], (w, h): (usize, usize), runs: usize, (cpu_necks, cpu_masks): (bool, bool)) -> Result<(), String> { + let t = Instant::now(); + let make = |r: &WeightReader| -> Result, String> { + Ok(Box::new(Heads { gpu: sam3::backbone(r)?, necks: !cpu_necks, masks: !cpu_masks })) + }; + let mut model = Sam3::load_accelerated(dir, candle_core::Device::Cpu, make).map_err(|e| e.to_string())?; + println!("app: load {} on {}", ms(t), model.backbone_device()); + let click = |x, y| lightcraft_segment::Click { x, y, positive: true }; + for run in 0..runs.max(1) { + let t = Instant::now(); + let mut enc = model.encode(rgb, w, h).map_err(|e| e.to_string())?; + let encode = ms(t); + let t = Instant::now(); + model.prepare_clicks(&mut enc).map_err(|e| e.to_string())?; + let features = ms(t); + let t = Instant::now(); + model.segment_clicks(&mut enc, &[click(0.5, 0.5)]).map_err(|e| e.to_string())?; + let click1 = ms(t); + let t = Instant::now(); + model.segment_text(&mut enc, "sky", 0.5).map_err(|e| e.to_string())?; + let text1 = ms(t); + let t = Instant::now(); + model.segment_text(&mut enc, "the red car", 0.5).map_err(|e| e.to_string())?; + let text2 = ms(t); + println!("app run {run}: encode {encode}, click features {features}, click {click1}, first describe {text1}, second describe {text2}"); + } + println!("app: the rest on {}", model.heads_device()); + Ok(()) +} diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs index 1e06e9f1ad..4fbef07c78 100644 --- a/crates/gpu/src/lib.rs +++ b/crates/gpu/src/lib.rs @@ -45,6 +45,8 @@ pub mod nn; mod params; #[cfg(not(target_arch = "wasm32"))] mod render; +#[cfg(all(feature = "sam", not(target_arch = "wasm32")))] +pub mod sam3; #[cfg(not(target_arch = "wasm32"))] mod vram; @@ -250,10 +252,11 @@ pub fn wait_idle(timeout: std::time::Duration) -> bool { } } -/// Why GPU compute that has a device of its own (denoise, faces) is switched off by the user's settings, or `None`: the -/// environment switches and the rendering preference, but not a render-device failure (the devices are separate). +/// Why GPU compute that has a device of its own (denoise, faces, SAM 3) is switched off by the user's settings, or +/// `None`: the environment switches and the rendering preference, but not a render-device failure (the devices are +/// separate). #[cfg(not(target_arch = "wasm32"))] -pub(crate) fn switched_off() -> Option { +pub fn switched_off() -> Option { if let Some(why) = env_off_reason() { return Some(why.into()); } diff --git a/crates/gpu/src/nn.rs b/crates/gpu/src/nn.rs index cca52177fc..f1064b5bc2 100644 --- a/crates/gpu/src/nn.rs +++ b/crates/gpu/src/nn.rs @@ -255,6 +255,7 @@ fn plan(net: &Net, tile: usize, max_binding: u64) -> Result<(Layout, Vec) let reads: Vec = match op { Op::Conv(c) => std::iter::once(c.src).chain(c.src2).collect(), Op::ConvT2(c) => vec![c.src], + Op::Add { src, src2 } => vec![*src, *src2], Op::MaxPool2 { src } | Op::DepthToSpace2 { src } => vec![*src], }; for t in reads { @@ -448,6 +449,7 @@ fn plan(net: &Net, tile: usize, max_binding: u64) -> Result<(Layout, Vec) } // run as part of the 1 × 1 convolution before it Op::DepthToSpace2 { .. } => {} + Op::Add { .. } => return unsupported("an elementwise add is not supported on the GPU"), } // buffers whose last reader was this layer are free for the next layer's result for t in 0..=i { diff --git a/crates/gpu/src/render.rs b/crates/gpu/src/render.rs index c569d3b9b5..31489ba476 100644 --- a/crates/gpu/src/render.rs +++ b/crates/gpu/src/render.rs @@ -609,7 +609,7 @@ fn sample(cx: &mut Cx<'_>, src: &Arc, src_buf: Arc, plan: &Plan<'_> Arc::new(out) }; let (base, (bw, bh)) = match sp.prefilter { - Some(d) => (Arc::new(resize(cx, &oriented, (sp.ow, sp.oh), d, 3, Filter::Mitchell)), d), + Some(d) => (Arc::new(resize(cx, &oriented, (sp.ow, sp.oh), d, 3, fr.downscale)), d), None => (oriented, (sp.ow, sp.oh)), }; let mut affine = |xf: &lightcraft_geom::Affine| { diff --git a/crates/gpu/src/sam3.rs b/crates/gpu/src/sam3.rs new file mode 100644 index 0000000000..f646935079 --- /dev/null +++ b/crates/gpu/src/sam3.rs @@ -0,0 +1,1195 @@ +//! The SAM 3 vision backbone on the GPU: a [`lightcraft_segment::BackboneAccel`] that runs the 32-layer ViT of +//! `lightcraft-segment` (`vit.rs`, the reference) with WGSL compute kernels, so AI masks (Object, Subject, Describe) +//! need not wait ~40 s per photo for the CPU on machines without Metal. +//! +//! What runs (`docs/gpu-pipeline.md` → SAM 3 backbone): the patch embedding as im2col and a matrix product, the +//! 24 × 24 position table, `ln_pre`, then per layer layer norm → one q|k|v product → 2-D RoPE → attention (24 × 24 +//! windows, or all 5184 tokens in layers 7, 15, 23 and 31) → output projection and residual → layer norm → MLP +//! (GELU, erf form) and residual. The tokens stay in *window order* the whole way (window-major, row-major inside a +//! window): a window's tokens are then a contiguous range for attention, the position table repeats per window, and +//! the global layers don't care about order (their RoPE table is stored in the same order). Only the last step puts +//! them back on the 72 × 72 grid, channels-first. +//! +//! Kernels: `wgsl/sam3_matmul.wgsl` (tiled, register-blocked; bias, GELU and residual in its epilogue), +//! `wgsl/sam3_attention.wgsl` (flash style: online softmax, the 16 × 5184² scores of a global layer never exist), +//! `wgsl/sam3_ops.wgsl` (layer norm, RoPE, im2col, the final reorder). All of the dispatches, with their parameters +//! and bind groups, are built once with the weights; a forward pass uploads the pixels, submits one command buffer +//! per layer and reads the result back once. No subgroups or shader-f16 needed. The two necks that follow the +//! backbone run on the same device, built when first asked for (`sam3/neck.rs`). +//! +//! The same accelerator runs the text detector's DETR encoder (`sam3/detr.rs`) and its mask decoder (`sam3/pixel.rs`); +//! their weights load on the first text prompt. +//! +//! The device is its own (like denoise's and faces'): it respects the same switches as GPU rendering +//! (`LIGHTCRAFT_GPU`, `LIGHTCRAFT_GPU_BACKEND`, `LIGHTCRAFT_GPU_ADAPTER`, the GPU preference), the crash sentinel +//! around device creation and the shutdown gate. A device error or loss stops its use for the process; every +//! failure is an `Err` (the caller then runs the candle backbone), never a panic. + +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex, OnceLock, PoisonError}; +use std::time::Duration; + +use bytemuck::Pod; +use lightcraft_segment::{BACKBONE_PREFIX, BackboneAccel, NeckKind, WeightReader}; +use wgpu::util::DeviceExt; + +mod detr; +mod neck; +mod pixel; +#[cfg(test)] +mod tests; + +/// Input side (pixels), patch size, patches per side. +const IMAGE: usize = 1008; +const PATCH: usize = 14; +const GRID: usize = IMAGE / PATCH; +const TOKENS: usize = GRID * GRID; +const HIDDEN: usize = 1024; +const HEADS: usize = 16; +const HEAD_DIM: usize = HIDDEN / HEADS; +const MLP: usize = 4736; +const LAYERS: usize = 32; +const WINDOW: usize = 24; +const GLOBAL: [usize; 4] = [7, 15, 23, 31]; +/// The pretraining grid of the position table (336 / 14), tiled over the 72 × 72 grid. +const POS_SIDE: usize = 24; +const EPS: f32 = 1e-6; +/// Numbers per patch (3 × 14 × 14): the patch embedding's K. +const PATCH_K: usize = 3 * PATCH * PATCH; + +/// Longest wait for one forward pass before the device is given up on. +const TIMEOUT: Duration = Duration::from_secs(120); +/// Conservative workgroup memory for key and value tiles (2 × [`ATTENTION_KEYS`] × 64 floats). +const ATTENTION_BYTES: u32 = 2 * ATTENTION_KEYS * HEAD_DIM as u32 * 4; +/// The maximum keys per step; also used to bound the required workgroup memory. +const ATTENTION_KEYS: u32 = 32; + +/// On DX12, creating the fully unrolled 32-key shader can be very slow on some drivers. Smaller +/// tiles shorten initialization; the existing 32-key limits remain conservative for every backend. +fn attention_keys(backend: wgpu::Backend) -> u32 { + if backend == wgpu::Backend::Dx12 { 8 } else { ATTENTION_KEYS } +} +/// The matrix product's blocking. +const TILE: Tile = Tile { rows: 4, cols: 4, bk: 16 }; + +/// How the matrix-product kernel blocks its work: each of its 16 × 16 threads makes `rows × cols` outputs (so a +/// workgroup makes 16 · rows × 16 · cols), walking k in steps of `bk` (a multiple of 8). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Tile { + rows: u32, + cols: u32, + bk: u32, +} + +impl Tile { + fn bm(self) -> usize { + 16 * self.rows as usize + } + + fn bn(self) -> usize { + 16 * self.cols as usize + } + + /// Workgroup memory: both tiles, k-contiguous, each row padded by one vector. + fn workgroup_bytes(self) -> u32 { + (self.bm() + self.bn()) as u32 * (self.bk / 4 + 1) * 16 + } +} + +/// A matrix-product pipeline and its blocking. +struct Matmul { + pipeline: wgpu::ComputePipeline, + tile: Tile, +} + +// --------------------------------------------------------------------------------------------------------------------- +// the device + +struct Dev { + device: wgpu::Device, + queue: wgpu::Queue, + info: wgpu::AdapterInfo, + limits: wgpu::Limits, + layout: wgpu::BindGroupLayout, + pipeline_layout: wgpu::PipelineLayout, + k: Kernels, + /// Bound where a kernel has fewer operands than bindings. + dummy: wgpu::Buffer, +} + +struct Kernels { + matmul: Matmul, + /// The same with f16 weights, compiled when first needed. + matmul16: OnceLock, + attention: wgpu::ComputePipeline, + layernorm: wgpu::ComputePipeline, + rope: wgpu::ComputePipeline, + im2col: wgpu::ComputePipeline, + to_chw: wgpu::ComputePipeline, +} + +static DEV: OnceLock> = OnceLock::new(); +static BROKEN: AtomicBool = AtomicBool::new(false); +static BROKEN_WHY: Mutex> = Mutex::new(None); + +fn mark_broken(why: &str) { + let mut w = BROKEN_WHY.lock().unwrap_or_else(PoisonError::into_inner); + if w.is_none() { + *w = Some(why.to_string()); + } + BROKEN.store(true, Ordering::Relaxed); +} + +/// Why the GPU stopped being used for SAM 3 (a device error), if it did. +pub fn broken_reason() -> Option { + BROKEN.load(Ordering::Relaxed).then(|| BROKEN_WHY.lock().unwrap_or_else(PoisonError::into_inner).clone().unwrap_or_else(|| "device error".into())) +} + +fn dev() -> Result<&'static Dev, String> { + if let Some(why) = broken_reason() { + return Err(format!("stopped after a GPU failure: {why}")); + } + if let Some(why) = crate::switched_off() { + return Err(why); + } + // creating the device is GPU work too: not once the process is ending (issue #620) + let _work = match DEV.get() { + Some(_) => None, + None => Some(crate::exit::enter().ok_or("LightCraft is closing")?), + }; + DEV.get_or_init(create_device).as_ref().map_err(|e| e.clone()) +} + +fn create_device() -> Result { + let Some(backends) = crate::backend::compute_backends() else { return Err("disabled by LIGHTCRAFT_GPU_BACKEND=off".into()) }; + crate::backend::with_init_marker(backends, || { + std::panic::catch_unwind(|| make_device(backends)).unwrap_or_else(|_| Err("device creation panicked".into())) + }) +} + +fn entry(binding: u32, ty: wgpu::BufferBindingType) -> wgpu::BindGroupLayoutEntry { + wgpu::BindGroupLayoutEntry { + binding, + visibility: wgpu::ShaderStages::COMPUTE, + ty: wgpu::BindingType::Buffer { ty, has_dynamic_offset: false, min_binding_size: None }, + count: None, + } +} + +/// The largest buffer the backbone binds: the MLP's hidden activations (5184 × 4736 floats, 98 MB). +const LARGEST_BUFFER: u64 = (TOKENS * MLP * 4) as u64; + +/// The limits the kernels need: the WebGPU downlevel defaults, with room for the largest buffer and the tiles. +fn needed_limits() -> wgpu::Limits { + wgpu::Limits { + max_storage_buffer_binding_size: LARGEST_BUFFER, + max_buffer_size: LARGEST_BUFFER, + max_compute_workgroup_storage_size: ATTENTION_BYTES.max(TILE.workgroup_bytes()), + max_compute_invocations_per_workgroup: 256, + max_compute_workgroup_size_x: 256, + ..wgpu::Limits::downlevel_defaults() + } +} + +/// The limits an adapter with `have` falls short of ([`needed_limits`]), as "name have < want"; empty when it has them all. +/// Such an adapter gets no device: SAM 3 then runs in candle on the CPU, and Settings says why. +fn short_limits(have: &wgpu::Limits) -> Vec { + let mut short = Vec::new(); + needed_limits().check_limits_with_fail_fn(have, false, |name, want, have| short.push(format!("{name} {have} < {want}"))); + short +} + +fn make_device(backends: wgpu::Backends) -> Result { + let mut desc = wgpu::InstanceDescriptor::new_without_display_handle(); + desc.backends = backends; + desc.backend_options = crate::backend::backend_options(); + desc.flags = crate::backend::instance_flags_from_env(desc.flags); + let instance = wgpu::Instance::new(desc); + let wanted = std::env::var("LIGHTCRAFT_GPU_ADAPTER").ok().map(|s| s.trim().to_lowercase()).filter(|s| !s.is_empty()); + let adapter = match &wanted { + Some(w) => pollster::block_on(instance.enumerate_adapters(backends)) + .into_iter() + .find(|a| { + let i = a.get_info(); + i.device_type != wgpu::DeviceType::Cpu && i.name.to_lowercase().contains(w.as_str()) + }) + .ok_or_else(|| format!("no GPU adapter named like `{w}`"))?, + None => pollster::block_on( + instance.request_adapter(&wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::HighPerformance, ..Default::default() }), + ) + .map_err(|e| format!("no GPU adapter among {backends:?} ({e})"))?, + }; + let info = adapter.get_info(); + if info.device_type == wgpu::DeviceType::Cpu { + return Err(format!("software adapter ({}) skipped: the CPU is faster", info.name)); + } + let need = needed_limits(); + let short = short_limits(&adapter.limits()); + if !short.is_empty() { + return Err(format!("{} is too limited for the SAM 3 kernels ({})", info.name, short.join(", "))); + } + let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor { + label: Some("lightcraft-sam3"), + required_limits: need, + ..Default::default() + })) + .map_err(|e| format!("{}: device creation failed ({e})", info.name))?; + device.on_uncaptured_error(Arc::new(|e| { + log::error!("gpu (sam3): {e}"); + mark_broken(&format!("device error: {e}")); + })); + device.set_device_lost_callback(|reason, msg| { + log::error!("gpu (sam3): device lost ({reason:?}): {msg}"); + mark_broken(&format!("device lost ({reason:?}): {msg}")); + }); + // a kernel the driver or naga rejects fails the device here, not the first forward pass + let validation = device.push_error_scope(wgpu::ErrorFilter::Validation); + use wgpu::BufferBindingType::{Storage, Uniform}; + let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("sam3"), + entries: &[ + entry(0, Uniform), + entry(1, Storage { read_only: true }), + entry(2, Storage { read_only: true }), + entry(3, Storage { read_only: true }), + entry(4, Storage { read_only: false }), + ], + }); + let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: None, bind_group_layouts: &[Some(&layout)], immediate_size: 0 }); + let pipe = |label: &str, source: &str, entry: &str| pipeline(&device, &pl, label, source, entry); + let ops = include_str!("wgsl/sam3_ops.wgsl"); + let k = Kernels { + matmul: Matmul { pipeline: pipe("sam3 matmul", &matmul_source(TILE, false), "main"), tile: TILE }, + matmul16: OnceLock::new(), + attention: pipe("sam3 attention", &attention_source(attention_keys(info.backend)), "main"), + layernorm: pipe("sam3 ops", ops, "layernorm"), + rope: pipe("sam3 ops", ops, "rope"), + im2col: pipe("sam3 ops", ops, "im2col"), + to_chw: pipe("sam3 ops", ops, "to_chw"), + }; + let dummy = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("sam3 unused"), + size: 16, + usage: wgpu::BufferUsages::STORAGE, + mapped_at_creation: false, + }); + if let Some(e) = pollster::block_on(validation.pop()) { + return Err(format!("{}: the SAM 3 kernels did not compile ({e})", info.name)); + } + let limits = device.limits(); + log::info!("gpu (sam3): {} ({:?})", info.name, info.backend); + Ok(Dev { device, queue, info, limits, layout, pipeline_layout: pl, k, dummy }) +} + +impl Dev { + fn matmul16(&self) -> &Matmul { + self.k.matmul16.get_or_init(|| Matmul { + pipeline: pipeline(&self.device, &self.pipeline_layout, "sam3 matmul f16", &matmul_source(TILE, true), "main"), + tile: TILE, + }) + } +} + +fn pipeline(device: &wgpu::Device, layout: &wgpu::PipelineLayout, label: &str, source: &str, entry: &str) -> wgpu::ComputePipeline { + let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some(label), source: wgpu::ShaderSource::Wgsl(source.into()) }); + device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: Some(entry), + layout: Some(layout), + module: &module, + entry_point: Some(entry), + // every kernel writes its workgroup memory before reading it + compilation_options: wgpu::PipelineCompilationOptions { zero_initialize_workgroup_memory: false, ..Default::default() }, + cache: None, + }) +} + +/// The matrix-product kernel for `tile` (`bk` 16 with `f16` weights), written out from `wgsl/sam3_matmul.wgsl`: one +/// variable per accumulator and per prefetched vector. +fn matmul_source(tile: Tile, f16: bool) -> String { + matmul_source_with(tile, f16, None) +} + +/// [`matmul_source`] with `load_a` (the A-tile loader) from `a_loader` instead of the dense one (the neck's 3 × 3 +/// convolution, `sam3/neck.rs`). +fn matmul_source_with(tile: Tile, f16: bool, a_loader: Option<&str>) -> String { + let Tile { rows, cols, bk } = tile; + use std::fmt::Write; + let mut src = String::new(); + // keep the B-tile loader of this weight type, and the A-tile loader asked for + let mut keep = true; + for line in include_str!("wgsl/sam3_matmul.wgsl").lines() { + match line.trim() { + "// #if f32" => keep = !f16, + "// #if f16" => keep = f16, + "// #if dense" => keep = a_loader.is_none(), + "// #endif" => keep = true, + _ if keep => { + src.push_str(line); + src.push('\n'); + } + _ => {} + } + } + src.push_str(a_loader.unwrap_or_default()); + let (bm, bn) = (16 * rows, 16 * cols); + let a_vecs = bm * bk / 4; + let b_vecs = if f16 { bn * bk / 8 } else { bn * bk / 4 }; + let (mut decl, mut load, mut next, mut store_tile, mut compute, mut store) = + (String::new(), String::new(), String::new(), String::new(), String::new(), String::new()); + let w = |s: &mut String, line: String| { + s.push_str(&line); + s.push('\n'); + }; + for i in 0..rows { + let row: Vec = (0..cols).map(|j| format!("var c{i}_{j} = 0.0;")).collect(); + w(&mut decl, format!(" {}", row.join(" "))); + } + let b_type = if f16 { "array, 2>" } else { "vec4" }; + let b_load = if f16 { "load_b16" } else { "load_b" }; + for (l, start) in (0..a_vecs).step_by(256).enumerate() { + w(&mut decl, format!(" var pa{l}: vec4;")); + let guard = if start + 256 > a_vecs { format!("if (tid + {start}u < {a_vecs}u) ") } else { String::new() }; + w(&mut load, format!(" {guard}{{ pa{l} = load_a(m0, 0u, tid + {start}u); }}")); + w(&mut next, format!(" {guard}{{ pa{l} = load_a(m0, k0 + BK, tid + {start}u); }}")); + w(&mut store_tile, format!(" {guard}{{ let e = tid + {start}u; As[e / KV * KS + e % KV] = pa{l}; }}")); + } + for (l, start) in (0..b_vecs).step_by(256).enumerate() { + w(&mut decl, format!(" var pb{l}: {b_type};")); + let guard = if start + 256 > b_vecs { format!("if (tid + {start}u < {b_vecs}u) ") } else { String::new() }; + w(&mut load, format!(" {guard}{{ pb{l} = {b_load}(n0, 0u, tid + {start}u); }}")); + w(&mut next, format!(" {guard}{{ pb{l} = {b_load}(n0, k0 + BK, tid + {start}u); }}")); + let put = if f16 { + format!("let r = e / (BK / 8u) * KS + 2u * (e % (BK / 8u)); Bs[r] = pb{l}[0]; Bs[r + 1u] = pb{l}[1];") + } else { + format!("Bs[e / KV * KS + e % KV] = pb{l};") + }; + w(&mut store_tile, format!(" {guard}{{ let e = tid + {start}u; {put} }}")); + } + for i in 0..rows { + w(&mut compute, format!(" let a{i} = As[(ty + {}u) * KS + kv];", 16 * i)); + } + for j in 0..cols { + w(&mut compute, format!(" let b{j} = Bs[(tx + {}u) * KS + kv];", 16 * j)); + } + for c in ["x", "y", "z", "w"] { + for i in 0..rows { + let mut line = String::from(" "); + for j in 0..cols { + // writing into a String cannot fail + let _ = write!(line, " c{i}_{j} = fma(a{i}.{c}, b{j}.{c}, c{i}_{j});"); + } + w(&mut compute, line); + } + } + for i in 0..rows { + w(&mut store, format!(" {{\n let m = m0 + ty + {}u;\n if (m < p.m) {{", 16 * i)); + for j in 0..cols { + w(&mut store, format!(" put(m, n0 + tx + {}u, c{i}_{j});", 16 * j)); + } + w(&mut store, " }\n }".into()); + } + src.replace("{{WEIGHT}}", if f16 { "vec4" } else { "vec4" }) + .replace("{{BM}}", &bm.to_string()) + .replace("{{BN}}", &bn.to_string()) + .replace("{{BK}}", &bk.to_string()) + .replace("{{DECL}}", &decl) + .replace("{{LOAD}}", &load) + .replace("{{LOAD_NEXT}}", &next) + .replace("{{STORE_TILE}}", &store_tile) + .replace("{{COMPUTE}}", &compute) + .replace("{{STORE}}", &store) +} + +/// The attention kernel for `keys` keys per step, written out from `wgsl/sam3_attention.wgsl`: one variable per q +/// and output vector and per score. +fn attention_source(keys: u32) -> String { + use std::fmt::Write; + let d4 = (HEAD_DIM / 4) as u32; + let (mut decl, mut scores, mut rescale, mut acc, mut store) = (String::new(), String::new(), String::new(), String::new(), String::new()); + // writing into a String cannot fail + for c in 0..d4 { + let _ = writeln!(decl, " let q{c} = qkv[qa + {c}u];\n var o{c} = vec4(0.0);"); + let _ = writeln!(rescale, " o{c} *= fix;"); + let _ = writeln!(store, " out[oa + {c}u] = o{c} * r;"); + } + for j in 0..keys { + let terms: Vec = (0..d4).map(|c| format!("q{c} * Ks[{}u]", j * d4 + c)).collect(); + let _ = writeln!( + scores, + " let d{j} = {};\n let s{j} = d{j}.x + d{j}.y + d{j}.z + d{j}.w;\n top = max(top, s{j});", + terms.join(" + ") + ); + let _ = writeln!(acc, " {{\n let w = exp(s{j} - top);\n l += w;"); + for c in 0..d4 { + let _ = writeln!(acc, " o{c} = fma(vec4(w), Vs[{}u], o{c});", j * d4 + c); + } + let _ = writeln!(acc, " }}"); + } + include_str!("wgsl/sam3_attention.wgsl") + .replace("{{KB}}", &keys.to_string()) + .replace("{{DECL}}", &decl) + .replace("{{SCORES}}", &scores) + .replace("{{RESCALE}}", &rescale) + .replace("{{ACCUMULATE}}", &acc) + .replace("{{STORE}}", &store) +} + +/// The adapter the SAM 3 backbone would use ("NVIDIA GeForce RTX 5070 (Vulkan)"), or why it cannot use one. Creates +/// the device on first use. +pub fn adapter() -> Result { + dev().map(|d| format!("{} ({:?})", d.info.name, d.info.backend)) +} + +// --------------------------------------------------------------------------------------------------------------------- +// steps: one dispatch each, recorded once + +/// One dispatch: a kernel, its parameters, its buffers (bindings 1–3 read, 4 written) and its workgroup counts. +struct Pending { + pipeline: &'static wgpu::ComputePipeline, + params: [u32; 8], + buffers: [wgpu::Buffer; 4], + groups: [u32; 3], +} + +/// A recorded dispatch, ready to replay. +struct Step { + pipeline: &'static wgpu::ComputePipeline, + bind: wgpu::BindGroup, + groups: [u32; 3], +} + +fn u32_of(v: usize) -> Result { + u32::try_from(v).ok().filter(|v| *v < (1 << 31)).ok_or_else(|| "a tensor too large for the SAM 3 kernels".to_string()) +} + +/// How the linear layers' weights are stored on the device. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Precision { + /// As in the checkpoint. + F32, + /// Halves, two per u32 (along k): half the memory and weight traffic; the products still run in f32. + F16, +} + +/// Builds a list of dispatches. +struct Graph { + dev: &'static Dev, + steps: Vec, + /// Where command buffers end (indices into `steps`): one submission each. + cuts: Vec, +} + +impl Graph { + fn new(dev: &'static Dev) -> Graph { + Graph { dev, steps: Vec::new(), cuts: Vec::new() } + } + + /// Workgroups for `count` items of 256 (or `count` workgroups), and the row length the kernel reads back. + fn flat(&self, count: usize) -> Result<([u32; 3], u32), String> { + let limit = (self.dev.limits.max_compute_workgroups_per_dimension as usize).min(65_535); + let blocks = count.max(1); + let row = blocks.min(limit); + let rows = blocks.div_ceil(row); + if rows > limit { + return Err("a step too large for the SAM 3 kernels".into()); + } + Ok(([u32_of(row)?, u32_of(rows)?, 1], u32_of(row)?)) + } + + fn push(&mut self, pipeline: &'static wgpu::ComputePipeline, params: [u32; 8], buffers: [&wgpu::Buffer; 4], groups: [u32; 3]) { + let buffers = buffers.map(Clone::clone); + self.steps.push(Pending { pipeline, params, buffers, groups }); + } + + /// End a command buffer here. + fn cut(&mut self) { + if self.cuts.last() != Some(&self.steps.len()) { + self.cuts.push(self.steps.len()); + } + } + + /// `y = act(x · wᵀ + bias[row % bias_rows])` (or `y +=` with `residual`): x `[m, k]`, w `[n, k]` (f32, or f16 + /// pairs), bias `[bias_rows, n]`, y `[m, n]`. + #[allow(clippy::too_many_arguments)] + fn matmul( + &mut self, + [x, w, bias, y]: [&wgpu::Buffer; 4], + (m, n, k): (usize, usize, usize), + bias_rows: usize, + gelu: bool, + residual: bool, + precision: Precision, + ) -> Result<(), String> { + let kernel = match precision { + Precision::F32 => &self.dev.k.matmul, + Precision::F16 => self.dev.matmul16(), + }; + self.matmul_with(kernel, precision, [x, w, bias, y], (m, n, k), bias_rows, gelu, residual) + } + + /// [`Graph::matmul`] with the pipeline `kernel` (benchmarks of other tiles). + #[allow(clippy::too_many_arguments)] + fn matmul_with( + &mut self, + kernel: &'static Matmul, + precision: Precision, + [x, w, bias, y]: [&wgpu::Buffer; 4], + (m, n, k): (usize, usize, usize), + bias_rows: usize, + gelu: bool, + residual: bool, + ) -> Result<(), String> { + let step = match precision { + Precision::F32 => 4, + Precision::F16 => kernel.tile.bk as usize, + }; + if !k.is_multiple_of(step) || bias_rows == 0 { + return Err(format!("a {m}×{k}·{k}×{n} product the SAM 3 kernel cannot do")); + } + let params = [u32_of(m)?, u32_of(n)?, u32_of(k)?, u32_of(bias_rows)?, u32::from(gelu), u32::from(residual), 0, 0]; + let groups = [u32_of(n.div_ceil(kernel.tile.bn()))?, u32_of(m.div_ceil(kernel.tile.bm()))?, 1]; + self.push(&kernel.pipeline, params, [x, w, bias, y], groups); + Ok(()) + } + + /// Layer norm of `rows` rows of `c` numbers: `y = (x − mean) / sqrt(var + eps) · gamma + beta`. + fn layernorm(&mut self, [x, gamma, beta, y]: [&wgpu::Buffer; 4], rows: usize, c: usize) -> Result<(), String> { + let (g, row) = self.flat(rows)?; + self.push(&self.dev.k.layernorm, [u32_of(rows)?, u32_of(c)?, 0, 0, EPS.to_bits(), 0, u32_of(rows)?, row], [x, gamma, beta, y], g); + Ok(()) + } + + /// RoPE on the q and k of `qkv` (`[tokens, stride]`, q | k | v each `hidden` wide) in place, from a table of + /// `table_rows` positions (token t uses row t % table_rows), and q scaled by `scale`. + fn rope( + &mut self, + qkv: &wgpu::Buffer, + table: &wgpu::Buffer, + (tokens, stride, hidden): (usize, usize, usize), + table_rows: usize, + scale: f32, + ) -> Result<(), String> { + if hidden % HEAD_DIM != 0 || table_rows == 0 { + return Err("a RoPE the SAM 3 kernel cannot do".into()); + } + let count = tokens.checked_mul(hidden).ok_or("too many tokens")?; + let (g, row) = self.flat(count.div_ceil(256))?; + let dummy = &self.dev.dummy; + let params = [u32_of(tokens)?, u32_of(stride)?, u32_of(hidden)?, u32_of(table_rows)?, 0, scale.to_bits(), u32_of(count)?, row]; + self.push(&self.dev.k.rope, params, [dummy, table, dummy, qkv], g); + Ok(()) + } + + /// Attention of every head over `qkv` (`[tokens, stride]`, q | k | v each `hidden` wide) into `out` + /// (`[tokens, hidden]`), each query over the `span` tokens of its window. + fn attention( + &mut self, + qkv: &wgpu::Buffer, + out: &wgpu::Buffer, + (tokens, stride, hidden): (usize, usize, usize), + span: usize, + ) -> Result<(), String> { + if span == 0 + || !span.is_multiple_of(64) + || !span.is_multiple_of(ATTENTION_KEYS as usize) + || !tokens.is_multiple_of(span) + || !hidden.is_multiple_of(HEAD_DIM) + || !stride.is_multiple_of(4) + { + return Err("an attention the SAM 3 kernel cannot do".into()); + } + let dummy = &self.dev.dummy; + let params = [u32_of(tokens)?, u32_of(span)?, u32_of(stride)?, u32_of(hidden)?, 0, 0, 0, 0]; + let groups = [u32_of(tokens / 64)?, u32_of(hidden / HEAD_DIM)?, 1]; + if groups[0] > self.dev.limits.max_compute_workgroups_per_dimension { + return Err("too many tokens for the SAM 3 attention kernel".into()); + } + self.push(&self.dev.k.attention, params, [qkv, dummy, dummy, out], groups); + Ok(()) + } + + /// The patches of `pixels` (`[channels, side, side]`) as rows of `[tokens, channels · patch²]`, in window order. + fn im2col( + &mut self, + pixels: &wgpu::Buffer, + cols: &wgpu::Buffer, + (side, patch, channels): (usize, usize, usize), + window: usize, + ) -> Result<(), String> { + let grid = side / patch.max(1); + if patch == 0 || window == 0 || grid % window != 0 { + return Err("a patch embedding the SAM 3 kernel cannot do".into()); + } + let count = grid * grid * channels * patch * patch; + let (g, row) = self.flat(count.div_ceil(256))?; + let dummy = &self.dev.dummy; + let params = [u32_of(side)?, u32_of(patch)?, u32_of(grid)?, u32_of(window)?, u32_of(channels)?, 0, u32_of(count)?, row]; + self.push(&self.dev.k.im2col, params, [pixels, dummy, dummy, cols], g); + Ok(()) + } + + /// Tokens `[grid², channels]` in window order to `[channels, grid, grid]`. + fn channels_first(&mut self, x: &wgpu::Buffer, out: &wgpu::Buffer, channels: usize, grid: usize, window: usize) -> Result<(), String> { + if window == 0 || !grid.is_multiple_of(window) { + return Err("a reorder the SAM 3 kernel cannot do".into()); + } + let count = channels * grid * grid; + let (g, row) = self.flat(count.div_ceil(256))?; + let dummy = &self.dev.dummy; + self.push(&self.dev.k.to_chw, [u32_of(channels)?, u32_of(grid)?, u32_of(window)?, 0, 0, 0, u32_of(count)?, row], [x, dummy, dummy, out], g); + Ok(()) + } + + /// The bind groups, with every step's parameters in one uniform buffer. + fn record(self) -> Recorded { + let d = self.dev; + let align = (d.limits.min_uniform_buffer_offset_alignment as usize).max(32); + let mut blob = vec![0u8; self.steps.len().max(1) * align]; + for (chunk, s) in blob.chunks_mut(align).zip(&self.steps) { + if let Some(to) = chunk.get_mut(..32) { + to.copy_from_slice(bytemuck::cast_slice(&s.params)); + } + } + let uniform = d.device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("sam3 params"), + contents: &blob, + usage: wgpu::BufferUsages::UNIFORM, + }); + let steps = self + .steps + .iter() + .enumerate() + .map(|(i, s)| { + let [a, b, c, out] = &s.buffers; + let bind = d.device.create_bind_group(&wgpu::BindGroupDescriptor { + label: None, + layout: &d.layout, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { + buffer: &uniform, + offset: (i * align) as u64, + size: wgpu::BufferSize::new(32), + }), + }, + wgpu::BindGroupEntry { binding: 1, resource: a.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 2, resource: b.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 3, resource: c.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 4, resource: out.as_entire_binding() }, + ], + }); + Step { pipeline: s.pipeline, bind, groups: s.groups } + }) + .collect(); + let mut cuts = self.cuts; + if cuts.last() != Some(&self.steps.len()) { + cuts.push(self.steps.len()); + } + Recorded { steps, cuts } + } +} + +/// Dispatches ready to replay, with where each command buffer ends. +struct Recorded { + steps: Vec, + cuts: Vec, +} + +impl Recorded { + /// Submit every step (one command buffer per cut), copy `len` floats of `src` into `staging` after the last, + /// wait and read them back. + /// Run the recorded dispatches of `stage` (its name for the reason a hung device is given up on) and read `len` + /// floats of `src` back. + fn run(&self, stage: &str, dev: &Dev, src: &wgpu::Buffer, staging: &wgpu::Buffer, len: usize) -> Result, String> { + let bytes = len as u64 * 4; + let oom = dev.device.push_error_scope(wgpu::ErrorFilter::OutOfMemory); + let validation = dev.device.push_error_scope(wgpu::ErrorFilter::Validation); + let mut from = 0; + let mut last = None; + for (n, &to) in self.cuts.iter().enumerate() { + let mut enc = dev.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("sam3") }); + { + let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("sam3"), timestamp_writes: None }); + for s in self.steps.get(from..to).unwrap_or_default() { + pass.set_pipeline(s.pipeline); + pass.set_bind_group(0, &s.bind, &[]); + let [x, y, z] = s.groups; + pass.dispatch_workgroups(x, y, z); + } + } + if n + 1 == self.cuts.len() { + enc.copy_buffer_to_buffer(src, 0, staging, 0, bytes); + } + last = Some(dev.queue.submit([enc.finish()])); + from = to; + } + let slice = staging.slice(..bytes); + let (tx, rx) = std::sync::mpsc::channel(); + slice.map_async(wgpu::MapMode::Read, move |r| { + let _ = tx.send(r); + }); + let waited = dev.device.poll(wgpu::PollType::Wait { submission_index: last, timeout: Some(TIMEOUT) }); + let (validation, oom) = (pollster::block_on(validation.pop()), pollster::block_on(oom.pop())); + // the read-back buffer must not stay mapped, whatever failed: the next pass copies into it + let mapped = if waited.is_ok() { rx.recv_timeout(Duration::from_secs(10)).map_err(|e| e.to_string()) } else { Err("not finished".into()) }; + let out = (|| { + if let Some(e) = oom { + return Err(format!("the GPU ran out of memory: {e}")); + } + if let Some(e) = validation { + mark_broken(&format!("device error: {e}")); + return Err(format!("the GPU reported an error: {e}")); + } + if let Err(e) = &waited { + mark_broken(&format!("the GPU did not finish {stage}: {e}")); + return Err(format!("the GPU did not finish: {e}")); + } + match &mapped { + Ok(Ok(())) => {} + Ok(Err(e)) => return Err(format!("reading the result back failed: {e}")), + Err(e) => return Err(format!("reading the result back failed: {e}")), + } + let data = slice.get_mapped_range().map_err(|e| format!("reading the result back failed: {e:?}"))?; + Ok(data.as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes(*b)).collect::>()) + })(); + if matches!(mapped, Ok(Ok(()))) { + staging.unmap(); + } + let out = out?; + if out.len() != len { + return Err("the GPU returned a short result".into()); + } + Ok(out) + } +} + +// --------------------------------------------------------------------------------------------------------------------- +// the backbone + +/// Device buffers, each `len` floats (`STORAGE | COPY_DST | COPY_SRC`), or uploaded from `data`. +fn buffer(dev: &Dev, label: &str, len: usize) -> wgpu::Buffer { + dev.device.create_buffer(&wgpu::BufferDescriptor { + label: Some(label), + size: (len.max(4) * 4) as u64, + usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::COPY_SRC, + mapped_at_creation: false, + }) +} + +/// A buffer holding `data`. Written through the queue rather than mapped at creation: a buffer the device has no +/// memory for then raises an out-of-memory error (and the caller tries something smaller), not a failed mapping. +fn upload(dev: &Dev, label: &str, data: &[T]) -> wgpu::Buffer { + let bytes: &[u8] = bytemuck::cast_slice(data); + let b = dev.device.create_buffer(&wgpu::BufferDescriptor { + label: Some(label), + size: (bytes.len() as u64).next_multiple_of(4).max(16), + usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + // write_buffer wants whole 4-byte words + if bytes.len().is_multiple_of(4) && !bytes.is_empty() { + dev.queue.write_buffer(&b, 0, bytes); + } + b +} + +/// The nearest f16 to `v` (ties to even), as its bits. +fn f16_bits(v: f32) -> u16 { + let b = v.to_bits(); + let sign = ((b >> 16) & 0x8000) as u16; + let exp = ((b >> 23) & 0xff) as i32; + let man = b & 0x7f_ffff; + if exp == 0xff { + return sign | 0x7c00 | if man != 0 { 0x200 } else { 0 }; + } + let e = exp - 127 + 15; + if e >= 0x1f { + return sign | 0x7c00; + } + let round = |value: u32, shift: u32| -> u32 { + let rest = value & ((1 << shift) - 1); + let half = 1 << (shift - 1); + let r = value >> shift; + if rest > half || (rest == half && r & 1 == 1) { r + 1 } else { r } + }; + if e <= 0 { + // a subnormal half, or zero + if e < -10 { + return sign; + } + return sign | round(man | 0x80_0000, (14 - e) as u32) as u16; + } + // a carry out of the mantissa correctly bumps the exponent (up to infinity) + sign | round(((e as u32) << 23) | man, 13) as u16 +} + +/// Weights `[n, k]` as f16 pairs (k even): u32 i holds k 2i (low half) and 2i + 1. +fn pack_f16(w: &[f32]) -> Vec { + w.chunks(2) + .map(|p| u32::from(f16_bits(p.first().copied().unwrap_or(0.0))) | (u32::from(f16_bits(p.get(1).copied().unwrap_or(0.0))) << 16)) + .collect() +} + +/// The RoPE table of `Sam3ViTRotaryEmbedding` as `vit::rope_tables` makes it, for the tokens of a `side × side` grid +/// listed in window order (`window` per side; `side` itself: plain row-major), coordinates scaled by `scale`: +/// `[tokens, 32]` pairs (cos, sin), pair i of a head rotating by x · f_i (i < 16) or y · f_(i − 16). +fn rope_table(side: usize, window: usize, scale: f64) -> Vec { + let spatial = HEAD_DIM / 2; + let inv: Vec = (0..spatial).step_by(2).map(|i| 1.0 / 10000f64.powf(i as f64 / spatial as f64)).collect(); + let mut out = Vec::with_capacity(side * side * HEAD_DIM); + for t in 0..side * side { + let (row, col) = window_cell(t, side, window); + let (x, y) = (col as f64 * scale, row as f64 * scale); + for pos in [x, y] { + for f in &inv { + let a = (pos * f) as f32 as f64; + out.extend([a.cos() as f32, a.sin() as f32]); + } + } + } + out +} + +/// The grid cell (row, col) of window-order token `t` on a `side × side` grid of `window × window` windows. +fn window_cell(t: usize, side: usize, window: usize) -> (usize, usize) { + let per_side = (side / window.max(1)).max(1); + let (w, l) = (t / (window * window).max(1), t % (window * window).max(1)); + (w / per_side * window + l / window.max(1), w % per_side * window + l % window.max(1)) +} + +/// One layer's weights on the device. +struct LayerWeights { + ln1: [wgpu::Buffer; 2], + qkv: [wgpu::Buffer; 2], + o: [wgpu::Buffer; 2], + ln2: [wgpu::Buffer; 2], + fc1: [wgpu::Buffer; 2], + fc2: [wgpu::Buffer; 2], +} + +/// Reads the backbone's tensors, checking their shapes. +struct Loader<'a> { + weights: &'a WeightReader, + dev: &'static Dev, + precision: Precision, + bytes: u64, +} + +impl Loader<'_> { + fn read(&self, name: &str, shape: &[usize]) -> Result, String> { + let full = format!("{BACKBONE_PREFIX}.{name}"); + let (got, data) = self.weights.read(&full).map_err(|e| format!("{full}: {e}"))?; + if got != shape { + return Err(format!("{full}: shape {got:?}, expected {shape:?}")); + } + Ok(data) + } + + /// A small tensor (a bias, a norm's scale…), always f32. + fn small(&mut self, name: &str, shape: &[usize]) -> Result { + let data = self.read(name, shape)?; + self.bytes += data.len() as u64 * 4; + Ok(upload(self.dev, name, &data)) + } + + /// A linear layer's weight `[n, k]` (concatenated along n when there are several) in the backbone's precision. + fn weight(&mut self, names: &[&str], n: usize, k: usize) -> Result { + let mut all = Vec::with_capacity(names.len() * n * k); + for name in names { + all.extend(self.read(name, &[n, k])?); + } + self.store(names.first().copied().unwrap_or("weight"), &all) + } + + fn store(&mut self, label: &str, data: &[f32]) -> Result { + Ok(match self.precision { + Precision::F32 => { + self.bytes += data.len() as u64 * 4; + upload(self.dev, label, data) + } + Precision::F16 => { + let packed = pack_f16(data); + self.bytes += packed.len() as u64 * 4; + upload(self.dev, label, &packed) + } + }) + } + + fn norm(&mut self, name: &str) -> Result<[wgpu::Buffer; 2], String> { + Ok([self.small(&format!("{name}.weight"), &[HIDDEN])?, self.small(&format!("{name}.bias"), &[HIDDEN])?]) + } + + fn layer(&mut self, i: usize) -> Result { + let l = format!("layers.{i}"); + let a = format!("{l}.attention"); + let qkv_names = [format!("{a}.q_proj.weight"), format!("{a}.k_proj.weight"), format!("{a}.v_proj.weight")]; + let qkv_names: Vec<&str> = qkv_names.iter().map(String::as_str).collect(); + let mut qkv_bias = Vec::with_capacity(3 * HIDDEN); + for p in ["q_proj", "k_proj", "v_proj"] { + qkv_bias.extend(self.read(&format!("{a}.{p}.bias"), &[HIDDEN])?); + } + self.bytes += qkv_bias.len() as u64 * 4; + Ok(LayerWeights { + ln1: self.norm(&format!("{l}.layer_norm1"))?, + qkv: [self.weight(&qkv_names, HIDDEN, HIDDEN)?, upload(self.dev, "qkv bias", &qkv_bias)], + o: [self.weight(&[&format!("{a}.o_proj.weight")], HIDDEN, HIDDEN)?, self.small(&format!("{a}.o_proj.bias"), &[HIDDEN])?], + ln2: self.norm(&format!("{l}.layer_norm2"))?, + fc1: [self.weight(&[&format!("{l}.mlp.fc1.weight")], MLP, HIDDEN)?, self.small(&format!("{l}.mlp.fc1.bias"), &[MLP])?], + fc2: [self.weight(&[&format!("{l}.mlp.fc2.weight")], HIDDEN, MLP)?, self.small(&format!("{l}.mlp.fc2.bias"), &[HIDDEN])?], + }) + } +} + +/// The buffers of a forward pass. +struct Work { + pixels: wgpu::Buffer, + out: wgpu::Buffer, + staging: wgpu::Buffer, +} + +/// The SAM 3 backbone on the GPU: weights, work buffers and every dispatch of a forward pass, made once. +pub struct Sam3Gpu { + dev: &'static Dev, + recorded: Recorded, + /// One forward pass at a time (they share the work buffers). + work: Mutex, + /// Bytes of weights on the device. + weight_bytes: u64, + /// Bytes of work buffers on the device. + work_bytes: u64, + precision: Precision, + /// The detector's DETR encoder, loaded on the first text prompt. + detr: detr::Encoder, + /// The feature pyramids, built on first use. + necks: neck::Necks, + /// The detector's mask decoder, loaded on the first text prompt. + masks: pixel::MaskDecoder, +} + +/// The SAM 3 backbone on the GPU with the checkpoint's weights uploaded, or why it can't run there (GPU off, missing, +/// broken, a software adapter, too small, or out of memory). The weights take 1.8 GB of device memory, or 0.9 GB as f16 +/// when the f32 ones do not fit. +pub fn backbone(weights: &WeightReader) -> Result, String> { + match load(weights, Precision::F32) { + Ok(b) => Ok(Box::new(b)), + // half the memory (0.9 GB of weights), a little less accurate (see `docs/gpu-pipeline.md`) + Err(e) if e.starts_with(NO_MEMORY) => { + log::info!("gpu (sam3): {e}; trying f16 weights"); + Ok(Box::new(load(weights, Precision::F16)?)) + } + Err(e) => Err(e), + } +} + +/// How a build that ran out of device memory fails. +const NO_MEMORY: &str = "not enough GPU memory for the SAM 3 backbone"; + +/// [`backbone`] with the linear layers' weights stored in `precision`. +pub fn load(weights: &WeightReader, precision: Precision) -> Result { + let dev = dev()?; + let Some(_work) = crate::exit::enter() else { return Err("LightCraft is closing".into()) }; + guarded("the SAM 3 backbone", || build(dev, weights, precision)) +} + +fn build(dev: &'static Dev, weights: &WeightReader, precision: Precision) -> Result { + let oom = dev.device.push_error_scope(wgpu::ErrorFilter::OutOfMemory); + let validation = dev.device.push_error_scope(wgpu::ErrorFilter::Validation); + let made = build_inner(dev, weights, precision); + // let the uploads land before the scopes close + let _ = dev.device.poll(wgpu::PollType::Wait { submission_index: None, timeout: Some(TIMEOUT) }); + let (validation, oom) = (pollster::block_on(validation.pop()), pollster::block_on(oom.pop())); + if let Some(e) = oom { + return Err(format!("{NO_MEMORY}: {e}")); + } + if let Some(e) = validation { + return Err(format!("the GPU rejected the SAM 3 backbone: {e}")); + } + made +} + +fn build_inner(dev: &'static Dev, weights: &WeightReader, precision: Precision) -> Result { + let mut ld = Loader { weights, dev, precision: Precision::F32, bytes: 0 }; + // the patch embedding (K = 588, not a multiple of the f16 tile) and its position table stay f32 + let patch = ld.read("embeddings.patch_embeddings.projection.weight", &[HIDDEN, 3, PATCH, PATCH])?; + let patch = ld.store("patch embedding", &patch)?; + let pos = ld.small("embeddings.position_embeddings", &[1, POS_SIDE * POS_SIDE, HIDDEN])?; + let ln_pre = ld.norm("layer_norm")?; + ld.precision = precision; + let mut layers = Vec::with_capacity(LAYERS); + for i in 0..LAYERS { + layers.push(ld.layer(i)?); + // hand the queued uploads (~55 MB a layer) to the device, so their staging memory is freed as they land + dev.queue.submit([]); + } + let rope_window = upload(dev, "rope window", &rope_table(WINDOW, WINDOW, 1.0)); + let rope_global = upload(dev, "rope global", &rope_table(GRID, WINDOW, WINDOW as f64 / GRID as f64)); + + let pixels = buffer(dev, "sam3 pixels", 3 * IMAGE * IMAGE); + let x = buffer(dev, "sam3 hidden", TOKENS * HIDDEN); + let y = buffer(dev, "sam3 normed", TOKENS * HIDDEN); + // im2col, then q|k|v, then the MLP's hidden activations + let big = buffer(dev, "sam3 wide", TOKENS * MLP.max(3 * HIDDEN).max(PATCH_K)); + let staging = dev.device.create_buffer(&wgpu::BufferDescriptor { + label: Some("sam3 read-back"), + size: (TOKENS * HIDDEN * 4) as u64, + usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let work_bytes = ((3 * IMAGE * IMAGE + 3 * TOKENS * HIDDEN + TOKENS * MLP) * 4) as u64; + + let mut g = Graph::new(dev); + g.im2col(&pixels, &big, (IMAGE, PATCH, 3), WINDOW)?; + g.matmul([&big, &patch, &pos, &y], (TOKENS, HIDDEN, PATCH_K), POS_SIDE * POS_SIDE, false, false, Precision::F32)?; + g.layernorm([&y, &ln_pre[0], &ln_pre[1], &x], TOKENS, HIDDEN)?; + g.cut(); + for (i, l) in layers.iter().enumerate() { + let global = GLOBAL.contains(&i); + g.layernorm([&x, &l.ln1[0], &l.ln1[1], &y], TOKENS, HIDDEN)?; + g.matmul([&y, &l.qkv[0], &l.qkv[1], &big], (TOKENS, 3 * HIDDEN, HIDDEN), 1, false, false, precision)?; + let (table, rows, span) = if global { (&rope_global, TOKENS, TOKENS) } else { (&rope_window, WINDOW * WINDOW, WINDOW * WINDOW) }; + g.rope(&big, table, (TOKENS, 3 * HIDDEN, HIDDEN), rows, 1.0 / (HEAD_DIM as f32).sqrt())?; + g.attention(&big, &y, (TOKENS, 3 * HIDDEN, HIDDEN), span)?; + g.matmul([&y, &l.o[0], &l.o[1], &x], (TOKENS, HIDDEN, HIDDEN), 1, false, true, precision)?; + g.layernorm([&x, &l.ln2[0], &l.ln2[1], &y], TOKENS, HIDDEN)?; + g.matmul([&y, &l.fc1[0], &l.fc1[1], &big], (TOKENS, MLP, HIDDEN), 1, true, false, precision)?; + g.matmul([&big, &l.fc2[0], &l.fc2[1], &x], (TOKENS, HIDDEN, MLP), 1, false, true, precision)?; + g.cut(); + } + g.channels_first(&x, &y, HIDDEN, GRID, WINDOW)?; + let recorded = g.record(); + let detr = detr::Encoder::new(weights.clone()); + let necks = neck::Necks::new(weights.clone()); + let masks = pixel::MaskDecoder::new(weights.clone()); + Ok(Sam3Gpu { + dev, + recorded, + work: Mutex::new(Work { pixels, out: y, staging }), + weight_bytes: ld.bytes, + work_bytes, + precision, + detr, + necks, + masks, + }) +} + +/// Run `f`, the work of `stage`, turning a panic into a broken device (with the stage's name). +fn guarded(stage: &str, f: impl FnOnce() -> Result) -> Result { + std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).unwrap_or_else(|_| { + mark_broken(&format!("{stage} on the GPU panicked")); + Err("the GPU runner gave up".into()) + }) +} + +impl Sam3Gpu { + /// Bytes of device memory the weights take. + pub fn weight_bytes(&self) -> u64 { + self.weight_bytes + } + + /// Bytes of device memory the work buffers take (activations, input, read-back). + pub fn work_bytes(&self) -> u64 { + self.work_bytes + (TOKENS * HIDDEN * 4) as u64 + } + + /// Bytes of device memory the DETR encoder's weights and work buffers take, once a text prompt loaded them. + pub fn detr_bytes(&self) -> Option<(u64, u64)> { + self.detr.bytes() + } + + /// Bytes of device memory the mask decoder's weights and work buffers take, once a text prompt loaded them. + pub fn mask_decoder_bytes(&self) -> Option<(u64, u64)> { + self.masks.bytes() + } + + fn run(&self, pixels: &[f32]) -> Result, String> { + if pixels.len() != 3 * IMAGE * IMAGE { + return Err(format!("{} pixel values, expected 3 × {IMAGE} × {IMAGE}", pixels.len())); + } + let Some(_work) = crate::exit::enter() else { return Err("LightCraft is closing".into()) }; + let work = self.work.lock().unwrap_or_else(PoisonError::into_inner); + self.dev.queue.write_buffer(&work.pixels, 0, bytemuck::cast_slice(pixels)); + let out = self.recorded.run("the SAM 3 backbone", self.dev, &work.out, &work.staging, TOKENS * HIDDEN)?; + if out.iter().any(|v| !v.is_finite()) { + return Err("the GPU backbone produced non-finite values".into()); + } + Ok(out) + } +} + +impl BackboneAccel for Sam3Gpu { + fn forward(&self, pixels: &[f32]) -> Result, String> { + if let Some(why) = broken_reason() { + return Err(format!("the GPU is not used any more: {why}")); + } + if let Some(why) = crate::switched_off() { + return Err(why); + } + guarded("the SAM 3 backbone", || self.run(pixels)) + } + + fn neck(&self, which: NeckKind, backbone: &[f32], n: usize) -> Result>, String> { + if let Some(why) = broken_reason() { + return Err(format!("the GPU is not used any more: {why}")); + } + if let Some(why) = crate::switched_off() { + return Err(why); + } + guarded("a SAM 3 neck", || self.necks.run(self.dev, which, backbone, n)) + } + + fn detr_encoder(&self, image: &[f32], pos: &[f32], text: &[f32], valid: &[bool]) -> Result, String> { + if let Some(why) = broken_reason() { + return Err(format!("the GPU is not used any more: {why}")); + } + if let Some(why) = crate::switched_off() { + return Err(why); + } + let Some(_work) = crate::exit::enter() else { return Err("LightCraft is closing".into()) }; + guarded("the SAM 3 DETR encoder", || self.detr.run(self.dev, image, pos, text, valid)) + } + + fn mask_decoder( + &self, + memory: &[f32], + text: &[f32], + valid: &[bool], + levels: [&[f32]; 2], + rows: &[f32], + bias: &[f32], + ) -> Result, String> { + if let Some(why) = broken_reason() { + return Err(format!("the GPU is not used any more: {why}")); + } + if let Some(why) = crate::switched_off() { + return Err(why); + } + let Some(_work) = crate::exit::enter() else { return Err("LightCraft is closing".into()) }; + guarded("the SAM 3 mask decoder", || self.masks.run(self.dev, memory, text, valid, levels, rows, bias)) + } + + fn closing(&self) -> bool { + crate::shutting_down() + } + + fn runs_necks(&self) -> bool { + true + } + + fn runs_detr_encoder(&self) -> bool { + true + } + + fn runs_mask_decoder(&self) -> bool { + true + } + + fn device(&self) -> String { + let weights = match self.precision { + Precision::F32 => "", + Precision::F16 => ", f16 weights", + }; + format!("{} ({:?}{weights})", self.dev.info.name, self.dev.info.backend) + } +} diff --git a/crates/gpu/src/sam3/detr.rs b/crates/gpu/src/sam3/detr.rs new file mode 100644 index 0000000000..1c2850c8ec --- /dev/null +++ b/crates/gpu/src/sam3/detr.rs @@ -0,0 +1,356 @@ +//! The DETR encoder of SAM 3's text detector on the GPU (`lightcraft-segment`'s `detector.rs` is the reference): six +//! layers over the 72 × 72 image tokens of 256, each self-attention (q and k from the normed tokens plus their sine +//! position encoding, v from the normed tokens) → cross-attention to the prompt's 32 tokens (with the key-padding bias) +//! → MLP 256 → 2048 → 256 with ReLU, each after a layer norm (eps 1e-5) and added to the tokens. ~4 s per prompt on +//! the CPU through candle. +//! +//! Kernels: the backbone's matrix product (ReLU in its epilogue) and layer norm, and `wgsl/sam3_detr.wgsl`: attention +//! with heads of 32 whose q, k and v come from separate buffers (the cross-attention's k and v from the prompt), with +//! an optional per-key bias, and a sum. The weights (38 MB) and the kernels load on the first prompt, not with the +//! backbone; then every dispatch is recorded once, and a prompt writes the tokens, their position encoding, the +//! prompt's tokens and its padding bias, submits one command buffer per layer and reads the memory back. + +use std::sync::{Mutex, OnceLock, PoisonError}; + +use lightcraft_segment::WeightReader; + +use super::{Dev, Graph, Precision, Recorded, TIMEOUT, buffer, pipeline, u32_of, upload}; + +#[cfg(test)] +mod tests; + +/// Where the encoder's weights are in the checkpoint. +const PREFIX: &str = "detector_model.detr_encoder"; +/// Image tokens (72 × 72), their width, the prompt's tokens. +const TOKENS: usize = 72 * 72; +const WIDTH: usize = 256; +const TEXT: usize = 32; +const HEAD_DIM: usize = 32; +const MLP: usize = 2048; +const LAYERS: usize = 6; +/// PyTorch's `nn.LayerNorm` default (`TORCH_LN_EPS`). +const EPS: f32 = 1e-5; +/// Required key-count alignment, kept at 32 even when the DX12 kernel uses smaller tiles. +const KEYS: u32 = 32; +/// `p.gelu` of the matrix product: ReLU. +const RELU: u32 = 2; +/// No bias in the attention kernel. +const NONE: u32 = u32::MAX; + +pub(super) struct Kernels { + attention: wgpu::ComputePipeline, + add: wgpu::ComputePipeline, +} + +static KERNELS: OnceLock> = OnceLock::new(); + +/// The encoder's kernels, compiled on first use (the mask decoder's prompt attention uses them too). +pub(super) fn kernels(dev: &'static Dev) -> Result<&'static Kernels, String> { + KERNELS + .get_or_init(|| { + let validation = dev.device.push_error_scope(wgpu::ErrorFilter::Validation); + let source = attention_source(super::attention_keys(dev.info.backend)); + let pipe = |entry: &str| pipeline(&dev.device, &dev.pipeline_layout, "sam3 detr", &source, entry); + let k = Kernels { attention: pipe("attention"), add: pipe("add") }; + match pollster::block_on(validation.pop()) { + Some(e) => Err(format!("{}: the SAM 3 DETR kernels did not compile ({e})", dev.info.name)), + None => Ok(k), + } + }) + .as_ref() + .map_err(Clone::clone) +} + +/// The attention kernel for `keys` keys per step, written out from `wgsl/sam3_detr.wgsl` (as the backbone's). +fn attention_source(keys: u32) -> String { + use std::fmt::Write; + let d4 = (HEAD_DIM / 4) as u32; + let (mut decl, mut scores, mut rescale, mut acc, mut store) = (String::new(), String::new(), String::new(), String::new(), String::new()); + // writing into a String cannot fail + for c in 0..d4 { + let _ = writeln!(decl, " let q{c} = qs[qa + {c}u];\n var o{c} = vec4(0.0);"); + let _ = writeln!(rescale, " o{c} *= fix;"); + let _ = writeln!(store, " out[oa + {c}u] = o{c} * r;"); + } + for j in 0..keys { + let terms: Vec = (0..d4).map(|c| format!("q{c} * Ks[{}u]", j * d4 + c)).collect(); + let _ = writeln!( + scores, + " let d{j} = {};\n let s{j} = (d{j}.x + d{j}.y + d{j}.z + d{j}.w) * SCALE + Bs[{j}u];\n top = max(top, s{j});", + terms.join(" + ") + ); + let _ = writeln!(acc, " {{\n let w = exp(s{j} - top);\n l += w;"); + for c in 0..d4 { + let _ = writeln!(acc, " o{c} = fma(vec4(w), Vs[{}u], o{c});", j * d4 + c); + } + let _ = writeln!(acc, " }}"); + } + include_str!("../wgsl/sam3_detr.wgsl") + .replace("{{KB}}", &keys.to_string()) + .replace("{{DECL}}", &decl) + .replace("{{SCORES}}", &scores) + .replace("{{RESCALE}}", &rescale) + .replace("{{ACCUMULATE}}", &acc) + .replace("{{STORE}}", &store) +} + +/// Where an attention's q, k and v are: a buffer, its row stride and the column of head 0 (in floats). +pub(super) struct Operand<'a> { + pub(super) buffer: &'a wgpu::Buffer, + pub(super) stride: usize, + pub(super) offset: usize, +} + +impl Graph { + /// Layer norm with PyTorch's eps (the backbone's is 1e-6). + pub(super) fn layernorm_torch(&mut self, [x, gamma, beta, y]: [&wgpu::Buffer; 4], rows: usize, c: usize) -> Result<(), String> { + let (g, row) = self.flat(rows)?; + self.push(&self.dev.k.layernorm, [u32_of(rows)?, u32_of(c)?, 0, 0, EPS.to_bits(), 0, u32_of(rows)?, row], [x, gamma, beta, y], g); + Ok(()) + } + + /// `y = relu(x · wᵀ + bias)`. + fn matmul_relu(&mut self, buffers: [&wgpu::Buffer; 4], dims: (usize, usize, usize)) -> Result<(), String> { + self.matmul(buffers, dims, 1, false, false, Precision::F32)?; + if let Some(step) = self.steps.last_mut() { + step.params[4] = RELU; + } + Ok(()) + } + + /// `out = a + b`, `len` floats (a multiple of 4). + fn add(&mut self, k: &'static Kernels, [a, b, out]: [&wgpu::Buffer; 3], len: usize) -> Result<(), String> { + if !len.is_multiple_of(4) { + return Err("a sum the SAM 3 kernel cannot do".into()); + } + let (g, row) = self.flat((len / 4).div_ceil(256))?; + self.push(&k.add, [u32_of(len / 4)?, row, 0, 0, 0, 0, 0, 0], [a, b, &self.dev.dummy, out], g); + Ok(()) + } + + /// Attention of `queries` queries over `keys` keys, `heads` heads of 32, into `out` (`[queries, heads · 32]`); + /// with `bias`, key j's scores get `k.buffer[bias + j]` added. + #[allow(clippy::too_many_arguments)] + pub(super) fn attention_detr( + &mut self, + kernels: &'static Kernels, + [q, k, v]: [Operand; 3], + bias: Option, + out: &wgpu::Buffer, + (queries, keys, heads): (usize, usize, usize), + ) -> Result<(), String> { + let aligned = [q.stride, q.offset, k.stride, k.offset, v.stride, v.offset].iter().all(|n| n.is_multiple_of(4)); + if keys == 0 || !keys.is_multiple_of(KEYS as usize) || !aligned || q.offset != 0 { + return Err("an attention the SAM 3 DETR kernel cannot do".into()); + } + let bias = match bias { + Some(b) => u32_of(b)?, + None => NONE, + }; + let params = + [u32_of(queries)?, u32_of(keys)?, u32_of(q.stride)?, u32_of(k.stride)?, u32_of(v.stride)?, u32_of(k.offset)?, u32_of(v.offset)?, bias]; + let groups = [u32_of(queries.div_ceil(64))?, u32_of(heads)?, 1]; + if groups[0] > self.dev.limits.max_compute_workgroups_per_dimension { + return Err("too many queries for the SAM 3 DETR attention kernel".into()); + } + self.push(&kernels.attention, params, [q.buffer, k.buffer, v.buffer, out], groups); + Ok(()) + } +} + +/// One layer's weights on the device: (weight, bias) pairs, the q | k and k | v ones concatenated. +struct Layer { + ln1: [wgpu::Buffer; 2], + self_qk: [wgpu::Buffer; 2], + self_v: [wgpu::Buffer; 2], + self_o: [wgpu::Buffer; 2], + ln2: [wgpu::Buffer; 2], + cross_q: [wgpu::Buffer; 2], + cross_kv: [wgpu::Buffer; 2], + cross_o: [wgpu::Buffer; 2], + ln3: [wgpu::Buffer; 2], + fc1: [wgpu::Buffer; 2], + fc2: [wgpu::Buffer; 2], +} + +/// Reads the encoder's tensors, checking their shapes. +struct Loader<'a> { + weights: &'a WeightReader, + dev: &'static Dev, + bytes: u64, +} + +impl Loader<'_> { + /// The tensors `names` (each of `shape`) concatenated along the first axis. + fn upload(&mut self, names: &[String], shape: &[usize]) -> Result { + let mut all = Vec::with_capacity(names.len() * shape.iter().product::()); + for name in names { + let full = format!("{PREFIX}.{name}"); + let (got, data) = self.weights.read(&full).map_err(|e| format!("{full}: {e}"))?; + if got != shape { + return Err(format!("{full}: shape {got:?}, expected {shape:?}")); + } + all.extend(data); + } + self.bytes += all.len() as u64 * 4; + Ok(upload(self.dev, names.first().map_or("weight", String::as_str), &all)) + } + + /// A linear layer (or several along n): `[n, k]` weights and their bias. + fn linear(&mut self, names: &[String], n: usize, k: usize) -> Result<[wgpu::Buffer; 2], String> { + let w: Vec = names.iter().map(|n| format!("{n}.weight")).collect(); + let b: Vec = names.iter().map(|n| format!("{n}.bias")).collect(); + Ok([self.upload(&w, &[n, k])?, self.upload(&b, &[n])?]) + } + + fn norm(&mut self, name: &str) -> Result<[wgpu::Buffer; 2], String> { + Ok([self.upload(&[format!("{name}.weight")], &[WIDTH])?, self.upload(&[format!("{name}.bias")], &[WIDTH])?]) + } + + fn layer(&mut self, i: usize) -> Result { + let l = format!("layers.{i}"); + let (s, c) = (format!("{l}.self_attn"), format!("{l}.cross_attn")); + let proj = |a: &str, ps: &[&str]| -> Vec { ps.iter().map(|p| format!("{a}.{p}_proj")).collect() }; + Ok(Layer { + ln1: self.norm(&format!("{l}.layer_norm1"))?, + self_qk: self.linear(&proj(&s, &["q", "k"]), WIDTH, WIDTH)?, + self_v: self.linear(&proj(&s, &["v"]), WIDTH, WIDTH)?, + self_o: self.linear(&proj(&s, &["o"]), WIDTH, WIDTH)?, + ln2: self.norm(&format!("{l}.layer_norm2"))?, + cross_q: self.linear(&proj(&c, &["q"]), WIDTH, WIDTH)?, + cross_kv: self.linear(&proj(&c, &["k", "v"]), WIDTH, WIDTH)?, + cross_o: self.linear(&proj(&c, &["o"]), WIDTH, WIDTH)?, + ln3: self.norm(&format!("{l}.layer_norm3"))?, + fc1: self.linear(&[format!("{l}.mlp.fc1")], MLP, WIDTH)?, + fc2: self.linear(&[format!("{l}.mlp.fc2")], WIDTH, MLP)?, + }) + } +} + +/// The buffers a prompt writes and reads. +struct Work { + /// The image tokens in, the memory out (the layers add to it in place). + x: wgpu::Buffer, + pos: wgpu::Buffer, + text: wgpu::Buffer, + /// The cross-attention's k | v of the prompt (`[32, 512]`), then its padding bias (32 floats). + text_kv: wgpu::Buffer, + staging: wgpu::Buffer, +} + +/// The encoder with its weights on the device and its dispatches recorded. +struct Built { + recorded: Recorded, + /// One prompt at a time (they share the work buffers). + work: Mutex, + /// Bytes of device memory: weights, work buffers. + weight_bytes: u64, + work_bytes: u64, +} + +/// The DETR encoder, built on first use from the checkpoint the backbone came from. +pub(super) struct Encoder { + weights: WeightReader, + built: OnceLock>, +} + +impl Encoder { + pub(super) fn new(weights: WeightReader) -> Self { + Self { weights, built: OnceLock::new() } + } + + /// Bytes of device memory the weights and the work buffers take, once built. + pub(super) fn bytes(&self) -> Option<(u64, u64)> { + self.built.get().and_then(|b| b.as_ref().ok()).map(|b| (b.weight_bytes, b.work_bytes)) + } + + /// The memory `[5184, 256]` for the image tokens and their position encoding (`[5184, 256]` each) and the prompt's + /// tokens `[32, 256]` (`valid`: its real ones). + pub(super) fn run(&self, dev: &'static Dev, image: &[f32], pos: &[f32], text: &[f32], valid: &[bool]) -> Result, String> { + if image.len() != TOKENS * WIDTH || pos.len() != TOKENS * WIDTH || text.len() != TEXT * WIDTH || valid.len() != TEXT { + return Err(format!( + "{} image, {} position, {} prompt values and {} prompt tokens, expected {TOKENS} × {WIDTH}, {TOKENS} × {WIDTH}, {TEXT} × {WIDTH} and {TEXT}", + image.len(), + pos.len(), + text.len(), + valid.len() + )); + } + let b = self.built.get_or_init(|| build(dev, &self.weights)).as_ref().map_err(Clone::clone)?; + let bias: Vec = valid.iter().map(|&ok| if ok { 0.0 } else { f32::MIN }).collect(); + let work = b.work.lock().unwrap_or_else(PoisonError::into_inner); + dev.queue.write_buffer(&work.x, 0, bytemuck::cast_slice(image)); + dev.queue.write_buffer(&work.pos, 0, bytemuck::cast_slice(pos)); + dev.queue.write_buffer(&work.text, 0, bytemuck::cast_slice(text)); + dev.queue.write_buffer(&work.text_kv, (TEXT * 2 * WIDTH * 4) as u64, bytemuck::cast_slice(&bias)); + let out = b.recorded.run("the SAM 3 DETR encoder", dev, &work.x, &work.staging, TOKENS * WIDTH)?; + if out.iter().any(|v| !v.is_finite()) { + return Err("the GPU DETR encoder produced non-finite values".into()); + } + Ok(out) + } +} + +fn build(dev: &'static Dev, weights: &WeightReader) -> Result { + let k = kernels(dev)?; + let oom = dev.device.push_error_scope(wgpu::ErrorFilter::OutOfMemory); + let validation = dev.device.push_error_scope(wgpu::ErrorFilter::Validation); + let made = build_inner(dev, k, weights); + // let the uploads land before the scopes close + let _ = dev.device.poll(wgpu::PollType::Wait { submission_index: None, timeout: Some(TIMEOUT) }); + let (validation, oom) = (pollster::block_on(validation.pop()), pollster::block_on(oom.pop())); + if let Some(e) = oom { + return Err(format!("not enough GPU memory for the SAM 3 DETR encoder: {e}")); + } + if let Some(e) = validation { + return Err(format!("the GPU rejected the SAM 3 DETR encoder: {e}")); + } + made +} + +fn build_inner(dev: &'static Dev, k: &'static Kernels, weights: &WeightReader) -> Result { + let mut ld = Loader { weights, dev, bytes: 0 }; + let layers = (0..LAYERS).map(|i| ld.layer(i)).collect::, _>>()?; + + let tokens = |label: &str| buffer(dev, label, TOKENS * WIDTH); + let (x, y, hp, v, att, pos) = + (tokens("detr hidden"), tokens("detr normed"), tokens("detr normed + pos"), tokens("detr v"), tokens("detr attention"), tokens("detr pos")); + // the self-attention's q | k, then the MLP's hidden activations + let wide = buffer(dev, "detr wide", TOKENS * MLP.max(2 * WIDTH)); + let text = buffer(dev, "detr prompt", TEXT * WIDTH); + let text_kv = buffer(dev, "detr prompt k|v", TEXT * 2 * WIDTH + TEXT); + let staging = dev.device.create_buffer(&wgpu::BufferDescriptor { + label: Some("detr read-back"), + size: (TOKENS * WIDTH * 4) as u64, + usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let work_bytes = ((7 * TOKENS * WIDTH + TOKENS * MLP + TEXT * (3 * WIDTH + 1)) * 4) as u64; + + let mut g = Graph::new(dev); + let heads = WIDTH / HEAD_DIM; + for l in &layers { + // self-attention: q and k from the normed tokens plus their position, v from the normed tokens + g.layernorm_torch([&x, &l.ln1[0], &l.ln1[1], &y], TOKENS, WIDTH)?; + g.add(k, [&y, &pos, &hp], TOKENS * WIDTH)?; + g.matmul([&hp, &l.self_qk[0], &l.self_qk[1], &wide], (TOKENS, 2 * WIDTH, WIDTH), 1, false, false, Precision::F32)?; + g.matmul([&y, &l.self_v[0], &l.self_v[1], &v], (TOKENS, WIDTH, WIDTH), 1, false, false, Precision::F32)?; + let (q, kk) = (Operand { buffer: &wide, stride: 2 * WIDTH, offset: 0 }, Operand { buffer: &wide, stride: 2 * WIDTH, offset: WIDTH }); + g.attention_detr(k, [q, kk, Operand { buffer: &v, stride: WIDTH, offset: 0 }], None, &att, (TOKENS, TOKENS, heads))?; + g.matmul([&att, &l.self_o[0], &l.self_o[1], &x], (TOKENS, WIDTH, WIDTH), 1, false, true, Precision::F32)?; + // cross-attention to the prompt, its padding masked + g.layernorm_torch([&x, &l.ln2[0], &l.ln2[1], &y], TOKENS, WIDTH)?; + g.matmul([&y, &l.cross_q[0], &l.cross_q[1], &v], (TOKENS, WIDTH, WIDTH), 1, false, false, Precision::F32)?; + g.matmul([&text, &l.cross_kv[0], &l.cross_kv[1], &text_kv], (TEXT, 2 * WIDTH, WIDTH), 1, false, false, Precision::F32)?; + let (tk, tv) = (Operand { buffer: &text_kv, stride: 2 * WIDTH, offset: 0 }, Operand { buffer: &text_kv, stride: 2 * WIDTH, offset: WIDTH }); + g.attention_detr(k, [Operand { buffer: &v, stride: WIDTH, offset: 0 }, tk, tv], Some(TEXT * 2 * WIDTH), &att, (TOKENS, TEXT, heads))?; + g.matmul([&att, &l.cross_o[0], &l.cross_o[1], &x], (TOKENS, WIDTH, WIDTH), 1, false, true, Precision::F32)?; + // MLP + g.layernorm_torch([&x, &l.ln3[0], &l.ln3[1], &y], TOKENS, WIDTH)?; + g.matmul_relu([&y, &l.fc1[0], &l.fc1[1], &wide], (TOKENS, MLP, WIDTH))?; + g.matmul([&wide, &l.fc2[0], &l.fc2[1], &x], (TOKENS, WIDTH, MLP), 1, false, true, Precision::F32)?; + g.cut(); + } + let recorded = g.record(); + Ok(Built { recorded, work: Mutex::new(Work { x, pos, text, text_kv, staging }), weight_bytes: ld.bytes, work_bytes }) +} diff --git a/crates/gpu/src/sam3/detr/tests.rs b/crates/gpu/src/sam3/detr/tests.rs new file mode 100644 index 0000000000..b94f342d99 --- /dev/null +++ b/crates/gpu/src/sam3/detr/tests.rs @@ -0,0 +1,269 @@ +//! The DETR encoder's kernels against plain loops: attention with heads of 32 (self- and cross-attention, the padding +//! bias, queries not filling the last workgroup), the sum, ReLU and the layer norm's eps. The whole encoder against +//! candle: `tests/it/sam3_detr.rs`. + +use super::super::dev; +use super::*; + +fn gpu() -> Option<(&'static Dev, &'static Kernels)> { + let d = match dev() { + Ok(d) => d, + // a kernel that doesn't compile is a failure, not a missing GPU + Err(e) if e.contains("did not compile") => panic!("{e}"), + Err(e) => { + lightcraft_testkit::skip!(Gpu, "no GPU for the SAM 3 kernels ({e})"); + return None; + } + }; + Some((d, kernels(d).unwrap())) +} + +/// Deterministic values in −scale..scale. +fn values(n: usize, seed: u64, scale: f32) -> Vec { + let mut s = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (0..n) + .map(|_| { + s = s.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + ((s >> 40) as f32 / (1u64 << 24) as f32 * 2.0 - 1.0) * scale + }) + .collect() +} + +fn read(d: &'static Dev, g: Graph, out: &wgpu::Buffer, len: usize) -> Vec { + let staging = d.device.create_buffer(&wgpu::BufferDescriptor { + label: None, + size: (len * 4) as u64, + usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + g.record().run("a test", d, out, &staging, len).unwrap() +} + +fn worst(got: &[f32], want: &[f32]) -> f32 { + assert_eq!(got.len(), want.len()); + got.iter().zip(want).fold(0f32, |m, (a, b)| m.max((a - b).abs())) +} + +/// Where a test attention's operand is in its buffer. +struct At<'a> { + data: &'a [f32], + stride: usize, + offset: usize, +} + +/// Softmax attention of every query over all keys, `heads` heads of 32, as candle computes it: the scores +/// `q · k / sqrt(32) + bias` in f32 (so f32::MIN swallows a padded key's score), the rest in f64. +fn attention_ref(q: At, k: At, v: At, bias: Option<&[f32]>, (queries, keys, heads): (usize, usize, usize)) -> Vec { + let scale = (HEAD_DIM as f32).powf(-0.5); + let mut out = vec![0f32; queries * heads * HEAD_DIM]; + for t in 0..queries { + for h in 0..heads { + let at = |o: &At, row: usize, c: usize| o.data[row * o.stride + o.offset + h * HEAD_DIM + c]; + let scores: Vec = (0..keys) + .map(|j| { + let dot = (0..HEAD_DIM).map(|c| f64::from(at(&q, t, c)) * f64::from(at(&k, j, c))).sum::() as f32; + dot * scale + bias.map_or(0.0, |b| b[j]) + }) + .collect(); + let top = scores.iter().fold(f32::MIN, |m, s| m.max(*s)); + let w: Vec = scores.iter().map(|s| f64::from(s - top).exp()).collect(); + let sum: f64 = w.iter().sum(); + for c in 0..HEAD_DIM { + let o = (0..keys).map(|j| w[j] * f64::from(at(&v, j, c))).sum::() / sum; + out[(t * heads + h) * HEAD_DIM + c] = o as f32; + } + } + } + out +} + +#[test] +fn the_kernel_source_is_written_out() { + let src = attention_source(KEYS); + assert!(!src.contains("{{"), "a mark is left"); + assert!(src.contains("let s31 = ") && !src.contains("let s32 = ")); + assert!(src.contains("let q7 = ") && !src.contains("let q8 = ")); + let dx12 = attention_source(super::super::attention_keys(wgpu::Backend::Dx12)); + assert!(dx12.contains("let s7 = ") && !dx12.contains("let s8 = ")); +} + +#[test] +fn self_attention_over_8_heads_of_32_gives_the_softmax_of_the_definition() { + let Some((d, k)) = gpu() else { return }; + let heads = 8; + let w = heads * HEAD_DIM; + // q | k in one buffer (k at column 256), v in another; 200 queries leave the last workgroup part empty + for (queries, keys) in [(200, 96), (64, 32), (130, 320)] { + let rows = queries.max(keys); + let qk = values(rows * 2 * w, queries as u64, 2.0); + let v = values(keys * w, 7 + keys as u64, 1.0); + let (bqk, bv) = (upload(d, "qk", &qk), upload(d, "v", &v)); + let out = buffer(d, "out", queries * w); + let mut g = Graph::new(d); + let ops = [ + Operand { buffer: &bqk, stride: 2 * w, offset: 0 }, + Operand { buffer: &bqk, stride: 2 * w, offset: w }, + Operand { buffer: &bv, stride: w, offset: 0 }, + ]; + g.attention_detr(k, ops, None, &out, (queries, keys, heads)).unwrap(); + let got = read(d, g, &out, queries * w); + let want = attention_ref( + At { data: &qk, stride: 2 * w, offset: 0 }, + At { data: &qk, stride: 2 * w, offset: w }, + At { data: &v, stride: w, offset: 0 }, + None, + (queries, keys, heads), + ); + let err = worst(&got, &want); + assert!(err < 2e-5, "{queries} queries × {keys} keys: off by {err}"); + } +} + +#[test] +fn cross_attention_to_32_prompt_tokens_leaves_out_the_padding() { + let Some((d, k)) = gpu() else { return }; + let (heads, queries) = (8, 130); + let w = heads * HEAD_DIM; + let q = values(queries * w, 1, 2.0); + // the prompt's k | v ([32, 512]), then its bias: 0 for the real tokens, f32::MIN for padding + for real in [5, 32, 1, 0] { + let mut kv = values(TEXT * 2 * w, 2 + real as u64, 2.0); + let bias: Vec = (0..TEXT).map(|j| if j < real { 0.0 } else { f32::MIN }).collect(); + kv.extend(&bias); + let (bq, bkv) = (upload(d, "q", &q), upload(d, "kv", &kv)); + let out = buffer(d, "out", queries * w); + let mut g = Graph::new(d); + let ops = [ + Operand { buffer: &bq, stride: w, offset: 0 }, + Operand { buffer: &bkv, stride: 2 * w, offset: 0 }, + Operand { buffer: &bkv, stride: 2 * w, offset: w }, + ]; + g.attention_detr(k, ops, Some(TEXT * 2 * w), &out, (queries, TEXT, heads)).unwrap(); + let got = read(d, g, &out, queries * w); + let want = attention_ref( + At { data: &q, stride: w, offset: 0 }, + At { data: &kv, stride: 2 * w, offset: 0 }, + At { data: &kv, stride: 2 * w, offset: w }, + Some(&bias), + (queries, TEXT, heads), + ); + let err = worst(&got, &want); + assert!(err < 2e-5, "{real} real tokens: off by {err}"); + if real == 1 { + // one real token: every query gets its v + let first = &kv[w..2 * w]; + assert!(worst(&got[..w], first) < 1e-6); + } + } +} + +#[test] +fn attention_the_kernel_cannot_do_is_an_error() { + let Some((d, k)) = gpu() else { return }; + let b = buffer(d, "b", 64 * 256); + let op = |stride, offset| Operand { buffer: &b, stride, offset }; + // keys not a multiple of 32, a stride not a multiple of 4, q not at column 0 + assert!(Graph::new(d).attention_detr(k, [op(256, 0), op(256, 0), op(256, 0)], None, &b, (64, 40, 8)).is_err()); + assert!(Graph::new(d).attention_detr(k, [op(256, 0), op(258, 0), op(256, 0)], None, &b, (64, 32, 8)).is_err()); + assert!(Graph::new(d).attention_detr(k, [op(256, 4), op(256, 0), op(256, 0)], None, &b, (64, 32, 8)).is_err()); + assert!(Graph::new(d).add(k, [&b, &b, &b], 6).is_err()); +} + +#[test] +fn sum_relu_and_torch_layer_norm_give_what_the_definitions_give() { + let Some((d, k)) = gpu() else { return }; + // the sum, over more than one row of workgroups' worth + let n = 4 * 256 * 70 + 12; + let (a, b) = (values(n, 1, 1.0), values(n, 2, 1.0)); + let (ba, bb, out) = (upload(d, "a", &a), upload(d, "b", &b), buffer(d, "out", n)); + let mut g = Graph::new(d); + g.add(k, [&ba, &bb, &out], n).unwrap(); + let want: Vec = a.iter().zip(&b).map(|(x, y)| x + y).collect(); + assert_eq!(read(d, g, &out, n), want); + + // ReLU in the product's epilogue + let (m, nn, kk) = (70, 90, 64); + let (x, w, bias) = (values(m * kk, 3, 1.0), values(nn * kk, 4, 0.3), values(nn, 5, 0.5)); + let (bx, bw, bbias, by) = (upload(d, "x", &x), upload(d, "w", &w), upload(d, "bias", &bias), buffer(d, "y", m * nn)); + let mut g = Graph::new(d); + g.matmul_relu([&bx, &bw, &bbias, &by], (m, nn, kk)).unwrap(); + let got = read(d, g, &by, m * nn); + let want: Vec = (0..m * nn) + .map(|o| { + let (i, j) = (o / nn, o % nn); + let v = f64::from(bias[j]) + (0..kk).map(|t| f64::from(x[i * kk + t]) * f64::from(w[j * kk + t])).sum::(); + v.max(0.0) as f32 + }) + .collect(); + assert!(worst(&got, &want) < 1e-5); + assert!(got.contains(&0.0) && got.iter().any(|v| *v > 0.0)); + + // rows of small spread, where eps 1e-5 and 1e-6 differ + let (rows, c) = (5, WIDTH); + let x = values(rows * c, 6, 3e-3); + let (gamma, beta) = (values(c, 7, 1.0), values(c, 8, 0.1)); + let (bx, bg, bb, by) = (upload(d, "x", &x), upload(d, "g", &gamma), upload(d, "b", &beta), buffer(d, "y", rows * c)); + let mut g = Graph::new(d); + g.layernorm_torch([&bx, &bg, &bb, &by], rows, c).unwrap(); + let got = read(d, g, &by, rows * c); + let mut want = vec![0f32; rows * c]; + for r in 0..rows { + let row = &x[r * c..(r + 1) * c]; + let mean = row.iter().map(|v| f64::from(*v)).sum::() / c as f64; + let var = row.iter().map(|v| (f64::from(*v) - mean).powi(2)).sum::() / c as f64; + for i in 0..c { + want[r * c + i] = ((f64::from(row[i]) - mean) / (var + f64::from(EPS)).sqrt() * f64::from(gamma[i]) + f64::from(beta[i])) as f32; + } + } + let err = worst(&got, &want); + assert!(err < 1e-4, "layer norm off by {err}"); +} + +/// The encoder's steps at its shapes: +/// `cargo test --release -p lightcraft-gpu --features sam --lib sam3::detr::tests::timings -- --ignored --nocapture`. +#[test] +#[ignore = "a benchmark: needs a GPU"] +fn timings() { + let Some((d, k)) = gpu() else { return }; + let reps = 20; + let time = |name: &str, flops: f64, build: &dyn Fn(&mut Graph)| { + let out = buffer(d, "out", 4); + let staging = d.device.create_buffer(&wgpu::BufferDescriptor { + label: None, + size: 16, + usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let mut g = Graph::new(d); + for _ in 0..reps { + build(&mut g); + } + let rec = g.record(); + rec.run("a test", d, &out, &staging, 4).unwrap(); + let t = std::time::Instant::now(); + rec.run("a test", d, &out, &staging, 4).unwrap(); + let ms = t.elapsed().as_secs_f64() * 1e3 / reps as f64; + eprintln!("{name:>34}: {ms:7.3} ms {:6.2} TFLOP/s", flops / ms / 1e9); + }; + let x = buffer(d, "x", TOKENS * MLP); + let y = buffer(d, "y", TOKENS * MLP); + let w = buffer(d, "w", MLP * WIDTH); + let b = buffer(d, "b", MLP); + for (n, kk) in [(2 * WIDTH, WIDTH), (WIDTH, WIDTH), (MLP, WIDTH), (WIDTH, MLP)] { + let flops = 2.0 * (TOKENS * n * kk) as f64; + time(&format!("matmul {TOKENS}x{n}x{kk}"), flops, &|g| g.matmul([&x, &w, &b, &y], (TOKENS, n, kk), 1, false, false, Precision::F32).unwrap()); + } + for keys in [TOKENS, TEXT] { + let flops = 4.0 * (TOKENS * keys * WIDTH) as f64; + time(&format!("attention {keys} keys"), flops, &|g| { + let ops = [ + Operand { buffer: &x, stride: 2 * WIDTH, offset: 0 }, + Operand { buffer: &x, stride: 2 * WIDTH, offset: WIDTH }, + Operand { buffer: &x, stride: WIDTH, offset: 0 }, + ]; + g.attention_detr(k, ops, None, &y, (TOKENS, keys, WIDTH / HEAD_DIM)).unwrap() + }); + } + time("layernorm", 0.0, &|g| g.layernorm_torch([&x, &b, &b, &y], TOKENS, WIDTH).unwrap()); + time("add", 0.0, &|g| g.add(k, [&x, &x, &y], TOKENS * WIDTH).unwrap()); +} diff --git a/crates/gpu/src/sam3/neck.rs b/crates/gpu/src/sam3/neck.rs new file mode 100644 index 0000000000..1d42fd341f --- /dev/null +++ b/crates/gpu/src/sam3/neck.rs @@ -0,0 +1,425 @@ +//! SAM 3's feature pyramids on the GPU: the necks of `lightcraft-segment` (`neck.rs`, the reference) for the click +//! decoder (`tracker_neck`) and the text detector (`detector_model.vision_encoder.neck`), the three finest levels of +//! each (288, 144 and 72 per side, 256 channels), from the backbone's `[1024, 72, 72]`. +//! +//! Images are kept as pixel rows (`[pixels, channels]`), so every step is a product of the backbone's matrix kernel: +//! - a 2 × 2 stride-2 transposed convolution is one product per input pixel, `[pixels, cin] · [cin, 4 · cout]` +//! (the checkpoint's `[cin, cout, 2, 2]` laid out as `[(ky, kx, cout), cin]` on upload), whose row holds the +//! pixel's four outputs one after the other; GELU (erf) between the two of level 0 runs in its epilogue; +//! - `proj1` (1 × 1) is a plain product, and does not care in which order the pixels come; +//! - `unshuffle` (`wgsl/sam3_neck.wgsl`) then puts the pixels of the transposed convolutions in row-major order; +//! - `proj2` (3 × 3, padding 1) is the same kernel with an A-tile loader that reads the 9 · cin numbers of a pixel's +//! neighbourhood straight from the image (`wgsl/sam3_conv.wgsl`): an implicit GEMM, the im2col matrix (764 MB at +//! 288²) never exists; +//! - `to_chw` (`wgsl/sam3_ops.wgsl`) writes the channels-first result. +//! +//! Nothing is uploaded with the backbone: the kernels compile, the work buffers (~190 MB, shared by both necks) are +//! made and a neck's weights (~27 MB) are uploaded when that neck is first asked for. A level is one submission +//! and one read-back, so no buffer exceeds the backbone's limits. Level 3 (36², a max pool) is not needed by either +//! head and is not run here. + +use std::sync::{Mutex, OnceLock, PoisonError}; + +use lightcraft_segment::{NeckKind, WeightReader}; + +use super::{Dev, GRID, Graph, HIDDEN, Matmul, Precision, Recorded, TILE, TIMEOUT, buffer, matmul_source_with, pipeline, u32_of, upload}; + +#[cfg(test)] +pub(super) mod tests; + +/// Channels of every level. +const FPN: usize = 256; +/// Levels run here: 288², 144² and 72². +const LEVELS: usize = 3; + +/// The sizes of a neck: the backbone's side and channels, and the channels of the levels (SAM 3's, or small ones +/// in tests). +#[derive(Clone, Copy, Debug)] +struct Sizes { + grid: usize, + hidden: usize, + fpn: usize, +} + +const SAM3: Sizes = Sizes { grid: GRID, hidden: HIDDEN, fpn: FPN }; + +impl Sizes { + /// Floats of the largest step of level 0: the second transposed convolution's output (4 · grid² · hidden), or a + /// 256-channel image of (4 · grid)² (both 85 MB for SAM 3). + fn largest(self) -> usize { + self.grid * self.grid * (4 * self.hidden).max(16 * self.fpn) + } +} + +/// Where a neck's tensors are in the checkpoint. +fn prefix(which: NeckKind) -> &'static str { + match which { + NeckKind::Tracker => "tracker_neck", + NeckKind::Detector => "detector_model.vision_encoder.neck", + } +} + +// --------------------------------------------------------------------------------------------------------------------- +// kernels + +pub(super) struct Kernels { + /// The 3 × 3 convolution: the matrix product with the implicit-im2col A loader. + conv: Matmul, + to_rows: wgpu::ComputePipeline, + unshuffle: wgpu::ComputePipeline, +} + +static KERNELS: OnceLock> = OnceLock::new(); + +/// The neck's own kernels, compiled on first use (the backbone's are compiled with the device; the mask decoder uses +/// the 3 × 3 convolution too). +pub(super) fn kernels(dev: &'static Dev) -> Result<&'static Kernels, String> { + KERNELS + .get_or_init(|| { + let validation = dev.device.push_error_scope(wgpu::ErrorFilter::Validation); + let pipe = |label: &str, source: &str, entry: &str| pipeline(&dev.device, &dev.pipeline_layout, label, source, entry); + let conv = matmul_source_with(TILE, false, Some(include_str!("../wgsl/sam3_conv.wgsl"))); + let ops = include_str!("../wgsl/sam3_neck.wgsl"); + let k = Kernels { + conv: Matmul { pipeline: pipe("sam3 conv3x3", &conv, "main"), tile: TILE }, + to_rows: pipe("sam3 neck", ops, "to_rows"), + unshuffle: pipe("sam3 neck", ops, "unshuffle"), + }; + if let Some(e) = pollster::block_on(validation.pop()) { + return Err(format!("{}: the SAM 3 neck kernels did not compile ({e})", dev.info.name)); + } + Ok(k) + }) + .as_ref() + .map_err(Clone::clone) +} + +impl Graph { + /// The 3 × 3 convolution (padding 1) of the image `x` (`[side², cin]`, cin a multiple of 4) with `w` + /// (`[cout, 3, 3, cin]`) and `bias` (`[cout]`) into `y` (`[side², cout]`). + pub(super) fn conv3( + &mut self, + k: &'static Kernels, + [x, w, bias, y]: [&wgpu::Buffer; 4], + side: usize, + (cin, cout): (usize, usize), + ) -> Result<(), String> { + if side == 0 || !cin.is_multiple_of(4) || cin == 0 || cout == 0 { + return Err(format!("a {side}² {cin} → {cout} convolution the SAM 3 kernel cannot do")); + } + let (m, depth) = (side * side, 9 * cin); + let params = [u32_of(m)?, u32_of(cout)?, u32_of(depth)?, 1, 0, 0, u32_of(side)?, 0]; + let groups = [u32_of(cout.div_ceil(k.conv.tile.bn()))?, u32_of(m.div_ceil(k.conv.tile.bm()))?, 1]; + if groups[1] > self.dev.limits.max_compute_workgroups_per_dimension { + return Err("an image too large for the SAM 3 convolution kernel".into()); + } + self.push(&k.conv.pipeline, params, [x, w, bias, y], groups); + Ok(()) + } + + /// `[channels, pixels]` (channels-first) to `[pixels, channels]`. + fn channels_last(&mut self, k: &'static Kernels, src: &wgpu::Buffer, dst: &wgpu::Buffer, channels: usize, pixels: usize) -> Result<(), String> { + let count = channels.checked_mul(pixels).ok_or("an image too large")?; + let (g, row) = self.flat(count.div_ceil(256))?; + let dummy = &self.dev.dummy; + self.push(&k.to_rows, [u32_of(channels)?, u32_of(pixels)?, 0, 0, 0, 0, u32_of(count)?, row], [src, dummy, dummy, dst], g); + Ok(()) + } + + /// The rows of a `side × side` image after `ups` 2 × 2 stride-2 transposed convolutions (in their order, see + /// `wgsl/sam3_neck.wgsl`) in row-major order. + fn unshuffle( + &mut self, + k: &'static Kernels, + src: &wgpu::Buffer, + dst: &wgpu::Buffer, + channels: usize, + side: usize, + ups: usize, + ) -> Result<(), String> { + if ups >= 16 || !side.is_multiple_of(1 << ups) { + return Err("a reorder the SAM 3 kernel cannot do".into()); + } + let count = channels.checked_mul(side * side).ok_or("an image too large")?; + let (g, row) = self.flat(count.div_ceil(256))?; + let dummy = &self.dev.dummy; + self.push(&k.unshuffle, [u32_of(channels)?, u32_of(side)?, u32_of(ups)?, 0, 0, 0, u32_of(count)?, row], [src, dummy, dummy, dst], g); + Ok(()) + } +} + +// --------------------------------------------------------------------------------------------------------------------- +// weights + +/// A transposed convolution's weights `[cin, cout, 2, 2]` as the rows of a product: `[(ky · 2 + kx) · cout + co, ci]`. +fn transposed_rows(w: &[f32], cin: usize, cout: usize) -> Vec { + let mut out = vec![0f32; w.len()]; + for ci in 0..cin { + for co in 0..cout { + for q in 0..4 { + if let (Some(o), Some(v)) = (out.get_mut((q * cout + co) * cin + ci), w.get((ci * cout + co) * 4 + q)) { + *o = *v; + } + } + } + } + out +} + +/// A convolution's weights `[cout, cin, k, k]` in the order of the convolution's A columns: `[cout, k, k, cin]`. +fn conv_rows(w: &[f32], cout: usize, cin: usize, k: usize) -> Vec { + let taps = k * k; + let mut out = vec![0f32; w.len()]; + for co in 0..cout { + for ci in 0..cin { + for t in 0..taps { + if let (Some(o), Some(v)) = (out.get_mut((co * taps + t) * cin + ci), w.get((co * cin + ci) * taps + t)) { + *o = *v; + } + } + } + } + out +} + +/// A transposed convolution's weight `[cin, cout, 2, 2]` and bias on the device: rows `[4 · cout, cin]`, and the +/// bias repeated for the four outputs. +fn transposed_weights(dev: &Dev, label: &str, w: &[f32], b: &[f32], cin: usize, cout: usize) -> [wgpu::Buffer; 2] { + [upload(dev, label, &transposed_rows(w, cin, cout)), upload(dev, label, &b.repeat(4))] +} + +/// A `k × k` convolution's weight `[cout, cin, k, k]` and bias on the device: rows `[cout, k, k, cin]`. +pub(super) fn conv_weights(dev: &Dev, label: &str, w: &[f32], b: &[f32], (cin, cout, k): (usize, usize, usize)) -> [wgpu::Buffer; 2] { + [upload(dev, label, &conv_rows(w, cout, cin, k)), upload(dev, label, b)] +} + +/// One level's weights on the device: the transposed convolutions (none, one or two), `proj1`, `proj2`. +struct LevelWeights { + up: Vec<[wgpu::Buffer; 2]>, + proj1: [wgpu::Buffer; 2], + proj2: [wgpu::Buffer; 2], +} + +/// Reads a neck's tensors, checking their shapes. +struct Loader<'a> { + weights: &'a WeightReader, + dev: &'static Dev, + prefix: &'static str, + bytes: u64, +} + +impl Loader<'_> { + fn read(&self, name: &str, shape: &[usize]) -> Result, String> { + let full = format!("{}.{name}", self.prefix); + let (got, data) = self.weights.read(&full).map_err(|e| format!("{full}: {e}"))?; + if got != shape { + return Err(format!("{full}: shape {got:?}, expected {shape:?}")); + } + Ok(data) + } + + /// A 2 × 2 stride-2 transposed convolution. + fn transposed(&mut self, name: &str, cin: usize, cout: usize) -> Result<[wgpu::Buffer; 2], String> { + let w = self.read(&format!("{name}.weight"), &[cin, cout, 2, 2])?; + let b = self.read(&format!("{name}.bias"), &[cout])?; + self.bytes += (w.len() + 4 * b.len()) as u64 * 4; + Ok(transposed_weights(self.dev, name, &w, &b, cin, cout)) + } + + /// A `k × k` convolution. + fn conv(&mut self, name: &str, cin: usize, cout: usize, k: usize) -> Result<[wgpu::Buffer; 2], String> { + let w = self.read(&format!("{name}.weight"), &[cout, cin, k, k])?; + let b = self.read(&format!("{name}.bias"), &[cout])?; + self.bytes += (w.len() + b.len()) as u64 * 4; + Ok(conv_weights(self.dev, name, &w, &b, (cin, cout, k))) + } + + /// Level `i` (0: 4× up, 1: 2× up, 2: as is). + fn level(&mut self, i: usize) -> Result { + let l = format!("fpn_layers.{i}"); + let s = format!("{l}.scale_layers"); + let (up, inter) = match i { + 0 => ( + vec![self.transposed(&format!("{s}.0"), HIDDEN, HIDDEN / 2)?, self.transposed(&format!("{s}.2"), HIDDEN / 2, HIDDEN / 4)?], + HIDDEN / 4, + ), + 1 => (vec![self.transposed(&format!("{s}.0"), HIDDEN, HIDDEN / 2)?], HIDDEN / 2), + 2 => (Vec::new(), HIDDEN), + _ => return Err(format!("level {i} of the SAM 3 neck does not run on the GPU")), + }; + Ok(LevelWeights { up, proj1: self.conv(&format!("{l}.proj1"), inter, FPN, 1)?, proj2: self.conv(&format!("{l}.proj2"), FPN, FPN, 3)? }) + } +} + +// --------------------------------------------------------------------------------------------------------------------- +// the necks + +/// The work buffers, shared by both necks (one runs at a time): the backbone as pixel rows, two buffers the steps +/// alternate between (the backbone's upload lands in the first), and the read-back. +struct Work { + x: wgpu::Buffer, + a: wgpu::Buffer, + b: wgpu::Buffer, + staging: wgpu::Buffer, +} + +impl Work { + fn new(dev: &Dev, sizes: Sizes) -> Work { + let largest = sizes.largest(); + Work { + x: buffer(dev, "sam3 neck input", sizes.hidden * sizes.grid * sizes.grid), + a: buffer(dev, "sam3 neck ping", largest), + b: buffer(dev, "sam3 neck pong", largest), + staging: dev.device.create_buffer(&wgpu::BufferDescriptor { + label: Some("sam3 neck read-back"), + size: (largest.max(4) * 4) as u64, + usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }), + } + } + + /// Bytes on the device: the read-back buffer is host memory on discrete GPUs and not counted. + fn bytes(sizes: Sizes) -> u64 { + ((sizes.hidden * sizes.grid * sizes.grid + 2 * sizes.largest()) * 4) as u64 + } +} + +/// One level, recorded: its dispatches, and the buffer its `[256, side, side]` result ends in (`len` floats). +struct Level { + recorded: Recorded, + out: wgpu::Buffer, + len: usize, +} + +/// A neck with its weights uploaded and its levels recorded. +struct Built { + levels: Vec, + weight_bytes: u64, +} + +/// The dispatches of level `i` from the pixel rows in `work.x` (level 0 first fills them from the channels-first +/// upload in `work.a`). +fn record_level(dev: &'static Dev, k: &'static Kernels, work: &Work, w: &LevelWeights, i: usize, sizes: Sizes) -> Result { + let Sizes { grid, hidden, fpn } = sizes; + let mut g = Graph::new(dev); + if i == 0 { + g.channels_last(k, &work.a, &work.x, hidden, grid * grid)?; + } + let mut spare = [&work.a, &work.b].into_iter().cycle(); + let mut next = || spare.next().ok_or_else(|| "no work buffer".to_string()); + let (mut cur, mut pixels, mut channels, mut side) = (&work.x, grid * grid, hidden, grid); + for (j, [weight, bias]) in w.up.iter().enumerate() { + let cout = channels / 2; + let dst = next()?; + // GELU between the two of level 0 + g.matmul([cur, weight, bias, dst], (pixels, 4 * cout, channels), 1, j + 1 < w.up.len(), false, Precision::F32)?; + (cur, pixels, channels, side) = (dst, pixels * 4, cout, side * 2); + } + let dst = next()?; + g.matmul([cur, &w.proj1[0], &w.proj1[1], dst], (pixels, fpn, channels), 1, false, false, Precision::F32)?; + cur = dst; + if !w.up.is_empty() { + let dst = next()?; + g.unshuffle(k, cur, dst, fpn, side, w.up.len())?; + cur = dst; + } + let dst = next()?; + g.conv3(k, [cur, &w.proj2[0], &w.proj2[1], dst], side, (fpn, fpn))?; + cur = dst; + let dst = next()?; + g.channels_first(cur, dst, fpn, side, side)?; + Ok(Level { recorded: g.record(), out: dst.clone(), len: fpn * side * side }) +} + +fn build(dev: &'static Dev, k: &'static Kernels, weights: &WeightReader, which: NeckKind, work: &Work) -> Result { + let mut ld = Loader { weights, dev, prefix: prefix(which), bytes: 0 }; + let mut levels = Vec::with_capacity(LEVELS); + for i in 0..LEVELS { + let w = ld.level(i)?; + levels.push(record_level(dev, k, work, &w, i, SAM3)?); + } + Ok(Built { levels, weight_bytes: ld.bytes }) +} + +/// Run `f` (buffer creation and uploads for `stage`), turning the device's out-of-memory and validation errors into an +/// `Err` that names the stage. +pub(super) fn scoped(dev: &Dev, stage: &str, f: impl FnOnce() -> Result) -> Result { + let oom = dev.device.push_error_scope(wgpu::ErrorFilter::OutOfMemory); + let validation = dev.device.push_error_scope(wgpu::ErrorFilter::Validation); + let made = f(); + // let the uploads land before the scopes close + let _ = dev.device.poll(wgpu::PollType::Wait { submission_index: None, timeout: Some(TIMEOUT) }); + let (validation, oom) = (pollster::block_on(validation.pop()), pollster::block_on(oom.pop())); + if let Some(e) = oom { + return Err(format!("not enough GPU memory for {stage}: {e}")); + } + if let Some(e) = validation { + return Err(format!("the GPU rejected {stage}: {e}")); + } + made +} + +#[derive(Default)] +struct State { + work: Option, + tracker: Option, + detector: Option, +} + +/// Both necks of a backbone on the GPU, each built when first run. +pub(super) struct Necks { + weights: WeightReader, + state: Mutex, +} + +impl Necks { + pub(super) fn new(weights: WeightReader) -> Necks { + Necks { weights, state: Mutex::new(State::default()) } + } + + /// The `n` finest levels of the `which` neck for `backbone` (`[1024, 72, 72]`), each `[256, s, s]`. + pub(super) fn run(&self, dev: &'static Dev, which: NeckKind, backbone: &[f32], n: usize) -> Result>, String> { + if n > LEVELS { + return Err(format!("{n} levels asked for; the GPU neck makes the {LEVELS} finest")); + } + if backbone.len() != HIDDEN * GRID * GRID { + return Err(format!("{} backbone values, expected {HIDDEN} × {GRID} × {GRID}", backbone.len())); + } + let Some(_work) = crate::exit::enter() else { return Err("LightCraft is closing".into()) }; + let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner); + let State { work, tracker, detector } = &mut *state; + let work = match work { + Some(w) => w, + None => work.insert(scoped(dev, "the SAM 3 necks", || Ok(Work::new(dev, SAM3)))?), + }; + let built = match which { + NeckKind::Tracker => tracker, + NeckKind::Detector => detector, + }; + let built = match built { + Some(b) => b, + None => { + let k = kernels(dev)?; + built.insert(scoped(dev, "a SAM 3 neck", || build(dev, k, &self.weights, which, work))?) + } + }; + dev.queue.write_buffer(&work.a, 0, bytemuck::cast_slice(backbone)); + built.levels.iter().take(n).map(|l| l.recorded.run("a SAM 3 neck", dev, &l.out, &work.staging, l.len)).collect() + } + + /// Device memory the necks built so far take (weights and work buffers). + fn bytes(&self) -> u64 { + let state = self.state.lock().unwrap_or_else(PoisonError::into_inner); + let weights: u64 = [&state.tracker, &state.detector].into_iter().flatten().map(|b| b.weight_bytes).sum(); + weights + if state.work.is_some() { Work::bytes(SAM3) } else { 0 } + } +} + +impl super::Sam3Gpu { + /// Bytes of device memory the necks run so far take (0 before the first): their weights and the work buffers + /// they share. + pub fn neck_bytes(&self) -> u64 { + self.necks.bytes() + } +} diff --git a/crates/gpu/src/sam3/neck/tests.rs b/crates/gpu/src/sam3/neck/tests.rs new file mode 100644 index 0000000000..d7b1ec668e --- /dev/null +++ b/crates/gpu/src/sam3/neck/tests.rs @@ -0,0 +1,215 @@ +//! The neck kernels against plain loops in f64 (odd sizes, every border of the 3 × 3 convolution, tiles cut off), and +//! a whole small neck against a direct transcription of `Neck::forward`. The real necks against candle: +//! `tests/it/sam3_backbone.rs`. + +use super::super::tests::{gelu, gpu, read, values, worst}; +use super::*; + +/// The neck's kernels on the test device; a kernel that doesn't compile is a failure. +fn neck_kernels(d: &'static Dev) -> &'static Kernels { + kernels(d).unwrap() +} + +/// PyTorch's `ConvTranspose2d(cin, cout, 2, stride 2)` on pixel rows `x` (`[side², cin]`), weight `[cin, cout, 2, 2]`: +/// `[(2 · side)², cout]`, row-major. +fn conv_transpose_ref(x: &[f64], side: usize, (cin, cout): (usize, usize), w: &[f32], b: &[f32]) -> Vec { + let out_side = 2 * side; + let mut y = vec![0f64; out_side * out_side * cout]; + for i in 0..side { + for j in 0..side { + for ky in 0..2 { + for kx in 0..2 { + for co in 0..cout { + let mut v = b[co] as f64; + for ci in 0..cin { + v += x[(i * side + j) * cin + ci] * w[((ci * cout + co) * 2 + ky) * 2 + kx] as f64; + } + y[((2 * i + ky) * out_side + 2 * j + kx) * cout + co] = v; + } + } + } + } + } + y +} + +/// PyTorch's `Conv2d(cin, cout, k, padding k / 2)` on pixel rows `x` (`[side², cin]`), weight `[cout, cin, k, k]`: +/// `[side², cout]`. +pub(in crate::sam3) fn conv_ref(x: &[f64], side: usize, (cin, cout, k): (usize, usize, usize), w: &[f32], b: &[f32]) -> Vec { + let pad = (k / 2) as isize; + let mut y = vec![0f64; side * side * cout]; + for r in 0..side { + for c in 0..side { + for co in 0..cout { + let mut v = b[co] as f64; + for ky in 0..k { + for kx in 0..k { + let (rr, cc) = (r as isize + ky as isize - pad, c as isize + kx as isize - pad); + if rr < 0 || cc < 0 || rr >= side as isize || cc >= side as isize { + continue; + } + let at = (rr as usize * side + cc as usize) * cin; + for ci in 0..cin { + v += x[at + ci] * w[((co * cin + ci) * k + ky) * k + kx] as f64; + } + } + } + y[(r * side + c) * cout + co] = v; + } + } + } + y +} + +pub(in crate::sam3) fn f32s(v: &[f64]) -> Vec { + v.iter().map(|x| *x as f32).collect() +} + +pub(in crate::sam3) fn f64s(v: &[f32]) -> Vec { + v.iter().map(|x| *x as f64).collect() +} + +#[test] +fn weights_are_laid_out_as_the_products_read_them() { + // ConvTranspose2d [cin 2, cout 3, 2, 2]: value = 1000 ci + 100 co + 10 ky + kx; rows [(ky, kx, co), ci] + let w: Vec = + (0..2).flat_map(|ci| (0..3).flat_map(move |co| (0..4).map(move |q| (1000 * ci + 100 * co + 10 * (q / 2) + q % 2) as f32))).collect(); + let rows = transposed_rows(&w, 2, 3); + assert_eq!(rows[(3 * 3 + 2) * 2 + 1], 1211.0); + assert_eq!(rows[3 * 2], 1.0); + // Conv2d [cout 2, cin 3, 3, 3]: value = 1000 co + 100 ci + 10 ky + kx; rows [cout, ky, kx, cin] + let w: Vec = + (0..2).flat_map(|co| (0..3).flat_map(move |ci| (0..9).map(move |t| (1000 * co + 100 * ci + 10 * (t / 3) + t % 3) as f32))).collect(); + let rows = conv_rows(&w, 2, 3, 3); + assert_eq!(rows[(9 + 2 * 3 + 1) * 3 + 2], 1221.0); + assert_eq!(rows[4 * 3], 11.0); +} + +#[test] +fn transposed_convolutions_and_the_reorder_give_the_definition() { + let Some(d) = gpu() else { return }; + let k = neck_kernels(d); + // one up-sampling (odd side, cut-off tiles), and two with GELU between as in level 0 + for (case, (side, chans)) in [(5usize, vec![8usize, 6]), (3, vec![12, 8, 4]), (9, vec![4, 68])].into_iter().enumerate() { + let x = values(side * side * chans[0], 10 + case as u64, 1.0); + let mut want = f64s(&x); + let mut s = side; + let mut g = Graph::new(d); + let mut cur = upload(d, "x", &x); + for (j, pair) in chans.windows(2).enumerate() { + let (cin, cout) = (pair[0], pair[1]); + let w = values(cin * cout * 4, 20 + j as u64, 0.3); + let b = values(cout, 30 + j as u64, 0.5); + let gelu_after = j + 2 < chans.len(); + want = conv_transpose_ref(&want, s, (cin, cout), &w, &b); + if gelu_after { + want.iter_mut().for_each(|v| *v = gelu(*v)); + } + let [bw, bb] = transposed_weights(d, "w", &w, &b, cin, cout); + let y = buffer(d, "y", s * s * 4 * cout); + g.matmul([&cur, &bw, &bb, &y], (s * s, 4 * cout, cin), 1, gelu_after, false, Precision::F32).unwrap(); + cur = y; + s *= 2; + } + let cout = *chans.last().unwrap(); + let out = buffer(d, "out", s * s * cout); + g.unshuffle(k, &cur, &out, cout, s, chans.len() - 1).unwrap(); + let got = read(d, g, &out, s * s * cout); + let err = worst(&got, &f32s(&want)); + assert!(err < 1e-4, "case {case}: off by {err}"); + } +} + +#[test] +fn the_3x3_convolution_gives_the_definition_at_every_border() { + let Some(d) = gpu() else { return }; + let k = neck_kernels(d); + // odd sides, a single pixel (all border), N not a multiple of the tile, more pixels than one tile + for (case, (side, cin, cout)) in [(7usize, 12usize, 5usize), (1, 8, 3), (9, 4, 70), (17, 16, 64), (2, 256, 9)].into_iter().enumerate() { + let x = values(side * side * cin, 40 + case as u64, 1.0); + let w = values(cout * cin * 9, 50 + case as u64, 0.2); + let b = values(cout, 60 + case as u64, 0.5); + let [bw, bb] = conv_weights(d, "w", &w, &b, (cin, cout, 3)); + let (bx, by) = (upload(d, "x", &x), buffer(d, "y", side * side * cout)); + let mut g = Graph::new(d); + g.conv3(k, [&bx, &bw, &bb, &by], side, (cin, cout)).unwrap(); + let got = read(d, g, &by, side * side * cout); + let want = f32s(&conv_ref(&f64s(&x), side, (cin, cout, 3), &w, &b)); + let err = worst(&got, &want); + assert!(err < 2e-5 * ((9 * cin) as f32).sqrt(), "case {case} ({side}² {cin} → {cout}): off by {err}"); + } +} + +#[test] +fn the_neck_kernels_refuse_what_they_cannot_do() { + let Some(d) = gpu() else { return }; + let k = neck_kernels(d); + let b = buffer(d, "b", 16); + let mut g = Graph::new(d); + assert!(g.conv3(k, [&b, &b, &b, &b], 4, (6, 8)).is_err(), "channels not a multiple of 4"); + assert!(g.conv3(k, [&b, &b, &b, &b], 0, (8, 8)).is_err(), "an empty image"); + assert!(g.unshuffle(k, &b, &b, 4, 6, 2).is_err(), "a side that is not a multiple of 2^ups"); +} + +/// A neck level's weights in the checkpoint's layouts: the transposed convolutions (weight, bias, cin, cout), +/// `proj1` (weight, bias, cin) and `proj2`. +struct RefLevel { + up: Vec<(Vec, Vec, usize, usize)>, + proj1: (Vec, Vec, usize), + proj2: (Vec, Vec), +} + +/// `Neck::forward` for one level on the channels-first backbone `x`, in f64: `[fpn, side, side]`. +fn level_ref(x: &[f32], sizes: Sizes, l: &RefLevel) -> Vec { + let Sizes { grid, hidden, fpn } = sizes; + let mut rows: Vec = (0..grid * grid).flat_map(|p| (0..hidden).map(move |c| x[c * grid * grid + p] as f64)).collect(); + let mut side = grid; + for (j, (w, b, cin, cout)) in l.up.iter().enumerate() { + rows = conv_transpose_ref(&rows, side, (*cin, *cout), w, b); + if j + 1 < l.up.len() { + rows.iter_mut().for_each(|v| *v = gelu(*v)); + } + side *= 2; + } + let (w1, b1, inter) = &l.proj1; + let rows = conv_ref(&rows, side, (*inter, fpn, 1), w1, b1); + let rows = conv_ref(&rows, side, (fpn, fpn, 3), &l.proj2.0, &l.proj2.1); + (0..fpn).flat_map(|c| (0..side * side).map(move |p| (c, p))).map(|(c, p)| rows[p * fpn + c] as f32).collect() +} + +#[test] +fn a_small_neck_gives_what_the_reference_neck_gives() { + let Some(d) = gpu() else { return }; + let k = neck_kernels(d); + let sizes = Sizes { grid: 6, hidden: 32, fpn: 8 }; + let Sizes { grid, hidden, fpn } = sizes; + let x = values(hidden * grid * grid, 70, 1.0); + let work = Work::new(d, sizes); + d.queue.write_buffer(&work.a, 0, bytemuck::cast_slice(&x)); + let mut seed = 80; + let mut next = |n: usize, scale: f32| { + seed += 1; + values(n, seed, scale) + }; + // in order: level 0 turns the upload into the pixel rows the others read + for i in 0..LEVELS { + let chans: Vec = match i { + 0 => vec![hidden, hidden / 2, hidden / 4], + 1 => vec![hidden, hidden / 2], + _ => vec![hidden], + }; + let up: Vec<_> = chans.windows(2).map(|p| (next(p[0] * p[1] * 4, 0.3), next(p[1], 0.3), p[0], p[1])).collect(); + let inter = *chans.last().unwrap(); + let r = RefLevel { up, proj1: (next(fpn * inter, 0.3), next(fpn, 0.3), inter), proj2: (next(fpn * fpn * 9, 0.2), next(fpn, 0.3)) }; + let w = LevelWeights { + up: r.up.iter().map(|(w, b, cin, cout)| transposed_weights(d, "up", w, b, *cin, *cout)).collect(), + proj1: conv_weights(d, "proj1", &r.proj1.0, &r.proj1.1, (inter, fpn, 1)), + proj2: conv_weights(d, "proj2", &r.proj2.0, &r.proj2.1, (fpn, fpn, 3)), + }; + let level = record_level(d, k, &work, &w, i, sizes).unwrap(); + let got = level.recorded.run("a test", d, &level.out, &work.staging, level.len).unwrap(); + let want = level_ref(&x, sizes, &r); + let err = worst(&got, &want); + assert!(err < 1e-4, "level {i}: off by {err}"); + } +} diff --git a/crates/gpu/src/sam3/pixel.rs b/crates/gpu/src/sam3/pixel.rs new file mode 100644 index 0000000000..08d5f5b749 --- /dev/null +++ b/crates/gpu/src/sam3/pixel.rs @@ -0,0 +1,377 @@ +//! The mask decoder of SAM 3's text detector on the GPU (`lightcraft-segment`'s `detector.rs` is the reference): the +//! DETR encoder's memory (72 × 72 tokens of 256) attends to the prompt and is added to it (`prompt_cross_attn`, after +//! its layer norm), then the pixel decoder brings it up to 288 × 288 in two stages, each a nearest 2 × up-sampling plus +//! the detector neck's level of that size (144², then 288²) → 3 × 3 convolution → GroupNorm (8 groups, eps 1e-5) → +//! ReLU; last, every row of a `[r, 256]` matrix (with its bias) is a 1 × 1 projection of the decoder's output, an image +//! `[r, 288, 288]`. The detector passes its 200 mask embeddings with the instance projection folded in, so these are the +//! per-query mask logits. ~0.9–1.4 s per prompt on the CPU through candle, most of it the 288² convolution. +//! +//! Images are pixel rows (`[pixels, channels]`), as in the necks (`sam3/neck.rs`): the convolutions are the necks' +//! implicit GEMM, the projection the backbone's matrix product (`[pixels, 256] · [r, 256]ᵀ`, then `to_chw`), the +//! prompt attention the DETR encoder's kernels (`sam3/detr.rs`). `wgsl/sam3_pixel.wgsl` adds the up-sampling, which +//! adds the channels-first neck level as uploaded, and GroupNorm + ReLU: two-pass statistics per chunk of 256 pixels, +//! merged per group (the parallel variance formula), then applied in place. +//! +//! Loaded on the first prompt, like the encoder: kernels, 6 MB of weights, ~280 MB of work buffers. A prompt uploads +//! the memory, the prompt's tokens and padding bias, both neck levels (106 MB; they stay on the CPU with the image's +//! features, see `docs/gpu-pipeline.md`) and the rows, submits once and reads `r · 288²` numbers back. The dispatches +//! are recorded once per row count. + +use std::sync::{Mutex, OnceLock, PoisonError}; + +use lightcraft_segment::WeightReader; + +use super::detr::{self, Operand}; +use super::neck::{self, conv_weights, scoped}; +use super::{Dev, Graph, Precision, Recorded, buffer, pipeline, u32_of, upload}; + +#[cfg(test)] +mod tests; + +/// Where the decoder's weights are in the checkpoint. +const PREFIX: &str = "detector_model.mask_decoder"; +/// The memory's side (72 × 72 tokens), the width of everything, the prompt's tokens. +const GRID: usize = 72; +const WIDTH: usize = 256; +const TEXT: usize = 32; +const HEAD_DIM: usize = 32; +/// The decoder's stages (each doubles the side): 144², 288². +const STAGES: usize = 2; +/// The output's side. +const SIDE: usize = GRID << STAGES; +/// GroupNorm's groups and eps (`candle_nn::group_norm(8, 256, 1e-5)`), and PyTorch's layer norm eps. +const GROUPS: usize = 8; +const EPS: f32 = 1e-5; +/// Pixels per workgroup of the GroupNorm statistics. +const CHUNK: usize = 256; + +struct Kernels { + upsample_add: wgpu::ComputePipeline, + group_stats: wgpu::ComputePipeline, + group_merge: wgpu::ComputePipeline, + group_norm_relu: wgpu::ComputePipeline, +} + +static KERNELS: OnceLock> = OnceLock::new(); + +/// The decoder's own kernels, compiled on first use. +fn kernels(dev: &'static Dev) -> Result<&'static Kernels, String> { + KERNELS + .get_or_init(|| { + let validation = dev.device.push_error_scope(wgpu::ErrorFilter::Validation); + let source = include_str!("../wgsl/sam3_pixel.wgsl"); + let pipe = |entry: &str| pipeline(&dev.device, &dev.pipeline_layout, "sam3 pixel", source, entry); + let k = Kernels { + upsample_add: pipe("upsample_add"), + group_stats: pipe("group_stats"), + group_merge: pipe("group_merge"), + group_norm_relu: pipe("group_norm_relu"), + }; + match pollster::block_on(validation.pop()) { + Some(e) => Err(format!("{}: the SAM 3 mask decoder kernels did not compile ({e})", dev.info.name)), + None => Ok(k), + } + }) + .as_ref() + .map_err(Clone::clone) +} + +/// Floats of the GroupNorm statistics of chunks for an image of `pixels`, `groups` groups. +fn partials_len(pixels: usize, groups: usize) -> usize { + pixels.div_ceil(CHUNK) * groups * 2 +} + +impl Graph { + /// Nearest up-sampling of the rows `src` (`[from², channels]`) to `to × to`, plus the channels-first image `skip` + /// (`[channels, to, to]`), into the rows `dst` (`[to², channels]`). + fn upsample_add( + &mut self, + k: &'static Kernels, + [src, skip, dst]: [&wgpu::Buffer; 3], + channels: usize, + (from, to): (usize, usize), + ) -> Result<(), String> { + if from == 0 || to < from || channels == 0 { + return Err("an up-sampling the SAM 3 kernel cannot do".into()); + } + let count = channels.checked_mul(to * to).ok_or("an image too large")?; + let (g, row) = self.flat(count.div_ceil(256))?; + let params = [u32_of(channels)?, u32_of(to)?, u32_of(from)?, 0, 0, 0, u32_of(count)?, row]; + self.push(&k.upsample_add, params, [src, skip, &self.dev.dummy, dst], g); + Ok(()) + } + + /// GroupNorm (`groups` groups of channels, eps) and ReLU in place on the rows `x` (`[pixels, channels]`, channels + /// ≤ 256), with the per-channel `gamma` and `beta`; `partials` (at least [`partials_len`] floats) and `stats` + /// (2 · groups) hold the statistics on the way. + #[allow(clippy::too_many_arguments)] + fn group_norm_relu( + &mut self, + k: &'static Kernels, + [x, gamma, beta]: [&wgpu::Buffer; 3], + [partials, stats]: [&wgpu::Buffer; 2], + (pixels, channels, groups): (usize, usize, usize), + eps: f32, + ) -> Result<(), String> { + if pixels == 0 || channels == 0 || channels > 256 || groups == 0 || !channels.is_multiple_of(groups) { + return Err("a GroupNorm the SAM 3 kernel cannot do".into()); + } + let dummy = &self.dev.dummy; + let chunks = pixels.div_ceil(CHUNK); + let (g, row) = self.flat(chunks)?; + let params = [u32_of(channels)?, u32_of(pixels)?, u32_of(CHUNK)?, u32_of(groups)?, 0, 0, 0, row]; + self.push(&k.group_stats, params, [x, dummy, dummy, partials], g); + let params = [u32_of(chunks)?, u32_of(pixels)?, u32_of(CHUNK)?, u32_of(groups)?, eps.to_bits(), u32_of(channels / groups)?, 0, 0]; + self.push(&k.group_merge, params, [partials, dummy, dummy, stats], [u32_of(groups)?, 1, 1]); + let count = pixels.checked_mul(channels).ok_or("an image too large")?; + let (g, row) = self.flat(count.div_ceil(256))?; + self.push(&k.group_norm_relu, [u32_of(channels)?, 0, 0, u32_of(groups)?, 0, 0, u32_of(count)?, row], [stats, gamma, beta, x], g); + Ok(()) + } +} + +/// The decoder's weights on the device: (weight, bias) pairs, the prompt attention's k | v concatenated, the +/// convolutions as rows `[cout, 3, 3, cin]`. +struct Weights { + ln: [wgpu::Buffer; 2], + q: [wgpu::Buffer; 2], + kv: [wgpu::Buffer; 2], + o: [wgpu::Buffer; 2], + convs: Vec<[wgpu::Buffer; 2]>, + norms: Vec<[wgpu::Buffer; 2]>, +} + +/// Reads the decoder's tensors, checking their shapes. +struct Loader<'a> { + weights: &'a WeightReader, + bytes: u64, +} + +impl Loader<'_> { + /// The tensors `names` (each of `shape`) concatenated along the first axis. + fn read(&mut self, names: &[String], shape: &[usize]) -> Result, String> { + let mut all = Vec::with_capacity(names.len() * shape.iter().product::()); + for name in names { + let full = format!("{PREFIX}.{name}"); + let (got, data) = self.weights.read(&full).map_err(|e| format!("{full}: {e}"))?; + if got != shape { + return Err(format!("{full}: shape {got:?}, expected {shape:?}")); + } + all.extend(data); + } + self.bytes += all.len() as u64 * 4; + Ok(all) + } + + /// A pair of `{name}.weight` (`[n, k]`, several concatenated along n) and `{name}.bias` (or a norm's scale and shift + /// with `k` 0), uploaded. + fn pair(&mut self, dev: &Dev, names: &[String], n: usize, k: usize) -> Result<[wgpu::Buffer; 2], String> { + let w: Vec = names.iter().map(|n| format!("{n}.weight")).collect(); + let b: Vec = names.iter().map(|n| format!("{n}.bias")).collect(); + let shape: &[usize] = if k == 0 { &[n] } else { &[n, k] }; + let label = names.first().map_or("weight", String::as_str); + Ok([upload(dev, label, &self.read(&w, shape)?), upload(dev, label, &self.read(&b, &[n])?)]) + } + + fn load(&mut self, dev: &Dev) -> Result { + let a = "prompt_cross_attn"; + let proj = |ps: &[&str]| -> Vec { ps.iter().map(|p| format!("{a}.{p}_proj")).collect() }; + let mut convs = Vec::with_capacity(STAGES); + let mut norms = Vec::with_capacity(STAGES); + for i in 0..STAGES { + let name = format!("pixel_decoder.conv_layers.{i}"); + let w = self.read(&[format!("{name}.weight")], &[WIDTH, WIDTH, 3, 3])?; + let b = self.read(&[format!("{name}.bias")], &[WIDTH])?; + convs.push(conv_weights(dev, &name, &w, &b, (WIDTH, WIDTH, 3))); + norms.push(self.pair(dev, &[format!("pixel_decoder.norms.{i}")], WIDTH, 0)?); + } + Ok(Weights { + ln: self.pair(dev, &["prompt_cross_attn_norm".to_string()], WIDTH, 0)?, + q: self.pair(dev, &proj(&["q"]), WIDTH, WIDTH)?, + kv: self.pair(dev, &proj(&["k", "v"]), WIDTH, WIDTH)?, + o: self.pair(dev, &proj(&["o"]), WIDTH, WIDTH)?, + convs, + norms, + }) + } +} + +/// The buffers a prompt writes and reads, and its dispatches (recorded for one row count). +struct Work { + /// The memory in, then the memory after the prompt attention. + x: wgpu::Buffer, + text: wgpu::Buffer, + /// The prompt attention's k | v of the prompt (`[32, 512]`), then its padding bias (32 floats). + text_kv: wgpu::Buffer, + /// The neck's levels as uploaded (`[256, 144, 144]`, `[256, 288, 288]`); the projection's channels-first result + /// ends in the second. + skip1: wgpu::Buffer, + skip0: wgpu::Buffer, + /// Two 288² images the steps alternate between (the prompt attention's smaller ones too). + a: wgpu::Buffer, + b: wgpu::Buffer, + rows: wgpu::Buffer, + row_bias: wgpu::Buffer, + partials: wgpu::Buffer, + stats: wgpu::Buffer, + staging: wgpu::Buffer, + recorded: Option<(usize, Recorded)>, +} + +impl Work { + fn new(dev: &Dev) -> Work { + let image = |label: &str| buffer(dev, label, SIDE * SIDE * WIDTH); + Work { + x: buffer(dev, "mask memory", GRID * GRID * WIDTH), + text: buffer(dev, "mask prompt", TEXT * WIDTH), + text_kv: buffer(dev, "mask prompt k|v", TEXT * 2 * WIDTH + TEXT), + skip1: buffer(dev, "mask level 1", WIDTH * (SIDE / 2) * (SIDE / 2)), + skip0: image("mask level 0"), + a: image("mask ping"), + b: image("mask pong"), + rows: buffer(dev, "mask rows", WIDTH * WIDTH), + row_bias: buffer(dev, "mask row bias", WIDTH), + partials: buffer(dev, "mask norm partials", partials_len(SIDE * SIDE, GROUPS)), + stats: buffer(dev, "mask norm stats", 2 * GROUPS), + staging: dev.device.create_buffer(&wgpu::BufferDescriptor { + label: Some("mask read-back"), + size: (SIDE * SIDE * WIDTH * 4) as u64, + usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }), + recorded: None, + } + } + + /// Bytes on the device: the read-back buffer is host memory on discrete GPUs and not counted. + fn bytes() -> u64 { + let floats = GRID * GRID * WIDTH + + TEXT * (3 * WIDTH + 1) + + WIDTH * (SIDE / 2) * (SIDE / 2) + + 3 * SIDE * SIDE * WIDTH + + WIDTH * (WIDTH + 1) + + partials_len(SIDE * SIDE, GROUPS) + + 2 * GROUPS; + (floats * 4) as u64 + } +} + +/// The dispatches of a prompt with `r` rows: everything after the uploads, the result in `work.skip0`. +fn record(dev: &'static Dev, w: &Weights, work: &Work, r: usize) -> Result { + let (kd, kn, k) = (detr::kernels(dev)?, neck::kernels(dev)?, kernels(dev)?); + let mut g = Graph::new(dev); + let tokens = GRID * GRID; + // the memory attends to the prompt (padding masked): x += o(attention(q(ln(x)), k | v(text))) + g.layernorm_torch([&work.x, &w.ln[0], &w.ln[1], &work.a], tokens, WIDTH)?; + g.matmul([&work.a, &w.q[0], &w.q[1], &work.b], (tokens, WIDTH, WIDTH), 1, false, false, Precision::F32)?; + g.matmul([&work.text, &w.kv[0], &w.kv[1], &work.text_kv], (TEXT, 2 * WIDTH, WIDTH), 1, false, false, Precision::F32)?; + let q = Operand { buffer: &work.b, stride: WIDTH, offset: 0 }; + let (tk, tv) = + (Operand { buffer: &work.text_kv, stride: 2 * WIDTH, offset: 0 }, Operand { buffer: &work.text_kv, stride: 2 * WIDTH, offset: WIDTH }); + g.attention_detr(kd, [q, tk, tv], Some(TEXT * 2 * WIDTH), &work.a, (tokens, TEXT, WIDTH / HEAD_DIM))?; + g.matmul([&work.a, &w.o[0], &w.o[1], &work.x], (tokens, WIDTH, WIDTH), 1, false, true, Precision::F32)?; + // the pixel decoder: up-sample + the neck's level → 3 × 3 convolution → GroupNorm → ReLU, at 144² and at 288² + let mut cur = &work.x; + let mut side = GRID; + for (i, skip) in [&work.skip1, &work.skip0].into_iter().enumerate() { + let (Some(conv), Some(norm)) = (w.convs.get(i), w.norms.get(i)) else { return Err("a pixel decoder stage without weights".into()) }; + g.upsample_add(k, [cur, skip, &work.a], WIDTH, (side, 2 * side))?; + side *= 2; + g.conv3(kn, [&work.a, &conv[0], &conv[1], &work.b], side, (WIDTH, WIDTH))?; + g.group_norm_relu(k, [&work.b, &norm[0], &norm[1]], [&work.partials, &work.stats], (side * side, WIDTH, GROUPS), EPS)?; + cur = &work.b; + } + // each row a 1 × 1 projection of the decoder's output: [pixels, r], then channels-first into the spent level 0 + g.matmul([&work.b, &work.rows, &work.row_bias, &work.a], (side * side, r, WIDTH), 1, false, false, Precision::F32)?; + g.channels_first(&work.a, &work.skip0, r, side, side)?; + Ok(g.record()) +} + +/// The decoder with its weights on the device. +struct Built { + weights: Weights, + /// One prompt at a time (they share the work buffers). + work: Mutex, + weight_bytes: u64, +} + +fn build(dev: &'static Dev, weights: &WeightReader) -> Result { + // every kernel compiles before anything is uploaded + detr::kernels(dev)?; + neck::kernels(dev)?; + kernels(dev)?; + scoped(dev, "the SAM 3 mask decoder", || { + let mut ld = Loader { weights, bytes: 0 }; + let w = ld.load(dev)?; + Ok(Built { weights: w, work: Mutex::new(Work::new(dev)), weight_bytes: ld.bytes }) + }) +} + +/// The mask decoder, built on first use from the checkpoint the backbone came from. +pub(super) struct MaskDecoder { + weights: WeightReader, + built: OnceLock>, +} + +impl MaskDecoder { + pub(super) fn new(weights: WeightReader) -> Self { + Self { weights, built: OnceLock::new() } + } + + /// Bytes of device memory the weights and the work buffers take, once built. + pub(super) fn bytes(&self) -> Option<(u64, u64)> { + self.built.get().and_then(|b| b.as_ref().ok()).map(|b| (b.weight_bytes, Work::bytes())) + } + + /// `[r, 288, 288]` for the encoder memory `[5184, 256]`, the prompt's tokens `[32, 256]` (`valid`: its real ones), + /// the detector neck's levels `[256, 144, 144]` and `[256, 288, 288]` (channels-first) and the rows `[r, 256]` + /// with their bias `[r]` (1 ≤ r ≤ 256). + #[allow(clippy::too_many_arguments)] + pub(super) fn run( + &self, + dev: &'static Dev, + memory: &[f32], + text: &[f32], + valid: &[bool], + [level1, level0]: [&[f32]; 2], + rows: &[f32], + row_bias: &[f32], + ) -> Result, String> { + let r = row_bias.len(); + let (l1, l0) = (WIDTH * (SIDE / 2) * (SIDE / 2), WIDTH * SIDE * SIDE); + if memory.len() != GRID * GRID * WIDTH || text.len() != TEXT * WIDTH || valid.len() != TEXT || level1.len() != l1 || level0.len() != l0 { + return Err(format!( + "{} memory, {} prompt values, {} prompt tokens and levels of {} and {} values, expected {GRID}² × {WIDTH}, {TEXT} × {WIDTH}, {TEXT}, {l1} and {l0}", + memory.len(), + text.len(), + valid.len(), + level1.len(), + level0.len() + )); + } + if r == 0 || r > WIDTH || rows.len() != r * WIDTH { + return Err(format!("{} row values and {r} biases, expected r × {WIDTH} and r (1 ≤ r ≤ {WIDTH})", rows.len())); + } + let b = self.built.get_or_init(|| build(dev, &self.weights)).as_ref().map_err(Clone::clone)?; + let bias: Vec = valid.iter().map(|&ok| if ok { 0.0 } else { f32::MIN }).collect(); + let mut work = b.work.lock().unwrap_or_else(PoisonError::into_inner); + if work.recorded.as_ref().is_none_or(|(n, _)| *n != r) { + let recorded = scoped(dev, "the SAM 3 mask decoder", || record(dev, &b.weights, &work, r))?; + work.recorded = Some((r, recorded)); + } + let q = &dev.queue; + q.write_buffer(&work.x, 0, bytemuck::cast_slice(memory)); + q.write_buffer(&work.text, 0, bytemuck::cast_slice(text)); + q.write_buffer(&work.text_kv, (TEXT * 2 * WIDTH * 4) as u64, bytemuck::cast_slice(&bias)); + q.write_buffer(&work.skip1, 0, bytemuck::cast_slice(level1)); + q.write_buffer(&work.skip0, 0, bytemuck::cast_slice(level0)); + q.write_buffer(&work.rows, 0, bytemuck::cast_slice(rows)); + q.write_buffer(&work.row_bias, 0, bytemuck::cast_slice(row_bias)); + let Some((_, recorded)) = &work.recorded else { return Err("the mask decoder was not recorded".into()) }; + let out = recorded.run("the SAM 3 mask decoder", dev, &work.skip0, &work.staging, r * SIDE * SIDE)?; + if !out.iter().fold(true, |ok, v| ok & v.is_finite()) { + return Err("the GPU mask decoder produced non-finite values".into()); + } + Ok(out) + } +} diff --git a/crates/gpu/src/sam3/pixel/tests.rs b/crates/gpu/src/sam3/pixel/tests.rs new file mode 100644 index 0000000000..ece1185c0e --- /dev/null +++ b/crates/gpu/src/sam3/pixel/tests.rs @@ -0,0 +1,165 @@ +//! The mask decoder's kernels against plain loops in f64: the up-sampling with the channels-first level added (odd +//! sides, cut-off workgroups), GroupNorm + ReLU (chunks cut off, a large mean, group sizes), and one whole pixel +//! decoder stage (up-sampling → 3 × 3 convolution at every border → GroupNorm → ReLU) on small images. The real +//! decoder against candle: `tests/it/sam3_mask_decoder.rs`. + +use super::super::neck::tests::{conv_ref, f32s, f64s}; +use super::super::tests::{gpu, read, values, worst}; +use super::*; + +fn pixel_kernels(d: &'static Dev) -> &'static Kernels { + kernels(d).unwrap() +} + +/// Nearest up-sampling of the rows `x` (`[from², c]`) to `to²`, plus the channels-first `skip` (`[c, to, to]`). +fn upsample_add_ref(x: &[f64], skip: &[f32], c: usize, (from, to): (usize, usize)) -> Vec { + let mut y = vec![0f64; to * to * c]; + for r in 0..to { + for col in 0..to { + // candle's upsample_nearest2d: floor(i · from / to) + let (sr, sc) = ((r as f64 * from as f64 / to as f64) as usize, (col as f64 * from as f64 / to as f64) as usize); + for ch in 0..c { + y[(r * to + col) * c + ch] = x[(sr * from + sc) * c + ch] + skip[ch * to * to + r * to + col] as f64; + } + } + } + y +} + +/// GroupNorm (centred two-pass variance, as candle's) and ReLU on the rows `x` (`[pixels, c]`). +fn group_norm_relu_ref(x: &[f64], c: usize, groups: usize, gamma: &[f32], beta: &[f32], eps: f64) -> Vec { + let pixels = x.len() / c; + let per = c / groups; + let mut y = x.to_vec(); + for g in 0..groups { + let at = |p: usize, i: usize| x[p * c + g * per + i]; + let n = (pixels * per) as f64; + let mean = (0..pixels).flat_map(|p| (0..per).map(move |i| (p, i))).map(|(p, i)| at(p, i)).sum::() / n; + let var = (0..pixels).flat_map(|p| (0..per).map(move |i| (p, i))).map(|(p, i)| (at(p, i) - mean).powi(2)).sum::() / n; + for p in 0..pixels { + for i in 0..per { + let ch = g * per + i; + let v = (x[p * c + ch] - mean) / (var + eps).sqrt() * gamma[ch] as f64 + beta[ch] as f64; + y[p * c + ch] = v.max(0.0); + } + } + } + y +} + +#[test] +fn up_sampling_adds_the_channels_first_level() { + let Some(d) = gpu() else { return }; + let k = pixel_kernels(d); + // the decoder's doublings, an odd one, and channels that leave the last workgroup part empty + for (case, (from, to, c)) in [(3usize, 6usize, 4usize), (5, 10, 12), (4, 7, 3), (1, 2, 256)].into_iter().enumerate() { + let x = values(from * from * c, 100 + case as u64, 1.0); + let skip = values(c * to * to, 110 + case as u64, 1.0); + let (bx, bs, by) = (upload(d, "x", &x), upload(d, "skip", &skip), buffer(d, "y", to * to * c)); + let mut g = Graph::new(d); + g.upsample_add(k, [&bx, &bs, &by], c, (from, to)).unwrap(); + let got = read(d, g, &by, to * to * c); + let err = worst(&got, &f32s(&upsample_add_ref(&f64s(&x), &skip, c, (from, to)))); + assert!(err < 1e-6, "case {case}: off by {err}"); + } +} + +#[test] +fn group_norm_and_relu_give_the_definition() { + let Some(d) = gpu() else { return }; + let k = pixel_kernels(d); + // one chunk cut short; several with the last cut short; the decoder's 256 channels in 8 groups over chunks of + // 256 pixels, around a mean far from 0 (where E[x²] − E[x]² in f32 would lose the variance) + for (case, (pixels, c, groups, offset)) in + [(37usize, 16usize, 4usize, 0f32), (700, 24, 3, 0.0), (1100, 256, 8, 0.0), (600, 256, 8, 50.0), (5, 8, 1, 0.0)].into_iter().enumerate() + { + let x: Vec = values(pixels * c, 120 + case as u64, 2.0).iter().map(|v| v + offset).collect(); + let gamma = values(c, 130 + case as u64, 1.5); + let beta = values(c, 140 + case as u64, 0.5); + // normed in place, then read back: a buffer that can be copied from + let bx = buffer(d, "x", pixels * c); + d.queue.write_buffer(&bx, 0, bytemuck::cast_slice(&x)); + let (bg, bb) = (upload(d, "gamma", &gamma), upload(d, "beta", &beta)); + let (partials, stats) = (buffer(d, "partials", partials_len(pixels, groups)), buffer(d, "stats", 2 * groups)); + let mut g = Graph::new(d); + g.group_norm_relu(k, [&bx, &bg, &bb], [&partials, &stats], (pixels, c, groups), EPS).unwrap(); + let got = read(d, g, &bx, pixels * c); + let want = f32s(&group_norm_relu_ref(&f64s(&x), c, groups, &gamma, &beta, f64::from(EPS))); + let err = worst(&got, &want); + assert!(err < 2e-5, "case {case} ({pixels} pixels, {c} channels, {groups} groups): off by {err}"); + assert!(got.iter().all(|v| *v >= 0.0), "case {case}: ReLU"); + } +} + +#[test] +fn a_small_pixel_decoder_stage_gives_the_definition() { + let Some(d) = gpu() else { return }; + let (k, kn) = (pixel_kernels(d), neck::kernels(d).unwrap()); + // two stages as in the decoder (3² → 6² → 12²), 16 channels in 4 groups + let (c, groups) = (16usize, 4usize); + let x = values(3 * 3 * c, 150, 1.0); + let mut want = f64s(&x); + let mut cur = upload(d, "x", &x); + let mut g = Graph::new(d); + let mut side = 3; + for stage in 0..2u64 { + let skip = values(c * 4 * side * side, 160 + stage, 1.0); + let (w, b) = (values(c * c * 9, 170 + stage, 0.3), values(c, 180 + stage, 0.3)); + let (gamma, beta) = (values(c, 190 + stage, 1.0), values(c, 200 + stage, 0.3)); + want = upsample_add_ref(&want, &skip, c, (side, 2 * side)); + side *= 2; + want = conv_ref(&want, side, (c, c, 3), &w, &b); + want = group_norm_relu_ref(&want, c, groups, &gamma, &beta, f64::from(EPS)); + + let up = buffer(d, "up", side * side * c); + let out = buffer(d, "out", side * side * c); + let [bw, bb] = conv_weights(d, "conv", &w, &b, (c, c, 3)); + let (bs, bg, bt) = (upload(d, "skip", &skip), upload(d, "gamma", &gamma), upload(d, "beta", &beta)); + let (partials, stats) = (buffer(d, "partials", partials_len(side * side, groups)), buffer(d, "stats", 2 * groups)); + g.upsample_add(k, [&cur, &bs, &up], c, (side / 2, side)).unwrap(); + g.conv3(kn, [&up, &bw, &bb, &out], side, (c, c)).unwrap(); + g.group_norm_relu(k, [&out, &bg, &bt], [&partials, &stats], (side * side, c, groups), EPS).unwrap(); + cur = out; + } + let got = read(d, g, &cur, side * side * c); + let err = worst(&got, &f32s(&want)); + assert!(err < 1e-4, "off by {err}"); +} + +#[test] +fn the_mask_decoder_kernels_refuse_what_they_cannot_do() { + let Some(d) = gpu() else { return }; + let k = pixel_kernels(d); + let b = buffer(d, "b", 16); + let mut g = Graph::new(d); + assert!(g.upsample_add(k, [&b, &b, &b], 4, (0, 2)).is_err(), "an empty image"); + assert!(g.upsample_add(k, [&b, &b, &b], 4, (4, 2)).is_err(), "down-sampling"); + assert!(g.group_norm_relu(k, [&b, &b, &b], [&b, &b], (4, 12, 8), EPS).is_err(), "channels not a multiple of the groups"); + assert!(g.group_norm_relu(k, [&b, &b, &b], [&b, &b], (4, 512, 8), EPS).is_err(), "more channels than threads"); + assert!(g.group_norm_relu(k, [&b, &b, &b], [&b, &b], (0, 8, 8), EPS).is_err(), "no pixels"); +} + +#[test] +fn the_decoder_refuses_inputs_of_the_wrong_size() { + let Some(d) = gpu() else { return }; + // checked before the checkpoint is read: an empty reader is never touched + let dir = std::env::temp_dir().join(format!("lc-sam3-pixel-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let mut st = 2u64.to_le_bytes().to_vec(); + st.extend_from_slice(b"{}"); + std::fs::write(dir.join("model.safetensors"), st).unwrap(); + std::fs::write(dir.join("vocab.json"), "{}").unwrap(); + std::fs::write(dir.join("merges.txt"), "").unwrap(); + let m = MaskDecoder::new(WeightReader::open(&dir).unwrap()); + let (mem, text, valid) = (vec![0f32; GRID * GRID * WIDTH], vec![0f32; TEXT * WIDTH], vec![true; TEXT]); + let (l1, l0) = (vec![0f32; WIDTH * 144 * 144], vec![0f32; WIDTH * SIDE * SIDE]); + let rows = vec![0f32; 3 * WIDTH]; + assert!(m.run(d, &mem[1..], &text, &valid, [&l1, &l0], &rows, &[0.0; 3]).is_err_and(|e| e.contains("expected"))); + assert!(m.run(d, &mem, &text, &valid, [&l0, &l1], &rows, &[0.0; 3]).is_err_and(|e| e.contains("expected"))); + assert!(m.run(d, &mem, &text, &valid, [&l1, &l0], &rows, &[0.0; 2]).is_err_and(|e| e.contains("row values"))); + assert!(m.run(d, &mem, &text, &valid, [&l1, &l0], &[], &[]).is_err_and(|e| e.contains("row values"))); + // the right sizes reach the checkpoint, which has no decoder + assert!(m.run(d, &mem, &text, &valid, [&l1, &l0], &rows, &[0.0; 3]).is_err_and(|e| e.contains("mask_decoder"))); + assert!(m.bytes().is_none()); + std::fs::remove_dir_all(dir).unwrap(); +} diff --git a/crates/gpu/src/sam3/tests.rs b/crates/gpu/src/sam3/tests.rs new file mode 100644 index 0000000000..1b9041f263 --- /dev/null +++ b/crates/gpu/src/sam3/tests.rs @@ -0,0 +1,467 @@ +//! The SAM 3 kernels against plain loops on small shapes (tiles cut off at the edges, several windows). The whole +//! backbone against candle: `tests/it/sam3_backbone.rs`. + +use super::*; + +pub(super) fn gpu() -> Option<&'static Dev> { + match dev() { + Ok(d) => Some(d), + // a kernel that doesn't compile is a failure, not a missing GPU + Err(e) if e.contains("did not compile") => panic!("{e}"), + Err(e) => { + lightcraft_testkit::skip!(Gpu, "no GPU for the SAM 3 kernels ({e})"); + None + } + } +} + +/// Deterministic values in −scale..scale. +pub(super) fn values(n: usize, seed: u64, scale: f32) -> Vec { + let mut s = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (0..n) + .map(|_| { + s = s.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + ((s >> 40) as f32 / (1u64 << 24) as f32 * 2.0 - 1.0) * scale + }) + .collect() +} + +pub(super) fn read(d: &'static Dev, g: Graph, out: &wgpu::Buffer, len: usize) -> Vec { + let staging = d.device.create_buffer(&wgpu::BufferDescriptor { + label: None, + size: (len * 4) as u64, + usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + g.record().run("a test", d, out, &staging, len).unwrap() +} + +pub(super) fn worst(got: &[f32], want: &[f32]) -> f32 { + assert_eq!(got.len(), want.len()); + got.iter().zip(want).fold(0f32, |m, (a, b)| m.max((a - b).abs())) +} + +/// GELU, erf form (candle's `gelu_erf`), with a high-precision erf: the kernel's approximation is what is checked. +pub(super) fn gelu(v: f64) -> f64 { + 0.5 * v * (1.0 + erf(v / std::f64::consts::SQRT_2)) +} + +/// erf to ~1e-15 (Taylor series near 0, continued fraction of erfc further out). +fn erf(x: f64) -> f64 { + let a = x.abs(); + let r = if a < 2.5 { + let (mut term, mut sum, mut n) = (a, a, 0.0); + while term.abs() > 1e-17 * sum.abs() { + n += 1.0; + term *= -a * a / n; + sum += term / (2.0 * n + 1.0); + } + sum * 2.0 / std::f64::consts::PI.sqrt() + } else { + // erfc(a) = exp(−a²)/√π · 1/(a + 1/2/(a + 1/(a + 3/2/(a + 2/(a + …))))) + let mut f = a; + for k in (1..60).rev() { + f = a + (k as f64 / 2.0) / f; + } + 1.0 - (-a * a).exp() / std::f64::consts::PI.sqrt() / f + }; + if x < 0.0 { -r } else { r } +} + +#[test] +fn erf_reference_is_right() { + for (x, want) in [(0.5, 0.520_499_877_813_046_5), (1.0, 0.842_700_792_949_714_9), (2.0, 0.995_322_265_018_952_7), (3.0, 0.999_977_909_503_001_4)] + { + assert!((erf(x) - want).abs() < 1e-13, "erf({x}) = {}", erf(x)); + assert!((erf(-x) + want).abs() < 1e-13); + } +} + +/// `y = act(x · wᵀ + bias[row % rows])` (+ y0) in f64. +#[allow(clippy::too_many_arguments)] +fn matmul_ref(x: &[f32], w: &[f32], bias: &[f32], y0: Option<&[f32]>, (m, n, k): (usize, usize, usize), rows: usize, act: bool) -> Vec { + let mut out = vec![0f32; m * n]; + for i in 0..m { + for j in 0..n { + let mut v = bias[(i % rows) * n + j] as f64; + for t in 0..k { + v += x[i * k + t] as f64 * w[j * k + t] as f64; + } + if act { + v = gelu(v); + } + if let Some(y0) = y0 { + v += y0[i * n + j] as f64; + } + out[i * n + j] = v as f32; + } + } + out +} + +#[test] +fn the_matrix_product_gives_what_the_definition_gives() { + let Some(d) = gpu() else { return }; + // whole tiles, cut-off tiles in every direction, K not a multiple of the tile's 16, a position-style bias table + for (case, (m, n, k, rows, act, residual)) in [ + (256, 128, 64, 1, false, false), + (200, 136, 52, 1, false, false), + (130, 300, 588, 7, false, false), + (77, 260, 96, 1, true, false), + (150, 129, 132, 1, false, true), + (5, 3, 4, 1, true, true), + ] + .into_iter() + .enumerate() + { + let x = values(m * k, case as u64, 1.0); + let w = values(n * k, 100 + case as u64, 0.2); + let bias = values(rows * n, 200 + case as u64, 0.5); + let y0 = values(m * n, 300 + case as u64, 1.0); + let (bx, bw, bb) = (upload(d, "x", &x), upload(d, "w", &w), upload(d, "b", &bias)); + let by = buffer(d, "y", m * n); + d.queue.write_buffer(&by, 0, bytemuck::cast_slice(&y0)); + let mut g = Graph::new(d); + g.matmul([&bx, &bw, &bb, &by], (m, n, k), rows, act, residual, Precision::F32).unwrap(); + let got = read(d, g, &by, m * n); + let want = matmul_ref(&x, &w, &bias, residual.then_some(&y0[..]), (m, n, k), rows, act); + let err = worst(&got, &want); + assert!(err < 2e-5 * (k as f32).sqrt().max(1.0), "case {case} ({m}×{n}×{k}): off by {err}"); + } +} + +#[test] +fn the_f16_matrix_product_uses_the_rounded_weights() { + let Some(d) = gpu() else { return }; + let (m, n, k) = (140, 200, 96); + let x = values(m * k, 1, 1.0); + let w = values(n * k, 2, 0.2); + let bias = values(n, 3, 0.5); + let rounded: Vec = w.iter().map(|v| f16_value(f16_bits(*v))).collect(); + let (bx, bw, bb) = (upload(d, "x", &x), upload(d, "w", &pack_f16(&w)), upload(d, "b", &bias)); + let by = buffer(d, "y", m * n); + let mut g = Graph::new(d); + g.matmul([&bx, &bw, &bb, &by], (m, n, k), 1, true, false, Precision::F16).unwrap(); + let got = read(d, g, &by, m * n); + let want = matmul_ref(&x, &rounded, &bias, None, (m, n, k), 1, true); + let err = worst(&got, &want); + assert!(err < 1e-4, "off by {err}"); + // K must be a multiple of the f16 tile + assert!(Graph::new(d).matmul([&bx, &bw, &bb, &by], (m, n, 40), 1, false, false, Precision::F16).is_err()); +} + +/// The value of half `h` (test reference). +fn f16_value(h: u16) -> f32 { + let sign = if h & 0x8000 != 0 { -1.0 } else { 1.0 }; + let (e, m) = (((h >> 10) & 0x1f) as i32, (h & 0x3ff) as f32); + sign * match e { + 0 => m * 2f32.powi(-24), + 0x1f => { + if m == 0.0 { + f32::INFINITY + } else { + f32::NAN + } + } + _ => (1.0 + m / 1024.0) * 2f32.powi(e - 15), + } +} + +#[test] +fn halves_round_to_nearest_even() { + for (v, h) in [ + (0.0f32, 0x0000u16), + (-0.0, 0x8000), + (1.0, 0x3c00), + (-2.0, 0xc000), + (65504.0, 0x7bff), + (65520.0, 0x7c00), + (1e10, 0x7c00), + (f32::INFINITY, 0x7c00), + (6.103_515_6e-5, 0x0400), + (5.960_464_5e-8, 0x0001), + (2.0e-8, 0x0000), + (0.333_333_34, 0x3555), + // exactly between 1 and the next half up (1 + 2⁻¹¹): ties to even (down), just above: up + (1.000_488_3, 0x3c00), + (1.000_488_4, 0x3c01), + ] { + assert_eq!(f16_bits(v), h, "{v}"); + } + assert!(f16_value(f16_bits(f32::NAN)).is_nan()); + // every half survives the round trip + for h in (0u16..0x7c00).step_by(7) { + assert_eq!(f16_bits(f16_value(h)), h); + } +} + +#[test] +fn layer_norm_gives_what_the_definition_gives() { + let Some(d) = gpu() else { return }; + for (rows, c) in [(7, 1024), (3, 300), (2, 4)] { + let x: Vec = values(rows * c, c as u64, 3.0).iter().enumerate().map(|(i, v)| v + (i / c) as f32).collect(); + let (gamma, beta) = (values(c, 5, 1.0), values(c, 6, 0.5)); + let (bx, bg, bb, by) = (upload(d, "x", &x), upload(d, "g", &gamma), upload(d, "b", &beta), buffer(d, "y", rows * c)); + let mut g = Graph::new(d); + g.layernorm([&bx, &bg, &bb, &by], rows, c).unwrap(); + let got = read(d, g, &by, rows * c); + let mut want = vec![0f32; rows * c]; + for r in 0..rows { + let row = &x[r * c..(r + 1) * c]; + let mean = row.iter().map(|v| *v as f64).sum::() / c as f64; + let var = row.iter().map(|v| (*v as f64 - mean).powi(2)).sum::() / c as f64; + for i in 0..c { + want[r * c + i] = ((row[i] as f64 - mean) / (var + EPS as f64).sqrt() * gamma[i] as f64 + beta[i] as f64) as f32; + } + } + let err = worst(&got, &want); + assert!(err < 2e-5, "{rows}×{c}: off by {err}"); + } +} + +/// `vit::apply_rope` (x·cos + rotate_pairwise(x)·sin) with the tables of `vit::rope_tables` for token `t`. +fn rope_ref(x: &[f32], table: &[f32], t: usize) -> Vec { + // the candle tables: [head_dim] cos and sin, each pair's value duplicated + let (mut cos, mut sin) = (Vec::new(), Vec::new()); + for i in 0..32 { + let (c, s) = (table[(t * 32 + i) * 2], table[(t * 32 + i) * 2 + 1]); + cos.extend([c, c]); + sin.extend([s, s]); + } + let mut out = vec![0f32; x.len()]; + for (h, head) in x.chunks(HEAD_DIM).enumerate() { + for i in 0..HEAD_DIM { + let rot = if i % 2 == 0 { -head[i + 1] } else { head[i - 1] }; + out[h * HEAD_DIM + i] = head[i] * cos[i] + rot * sin[i]; + } + } + out +} + +#[test] +fn rope_tables_follow_the_candle_port() { + // window table: plain row-major 24 × 24 positions; the global one lists the 72 × 72 grid in window order + let win = rope_table(WINDOW, WINDOW, 1.0); + let global = rope_table(GRID, WINDOW, WINDOW as f64 / GRID as f64); + assert_eq!(win.len(), WINDOW * WINDOW * 64); + assert_eq!(global.len(), TOKENS * 64); + // token 25 of a window is at (1, 1): x frequency 0 rotates by 1, y frequency 0 by 1 + assert!((win[(25 * 32) * 2] - 1f32.cos()).abs() < 1e-7); + assert!((win[(25 * 32 + 16) * 2 + 1] - 1f32.sin()).abs() < 1e-7); + // window-order token 576 (the second window's first) is cell (0, 24): x = 24 · (24 / 72) = 8 + assert_eq!(window_cell(576, GRID, WINDOW), (0, 24)); + assert!((global[(576 * 32) * 2] - 8f32.cos()).abs() < 1e-6); + assert!((global[(576 * 32 + 16) * 2] - 1.0).abs() < 1e-7, "y = 0"); + // every cell exactly once + let mut seen = vec![false; TOKENS]; + for t in 0..TOKENS { + let (r, c) = window_cell(t, GRID, WINDOW); + assert!(!seen[r * GRID + c]); + seen[r * GRID + c] = true; + } +} + +#[test] +fn rope_rotates_q_and_k_and_scales_q() { + let Some(d) = gpu() else { return }; + let (tokens, hidden, rows) = (40, 128, 16); + let stride = 3 * hidden; + let qkv = values(tokens * stride, 9, 1.0); + let table = rope_table(4, 4, 1.0); + let (bq, bt) = (buffer(d, "qkv", tokens * stride), upload(d, "table", &table)); + d.queue.write_buffer(&bq, 0, bytemuck::cast_slice(&qkv)); + let mut g = Graph::new(d); + g.rope(&bq, &bt, (tokens, stride, hidden), rows, 0.125).unwrap(); + let got = read(d, g, &bq, tokens * stride); + let mut want = qkv.clone(); + for t in 0..tokens { + let row = &qkv[t * stride..(t + 1) * stride]; + let q: Vec = rope_ref(&row[..hidden], &table, t % rows).iter().map(|v| v * 0.125).collect(); + let k = rope_ref(&row[hidden..2 * hidden], &table, t % rows); + want[t * stride..t * stride + hidden].copy_from_slice(&q); + want[t * stride + hidden..t * stride + 2 * hidden].copy_from_slice(&k); + } + let err = worst(&got, &want); + assert!(err < 1e-6, "off by {err}"); +} + +/// Softmax attention of each query over its window's `span` keys (q already scaled), f64. +fn attention_ref(qkv: &[f32], (tokens, stride, hidden): (usize, usize, usize), span: usize) -> Vec { + let mut out = vec![0f32; tokens * hidden]; + for h in 0..hidden / HEAD_DIM { + for t in 0..tokens { + let first = t / span * span; + let q = &qkv[t * stride + h * HEAD_DIM..][..HEAD_DIM]; + let s: Vec = (first..first + span) + .map(|j| q.iter().zip(&qkv[j * stride + hidden + h * HEAD_DIM..][..HEAD_DIM]).map(|(a, b)| *a as f64 * *b as f64).sum()) + .collect(); + let top = s.iter().fold(f64::MIN, |m, v| m.max(*v)); + let e: Vec = s.iter().map(|v| (v - top).exp()).collect(); + let sum: f64 = e.iter().sum(); + for c in 0..HEAD_DIM { + let v: f64 = (first..first + span).zip(&e).map(|(j, w)| w * qkv[j * stride + 2 * hidden + h * HEAD_DIM + c] as f64).sum(); + out[t * hidden + h * HEAD_DIM + c] = (v / sum) as f32; + } + } + } + out +} + +#[test] +fn windowed_and_global_attention_give_the_softmax_of_the_definition() { + let Some(d) = gpu() else { return }; + let (tokens, hidden) = (384, 128); + let stride = 3 * hidden; + // large scores: the online maximum must keep exp() in range + let qkv = values(tokens * stride, 11, 2.5); + let bq = upload(d, "qkv", &qkv); + for span in [64, 128, 384] { + let out = buffer(d, "out", tokens * hidden); + let mut g = Graph::new(d); + g.attention(&bq, &out, (tokens, stride, hidden), span).unwrap(); + let got = read(d, g, &out, tokens * hidden); + let want = attention_ref(&qkv, (tokens, stride, hidden), span); + let err = worst(&got, &want); + // relative to the outputs' size: Metal's exp() is a little less exact than Vulkan's + // (span 128 is off by 2.04e-5 on an M4 Pro, 8e-6 of the largest output) + let scale = want.iter().fold(1f32, |m, v| m.max(v.abs())); + assert!(err < 2e-5 * scale, "span {span}: off by {err} (scale {scale})"); + } + // windows must hold whole workgroups of queries + assert!(Graph::new(d).attention(&bq, &bq, (tokens, stride, hidden), 96).is_err()); +} + +#[test] +fn patches_go_in_and_out_of_window_order() { + let Some(d) = gpu() else { return }; + // 3 × 56 × 56 pixels, 14-pixel patches: a 4 × 4 grid of 2 × 2 windows + let (side, patch, window) = (56, 14, 2); + let grid = side / patch; + let k = 3 * patch * patch; + let pixels = values(3 * side * side, 12, 1.0); + let bp = upload(d, "pixels", &pixels); + let cols = buffer(d, "cols", grid * grid * k); + let mut g = Graph::new(d); + g.im2col(&bp, &cols, (side, patch, 3), window).unwrap(); + let got = read(d, g, &cols, grid * grid * k); + for t in 0..grid * grid { + let (row, col) = window_cell(t, grid, window); + for ch in 0..3 { + for ky in 0..patch { + for kx in 0..patch { + let want = pixels[(ch * side + row * patch + ky) * side + col * patch + kx]; + assert_eq!(got[t * k + (ch * patch + ky) * patch + kx], want, "token {t}"); + } + } + } + } + // and back: channels-first on the grid + let channels = 8; + let tokens = values(grid * grid * channels, 13, 1.0); + let bt = upload(d, "tokens", &tokens); + let out = buffer(d, "chw", grid * grid * channels); + let mut g = Graph::new(d); + g.channels_first(&bt, &out, channels, grid, window).unwrap(); + let got = read(d, g, &out, grid * grid * channels); + for t in 0..grid * grid { + let (row, col) = window_cell(t, grid, window); + for ch in 0..channels { + assert_eq!(got[(ch * grid + row) * grid + col], tokens[t * channels + ch]); + } + } +} + +#[test] +fn the_kernel_source_is_written_out_for_both_weight_types() { + for f16 in [false, true] { + let src = matmul_source(TILE, f16); + assert!(!src.contains("{{"), "a mark left"); + assert_eq!(src.contains("fn load_b16"), f16); + assert_eq!(src.contains("fn load_b("), !f16); + assert_eq!(src.matches("= fma(").count() as u32, 4 * TILE.rows * TILE.cols); + } +} + +/// Kernel timings at the backbone's shapes: +/// `cargo test --release -p lightcraft-gpu --features sam --lib sam3::tests::timings -- --ignored --nocapture`. +#[test] +#[ignore = "a benchmark: needs a GPU"] +fn timings() { + let Some(d) = gpu() else { return }; + let reps = 20; + let time = |name: &str, flops: f64, build: &dyn Fn(&mut Graph)| { + let out = buffer(d, "out", 4); + let staging = d.device.create_buffer(&wgpu::BufferDescriptor { + label: None, + size: 16, + usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let mut g = Graph::new(d); + for _ in 0..reps { + build(&mut g); + } + let rec = g.record(); + rec.run("a test", d, &out, &staging, 4).unwrap(); + let t = std::time::Instant::now(); + rec.run("a test", d, &out, &staging, 4).unwrap(); + let ms = t.elapsed().as_secs_f64() * 1e3 / reps as f64; + eprintln!("{name:>34}: {ms:7.3} ms {:6.2} TFLOP/s", flops / ms / 1e9); + }; + let x = buffer(d, "x", TOKENS * MLP); + let y = buffer(d, "y", TOKENS * MLP); + let w = buffer(d, "w", MLP * HIDDEN); + let b = buffer(d, "b", MLP); + let w16 = buffer(d, "w16", MLP * HIDDEN / 2); + for (n, k) in [(3 * HIDDEN, HIDDEN), (HIDDEN, HIDDEN), (MLP, HIDDEN), (HIDDEN, MLP)] { + let flops = 2.0 * (TOKENS * n * k) as f64; + time(&format!("matmul {TOKENS}x{n}x{k}"), flops, &|g| g.matmul([&x, &w, &b, &y], (TOKENS, n, k), 1, false, false, Precision::F32).unwrap()); + time(&format!("matmul f16 {TOKENS}x{n}x{k}"), flops, &|g| { + g.matmul([&x, &w16, &b, &y], (TOKENS, n, k), 1, false, false, Precision::F16).unwrap() + }); + } + // other blockings (`LC_SAM3_TILES=rows,cols,bk;…`) + for t in std::env::var("LC_SAM3_TILES").unwrap_or_default().split(';').filter(|t| !t.is_empty()) { + let v: Vec = t.split(',').map(|v| v.trim().parse().unwrap()).collect(); + let tile = Tile { rows: v[0], cols: v[1], bk: v[2] }; + let kernel: &'static Matmul = + Box::leak(Box::new(Matmul { pipeline: pipeline(&d.device, &d.pipeline_layout, "variant", &matmul_source(tile, false), "main"), tile })); + for (n, k) in [(3 * HIDDEN, HIDDEN), (MLP, HIDDEN), (HIDDEN, MLP)] { + let flops = 2.0 * (TOKENS * n * k) as f64; + time(&format!("{tile:?} {n}x{k}"), flops, &|g| { + g.matmul_with(kernel, Precision::F32, [&x, &w, &b, &y], (TOKENS, n, k), 1, false, false).unwrap() + }); + } + } + time("matmul 5184x4736x1024 gelu", 2.0 * (TOKENS * MLP * HIDDEN) as f64, &|g| { + g.matmul([&x, &w, &b, &y], (TOKENS, MLP, HIDDEN), 1, true, false, Precision::F32).unwrap() + }); + for span in [WINDOW * WINDOW, TOKENS] { + let flops = 4.0 * (TOKENS * span * HIDDEN) as f64; + time(&format!("attention span {span}"), flops, &|g| g.attention(&x, &y, (TOKENS, 3 * HIDDEN, HIDDEN), span).unwrap()); + } + time("layernorm", 0.0, &|g| g.layernorm([&x, &b, &b, &y], TOKENS, HIDDEN).unwrap()); + time("rope", 0.0, &|g| g.rope(&x, &w, (TOKENS, 3 * HIDDEN, HIDDEN), TOKENS, 0.125).unwrap()); +} + +/// An adapter without the storage-buffer size or the workgroup memory the kernels need gets no device (the model then +/// runs in candle on the CPU); the error names what it lacks. No GPU needed. +#[test] +fn an_adapter_short_of_the_limits_is_refused_with_what_it_lacks() { + assert!(short_limits(&needed_limits()).is_empty()); + let short = short_limits(&wgpu::Limits { max_storage_buffer_binding_size: 64 << 20, ..needed_limits() }); + assert_eq!(short.len(), 1, "{short:?}"); + assert!(short[0].starts_with("max_storage_buffer_binding_size 67108864 <"), "{short:?}"); + let short = short_limits(&wgpu::Limits { max_compute_workgroup_storage_size: 8 << 10, ..needed_limits() }); + assert_eq!(short.len(), 1, "{short:?}"); + assert!(short[0].starts_with("max_compute_workgroup_storage_size 8192 <"), "{short:?}"); +} + +/// DX12 pipeline creation can take minutes for the fully unrolled attention shader; other backends keep the larger tile. +#[test] +fn attention_tiles_are_smaller_on_dx12() { + assert_eq!(attention_keys(wgpu::Backend::Dx12), 8); + assert_eq!(attention_keys(wgpu::Backend::Vulkan), ATTENTION_KEYS); + let src = attention_source(attention_keys(wgpu::Backend::Dx12)); + assert!(src.contains("let s7 = ") && !src.contains("let s8 = ")); +} diff --git a/crates/gpu/src/wgsl/sam3_attention.wgsl b/crates/gpu/src/wgsl/sam3_attention.wgsl new file mode 100644 index 0000000000..e9dca40da3 --- /dev/null +++ b/crates/gpu/src/wgsl/sam3_attention.wgsl @@ -0,0 +1,75 @@ +// Self-attention of the SAM 3 backbone (`sam3.rs`), flash style: the scores are never stored. Each query keeps a +// running maximum, softmax denominator and weighted sum of values while the keys stream past (online softmax), so a +// global layer (5184 tokens, 16 heads) needs no 16 x 5184² score matrix. +// +// qkv [tokens, stride]: per token q | k | v, each `hidden` wide (heads x 64), q and k already rotated (RoPE) +// and q already scaled by 1 / sqrt(64) +// out [tokens, hidden] +// +// Tokens are in window order, so a query's keys are the `span` tokens of its window: a contiguous range (span = all +// tokens for the global layers). A workgroup is 64 queries of one head (span is a multiple of 64, so they share +// their window), one query per thread with its q and its partial output in registers; keys and values pass through +// workgroup memory KB at a time, read by all 64 threads at once (a broadcast). The host writes out the per-thread +// work with one variable per vector and score (the DECL, SCORES, RESCALE, ACCUMULATE and STORE marks): arrays indexed +// in loops can end up in slow local memory. + +struct P { + tokens: u32, + span: u32, + stride: u32, + hidden: u32, +} + +@group(0) @binding(0) var p: P; +@group(0) @binding(1) var qkv: array>; +@group(0) @binding(4) var out: array>; + +// head_dim / 4, keys per step +const D4: u32 = 16u; +const KB: u32 = {{KB}}u; + +var Ks: array, KB * D4>; +var Vs: array, KB * D4>; + +@compute @workgroup_size(64) +fn main(@builtin(workgroup_id) wg: vec3, @builtin(local_invocation_index) lid: u32) { + let head = wg.y; + let qw = wg.x * 64u; + let tq = qw + lid; + let s4 = p.stride / 4u; + let h4 = p.hidden / 4u; + let first = qw / p.span * p.span; + // a whole workgroup returns together (tokens is a multiple of 64): the barriers below stay uniform + if (qw >= p.tokens) { + return; + } + let qa = tq * s4 + head * D4; + +{{DECL}} + var m = -3.0e38; + var l = 0.0; + + for (var k0 = 0u; k0 < p.span; k0 += KB) { + for (var e = lid; e < KB * D4; e += 64u) { + let t = first + k0 + e / D4; + let c = head * D4 + e % D4; + Ks[e] = qkv[t * s4 + h4 + c]; + Vs[e] = qkv[t * s4 + 2u * h4 + c]; + } + workgroupBarrier(); + + var top = m; +{{SCORES}} + // rescale what was summed under the old maximum + let fix = exp(m - top); + l *= fix; +{{RESCALE}} +{{ACCUMULATE}} + m = top; + workgroupBarrier(); + } + + let r = 1.0 / l; + let oa = tq * h4 + head * D4; +{{STORE}} +} diff --git a/crates/gpu/src/wgsl/sam3_conv.wgsl b/crates/gpu/src/wgsl/sam3_conv.wgsl new file mode 100644 index 0000000000..67cc55ef73 --- /dev/null +++ b/crates/gpu/src/wgsl/sam3_conv.wgsl @@ -0,0 +1,29 @@ +// The A-tile loader of the necks' 3 x 3 convolution (`sam3/neck.rs`, padding 1, stride 1): spliced into +// `sam3_matmul.wgsl` in place of its dense `load_a`, so the convolution is that kernel's product over an im2col +// matrix that is never stored (an implicit GEMM; at 288 x 288 x 256 the stored one would be 764 MB). +// +// X [side², cin] the image, pixels row-major, channels last (cin a multiple of 4) +// A [side², 9 · cin] row m: output pixel (m / side, m % side); column k = tap · cin + c: input channel c of the +// pixel at tap (ky, kx) = (tap / 3, tap % 3), i.e. (row + ky − 1, col + kx − 1), zero outside the image +// W [cout, 9 · cin] the weights in the same (ky, kx, c) order +// +// A vector of four k is four channels of one pixel, so it is one aligned load from X. + +// Vector e of the A tile at k0 (row e / KV); zero outside the image (the padding) and outside A. +fn load_a(m0: u32, k0: u32, e: u32) -> vec4 { + let m = m0 + e / KV; + let kq = k0 / 4u + e % KV; + let k4 = p.k / 4u; + if (m >= p.m || kq >= k4) { + return vec4(0.0); + } + let side = p.side; + let c4 = k4 / 9u; + let tap = kq / c4; + let row = i32(m / side) + i32(tap / 3u) - 1; + let col = i32(m % side) + i32(tap % 3u) - 1; + if (row < 0 || col < 0 || row >= i32(side) || col >= i32(side)) { + return vec4(0.0); + } + return x[(u32(row) * side + u32(col)) * c4 + kq % c4]; +} diff --git a/crates/gpu/src/wgsl/sam3_detr.wgsl b/crates/gpu/src/wgsl/sam3_detr.wgsl new file mode 100644 index 0000000000..2ed63db145 --- /dev/null +++ b/crates/gpu/src/wgsl/sam3_detr.wgsl @@ -0,0 +1,105 @@ +// The DETR encoder of SAM 3's text detector (`sam3/detr.rs`): attention with heads of 32 (8 of them over 256 numbers), +// for the image tokens over themselves (self-attention) and over the prompt's tokens (cross-attention, with a +// key-padding bias), and the sum of two arrays (the position encoding added to the normed tokens). +// +// q [queries, q_stride]: head h's q at h · 32 (binding 1) +// k [keys, k_stride] from k_off (binding 2), v [keys, v_stride] from v_off (binding 3); 2 and 3 may be one buffer +// bias `keys` floats in binding 2 from `bias` (NONE: no bias), added to every score of its key: 0 for a real +// token, f32::MIN for padding, as candle's `padding_bias` +// out [queries, heads · 32] +// +// Strides and offsets count floats (multiples of 4); keys is a multiple of KB. Flash style like +// `sam3_attention.wgsl`: one query per thread with its q and partial output in registers, keys and values KB at a +// time through workgroup memory, online softmax. The running maximum starts at f32::MIN rather than below it: a padded +// key's score is then exactly f32::MIN (as in candle, where s + f32::MIN rounds to f32::MIN) and weighs nothing next +// to a real one, and a query whose keys are all padding averages them, as candle's softmax over equal scores does. +// The host writes out the per-thread work with one variable per vector and score (the DECL, SCORES, RESCALE, +// ACCUMULATE and STORE marks). + +struct P { + queries: u32, + keys: u32, + q_stride: u32, + k_stride: u32, + v_stride: u32, + k_off: u32, + v_off: u32, + bias: u32, +} + +@group(0) @binding(0) var p: P; +@group(0) @binding(1) var qs: array>; +@group(0) @binding(2) var ks: array>; +@group(0) @binding(3) var vs: array>; +@group(0) @binding(4) var out: array>; + +// head_dim / 4, keys per step, 1 / sqrt(head_dim) +const D4: u32 = 8u; +const KB: u32 = {{KB}}u; +const SCALE: f32 = 0.17677669529663687; +const NONE: u32 = 0xffffffffu; +const LOWEST: f32 = -3.4028234663852886e38; + +var Ks: array, KB * D4>; +var Vs: array, KB * D4>; +var Bs: array; + +@compute @workgroup_size(64) +fn attention(@builtin(workgroup_id) wg: vec3, @builtin(num_workgroups) groups: vec3, @builtin(local_invocation_index) lid: u32) { + let head = wg.y; + let tq = wg.x * 64u + lid; + // threads past the last query compute on query 0 (the barriers below stay uniform) and store nothing + let live = tq < p.queries; + let qa = select(0u, tq, live) * (p.q_stride / 4u) + head * D4; + let k4 = p.k_stride / 4u; + let v4 = p.v_stride / 4u; + let ka = p.k_off / 4u + head * D4; + let va = p.v_off / 4u + head * D4; + +{{DECL}} + var m = LOWEST; + var l = 0.0; + + for (var k0 = 0u; k0 < p.keys; k0 += KB) { + for (var e = lid; e < KB * D4; e += 64u) { + let t = k0 + e / D4; + Ks[e] = ks[t * k4 + ka + e % D4]; + Vs[e] = vs[t * v4 + va + e % D4]; + } + if (lid < KB) { + var b = 0.0; + if (p.bias != NONE) { + let i = p.bias + k0 + lid; + b = ks[i / 4u][i % 4u]; + } + Bs[lid] = b; + } + workgroupBarrier(); + + var top = m; +{{SCORES}} + // rescale what was summed under the old maximum + let fix = exp(m - top); + l *= fix; +{{RESCALE}} +{{ACCUMULATE}} + m = top; + workgroupBarrier(); + } + + if (live) { + let r = 1.0 / l; + let oa = tq * groups.y * D4 + head * D4; +{{STORE}} + } +} + +// out = qs + ks, `queries` vectors (keys: workgroups per row of the dispatch). +@compute @workgroup_size(256) +fn add(@builtin(workgroup_id) wg: vec3, @builtin(local_invocation_index) lid: u32) { + let i = (wg.y * p.keys + wg.x) * 256u + lid; + if (i >= p.queries) { + return; + } + out[i] = qs[i] + ks[i]; +} diff --git a/crates/gpu/src/wgsl/sam3_matmul.wgsl b/crates/gpu/src/wgsl/sam3_matmul.wgsl new file mode 100644 index 0000000000..7ccc17f7f1 --- /dev/null +++ b/crates/gpu/src/wgsl/sam3_matmul.wgsl @@ -0,0 +1,138 @@ +// The linear layers of the SAM 3 backbone (`sam3.rs`): Y = act(X · Wᵀ + bias), or Y += X · Wᵀ + bias (a residual); +// act is none, GELU (gelu = 1) or ReLU (gelu = 2, the DETR encoder's MLP, `sam3/detr.rs`). +// +// X [M, K] row-major activations +// W [N, K] row-major: the checkpoint's own layout (f32; or, with the f16 variant, pairs of halves packed into +// u32s, k first) +// bias [bias_rows, N]: row m adds bias row m % bias_rows (1: an ordinary bias; 576: the patch embedding's +// 24 x 24 position table, which repeats over the windows) +// Y [M, N] +// +// K is a multiple of 4 (of BK for the f16 variant); M and N are anything. A workgroup of 256 threads (16 x 16) makes a +// BM x BN block of Y, TM x TN values per thread: rows ty + 16 i and columns tx + 16 j, so neighbouring threads write +// neighbouring numbers. K is walked in steps of BK through workgroup memory, where both tiles are kept k-contiguous +// as they are loaded (four k per vector), each row padded by one vector so that the eight threads of a 128-bit load +// phase read eight different bank groups. The next step's tiles are fetched into registers while the current one is +// multiplied. The host writes out the per-thread work with one variable per accumulator (the DECL, LOAD, STORE_TILE, +// COMPUTE and STORE marks): arrays indexed in loops can end up in slow local memory. + +struct P { + m: u32, + n: u32, + k: u32, + bias_rows: u32, + gelu: u32, + residual: u32, + // the image side of the 3 x 3 convolution's loader (`sam3_conv.wgsl`); unused here + side: u32, + pad: u32, +} + +@group(0) @binding(0) var p: P; +@group(0) @binding(1) var x: array>; +@group(0) @binding(2) var w: array<{{WEIGHT}}>; +@group(0) @binding(3) var bias: array; +@group(0) @binding(4) var y: array; + +const BM: u32 = {{BM}}u; +const BN: u32 = {{BN}}u; +const BK: u32 = {{BK}}u; +// vectors per tile row, and the padded row stride +const KV: u32 = BK / 4u; +const KS: u32 = KV + 1u; + +var As: array, BM * KS>; +var Bs: array, BN * KS>; + +// #if dense +// Vector e of the A tile at k0 (row e / KV); zero outside X. +fn load_a(m0: u32, k0: u32, e: u32) -> vec4 { + let m = m0 + e / KV; + let kq = k0 / 4u + e % KV; + let k4 = p.k / 4u; + if (m < p.m && kq < k4) { + return x[m * k4 + kq]; + } + return vec4(0.0); +} +// #endif + +// #if f32 +// Vector e of the B tile at k0 (row e / KV of W); zero outside W. +fn load_b(n0: u32, k0: u32, e: u32) -> vec4 { + let n = n0 + e / KV; + let kq = k0 / 4u + e % KV; + let k4 = p.k / 4u; + if (n < p.n && kq < k4) { + return w[n * k4 + kq]; + } + return vec4(0.0); +} +// #endif + +// #if f16 +// The f16 variant: packed vector e of the B tile at k0 (eight k of row e / (BK / 8)), as two f32 vectors. +fn load_b16(n0: u32, k0: u32, e: u32) -> array, 2> { + let n = n0 + e / (BK / 8u); + let kq = k0 / 8u + e % (BK / 8u); + let k8 = p.k / 8u; + var v = vec4(0u); + if (n < p.n && kq < k8) { + v = w[n * k8 + kq]; + } + return array, 2>(vec4(unpack2x16float(v.x), unpack2x16float(v.y)), vec4(unpack2x16float(v.z), unpack2x16float(v.w))); +} +// #endif + +fn erf(v: f32) -> f32 { + // Abramowitz & Stegun 7.1.26 (|error| < 1.5e-7) + let a = abs(v); + let t = 1.0 / (1.0 + 0.3275911 * a); + let poly = t * (0.254829592 + t * (-0.284496736 + t * (1.421413741 + t * (-1.453152027 + t * 1.061405429)))); + let r = 1.0 - poly * exp(-a * a); + return select(-r, r, v >= 0.0); +} + +fn put(m: u32, n: u32, acc: f32) { + if (n >= p.n) { + return; + } + var v = acc + bias[(m % p.bias_rows) * p.n + n]; + if (p.gelu == 1u) { + // GELU, exact (erf) form + v = 0.5 * v * (1.0 + erf(v * 0.7071067811865476)); + } else if (p.gelu == 2u) { + // ReLU (the DETR encoder's MLP) + v = max(v, 0.0); + } + let o = m * p.n + n; + if (p.residual != 0u) { + v += y[o]; + } + y[o] = v; +} + +@compute @workgroup_size(256) +fn main(@builtin(workgroup_id) wg: vec3, @builtin(local_invocation_index) tid: u32) { + let n0 = wg.x * BN; + let m0 = wg.y * BM; + let tx = tid % 16u; + let ty = tid / 16u; + +{{DECL}} + +{{LOAD}} + for (var k0 = 0u; k0 < p.k; k0 += BK) { +{{STORE_TILE}} + workgroupBarrier(); + if (k0 + BK < p.k) { +{{LOAD_NEXT}} + } + for (var kv = 0u; kv < KV; kv++) { +{{COMPUTE}} + } + workgroupBarrier(); + } + +{{STORE}} +} diff --git a/crates/gpu/src/wgsl/sam3_neck.wgsl b/crates/gpu/src/wgsl/sam3_neck.wgsl new file mode 100644 index 0000000000..db2853a1b4 --- /dev/null +++ b/crates/gpu/src/wgsl/sam3_neck.wgsl @@ -0,0 +1,60 @@ +// The reorderings of the SAM 3 necks (`sam3/neck.rs`) around their products: the backbone's channels-first output +// to pixel rows, and the rows of the transposed convolutions back to row-major. (Back to channels-first: `to_chw` +// of `sam3_ops.wgsl`, with one window over the whole image.) +// +// Same bindings and parameter block as `sam3_ops.wgsl`; flat dispatches cover `count` items, 256 per workgroup, +// workgroups in rows of `row`. + +struct P { + a: u32, + b: u32, + c: u32, + d: u32, + e: u32, + f: u32, + count: u32, + row: u32, +} + +@group(0) @binding(0) var p: P; +@group(0) @binding(1) var src: array; +@group(0) @binding(2) var aux: array; +@group(0) @binding(3) var aux2: array; +@group(0) @binding(4) var dst: array; + +fn flat_id(wg: vec3, lid: u32) -> u32 { + return (wg.y * p.row + wg.x) * 256u + lid; +} + +// Channels-first to pixel rows (a: channels, b: pixels): dst[pixel, ch] = src[ch, pixel]. +@compute @workgroup_size(256) +fn to_rows(@builtin(workgroup_id) wg: vec3, @builtin(local_invocation_index) lid: u32) { + let g = flat_id(wg, lid); + if (g >= p.count) { + return; + } + dst[g] = src[g % p.a * p.b + g / p.a]; +} + +// Pixel rows after `c` 2 x 2 stride-2 transposed convolutions to row-major (a: channels, b: side). Such a convolution +// is one product per input pixel whose row holds its four output pixels (ky, kx) one after the other, so after c of +// them the pixels of the side x side image come ordered by (row >> c, col >> c), then the (ky, kx) of the first, …, +// of the last: dst[row · side + col, ch] = src[that position, ch]. +@compute @workgroup_size(256) +fn unshuffle(@builtin(workgroup_id) wg: vec3, @builtin(local_invocation_index) lid: u32) { + let g = flat_id(wg, lid); + if (g >= p.count) { + return; + } + let side = p.b; + let ups = p.c; + let ch = g % p.a; + let pixel = g / p.a; + let row = pixel / side; + let col = pixel % side; + var at = (row >> ups) * (side >> ups) + (col >> ups); + for (var s = ups; s > 0u; s--) { + at = at * 4u + ((row >> (s - 1u)) & 1u) * 2u + ((col >> (s - 1u)) & 1u); + } + dst[g] = src[at * p.a + ch]; +} diff --git a/crates/gpu/src/wgsl/sam3_ops.wgsl b/crates/gpu/src/wgsl/sam3_ops.wgsl new file mode 100644 index 0000000000..a46d3ccad1 --- /dev/null +++ b/crates/gpu/src/wgsl/sam3_ops.wgsl @@ -0,0 +1,143 @@ +// The small steps of the SAM 3 backbone (`sam3.rs`) around its matrix products and attention: layer norm, rotary +// position encoding, the patch embedding's im2col and the final reordering to channels-first. +// +// Tokens are kept in window order: token t = window · win² + (row % win) · win + col % win, windows row-major over +// the grid (win = 24 on the 72 x 72 grid). The per-token steps don't care; `im2col` puts the patches in this order +// and `to_chw` takes them out of it. +// +// One uniform block of up to eight numbers per step (`P`); flat dispatches cover `count` items, 256 per workgroup, +// workgroups in rows of `row`. + +struct P { + a: u32, + b: u32, + c: u32, + d: u32, + e: u32, + f: u32, + count: u32, + row: u32, +} + +@group(0) @binding(0) var p: P; +@group(0) @binding(1) var src: array; +@group(0) @binding(2) var aux: array; +@group(0) @binding(3) var aux2: array; +@group(0) @binding(4) var dst: array; + +fn flat_id(wg: vec3, lid: u32) -> u32 { + return (wg.y * p.row + wg.x) * 256u + lid; +} + +// The position in window order of grid cell (row, col). +fn window_token(row: u32, col: u32, grid: u32, win: u32) -> u32 { + let w = row / win * (grid / win) + col / win; + return w * win * win + row % win * win + col % win; +} + +var red: array; + +fn reduce(lid: u32, v: f32) -> f32 { + red[lid] = v; + workgroupBarrier(); + for (var s = 128u; s > 0u; s >>= 1u) { + if (lid < s) { + red[lid] += red[lid + s]; + } + workgroupBarrier(); + } + let total = red[0]; + workgroupBarrier(); + return total; +} + +// LayerNorm over rows of `c` numbers (a: rows, b: c, e: eps bits): dst = (src − mean) / sqrt(var + eps) · aux + aux2. +// One workgroup per row. +@compute @workgroup_size(256) +fn layernorm(@builtin(workgroup_id) wg: vec3, @builtin(local_invocation_index) lid: u32) { + let row = wg.y * p.row + wg.x; + if (row >= p.a) { + return; + } + let c = p.b; + let base = row * c; + var s = 0.0; + for (var i = lid; i < c; i += 256u) { + s += src[base + i]; + } + let mean = reduce(lid, s) / f32(c); + var q = 0.0; + for (var i = lid; i < c; i += 256u) { + let d = src[base + i] - mean; + q += d * d; + } + let rstd = inverseSqrt(reduce(lid, q) / f32(c) + bitcast(p.e)); + for (var i = lid; i < c; i += 256u) { + dst[base + i] = (src[base + i] - mean) * rstd * aux[i] + aux2[i]; + } +} + +// Rotary position encoding of q and k in place, and q scaled (a: tokens, b: row stride, c: hidden = heads · 64, +// d: rows of the table, f: q scale bits). One thread per pair (x, y) of neighbouring numbers of a head: +// (x cos − y sin, y cos + x sin), cos and sin from row t % d of `aux` ([rows, 32] pairs of cos, sin). +@compute @workgroup_size(256) +fn rope(@builtin(workgroup_id) wg: vec3, @builtin(local_invocation_index) lid: u32) { + let g = flat_id(wg, lid); + if (g >= p.count) { + return; + } + let half = p.c / 2u; + let t = g / p.c; + let r = g % p.c; + let which = r / half; + let pair = r % half; + let i = t * p.b + which * p.c + 2u * pair; + let at = ((t % p.d) * 32u + pair % 32u) * 2u; + let cs = aux[at]; + let sn = aux[at + 1u]; + let x = dst[i]; + let y = dst[i + 1u]; + let scale = select(1.0, bitcast(p.f), which == 0u); + dst[i] = (x * cs - y * sn) * scale; + dst[i + 1u] = (y * cs + x * sn) * scale; +} + +// The patches as rows, in window order (a: image side, b: patch, c: grid side, d: window, e: channels): +// dst[t, (ch · patch + ky) · patch + kx] = src[ch, row · patch + ky, col · patch + kx] for the cell (row, col) of t. +@compute @workgroup_size(256) +fn im2col(@builtin(workgroup_id) wg: vec3, @builtin(local_invocation_index) lid: u32) { + let g = flat_id(wg, lid); + if (g >= p.count) { + return; + } + let side = p.a; + let size = p.b; + let grid = p.c; + let k = p.e * size * size; + let t = g / k; + let r = g % k; + let ch = r / (size * size); + let ky = r / size % size; + let kx = r % size; + // the cell of window-order token t + let win = p.d; + let w = t / (win * win); + let l = t % (win * win); + let row = w / (grid / win) * win + l / win; + let col = w % (grid / win) * win + l % win; + dst[g] = src[(ch * side + row * size + ky) * side + col * size + kx]; +} + +// Tokens in window order to channels-first (a: channels, b: grid side, c: window): dst[ch, row, col] = src[t, ch]. +@compute @workgroup_size(256) +fn to_chw(@builtin(workgroup_id) wg: vec3, @builtin(local_invocation_index) lid: u32) { + let g = flat_id(wg, lid); + if (g >= p.count) { + return; + } + let n = p.b * p.b; + let ch = g / n; + let cell = g % n; + let t = window_token(cell / p.b, cell % p.b, p.b, p.c); + dst[g] = src[t * p.a + ch]; +} diff --git a/crates/gpu/src/wgsl/sam3_pixel.wgsl b/crates/gpu/src/wgsl/sam3_pixel.wgsl new file mode 100644 index 0000000000..bc6b972cfd --- /dev/null +++ b/crates/gpu/src/wgsl/sam3_pixel.wgsl @@ -0,0 +1,161 @@ +// The small steps of the text detector's pixel decoder (`sam3/pixel.rs`) around its 3 x 3 convolutions: nearest +// up-sampling plus the neck level it is added to, and GroupNorm + ReLU (statistics per chunk of pixels, merged per +// group, then applied in place). +// +// Images are pixel rows (`[pixels, channels]`, row-major); the neck levels come channels-first, as uploaded. Same +// bindings and parameter block as `sam3_ops.wgsl`; flat dispatches cover `count` items, 256 per workgroup, workgroups +// in rows of `row`. + +struct P { + a: u32, + b: u32, + c: u32, + d: u32, + e: u32, + f: u32, + count: u32, + row: u32, +} + +@group(0) @binding(0) var p: P; +@group(0) @binding(1) var src: array; +@group(0) @binding(2) var aux: array; +@group(0) @binding(3) var aux2: array; +@group(0) @binding(4) var dst: array; + +fn flat_id(wg: vec3, lid: u32) -> u32 { + return (wg.y * p.row + wg.x) * 256u + lid; +} + +// Nearest up-sampling of the rows `src` (a: channels, c: side) to side b, plus the channels-first image `aux` +// (`[a, b, b]`): dst[row · b + col, ch] = src[(row · c / b) · c + col · c / b, ch] + aux[ch, row, col]. (candle's +// `upsample_nearest2d` takes floor(i · c / b), the same for the decoder's exact doublings.) +@compute @workgroup_size(256) +fn upsample_add(@builtin(workgroup_id) wg: vec3, @builtin(local_invocation_index) lid: u32) { + let g = flat_id(wg, lid); + if (g >= p.count) { + return; + } + let ch = g % p.a; + let pixel = g / p.a; + let row = pixel / p.b; + let col = pixel % p.b; + let at = row * p.c / p.b * p.c + col * p.c / p.b; + dst[g] = src[at * p.a + ch] + aux[ch * p.b * p.b + pixel]; +} + +var red: array; + +fn reduce(lid: u32, v: f32) -> f32 { + red[lid] = v; + workgroupBarrier(); + for (var s = 128u; s > 0u; s >>= 1u) { + if (lid < s) { + red[lid] += red[lid + s]; + } + workgroupBarrier(); + } + let total = red[0]; + workgroupBarrier(); + return total; +} + +// Thread `lid` holds channel lid's `v`: leaves the sum over each group's channels in red[group] (a: channels, +// d: groups). +fn group_sums(lid: u32, v: f32) { + red[lid] = v; + workgroupBarrier(); + let per = p.a / p.d; + var s = 0.0; + if (lid < p.d) { + for (var i = 0u; i < per; i++) { + s += red[lid * per + i]; + } + } + workgroupBarrier(); + if (lid < p.d) { + red[lid] = s; + } + workgroupBarrier(); +} + +// GroupNorm statistics of one chunk of pixels (a: channels ≤ 256, b: pixels, c: pixels per chunk, d: groups), one +// workgroup per chunk, thread = channel: each group's mean over the chunk and the sum of squared differences from +// it, at dst[(chunk · d + group) · 2 + 0 | 1]. Two passes over the chunk (the second from the cache), so a large mean +// costs no precision. +@compute @workgroup_size(256) +fn group_stats(@builtin(workgroup_id) wg: vec3, @builtin(local_invocation_index) lid: u32) { + let chunk = wg.y * p.row + wg.x; + let first = chunk * p.c; + if (first >= p.b) { + return; + } + let last = min(first + p.c, p.b); + let live = lid < p.a; + let ch = min(lid, p.a - 1u); + let per = p.a / p.d; + let n = f32((last - first) * per); + var s = 0.0; + if (live) { + for (var px = first; px < last; px++) { + s += src[px * p.a + ch]; + } + } + group_sums(lid, s); + let mean = red[ch / per] / n; + let own = red[min(lid, p.d - 1u)] / n; + workgroupBarrier(); + var q = 0.0; + if (live) { + for (var px = first; px < last; px++) { + let d = src[px * p.a + ch] - mean; + q += d * d; + } + } + group_sums(lid, q); + if (lid < p.d) { + let o = (chunk * p.d + lid) * 2u; + dst[o] = own; + dst[o + 1u] = red[lid]; + } +} + +// The chunks' statistics merged, one workgroup per group (a: chunks, b: pixels, c: pixels per chunk, d: groups, +// e: eps bits, f: channels per group): dst[group · 2 + 0 | 1] = the group's mean and 1 / sqrt(variance + eps), the +// variance biased (over all of the group's numbers), as candle's GroupNorm. +@compute @workgroup_size(256) +fn group_merge(@builtin(workgroup_id) wg: vec3, @builtin(local_invocation_index) lid: u32) { + let g = wg.x; + let total = f32(p.b * p.f); + var s = 0.0; + for (var i = lid; i < p.a; i += 256u) { + let n = f32(min(p.c, p.b - i * p.c) * p.f); + s += n * src[(i * p.d + g) * 2u]; + } + let mean = reduce(lid, s) / total; + var q = 0.0; + for (var i = lid; i < p.a; i += 256u) { + let n = f32(min(p.c, p.b - i * p.c) * p.f); + let o = (i * p.d + g) * 2u; + let d = src[o] - mean; + q += src[o + 1u] + n * d * d; + } + let variance = reduce(lid, q) / total; + if (lid == 0u) { + dst[g * 2u] = mean; + dst[g * 2u + 1u] = inverseSqrt(variance + bitcast(p.e)); + } +} + +// GroupNorm and ReLU in place on the rows `dst` (a: channels, d: groups) with the merged statistics `src`, the scale +// `aux` and the shift `aux2` (`[a]` each): dst = max((dst − mean) · rstd · aux + aux2, 0). +@compute @workgroup_size(256) +fn group_norm_relu(@builtin(workgroup_id) wg: vec3, @builtin(local_invocation_index) lid: u32) { + let g = flat_id(wg, lid); + if (g >= p.count) { + return; + } + let ch = g % p.a; + let group = ch / (p.a / p.d); + dst[g] = max((dst[g] - src[group * 2u]) * src[group * 2u + 1u] * aux[ch] + aux2[ch], 0.0); +} diff --git a/crates/gpu/tests/it/equivalence.rs b/crates/gpu/tests/it/equivalence.rs index 1e097d0ca2..7e36ba3a9c 100644 --- a/crates/gpu/tests/it/equivalence.rs +++ b/crates/gpu/tests/it/equivalence.rs @@ -1216,6 +1216,34 @@ fn windows_of_a_big_photo_share_one_uploaded_source() { assert_eq!(lightcraft_gpu::source_uploads() - start, 2); } +/// Raw decoding keeps negative channels (near-black sensor noise through a saturating camera matrix, a NIKON D780 +/// profile's): pushed and edited, the GPU renders them as the CPU does. +#[test] +fn negative_channels_match_cpu() { + if !gpu() { + return; + } + let m = [[3.48f32, -2.41, -0.06], [-0.41, 1.57, -0.16], [0.32, -1.86, 2.58]]; + let noise = |x: usize, y: usize, c: usize| { + let h = ((x * 7919 + y * 104_729 + c * 1_299_709) as u32).wrapping_mul(2_654_435_761); + (h >> 8) as f32 / (1u32 << 24) as f32 * 0.008 - 0.004 + }; + let src = Arc::new(Rgb32f::from_fn(320, 240, |x, y| { + let g = 0.0005 * 1.02f32.powi(x as i32); + let cam: [f32; 3] = std::array::from_fn(|c| g + noise(x, y, c)); + std::array::from_fn(|i| m[i][0] * cam[0] + m[i][1] * cam[1] + m[i][2] * cam[2]) + })); + assert!(src.data.iter().flatten().any(|v| *v < 0.0)); + let info = SourceInfo { raw: true, ..Default::default() }; + let req = RenderRequest::fit(320, 240); + for (name, edit) in cases() { + let mut s = DevelopSettings::default(); + edit(&mut s); + s.light.exposure += 4.0; + check(&format!("negatives +4 EV, {name}"), &src, &info, &s, &req); + } +} + /// A non-trivial 3D LUT (cross-process look: lifted blacks, warm highlights, swapped-ish blues). fn look_lut(n: usize, domain_max: f32) -> lightcraft_pipeline::lut::Lut3d { let mut data = Vec::with_capacity(n * n * n); diff --git a/crates/gpu/tests/it/main.rs b/crates/gpu/tests/it/main.rs index 1803370213..893b4b279d 100644 --- a/crates/gpu/tests/it/main.rs +++ b/crates/gpu/tests/it/main.rs @@ -8,4 +8,12 @@ mod equivalence; mod fallback; #[cfg(not(target_arch = "wasm32"))] mod gpu_probe; +#[cfg(feature = "sam")] +mod sam3_backbone; +#[cfg(feature = "sam")] +mod sam3_detr; +#[cfg(feature = "sam")] +mod sam3_mask_decoder; +#[cfg(feature = "sam")] +mod sam3_necks; mod thumbs_bench; diff --git a/crates/gpu/tests/it/sam3_backbone.rs b/crates/gpu/tests/it/sam3_backbone.rs new file mode 100644 index 0000000000..66741d6a3a --- /dev/null +++ b/crates/gpu/tests/it/sam3_backbone.rs @@ -0,0 +1,143 @@ +//! The SAM 3 backbone on the GPU against the candle backbone on the CPU (the reference), on one photo, and what the +//! difference does to the masks downstream (a click mask and a Describe mask). +//! +//! Needs the checkpoint: `LIGHTCRAFT_SAM3_DIR= cargo test --release -p lightcraft-gpu --features sam +//! --test it sam3_backbone:: -- --nocapture`. The photo is a procedural one, or the input of a reference file made by +//! `tools/sam3_reference.py` (`LIGHTCRAFT_SAM3_REF=`; then the backbone is also checked against +//! Hugging Face's). `LIGHTCRAFT_SAM3_PROMPT` names the Describe prompt (default "sky"); `LIGHTCRAFT_SAM3_GPU_F16=1` +//! stores the GPU weights as f16 (bounds as for f32 do not apply then: the errors are printed). Skipped without a +//! model or a GPU. + +use std::path::PathBuf; + +use candle_core::{Device, Tensor}; +use lightcraft_gpu::sam3::{self, Precision}; +use lightcraft_segment::{BackboneAccel, Click, INPUT, Sam3, WeightReader}; + +fn values(t: &Tensor) -> Vec { + t.to_device(&Device::Cpu).unwrap().flatten_all().unwrap().to_vec1::().unwrap() +} + +/// Max |a − b|, that relative to max |b|, and mean |a − b|. +fn errors(name: &str, a: &[f32], b: &[f32]) -> (f32, f32, f64) { + assert_eq!(a.len(), b.len(), "{name}: length"); + let scale = b.iter().fold(0f32, |m, v| m.max(v.abs())).max(1e-6); + let max = a.iter().zip(b).fold(0f32, |m, (x, y)| m.max((x - y).abs())); + let mean = a.iter().zip(b).map(|(x, y)| f64::from((x - y).abs())).sum::() / a.len().max(1) as f64; + eprintln!("{name}: max abs {max:.3e}, max rel {:.3e} (scale {scale:.2}), mean abs {mean:.3e}", max / scale); + (max, max / scale, mean) +} + +/// Intersection over union of two masks (logits > 0). +fn iou(a: &[f32], b: &[f32]) -> f32 { + // masks of different sizes are no match (`zip` would compare only the shorter's pixels) + assert_eq!(a.len(), b.len(), "mask sizes"); + let (mut both, mut either) = (0usize, 0usize); + for (x, y) in a.iter().zip(b) { + let (x, y) = (*x > 0.0, *y > 0.0); + both += usize::from(x && y); + either += usize::from(x || y); + } + if either == 0 { 1.0 } else { both as f32 / either as f32 } +} + +/// The largest |Δ| between two masks' logits, and between the masks themselves (their sigmoid, 0..1). +fn mask_diff(a: &[f32], b: &[f32]) -> (f32, f32) { + let sigmoid = |v: f32| 1.0 / (1.0 + (-v).exp()); + a.iter().zip(b).fold((0f32, 0f32), |(l, m), (x, y)| (l.max((x - y).abs()), m.max((sigmoid(*x) - sigmoid(*y)).abs()))) +} + +/// The photo as preprocessed pixels `[1, 3, 1008, 1008]`, and the reference backbone (72 × 72 tokens of 1024) if there +/// is a reference file. +fn photo() -> (Tensor, Option) { + if let Some(path) = std::env::var_os("LIGHTCRAFT_SAM3_REF").map(PathBuf::from) { + let mut r = candle_core::safetensors::load(&path, &Device::Cpu).unwrap(); + return (r.remove("pixel_values").unwrap(), r.remove("backbone")); + } + let img = lightcraft_scenes::demo_library()[0].render_fit(1600).to_srgb8(); + let rgb: Vec = img.data.iter().flat_map(|p| [p[0], p[1], p[2]]).collect(); + let px = lightcraft_segment::mask::preprocess(&rgb, img.width, img.height, INPUT).unwrap(); + (Tensor::from_vec(px, (1, 3, INPUT, INPUT), &Device::Cpu).unwrap(), None) +} + +#[test] +fn the_gpu_backbone_matches_the_cpu_backbone() { + let Some(dir) = std::env::var_os("LIGHTCRAFT_SAM3_DIR").map(PathBuf::from).filter(|d| lightcraft_segment::is_model_dir(d)) else { + lightcraft_testkit::skip!(Model, "set LIGHTCRAFT_SAM3_DIR to the SAM 3 model directory"); + return; + }; + let adapter = match sam3::adapter() { + Ok(a) => a, + // a kernel that doesn't compile is a failure, not a missing GPU + Err(e) if e.contains("did not compile") => panic!("{e}"), + Err(e) => { + lightcraft_testkit::skip!(Gpu, "no GPU for the SAM 3 kernels ({e})"); + return; + } + }; + let (pixels, reference) = photo(); + let mut cpu = Sam3::load_on(&dir, Device::Cpu).unwrap(); + let want_f16 = std::env::var("LIGHTCRAFT_SAM3_GPU_F16").is_ok_and(|v| v == "1"); + let mut gpu = if want_f16 { + let make = |w: &WeightReader| -> Result, String> { Ok(Box::new(sam3::load(w, Precision::F16)?)) }; + Sam3::load_accelerated(&dir, Device::Cpu, make).unwrap() + } else { + Sam3::load_accelerated(&dir, Device::Cpu, sam3::backbone).unwrap() + }; + assert!(gpu.backbone_device().starts_with(&adapter[..adapter.len() - 1]), "the accelerator is in use"); + // f16 weights asked for, or the fallback `sam3::backbone` takes when the f32 ones don't fit: the f16 bounds apply + let f16 = want_f16 || gpu.backbone_device().contains("f16 weights"); + if f16 { + eprintln!("f16 weights: {}", gpu.backbone_device()); + } + + let t = std::time::Instant::now(); + let mut want = cpu.encode_pixels(&pixels).unwrap(); + eprintln!("CPU backbone: {:?}", t.elapsed()); + let t = std::time::Instant::now(); + let mut got = gpu.encode_pixels(&pixels).unwrap(); + eprintln!("GPU backbone (first run): {:?} on {adapter}", t.elapsed()); + // a GPU that failed on the photo leaves it to candle, which would compare the CPU with itself + assert!(gpu.accelerated(), "the GPU backbone ran (it fell back: {:?})", gpu.backbone_fallback()); + // the bounds of `docs/gpu-pipeline.md`: f16 weights are ~20 × further off (max rel 3.8e-3, mean abs 5.4e-4 measured) + let (rel_max, mean_max) = if f16 { (1e-2, 1e-3) } else { (2e-3, 1e-4) }; + let (a, b) = (values(got.backbone()), values(want.backbone())); + let (_, rel, mean) = errors("GPU vs CPU backbone", &a, &b); + assert!(rel < rel_max && mean < mean_max, "the GPU backbone is off"); + if let Some(r) = reference { + let hf = values(&r.reshape((1, 72, 72, 1024)).unwrap().permute((0, 3, 1, 2)).unwrap()); + let (_, cpu_rel, _) = errors("CPU vs Hugging Face", &b, &hf); + let (_, gpu_rel, _) = errors("GPU vs Hugging Face", &a, &hf); + assert!(gpu_rel < rel_max && cpu_rel < 2e-3); + } + + // a click mask (the tracker head) and a Describe mask (the detector head) from both + for click in [Click { x: 0.5, y: 0.6, positive: true }, Click { x: 0.3, y: 0.3, positive: true }] { + let (m_cpu, m_gpu) = (cpu.segment_clicks(&mut want, &[click]).unwrap(), gpu.segment_clicks(&mut got, &[click]).unwrap()); + let i = iou(&m_gpu.logits, &m_cpu.logits); + let (dl, dm) = mask_diff(&m_gpu.logits, &m_cpu.logits); + eprintln!( + "click ({}, {}): mask IoU {i:.5}, max |Δ| logits {dl:.2e}, mask {dm:.2e}, score {:.4} vs {:.4}", + click.x, click.y, m_gpu.score, m_cpu.score + ); + assert!(i > 0.99, "click mask IoU {i}"); + } + let prompt = std::env::var("LIGHTCRAFT_SAM3_PROMPT").unwrap_or_else(|_| "sky".into()); + let (d_cpu, d_gpu) = (cpu.segment_text(&mut want, &prompt, 0.5).unwrap(), gpu.segment_text(&mut got, &prompt, 0.5).unwrap()); + match (d_cpu, d_gpu) { + (Some(c), Some(g)) => { + let i = iou(&g.logits, &c.logits); + let (dl, dm) = mask_diff(&g.logits, &c.logits); + let cover = c.logits.iter().filter(|v| **v > 0.0).count() as f32 / c.logits.len() as f32; + eprintln!( + "describe {prompt:?}: mask IoU {i:.5} (covers {:.1} %), max |Δ| logits {dl:.2e}, mask {dm:.2e}, score {:.4} vs {:.4}", + cover * 100.0, + g.score, + c.score + ); + assert!(i > 0.98, "describe mask IoU {i}"); + } + (None, None) => eprintln!("describe {prompt:?}: nothing found by either"), + (c, g) => panic!("describe {prompt:?}: CPU found {}, GPU {}", c.is_some(), g.is_some()), + } +} diff --git a/crates/gpu/tests/it/sam3_detr.rs b/crates/gpu/tests/it/sam3_detr.rs new file mode 100644 index 0000000000..69e2355626 --- /dev/null +++ b/crates/gpu/tests/it/sam3_detr.rs @@ -0,0 +1,182 @@ +//! The text detector's DETR encoder on the GPU against the candle encoder (the reference), on one photo: the encoder +//! memory, and what the difference does to the detector's outputs (per-query logits, presence, boxes and the merged +//! Describe mask) for a few prompts. Both models get the same backbone output (one GPU backbone, shared), so only the +//! encoder differs. +//! +//! Needs the checkpoint: `LIGHTCRAFT_SAM3_DIR= cargo test --release -p lightcraft-gpu --features sam +//! --test it sam3_detr:: -- --nocapture`. The photo is a procedural one, or the input of a reference file made by +//! `tools/sam3_reference.py` (`LIGHTCRAFT_SAM3_REF=`). `LIGHTCRAFT_SAM3_PROMPTS` lists the prompts, +//! comma-separated (default "person,sky,the red car"). Skipped without a model or a GPU. + +use std::path::PathBuf; +use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::time::Instant; + +use candle_core::{Device, Tensor}; +use lightcraft_gpu::sam3::{self, Precision, Sam3Gpu}; +use lightcraft_segment::{BackboneAccel, DetectorOutput, INPUT, Sam3, WeightReader}; + +fn values(t: &Tensor) -> Vec { + t.to_device(&Device::Cpu).unwrap().flatten_all().unwrap().to_vec1::().unwrap() +} + +/// Max |a − b|, that relative to max |b|, and mean |a − b|. +fn errors(name: &str, a: &[f32], b: &[f32]) -> (f32, f32, f64) { + assert_eq!(a.len(), b.len(), "{name}: length"); + let scale = b.iter().fold(0f32, |m, v| m.max(v.abs())).max(1e-6); + let max = a.iter().zip(b).fold(0f32, |m, (x, y)| m.max((x - y).abs())); + let mean = a.iter().zip(b).map(|(x, y)| f64::from((x - y).abs())).sum::() / a.len().max(1) as f64; + eprintln!(" {name}: max abs {max:.3e}, max rel {:.3e} (scale {scale:.2}), mean abs {mean:.3e}", max / scale); + (max, max / scale, mean) +} + +/// Intersection over union of two masks (logits > 0). +fn iou(a: &[f32], b: &[f32]) -> f32 { + // masks of different sizes are no match (`zip` would compare only the shorter's pixels) + assert_eq!(a.len(), b.len(), "mask sizes"); + let (mut both, mut either) = (0usize, 0usize); + for (x, y) in a.iter().zip(b) { + let (x, y) = (*x > 0.0, *y > 0.0); + both += usize::from(x && y); + either += usize::from(x || y); + } + if either == 0 { 1.0 } else { both as f32 / either as f32 } +} + +fn sigmoid(x: f32) -> f32 { + 1.0 / (1.0 + (-x).exp()) +} + +/// The Describe mask of `out` as `Sam3::segment_text` merges it at 0.5 (the per-pixel maximum over the instances +/// scoring above it), and how many instances that is. +fn merged(out: &DetectorOutput) -> (Vec, usize) { + let masks = values(&out.masks); + let side = lightcraft_segment::MASK_SIDE * lightcraft_segment::MASK_SIDE; + let mut merged = vec![f32::MIN; side]; + let keep: Vec = (0..out.logits.len()).filter(|&i| sigmoid(out.logits[i]) * sigmoid(out.presence) > 0.5).collect(); + for i in &keep { + for (m, v) in merged.iter_mut().zip(&masks[i * side..(i + 1) * side]) { + *m = m.max(*v); + } + } + (merged, keep.len()) +} + +/// The photo as preprocessed pixels `[1, 3, 1008, 1008]`. +fn photo() -> Tensor { + if let Some(path) = std::env::var_os("LIGHTCRAFT_SAM3_REF").map(PathBuf::from) { + let mut r = candle_core::safetensors::load(&path, &Device::Cpu).unwrap(); + return r.remove("pixel_values").unwrap(); + } + let img = lightcraft_scenes::demo_library()[0].render_fit(1600).to_srgb8(); + let rgb: Vec = img.data.iter().flat_map(|p| [p[0], p[1], p[2]]).collect(); + let px = lightcraft_segment::mask::preprocess(&rgb, img.width, img.height, INPUT).unwrap(); + Tensor::from_vec(px, (1, 3, INPUT, INPUT), &Device::Cpu).unwrap() +} + +/// One GPU backbone for both models; the DETR encoder only for one of them (`asked` counts the calls). +struct Shared { + gpu: Arc, + detr: bool, + asked: Arc, +} + +impl BackboneAccel for Shared { + fn forward(&self, pixels: &[f32]) -> Result, String> { + self.gpu.forward(pixels) + } + + fn device(&self) -> String { + self.gpu.device() + } + + fn runs_detr_encoder(&self) -> bool { + true + } + fn detr_encoder(&self, image: &[f32], pos: &[f32], text: &[f32], valid: &[bool]) -> Result, String> { + self.asked.fetch_add(1, Ordering::Relaxed); + if self.detr { self.gpu.detr_encoder(image, pos, text, valid) } else { Err("left to candle for the comparison".into()) } + } +} + +#[test] +fn the_gpu_detr_encoder_matches_the_candle_encoder() { + let Some(dir) = std::env::var_os("LIGHTCRAFT_SAM3_DIR").map(PathBuf::from).filter(|d| lightcraft_segment::is_model_dir(d)) else { + lightcraft_testkit::skip!(Model, "set LIGHTCRAFT_SAM3_DIR to the SAM 3 model directory"); + return; + }; + let adapter = match sam3::adapter() { + Ok(a) => a, + // a kernel that doesn't compile is a failure, not a missing GPU + Err(e) if e.contains("did not compile") => panic!("{e}"), + Err(e) => { + lightcraft_testkit::skip!(Gpu, "no GPU for the SAM 3 kernels ({e})"); + return; + } + }; + let gpu = Arc::new(sam3::load(&WeightReader::open(&dir).unwrap(), Precision::F32).unwrap()); + let (asked_cpu, asked_gpu) = (Arc::new(AtomicUsize::new(0)), Arc::new(AtomicUsize::new(0))); + let with = |detr: bool, asked: &Arc| { + let (gpu, asked) = (gpu.clone(), asked.clone()); + move |_: &WeightReader| -> Result, String> { Ok(Box::new(Shared { gpu, detr, asked })) } + }; + let mut cpu = Sam3::load_accelerated(&dir, Device::Cpu, with(false, &asked_cpu)).unwrap(); + let mut acc = Sam3::load_accelerated(&dir, Device::Cpu, with(true, &asked_gpu)).unwrap(); + let pixels = photo(); + let mut enc_cpu = cpu.encode_pixels(&pixels).unwrap(); + let mut enc_acc = acc.encode_pixels(&pixels).unwrap(); + assert_eq!(values(enc_cpu.backbone()), values(enc_acc.backbone()), "the same backbone output for both"); + + let prompts = std::env::var("LIGHTCRAFT_SAM3_PROMPTS").unwrap_or_else(|_| "person,sky,the red car".into()); + let prompts: Vec<&str> = prompts.split(',').map(str::trim).filter(|p| !p.is_empty()).collect(); + for (n, prompt) in prompts.iter().copied().enumerate() { + let t = Instant::now(); + let want = cpu.detect(&mut enc_cpu, prompt).unwrap(); + let cpu_time = t.elapsed(); + let t = Instant::now(); + let got = acc.detect(&mut enc_acc, prompt).unwrap(); + let gpu_time = t.elapsed(); + let first = if n == 0 { " (first prompt: with the detector neck and loading)" } else { "" }; + eprintln!("{prompt:?}: detector with the candle encoder {cpu_time:?}, with the GPU encoder {gpu_time:?}{first}"); + assert_eq!(acc.detr_fallback(), None, "the GPU encoder ran"); + assert!(cpu.detr_fallback().is_some_and(|w| w.contains("left to candle"))); + + let (_, rel, mean) = errors("memory", &values(&got.memory), &values(&want.memory)); + assert!(rel < 1e-3 && mean < 1e-4, "the GPU encoder memory is off"); + let (logits, _, _) = errors("query logits", &got.logits, &want.logits); + let presence = (got.presence - want.presence).abs(); + let boxes = got.boxes.iter().flatten().zip(want.boxes.iter().flatten()).fold(0f32, |m, (a, b)| m.max((a - b).abs())); + let ((mask_g, kept_g), (mask_c, kept_c)) = (merged(&got), merged(&want)); + let i = iou(&mask_g, &mask_c); + eprintln!( + " presence {:.4} vs {:.4} (logit diff {presence:.2e}), boxes max diff {boxes:.2e}, instances {kept_g} vs {kept_c}, mask IoU {i:.5}", + sigmoid(got.presence), + sigmoid(want.presence) + ); + // every query's mask, not only the merged ones: the largest |Δ| of the logits and of the masks (sigmoid, 0..1) + let (dl, dm) = values(&got.masks) + .iter() + .zip(&values(&want.masks)) + .fold((0f32, 0f32), |(l, m), (a, b)| (l.max((a - b).abs()), m.max((sigmoid(*a) - sigmoid(*b)).abs()))); + eprintln!(" masks of all {} queries: max |Δ| logits {dl:.2e}, mask {dm:.2e}", got.logits.len()); + assert!(logits < 0.05 && presence < 0.05 && boxes < 1e-2, "the detector outputs moved"); + assert_eq!(kept_g, kept_c, "the same instances"); + assert!(i > 0.99, "describe mask IoU {i}"); + } + // an accelerator that failed on the encoder once isn't asked again + assert_eq!(asked_cpu.load(Ordering::Relaxed), 1); + assert_eq!(asked_gpu.load(Ordering::Relaxed), prompts.len()); + + // the encoder alone (with the uploads and the read-back) + let (image, pos, text) = (vec![0.1f32; 5184 * 256], vec![0.2f32; 5184 * 256], vec![0.3f32; 32 * 256]); + let valid: Vec = (0..32).map(|i| i < 4).collect(); + let mut best = f64::MAX; + for _ in 0..5 { + let t = Instant::now(); + gpu.detr_encoder(&image, &pos, &text, &valid).unwrap(); + best = best.min(t.elapsed().as_secs_f64()); + } + let (w, b) = gpu.detr_bytes().unwrap(); + eprintln!("GPU DETR encoder alone: {:.1} ms on {adapter}; {:.0} MB weights, {:.0} MB work buffers", best * 1e3, w as f64 / 1e6, b as f64 / 1e6); +} diff --git a/crates/gpu/tests/it/sam3_mask_decoder.rs b/crates/gpu/tests/it/sam3_mask_decoder.rs new file mode 100644 index 0000000000..09520ebea9 --- /dev/null +++ b/crates/gpu/tests/it/sam3_mask_decoder.rs @@ -0,0 +1,287 @@ +//! The text detector's mask decoder on the GPU against the candle decoder (the reference), on one photo: the per-query +//! mask logits of all 200 queries, and the merged Describe mask, for a few prompts. Both models get the same backbone +//! output, necks and DETR encoder memory (one GPU accelerator, shared), so only the mask decoder differs. For the first +//! prompt, the instance features also against the decoder transcribed with candle's tensor ops in f64 (and in f32, to +//! show how far candle's own f32 decoder is from it). +//! +//! Needs the checkpoint: `LIGHTCRAFT_SAM3_DIR= cargo test --release -p lightcraft-gpu --features sam +//! --test it sam3_mask_decoder:: -- --nocapture`. The photo is a procedural one, or the input of a reference file made by +//! `tools/sam3_reference.py` (`LIGHTCRAFT_SAM3_REF=`). `LIGHTCRAFT_SAM3_PROMPTS` lists the prompts, +//! comma-separated (default "person,sky,the red car"). Skipped without a model or a GPU. + +use std::path::PathBuf; +use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::time::Instant; + +use candle_core::{Device, Tensor}; +use lightcraft_gpu::sam3::{self, Precision, Sam3Gpu}; +use lightcraft_segment::{BackboneAccel, DetectorOutput, INPUT, NeckKind, Sam3, WeightReader}; + +fn values(t: &Tensor) -> Vec { + t.to_device(&Device::Cpu).unwrap().flatten_all().unwrap().to_vec1::().unwrap() +} + +/// Max |a − b|, that relative to max |b|, and mean |a − b|. +fn errors(name: &str, a: &[f32], b: &[f32]) -> (f32, f32, f64) { + assert_eq!(a.len(), b.len(), "{name}: length"); + let scale = b.iter().fold(0f32, |m, v| m.max(v.abs())).max(1e-6); + let max = a.iter().zip(b).fold(0f32, |m, (x, y)| m.max((x - y).abs())); + let mean = a.iter().zip(b).map(|(x, y)| f64::from((x - y).abs())).sum::() / a.len().max(1) as f64; + eprintln!(" {name}: max abs {max:.3e}, max rel {:.3e} (scale {scale:.2}), mean abs {mean:.3e}", max / scale); + (max, max / scale, mean) +} + +/// Intersection over union of two masks (logits > 0). +fn iou(a: &[f32], b: &[f32]) -> f32 { + // masks of different sizes are no match (`zip` would compare only the shorter's pixels) + assert_eq!(a.len(), b.len(), "mask sizes"); + let (mut both, mut either) = (0usize, 0usize); + for (x, y) in a.iter().zip(b) { + let (x, y) = (*x > 0.0, *y > 0.0); + both += usize::from(x && y); + either += usize::from(x || y); + } + if either == 0 { 1.0 } else { both as f32 / either as f32 } +} + +fn sigmoid(x: f32) -> f32 { + 1.0 / (1.0 + (-x).exp()) +} + +/// The Describe mask of `out` as `Sam3::segment_text` merges it at 0.5 (the per-pixel maximum over the instances +/// scoring above it), the instances, and the best-scoring query. +fn merged(out: &DetectorOutput, masks: &[f32]) -> (Vec, Vec, usize) { + let side = lightcraft_segment::MASK_SIDE * lightcraft_segment::MASK_SIDE; + let mut merged = vec![f32::MIN; side]; + let keep: Vec = (0..out.logits.len()).filter(|&i| sigmoid(out.logits[i]) * sigmoid(out.presence) > 0.5).collect(); + for i in &keep { + for (m, v) in merged.iter_mut().zip(&masks[i * side..(i + 1) * side]) { + *m = m.max(*v); + } + } + let best = (0..out.logits.len()).max_by(|a, b| out.logits[*a].total_cmp(&out.logits[*b])).unwrap(); + (merged, keep, best) +} + +/// The photo as preprocessed pixels `[1, 3, 1008, 1008]`. +fn photo() -> Tensor { + if let Some(path) = std::env::var_os("LIGHTCRAFT_SAM3_REF").map(PathBuf::from) { + let mut r = candle_core::safetensors::load(&path, &Device::Cpu).unwrap(); + return r.remove("pixel_values").unwrap(); + } + let img = lightcraft_scenes::demo_library()[0].render_fit(1600).to_srgb8(); + let rgb: Vec = img.data.iter().flat_map(|p| [p[0], p[1], p[2]]).collect(); + let px = lightcraft_segment::mask::preprocess(&rgb, img.width, img.height, INPUT).unwrap(); + Tensor::from_vec(px, (1, 3, INPUT, INPUT), &Device::Cpu).unwrap() +} + +/// The mask decoder transcribed with candle's tensor ops in `dtype` (f64: the arbiter between the two f32 decoders): +/// the instance features `[256, 288 · 288]` for the encoder memory `[5184, 256]`, the prompt `[32, 256]` (`valid`: its +/// real tokens) and the neck levels `[256, 144, 144]`, `[256, 288, 288]`. +fn decoder_ref(w: &WeightReader, memory: &Tensor, (text, valid): (&Tensor, &[bool]), [l1, l0]: [&Tensor; 2], dtype: candle_core::DType) -> Tensor { + let get = |name: &str| { + let (shape, data) = w.read(&format!("detector_model.mask_decoder.{name}")).unwrap(); + Tensor::from_vec(data, shape, &Device::Cpu).unwrap().to_dtype(dtype).unwrap() + }; + let lin = |x: &Tensor, name: &str| { + x.matmul(&get(&format!("{name}.weight")).t().unwrap()).unwrap().broadcast_add(&get(&format!("{name}.bias"))).unwrap() + }; + let (memory, text) = (memory.to_dtype(dtype).unwrap(), text.to_dtype(dtype).unwrap()); + // prompt attention: LN (eps 1e-5) → 8 heads of 32 over the prompt (padding masked) → output projection, added + let mean = memory.mean_keepdim(1).unwrap(); + let centred = memory.broadcast_sub(&mean).unwrap(); + let var = centred.sqr().unwrap().mean_keepdim(1).unwrap(); + let h = centred.broadcast_div(&(var + 1e-5).unwrap().sqrt().unwrap()).unwrap(); + let h = h.broadcast_mul(&get("prompt_cross_attn_norm.weight")).unwrap().broadcast_add(&get("prompt_cross_attn_norm.bias")).unwrap(); + let heads = |x: Tensor| x.reshape((x.dim(0).unwrap(), 8, 32)).unwrap().transpose(0, 1).unwrap().contiguous().unwrap(); + let q = heads(lin(&h, "prompt_cross_attn.q_proj")); + let k = heads(lin(&text, "prompt_cross_attn.k_proj")); + let v = heads(lin(&text, "prompt_cross_attn.v_proj")); + let bias: Vec = valid.iter().map(|&ok| if ok { 0.0 } else { f32::MIN }).collect(); + let bias = Tensor::from_vec(bias, (1, 1, 32), &Device::Cpu).unwrap().to_dtype(dtype).unwrap(); + let s = (q.matmul(&k.t().unwrap()).unwrap() * (32f64).powf(-0.5)).unwrap().broadcast_add(&bias).unwrap(); + let e = s.broadcast_sub(&s.max_keepdim(2).unwrap()).unwrap().exp().unwrap(); + let p = e.broadcast_div(&e.sum_keepdim(2).unwrap()).unwrap(); + let o = p.matmul(&v).unwrap().transpose(0, 1).unwrap().reshape((5184, 256)).unwrap(); + let mem = (memory + lin(&o, "prompt_cross_attn.o_proj")).unwrap(); + // the pixel decoder + let mut prev = mem.t().unwrap().reshape((1, 256, 72, 72)).unwrap(); + for (i, skip) in [l1, l0].into_iter().enumerate() { + let side = skip.dim(1).unwrap(); + prev = (prev.upsample_nearest2d(side, side).unwrap() + skip.to_dtype(dtype).unwrap().unsqueeze(0).unwrap()).unwrap(); + let c = format!("pixel_decoder.conv_layers.{i}"); + prev = prev + .conv2d(&get(&format!("{c}.weight")), 1, 1, 1, 1) + .unwrap() + .broadcast_add(&get(&format!("{c}.bias")).reshape((1, 256, 1, 1)).unwrap()) + .unwrap(); + let g = prev.reshape((8, 32 * side * side)).unwrap(); + let centred = g.broadcast_sub(&g.mean_keepdim(1).unwrap()).unwrap(); + let var = centred.sqr().unwrap().mean_keepdim(1).unwrap(); + let normed = centred.broadcast_div(&(var + 1e-5).unwrap().sqrt().unwrap()).unwrap().reshape((1, 256, side, side)).unwrap(); + let n = format!("pixel_decoder.norms.{i}"); + let (gamma, beta) = + (get(&format!("{n}.weight")).reshape((1, 256, 1, 1)).unwrap(), get(&format!("{n}.bias")).reshape((1, 256, 1, 1)).unwrap()); + prev = normed.broadcast_mul(&gamma).unwrap().broadcast_add(&beta).unwrap().relu().unwrap(); + } + let inst = prev.conv2d(&get("instance_projection.weight"), 0, 1, 1, 1).unwrap(); + inst.broadcast_add(&get("instance_projection.bias").reshape((1, 256, 1, 1)).unwrap()).unwrap().reshape((256, 288 * 288)).unwrap() +} + +/// One GPU accelerator for both models; the mask decoder only for one of them, the other gets a result of the wrong +/// size (and then runs the candle decoder; `asked` counts the calls). +struct Shared { + gpu: Arc, + masks: bool, + asked: Arc, +} + +impl BackboneAccel for Shared { + fn forward(&self, pixels: &[f32]) -> Result, String> { + self.gpu.forward(pixels) + } + + fn device(&self) -> String { + self.gpu.device() + } + + fn runs_necks(&self) -> bool { + true + } + + fn runs_detr_encoder(&self) -> bool { + true + } + + fn runs_mask_decoder(&self) -> bool { + true + } + + fn neck(&self, which: NeckKind, backbone: &[f32], n: usize) -> Result>, String> { + self.gpu.neck(which, backbone, n) + } + + fn detr_encoder(&self, image: &[f32], pos: &[f32], text: &[f32], valid: &[bool]) -> Result, String> { + self.gpu.detr_encoder(image, pos, text, valid) + } + + fn mask_decoder( + &self, + memory: &[f32], + text: &[f32], + valid: &[bool], + levels: [&[f32]; 2], + rows: &[f32], + bias: &[f32], + ) -> Result, String> { + self.asked.fetch_add(1, Ordering::Relaxed); + if self.masks { self.gpu.mask_decoder(memory, text, valid, levels, rows, bias) } else { Ok(vec![0.0; 10]) } + } +} + +#[test] +fn the_gpu_mask_decoder_matches_the_candle_decoder() { + let Some(dir) = std::env::var_os("LIGHTCRAFT_SAM3_DIR").map(PathBuf::from).filter(|d| lightcraft_segment::is_model_dir(d)) else { + lightcraft_testkit::skip!(Model, "set LIGHTCRAFT_SAM3_DIR to the SAM 3 model directory"); + return; + }; + let adapter = match sam3::adapter() { + Ok(a) => a, + // a kernel that doesn't compile is a failure, not a missing GPU + Err(e) if e.contains("did not compile") => panic!("{e}"), + Err(e) => { + lightcraft_testkit::skip!(Gpu, "no GPU for the SAM 3 kernels ({e})"); + return; + } + }; + let gpu = Arc::new(sam3::load(&WeightReader::open(&dir).unwrap(), Precision::F32).unwrap()); + let (asked_cpu, asked_gpu) = (Arc::new(AtomicUsize::new(0)), Arc::new(AtomicUsize::new(0))); + let with = |masks: bool, asked: &Arc| { + let (gpu, asked) = (gpu.clone(), asked.clone()); + move |_: &WeightReader| -> Result, String> { Ok(Box::new(Shared { gpu, masks, asked })) } + }; + let mut cpu = Sam3::load_accelerated(&dir, Device::Cpu, with(false, &asked_cpu)).unwrap(); + let mut acc = Sam3::load_accelerated(&dir, Device::Cpu, with(true, &asked_gpu)).unwrap(); + let pixels = photo(); + let mut enc_cpu = cpu.encode_pixels(&pixels).unwrap(); + let mut enc_acc = acc.encode_pixels(&pixels).unwrap(); + + let prompts = std::env::var("LIGHTCRAFT_SAM3_PROMPTS").unwrap_or_else(|_| "person,sky,the red car".into()); + let prompts: Vec<&str> = prompts.split(',').map(str::trim).filter(|p| !p.is_empty()).collect(); + for (n, prompt) in prompts.iter().copied().enumerate() { + let t = Instant::now(); + let want = cpu.detect(&mut enc_cpu, prompt).unwrap(); + let cpu_time = t.elapsed(); + let t = Instant::now(); + let got = acc.detect(&mut enc_acc, prompt).unwrap(); + let gpu_time = t.elapsed(); + let first = if n == 0 { " (first prompt: with the detector neck and loading)" } else { "" }; + eprintln!("{prompt:?}: detector with the candle mask decoder {cpu_time:?}, with the GPU one {gpu_time:?}{first}"); + assert_eq!(acc.mask_fallback(), None, "the GPU mask decoder ran"); + assert!(cpu.mask_fallback().is_some_and(|w| w.contains("returned 10 values"))); + assert_eq!(acc.heads_device(), "CPU; the necks, the DETR encoder and the mask decoder on the GPU"); + assert_eq!(cpu.heads_device(), "CPU; the necks and the DETR encoder on the GPU"); + + if n == 0 { + // the instance features (the instance projection as the rows) against the f64 transcription, and how far + // the same transcription in f32 is from it + let reader = WeightReader::open(&dir).unwrap(); + let (_, valid) = lightcraft_segment::tokenizer::Tokenizer::load(&dir).unwrap().encode(prompt); + let levels = acc.neck_levels(NeckKind::Detector, &enc_acc).unwrap(); + let (l1, l0) = (levels[1].squeeze(0).unwrap(), levels[0].squeeze(0).unwrap()); + let (memory, text) = (got.memory.squeeze(0).unwrap(), got.text.squeeze(0).unwrap()); + let (_, rows) = reader.read("detector_model.mask_decoder.instance_projection.weight").unwrap(); + let (_, bias) = reader.read("detector_model.mask_decoder.instance_projection.bias").unwrap(); + let t = Instant::now(); + let ours = gpu.mask_decoder(&values(&memory), &values(&text), &valid, [&values(&l1), &values(&l0)], &rows, &bias).unwrap(); + eprintln!(" GPU instance features {:?}", t.elapsed()); + let t = Instant::now(); + let f64_ref: Vec = values( + &decoder_ref(&reader, &memory, (&text, &valid), [&l1, &l0], candle_core::DType::F64).to_dtype(candle_core::DType::F32).unwrap(), + ); + let f32_ref = values(&decoder_ref(&reader, &memory, (&text, &valid), [&l1, &l0], candle_core::DType::F32)); + eprintln!(" references {:?}", t.elapsed()); + let (_, rel, mean) = errors("instance features, GPU vs f64", &ours, &f64_ref); + errors("instance features, candle f32 vs f64", &f32_ref, &f64_ref); + assert!(rel < 1e-4 && mean < 1e-5, "the GPU instance features are off"); + } + + // the same memory and decoder for both: only the masks may differ, by candle's own error (its f32 decoder is + // ~400 × further from the f64 one than the GPU's, above) + let (_, logits, _) = errors("query logits", &got.logits, &want.logits); + assert!(logits < 1e-4, "the query logits moved"); + let (mg, mc) = (values(&got.masks), values(&want.masks)); + let (_, rel, mean) = errors("mask logits (200 queries), GPU vs candle", &mg, &mc); + assert!(rel < 1e-2 && mean < 0.1, "the GPU mask logits are off"); + let ((mask_g, kept_g, best_g), (mask_c, kept_c, best_c)) = (merged(&got, &mg), merged(&want, &mc)); + let side = lightcraft_segment::MASK_SIDE * lightcraft_segment::MASK_SIDE; + let best = iou(&mg[best_g * side..(best_g + 1) * side], &mc[best_c * side..(best_c + 1) * side]); + let i = iou(&mask_g, &mask_c); + eprintln!(" instances {} vs {}, Describe mask IoU {i:.5}, best query's mask IoU {best:.5}", kept_g.len(), kept_c.len()); + assert_eq!(kept_g, kept_c, "the same instances"); + assert!(i > 0.99 && best > 0.99, "describe mask IoU {i}, best query {best}"); + // the semantic mask (one more row of the GPU's mask product) + let (_, rel, mean) = errors("semantic mask logits, GPU vs candle", &got.semantic, &want.semantic); + let semantic = iou(&got.semantic, &want.semantic); + eprintln!(" semantic mask IoU {semantic:.5}"); + assert!(rel < 1e-2 && mean < 0.1 && semantic > 0.99, "the GPU semantic mask is off"); + } + // an accelerator whose decoder failed once isn't asked again + assert_eq!(asked_cpu.load(Ordering::Relaxed), 1); + assert_eq!(asked_gpu.load(Ordering::Relaxed), prompts.len()); + + // the decoder alone (with the uploads and the read-back) + let (memory, text) = (vec![0.1f32; 5184 * 256], vec![0.3f32; 32 * 256]); + let valid: Vec = (0..32).map(|i| i < 4).collect(); + let (l1, l0) = (vec![0.2f32; 256 * 144 * 144], vec![0.4f32; 256 * 288 * 288]); + let (rows, bias) = (vec![0.01f32; 200 * 256], vec![0.5f32; 200]); + let mut best = f64::MAX; + for _ in 0..5 { + let t = Instant::now(); + gpu.mask_decoder(&memory, &text, &valid, [&l1, &l0], &rows, &bias).unwrap(); + best = best.min(t.elapsed().as_secs_f64()); + } + let (w, b) = gpu.mask_decoder_bytes().unwrap(); + eprintln!("GPU mask decoder alone: {:.1} ms on {adapter}; {:.0} MB weights, {:.0} MB work buffers", best * 1e3, w as f64 / 1e6, b as f64 / 1e6); +} diff --git a/crates/gpu/tests/it/sam3_necks.rs b/crates/gpu/tests/it/sam3_necks.rs new file mode 100644 index 0000000000..8529162de7 --- /dev/null +++ b/crates/gpu/tests/it/sam3_necks.rs @@ -0,0 +1,165 @@ +//! SAM 3's two necks on the GPU against the candle necks on the CPU (the reference), on one photo: every level, and +//! what the difference does to the masks downstream (click masks and a Describe mask). Both models get the same +//! GPU backbone output, so only the necks differ. +//! +//! Needs the checkpoint: `LIGHTCRAFT_SAM3_DIR= cargo test --release -p lightcraft-gpu --features sam +//! --test it sam3_necks:: -- --nocapture`. `LIGHTCRAFT_SAM3_PROMPT` names the Describe prompt (default "sky"). Skipped +//! without a model or a GPU. + +use std::path::PathBuf; +use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::time::Instant; + +use candle_core::{Device, Tensor}; +use lightcraft_gpu::sam3::{self, Precision, Sam3Gpu}; +use lightcraft_segment::{BackboneAccel, Click, INPUT, NeckKind, Sam3}; + +fn values(t: &Tensor) -> Vec { + t.to_device(&Device::Cpu).unwrap().flatten_all().unwrap().to_vec1::().unwrap() +} + +/// Max |a − b|, that relative to max |b|, and mean |a − b|. +fn errors(name: &str, a: &[f32], b: &[f32]) -> (f32, f32, f64) { + assert_eq!(a.len(), b.len(), "{name}: length"); + let scale = b.iter().fold(0f32, |m, v| m.max(v.abs())).max(1e-6); + let max = a.iter().zip(b).fold(0f32, |m, (x, y)| m.max((x - y).abs())); + let mean = a.iter().zip(b).map(|(x, y)| f64::from((x - y).abs())).sum::() / a.len().max(1) as f64; + eprintln!("{name}: max abs {max:.3e}, max rel {:.3e} (scale {scale:.2}), mean abs {mean:.3e}", max / scale); + (max, max / scale, mean) +} + +/// Intersection over union of two masks (logits > 0). +fn iou(a: &[f32], b: &[f32]) -> f32 { + // masks of different sizes are no match (`zip` would compare only the shorter's pixels) + assert_eq!(a.len(), b.len(), "mask sizes"); + let (mut both, mut either) = (0usize, 0usize); + for (x, y) in a.iter().zip(b) { + let (x, y) = (*x > 0.0, *y > 0.0); + both += usize::from(x && y); + either += usize::from(x || y); + } + if either == 0 { 1.0 } else { both as f32 / either as f32 } +} + +/// The largest |Δ| between two masks' logits, and between the masks themselves (their sigmoid, 0..1). +fn mask_diff(a: &[f32], b: &[f32]) -> (f32, f32) { + let sigmoid = |v: f32| 1.0 / (1.0 + (-v).exp()); + a.iter().zip(b).fold((0f32, 0f32), |(l, m), (x, y)| (l.max((x - y).abs()), m.max((sigmoid(*x) - sigmoid(*y)).abs()))) +} + +/// One GPU backbone for both models: with its necks (counting the levels it hands out), or without (candle's run). +struct Shared { + gpu: Arc, + necks: bool, + runs: Arc, +} + +impl BackboneAccel for Shared { + fn forward(&self, pixels: &[f32]) -> Result, String> { + self.gpu.forward(pixels) + } + fn device(&self) -> String { + self.gpu.device() + } + fn runs_necks(&self) -> bool { + true + } + fn neck(&self, which: NeckKind, backbone: &[f32], n: usize) -> Result>, String> { + if !self.necks { + return Err("necks off".into()); + } + let levels = self.gpu.neck(which, backbone, n)?; + self.runs.fetch_add(1, Ordering::Relaxed); + Ok(levels) + } +} + +#[test] +fn the_gpu_necks_match_the_cpu_necks() { + let Some(dir) = std::env::var_os("LIGHTCRAFT_SAM3_DIR").map(PathBuf::from).filter(|d| lightcraft_segment::is_model_dir(d)) else { + lightcraft_testkit::skip!(Model, "set LIGHTCRAFT_SAM3_DIR to the SAM 3 model directory"); + return; + }; + let adapter = match sam3::adapter() { + Ok(a) => a, + // a kernel that doesn't compile is a failure, not a missing GPU + Err(e) if e.contains("did not compile") => panic!("{e}"), + Err(e) => { + lightcraft_testkit::skip!(Gpu, "no GPU for the SAM 3 kernels ({e})"); + return; + } + }; + let img = lightcraft_scenes::demo_library()[0].render_fit(1600).to_srgb8(); + let rgb: Vec = img.data.iter().flat_map(|p| [p[0], p[1], p[2]]).collect(); + let px = lightcraft_segment::mask::preprocess(&rgb, img.width, img.height, INPUT).unwrap(); + let pixels = Tensor::from_vec(px, (1, 3, INPUT, INPUT), &Device::Cpu).unwrap(); + + let reader = lightcraft_segment::WeightReader::open(&dir).unwrap(); + let gpu = Arc::new(sam3::load(&reader, Precision::F32).unwrap()); + let runs = Arc::new(AtomicUsize::new(0)); + let accel = |necks: bool| { + let shared = Shared { gpu: gpu.clone(), necks, runs: runs.clone() }; + move |_: &lightcraft_segment::WeightReader| -> Result, String> { Ok(Box::new(shared)) } + }; + let mut cpu = Sam3::load_accelerated(&dir, Device::Cpu, accel(false)).unwrap(); + let mut on_gpu = Sam3::load_accelerated(&dir, Device::Cpu, accel(true)).unwrap(); + let mut want = cpu.encode_pixels(&pixels).unwrap(); + let mut got = on_gpu.encode_pixels(&pixels).unwrap(); + assert_eq!(values(want.backbone()), values(got.backbone()), "the same backbone output for both"); + + for which in [NeckKind::Tracker, NeckKind::Detector] { + let t = Instant::now(); + let reference = cpu.neck_levels(which, &want).unwrap(); + eprintln!("{which:?} neck, CPU: {:?}", t.elapsed()); + let before = runs.load(Ordering::Relaxed); + let t = Instant::now(); + let levels = on_gpu.neck_levels(which, &got).unwrap(); + eprintln!("{which:?} neck, GPU (first, builds it): {:?} on {adapter}", t.elapsed()); + let t = Instant::now(); + on_gpu.neck_levels(which, &got).unwrap(); + eprintln!("{which:?} neck, GPU (again): {:?}", t.elapsed()); + assert_eq!(runs.load(Ordering::Relaxed), before + 2, "{which:?}: the GPU neck ran"); + for (i, (g, c)) in levels.iter().zip(&reference).enumerate() { + assert_eq!(g.dims(), c.dims(), "{which:?} level {i}"); + let (_, rel, mean) = errors(&format!("{which:?} level {i}"), &values(g), &values(c)); + assert!(rel < 1e-4 && mean < 1e-5, "{which:?} level {i} is off"); + } + } + + // a click mask (the tracker head) and a Describe mask (the detector head) from both + for click in [Click { x: 0.5, y: 0.6, positive: true }, Click { x: 0.3, y: 0.3, positive: true }] { + let (m_cpu, m_gpu) = (cpu.segment_clicks(&mut want, &[click]).unwrap(), on_gpu.segment_clicks(&mut got, &[click]).unwrap()); + let i = iou(&m_gpu.logits, &m_cpu.logits); + let (dl, dm) = mask_diff(&m_gpu.logits, &m_cpu.logits); + eprintln!( + "click ({}, {}): mask IoU {i:.5}, max |Δ| logits {dl:.2e}, mask {dm:.2e}, score {:.4} vs {:.4}", + click.x, click.y, m_gpu.score, m_cpu.score + ); + assert!(i > 0.995, "click mask IoU {i}"); + } + let prompt = std::env::var("LIGHTCRAFT_SAM3_PROMPT").unwrap_or_else(|_| "sky".into()); + let (d_cpu, d_gpu) = (cpu.segment_text(&mut want, &prompt, 0.5).unwrap(), on_gpu.segment_text(&mut got, &prompt, 0.5).unwrap()); + match (d_cpu, d_gpu) { + (Some(c), Some(g)) => { + let i = iou(&g.logits, &c.logits); + let (dl, dm) = mask_diff(&g.logits, &c.logits); + let cover = c.logits.iter().filter(|v| **v > 0.0).count() as f32 / c.logits.len() as f32; + eprintln!( + "describe {prompt:?}: mask IoU {i:.5} (covers {:.1} %), max |Δ| logits {dl:.2e}, mask {dm:.2e}, score {:.4} vs {:.4}", + cover * 100.0, + g.score, + c.score + ); + assert!(i > 0.99, "describe mask IoU {i}"); + } + (None, None) => eprintln!("describe {prompt:?}: nothing found by either"), + (c, g) => panic!("describe {prompt:?}: CPU found {}, GPU {}", c.is_some(), g.is_some()), + } + assert_eq!(runs.load(Ordering::Relaxed), 4 + 2, "the clicks and the prompt used the GPU necks"); + eprintln!("neck device memory: {:.0} MB", gpu.neck_bytes() as f64 / 1e6); + drop((cpu, on_gpu, gpu)); + // no GPU work in flight when the process ends (issue #620) + lightcraft_gpu::begin_shutdown(); + lightcraft_gpu::wait_idle(std::time::Duration::from_secs(5)); +} diff --git a/crates/meta/src/exif.rs b/crates/meta/src/exif.rs index c35b96856d..4eefbb6afa 100644 --- a/crates/meta/src/exif.rs +++ b/crates/meta/src/exif.rs @@ -68,6 +68,7 @@ mod write_tests { focal_length: Some(35.0), lens_model: Some("35mm F2".into()), gps: Some(Gps { latitude: 43.7904, longitude: -110.6818, altitude: Some(2000.0) }), + rating: Some(4), ..Default::default() }; let back = read_exif(&write_exif(&m)); @@ -80,8 +81,12 @@ mod write_tests { assert!((back.f_number.unwrap() - 2.8).abs() < 1e-6); assert!((back.exposure_time.unwrap() - 0.004).abs() < 1e-9); assert_eq!(back.lens_model, m.lens_model); + assert_eq!(back.rating, Some(4)); let g = back.gps.unwrap(); assert!((g.latitude - 43.7904).abs() < 1e-5 && (g.longitude + 110.6818).abs() < 1e-5, "{g:?}"); + + let rejected = read_exif(&write_exif(&Metadata { rating: Some(-1), ..Default::default() })); + assert_eq!(rejected.rating, Some(-1)); } #[test] diff --git a/crates/pipeline/examples/upright_planes.rs b/crates/pipeline/examples/upright_planes.rs new file mode 100644 index 0000000000..fa87f837ed --- /dev/null +++ b/crates/pipeline/examples/upright_planes.rs @@ -0,0 +1,47 @@ +//! Upright detector on saved analysis planes (a developer tool, not part of the app): reads the `.lum` planes +//! that `lightcraft-engine`'s `upright_eval` example saves, runs the line finder and the solver at the app's +//! analysis size and writes one JSON line per plane (the Vertical / Auto / Full transforms and why a mode found +//! nothing), so a change to the detector can be scored against the photographer's own corrections quickly. +//! +//! `cargo run --release -p lightcraft-pipeline --example upright_planes -- ` +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::io::Write; + +use lightcraft_develop::Upright; +use lightcraft_pipeline::upright; +use lightcraft_raster::Plane; + +fn read_plane(path: &std::path::Path) -> Plane { + let b = std::fs::read(path).unwrap(); + let w = u32::from_le_bytes(b[0..4].try_into().unwrap()) as usize; + let h = u32::from_le_bytes(b[4..8].try_into().unwrap()) as usize; + let data = b[8..].as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes(*c)).collect(); + Plane { width: w, height: h, data } +} + +fn main() { + let args: Vec = std::env::args().skip(1).collect(); + let mut out = std::fs::File::create(&args[1]).unwrap(); + let mut paths: Vec<_> = std::fs::read_dir(&args[0]).unwrap().filter_map(|e| e.ok().map(|e| e.path())).collect(); + paths.retain(|p| p.extension().is_some_and(|e| e == "lum")); + paths.sort(); + for p in paths { + let key = p.file_stem().unwrap().to_string_lossy().to_string(); + let plane = read_plane(&p); + let size = std::env::var("UPRIGHT_SIZE").ok().and_then(|v| v.parse::().ok()).filter(|&n| n > 0).unwrap_or(1024); + let a = upright::analyze_plane_at(&plane, size); + let mut line = serde_json::json!({"key": key}); + for (name, mode) in [("vertical", Upright::Vertical), ("auto", Upright::Auto), ("full", Upright::Full)] { + line[name] = serde_json::json!({"transform": upright::solve(mode, &a), "note": upright::shortfall(mode, &a)}); + } + writeln!(out, "{line}").unwrap(); + // UPRIGHT_DUMP=dir: the near-vertical lines and the vanishing point, to draw over the photo + if let Ok(dir) = std::env::var("UPRIGHT_DUMP") { + let segs: Vec<[f64; 4]> = a.vertical.iter().map(|s| [s.a.x, s.a.y, s.b.x, s.b.y]).collect(); + let h: Vec<[f64; 4]> = a.horizontal.iter().map(|s| [s.a.x, s.a.y, s.b.x, s.b.y]).collect(); + let d = serde_json::json!({"vertical": segs, "horizontal": h, "vp": a.vertical_vp.or(upright::vanishing_point(&a.vertical).map(|x| x.0)), "why": a.vertical_why.map(|w| w.message())}); + std::fs::write(std::path::Path::new(&dir).join(format!("{key}.json")), d.to_string()).unwrap(); + } + } +} diff --git a/crates/pipeline/src/geometry.rs b/crates/pipeline/src/geometry.rs index 5d8a07489a..32516eaae2 100644 --- a/crates/pipeline/src/geometry.rs +++ b/crates/pipeline/src/geometry.rs @@ -37,6 +37,9 @@ pub struct Frame { /// `lightcraft_develop::Mask::on_photo`); otherwise they are normalized coordinates of this /// frame's transformed image, like spots and the crop. pub masks_on_photo: bool, + /// Filter of the area downscale ahead of the bilinear resample ([`Frame::sample`]); see + /// [`crate::Downscale`]. + pub downscale: Filter, } /// Where a windowed [`Frame`]'s pixels sit in the full output: its offset and the full output's @@ -82,6 +85,7 @@ impl Frame { warp: (!warp.is_identity()).then_some(warp), view: None, masks_on_photo: false, + downscale: Filter::Mitchell, }; if apply_crop { f.constrain_to_image(s.geometry.constrain_crop); @@ -312,8 +316,12 @@ impl Frame { pub fn sample_plan(&self, src_w: usize, src_h: usize, w: usize, h: usize) -> SamplePlan { let (ow, oh) = if self.orient.swaps_axes() { (src_h, src_w) } else { (src_w, src_h) }; let crop_px = self.crop.rect_px(self.ow, self.oh); - let k = crop_px.width() / w as f64; - let prefilter = (k > 1.25).then(|| (((ow as f64 / k).round() as usize).max(1), ((oh as f64 / k).round() as usize).max(1))); + // the larger of the two axes' reductions: the prefilter then takes every axis at least as small + // as its output needs, so the bilinear pass after it never minifies (and aliases) either one + let k = (crop_px.width() / w as f64).max(crop_px.height() / h as f64); + // Sharp exports use their selected filter for every downscale; keep smooth previews' threshold. + let threshold = if self.downscale == Filter::Lanczos3 { 1.0 } else { 1.25 }; + let prefilter = (k > threshold).then(|| (((ow as f64 / k).round() as usize).max(1), ((oh as f64 / k).round() as usize).max(1))); let (bw, bh) = prefilter.unwrap_or((ow, oh)); let (sx, sy) = (bw as f64 / ow as f64, bh as f64 / oh as f64); let mode = if self.warp.is_some() { @@ -333,7 +341,7 @@ impl Frame { let o = oriented.as_ref().unwrap_or(src); let plan = self.sample_plan(src.width, src.height, w, h); let base = match plan.prefilter { - Some((nw, nh)) => std::borrow::Cow::Owned(resize(o, nw, nh, Filter::Mitchell)), + Some((nw, nh)) => std::borrow::Cow::Owned(resize(o, nw, nh, self.downscale)), None => std::borrow::Cow::Borrowed(o), }; self.sample_base(base, plan, w, h) @@ -355,7 +363,7 @@ impl Frame { let mut bases: Vec<((usize, usize), Rgb32f)> = Vec::new(); for dims in plans.iter().filter_map(|p| p.1.prefilter) { if !bases.iter().any(|b| b.0 == dims) { - bases.push((dims, resize(o, dims.0, dims.1, Filter::Mitchell))); + bases.push((dims, resize(o, dims.0, dims.1, self.downscale))); } } plans @@ -443,7 +451,7 @@ pub struct SamplePlan { /// Oriented source size. pub ow: usize, pub oh: usize, - /// Size of the Mitchell prefilter (area downscale before the bilinear resample), if any. + /// Size of the prefilter ([`Frame::downscale`]: area downscale before the bilinear resample), if any. pub prefilter: Option<(usize, usize)>, /// Oriented-source px → prefiltered px. pub sx: f64, @@ -529,6 +537,24 @@ mod tests { assert!((f.px_per_long(300) - 300.0).abs() < 1e-9); } + #[test] + fn sharp_downscale_filters_mild_reductions_and_native_size_stays_identical() { + let src = Rgb32f::from_fn(100, 100, |x, y| [((x + y) % 2) as f32; 3]); + for filter in [Filter::Mitchell, Filter::Lanczos3] { + let mut f = Frame::new(100, 100, &DevelopSettings::default(), true); + f.downscale = filter; + let edge = if filter == Filter::Lanczos3 { 90 } else { 70 }; + assert_eq!(f.sample_plan(100, 100, edge, edge).prefilter, Some((edge, edge))); + assert_eq!(f.sample(&src, edge, edge).data, resize(&src, edge, edge, filter).data); + if filter == Filter::Mitchell { + assert_eq!(f.sample_plan(100, 100, 90, 90).prefilter, None); + } + assert_eq!(f.sample_plan(100, 100, 100, 100).prefilter, None); + assert_eq!(f.sample(&src, 100, 100).data, src.data); + assert_eq!(f.sample_plan(100, 100, 110, 110).prefilter, None); + } + } + #[test] fn rotation_swaps_aspect() { let s = DevelopSettings { orientation: Orientation::Rotate90, ..Default::default() }; diff --git a/crates/pipeline/src/lib.rs b/crates/pipeline/src/lib.rs index cc19f7b31f..5d4fcf25dd 100644 --- a/crates/pipeline/src/lib.rs +++ b/crates/pipeline/src/lib.rs @@ -129,6 +129,26 @@ impl Default for SourceInfo { } } +/// How a render shrinks its source to the output size. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] +pub enum Downscale { + /// Mitchell–Netravali: soft, no visible ringing. Previews and thumbnails. + #[default] + Smooth, + /// Lanczos-3: keeps the detail a smaller output can hold, as a dedicated downscale does + /// (exports, #2970). Its slight overshoot at hard edges stays below the output sharpening's. + Sharp, +} + +impl Downscale { + pub fn filter(self) -> lightcraft_raster::resample::Filter { + match self { + Downscale::Smooth => lightcraft_raster::resample::Filter::Mitchell, + Downscale::Sharp => lightcraft_raster::resample::Filter::Lanczos3, + } + } +} + #[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] pub enum Quality { /// Interactive drags: skips the most expensive refinements. @@ -162,6 +182,8 @@ pub struct RenderRequest { /// Previews for a monitor with a display profile: render 8-bit into its primaries instead of /// `space` (see [`DisplaySpace`]; ignored by deep renders). pub display: Option, + /// Filter of the downscale to the output size. + pub downscale: Downscale, } /// A window of the (virtual) full output, in its pixels: what a zoomed view needs, rendered @@ -236,6 +258,7 @@ impl RenderRequest { proof: None, window: None, display: None, + downscale: Downscale::Smooth, } } @@ -491,7 +514,8 @@ pub fn plan<'a>(src: &Rgb32f, info: &SourceInfo, s: &'a DevelopSettings, req: &R } } let s = &*settings; - let frame = frame_for(src, info, s, req.apply_crop); + let mut frame = frame_for(src, info, s, req.apply_crop); + frame.downscale = req.downscale.filter(); let (full_w, full_h) = req.size(&frame); // sizes and scale are those of the whole output; a window only narrows what is drawn let px_per_long = frame.px_per_long(full_w); diff --git a/crates/pipeline/src/tests.rs b/crates/pipeline/src/tests.rs index 1e57606463..ed85e83c19 100644 --- a/crates/pipeline/src/tests.rs +++ b/crates/pipeline/src/tests.rs @@ -107,6 +107,27 @@ fn dehaze_does_not_crush_dark_regions_next_to_bright_ones() { } } +/// An export's sharp downscale (#2970) keeps more of the fine detail a smaller output can hold +/// than a preview's smooth one, and changes nothing when the output is the source's own size. +#[test] +fn sharp_downscale_keeps_detail() { + use crate::Downscale; + // fine stripes: a period of 5 source pixels, 3 output pixels at 600 → 360 + let src = Rgb32f::from_fn(600, 400, |x, _| [0.18 * (1.0 + 0.8 * (x as f32 * std::f32::consts::TAU / 5.0).sin()); 3]); + let swing = |down: Downscale, edge: usize| { + let r = + render(&src, &SourceInfo::default(), &DevelopSettings::default(), &RenderRequest { downscale: down, ..RenderRequest::fit(edge, edge) }); + let row: Vec = (40..r.image.width - 40).map(|x| r.image.data[(r.image.height / 2) * r.image.width + x][1] as f32).collect(); + let m = row.iter().sum::() / row.len() as f32; + (row.iter().map(|v| (v - m).abs()).sum::() / row.len() as f32, r.image) + }; + let ((smooth, _), (sharp, _)) = (swing(Downscale::Smooth, 360), swing(Downscale::Sharp, 360)); + assert!(sharp > smooth * 1.25, "sharp {sharp} vs smooth {smooth}"); + let ((_, a), (_, b)) = (swing(Downscale::Smooth, 600), swing(Downscale::Sharp, 600)); + assert_eq!((b.width, b.height), (600, 400)); + assert_eq!(a.data, b.data, "no resize, no difference"); +} + #[test] fn resolution_independence_of_local_contrast() { // Clarity at two preview sizes should give similar results after downscaling. @@ -974,6 +995,72 @@ fn sliver_crops_render_quickly_with_wide_stages_on() { } } +/// A raw's linear Rec.2020 as decoding leaves it since it stopped clamping channels at zero: a dark ramp with +/// sensor noise through a saturating camera matrix (a NIKON D780 profile's), so near black many channels are +/// negative, and a few strongly out-of-gamut pixels. +fn negative_noise() -> Rgb32f { + let m = [[3.48f32, -2.41, -0.06], [-0.41, 1.57, -0.16], [0.32, -1.86, 2.58]]; + // ±0.004 of noise per channel, a hash of the position + let noise = |x: usize, y: usize, c: usize| { + let h = ((x * 7919 + y * 104_729 + c * 1_299_709) as u32).wrapping_mul(2_654_435_761); + (h >> 8) as f32 / (1u32 << 24) as f32 * 0.008 - 0.004 + }; + Rgb32f::from_fn(48, 32, |x, y| { + if (x + y) % 37 == 0 { + return [-0.05, 0.01, -0.02]; + } + let g = 0.0005 * 1.15f32.powi(x as i32); + let cam: [f32; 3] = std::array::from_fn(|c| g + noise(x, y, c)); + std::array::from_fn(|i| m[i][0] * cam[0] + m[i][1] * cam[1] + m[i][2] * cam[2]) + }) +} + +/// Negative channels from decoding reach every stage after it: every slider at its ends, at every output depth +/// (HDR on and off), and the auto settings give finite values only. +#[test] +fn negative_channels_render_finite_everywhere() { + use crate::{DeepSamples, OutputDepth, auto}; + let src = negative_noise(); + assert!(src.data.iter().flatten().filter(|v| **v < 0.0).count() > src.data.len() / 4, "the source has few negatives"); + let info = SourceInfo { raw: true, ..Default::default() }; + let finite = |s: &DevelopSettings, depth: OutputDepth, what: &str| { + let r = render(&src, &info, s, &RenderRequest { depth, ..RenderRequest::fit(48, 48) }); + assert!(r.histogram.total > 0, "{what}"); + match (depth, r.deep.map(|d| d.samples)) { + (OutputDepth::U8, None) | (OutputDepth::U16, Some(DeepSamples::U16(_))) => {} + (OutputDepth::F32Linear | OutputDepth::F32Hdr, Some(DeepSamples::F32(v))) => { + assert!(v.iter().all(|v| v.is_finite()), "{what} {depth:?}: non-finite output"); + } + _ => panic!("{what} {depth:?}: missing or wrong deep samples"), + } + }; + let mut pushed = DevelopSettings::default(); + pushed.light.exposure = 4.0; + pushed.light.shadows = 100.0; + pushed.light.blacks = 100.0; + for hdr in [false, true] { + let mut s = pushed.clone(); + s.hdr.enabled = hdr; + for depth in [OutputDepth::U8, OutputDepth::U16, OutputDepth::F32Linear, OutputDepth::F32Hdr] { + finite(&s, depth, &format!("pushed, hdr {hdr}")); + } + } + for c in controls::CONTROLS { + for v in [c.min, c.max] { + let mut s = pushed.clone(); + controls::set(&mut s, c.id, v); + finite(&s, OutputDepth::F32Linear, &format!("{} = {v}", c.id)); + } + } + let tone = auto::auto_tone(&src, &info, &pushed); + let t = [tone.exposure, tone.contrast, tone.highlights, tone.shadows, tone.whites, tone.blacks, tone.vibrance, tone.saturation]; + assert!(t.iter().all(|v| v.is_finite()), "auto tone {t:?}"); + assert!(auto::auto_bw_mix(&src, &info, &pushed).iter().all(|v| v.is_finite())); + let (t, k) = auto::auto_wb(&src, &info); + assert!(t.is_finite() && k.is_finite(), "auto WB {t} {k}"); + assert!(auto::scene_log_mean(&src, &info, &pushed).is_none_or(f64::is_finite)); +} + // Given a cached render with one process, a change to a process with another colour filter (Update // to Current Process, undo) renders like a fresh render, not the cached denoised image #[test] diff --git a/crates/pipeline/src/tests_geometry.rs b/crates/pipeline/src/tests_geometry.rs index dcd38d28c3..0f8b284aa0 100644 --- a/crates/pipeline/src/tests_geometry.rs +++ b/crates/pipeline/src/tests_geometry.rs @@ -481,6 +481,28 @@ fn upright_analysis_is_resolution_independent() { assert_eq!(lazy.data, stored.data); } +/// Raw decoding keeps negative channels; Upright analyses a dark noisy frame as it did when decoding clipped them at +/// zero (resampled as they are, they lowered the luminance and changed the correction found). +#[test] +fn upright_analysis_clips_negative_channels_first() { + let shot = lightcraft_develop::Geometry { vertical: 30.0, rotate: 1.5, ..Default::default() }; + let grid = keystoned_grid(1200, 800, crate::transform::manual(&shot), 80.0); + // ±0.04 of noise per channel, a hash of the position + let noise = |i: usize, c: usize| { + let h = ((i * 7919 + c * 1_299_709) as u32).wrapping_mul(2_654_435_761); + (h >> 8) as f32 / (1u32 << 24) as f32 * 0.08 - 0.04 + }; + let mut signed = grid.clone(); + for (i, p) in signed.data.iter_mut().enumerate() { + *p = std::array::from_fn(|c| p[c] * 0.02 + noise(i, c)); + } + let clipped = signed.map(|p| p.map(|v| v.max(0.0))); + assert!(signed.data.iter().flatten().filter(|v| **v < 0.0).count() > signed.data.len() / 4, "the frame has few negatives"); + let (info, s) = (SourceInfo::default(), DevelopSettings::default()); + let (a, b) = (crate::upright::analysis_plane(&signed, &info, &s), crate::upright::analysis_plane(&clipped, &info, &s)); + assert!(a.data == b.data, "negative channels change Upright's analysis image"); +} + /// Regression: Upright Auto must not invent perspective in natural scenes (conical trees, ridgelines, a level /// water line) — the demo library has no buildings, so Auto should stay close to identity everywhere. #[test] @@ -665,3 +687,332 @@ fn the_analysis_cache_tells_lenses_and_optics_apart() { assert!(!off.section_enabled("optics")); assert_ne!(key(&src, &plain, &s), key(&src, &plain, &off), "the optics section off"); } + +/// A ceremony aisle under a pavilion, shot from below and slightly rolled. Two thick white posts, +/// left and right, clipped by the frame's top and bottom, converge; a level hedge line; in the middle, people and +/// a dress whose edges are near-vertical but point nowhere in common; tree texture behind. Upright Vertical / Auto +/// did nothing on such a photo. +fn pavilion(w: usize, h: usize, fwd: lightcraft_geom::Homography) -> Rgb32f { + let l = w.max(h) as f64 / 2.0; + let (cx, cy) = (w as f64 / 2.0, h as f64 / 2.0); + // cheap deterministic noise + let noise = |x: f64, y: f64| { + let n = ((x * 12.9898 + y * 78.233).sin() * 43758.5453).fract().abs(); + n as f32 + }; + synth( + w, + h, + move |p| { + let q = fwd.apply(Point::new((p.x - cx) / l, (p.y - cy) / l)); + Point::new(q.x, q.y) + }, + move |q| { + let (x, y) = (q.x, q.y); + // posts: thick, bright, the whole height + for px in [-0.78, 0.8] { + if (x - px).abs() < 0.045 { + return [0.95; 3]; + } + } + // people in the middle: tilted shapes (a dress, suits), near-vertical edges in every direction + let people: [(f64, f64, f64, f64, f32); 6] = [ + (-0.32, 0.25, 0.09, 9.0, 0.08), + (-0.12, 0.2, 0.13, -11.0, 0.92), + (0.05, 0.22, 0.08, 14.0, 0.1), + (0.22, 0.28, 0.07, -7.0, 0.85), + (0.38, 0.3, 0.06, 18.0, 0.15), + (-0.5, 0.33, 0.05, -16.0, 0.12), + ]; + for (px, py, half_w, tilt, v) in people { + let (s, c) = tilt.to_radians().sin_cos(); + let (dx, dy) = (x - px, y - py); + let (u, t) = (dx * c - dy * s, dx * s + dy * c); + // a body from py − 0.35 (head) to py + 0.35, wider at the bottom (a dress) + if t.abs() < 0.35 && u.abs() < half_w * (1.0 + 0.8 * (t + 0.35)) { + return [v; 3]; + } + } + if y < -0.12 { + // sky (bright, but not as bright as the white posts) + [0.62 - 0.05 * y.abs() as f32; 3] + } else if y < 0.08 { + // trees: dark, textured + [0.18 + 0.12 * noise((x * 90.0).floor(), (y * 90.0).floor()); 3] + } else { + // lawn, below a level hedge line + [0.42 + 0.06 * noise((x * 140.0).floor(), (y * 140.0).floor()); 3] + } + }, + ) +} + +#[test] +fn upright_corrects_converging_posts_among_people() { + let (w, h) = (900usize, 600usize); + let shot = lightcraft_develop::Geometry { vertical: 30.0, rotate: -1.5, ..Default::default() }; + let src = pavilion(w, h, crate::transform::manual(&shot)); + let a = crate::upright::analyze_source(&src, &SourceInfo::default(), &DevelopSettings::default()); + assert!(a.vertical_vp.is_some(), "the posts give a vertical vanishing point: {:?}", a.vertical_why); + // the middle of the bright post in a quarter of the frame, on a row (centroid of the white pixels) + let post_x = |img: &Rgba8, y: usize, right: bool| { + let (a, b) = if right { (img.width * 3 / 4, img.width) } else { (0, img.width / 4) }; + let (mut s, mut n) = (0.0f64, 0.0f64); + for x in a..b { + if img.get(x, y)[1] > 225 { + s += x as f64; + n += 1.0; + } + } + assert!(n > 0.0, "a post is visible on row {y}"); + s / n + }; + let lean = |img: &Rgba8, right: bool| post_x(img, img.height / 6, right) - post_x(img, img.height * 5 / 6, right); + let raw = render(&src, &SourceInfo::default(), &DevelopSettings::default(), &RenderRequest::fit(w, h)).image; + assert!(lean(&raw, false).abs() > 8.0 && lean(&raw, true).abs() > 8.0, "the posts lean in the photo: {} {}", lean(&raw, false), lean(&raw, true)); + for mode in [Upright::Vertical, Upright::Auto] { + let img = upright_render(&src, mode); + for right in [false, true] { + assert!( + lean(&img, right).abs() < 2.5, + "{mode:?}: the {} post still leans {} px", + if right { "right" } else { "left" }, + lean(&img, right) + ); + } + } +} + +/// A ceremony under a white gazebo, shot level with a long lens but rolled 1.6° +/// (portrait). Two white posts stand up the whole frame; the deck's boards run away to the horizon (they meet +/// inside the photo); two drapes hang diagonally from the roof; a couple stands between the posts. Upright +/// Vertical said "the straight lines point in different directions" and did nothing. +fn gazebo(w: usize, h: usize, fwd: lightcraft_geom::Homography) -> Rgb32f { + let l = w.max(h) as f64 / 2.0; + let (cx, cy) = (w as f64 / 2.0, h as f64 / 2.0); + synth( + w, + h, + move |p| fwd.apply(Point::new((p.x - cx) / l, (p.y - cy) / l)), + move |q| { + let (x, y) = (q.x, q.y); + for px in [-0.47, 0.47] { + if (x - px).abs() < 0.035 { + return [0.95; 3]; + } + } + // drapes from the roof's middle out and down, thin bright bands + for (x0, x1) in [(-0.05, -0.3), (0.05, 0.3)] { + let (y0, y1) = (-1.0, 0.25); + if y > y0 && y < y1 { + let t = (y - y0) / (y1 - y0); + if (x - (x0 + (x1 - x0) * t)).abs() < 0.02 { + return [0.7; 3]; + } + } + } + // the couple: a dark suit and a white gown, a little tilted + for (px, half_w, tilt, v) in [(-0.1, 0.07, 6.0f64, 0.85f32), (0.1, 0.06, -5.0, 0.08)] { + let (s, c) = tilt.to_radians().sin_cos(); + let (dx, dy) = (x - px, y - 0.25); + let (u, t) = (dx * c - dy * s, dx * s + dy * c); + if t.abs() < 0.4 && u.abs() < half_w * (1.0 + 0.8 * (t + 0.4)) { + return [v; 3]; + } + } + if y > 0.3 { + // deck boards running to a point on the horizon (inside the photo) + let a = x.atan2(y + 0.1); + if (a * 14.0).rem_euclid(1.0) < 0.12 { + return [0.15; 3]; + } + return [0.55; 3]; + } + // sky, a railing line + if (y - 0.05).abs() < 0.01 { [0.3; 3] } else { [0.62; 3] } + }, + ) +} + +#[test] +fn upright_vertical_follows_the_posts_not_the_deck_or_the_drapes() { + let (w, h) = (600usize, 900usize); + let shot = lightcraft_develop::Geometry { rotate: 1.6, ..Default::default() }; + let src = gazebo(w, h, crate::transform::manual(&shot)); + let a = crate::upright::analyze_source(&src, &SourceInfo::default(), &DevelopSettings::default()); + assert!(a.vertical_vp.is_some(), "the posts give a vertical vanishing point: {:?}", a.vertical_why); + let post_x = |img: &Rgba8, y: usize, right: bool| { + let (a, b) = if right { (img.width * 3 / 4, img.width) } else { (0, img.width / 4) }; + let (mut s, mut n) = (0.0f64, 0.0f64); + for x in a..b { + if img.get(x, y)[1] > 235 { + s += x as f64; + n += 1.0; + } + } + assert!(n > 0.0, "a post is visible on row {y}"); + s / n + }; + let lean = |img: &Rgba8, right: bool| post_x(img, img.height / 8, right) - post_x(img, img.height * 5 / 8, right); + let raw = render(&src, &SourceInfo::default(), &DevelopSettings::default(), &RenderRequest::fit(w, h)).image; + assert!(lean(&raw, false).abs() > 6.0 && lean(&raw, true).abs() > 6.0, "the posts lean: {} {}", lean(&raw, false), lean(&raw, true)); + for mode in [Upright::Vertical, Upright::Auto] { + let img = upright_render(&src, mode); + for right in [false, true] { + assert!( + lean(&img, right).abs() < 2.0, + "{mode:?}: the {} post still leans {} px", + if right { "right" } else { "left" }, + lean(&img, right) + ); + } + } +} + +/// Do no harm: a gown's folds spreading to the floor point at a far point too, but they are short and there is +/// no post, wall or door among them: Upright Vertical leaves such a photo alone. +#[test] +fn upright_vertical_leaves_a_gown_without_structure_alone() { + let (w, h) = (600usize, 900usize); + let l = 450.0; + let src = synth( + w, + h, + |p| Point::new((p.x - 300.0) / l, (p.y - 450.0) / l), + |q| { + let (x, y) = (q.x, q.y); + // the gown: from the waist (y = −0.1) to the floor (y = 0.9), widening + if y > -0.1 && y < 0.9 && x.abs() < 0.08 + 0.45 * (y + 0.1) { + // folds: soft, wavy dark lines that all aim at a point far below (y = 3) + let a = x.atan2(3.0 - y) + 0.012 * (y * 23.0).sin(); + let band = (a * 40.0).rem_euclid(1.0) < 0.15; + let piece = ((y * 9.0).floor() as i64 + (a * 40.0).floor() as i64).rem_euclid(3) == 0; + return if band && piece { [0.55; 3] } else { [0.92; 3] }; + } + // a plain, soft background + [0.35 + 0.05 * (x as f32); 3] + }, + ); + let a = crate::upright::analyze_source(&src, &SourceInfo::default(), &DevelopSettings::default()); + assert!(a.vertical_vp.is_none(), "folds are not structure: {:?}", a.vertical_vp); + assert!(crate::upright::shortfall(Upright::Vertical, &a).is_some(), "and it says why"); +} + +/// Auto's note follows what Auto did: a tilted horizon it won't fix (over 5°) and a vertical correction too steep +/// to make both say why, while a level horizon it accepts says nothing. +#[test] +fn upright_auto_says_why_whenever_it_leaves_the_photo_alone() { + use crate::upright::{Analysis, Reject, Segment, shortfall, solve}; + use lightcraft_develop::Upright; + use lightcraft_geom::Homography; + let line = |deg: f64, y: f64| { + let (s, c) = deg.to_radians().sin_cos(); + Segment { a: Point::new(-0.4 * c, y - 0.4 * s), b: Point::new(0.4 * c, y + 0.4 * s) } + }; + // a level horizon: Auto accepts a zero-degree correction, so it has nothing to explain + let level = Analysis { horizontal: vec![line(0.0, -0.2), line(0.0, 0.2)], ..Analysis::default() }; + assert_eq!(shortfall(Upright::Auto, &level), None); + // a horizon 10° off: Auto leaves it alone, and says so + let tilted = Analysis { horizontal: vec![line(10.0, -0.2), line(10.0, 0.2)], ..Analysis::default() }; + assert_eq!(solve(Upright::Auto, &tilted), Homography::IDENTITY); + assert_eq!(shortfall(Upright::Auto, &tilted), Some(Reject::TooTilted.message()), "too tilted, not too few lines"); + assert_ne!(solve(Upright::Level, &tilted), Homography::IDENTITY, "Level still fixes it"); + // lines meeting just below the photo: too steep for Auto, which says so; Vertical still corrects them + let steep = Analysis { vertical_vp: Some([0.0, 0.3, 1.0]), ..Analysis::default() }; + assert_eq!(solve(Upright::Auto, &steep), Homography::IDENTITY); + assert_eq!(shortfall(Upright::Auto, &steep), Some(Reject::TooSteep.message())); + assert_ne!(solve(Upright::Vertical, &steep), Homography::IDENTITY); + // Level with no lines at all says there are too few, not that they disagree + assert_eq!(shortfall(Upright::Level, &Analysis::default()), Some(Reject::TooFew.message())); +} + +/// A mode that falls back to a lesser correction says which one it applied, and "no correction" is kept for no +/// correction at all (CodeRabbit on #2966). +#[test] +fn upright_note_names_the_fallback_it_applied() { + use crate::upright::{Analysis, Segment, fallback, shortfall, solve}; + use lightcraft_develop::Upright; + use lightcraft_geom::Homography; + let line = |deg: f64, y: f64| { + let (s, c) = deg.to_radians().sin_cos(); + Segment { a: Point::new(-0.4 * c, y - 0.4 * s), b: Point::new(0.4 * c, y + 0.4 * s) } + }; + // no verticals, a tilted horizon: Vertical and Full both level it, and say so + let tilted = Analysis { horizontal: vec![line(4.0, -0.2), line(4.0, 0.2)], ..Analysis::default() }; + for m in [Upright::Vertical, Upright::Full] { + assert!(shortfall(m, &tilted).is_some()); + assert_ne!(solve(m, &tilted), Homography::IDENTITY); + assert_eq!(fallback(m, &tilted), Some("Levelled the photo instead"), "{m:?}"); + } + // a vertical vanishing point but no horizontal one: Full straightens the verticals + let vertical = Analysis { vertical_vp: Some([0.0, 3.0, 1.0]), ..Analysis::default() }; + assert!(shortfall(Upright::Full, &vertical).is_some()); + assert_ne!(solve(Upright::Full, &vertical), Homography::IDENTITY); + assert_eq!(fallback(Upright::Full, &vertical), Some("Straightened the vertical lines instead")); + assert_eq!(fallback(Upright::Vertical, &vertical), None, "Vertical did what it says"); + // verticals already along the image's y axis: Full stores no correction, so it names no fallback + let straight = Analysis { vertical_vp: Some([0.0, 1.0, 0.0]), ..Analysis::default() }; + assert!(shortfall(Upright::Full, &straight).is_some()); + assert_eq!(solve(Upright::Full, &straight), Homography::IDENTITY); + assert_eq!(fallback(Upright::Full, &straight), None); + // nothing at all to go by: no fallback, the note says there was no correction + for m in [Upright::Vertical, Upright::Full, Upright::Level] { + assert_eq!(fallback(m, &Analysis::default()), None); + assert_eq!(solve(m, &Analysis::default()), Homography::IDENTITY); + } +} + +/// The Guided hint says what to draw: Full needs two guides of each family (Guided uses only the guides drawn, and +/// one of a kind only levels), Vertical two vertical ones, and Level a single line. +#[test] +fn upright_hint_asks_for_the_lines_guided_needs() { + use crate::upright::{Analysis, Segment, guided_hint}; + use lightcraft_develop::Upright; + let none = Analysis::default(); + assert_eq!(guided_hint(Upright::Full, &none), "two lines along what should be vertical and two along what should be horizontal"); + assert_eq!(guided_hint(Upright::Vertical, &none), "two lines along what should be vertical"); + assert_eq!(guided_hint(Upright::Level, &none), "a line along what should be level or upright"); + // Auto with no usable lines: either kind of guide can help + assert_eq!(guided_hint(Upright::Auto, &none), "two lines along what should be vertical, or one line along what should be level"); + // Auto stopped by a horizon over 5°: one level line fixes it (solve_guided_levels_one_guide_of_each_family_only) + let line = |deg: f64, y: f64| { + let (s, c) = deg.to_radians().sin_cos(); + Segment { a: Point::new(-0.4 * c, y - 0.4 * s), b: Point::new(0.4 * c, y + 0.4 * s) } + }; + let tilted = Analysis { horizontal: vec![line(10.0, -0.2), line(10.0, 0.2)], ..Analysis::default() }; + assert_eq!(guided_hint(Upright::Auto, &tilted), "one line along what should be level"); + // the same tilt found from vertical lines only (posts 10° off, no horizon): one upright line, as + // one vertical guide levels too (CodeRabbit, #2966) + let leaning = Analysis { vertical: vec![line(100.0, -0.2), line(100.0, 0.2)], ..Analysis::default() }; + assert_eq!(guided_hint(Upright::Auto, &leaning), "one line along what should be upright"); + // Auto stopped by converging posts too steep for it: a level line can't straighten them (CodeRabbit, #2966) + let steep = Analysis { vertical_vp: Some([0.0, 0.3, 1.0]), ..Analysis::default() }; + assert_eq!(guided_hint(Upright::Auto, &steep), "two lines along what should be vertical"); +} + +/// What the hints promise is what Guided does: one vertical and one horizontal guide only level (the horizontal one +/// becomes level, the vertical one keeps its lean, so Full's hint asks for two of each), and the single level line +/// Auto's hint offers fixes the horizon Auto leaves alone for being more than 5° off. +#[test] +fn solve_guided_levels_one_guide_of_each_family_only() { + use crate::upright::{Analysis, Reject, Segment, shortfall, solve_guided}; + use lightcraft_develop::Upright; + let vertical = Segment { a: Point::new(0.1, -0.5), b: Point::new(0.19, 0.5) }; + let horizontal = Segment { a: Point::new(-0.5, 0.1), b: Point::new(0.5, 0.12) }; + let h = solve_guided(&[vertical, horizontal]); + let (p, q) = (h.apply(horizontal.a), h.apply(horizontal.b)); + assert!((p.y - q.y).abs() < 1e-9, "the horizontal guide is levelled: {p:?} {q:?}"); + let (p, q) = (h.apply(vertical.a), h.apply(vertical.b)); + assert!((p.x - q.x).abs() > 0.03, "the vertical guide keeps its lean (no full correction): {p:?} {q:?}"); + // a horizon 10° off: too tilted for Auto, levelled by the one line its hint asks for + let (s, c) = 10f64.to_radians().sin_cos(); + let horizon = Segment { a: Point::new(-0.4 * c, -0.4 * s), b: Point::new(0.4 * c, 0.4 * s) }; + let tilted = Analysis { + horizontal: vec![horizon, Segment { a: Point::new(horizon.a.x, 0.2 + horizon.a.y), b: Point::new(horizon.b.x, 0.2 + horizon.b.y) }], + ..Analysis::default() + }; + assert_eq!(shortfall(Upright::Auto, &tilted), Some(Reject::TooTilted.message())); + let h = solve_guided(&[horizon]); + let (p, q) = (h.apply(horizon.a), h.apply(horizon.b)); + assert!((p.y - q.y).abs() < 1e-9, "one level guide fixes it: {p:?} {q:?}"); +} diff --git a/crates/pipeline/src/tone.rs b/crates/pipeline/src/tone.rs index 74a2861f70..c0f800c742 100644 --- a/crates/pipeline/src/tone.rs +++ b/crates/pipeline/src/tone.rs @@ -1,3 +1,30 @@ //! The global tone map: scene luminance → display-linear luminance, backed by `craft_develop::tone`. pub use craft_develop::tone::{CHROMA_N, CameraTone, GENERIC_KNEE_STOPS, GREY, LUT_MAX_EV, LUT_MIN_EV, LUT_N, ROLLOFF_STOPS, ToneMap}; + +/// The default raw tone curve ([`ToneMap::new`] at neutral settings) as camera-curve knots, about 1/3 EV apart +/// from 8 EV below grey to just under display white: for a camera look that knows a photo's colour but not its tone. +pub fn default_raw_camera_tone() -> Option { + const FROM_EV: f32 = -8.0; + const TO_EV: f32 = 2.6; + let map = ToneMap::new(0.0, 0.0, 0.0); + CameraTone::new(std::array::from_fn(|i| { + let x = GREY * 2f32.powf(FROM_EV + (TO_EV - FROM_EV) * i as f32 / 31.0); + [x, map.apply(x)] + })) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn default_raw_camera_tone_follows_the_default_tone_curve() { + let (camera, default) = (default_raw_camera_tone().unwrap(), ToneMap::new(0.0, 0.0, 0.0)); + for ev in [-8.0f32, -6.0, -4.0, -2.0, -1.0, 0.0, 1.0, 2.0, 2.5] { + let y = GREY * 2f32.powf(ev); + let (a, b) = (camera.apply(y), default.apply(y)); + assert!((a - b).abs() <= 0.01 * b.max(0.01), "{ev} EV: {a} vs {b}"); + } + } +} diff --git a/crates/pipeline/src/upright.rs b/crates/pipeline/src/upright.rs index a77369eb4b..c449067a5d 100644 --- a/crates/pipeline/src/upright.rs +++ b/crates/pipeline/src/upright.rs @@ -99,7 +99,8 @@ pub fn detect_segments(lum: &Plane) -> Vec { } sorted.sort_by(f32::total_cmp); let p90 = sorted[sorted.len() * 9 / 10]; - let thr = (p90 * 0.35).max(0.008); + // a quarter of the 90th percentile: a post's edge against foliage stays in + let thr = (p90 * 0.25).max(0.008); let mut order: Vec = (0..n as u32).filter(|&i| mag[i as usize] > thr).collect(); order.sort_by(|&a, &b| mag[b as usize].total_cmp(&mag[a as usize])); let mut used = vec![false; n]; @@ -273,6 +274,11 @@ fn refine_vp(segs: &[&Segment]) -> [f64; 3] { /// The dominant vanishing point of a segment family: RANSAC over pairs, then least squares on the inliers. /// Returns the point and the total inlier length, or None with fewer than two consistent segments. pub fn vanishing_point(segs: &[Segment]) -> Option<([f64; 3], f64)> { + vanishing_point_where(segs, |_| true) +} + +/// [`vanishing_point`] among the candidate points `ok` accepts. +fn vanishing_point_where(segs: &[Segment], ok: impl Fn([f64; 3]) -> bool) -> Option<([f64; 3], f64)> { if segs.len() < 2 { return None; } @@ -290,6 +296,9 @@ pub fn vanishing_point(segs: &[Segment]) -> Option<([f64; 3], f64)> { continue; } let v = norm(v); + if !ok(v) { + continue; + } let sc = score(v); if best.is_none_or(|b| sc > b.1) { best = Some((v, sc)); @@ -301,7 +310,8 @@ pub fn vanishing_point(segs: &[Segment]) -> Option<([f64; 3], f64)> { if inl.len() < 2 { return None; } - let v = refine_vp(&inl); + // refined, the point must still be one `ok` accepts (else the candidate it came from stands) + let v = Some(refine_vp(&inl)).filter(|r| ok(*r)).unwrap_or(v); let total: f64 = segs.iter().filter(|s| vp_error(s, v) < thr * 2.0).map(|s| s.len()).sum(); let count = segs.iter().filter(|s| vp_error(s, v) < thr * 2.0).count(); (count >= 2).then_some((v, total)) @@ -380,6 +390,14 @@ fn level_angle(vert: &[Segment], horiz: &[Segment]) -> Option { /// [`level_angle`] that only answers for at most `max` degrees, backed by at least `min_lines` /// agreeing segments. +/// Whether levelling goes by the vertical lines: the horizontal ones lead unless there are none or +/// their length is under half the verticals'. +fn levels_by_vertical(vert: &[Segment], horiz: &[Segment]) -> bool { + let lh: f64 = horiz.iter().map(Segment::len).sum(); + let lv: f64 = vert.iter().map(Segment::len).sum(); + !(lh >= lv * 0.5 && lh > 0.0) +} + pub(crate) fn level_angle_within(vert: &[Segment], horiz: &[Segment], max: f64, min_lines: usize) -> Option { let dev = |s: &Segment, vertical: bool| { let (dx, dy) = (s.b.x - s.a.x, s.b.y - s.a.y); @@ -395,9 +413,8 @@ pub(crate) fn level_angle_within(vert: &[Segment], horiz: &[Segment], max: f64, }; if vertical { -a } else { a } }; - let lh: f64 = horiz.iter().map(Segment::len).sum(); - let lv: f64 = vert.iter().map(Segment::len).sum(); - let (set, vertical) = if lh >= lv * 0.5 && lh > 0.0 { (horiz, false) } else { (vert, true) }; + let vertical = levels_by_vertical(vert, horiz); + let set = if vertical { vert } else { horiz }; if set.is_empty() { return None; } @@ -429,36 +446,313 @@ pub struct Analysis { pub horizontal: Vec, pub vertical_vp: Option<[f64; 3]>, pub horizontal_vp: Option<[f64; 3]>, + /// Why there is no vertical vanishing point (when there is none). + pub vertical_why: Option, + /// Why there is no horizontal vanishing point (when there is none). + pub horizontal_why: Option, } +/// Why a family of lines gives no perspective to correct. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Reject { + /// Fewer than two long lines of the family. + TooFew, + /// Too little of them: short lines only. + TooShort, + /// All on one object: not spread across the photo. + OneObject, + /// They point in different directions (trees, people, folds), not at one vanishing point. + Disagree, + /// They meet inside or near the photo: a scene feature (a road, rays), not a tilted camera. + MeetInside, + /// Correcting them would turn the camera too far to be a tilt (Auto leaves it to Vertical). + TooSteep, + /// The lines it would level by (horizontal, else vertical) are tilted more than Auto levels (5°): usually + /// intentional, or scene lines (Level fixes it anyway). + TooTilted, +} + +impl Reject { + /// In words for the user: "No vertical correction: …". + pub fn message(self) -> &'static str { + match self { + Reject::TooFew => "too few straight lines", + Reject::TooShort => "the straight lines are too short", + Reject::OneObject => "the straight lines are all on one object", + Reject::Disagree => "the long lines lean different ways", + Reject::MeetInside => "the lines meet inside the photo (a floor or a road, not a tilted camera)", + Reject::TooSteep => "the lines lean too far to be a tilted camera (Vertical corrects them anyway)", + Reject::TooTilted => "the lines are tilted too far to be a levelling fix (Level corrects them anyway)", + } + } +} + +/// How far (degrees) the camera turns to send the vertical vanishing point `v` to the image's y axis. +fn tilt_degrees(v: [f64; 3]) -> f64 { + let d = direction(v, DEFAULT_FOCAL); + d[1].abs().clamp(0.0, 1.0).acos().to_degrees() +} + +/// Whether a (homogeneous) vanishing point lies inside or near the photo (within twice the half long edge of +/// its centre): a scene feature rather than a camera tilt. +fn inside(v: [f64; 3]) -> bool { + v[2].abs() > 1e-9 && (v[0] / v[2]).hypot(v[1] / v[2]) < 2.0 +} + +/// A long line (in half long edges: 7.5 % of the long edge), and how far apart (across the family) two of them +/// must be to vouch for a vanishing point. Tuned on a photographer's own Upright corrections. +const LONG_LINE: f64 = 0.15; +const LONG_APART: f64 = 0.25; +/// Camera turns (degrees) above which a vertical correction needs three long lines and half the long lines' +/// length agreeing, and above which it needs most of it. +const BIG_TILT: f64 = 10.0; +const HUGE_TILT: f64 = 20.0; + /// Whether a family's vanishing point is backed by real structure rather than one object: at least three /// inlier segments, a total inlier length of a quarter of the long edge, and inliers spread across at least a -/// fifth of the long edge perpendicular to the family, and at least 60 % of the family's length agreeing (the -/// mirrored flanks of conical trees or peaks converge somewhere but say nothing about the camera). -fn reliable(segs: &[Segment], v: [f64; 3], vertical: bool) -> bool { +/// fifth of the long edge perpendicular to the family, and most of the family's long lines agreeing (the +/// mirrored flanks of conical trees or peaks converge somewhere but say nothing about the camera), or at least +/// the lines that disagree not gathering at a rival point (two posts flanking a crowd). +fn reliable(segs: &[Segment], v: [f64; 3], vertical: bool) -> Result<(), Reject> { let thr = 3f64.to_radians(); let inl: Vec<&Segment> = segs.iter().filter(|s| vp_error(s, v) < thr).collect(); let total: f64 = inl.iter().map(|s| s.len()).sum(); let across = |s: &&Segment| if vertical { s.mid().x } else { s.mid().y }; let (lo, hi) = inl.iter().map(across).fold((f64::MAX, f64::MIN), |(lo, hi), x| (lo.min(x), hi.max(x))); - // consensus: real structure agrees; mirrored flanks (trees, peaks) split the family roughly in half - let family: f64 = segs.iter().map(Segment::len).sum(); // a camera-tilt vanishing point lies far outside the frame; one inside or near it is a scene feature // (sun rays, a road to the horizon), not perspective to correct - if v[2].abs() > 1e-9 && (v[0] / v[2]).hypot(v[1] / v[2]) < 2.0 { + if inside(v) { + return Err(Reject::MeetInside); + } + if inl.len() < 3 { + return Err(Reject::TooFew); + } + if total < 0.5 { + return Err(Reject::TooShort); + } + if hi - lo < 0.4 { + return Err(Reject::OneObject); + } + // real structure has long straight edges: at least two long lines, apart, agree (folds of a dress, hair + // and foliage are short pieces that agree by chance) + let long: Vec = inl.iter().filter(|s| s.len() >= LONG_LINE).map(across).collect(); + let spread = long.iter().fold((f64::MAX, f64::MIN), |(lo, hi), x| (lo.min(*x), hi.max(*x))); + if long.len() < 2 || spread.1 - spread.0 < LONG_APART { + return Err(Reject::TooShort); + } + // a big correction needs more than a few lines: three long lines and half the long lines' + // length agreeing (the folds of a gown spreading to the floor point at a far point too) + let tilt = if vertical { tilt_degrees(v) } else { 0.0 }; + // consensus: real structure agrees; mirrored flanks (trees, peaks) split the family in two halves that each + // converge somewhere. Most of the family agreeing settles it; else the lines that disagree must not gather at + // a rival point of their own nearly as strongly (people, folds and foliage point every which way, so a few + // long posts among them still decide) + let mut family: f64 = segs.iter().map(Segment::len).sum(); + // (judged on the long lines: a gown's many short folds don't outvote the posts around it) + let mut long_family: f64 = segs.iter().filter(|s| s.len() >= LONG_LINE).map(Segment::len).sum(); + let long_total: f64 = inl.iter().filter(|s| s.len() >= LONG_LINE).map(|s| s.len()).sum(); + let share = if tilt > HUGE_TILT { 0.6 } else { 0.5 }; + let big = tilt > BIG_TILT; + // Lines that meet inside or near the photo are scene features (floorboards running to the horizon, the + // apex of a drape, rays), never a camera tilt: they neither vote against the posts nor make a rival + // (the posts of a gazebo were outvoted by its deck and its curtains), and the big-tilt test below + // doesn't count them either. + let mut rival = 0.0; + if big || total < 0.6 * family { + let mut rest: Vec = segs.iter().copied().filter(|s| vp_error(s, v) >= thr).collect(); + for _ in 0..4 { + let Some((r, support)) = vanishing_point(&rest) else { break }; + if !inside(r) { + rival = support; + break; + } + let (scene, other): (Vec, Vec) = rest.iter().partition(|s| vp_error(s, r) < thr); + if scene.is_empty() { + break; + } + family -= scene.iter().map(Segment::len).sum::(); + long_family -= scene.iter().filter(|s| s.len() >= LONG_LINE).map(Segment::len).sum::(); + rest = other; + } + } + if big && (long.len() < 3 || long_total < share * long_family) { + return Err(Reject::Disagree); + } + if total >= 0.6 * family { + return Ok(()); + } + if total >= 0.3 * family && total >= 2.0 * rival { + return Ok(()); + } + // most of the long lines agreeing settles it too (posts round a gown and its folds) + if long_total >= 0.6 * long_family { + return Ok(()); + } + Err(Reject::Disagree) +} + +/// Join the pieces of one straight edge (a post's side broken by a person in front of it, a branch, a +/// highlight) into one line, so a long structural edge counts as long: pieces on the same line (within 1.5° +/// and about 3 px at the analysis size) with a gap of at most a quarter of the half long edge between them. +fn merge_collinear(mut segs: Vec) -> Vec { + segs.sort_by(|a, b| b.len().total_cmp(&a.len())); + // each line: its first (longest) piece as the reference, and every piece joined to it + let mut lines: Vec<(Segment, Vec)> = Vec::with_capacity(segs.len()); + for s in segs { + let joined = lines.iter_mut().find(|(l, _)| collinear(l, &s)); + match joined { + Some((l, pieces)) => { + pieces.push(s); + *l = fit_line(pieces).unwrap_or(*l); + } + None => lines.push((s, vec![s])), + } + } + lines.into_iter().map(|(l, _)| l).collect() +} + +/// Whether piece `s` lies on line `l` (within 1.5° and about 3 px at the analysis size) with a gap of at most a +/// quarter of the half long edge between them. +fn collinear(l: &Segment, s: &Segment) -> bool { + let (dx, dy) = (l.b.x - l.a.x, l.b.y - l.a.y); + let n = dx.hypot(dy); + if n < 1e-9 { return false; } - inl.len() >= 3 && total >= 0.5 && hi - lo >= 0.4 && total >= 0.6 * family + let (ux, uy) = (dx / n, dy / n); + let (sx, sy) = (s.b.x - s.a.x, s.b.y - s.a.y); + let sn = sx.hypot(sy).max(1e-12); + if ((ux * sx + uy * sy) / sn).abs() < 1.5f64.to_radians().cos() { + return false; + } + let off = |p: Point| (p.x - l.a.x) * -uy + (p.y - l.a.y) * ux; + if off(s.a).abs() > 0.006 || off(s.b).abs() > 0.006 { + return false; + } + let t = |p: Point| (p.x - l.a.x) * ux + (p.y - l.a.y) * uy; + let (t0, t1) = (t(s.a).min(t(s.b)), t(s.a).max(t(s.b))); + (t0 - n).max(-t1).max(0.0) <= 0.25 +} + +/// The line through pieces (their endpoints weighted by the piece's length, principal axis), from end to end. +fn fit_line(pieces: &[Segment]) -> Option { + let (mut sw, mut mx, mut my) = (0.0, 0.0, 0.0); + for s in pieces { + let w = s.len(); + for p in [s.a, s.b] { + sw += w; + mx += w * p.x; + my += w * p.y; + } + } + if sw <= 0.0 { + return None; + } + let (mx, my) = (mx / sw, my / sw); + let (mut sxx, mut syy, mut sxy) = (0.0, 0.0, 0.0); + for s in pieces { + let w = s.len(); + for p in [s.a, s.b] { + let (dx, dy) = (p.x - mx, p.y - my); + sxx += w * dx * dx; + syy += w * dy * dy; + sxy += w * dx * dy; + } + } + let th = 0.5 * (2.0 * sxy).atan2(sxx - syy); + let (ux, uy) = (th.cos(), th.sin()); + let t = |p: Point| (p.x - mx) * ux + (p.y - my) * uy; + let (lo, hi) = pieces.iter().flat_map(|s| [t(s.a), t(s.b)]).fold((f64::MAX, f64::MIN), |(lo, hi), v| (lo.min(v), hi.max(v))); + Some(Segment { a: Point::new(mx + ux * lo, my + uy * lo), b: Point::new(mx + ux * hi, my + uy * hi) }) +} + +/// One family's vanishing point, if [`reliable`], else why not. +fn family_vp(segs: &[Segment], vertical: bool) -> (Option<[f64; 3]>, Option) { + // a camera tilt puts the point outside the photo: look there first, so lines meeting inside it (a deck + // running to the horizon) can't take the place of the posts + let found = vanishing_point_where(segs, |v| !inside(v)).or_else(|| vanishing_point(segs)); + match found { + None => (None, Some(Reject::TooFew)), + Some((v, _)) => match reliable(segs, v, vertical) { + Ok(()) => (Some(v), None), + // the strongest point may be one of many short pieces (foliage, folds) outweighing a few long posts: + // the long lines alone get their say, judged against the whole family (a short-only family stays out) + Err(Reject::TooShort) => { + let long: Vec = segs.iter().copied().filter(|s| s.len() >= LONG_LINE).collect(); + let again = (long.len() >= 2 && long.len() < segs.len()) + .then(|| vanishing_point_where(&long, |v| !inside(v)).or_else(|| vanishing_point(&long))) + .flatten() + .filter(|(v, _)| reliable(segs, *v, vertical).is_ok()); + match again { + Some((v, _)) => (Some(v), None), + None => (None, Some(Reject::TooShort)), + } + } + Err(why) => (None, Some(why)), + }, + } } /// Group segments into near-vertical / near-horizontal families and find their vanishing points (only reliable /// ones; see [`reliable`]). pub fn analyze(segs: &[Segment]) -> Analysis { - let vertical: Vec = segs.iter().copied().filter(|s| s.tilt_from_vertical() < 30.0).collect(); - let horizontal: Vec = segs.iter().copied().filter(|s| s.tilt_from_vertical() > 60.0).collect(); - let vertical_vp = vanishing_point(&vertical).map(|v| v.0).filter(|v| reliable(&vertical, *v, true)); - let horizontal_vp = vanishing_point(&horizontal).map(|v| v.0).filter(|v| reliable(&horizontal, *v, false)); - Analysis { vertical, horizontal, vertical_vp, horizontal_vp } + let vertical = merge_collinear(segs.iter().copied().filter(|s| s.tilt_from_vertical() < 30.0).collect()); + let horizontal = merge_collinear(segs.iter().copied().filter(|s| s.tilt_from_vertical() > 60.0).collect()); + let (vertical_vp, vertical_why) = family_vp(&vertical, true); + let (horizontal_vp, horizontal_why) = family_vp(&horizontal, false); + Analysis { vertical, horizontal, vertical_vp, horizontal_vp, vertical_why, horizontal_why } +} + +/// Why `mode` corrects less than it asks for on this analysis: `None` when it does what it says (or it is Off, +/// Guided or Auto with nothing to fix). In words for the user, after "No vertical correction: ". +pub fn shortfall(mode: Upright, a: &Analysis) -> Option<&'static str> { + match mode { + Upright::Vertical | Upright::Full if a.vertical_vp.is_none() => Some(a.vertical_why.unwrap_or(Reject::TooFew).message()), + Upright::Full if a.horizontal_vp.is_none() => Some(a.horizontal_why.unwrap_or(Reject::TooFew).message()), + Upright::Level if level_angle(&a.vertical, &a.horizontal).is_none() => { + let why = if a.vertical.is_empty() && a.horizontal.is_empty() { Reject::TooFew } else { Reject::Disagree }; + Some(why.message()) + } + Upright::Auto => auto(a).err().map(Reject::message), + _ => None, + } +} + +/// What [`solve`] applies instead when `mode` falls short ([`shortfall`]) but corrects something all the same: Full +/// without a horizontal vanishing point straightens the verticals, and Vertical or Full without a vertical one levels. +/// In words for the user, after "No full correction: …. " (`None` when the result is no correction at all). +pub fn fallback(mode: Upright, a: &Analysis) -> Option<&'static str> { + let levels = || level_angle(&a.vertical, &a.horizontal).is_some_and(|d| d != 0.0); + match mode { + // verticals that already stand straight leave no correction to name + Upright::Full if a.vertical_vp.is_some() && a.horizontal_vp.is_none() => { + (solve(Upright::Full, a) != Homography::IDENTITY).then_some("Straightened the vertical lines instead") + } + Upright::Vertical | Upright::Full if a.vertical_vp.is_none() && levels() => Some("Levelled the photo instead"), + _ => None, + } +} + +/// What to draw in Guided when `mode` falls short on `a` ("Try Guided: draw …"). Guided works from the guides +/// alone, not from lines the mode found, and one guide of a kind only levels ([`solve_guided`]): Full needs two of +/// each family, Vertical two vertical ones, and levelling one line. Auto follows why it stopped: a tilt more than +/// it levels ([`Reject::TooTilted`]) takes one guide of the family it levelled by (a level line for a horizon, an +/// upright one when only vertical lines were found); a vertical correction too steep for it +/// ([`Reject::TooSteep`]) needs two vertical guides, as one level line can't straighten converging posts; with too +/// few or unusable lines either can help, so it names both. +pub fn guided_hint(mode: Upright, a: &Analysis) -> &'static str { + const VERTICAL: &str = "two lines along what should be vertical"; + match mode { + Upright::Full => "two lines along what should be vertical and two along what should be horizontal", + Upright::Level => "a line along what should be level or upright", + Upright::Auto => match auto(a) { + Err(Reject::TooTilted) if levels_by_vertical(&a.vertical, &a.horizontal) => "one line along what should be upright", + Err(Reject::TooTilted) => "one line along what should be level", + Err(Reject::TooSteep) => VERTICAL, + _ => "two lines along what should be vertical, or one line along what should be level", + }, + _ => VERTICAL, + } } /// The Upright correction for `mode` from an analysis (lens-corrected → transformed, centred coordinates). @@ -478,29 +772,49 @@ pub fn solve(mode: Upright, a: &Analysis) -> Homography { Some((r, f)) => recentre(&rotation_homography(&r, f)), None => vertical().map(|r| recentre(&rotation_homography(&r, DEFAULT_FOCAL))).unwrap_or_else(level), }, - Upright::Auto => { - // A vertical family that implies a camera roll must be confirmed by the horizontals (a real roll tilts - // both); otherwise it is scene structure (e.g. the same-side flanks of many conical trees). - if let Some(v) = a.vertical_vp { - let (x, y) = if v[1] < 0.0 { (-v[0], -v[1]) } else { (v[0], v[1]) }; - let roll = x.atan2(y).to_degrees(); - let confirmed = roll.abs() <= 3.0 || level_angle(&[], &a.horizontal).is_some_and(|h| (h - roll).abs() <= 3.0); - if !confirmed { - let weaker = Analysis { vertical_vp: None, horizontal_vp: None, ..a.clone() }; - return solve(Upright::Auto, &weaker); - } - } - // balanced: full correction only when it is moderate, else vertical, else level - if let Some((r, f)) = full().filter(|(r, _)| rotation_angle(r) < 20f64.to_radians()) { - return recentre(&rotation_homography(&r, f)); - } - match vertical().filter(|r| rotation_angle(r) < 25f64.to_radians()) { - Some(r) => recentre(&rotation_homography(&r, DEFAULT_FOCAL)), - // conservative: only small horizon fixes; bigger tilts are usually intentional or scene lines - None => level_angle(&a.vertical, &a.horizontal).filter(|d| d.abs() <= 5.0).map(rot_z_h).unwrap_or(Homography::IDENTITY), - } + Upright::Auto => auto(a).unwrap_or(Homography::IDENTITY), + } +} + +/// What Auto does with an analysis: the correction it applies, or why it applies none. [`solve`] and +/// [`shortfall`] both ask it, so the note always matches the correction. +fn auto(a: &Analysis) -> Result { + // A vertical family that implies a camera roll must be confirmed by the horizontals (a real roll tilts + // both); otherwise it is scene structure (e.g. the same-side flanks of many conical trees). + if let Some(v) = a.vertical_vp { + let (x, y) = if v[1] < 0.0 { (-v[0], -v[1]) } else { (v[0], v[1]) }; + let roll = x.atan2(y).to_degrees(); + let confirmed = roll.abs() <= 3.0 || level_angle(&[], &a.horizontal).is_some_and(|h| (h - roll).abs() <= 3.0); + if !confirmed { + let weaker = Analysis { vertical_vp: None, horizontal_vp: None, vertical_why: Some(Reject::Disagree), ..a.clone() }; + return auto(&weaker); } } + // balanced: full correction only when it is moderate, else vertical, else level + if let Some((v, h)) = a.vertical_vp.zip(a.horizontal_vp) { + let f = focal_from_vps(v, h).unwrap_or(DEFAULT_FOCAL); + let r = solve_full(v, h, f); + if rotation_angle(&r) < 20f64.to_radians() { + return Ok(recentre(&rotation_homography(&r, f))); + } + } + let vertical = a.vertical_vp.map(|v| solve_vertical(v, DEFAULT_FOCAL)); + if let Some(r) = vertical.filter(|r| rotation_angle(r) < 25f64.to_radians()) { + return Ok(recentre(&rotation_homography(&r, DEFAULT_FOCAL))); + } + // conservative: only small horizon fixes; bigger tilts are usually intentional or scene lines + match level_angle(&a.vertical, &a.horizontal) { + Some(d) if d.abs() <= 5.0 => Ok(rot_z_h(d)), + _ if vertical.is_some() => Err(Reject::TooSteep), + Some(_) => Err(Reject::TooTilted), + // nothing to level by: a vertical family's own reason when it has one beyond a lack of lines, else lines + // that are there but don't agree, else too few lines + _ => Err(match a.vertical_why { + Some(why) if why != Reject::TooFew => why, + _ if a.vertical.is_empty() && a.horizontal.is_empty() => Reject::TooFew, + _ => Reject::Disagree, + }), + } } /// Guided Upright from user guides (centred coordinates of the lens-corrected image). Guides closer to vertical @@ -563,6 +877,46 @@ pub fn analyze_source(src: &Rgb32f, info: &SourceInfo, s: &DevelopSettings) -> A a } +/// [`analysis_plane`] at `long` px on its long edge (the evaluation examples read a larger one). +pub fn analysis_luminance(src: &Rgb32f, info: &SourceInfo, s: &DevelopSettings, long: usize) -> Plane { + // Raw decoding keeps negative channels (noise near black through the camera matrix). Resampled as they are, + // they lower the luminance the segments are found in, so Upright would find a different correction than for + // the same photo decoded with its channels clipped at zero; it analyses that clipped source, as it always has. + let clipped; + let src = if src.data.iter().flatten().any(|v| *v < 0.0) { + clipped = src.map(|p| p.map(|v| v.max(0.0))); + &clipped + } else { + src + }; + let mut base = s.clone(); + base.geometry = Geometry::default(); + base.crop = Crop::default(); + let frame = crate::frame_for(src, info, &base, false); + let (w, h) = frame.fit(long, long); + let img = frame.sample(src, w, h); + let lum = img.luminance(); + let mut v: Vec = lum.data.iter().copied().filter(|x| x.is_finite()).collect(); + v.sort_by(f32::total_cmp); + let white = v.get(v.len() * 99 / 100).copied().unwrap_or(1.0).max(1e-4); + lum.map(|x| (x.max(0.0) / white).min(1.5).powf(1.0 / 2.4)) +} + +/// Analyse an [`analysis_luminance`] plane of any size (brought to the analysis size first). +pub fn analyze_plane(lum: &Plane) -> Analysis { + analyze_plane_at(lum, ANALYSIS_LONG) +} + +/// [`analyze_plane`] at `size` px on the long edge (at most the plane's own). +pub fn analyze_plane_at(lum: &Plane, size: usize) -> Analysis { + let long = lum.width.max(lum.height); + if long > size { + let fit = lightcraft_raster::resample::fit(lum, size, size, lightcraft_raster::resample::Filter::Box); + return analyze(&detect_segments(&fit)); + } + analyze(&detect_segments(lum)) +} + /// What an analysis depends on: the source (by its sampled fingerprint), the optics and /// orientation settings, whether the optics section is on, and the lens the frame is corrected for /// (`info.lens`, which [`analysis_plane`] reads through the frame). @@ -579,17 +933,7 @@ pub(crate) fn analysis_key(src: &Rgb32f, info: &SourceInfo, s: &DevelopSettings) /// The image an analysis reads: the lens-corrected source (optics applied, no perspective or crop) /// at [`ANALYSIS_LONG`] px, as perceptual lightness normalized to its bright end. pub(crate) fn analysis_plane(src: &Rgb32f, info: &SourceInfo, s: &DevelopSettings) -> Plane { - let mut base = s.clone(); - base.geometry = Geometry::default(); - base.crop = Crop::default(); - let frame = crate::frame_for(src, info, &base, false); - let (w, h) = frame.fit(ANALYSIS_LONG, ANALYSIS_LONG); - let img = frame.sample(src, w, h); - let lum = img.luminance(); - let mut v: Vec = lum.data.iter().copied().filter(|x| x.is_finite()).collect(); - v.sort_by(f32::total_cmp); - let white = v.get(v.len() * 99 / 100).copied().unwrap_or(1.0).max(1e-4); - lum.map(|x| (x.max(0.0) / white).min(1.5).powf(1.0 / 2.4)) + analysis_luminance(src, info, s, ANALYSIS_LONG) } /// The crop angle (degrees, clockwise +) Auto straighten levels `src` by, if it finds a horizon or @@ -633,3 +977,83 @@ pub fn homography(g: &Geometry, ow: f64, oh: f64) -> Homography { _ => g.upright_transform.unwrap_or(Homography::IDENTITY), } } + +#[cfg(test)] +mod tests { + use super::*; + + /// Many short parallel pieces outweighing three long posts don't hide the posts' vanishing point: the long + /// lines are tried on their own when the strongest point has only short lines (CodeRabbit on #2966). + #[test] + fn short_pieces_outweighing_the_posts_do_not_hide_their_vanishing_point() { + let mut segs: Vec = [-0.7, 0.0, 0.7].iter().map(|&x| Segment { a: Point::new(x, -0.8), b: Point::new(0.75 * x, 0.8) }).collect(); + let (dx, dy) = (0.06 * 20f64.to_radians().sin(), 0.06 * 20f64.to_radians().cos()); + for i in 0..60 { + let cx = -0.59 + 0.02 * i as f64; + segs.push(Segment { a: Point::new(cx - dx, -dy), b: Point::new(cx + dx, dy) }); + } + let a = analyze(&segs); + assert!(a.vertical_vp.is_some(), "the posts give a vertical vanishing point: {:?}", a.vertical_why); + // short pieces alone still give none + let a = analyze(&segs[3..]); + assert!(a.vertical_vp.is_none()); + } + + /// Lines that are there but don't agree on a level say so, rather than that there are too few lines + /// (CodeRabbit on #2966). + #[test] + fn horizontals_that_disagree_are_reported_as_disagreeing() { + let segs: Vec = [-4f64, 0.0, 4.0] + .iter() + .enumerate() + .map(|(i, d)| { + let (c, s) = (0.4 * d.to_radians().cos(), 0.4 * d.to_radians().sin()); + let y = -0.5 + 0.5 * i as f64; + Segment { a: Point::new(-c, y - s), b: Point::new(c, y + s) } + }) + .collect(); + let a = analyze(&segs); + assert!(a.vertical.is_empty()); + assert_eq!(auto(&a).err(), Some(Reject::Disagree)); + } + + /// The point refined from a candidate's lines is still held to the same test as the candidate: one that test + /// turns down leaves the candidate itself (CodeRabbit on #2966). + #[test] + fn a_refined_vanishing_point_the_test_refuses_falls_back_to_its_candidate() { + // three near-vertical lines that nearly, not exactly, meet far above the photo + let segs = [ + Segment { a: Point::new(-0.5, -0.8), b: Point::new(-0.45, 0.8) }, + Segment { a: Point::new(0.5, -0.8), b: Point::new(0.45, 0.8) }, + Segment { a: Point::new(0.0, -0.8), b: Point::new(0.0003, 0.8) }, + ]; + // only the candidates made from two of the lines pass; the least-squares point of all three does not + let candidates: Vec<[f64; 3]> = (0..3) + .flat_map(|i| (i + 1..3).map(move |j| (i, j))) + .flat_map(|(i, j)| [norm(cross(segs[i].line(), segs[j].line())), norm(cross(segs[j].line(), segs[i].line()))]) + .collect(); + let ok = |v: [f64; 3]| candidates.contains(&v); + let (v, _) = vanishing_point_where(&segs, ok).expect("a point"); + assert!(ok(v), "{v:?} is not one of the candidates"); + } + + /// Long lines meeting inside the photo (floorboards, a drape) are scene features: they don't make a big + /// tilt's posts look outvoted (CodeRabbit on #2966). + #[test] + fn scene_lines_inside_the_photo_do_not_outvote_a_big_tilts_posts() { + // three posts leaning to a point far above the photo: a camera tilt of about 15 degrees + let v = norm([0.0, 5.6, 1.0]); + assert!(tilt_degrees(v) > BIG_TILT && tilt_degrees(v) < HUGE_TILT, "{}", tilt_degrees(v)); + let toward = |x: f64, (px, py): (f64, f64), y1: f64| { + let t = (y1 + 0.8) / (py + 0.8); + Segment { a: Point::new(x, -0.8), b: Point::new(x + (px - x) * t, y1) } + }; + let mut segs: Vec = [-0.8, 0.0, 0.8].iter().map(|&x| toward(x, (0.0, 5.6), 0.8)).collect(); + // six longer floor lines running to a point inside the photo, more length than the posts + segs.extend([-0.5, -0.35, -0.2, 0.2, 0.35, 0.5].iter().map(|&x| toward(x, (0.0, 0.9), 0.6))); + let posts: f64 = segs[..3].iter().map(Segment::len).sum(); + let floor: f64 = segs[3..].iter().map(Segment::len).sum(); + assert!(posts < 0.5 * (posts + floor), "the floor lines must outweigh the posts: {posts} vs {floor}"); + assert_eq!(reliable(&segs, v, true), Ok(())); + } +} diff --git a/crates/pipeline/tests/sharp_downscale.rs b/crates/pipeline/tests/sharp_downscale.rs new file mode 100644 index 0000000000..da4fb57e09 --- /dev/null +++ b/crates/pipeline/tests/sharp_downscale.rs @@ -0,0 +1,42 @@ +//! A pure above-Nyquist carrier must be suppressed rather than folded into a smaller export. +use lightcraft_develop::DevelopSettings; +use lightcraft_pipeline::geometry::Frame; +use lightcraft_raster::{Rgb32f, resample::Filter}; + +#[test] +fn mild_sharp_reductions_suppress_above_target_nyquist_aliases() { + // 0.49 cycles/source pixel is above the 90% and 80% outputs' Nyquist limits. + let source = Rgb32f::from_fn(1000, 100, |x, _| [0.5 + 0.25 * (std::f32::consts::TAU * 0.49 * x as f32).sin(); 3]); + let power = |image: &Rgb32f| { + let values: Vec = (12..image.width - 12).map(|x| f64::from(image.get(x, image.height / 2)[0])).collect(); + let mean = values.iter().sum::() / values.len() as f64; + values.iter().map(|v| (v - mean).powi(2)).sum::() / values.len() as f64 + }; + let mut frame = Frame::new(1000, 100, &DevelopSettings::default(), true); + frame.downscale = Filter::Lanczos3; + for (w, h) in [(900, 90), (800, 80)] { + let k = 1000.0 / w as f64; + let unfiltered = Rgb32f::from_fn(w, h, |x, y| source.sample_bilinear(((x as f64 + 0.5) * k) as f32, ((y as f64 + 0.5) * k) as f32)); + let (sharp, bilinear) = (power(&frame.sample(&source, w, h)), power(&unfiltered)); + assert!(sharp < bilinear * 0.95, "{w}: residual alias power {sharp} vs unfiltered {bilinear}"); + } +} + +#[test] +fn a_height_only_reduction_is_prefiltered_too() { + // the width stays 1:1, the height shrinks 1000 → 900: the vertical carrier must not fold in + let source = Rgb32f::from_fn(100, 1000, |_, y| [0.5 + 0.25 * (std::f32::consts::TAU * 0.49 * y as f32).sin(); 3]); + let power = |image: &Rgb32f| { + let values: Vec = (12..image.height - 12).map(|y| f64::from(image.get(image.width / 2, y)[0])).collect(); + let mean = values.iter().sum::() / values.len() as f64; + values.iter().map(|v| (v - mean).powi(2)).sum::() / values.len() as f64 + }; + let mut frame = Frame::new(100, 1000, &DevelopSettings::default(), true); + frame.downscale = Filter::Lanczos3; + let (w, h) = (100, 900); + assert!(frame.sample_plan(100, 1000, w, h).prefilter.is_some(), "a reduction on either axis is prefiltered"); + let k = 1000.0 / h as f64; + let unfiltered = Rgb32f::from_fn(w, h, |x, y| source.sample_bilinear(x as f32 + 0.5, ((y as f64 + 0.5) * k) as f32)); + let (sharp, bilinear) = (power(&frame.sample(&source, w, h)), power(&unfiltered)); + assert!(sharp < bilinear * 0.95, "residual alias power {sharp} vs unfiltered {bilinear}"); +} diff --git a/crates/segment/examples/sam3_bench.rs b/crates/segment/examples/sam3_bench.rs index 982f482e96..a00ae556dd 100644 --- a/crates/segment/examples/sam3_bench.rs +++ b/crates/segment/examples/sam3_bench.rs @@ -1,25 +1,57 @@ //! Times SAM 3 on this machine (a synthetic gradient image; the first run includes compiling -//! the GPU kernels): `cargo run -p lightcraft-segment --release --example sam3_bench -- `. +//! the GPU kernels and loading the heads): `cargo run -p lightcraft-segment --release --example +//! sam3_bench -- `. Each run times the backbone, the click features (tracker neck), +//! a first and a further click, and a first and a second description of the same image (the +//! first one computes the detector's features). + +use std::time::{Duration, Instant}; + +fn ms(d: Duration) -> String { + format!("{:.0} ms", d.as_secs_f64() * 1e3) +} fn main() -> Result<(), Box> { let mut args = std::env::args().skip(1); - let dir = std::path::PathBuf::from(args.next().ok_or("usage: sam3_bench ")?); - let t = std::time::Instant::now(); + let dir = std::path::PathBuf::from(args.next().ok_or("usage: sam3_bench [runs]")?); + let runs: usize = args.next().map(|s| s.parse()).transpose()?.unwrap_or(3); + let t = Instant::now(); let mut model = lightcraft_segment::Sam3::load(&dir)?; - eprintln!("load: {:?} on {:?}", t.elapsed(), model.device()); + eprintln!("load: {} on {}", ms(t.elapsed()), model.backbone_device()); let (w, h) = (1200, 800); let rgb: Vec = (0..w * h * 3).map(|i| ((i / 3 % w) * 255 / w) as u8).collect(); - for run in 0..3 { - let t = std::time::Instant::now(); + let click = |x, y| lightcraft_segment::Click { x, y, positive: true }; + for run in 0..runs { + let t = Instant::now(); let mut enc = model.encode(&rgb, w, h)?; lightcraft_segment::sync(&model)?; - let e = t.elapsed(); - let t = std::time::Instant::now(); - let p = model.segment_clicks(&mut enc, &[lightcraft_segment::Click { x: 0.5, y: 0.5, positive: true }])?; - let c = t.elapsed(); - let t = std::time::Instant::now(); + let encode = t.elapsed(); + let t = Instant::now(); + model.prepare_clicks(&mut enc)?; + lightcraft_segment::sync(&model)?; + let features = t.elapsed(); + let t = Instant::now(); + let p = model.segment_clicks(&mut enc, &[click(0.5, 0.5)])?; + let click1 = t.elapsed(); + let t = Instant::now(); + model.segment_clicks(&mut enc, &[click(0.5, 0.5), click(0.3, 0.6)])?; + let click2 = t.elapsed(); + let t = Instant::now(); let d = model.segment_text(&mut enc, "sky", 0.5)?; - eprintln!("run {run}: encode {e:?}, click {c:?} (score {:.2}), text {:?} ({})", p.score, t.elapsed(), d.is_some()); + let text1 = t.elapsed(); + let t = Instant::now(); + model.segment_text(&mut enc, "the red car", 0.5)?; + let text2 = t.elapsed(); + eprintln!( + "run {run}: encode {}, click features {}, click {} (score {:.2}), further click {}, first describe {} ({}), second describe {}", + ms(encode), + ms(features), + ms(click1), + p.score, + ms(click2), + ms(text1), + d.is_some(), + ms(text2) + ); } Ok(()) } diff --git a/crates/segment/src/detector.rs b/crates/segment/src/detector.rs index 73608dd30a..36b5d48628 100644 --- a/crates/segment/src/detector.rs +++ b/crates/segment/src/detector.rs @@ -6,6 +6,9 @@ //! the Python/PyTorch SAM 3 code of Hugging Face Transformers (`models/sam3/modeling_sam3.py`), Copyright The HuggingFace //! Team and Meta Platforms, Inc.; translated to Rust on candle and restructured. See NOTICE. +use std::collections::VecDeque; +use std::sync::{Mutex, OnceLock, PoisonError}; + use candle_core::{D, Device, IndexOp, Module, Tensor}; use candle_nn::{Conv2d, Conv2dConfig, LayerNorm, Linear, VarBuilder}; @@ -14,12 +17,15 @@ use crate::neck::{FPN, Neck}; use crate::nn::{ Attention, DecoderMlp, GroupNormRelu, Mlp, TORCH_LN_EPS, cxcywh_to_xyxy, inverse_sigmoid, linear, ln, padding_bias, sine_grid, to_vec, }; -use crate::{Error, Prediction, Result, cpu}; +use crate::{BackboneAccel, Error, Prediction, Result, cpu}; const HIDDEN: usize = FPN; const HEADS: usize = 8; const QUERIES: usize = 200; const LAYERS: usize = 6; +/// Prompts whose text features are kept: they don't depend on the image, and the same few come back (Subject's +/// "person" on every photo). 32 KB each. +const TEXT_CACHE: usize = 16; /// Detector image features, computed once per image. pub struct Features { @@ -46,6 +52,17 @@ pub struct Output { /// Semantic logits `[288, 288]` flattened: everything the prompt names, one mask without /// boundaries between instances. pub semantic: Vec, + /// The DETR encoder's memory `[1, 5184, 256]` (tests). + pub memory: Tensor, +} + +/// Where the DETR encoder and the mask decoder may run outside candle: the model's accelerator (if it still has one), +/// and why the encoder (`failed`) or the mask decoder (`masks_failed`) stopped running there (set on its first failure; +/// from then on candle runs it). +pub struct EncoderAccel<'a> { + pub accel: &'a Mutex>>, + pub failed: &'a OnceLock, + pub masks_failed: &'a OnceLock, } struct EncoderLayer { @@ -73,6 +90,8 @@ pub struct Detector { neck: Neck, text: TextEncoder, text_proj: Linear, + /// The latest prompts' token ids and valid marks with their features `[1, 32, 256]`, most recent last. + texts: Mutex, Vec, Tensor)>>, encoder: Vec, decoder: Vec, out_ln: LayerNorm, @@ -140,6 +159,7 @@ impl Detector { neck: Neck::new(vb.pp("vision_encoder.neck"))?, text: TextEncoder::new(vb.pp("text_encoder.text_model"))?, text_proj: linear(1024, HIDDEN, vb.pp("text_projection"))?, + texts: Mutex::new(VecDeque::with_capacity(TEXT_CACHE)), encoder, decoder, out_ln: ln(HIDDEN, TORCH_LN_EPS, d.pp("output_layer_norm"))?, @@ -166,9 +186,13 @@ impl Detector { }) } - /// The detector's feature pyramid for the backbone output `[1, 1024, 72, 72]`. - pub fn features(&self, backbone: &Tensor) -> Result { - let levels = self.neck.forward(backbone, 3)?; + /// The detector's feature pyramid for the backbone output `[1, 1024, 72, 72]`, or from its neck's three + /// levels when they were computed elsewhere (an accelerator). + pub fn features(&self, backbone: &Tensor, levels: Option>) -> Result { + let levels = match levels { + Some(levels) => levels, + None => self.neck.forward(backbone, 3)?, + }; let last = levels.last().ok_or_else(|| Error::Model("detector neck".into()))?; let (_, _, side, _) = last.dims4()?; let flat = last.flatten_from(2)?.transpose(1, 2)?.contiguous()?; @@ -176,6 +200,23 @@ impl Detector { Ok(Features { levels, flat, pos, side }) } + /// The prompt's features `[1, 32, 256]`: the CLIP text encoder and its projection, or the same tensor again + /// when the prompt was among the last [`TEXT_CACHE`]. + fn text_features(&self, ids: &[u32], valid: &[bool]) -> Result { + let mut texts = self.texts.lock().unwrap_or_else(PoisonError::into_inner); + if let Some(seen) = texts.iter().position(|(i, v, _)| i == ids && v == valid).and_then(|at| texts.remove(at)) { + let text = seen.2.clone(); + texts.push_back(seen); + return Ok(text); + } + let text = self.text_proj.forward(&self.text.forward(ids, valid)?)?; + if texts.len() >= TEXT_CACHE { + texts.pop_front(); + } + texts.push_back((ids.to_vec(), valid.to_vec(), text.clone())); + Ok(text) + } + /// Box relative-position bias `[1, heads, 1 + 200, side²]` for reference boxes (cx, cy, w, h). fn rpb(&self, boxes: &Tensor, side: usize) -> Result { let xyxy = cxcywh_to_xyxy(boxes)?.squeeze(0)?; // [200, 4] @@ -213,23 +254,143 @@ impl Detector { Ok(Tensor::cat(&[one(1)?, one(0)?, one(2)?, one(3)?], D::Minus1)?) } - /// Run the detector for one tokenized prompt. - pub fn predict(&self, f: &Features, ids: &[u32], valid: &[bool]) -> Result { - let text = self.text_proj.forward(&self.text.forward(ids, valid)?)?; // [1, 32, 256] - let text_bias = padding_bias(valid, &self.device)?; - - // DETR encoder: image tokens attend to themselves and to the prompt + /// The DETR encoder: image tokens attend to themselves and to the prompt. Returns the memory `[1, 5184, 256]`. + fn encode(&self, f: &Features, text: &Tensor, text_bias: &Tensor) -> Result { let mut x = f.flat.clone(); for l in &self.encoder { let h = l.ln1.forward(&x)?; let hp = (&h + &f.pos)?; x = (&x + l.self_attn.forward(&hp, &hp, &h, None)?)?; let h = l.ln2.forward(&x)?; - x = (&x + l.cross_attn.forward(&h, &text, &text, Some(&text_bias))?)?; + x = (&x + l.cross_attn.forward(&h, text, text, Some(text_bias))?)?; let h = l.ln3.forward(&x)?; x = l.mlp.forward_add(&h, &x)?; } - let memory = x; + Ok(x) + } + + /// [`Detector::encode`] on the accelerator; `None` when there is none, or it doesn't run the encoder or fails (the + /// first failure is logged and noted in `accel.failed`, and the accelerator isn't asked again). `Err` when the app is + /// closing. + fn encode_accelerated(&self, f: &Features, text: &Tensor, valid: &[bool], accel: &EncoderAccel) -> Result> { + if accel.failed.get().is_some() { + return Ok(None); + } + let guard = accel.accel.lock().unwrap_or_else(PoisonError::into_inner); + // an accelerator for the backbone only: candle runs this, and that is no failure + let Some(a) = guard.as_ref().filter(|a| a.runs_detr_encoder()) else { return Ok(None) }; + let image = to_vec(&f.flat)?; + let want = image.len(); + // what the decoder can't use is a failure too: a wrong size, or NaN / ∞ from a broken kernel + let checked = a.detr_encoder(&image, &to_vec(&f.pos)?, &to_vec(text)?, valid).and_then(|out| { + if out.len() != want { + Err(format!("it returned {} values instead of {want}", out.len())) + } else if out.iter().any(|v| !v.is_finite()) { + Err("it returned values that are not numbers".into()) + } else { + Ok(out) + } + }); + match checked { + Ok(out) => Ok(Some(Tensor::from_vec(out, f.flat.dims(), &self.device)?)), + Err(e) if a.closing() => Err(Error::Model(e)), + Err(e) => { + log::warn!("SAM 3 DETR encoder not run on {} ({e}); using the {} for it from now on", a.device(), crate::device_name(&self.device)); + let _ = accel.failed.set(format!("{}: {e}", a.device())); + Ok(None) + } + } + } + + /// The mask decoder in candle: the per-query mask logits `[200, 288, 288]` for the encoder memory and the mask + /// embeddings `e` `[1, 200, 256]`. + fn masks(&self, f: &Features, memory: &Tensor, text: &Tensor, text_bias: &Tensor, e: &Tensor) -> Result<(Tensor, Vec)> { + // the encoder memory attends to the prompt, then a pixel decoder up to 288² + let mem = (memory + self.prompt_attn.forward(&self.prompt_ln.forward(memory)?, text, text, Some(text_bias))?)?; + let [l0, l1, _] = &f.levels[..] else { return Err(Error::Model("detector levels".into())) }; + let mut prev = mem.transpose(1, 2)?.reshape((1, HIDDEN, f.side, f.side))?; + for (i, skip) in [l1, l0].into_iter().enumerate() { + let (_, _, sh, sw) = skip.dims4()?; + prev = (prev.upsample_nearest2d(sh, sw)? + skip)?; + let (Some(conv), Some(norm)) = (self.pixel_convs.get(i), self.pixel_norms.get(i)) else { + return Err(Error::Model("pixel decoder".into())); + }; + prev = norm.forward(&conv.forward(&prev)?)?; + } + let inst = self.instance_proj.forward(&prev)?; // [1, 256, 288, 288] + let semantic = to_vec(&self.semantic_proj.forward(&prev)?)?; + let (_, c, mh, mw) = inst.dims4()?; + Ok((e.matmul(&inst.reshape((1, c, mh * mw))?)?.reshape((QUERIES, mh, mw))?, semantic)) + } + + /// [`Detector::masks`] on the accelerator (the semantic mask as one more row of the same product); `None` when there + /// is none, or it doesn't run the mask decoder or fails + /// (the first failure is logged and noted in `accel.masks_failed`, and the accelerator isn't asked again). `Err` when + /// the app is closing. + fn masks_accelerated( + &self, + f: &Features, + memory: &Tensor, + (text, valid): (&Tensor, &[bool]), + e: &Tensor, + accel: &EncoderAccel, + ) -> Result)>> { + if accel.masks_failed.get().is_some() { + return Ok(None); + } + let guard = accel.accel.lock().unwrap_or_else(PoisonError::into_inner); + // an accelerator for the backbone only: candle runs this, and that is no failure + let Some(a) = guard.as_ref().filter(|a| a.runs_mask_decoder()) else { return Ok(None) }; + let [l0, l1, _] = &f.levels[..] else { return Err(Error::Model("detector levels".into())) }; + let (_, _, mh, mw) = l0.dims4()?; + // the instance projection folded into the embeddings: e · (W x + b) = (e W) x + e b, one product per pixel + let e = e.squeeze(0)?; // [200, 256] + let rows = e.matmul(&self.instance_proj.weight().reshape((HIDDEN, HIDDEN))?)?; + let mut bias = match self.instance_proj.bias() { + Some(b) => to_vec(&e.matmul(&b.unsqueeze(1)?)?)?, + None => vec![0.0; QUERIES], + }; + // the semantic projection (1 × 1, 256 → 1) is one more row: the last mask is the semantic one + let rows = Tensor::cat(&[rows, self.semantic_proj.weight().reshape((1, HIDDEN))?], 0)?; + bias.push(match self.semantic_proj.bias() { + Some(b) => to_vec(b)?.first().copied().unwrap_or(0.0), + None => 0.0, + }); + let want = (QUERIES + 1) * mh * mw; + // what the masks can't use is a failure too: a wrong size, or NaN / ∞ from a broken kernel + let checked = a.mask_decoder(&to_vec(memory)?, &to_vec(text)?, valid, [&to_vec(l1)?, &to_vec(l0)?], &to_vec(&rows)?, &bias).and_then(|out| { + if out.len() != want { + Err(format!("it returned {} values instead of {want}", out.len())) + } else if !out.iter().fold(true, |ok, v| ok & v.is_finite()) { + // without short-cutting, so that it vectorizes (17 M values) + Err("it returned values that are not numbers".into()) + } else { + Ok(out) + } + }); + match checked { + Ok(mut out) => { + let semantic = out.split_off(QUERIES * mh * mw); + Ok(Some((Tensor::from_vec(out, (QUERIES, mh, mw), &self.device)?, semantic))) + } + Err(e) if a.closing() => Err(Error::Model(e)), + Err(e) => { + log::warn!("SAM 3 mask decoder not run on {} ({e}); using the {} for it from now on", a.device(), crate::device_name(&self.device)); + let _ = accel.masks_failed.set(format!("{}: {e}", a.device())); + Ok(None) + } + } + } + + /// Run the detector for one tokenized prompt, the DETR encoder and the mask decoder on `accel` when it runs them. + pub fn predict(&self, f: &Features, ids: &[u32], valid: &[bool], accel: &EncoderAccel) -> Result { + let text = self.text_features(ids, valid)?; + let text_bias = padding_bias(valid, &self.device)?; + + let memory = match self.encode_accelerated(f, &text, valid, accel)? { + Some(memory) => memory, + None => self.encode(f, &text, &text_bias)?, + }; // DETR decoder: presence token + 200 queries with iterative box refinement let mut boxes = candle_nn::ops::sigmoid(&self.reference_points)?; @@ -265,21 +426,7 @@ impl Detector { let pq = self.score_query_proj.forward(&queries)?; // [1, 200, 256] let logits = (pq.matmul(&pt.unsqueeze(2)?)? / (HIDDEN as f64).sqrt())?.clamp(-12f32, 12f32)?; - // masks: the encoder memory attends to the prompt, then a pixel decoder up to 288² - let mem = (&memory + self.prompt_attn.forward(&self.prompt_ln.forward(&memory)?, &text, &text, Some(&text_bias))?)?; - let [l0, l1, _] = &f.levels[..] else { return Err(Error::Model("detector levels".into())) }; - let mut prev = mem.transpose(1, 2)?.reshape((1, HIDDEN, f.side, f.side))?; - for (i, skip) in [l1, l0].into_iter().enumerate() { - let (_, _, sh, sw) = skip.dims4()?; - prev = (prev.upsample_nearest2d(sh, sw)? + skip)?; - let (Some(conv), Some(norm)) = (self.pixel_convs.get(i), self.pixel_norms.get(i)) else { - return Err(Error::Model("pixel decoder".into())); - }; - prev = norm.forward(&conv.forward(&prev)?)?; - } - let inst = self.instance_proj.forward(&prev)?; // [1, 256, 288, 288] - let semantic = to_vec(&self.semantic_proj.forward(&prev)?)?; - let (_, c, mh, mw) = inst.dims4()?; + // masks: each query's mask embedding against the mask decoder's per-pixel output let mut e = queries.clone(); for (i, l) in self.mask_embedder.iter().enumerate() { e = l.forward(&e)?; @@ -287,7 +434,10 @@ impl Detector { e = e.relu()?; } } - let masks = e.matmul(&inst.reshape((1, c, mh * mw))?)?.reshape((QUERIES, mh, mw))?; + let (masks, semantic) = match self.masks_accelerated(f, &memory, (&text, valid), &e, accel)? { + Some(masks) => masks, + None => self.masks(f, &memory, &text, &text_bias, &e)?, + }; let boxes = cxcywh_to_xyxy(&boxes)?; let bv = to_vec(&boxes)?; Ok(Output { @@ -297,6 +447,7 @@ impl Detector { boxes: bv.as_chunks::<4>().0.to_vec(), text, semantic, + memory, }) } } @@ -423,7 +574,89 @@ pub fn subject(outs: &[Output], threshold: f32, focus: Option<(f32, f32)>) -> Op #[cfg(test)] mod tests { + use std::path::PathBuf; + use super::*; + use crate::Sam3; + + /// The real checkpoint in `$LIGHTCRAFT_SAM3_DIR` (as the GPU tests), or `None` (the test skips) without it or when it + /// doesn't load. + fn model() -> Option { + let dir = std::env::var_os("LIGHTCRAFT_SAM3_DIR").filter(|v| !v.is_empty()).map(PathBuf::from)?; + if !crate::is_model_dir(&dir) { + return None; + } + match Sam3::load_on(&dir, Device::Cpu) { + Ok(m) => Some(m), + Err(e) => { + eprintln!("the model in {} doesn't load: {e}", dir.display()); + None + } + } + } + + fn values(t: &Tensor) -> Vec { + t.flatten_all().unwrap().to_vec1().unwrap() + } + + #[test] + fn the_box_bias_matches_the_tensor_ops_on_random_boxes() { + let Some(mut m) = model() else { + lightcraft_testkit::skip!(Model, "SAM 3 not installed (set LIGHTCRAFT_SAM3_DIR)"); + return; + }; + let (det, _, _) = m.detector_parts().unwrap(); + let side = 72; + for _ in 0..3 { + let centres = Tensor::rand(0f32, 1.0, (1, QUERIES, 2), &Device::Cpu).unwrap(); + let sizes = Tensor::rand(0.01f32, 0.6, (1, QUERIES, 2), &Device::Cpu).unwrap(); + let boxes = Tensor::cat(&[centres, sizes], 2).unwrap(); + let got = det.rpb(&boxes, side).unwrap(); + // what the other devices run, from the same row and column terms + let xyxy = cxcywh_to_xyxy(&boxes).unwrap().squeeze(0).unwrap(); + let coords = Tensor::arange(0u32, side as u32, &Device::Cpu).unwrap().to_dtype(candle_core::DType::F32).unwrap(); + let coords = coords.affine(1.0 / side as f64, 0.0).unwrap().reshape((1, side, 1)).unwrap(); + let term = |mlp: &DecoderMlp, a: usize, b: usize| { + let pick = Tensor::cat(&[xyxy.narrow(1, a, 1).unwrap(), xyxy.narrow(1, b, 1).unwrap()], 1).unwrap().unsqueeze(1).unwrap(); + let d = (coords.broadcast_sub(&pick).unwrap() * 8.0).unwrap(); + let d = d.sign().unwrap().mul(&((d.abs().unwrap() + 1.0).unwrap().log().unwrap() / 8f64.ln()).unwrap()).unwrap(); + mlp.forward(&d).unwrap() + }; + let (ey, ex) = (term(&det.rpb_y, 1, 3), term(&det.rpb_x, 0, 2)); + let want = ey.unsqueeze(2).unwrap().broadcast_add(&ex.unsqueeze(1).unwrap()).unwrap(); + let want = want.reshape((QUERIES, side * side, HEADS)).unwrap().permute((2, 0, 1)).unwrap().pad_with_zeros(1, 1, 0).unwrap(); + assert_eq!(got.dims(), [1, HEADS, 1 + QUERIES, side * side]); + assert_eq!(values(&got), values(&want)); + } + } + + #[test] + fn prompt_features_are_kept_for_the_latest_prompts() { + let Some(mut m) = model() else { + lightcraft_testkit::skip!(Model, "SAM 3 not installed (set LIGHTCRAFT_SAM3_DIR)"); + return; + }; + let (det, tok, _) = m.detector_parts().unwrap(); + let prompts: Vec<(Vec, Vec)> = (0..=TEXT_CACHE).map(|i| tok.encode(&format!("{i} people"))).collect(); + let features = |i: usize| det.text_features(&prompts[i].0, &prompts[i].1).unwrap(); + let first = features(0); + let fresh = det.text_proj.forward(&det.text.forward(&prompts[0].0, &prompts[0].1).unwrap()).unwrap(); + assert_eq!(values(&first), values(&fresh)); + // the same tensor again, also after other prompts + assert_eq!(features(0).id(), first.id()); + let second = features(1); + for i in 2..TEXT_CACHE { + features(i); + } + assert_eq!(features(0).id(), first.id(), "prompt 0 is the latest one now"); + // one more prompt drops the least recently used, prompt 1, which is computed again + features(TEXT_CACHE); + assert_eq!(det.texts.lock().unwrap().len(), TEXT_CACHE); + assert_eq!(features(0).id(), first.id()); + let again = features(1); + assert_ne!(again.id(), second.id()); + assert_eq!(values(&again), values(&second)); + } /// A group in front is kept, the crowd behind isn't; the camera's focus decides: on a person, /// that person and the others as large; on nobody, nothing (the object there is the subject). @@ -488,6 +721,7 @@ mod tests { boxes: vec![[0.0; 4]; 3], text: Tensor::zeros(1, candle_core::DType::F32, &Device::Cpu).unwrap(), semantic: semantic.to_vec(), + memory: Tensor::zeros(1, candle_core::DType::F32, &Device::Cpu).unwrap(), }; let semantic = [5.0, 6.0, 4.0, 6.0, 5.0]; let merged = merge(&output([4.0, 4.0, -6.0], &semantic), 0.5).unwrap(); diff --git a/crates/segment/src/fetch.rs b/crates/segment/src/fetch.rs index be2a1070f5..1e7cf833c6 100644 --- a/crates/segment/src/fetch.rs +++ b/crates/segment/src/fetch.rs @@ -11,14 +11,21 @@ use std::path::Path; /// The `facebook/sam3` checkpoint files [`crate::Sam3::load`] needs. /// -/// `model.safetensors` is pinned to the official checkpoint (Hugging Face LFS SHA-256). The two -/// tokenizer files are small text files without a pinned hash yet: they are only parsed by the -/// tokenizer (never executed) and capped in size. -// TODO(maintainer): pin `vocab.json` and `merges.txt` (size + SHA-256) when the files are -// uploaded to LightCraft's CDN. +/// All three are pinned (exact size + SHA-256) to the official `facebook/sam3` checkpoint files, +/// checked against a copy of them on 2026-10-13. pub const SAM3_FILES: &[FileSpec] = &[ - FileSpec { name: "vocab.json", size: None, sha256: None, max: 4 << 20 }, - FileSpec { name: "merges.txt", size: None, sha256: None, max: 4 << 20 }, + FileSpec { + name: "vocab.json", + size: Some(862_328), + sha256: Some("5047b556ce86ccaf6aa22b3ffccfc52d391ea4accdab9c2f2407da5b742d4363"), + max: 4 << 20, + }, + FileSpec { + name: "merges.txt", + size: Some(524_619), + sha256: Some("9fd691f7c8039210e0fced15865466c65820d09b63988b0174bfe25de299051a"), + max: 4 << 20, + }, FileSpec { name: crate::WEIGHTS_FILE, size: Some(SAM3_WEIGHTS_SIZE), diff --git a/crates/segment/src/lib.rs b/crates/segment/src/lib.rs index 567cb84abf..1a393f8181 100644 --- a/crates/segment/src/lib.rs +++ b/crates/segment/src/lib.rs @@ -8,9 +8,14 @@ //! The expensive part, the 32-layer ViT over the 1008 × 1008 input, runs once per image //! ([`Sam3::encode`]); each click or prompt then reuses the [`Encoded`] features. //! -//! On macOS the model runs on the GPU through Metal; elsewhere (for now) on the CPU. The -//! weights are not part of LightCraft: they are the `facebook/sam3` checkpoint (SAM License), -//! read from a directory the user downloads them to ([`Sam3::load`]). +//! On macOS the model runs on the GPU through Metal ([`Sam3::load`]). Elsewhere candle runs on +//! the CPU, and the backbone, most of the work, can run outside candle on an accelerator, with +//! the two necks after it ([`BackboneAccel`]: `lightcraft-gpu`'s wgpu kernels on Vulkan / DX12, loaded with +//! [`Sam3::load_accelerated`]); when that can't be built or fails on a photo, the candle backbone +//! takes over ([`Sam3::backbone_fallback`] says why; not while the app is closing: [`BackboneAccel::closing`]). +//! The accelerator can also run the text detector's DETR encoder (else, or once it fails, candle does: +//! [`Sam3::detr_fallback`]). The weights are not part of LightCraft: they are the `facebook/sam3` checkpoint +//! (SAM License), read from a directory the user downloads them to. //! //! Ported from the Hugging Face `transformers` implementation (Apache-2.0); see `NOTICE`. //! This crate is therefore licensed under the Apache License 2.0 only (not the MIT option of @@ -51,13 +56,15 @@ mod weights; use std::path::{Path, PathBuf}; #[cfg(not(target_arch = "wasm32"))] -use std::sync::Arc; +use std::sync::{Arc, Mutex, OnceLock, PoisonError}; #[cfg(not(target_arch = "wasm32"))] -use candle_core::{DType, Device, Tensor}; +use candle_core::{DType, Tensor}; #[cfg(not(target_arch = "wasm32"))] use candle_nn::VarBuilder; +#[cfg(not(target_arch = "wasm32"))] +pub use candle_core::Device; #[cfg(not(target_arch = "wasm32"))] pub use tracker::Click; @@ -111,12 +118,135 @@ pub fn best_device() -> Device { } #[cfg(not(target_arch = "wasm32"))] -/// A loaded model. The vision backbone loads with it; the point and text heads load on first use. +/// Where the backbone's weights are in the checkpoint. +pub const BACKBONE_PREFIX: &str = "detector_model.vision_encoder.backbone"; + +#[cfg(not(target_arch = "wasm32"))] +/// The vision backbone run outside candle (the wgpu compute kernels of `lightcraft-gpu` on +/// Vulkan / DX12 / Metal). It computes what the candle ViT computes, so everything after the +/// backbone (necks, heads) stays as it is. +pub trait BackboneAccel: Send + Sync { + /// `pixels`: `[3, 1008, 1008]` (CHW, normalized to −1..1). Returns the backbone output + /// `[1024, 72, 72]` (CHW), as the candle ViT's `[1, 1024, 72, 72]` without the batch. + fn forward(&self, pixels: &[f32]) -> std::result::Result, String>; + /// What it runs on, for logs and Settings (e.g. "NVIDIA GeForce RTX 5070 (Vulkan)"). + fn device(&self) -> String; + + /// Whether the app is closing, so that an `Err` from it is no failure of the accelerator: it stays in use, and the + /// work ends with that error instead of running in candle (no CPU inference while the app quits). + fn closing(&self) -> bool { + false + } + + /// Whether it runs the necks ([`BackboneAccel::neck`]); when not, they are never asked for and run in candle. + fn runs_necks(&self) -> bool { + false + } + + /// Whether it runs the text detector's DETR encoder ([`BackboneAccel::detr_encoder`]); when not, candle does. + fn runs_detr_encoder(&self) -> bool { + false + } + + /// Whether it runs the text detector's mask decoder ([`BackboneAccel::mask_decoder`]); when not, candle does. + fn runs_mask_decoder(&self) -> bool { + false + } + + /// The feature pyramid of the `which` neck for a backbone output `[1024, 72, 72]` (CHW): the + /// `n` finest levels, each `[256, s, s]` (CHW; s = 288, 144, 72, 36), as the candle `Neck::forward`. + /// `Err` when this accelerator doesn't run it (the candle neck runs instead). + fn neck(&self, which: NeckKind, backbone: &[f32], n: usize) -> std::result::Result>, String> { + let _ = (which, backbone, n); + Err("no neck on this accelerator".into()) + } + + /// The detector's DETR encoder (6 layers): the image tokens `[5184, 256]` with their sine + /// position encoding `pos` `[5184, 256]` attend to themselves and to the prompt `text` + /// `[32, 256]` (`valid` marks its real tokens). Returns the encoder memory `[5184, 256]`. + /// `Err` when this accelerator doesn't run it (the candle encoder runs instead). + fn detr_encoder(&self, image: &[f32], pos: &[f32], text: &[f32], valid: &[bool]) -> std::result::Result, String> { + let _ = (image, pos, text, valid); + Err("no DETR encoder on this accelerator".into()) + } + + /// The detector's mask decoder: the encoder memory `[5184, 256]` attends to the prompt `text` `[32, 256]` (`valid` + /// marks its real tokens) and is added to it, the pixel decoder brings that up to 288² with the detector neck's + /// `levels` `[256, 144, 144]` and `[256, 288, 288]` (CHW), and each of the `rows` `[r, 256]` (1 ≤ r ≤ 256, with + /// `bias` `[r]`) is a 1 × 1 projection of its output. Returns `[r, 288, 288]` (the detector passes its mask + /// embeddings with the instance projection folded in: the per-query mask logits). `Err` when this accelerator + /// doesn't run it (the candle decoder runs instead). + fn mask_decoder( + &self, + memory: &[f32], + text: &[f32], + valid: &[bool], + levels: [&[f32]; 2], + rows: &[f32], + bias: &[f32], + ) -> std::result::Result, String> { + let _ = (memory, text, valid, levels, rows, bias); + Err("no mask decoder on this accelerator".into()) + } +} + +#[cfg(not(target_arch = "wasm32"))] +/// The two feature pyramids of the checkpoint. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum NeckKind { + /// `tracker_neck`: the click decoder's (3 levels). + Tracker, + /// `detector_model.vision_encoder.neck`: the text detector's (3 levels). + Detector, +} + +#[cfg(not(target_arch = "wasm32"))] +/// Read access to a checkpoint's tensors (for accelerators that upload weights themselves; +/// cloning shares the open file, so an accelerator can keep one and load more layers later). +#[derive(Clone)] +pub struct WeightReader(Arc); + +#[cfg(not(target_arch = "wasm32"))] +impl WeightReader { + /// The checkpoint in a model directory (see [`is_model_dir`]). + pub fn open(dir: &Path) -> Result { + if !is_model_dir(dir) { + return Err(Error::Missing(dir.to_path_buf())); + } + Ok(Self(weights::Weights::open(&dir.join(WEIGHTS_FILE))?)) + } + + /// The stored shape of `name`, without reading its data. + pub fn shape(&self, name: &str) -> Option> { + self.0.shape(name).map(<[usize]>::to_vec) + } + + /// Tensor `name`: its shape and its values (f32, row-major). + pub fn read(&self, name: &str) -> Result<(Vec, Vec)> { + let t = self.0.read(name)?; + Ok((t.dims().to_vec(), t.flatten_all()?.to_vec1::()?)) + } +} + +#[cfg(not(target_arch = "wasm32"))] +/// A loaded model. The vision backbone loads with it (unless an accelerator runs it); the point +/// and text heads load on first use. pub struct Sam3 { dir: PathBuf, device: Device, weights: Arc, - backbone: vit::Vit, + /// The candle backbone: loaded with the model, or only when an accelerator fails. + backbone: OnceLock, + accel: Mutex>>, + /// Why the accelerator `load_accelerated` was given is not (or no longer) used. + fallback: Mutex>, + /// Why the DETR encoder runs in candle although there is an accelerator (it failed there once). + detr_fallback: OnceLock, + /// The same for the text detector's mask decoder. + mask_fallback: OnceLock, + /// The necks the accelerator failed on: candle runs them from then on. + necks_off: Mutex>, + /// The candle tracker neck: loaded on first use, unless the accelerator runs it. tracker_neck: Option, tracker: Option, detector: Option, @@ -158,8 +288,124 @@ impl Sam3 { } let weights = weights::Weights::open(&dir.join(WEIGHTS_FILE))?; hugging_face_format(&weights)?; - let backbone = vit::Vit::new(Self::vb(&weights, &device).pp("detector_model.vision_encoder.backbone"))?; - Ok(Self { dir: dir.to_path_buf(), device, weights, backbone, tracker_neck: None, tracker: None, detector: None, tokenizer: None }) + let model = Self::unloaded(dir, device, weights, None); + model.candle_backbone()?; + Ok(model) + } + + /// Load with the backbone on an accelerator `make` builds from the checkpoint, and the rest + /// on `device`. When `make` fails the candle backbone loads instead, and when the + /// accelerator fails later, [`Sam3::encode`] falls back to it (logged, not an error), unless the app is closing. + pub fn load_accelerated( + dir: &Path, + device: Device, + make: impl FnOnce(&WeightReader) -> std::result::Result, String>, + ) -> Result { + let reader = WeightReader::open(dir)?; + hugging_face_format(&reader.0)?; + match make(&reader) { + Ok(accel) => { + log::info!("SAM 3 backbone on {}", accel.device()); + Ok(Self::unloaded(dir, device, reader.0, Some(accel))) + } + Err(e) => { + log::warn!("SAM 3 backbone accelerator unavailable ({e}); using the {}", device_name(&device)); + let model = Self::unloaded(dir, device, reader.0, None); + *model.fallback.lock().unwrap_or_else(PoisonError::into_inner) = Some(e); + model.candle_backbone()?; + Ok(model) + } + } + } + + fn unloaded(dir: &Path, device: Device, weights: Arc, accel: Option>) -> Self { + Self { + dir: dir.to_path_buf(), + device, + weights, + backbone: OnceLock::new(), + accel: Mutex::new(accel), + fallback: Mutex::new(None), + detr_fallback: OnceLock::new(), + mask_fallback: OnceLock::new(), + necks_off: Mutex::new(Vec::new()), + tracker_neck: None, + tracker: None, + detector: None, + tokenizer: None, + } + } + + /// The candle backbone, loading it on first use. + fn candle_backbone(&self) -> Result<&vit::Vit> { + if let Some(b) = self.backbone.get() { + return Ok(b); + } + let b = vit::Vit::new(Self::vb(&self.weights, &self.device).pp(BACKBONE_PREFIX))?; + Ok(self.backbone.get_or_init(|| b)) + } + + /// What the backbone runs on: the accelerator's device, else the candle device ("CPU", "Metal GPU"). + pub fn backbone_device(&self) -> String { + match &*self.accel.lock().unwrap_or_else(PoisonError::into_inner) { + Some(a) => a.device(), + None => device_name(&self.device), + } + } + + /// Whether the backbone runs on the accelerator (rather than in candle). + pub fn accelerated(&self) -> bool { + self.accel.lock().unwrap_or_else(PoisonError::into_inner).is_some() + } + + /// Why the backbone runs in candle although an accelerator was offered: it could not be built, or it failed on + /// a photo (from then on the model stays in candle). `None` when there is no such reason. + pub fn backbone_fallback(&self) -> Option { + self.fallback.lock().unwrap_or_else(PoisonError::into_inner).clone() + } + + /// Why the text detector's DETR encoder runs in candle although the backbone runs on an accelerator: the + /// accelerator doesn't run it or failed on it (then it isn't asked again). `None` when there is no such reason. + pub fn detr_fallback(&self) -> Option { + self.detr_fallback.get().cloned() + } + + /// Why the text detector's mask decoder runs in candle although the backbone runs on an accelerator: the + /// accelerator doesn't run it or failed on it (then it isn't asked again). `None` when there is no such reason. + pub fn mask_fallback(&self) -> Option { + self.mask_fallback.get().cloned() + } + + /// What runs everything after the backbone: the model's device, and which of those parts the accelerator runs + /// (e.g. "CPU; the necks, the DETR encoder and the mask decoder on the GPU"). + pub fn heads_device(&self) -> String { + let base = device_name(&self.device); + // what the accelerator runs (none: there is none any more), less what failed on it + let (necks, detr, masks) = match self.accel.lock().unwrap_or_else(PoisonError::into_inner).as_ref() { + Some(a) => (a.runs_necks(), a.runs_detr_encoder(), a.runs_mask_decoder()), + None => (false, false, false), + }; + let mut gpu = Vec::new(); + if necks { + let off = self.necks_off.lock().unwrap_or_else(PoisonError::into_inner); + match (off.contains(&NeckKind::Tracker), off.contains(&NeckKind::Detector)) { + (false, false) => gpu.push("the necks"), + (false, true) => gpu.push("the click neck"), + (true, false) => gpu.push("the text neck"), + (true, true) => {} + } + } + if detr && self.detr_fallback.get().is_none() { + gpu.push("the DETR encoder"); + } + if masks && self.mask_fallback.get().is_none() { + gpu.push("the mask decoder"); + } + match gpu.split_last() { + None => base, + Some((last, [])) => format!("{base}; {last} on the GPU"), + Some((last, rest)) => format!("{base}; {} and {last} on the GPU", rest.join(", ")), + } } fn vb<'a>(w: &Arc, device: &Device) -> VarBuilder<'a> { @@ -180,30 +426,133 @@ impl Sam3 { /// Run the backbone on preprocessed pixels `[1, 3, 1008, 1008]` (−1..1). pub fn encode_pixels(&self, pixels: &Tensor) -> Result { - Ok(Encoded { backbone: self.backbone.forward(&pixels.to_device(&self.device)?)?, tracker: None, detector: None }) + let side = vit::GRID; + { + let mut accel = self.accel.lock().unwrap_or_else(PoisonError::into_inner); + if let Some(a) = accel.as_ref() { + let px = pixels.to_device(&Device::Cpu)?.flatten_all()?.to_vec1::()?; + // what the necks can't use is a failure too: a wrong size, or NaN / ∞ from a broken kernel + let want = vit::HIDDEN * side * side; + let checked = a.forward(&px).and_then(|out| { + if out.len() != want { + Err(format!("it returned {} values instead of {want}", out.len())) + } else if out.iter().any(|v| !v.is_finite()) { + Err("it returned values that are not numbers".into()) + } else { + Ok(out) + } + }); + match checked { + Ok(out) => { + let backbone = Tensor::from_vec(out, (1, vit::HIDDEN, side, side), &self.device)?; + return Ok(Encoded { backbone, tracker: None, detector: None }); + } + Err(e) if a.closing() => return Err(Error::Model(e)), + Err(e) => { + log::warn!("SAM 3 backbone failed on {} ({e}); using the {} from now on", a.device(), device_name(&self.device)); + *self.fallback.lock().unwrap_or_else(PoisonError::into_inner) = Some(format!("{} failed: {e}", a.device())); + *accel = None; + } + } + } + } + let backbone = self.candle_backbone()?.forward(&pixels.to_device(&self.device)?)?; + Ok(Encoded { backbone, tracker: None, detector: None }) } - fn tracker_parts(&mut self) -> Result<(&neck::Neck, &tracker::Tracker)> { - if self.tracker_neck.is_none() { - self.tracker_neck = Some(neck::Neck::new(Self::vb(&self.weights, &self.device).pp("tracker_neck"))?); + /// The `n` finest levels of the `which` neck for `backbone`, computed by the accelerator and put on the model's + /// device; `None` when there is no accelerator, it doesn't run this neck or failed on it (logged once; candle + /// runs that neck from then on). `Err` when the app is closing. + fn accel_neck(&self, which: NeckKind, backbone: &Tensor, n: usize) -> Result>> { + let accel = self.accel.lock().unwrap_or_else(PoisonError::into_inner); + // an accelerator for the backbone only: the necks run in candle, and that is no failure + let Some(a) = accel.as_ref().filter(|a| a.runs_necks()) else { return Ok(None) }; + let mut off = self.necks_off.lock().unwrap_or_else(PoisonError::into_inner); + if off.contains(&which) { + return Ok(None); } + let run = || -> std::result::Result, String> { + let x = backbone.to_device(&Device::Cpu).and_then(|t| t.flatten_all()).and_then(|t| t.to_vec1::()).map_err(|e| e.to_string())?; + let levels = a.neck(which, &x, n)?; + if levels.len() != n { + return Err(format!("it returned {} levels instead of {n}", levels.len())); + } + levels + .into_iter() + .enumerate() + .map(|(i, l)| { + // what the heads can't use is a failure too: a wrong size, or NaN / ∞ from a broken kernel + let side = tracker::LOW_RES >> i; + if l.len() != neck::FPN * side * side { + return Err(format!("it returned {} values for level {i} instead of {}", l.len(), neck::FPN * side * side)); + } + // without short-cutting, so that it vectorizes (28 M values) + if !l.iter().fold(true, |ok, v| ok & v.is_finite()) { + return Err("it returned values that are not numbers".into()); + } + Tensor::from_vec(l, (1, neck::FPN, side, side), &self.device).map_err(|e| e.to_string()) + }) + .collect() + }; + match run() { + Ok(levels) => Ok(Some(levels)), + Err(e) if a.closing() => Err(Error::Model(e)), + Err(e) => { + let name = match which { + NeckKind::Tracker => "tracker", + NeckKind::Detector => "detector", + }; + log::warn!("SAM 3 {name} neck failed on {} ({e}); using the {} for it from now on", a.device(), device_name(&self.device)); + off.push(which); + Ok(None) + } + } + } + + fn tracker(&mut self) -> Result<&tracker::Tracker> { if self.tracker.is_none() { self.tracker = Some(tracker::Tracker::new(Self::vb(&self.weights, &self.device).pp("tracker_model"))?); } - match (&self.tracker_neck, &self.tracker) { - (Some(n), Some(t)) => Ok((n, t)), - _ => Err(Error::Model("tracker failed to load".into())), + self.tracker.as_ref().ok_or_else(|| Error::Model("tracker failed to load".into())) + } + + /// The click decoder's features for `enc`, once: the tracker neck on the accelerator when it runs it, else in + /// candle. + fn tracker_features(&mut self, enc: &mut Encoded) -> Result<()> { + if enc.tracker.is_some() { + return Ok(()); } + let levels = match self.accel_neck(NeckKind::Tracker, &enc.backbone, 3)? { + Some(levels) => levels, + None => { + if self.tracker_neck.is_none() { + self.tracker_neck = Some(neck::Neck::new(Self::vb(&self.weights, &self.device).pp("tracker_neck"))?); + } + let neck = self.tracker_neck.as_ref().ok_or_else(|| Error::Model("tracker neck failed to load".into()))?; + neck.forward(&enc.backbone, 3)? + } + }; + enc.tracker = Some(self.tracker()?.features(&levels)?); + Ok(()) + } + + /// The `which` neck's three finest levels for `enc`, each `[1, 256, s, s]` (tests and tools): on the + /// accelerator when it runs it, else in candle. + pub fn neck_levels(&self, which: NeckKind, enc: &Encoded) -> Result> { + if let Some(levels) = self.accel_neck(which, &enc.backbone, 3)? { + return Ok(levels); + } + let prefix = match which { + NeckKind::Tracker => "tracker_neck", + NeckKind::Detector => "detector_model.vision_encoder.neck", + }; + neck::Neck::new(Self::vb(&self.weights, &self.device).pp(prefix))?.forward(&enc.backbone, 3) } /// Compute the click decoder's features for `enc` now (so the first click is fast). pub fn prepare_clicks(&mut self, enc: &mut Encoded) -> Result<()> { - let (neck, tracker) = self.tracker_parts()?; - if enc.tracker.is_none() { - let levels = neck.forward(&enc.backbone, 3)?; - enc.tracker = Some(tracker.features(&levels)?); - } - Ok(()) + self.tracker()?; + self.tracker_features(enc) } /// Segment one object from clicks (positions normalized to the image, 0..1). @@ -215,18 +564,15 @@ impl Sam3 { if clicks.len() > MAX_CLICKS { return Err(Error::Model(format!("at most {MAX_CLICKS} clicks, not {}", clicks.len()))); } - let (neck, tracker) = self.tracker_parts()?; - if enc.tracker.is_none() { - let levels = neck.forward(&enc.backbone, 3)?; - enc.tracker = Some(tracker.features(&levels)?); - } + self.tracker_features(enc)?; + let tracker = self.tracker()?; let f = enc.tracker.as_ref().ok_or_else(|| Error::Model("tracker features".into()))?; // one click: SAM's three alternatives, best by predicted IoU; more: the single mask let p = tracker.predict(f, clicks, clicks.len() == 1)?; Ok(Prediction { logits: p.logits, score: p.iou * sigmoid(p.object_score) }) } - fn detector_parts(&mut self) -> Result<(&detector::Detector, &tokenizer::Tokenizer)> { + fn detector_parts(&mut self) -> Result<(&detector::Detector, &tokenizer::Tokenizer, detector::EncoderAccel<'_>)> { if self.detector.is_none() { self.detector = Some(detector::Detector::new(Self::vb(&self.weights, &self.device).pp("detector_model"))?); } @@ -234,22 +580,32 @@ impl Sam3 { self.tokenizer = Some(tokenizer::Tokenizer::load(&self.dir)?); } match (&self.detector, &self.tokenizer) { - (Some(d), Some(t)) => Ok((d, t)), + (Some(d), Some(t)) => { + Ok((d, t, detector::EncoderAccel { accel: &self.accel, failed: &self.detr_fallback, masks_failed: &self.mask_fallback })) + } _ => Err(Error::Model("detector failed to load".into())), } } + /// The detector's features for `enc`, once: its neck on the accelerator when it runs it, else in candle. + fn detector_features(&mut self, enc: &mut Encoded) -> Result<()> { + if enc.detector.is_none() { + let levels = self.accel_neck(NeckKind::Detector, &enc.backbone, 3)?; + let (det, _, _) = self.detector_parts()?; + enc.detector = Some(det.features(&enc.backbone, levels)?); + } + Ok(()) + } + /// Segment every instance of the concept `text` names. Instances scoring above /// `threshold` (0..1, 0.5 is the reference default) are merged into one mask; `None` when /// nothing matches. pub fn segment_text(&mut self, enc: &mut Encoded, text: &str, threshold: f32) -> Result> { - let (det, tok) = self.detector_parts()?; - if enc.detector.is_none() { - enc.detector = Some(det.features(&enc.backbone)?); - } + self.detector_features(enc)?; + let (det, tok, accel) = self.detector_parts()?; let f = enc.detector.as_ref().ok_or_else(|| Error::Model("detector features".into()))?; let (ids, valid) = tok.encode(text); - let out = det.predict(f, &ids, &valid)?; + let out = det.predict(f, &ids, &valid, &accel)?; Ok(detector::merge(&out, threshold)) } @@ -264,13 +620,11 @@ impl Sam3 { /// Raw detector outputs for `text` (tests and tools). pub fn detect(&mut self, enc: &mut Encoded, text: &str) -> Result { - let (det, tok) = self.detector_parts()?; - if enc.detector.is_none() { - enc.detector = Some(det.features(&enc.backbone)?); - } + self.detector_features(enc)?; + let (det, tok, accel) = self.detector_parts()?; let f = enc.detector.as_ref().ok_or_else(|| Error::Model("detector features".into()))?; let (ids, valid) = tok.encode(text); - det.predict(f, &ids, &valid) + det.predict(f, &ids, &valid, &accel) } } @@ -282,6 +636,16 @@ impl Encoded { } } +#[cfg(not(target_arch = "wasm32"))] +/// A candle device as people call it ("CPU", "Metal GPU"). +pub fn device_name(device: &Device) -> String { + match device { + Device::Cpu => "CPU".into(), + Device::Metal(_) => "Metal GPU".into(), + Device::Cuda(_) => "CUDA GPU".into(), + } +} + #[cfg(not(target_arch = "wasm32"))] /// Meta's original checkpoint (`sam3.pt`, or a `sam3.safetensors` conversion of it as on community /// mirrors) names its tensors differently: say so, rather than name the first tensor it lacks (#3378). @@ -314,6 +678,191 @@ pub fn sync(model: &Sam3) -> Result<()> { mod tests { use super::*; + /// A model folder whose checkpoint holds no tensors: enough to load with an accelerator, never to run candle. + #[allow(clippy::unwrap_used)] + fn empty_model(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("lc-sam3-{name}-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let mut st = 2u64.to_le_bytes().to_vec(); + st.extend_from_slice(b"{}"); + std::fs::write(dir.join(WEIGHTS_FILE), st).unwrap(); + std::fs::write(dir.join("vocab.json"), "{}").unwrap(); + std::fs::write(dir.join("merges.txt"), "").unwrap(); + dir + } + + /// Answers with `values` backbone values, all `fill`, or fails. + struct Fake { + values: usize, + fill: f32, + fail: bool, + } + + impl BackboneAccel for Fake { + fn forward(&self, pixels: &[f32]) -> std::result::Result, String> { + assert_eq!(pixels.len(), 3 * INPUT * INPUT); + if self.fail { Err("device lost".into()) } else { Ok(vec![self.fill; self.values]) } + } + fn device(&self) -> String { + "Fake GPU (Vulkan)".into() + } + } + + const FULL: usize = vit::HIDDEN * vit::GRID * vit::GRID; + + fn with(fake: Fake) -> impl FnOnce(&WeightReader) -> std::result::Result, String> { + move |_| Ok(Box::new(fake)) + } + + #[test] + fn the_backbone_runs_on_the_accelerator_without_loading_candle() { + let dir = empty_model("accel"); + let m = Sam3::load_accelerated(&dir, Device::Cpu, with(Fake { values: FULL, fill: 0.25, fail: false })).unwrap(); + assert!(m.accelerated()); + assert_eq!(m.backbone_device(), "Fake GPU (Vulkan)"); + assert_eq!(m.backbone_fallback(), None); + // an accelerator for the backbone only: the rest is candle's + assert_eq!(m.heads_device(), "CPU"); + let enc = m.encode(&[128; 4 * 3 * 3], 4, 3).unwrap(); + assert_eq!(enc.backbone().dims(), [1, vit::HIDDEN, vit::GRID, vit::GRID]); + assert!(m.backbone.get().is_none(), "the candle backbone was never loaded"); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn an_accelerator_that_cannot_be_built_leaves_the_backbone_to_candle() { + let dir = empty_model("nomake"); + // the empty checkpoint has no candle backbone: the load fails, but only after trying it + let r = Sam3::load_accelerated(&dir, Device::Cpu, |_| Err("no adapter".into())); + assert!(r.is_err_and(|e| !e.to_string().contains("no adapter"))); + std::fs::remove_dir_all(dir).unwrap(); + } + + /// A backbone of `fill`, and neck levels of the right sizes (filled with their index) for the tracker; for the + /// detector the third level is cut short (`short`) or holds a NaN. + struct NeckFake { + calls: Arc, + short: bool, + } + + impl BackboneAccel for NeckFake { + fn forward(&self, _: &[f32]) -> std::result::Result, String> { + Ok(vec![0.5; FULL]) + } + fn device(&self) -> String { + "Fake GPU (Vulkan)".into() + } + fn runs_necks(&self) -> bool { + true + } + fn neck(&self, which: NeckKind, backbone: &[f32], n: usize) -> std::result::Result>, String> { + self.calls.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + assert_eq!((backbone.len(), backbone[0]), (FULL, 0.5)); + let mut levels: Vec> = (0..n).map(|i| vec![i as f32; neck::FPN * (tracker::LOW_RES >> i).pow(2)]).collect(); + if which == NeckKind::Detector { + if self.short { + levels[2].pop(); + } else { + levels[2][7] = f32::NAN; + } + } + Ok(levels) + } + } + + #[test] + fn neck_levels_come_from_the_accelerator_and_a_failing_neck_is_left_to_candle() { + for short in [true, false] { + let dir = empty_model(&format!("neck-{short}")); + let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let fake = NeckFake { calls: calls.clone(), short }; + let m = Sam3::load_accelerated(&dir, Device::Cpu, move |_| Ok(Box::new(fake))).unwrap(); + let enc = m.encode(&[128; 4 * 3 * 3], 4, 3).unwrap(); + assert_eq!(m.heads_device(), "CPU; the necks on the GPU"); + let levels = m.accel_neck(NeckKind::Tracker, enc.backbone(), 3).unwrap().unwrap(); + for (i, (l, side)) in levels.iter().zip([288, 144, 72]).enumerate() { + assert_eq!(l.dims(), [1, neck::FPN, side, side]); + assert_eq!(l.flatten_all().unwrap().max(0).unwrap().to_scalar::().unwrap(), i as f32); + } + // a wrong level: candle's neck from then on, without asking again + assert!(m.accel_neck(NeckKind::Detector, enc.backbone(), 3).unwrap().is_none()); + assert!(m.accel_neck(NeckKind::Detector, enc.backbone(), 3).unwrap().is_none()); + assert_eq!(calls.load(std::sync::atomic::Ordering::Relaxed), 2); + assert_eq!(m.heads_device(), "CPU; the click neck on the GPU"); + // the other neck and the backbone stay on the accelerator + assert!(m.accel_neck(NeckKind::Tracker, enc.backbone(), 3).unwrap().is_some()); + assert_eq!(calls.load(std::sync::atomic::Ordering::Relaxed), 3); + assert!(m.accelerated()); + std::fs::remove_dir_all(dir).unwrap(); + } + } + + /// Fails as the GPU does once the app is closing (the backbone or, with a backbone of zeros, a neck). + struct Closing { + backbone: bool, + } + + impl BackboneAccel for Closing { + fn forward(&self, _: &[f32]) -> std::result::Result, String> { + if self.backbone { Err("LightCraft is closing".into()) } else { Ok(vec![0.0; FULL]) } + } + fn device(&self) -> String { + "Fake GPU (Vulkan)".into() + } + fn closing(&self) -> bool { + true + } + fn runs_necks(&self) -> bool { + true + } + fn neck(&self, _: NeckKind, _: &[f32], _: usize) -> std::result::Result>, String> { + Err("LightCraft is closing".into()) + } + } + + #[test] + fn closing_is_no_accelerator_failure_and_nothing_runs_in_candle() { + let dir = empty_model("closing"); + let m = Sam3::load_accelerated(&dir, Device::Cpu, with_closing(true)).unwrap(); + let e = m.encode(&[128; 4 * 3 * 3], 4, 3).err().unwrap(); + assert!(e.to_string().contains("LightCraft is closing"), "{e}"); + assert!(m.backbone.get().is_none(), "the candle backbone was never loaded"); + assert!(m.accelerated()); + assert_eq!((m.backbone_device().as_str(), m.backbone_fallback()), ("Fake GPU (Vulkan)", None)); + // a neck: the error, not candle's neck, and the accelerator keeps it + let m = Sam3::load_accelerated(&dir, Device::Cpu, with_closing(false)).unwrap(); + let enc = m.encode(&[128; 4 * 3 * 3], 4, 3).unwrap(); + for which in [NeckKind::Tracker, NeckKind::Detector] { + assert!(m.accel_neck(which, enc.backbone(), 3).is_err_and(|e| e.to_string().contains("closing")), "{which:?}"); + assert!(m.neck_levels(which, &enc).is_err_and(|e| e.to_string().contains("closing")), "{which:?}"); + } + assert_eq!(m.heads_device(), "CPU; the necks on the GPU"); + std::fs::remove_dir_all(dir).unwrap(); + } + + fn with_closing(backbone: bool) -> impl FnOnce(&WeightReader) -> std::result::Result, String> { + move |_| Ok(Box::new(Closing { backbone })) + } + + #[test] + fn a_failing_or_wrong_accelerator_is_dropped_for_candle() { + for (name, fake, why) in [ + ("fail", Fake { values: FULL, fill: 0.0, fail: true }, "device lost"), + ("short", Fake { values: 10, fill: 0.0, fail: false }, "returned 10 values"), + ("nan", Fake { values: FULL, fill: f32::NAN, fail: false }, "not numbers"), + ] { + let dir = empty_model(name); + let m = Sam3::load_accelerated(&dir, Device::Cpu, with(fake)).unwrap(); + // the candle backbone takes over (and fails here: the checkpoint is empty) + assert!(m.encode(&[128; 4 * 3 * 3], 4, 3).is_err(), "{name}"); + assert!(!m.accelerated(), "{name}"); + assert_eq!(m.backbone_device(), "CPU", "{name}"); + let fallback = m.backbone_fallback().unwrap(); + assert!(fallback.starts_with("Fake GPU (Vulkan) failed: ") && fallback.contains(why), "{name}: {fallback}"); + std::fs::remove_dir_all(dir).unwrap(); + } + } + #[test] fn meta_original_checkpoint_is_named_as_such() { // #3378: a community mirror's `sam3.safetensors` (Meta's key names, C64 RoPE tables) saved as model.safetensors diff --git a/crates/segment/src/nn.rs b/crates/segment/src/nn.rs index 0749d9c72a..fb832e0c06 100644 --- a/crates/segment/src/nn.rs +++ b/crates/segment/src/nn.rs @@ -171,15 +171,25 @@ impl DecoderMlp { Ok(Self { layers }) } + /// On the CPU the hidden layers' bias add and ReLU are fused ([`cpu::linear_act`]: the box bias's MLPs have + /// 200 · 72 rows of 256). pub fn forward(&self, x: &Tensor) -> Result { + let mut dims = x.dims().to_vec(); let mut x = x.clone(); for (i, l) in self.layers.iter().enumerate() { - x = l.forward(&x)?; - if i + 1 < self.layers.len() { - x = x.relu()?; - } + x = if i + 1 == self.layers.len() { + l.forward(&x)? + } else if x.device().is_cpu() { + cpu::linear_act(&x, l, false)? + } else { + l.forward(&x)?.relu()? + }; } - Ok(x) + // the fused layers return rows + if let Some(last) = dims.last_mut() { + *last = x.dim(D::Minus1)?; + } + Ok(x.reshape(dims)?) } } @@ -286,3 +296,29 @@ pub fn cxcywh_to_xyxy(b: &Tensor) -> Result { pub fn to_vec(t: &Tensor) -> Result> { Ok(t.to_dtype(DType::F32)?.flatten_all()?.to_vec1::()?) } + +#[cfg(test)] +mod tests { + use candle_core::{DType, Device}; + use candle_nn::VarMap; + + use super::*; + + #[test] + fn a_decoder_mlp_over_rows_matches_linear_per_batch() { + let vars = VarMap::new(); + let vb = VarBuilder::from_varmap(&vars, DType::F32, &Device::Cpu); + let mlp = DecoderMlp::new(2, 256, 8, 2, vb).unwrap(); + let x = Tensor::randn(0f32, 1.0, (200, 72, 2), &Device::Cpu).unwrap(); + let mut want = x.clone(); + for (i, l) in mlp.layers.iter().enumerate() { + want = l.forward(&want).unwrap(); + if i + 1 < mlp.layers.len() { + want = want.relu().unwrap(); + } + } + let got = mlp.forward(&x).unwrap(); + assert_eq!(got.dims(), [200, 72, 8]); + assert_eq!(got.flatten_all().unwrap().to_vec1::().unwrap(), want.flatten_all().unwrap().to_vec1::().unwrap()); + } +} diff --git a/crates/segment/src/remote.rs b/crates/segment/src/remote.rs index 4f23d10bc7..2534e9ff05 100644 --- a/crates/segment/src/remote.rs +++ b/crates/segment/src/remote.rs @@ -10,6 +10,7 @@ use serde::{Deserialize, Serialize}; const CONTROL_LIMIT: usize = 16 * 1024; const RESPONSE_LIMIT: usize = 4 * 1024 * 1024; const TIMEOUT: Duration = Duration::from_secs(9 * 60); +const ACCEPT_RETRY_DELAY: Duration = Duration::from_millis(100); pub const ENV: &str = "LIGHTCRAFT_SAM3_REMOTE"; #[derive(Serialize, Deserialize)] @@ -194,6 +195,30 @@ fn serve_client(stream: &mut TcpStream, dir: &Path, device: candle_core::Device) } } +fn serve_connections(incoming: I, mut handle_client: H, mut retry_sleep: S) +where + I: IntoIterator>, + H: FnMut(&mut C) -> Result<(), String>, + S: FnMut(Duration), +{ + for connection in incoming { + let mut stream = match connection { + Ok(stream) => stream, + Err(error) => { + eprintln!("SAM3 accept failed: {error}"); + retry_sleep(ACCEPT_RETRY_DELAY); + continue; + } + }; + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| handle_client(&mut stream))); + match result { + Ok(Err(error)) => eprintln!("SAM3 session closed: {error}"), + Err(_) => eprintln!("SAM3 session panicked; model released"), + Ok(Ok(())) => {} + } + } +} + pub fn serve(address: SocketAddr, dir: &Path, device: candle_core::Device) -> Result<(), String> { if !address.ip().is_loopback() || !device.is_metal() { return Err("SAM worker requires a loopback address and a Metal device".into()); @@ -203,14 +228,97 @@ pub fn serve(address: SocketAddr, dir: &Path, device: candle_core::Device) -> Re } let listener = TcpListener::bind(address).map_err(|e| e.to_string())?; eprintln!("SAM3 worker listening on {address}; device=Metal; idle unload=600s"); - for stream in listener.incoming() { - let mut stream = stream.map_err(|e| e.to_string())?; - let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| serve_client(&mut stream, dir, device.clone()))); - match result { - Ok(Err(error)) => eprintln!("SAM3 session closed: {error}"), - Err(_) => eprintln!("SAM3 session panicked; model released"), - Ok(Ok(())) => {} - } - } + serve_connections(listener.incoming(), |stream| serve_client(stream, dir, device.clone()), std::thread::sleep); Ok(()) } + +#[cfg(test)] +mod tests { + use super::*; + + fn accept_error() -> io::Result { + Err(io::Error::new(io::ErrorKind::ConnectionAborted, "injected accept failure")) + } + + #[test] + fn sam_accept_error_before_client_keeps_serving() { + let mut handled = Vec::new(); + serve_connections( + [accept_error(), Ok(1_u8)], + |stream| { + handled.push(*stream); + Ok(()) + }, + |_| {}, + ); + + assert_eq!(handled, [1]); + } + + #[test] + fn sam_accept_error_between_clients_keeps_serving() { + let mut handled = Vec::new(); + serve_connections( + [Ok(1_u8), accept_error(), Ok(2_u8)], + |stream| { + handled.push(*stream); + Ok(()) + }, + |_| {}, + ); + + assert_eq!(handled, [1, 2]); + } + + #[test] + fn sam_accept_repeated_errors_back_off() { + let mut handled = Vec::new(); + let mut delays = Vec::new(); + serve_connections( + [accept_error(), accept_error(), Ok(1_u8)], + |stream| { + handled.push(*stream); + Ok(()) + }, + |delay| delays.push(delay), + ); + + assert_eq!(handled, [1]); + assert_eq!(delays, [Duration::from_millis(100), Duration::from_millis(100)]); + } + + #[test] + fn sam_accept_client_failure_keeps_serving() { + let mut handled = Vec::new(); + let mut delays = Vec::new(); + serve_connections( + [Ok(1_u8), Ok(2_u8)], + |stream| { + handled.push(*stream); + if *stream == 1 { Err("injected client failure".into()) } else { Ok(()) } + }, + |delay| delays.push(delay), + ); + + assert_eq!(handled, [1, 2]); + assert!(delays.is_empty()); + } + + #[test] + fn sam_accept_client_panic_keeps_serving() { + let mut handled = Vec::new(); + serve_connections( + [Ok(1_u8), Ok(2_u8)], + |stream| { + handled.push(*stream); + if *stream == 1 { + std::panic::resume_unwind(Box::new("injected client panic")); + } + Ok(()) + }, + |_| {}, + ); + + assert_eq!(handled, [1, 2]); + } +} diff --git a/crates/segment/tests/it/accel.rs b/crates/segment/tests/it/accel.rs new file mode 100644 index 0000000000..ad8dad3c11 --- /dev/null +++ b/crates/segment/tests/it/accel.rs @@ -0,0 +1,58 @@ +//! A backbone accelerator that fails leaves the work to candle, with the real checkpoint. +//! +//! Needs the model: `$LIGHTCRAFT_SAM3_DIR`, else the desktop app's folder (`~/.config/lightcraft/models/sam3` on +//! Linux). Skipped when it is missing. Runs the candle backbone once on the CPU (about half a minute in release). + +use std::path::PathBuf; + +use lightcraft_segment::{BackboneAccel, Device, Sam3, WeightReader}; + +fn model_dir() -> Option { + // only `$LIGHTCRAFT_SAM3_DIR`, as the GPU tests: never whatever is in the user's model folder + let dir = std::env::var_os("LIGHTCRAFT_SAM3_DIR").filter(|v| !v.is_empty()).map(PathBuf::from)?; + lightcraft_segment::is_model_dir(&dir).then_some(dir) +} + +/// Fails on every photo, as a GPU that lost its device would. +struct Lost; + +impl BackboneAccel for Lost { + fn forward(&self, _: &[f32]) -> Result, String> { + Err("device lost".into()) + } + fn device(&self) -> String { + "Lost GPU (Vulkan)".into() + } +} + +#[test] +fn an_accelerator_failing_on_a_photo_falls_back_to_candle() { + let Some(dir) = model_dir() else { + lightcraft_testkit::skip!(Model, "SAM 3 not installed (set LIGHTCRAFT_SAM3_DIR)"); + return; + }; + let m = Sam3::load_accelerated(&dir, Device::Cpu, |_: &WeightReader| Ok(Box::new(Lost) as Box)).unwrap(); + assert!(m.accelerated()); + assert_eq!(m.backbone_device(), "Lost GPU (Vulkan)"); + let (w, h) = (64, 48); + let rgb: Vec = (0..w * h * 3).map(|i| (i % 251) as u8).collect(); + let enc = m.encode(&rgb, w, h).unwrap(); + assert_eq!(enc.backbone().dims(), [1, 1024, 72, 72]); + let v = enc.backbone().flatten_all().unwrap().to_vec1::().unwrap(); + assert!(v.iter().all(|x| x.is_finite()) && v.iter().any(|x| *x != 0.0), "candle computed the features"); + assert!(!m.accelerated()); + assert_eq!(m.backbone_device(), "CPU"); + assert_eq!(m.backbone_fallback().as_deref(), Some("Lost GPU (Vulkan) failed: device lost")); +} + +#[test] +fn an_accelerator_that_cannot_be_built_loads_candles_backbone() { + let Some(dir) = model_dir() else { + lightcraft_testkit::skip!(Model, "SAM 3 not installed (set LIGHTCRAFT_SAM3_DIR)"); + return; + }; + let m = Sam3::load_accelerated(&dir, Device::Cpu, |_| Err("no GPU adapter".into())).unwrap(); + assert!(!m.accelerated()); + assert_eq!(m.backbone_device(), "CPU"); + assert_eq!(m.backbone_fallback().as_deref(), Some("no GPU adapter")); +} diff --git a/crates/segment/tests/it/main.rs b/crates/segment/tests/it/main.rs index 4dcb685916..629ae5f085 100644 --- a/crates/segment/tests/it/main.rs +++ b/crates/segment/tests/it/main.rs @@ -1,4 +1,6 @@ //! The integration tests, one module per file, linked into one test binary. +mod accel; +mod prompts; mod reference; mod remote; diff --git a/crates/segment/tests/it/prompts.rs b/crates/segment/tests/it/prompts.rs new file mode 100644 index 0000000000..1ff14679e8 --- /dev/null +++ b/crates/segment/tests/it/prompts.rs @@ -0,0 +1,63 @@ +//! A text prompt seen before reuses its features, with the same detector output as the first time. +//! +//! Needs the model: `$LIGHTCRAFT_SAM3_DIR`, else the desktop app's folder (`~/.config/lightcraft/models/sam3` on +//! Linux). Skipped when it is missing. The backbone output is made up (no ViT run); the necks, the text encoder +//! and the detector are candle's on the CPU. + +use std::path::PathBuf; + +use candle_core::Tensor; +use lightcraft_segment::{BackboneAccel, DetectorOutput, Device, Sam3}; + +fn model_dir() -> Option { + // only `$LIGHTCRAFT_SAM3_DIR`, as the GPU tests: never whatever is in the user's model folder + let dir = std::env::var_os("LIGHTCRAFT_SAM3_DIR").filter(|v| !v.is_empty()).map(PathBuf::from)?; + lightcraft_segment::is_model_dir(&dir).then_some(dir) +} + +/// A backbone output `[1024, 72, 72]` that varies over the channels and the grid. +struct Waves; + +impl BackboneAccel for Waves { + fn forward(&self, _: &[f32]) -> Result, String> { + Ok((0..1024 * 72 * 72).map(|i| (i as f32 * 0.37).sin() * 0.5).collect()) + } + fn device(&self) -> String { + "Waves (test)".into() + } +} + +fn values(t: &Tensor) -> Vec { + t.flatten_all().unwrap().to_vec1().unwrap() +} + +fn assert_same(a: &DetectorOutput, b: &DetectorOutput) { + assert_eq!(a.logits, b.logits); + assert_eq!(a.presence, b.presence); + assert_eq!(a.boxes, b.boxes); + assert_eq!(values(&a.text), values(&b.text)); + assert_eq!(values(&a.memory), values(&b.memory)); + assert_eq!(values(&a.masks), values(&b.masks)); +} + +#[test] +fn a_repeated_prompt_gives_the_same_output() { + let Some(dir) = model_dir() else { + lightcraft_testkit::skip!(Model, "SAM 3 not installed (set LIGHTCRAFT_SAM3_DIR)"); + return; + }; + let mut m = Sam3::load_accelerated(&dir, Device::Cpu, |_| Ok(Box::new(Waves) as Box)).unwrap(); + let (w, h) = (64, 48); + let rgb: Vec = (0..w * h * 3).map(|i| (i % 251) as u8).collect(); + let mut enc = m.encode(&rgb, w, h).unwrap(); + let fresh = m.detect(&mut enc, "person").unwrap(); + m.detect(&mut enc, "sky").unwrap(); + let cached = m.detect(&mut enc, "person").unwrap(); + assert_eq!(cached.text.id(), fresh.text.id(), "the prompt's features were reused"); + assert_same(&cached, &fresh); + // and on the next photo + let mut next = m.encode(&rgb, w, h).unwrap(); + let again = m.detect(&mut next, "person").unwrap(); + assert_eq!(again.text.id(), fresh.text.id()); + assert_same(&again, &fresh); +} diff --git a/crates/ui-egui/examples/thumb_request_bench.rs b/crates/ui-egui/examples/thumb_request_bench.rs index 728059b0e3..091482eda0 100644 --- a/crates/ui-egui/examples/thumb_request_bench.rs +++ b/crates/ui-egui/examples/thumb_request_bench.rs @@ -207,7 +207,7 @@ fn real() { p.kind = probe.kind; p.meta = probe.meta; p.as_shot_wb = probe.as_shot_wb; - p.embedded_lens = probe.embedded_lens; + p.embedded_lens = probe.embedded_lens.map(Box::new); p.content_hash = probe.content_hash; p.preview_only = probe.preview_only; lightcraft_engine::import::apply_import_defaults(&session, &mut p); diff --git a/crates/ui-egui/locales/cs-formats.json b/crates/ui-egui/locales/cs-formats.json index f62de3260a..afd4435bb8 100644 --- a/crates/ui-egui/locales/cs-formats.json +++ b/crates/ui-egui/locales/cs-formats.json @@ -303,10 +303,10 @@ "Color space: Rec. 2020 {curve} (HDR AVIF)": "Barevný prostor: Rec. 2020 {curve} (HDR AVIF)", "{n} selected photo{} · {pages} page{}": "Vybrané fotografie: {n} · stránek: {pages}{:.0}{:.0}", "Already in “{}”": "Již v „{}“", - "Move {n} photo{} to “{}”": "Přesunout do „{1}“ fotografie: {n}{0:.0}", - "Move {n} photo{} to “{}”?": "Přesunout do „{1}“ fotografie: {n}{0:.0}?", + "Move {n} file{} to “{}”": "Přesunout do „{1}“ soubory: {n}{0:.0}", + "Move {n} file{} to “{}”?": "Přesunout do „{1}“ soubory: {n}{0:.0}?", "Listing folders — folders: {folders}, files: {files}": "Procházení složek – složky: {folders}, soubory: {files}", - "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "Do „{1}“ přesunuto fotografií: {n}{0:.0}. Úpravy → Zpět je vrátí.", + "Moved {n} file{} to “{}”. Edit → Undo moves them back.": "Do „{1}“ přesunuto souborů: {n}{0:.0}. Úpravy → Zpět je vrátí.", "Drop to review {n} item{} for import": "Pusťte pro kontrolu před importem (položek: {n}){:.0}", "Drop to import {n} item{}": "Pusťte pro import (položek: {n}){:.0}", "Drop to import {n} preset{}": "Pusťte pro import přednastavení: {n}{:.0}", @@ -322,11 +322,16 @@ "Panel move was not applied: {error}": "Přesun panelu nebyl použit: {error}", "{name} is installed": "{name} je nainstalován", "{name} is installed and in use: face recognition is on": "{name} je nainstalován a používán: rozpoznávání obličejů je zapnuto", + "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} s, kodér obrazu {encoder:.1} s", "Bring photos in with File › Import Photos… ({keys}).": "Fotografie importujete přes Soubor › Importovat fotografie… ({keys}).", "View › Detail View ({keys}).": "Zobrazení › Zobrazení detailu ({keys}).", "File › Export… · File › Print… ({keys}).": "Soubor › Exportovat… · Soubor › Tisk… ({keys}).", "{n} folder{} could not be read": "Složky, které se nepodařilo přečíst: {n}{:.0}", "{n} file{} skipped (not a supported photo type)": "Přeskočené soubory (nejde o podporovaný typ fotografie): {n}{:.0}", + "It leads back to itself through “{}”: change the rules of one album on the loop (Edit Smart Album…)": "Vede zpět samo na sebe přes album „{}“: změňte pravidla jednoho alba ve smyčce (Upravit inteligentní album…)", + "Add {n} photo{} to “{}”": "Přidat do „{1}“ fotografie: {n}{0:.0}", + "{n} already there": "již tam je: {n}", + "Add “{keyword}” to {n} photo{}": "Přidat „{keyword}“ k fotografiím: {n}{:.0}", "Rule {n} of {m}: {what}. Move with the arrow keys": "Pravidlo {n} z {m}: {what}. Přesun pomocí šipek", "Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "Skupina {n} z {m}: shoda {mode}, uvnitř {count}. Přesun pomocí šipek", ", rating {} of 5": ", hodnocení: {} z 5" diff --git a/crates/ui-egui/locales/cs.json b/crates/ui-egui/locales/cs.json index 39eaa5a400..67eabc903b 100644 --- a/crates/ui-egui/locales/cs.json +++ b/crates/ui-egui/locales/cs.json @@ -60,6 +60,7 @@ "Import photos with File → Import Photos…, or drop them here": "Importujte fotografie přes Soubor → Importovat fotografie… nebo je přetáhněte sem", "This row covers more than one disk: drop on a folder inside it": "Tento řádek zahrnuje více disků: přetáhněte položky na některou ze složek v něm", "Local photos aren't in the library yet: Add to My Photos first, then move them": "Místní fotografie zatím nejsou v knihovně: nejprve použijte Přidat do mých fotografií a pak je přesuňte", + "Demo photos have no file on disk, so they can't be moved": "Ukázkové fotografie nemají soubor na disku, proto je nelze přesunout", "Add to My Photos First": "Nejprve přidat do mých fotografií", "Add to Selected Photos": "Přidat k vybraným fotografiím", "Add to Target Album": "Přidat do cílového alba", @@ -277,6 +278,7 @@ "Before/After (Y)": "Před/Po (Y)", "Before/After Settings": "Nastavení Před/Po", "Before/After Split": "Rozdělené Před/Po", + "Before/After": "Před/Po", "Before/After Split Top/Bottom": "Rozdělené Před/Po nahoře/dole", "Before/After Top/Bottom": "Před/Po nahoře/dole", "Begin Interaction": "Zahájit interakci", @@ -507,6 +509,7 @@ "Cut": "Vyjmout", "Cut pages": "Vyjmout stránky", "Cycle Crop Overlay": "Přepnout překrytí ořezu", + "Crop Overlay": "Překrytí ořezu", "Cycle Crop Overlay Orientation": "Přepnout orientaci překrytí ořezu", "Cycle Info Overlay": "Přepnout překrytí informací", "Cycle Mask Overlay Color": "Přepnout barvu překrytí masky", @@ -2067,6 +2070,7 @@ "XMP sidecars": "Přidružené soubory XMP", "Year": "Rok", "Yellow": "Žlutá", + "White": "Bílá", "Yellow Hue": "Odstín žluté", "Yellow Luminance": "Jas žluté", "Yellow Saturation": "Sytost žluté", @@ -2255,6 +2259,9 @@ "Display profile not used": "Profil displeje nebyl použit", "Drag to set hue and saturation. Hold Shift to keep the hue, Cmd/Ctrl to keep the saturation, Alt/Option to fine-adjust. Double-click to reset.": "Tažením nastavíte odstín a sytost. Podržením Shift zachováte odstín, Cmd/Ctrl zachováte sytost, Alt/Option umožní jemné doladění. Dvojitým kliknutím obnovíte výchozí hodnoty.", "Edit In": "Upravit v", + "Filter settings": "Filtrovat nastavení", + "No setting matches what is typed.": "Zadanému textu neodpovídá žádné nastavení.", + "Try one word, or part of one: the names of tabs and sections, labels and explanations are all looked through.": "Zkuste jedno slovo nebo jeho část: prohledávají se názvy karet a sekcí, popisky i vysvětlivky.", "Face models (ONNX)": "Modely rozpoznávání obličejů (ONNX)", "ICC Profiles": "Profily ICC", "Next History Step": "Další krok historie", @@ -2451,6 +2458,13 @@ "The photos are imported once it ends": "Fotky se naimportují potom", "An import is running. Drop photos when it has finished": "Import už běží. Fotky přetáhněte, až skončí", "Finish Lightroom catalog import before adding photos": "Dokončete import katalogu Lightroom, než přidáte fotky", + "Mixer": "Směšovač", + "HSL": "HSL", + "Adjust": "Upravit", + "Color Mixer Layout": "Rozvržení směšovače barev", + "Loupe Overlay": "Překrytí lupy", + "View Options…": "Možnosti zobrazení…", + "View → Loupe Overlay → View Options chooses the lines Info 1 and Info 2 show.": "Zobrazení → Překrytí lupy → Možnosti zobrazení určuje, které řádky zobrazují Info 1 a Info 2.", "Profile: from the file (the camera's own correction)": "Profil: ze souboru (vlastní korekce fotoaparátu)", "Downloading the lens database…": "Stahuje se databáze objektivů…", "This file names no lens.": "Tento soubor neuvádí žádný objektiv.", @@ -2481,6 +2495,14 @@ "Top bar": "Horní lišta", "Tool strip": "Pruh nástrojů", "Bottom bar": "Dolní lišta", + "AI masks": "AI masky", + "Device": "Zařízení", + "Last photo": "Poslední fotka", + "Remote worker": "Vzdálený proces", + "Run on": "Spouštět na", + "Automatic (GPU when available)": "Automaticky (GPU, je-li k dispozici)", + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer.": "Masky Objekt a Popsat analyzují každou fotku jednou, na grafické kartě, pokud není zvoleno CPU nebo vypnuto „Použít GPU pro vykreslování“. Na procesoru to trvá mnohem déle.", + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "Automaticky spouští model na grafické kartě Macu. Pokud tam AI masky selhávají, zvolte CPU; na procesoru trvají mnohem déle.", "User Templates": "Uživatelské šablony", "Delete Folder": "Odstranit složku", "Folder name": "Název složky", @@ -2508,6 +2530,18 @@ "Next": "Další", "Get Started": "Začít", "Stopped at the scan limit: there may be more photos": "Zastaveno na limitu skenování: je možné, že existují další fotografie", + "Keywords and presets apply to new files only, not to photos already in Local": "Klíčová slova a předvolby se použijí jen u nových souborů, ne u fotografií, které už jsou v Místních souborech", + "This album is in a loop, so it shows nothing": "Toto album je ve smyčce, a proto nic nezobrazuje", + "It tests itself: change its rules (Edit Smart Album…)": "Testuje samo sebe: změňte jeho pravidla (Upravit inteligentní album…)", + "Can't add to an album folder": "Nelze přidat do složky alb", + "An album folder holds albums, not photos: drop on an album inside it": "Složka alb obsahuje alba, ne fotografie: pusťte je na album uvnitř", + "Can't add to a smart album": "Nelze přidat do inteligentního alba", + "A smart album's rules choose its photos: change them with Edit Smart Album…": "O fotografiích inteligentního alba rozhodují jeho pravidla: změníte je přes Upravit inteligentní album…", + "Add keywords in the Keyword List": "Klíčová slova přidávejte v Seznamu klíčových slov", + "Give photos a keyword in the Keyword List (Window → Keywords, K): drop them on it there": "Klíčové slovo fotografiím přidáte v Seznamu klíčových slov (Okno → Klíčová slova, K): pusťte je tam na klíčové slovo", + "Already on these photos": "Už je mají", + "Can't go inside itself": "Nemůže jít samo do sebe", + "Same Content as Another Photo": "Stejný obsah jako jiná fotografie", "Reduce Motion": "Omezit pohyb", "Reduce motion": "Omezit pohyb", "Turns off zoom and spinner animations. Fades stay. Follows the system's Reduce Motion until you change it here.": "Vypne animace přiblížení a načítacích indikátorů. Prolínání zůstává. Dokud to zde nezměníte, řídí se nastavením Omezit pohyb v systému.", @@ -2520,5 +2554,11 @@ "Stack — click to collapse (S)": "Sada — kliknutím sbalíte (S)", "Virtual copy": "Virtuální kopie", "Right-click ▸ Locate Missing File… to find it again.": "Klikněte pravým tlačítkem → Najít chybějící soubor… a najděte jej znovu.", - "Right-click ▸ Reload from Disk to try again.": "Klikněte pravým tlačítkem → Znovu načíst z disku a zkuste to znovu." + "Right-click ▸ Reload from Disk to try again.": "Klikněte pravým tlačítkem → Znovu načíst z disku a zkuste to znovu.", + "Album name (empty outside an album view)": "Název alba (prázdné mimo zobrazení alba)", + "Export date (YYYYMMDD)": "Datum exportu (YYYYMMDD)", + "Export time (HHMM)": "Čas exportu (HHMM)", + "Insert variable": "Vložit proměnnou", + "Insert…": "Vložit…", + "none ({album}, {date}, {hour})": "žádné ({album}, {date}, {hour})" } diff --git a/crates/ui-egui/locales/de-formats.json b/crates/ui-egui/locales/de-formats.json index 867e14b5a5..591920bdf8 100644 --- a/crates/ui-egui/locales/de-formats.json +++ b/crates/ui-egui/locales/de-formats.json @@ -306,10 +306,10 @@ "{what} merge added at {mp}: its full size, {full}, needs more memory than this computer has": "{what}-Zusammenfügung mit {mp} hinzugefügt: die volle Größe, {full}, braucht mehr Arbeitsspeicher, als dieser Computer hat", "{what} merge added at {mp}, the largest a panorama can be (its full size is {full})": "{what}-Zusammenfügung mit {mp} hinzugefügt, der größten möglichen Panoramagröße (volle Größe: {full})", "Already in “{}”": "Bereits in „{}“", - "Move {n} photo{} to “{}”": "{n} Foto{0} nach „{1}“ verschieben", - "Move {n} photo{} to “{}”?": "{n} Foto{0} nach „{1}“ verschieben?", + "Move {n} file{} to “{}”": "Nach „{1}“ verschieben (Dateien: {n}){0:.0}", + "Move {n} file{} to “{}”?": "Nach „{1}“ verschieben (Dateien: {n})?{0:.0}", "Listing folders — folders: {folders}, files: {files}": "Ordner werden aufgelistet – Ordner: {folders}, Dateien: {files}", - "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "{n} Foto{0} nach „{1}“ verschoben. Bearbeiten → Rückgängig holt sie zurück.", + "Moved {n} file{} to “{}”. Edit → Undo moves them back.": "Nach „{1}“ verschoben (Dateien: {n}). Bearbeiten → Rückgängig holt sie zurück.{0:.0}", "Drop to review {n} item{} for import": "Ablegen, um vor dem Import zu prüfen (Objekte: {n}){:.0}", "Drop to import {n} item{}": "Ablegen zum Importieren (Objekte: {n}){:.0}", "Drop to import {n} preset{}": "Ablegen zum Importieren von Vorgaben: {n}{:.0}", @@ -325,9 +325,14 @@ "Panel move was not applied: {error}": "Das Verschieben des Bereichs wurde nicht ausgeführt: {error}", "{name} is installed": "{name} ist installiert", "{name} is installed and in use: face recognition is on": "{name} ist installiert und in Gebrauch: Gesichtserkennung ist eingeschaltet", + "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} s, Bildencoder {encoder:.1} s", "Bring photos in with File › Import Photos… ({keys}).": "Fotos holen Sie mit Datei › Fotos importieren… ({keys}) in die Bibliothek.", "View › Detail View ({keys}).": "Ansicht › Detailansicht ({keys}).", "File › Export… · File › Print… ({keys}).": "Datei › Exportieren… · Datei › Drucken… ({keys}).", + "It leads back to itself through “{}”: change the rules of one album on the loop (Edit Smart Album…)": "Es führt über das Album „{}“ zu sich selbst zurück: Ändere die Regeln eines Albums im Kreis (Smart-Album bearbeiten…)", + "Add {n} photo{} to “{}”": "{n} Foto{0} zu „{1}“ hinzufügen", + "{n} already there": "{n} bereits enthalten", + "Add “{keyword}” to {n} photo{}": "„{keyword}“ zu {n} Foto{} hinzufügen", "Rule {n} of {m}: {what}. Move with the arrow keys": "Regel {n} von {m}: {what}. Mit den Pfeiltasten verschieben", "Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "Gruppe {n} von {m}: erfülle {mode}, {count} darin. Mit den Pfeiltasten verschieben", ", rating {} of 5": ", Bewertung: {} von 5" diff --git a/crates/ui-egui/locales/de.json b/crates/ui-egui/locales/de.json index 991ca0b761..fda9bc920c 100644 --- a/crates/ui-egui/locales/de.json +++ b/crates/ui-egui/locales/de.json @@ -60,6 +60,7 @@ "Import photos with File → Import Photos…, or drop them here": "Importiere Fotos über Datei → Fotos importieren… oder lege sie hier ab", "This row covers more than one disk: drop on a folder inside it": "Diese Zeile umfasst mehr als ein Laufwerk: auf einem Ordner darin ablegen", "Local photos aren't in the library yet: Add to My Photos first, then move them": "Lokale Fotos sind noch nicht in der Bibliothek: erst zu „Meine Fotos“ hinzufügen, dann verschieben", + "Demo photos have no file on disk, so they can't be moved": "Demofotos haben keine Datei auf dem Datenträger und lassen sich deshalb nicht verschieben", "Add to Selected Photos": "Zu ausgewählten Fotos hinzufügen", "Add to Target Album": "Zu Zielalbum hinzufügen", "Add to this mask": "Zu dieser Maske hinzufügen", @@ -157,6 +158,7 @@ "Before/After (Y)": "Vorher/Nachher (Y)", "Before/After Settings": "Vorher/Nachher-Einstellungen", "Before/After Split": "Vorher/Nachher geteilt", + "Before/After": "Vorher/Nachher", "Before/After Split Top/Bottom": "Vorher/Nachher geteilt – oben/unten", "Before/After Top/Bottom": "Vorher/Nachher – oben/unten", "Begin Interaction": "Interaktion beginnen", @@ -371,6 +373,7 @@ "Cut": "Ausschneiden", "Cut pages": "Seiten ausschneiden", "Cycle Crop Overlay": "Zuschnittüberlagerung wechseln", + "Crop Overlay": "Zuschnittüberlagerung", "Cycle Crop Overlay Orientation": "Ausrichtung der Zuschnittüberlagerung wechseln", "Cycle Info Overlay": "Infoüberlagerung wechseln", "Cycle Mask Overlay Color": "Farbe der Maskenüberlagerung wechseln", @@ -1672,6 +1675,7 @@ "XMP sidecars": "XMP-Begleitdateien", "Year": "Jahr", "Yellow": "Gelb", + "White": "Weiß", "Yellow Hue": "Gelb – Farbton", "Yellow Luminance": "Gelb – Luminanz", "Yellow Saturation": "Gelb – Sättigung", @@ -2096,6 +2100,9 @@ "Not saved": "Nicht gespeichert", "A folder is being synchronized": "Ein Ordner wird gerade synchronisiert", "Wait for the import to finish": "Warte, bis der Import abgeschlossen ist", + "Filter settings": "Einstellungen filtern", + "No setting matches what is typed.": "Keine Einstellung passt zur Eingabe.", + "Try one word, or part of one: the names of tabs and sections, labels and explanations are all looked through.": "Versuche ein Wort oder einen Teil davon: Durchsucht werden die Namen der Tabs und Abschnitte, Beschriftungen und Erklärungen.", "Appearance": "Erscheinungsbild", "Appearance Mode": "Erscheinungsmodus", "Sync with System": "Mit System synchronisieren", @@ -2358,6 +2365,28 @@ "CPU": "CPU", "A face model uses the GPU only when a check shows it gives the same results faster.": "Ein Gesichtsmodell nutzt die GPU nur, wenn eine Prüfung zeigt, dass sie dieselben Ergebnisse schneller liefert.", "Checking the GPU for faces": "GPU für Gesichter wird geprüft", + "Bursts": "Serien", + "Burst": "Serie", + "Photo → Assisted Culling… groups look-alike shots into bursts. They show here to put right by hand.": "Foto → Unterstützte Fotoauswahl… fasst ähnliche Aufnahmen zu Serien zusammen. Hier lassen sie sich von Hand korrigieren.", + "Drag a photo to its place: the first of a burst is its pick. Drag one into another burst, or a burst by its title onto another to merge them.": "Ziehe ein Foto an seinen Platz: Das erste einer Serie ist ihre Auswahl. Ziehe ein Foto in eine andere Serie oder eine Serie an ihrem Titel auf eine andere, um sie zusammenzuführen.", + "New burst": "Neue Serie", + "Not in a burst": "In keiner Serie", + "Run Assisted Culling on it first": "Zuerst die unterstützte Fotoauswahl darauf anwenden", + "Run Assisted Culling on these photos first": "Zuerst die unterstützte Fotoauswahl auf diese Fotos anwenden", + "Only photos Assisted Culling scored can be in a burst: run Photo → Assisted Culling… on them first": "Nur Fotos, die die unterstützte Fotoauswahl bewertet hat, können in einer Serie sein: Wende zuerst Foto → Unterstützte Fotoauswahl… darauf an", + "Merge into this burst": "Mit dieser Serie zusammenführen", + "Make it the pick": "Zur Auswahl machen", + "Put first: the first is the pick": "An den Anfang: Das erste ist die Auswahl", + "Move here": "Hierher verschieben", + "Move to this burst": "In diese Serie verschieben", + "Take out of its burst": "Aus der Serie nehmen", + "Regroup bursts I arranged by hand": "Von Hand geordnete Serien neu gruppieren", + "Put bursts right by dragging in Window → Bursts: the first photo of a burst is its pick, and culling again keeps what you arranged.": "Serien lassen sich unter Fenster → Serien per Ziehen korrigieren: Das erste Foto einer Serie ist ihre Auswahl, und eine erneute Fotoauswahl behält, was du geordnet hast.", + "Choose Burst Pick": "Auswahl der Serie wählen", + "Rearrange Burst": "Serie umordnen", + "Move to Burst": "In Serie verschieben", + "New Burst": "Neue Serie", + "Remove from Burst": "Aus Serie nehmen", "Set Folder Color Label": "Ordner-Farbmarkierung festlegen", "Photo Below": "Foto darunter", "Photo Above": "Foto darüber", @@ -3485,6 +3514,12 @@ "The photos are imported once it ends": "Die Fotos werden danach importiert", "An import is running. Drop photos when it has finished": "Ein Import läuft. Lege die Fotos ab, wenn er fertig ist", "Finish Lightroom catalog import before adding photos": "Schließe den Import des Lightroom-Katalogs ab, bevor du Fotos hinzufügst", + "Mixer": "Mischer", + "HSL": "HSL", + "Adjust": "Anpassen", + "Color Mixer Layout": "Farbmischer-Ansicht", + "View Options…": "Ansichtsoptionen…", + "View → Loupe Overlay → View Options chooses the lines Info 1 and Info 2 show.": "Ansicht → Lupenüberlagerung → Ansichtsoptionen legt fest, welche Zeilen Info 1 und Info 2 zeigen.", "Camera preview": "Kameravorschau", "The camera's own JPEG, shown until LightCraft has rendered the raw. Judge colour and tone on the rendered photo.": "Das eigene JPEG der Kamera, angezeigt, bis LightCraft die Raw-Datei gerendert hat. Farbe und Tonwerte am gerenderten Foto beurteilen.", "Profile: from the file (the camera's own correction)": "Profil: aus der Datei (Korrektur der Kamera)", @@ -3518,6 +3553,14 @@ "Tool strip": "Werkzeugleiste", "Bottom bar": "Untere Leiste", "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "G-SYNC-/FreeSync-Flimmern verhindern (gilt ab dem nächsten Start)", + "AI masks": "KI-Masken", + "Device": "Gerät", + "Last photo": "Letztes Foto", + "Remote worker": "Entfernter Worker", + "Run on": "Ausführen auf", + "Automatic (GPU when available)": "Automatisch (GPU, wenn vorhanden)", + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer.": "Objekt- und Beschreiben-Masken analysieren jedes Foto einmal, auf der Grafikkarte, außer CPU ist gewählt oder „GPU zum Rendern verwenden“ ist aus. Auf dem Prozessor dauert das deutlich länger.", + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "Automatisch führt das Modell auf der Grafikkarte des Mac aus. Wähle CPU, wenn KI-Masken dort scheitern; auf dem Prozessor dauern sie deutlich länger.", "User Templates": "Benutzervorlagen", "Delete Folder": "Ordner löschen", "Folder name": "Ordnername", @@ -3544,6 +3587,18 @@ "Welcome": "Willkommen", "Next": "Weiter", "Get Started": "Loslegen", + "Keywords and presets apply to new files only, not to photos already in Local": "Stichwörter und Vorgaben gelten nur für neue Dateien, nicht für Fotos, die schon in „Lokal“ sind", + "This album is in a loop, so it shows nothing": "Dieses Album ist in einem Kreis und zeigt deshalb nichts", + "It tests itself: change its rules (Edit Smart Album…)": "Es prüft sich selbst: Ändere seine Regeln (Smart-Album bearbeiten…)", + "Can't add to an album folder": "Nicht zu einem Albenordner hinzufügbar", + "An album folder holds albums, not photos: drop on an album inside it": "Ein Albenordner enthält Alben, keine Fotos: auf ein Album darin ablegen", + "Can't add to a smart album": "Nicht zu einem Smart-Album hinzufügbar", + "A smart album's rules choose its photos: change them with Edit Smart Album…": "Die Regeln eines Smart-Albums bestimmen seine Fotos: ändere sie mit Smart-Album bearbeiten…", + "Add keywords in the Keyword List": "Stichwörter in der Stichwortliste hinzufügen", + "Give photos a keyword in the Keyword List (Window → Keywords, K): drop them on it there": "Stichwörter vergibst du in der Stichwortliste (Fenster → Stichwörter, K): Fotos dort auf ein Stichwort ziehen", + "Already on these photos": "Bereits bei diesen Fotos", + "Can't go inside itself": "Kann nicht in sich selbst liegen", + "Same Content as Another Photo": "Gleicher Inhalt wie ein anderes Foto", "Reduce Motion": "Bewegung reduzieren", "Reduce motion": "Bewegung reduzieren", "Turns off zoom and spinner animations. Fades stay. Follows the system's Reduce Motion until you change it here.": "Schaltet Zoom- und Ladeanimationen ab. Überblendungen bleiben erhalten. Folgt der Systemeinstellung „Bewegung reduzieren“, bis Sie sie hier ändern.", @@ -3556,5 +3611,11 @@ "Stack — click to collapse (S)": "Stapel — Klicken zum Zuklappen (S)", "Virtual copy": "Virtuelle Kopie", "Right-click ▸ Locate Missing File… to find it again.": "Rechtsklick → Fehlende Datei suchen…, um sie wiederzufinden.", - "Right-click ▸ Reload from Disk to try again.": "Rechtsklick → Vom Datenträger neu laden, um es erneut zu versuchen." + "Right-click ▸ Reload from Disk to try again.": "Rechtsklick → Vom Datenträger neu laden, um es erneut zu versuchen.", + "Album name (empty outside an album view)": "Albumname (leer außerhalb einer Albumansicht)", + "Export date (YYYYMMDD)": "Exportdatum (YYYYMMDD)", + "Export time (HHMM)": "Exportzeit (HHMM)", + "Insert variable": "Variable einfügen", + "Insert…": "Einfügen…", + "none ({album}, {date}, {hour})": "keine ({album}, {date}, {hour})" } diff --git a/crates/ui-egui/locales/es-formats.json b/crates/ui-egui/locales/es-formats.json index 50b868a3e7..54b8c3c2f6 100644 --- a/crates/ui-egui/locales/es-formats.json +++ b/crates/ui-egui/locales/es-formats.json @@ -306,10 +306,10 @@ "{what} merge added at {mp}: its full size, {full}, needs more memory than this computer has": "Combinación {what} añadida a {mp}: el tamaño completo, {full}, necesita más memoria de la que tiene este ordenador", "{what} merge added at {mp}, the largest a panorama can be (its full size is {full})": "Combinación {what} añadida a {mp}, el tamaño máximo de una panorámica (tamaño completo: {full})", "Already in “{}”": "Ya está en “{}”", - "Move {n} photo{} to “{}”": "Mover {n} foto{0} a “{1}”", - "Move {n} photo{} to “{}”?": "¿Mover {n} foto{0} a “{1}”?", + "Move {n} file{} to “{}”": "Mover {n} archivo{0} a “{1}”", + "Move {n} file{} to “{}”?": "¿Mover {n} archivo{0} a “{1}”?", "Listing folders — folders: {folders}, files: {files}": "Listando carpetas — carpetas: {folders}, archivos: {files}", - "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "{n} foto{0} movida{0} a “{1}”. Editar → Deshacer las devuelve.", + "Moved {n} file{} to “{}”. Edit → Undo moves them back.": "{n} archivo{0} movido{0} a “{1}”. Editar → Deshacer los devuelve.", "Drop to review {n} item{} for import": "Suelta para revisar {n} elemento{} antes de importar", "Drop to import {n} item{}": "Suelta para importar {n} elemento{}", "Drop to import {n} preset{}": "Suelta para importar {n} ajuste{0} preestablecido{0}", @@ -325,9 +325,14 @@ "Panel move was not applied: {error}": "No se aplicó el movimiento del panel: {error}", "{name} is installed": "{name} está instalado", "{name} is installed and in use: face recognition is on": "{name} está instalado y en uso: el reconocimiento facial está activado", + "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} s, codificador de imagen {encoder:.1} s", "Bring photos in with File › Import Photos… ({keys}).": "Importa fotos con Archivo › Importar fotos… ({keys}).", "View › Detail View ({keys}).": "Vista › Vista de detalle ({keys}).", "File › Export… · File › Print… ({keys}).": "Archivo › Exportar… · Archivo › Imprimir… ({keys}).", + "It leads back to itself through “{}”: change the rules of one album on the loop (Edit Smart Album…)": "Vuelve a sí mismo a través del álbum “{}”: cambia las reglas de uno de los álbumes del bucle (Editar álbum inteligente…)", + "Add {n} photo{} to “{}”": "Añadir {n} foto{0} a “{1}”", + "{n} already there": "ya en el álbum: {n}", + "Add “{keyword}” to {n} photo{}": "Añadir “{keyword}” a {n} foto{}", "Rule {n} of {m}: {what}. Move with the arrow keys": "Regla {n} de {m}: {what}. Mover con las teclas de flecha", "Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "Grupo {n} de {m}: coincidir con {mode}, {count} dentro. Mover con las teclas de flecha", ", rating {} of 5": ", valoración: {} de 5" diff --git a/crates/ui-egui/locales/es.json b/crates/ui-egui/locales/es.json index 40a7f31562..4f51d68d42 100644 --- a/crates/ui-egui/locales/es.json +++ b/crates/ui-egui/locales/es.json @@ -45,6 +45,7 @@ "Import photos with File → Import Photos…, or drop them here": "Importar fotos con Archivo → Importar fotos… o soltarlas aquí", "This row covers more than one disk: drop on a folder inside it": "Esta fila abarca más de un disco: suéltalas en una carpeta dentro de ella", "Local photos aren't in the library yet: Add to My Photos first, then move them": "Las fotos locales aún no están en la biblioteca: primero Añadir a Mis fotos y luego muévelas", + "Demo photos have no file on disk, so they can't be moved": "Las fotos de demostración no tienen archivo en el disco, así que no se pueden mover", "Add to Selected Photos": "Añadir a las fotos seleccionadas", "Add to Target Album": "Añadir al álbum de destino", "Add to this mask": "Añadir a esta máscara", @@ -140,6 +141,7 @@ "Before/After (Y)": "Antes/Después (Y)", "Before/After Settings": "Ajustes de Antes/Después", "Before/After Split": "Antes/Después dividido", + "Before/After": "Antes/Después", "Before/After Split Top/Bottom": "Antes/Después dividido arriba/abajo", "Before/After Top/Bottom": "Antes/Después arriba/abajo", "Begin Interaction": "Iniciar interacción", @@ -360,6 +362,7 @@ "Cut": "Cortar", "Cut pages": "Cortar páginas", "Cycle Crop Overlay": "Alternar superposición de recorte", + "Crop Overlay": "Superposición de recorte", "Cycle Crop Overlay Orientation": "Alternar orientación de la superposición de recorte", "Cycle Info Overlay": "Alternar superposición de información", "Cycle Mask Overlay Color": "Alternar color de superposición de máscara", @@ -1778,6 +1781,7 @@ "XMP sidecars": "Archivos XMP complementarios", "Year": "Año", "Yellow": "Amarillo", + "White": "Blanco", "Yellow Hue": "Tono amarillo", "Yellow Luminance": "Luminancia amarilla", "Yellow Saturation": "Saturación amarilla", @@ -2122,6 +2126,9 @@ "Not saved": "Sin guardar", "A folder is being synchronized": "Se está sincronizando una carpeta", "Wait for the import to finish": "Esperar a que termine la importación", + "Filter settings": "Filtrar ajustes", + "No setting matches what is typed.": "Ningún ajuste coincide con lo escrito.", + "Try one word, or part of one: the names of tabs and sections, labels and explanations are all looked through.": "Prueba con una palabra o parte de ella: se buscan los nombres de pestañas y secciones, las etiquetas y las explicaciones.", "Appearance": "Apariencia", "Appearance Mode": "Modo de apariencia", "Sync with System": "Sincronizar con el sistema", @@ -2402,6 +2409,13 @@ "The photos are imported once it ends": "Las fotos se importarán después", "An import is running. Drop photos when it has finished": "Hay una importación en curso. Suelta las fotos cuando termine", "Finish Lightroom catalog import before adding photos": "Termina la importación del catálogo de Lightroom antes de añadir fotos", + "Mixer": "Mezclador", + "HSL": "HSL", + "Adjust": "Ajustar", + "Color Mixer Layout": "Disposición del mezclador de color", + "Loupe Overlay": "Superposición de la lupa", + "View Options…": "Opciones de vista…", + "View → Loupe Overlay → View Options chooses the lines Info 1 and Info 2 show.": "Vista → Superposición de la lupa → Opciones de vista elige las líneas que muestran Info 1 e Info 2.", "Camera preview": "Vista previa de la cámara", "The camera's own JPEG, shown until LightCraft has rendered the raw. Judge colour and tone on the rendered photo.": "El JPEG propio de la cámara, mostrado hasta que LightCraft haya renderizado el RAW. Juzga el color y el tono en la foto renderizada.", "Profile: from the file (the camera's own correction)": "Perfil: del archivo (corrección de la propia cámara)", @@ -2436,6 +2450,14 @@ "Tool strip": "Barra de herramientas", "Bottom bar": "Barra inferior", "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Evitar el parpadeo de G-SYNC/FreeSync (se aplica al reiniciar)", + "AI masks": "Máscaras de IA", + "Device": "Dispositivo", + "Last photo": "Última foto", + "Remote worker": "Proceso remoto", + "Run on": "Ejecutar en", + "Automatic (GPU when available)": "Automático (GPU si la hay)", + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer.": "Las máscaras Objeto y Describir analizan cada foto una sola vez, en la tarjeta gráfica salvo que se elija CPU o «Usar la GPU para renderizar» esté desactivado. En el procesador tarda mucho más.", + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "Automático ejecuta el modelo en la tarjeta gráfica del Mac. Elige CPU si las máscaras de IA fallan allí; en el procesador tardan mucho más.", "User Templates": "Plantillas del usuario", "Delete Folder": "Eliminar carpeta", "Folder name": "Nombre de la carpeta", @@ -2462,6 +2484,18 @@ "Welcome": "Bienvenido", "Next": "Siguiente", "Get Started": "Empezar", + "Keywords and presets apply to new files only, not to photos already in Local": "Las palabras clave y los ajustes preestablecidos solo se aplican a archivos nuevos, no a fotos que ya están en Local", + "This album is in a loop, so it shows nothing": "Este álbum está en un bucle, así que no muestra nada", + "It tests itself: change its rules (Edit Smart Album…)": "Se comprueba a sí mismo: cambia sus reglas (Editar álbum inteligente…)", + "Can't add to an album folder": "No se puede añadir a una carpeta de álbumes", + "An album folder holds albums, not photos: drop on an album inside it": "Una carpeta de álbumes contiene álbumes, no fotos: suéltalas en un álbum de dentro", + "Can't add to a smart album": "No se puede añadir a un álbum inteligente", + "A smart album's rules choose its photos: change them with Edit Smart Album…": "Las reglas de un álbum inteligente eligen sus fotos: cámbialas con Editar álbum inteligente…", + "Add keywords in the Keyword List": "Añade palabras clave en la Lista de palabras clave", + "Give photos a keyword in the Keyword List (Window → Keywords, K): drop them on it there": "Para dar una palabra clave a las fotos, usa la Lista de palabras clave (Ventana → Palabras clave, K): suéltalas allí sobre ella", + "Already on these photos": "Ya las tienen estas fotos", + "Can't go inside itself": "No puede ir dentro de sí misma", + "Same Content as Another Photo": "Mismo contenido que otra foto", "Reduce Motion": "Reducir movimiento", "Reduce motion": "Reducir movimiento", "Turns off zoom and spinner animations. Fades stay. Follows the system's Reduce Motion until you change it here.": "Desactiva las animaciones del zoom y de los indicadores de actividad. Los fundidos se mantienen. Sigue el ajuste Reducir movimiento del sistema hasta que lo cambies aquí.", @@ -2474,5 +2508,11 @@ "Stack — click to collapse (S)": "Pila — clic para contraer (S)", "Virtual copy": "Copia virtual", "Right-click ▸ Locate Missing File… to find it again.": "Clic derecho → Localizar archivo que falta… para encontrarlo de nuevo.", - "Right-click ▸ Reload from Disk to try again.": "Clic derecho → Recargar desde el disco para intentarlo de nuevo." + "Right-click ▸ Reload from Disk to try again.": "Clic derecho → Recargar desde el disco para intentarlo de nuevo.", + "Album name (empty outside an album view)": "Nombre del álbum (vacío fuera de una vista de álbum)", + "Export date (YYYYMMDD)": "Fecha de exportación (YYYYMMDD)", + "Export time (HHMM)": "Hora de exportación (HHMM)", + "Insert variable": "Insertar variable", + "Insert…": "Insertar…", + "none ({album}, {date}, {hour})": "ninguno ({album}, {date}, {hour})" } diff --git a/crates/ui-egui/locales/fi-formats.json b/crates/ui-egui/locales/fi-formats.json index f0798061a7..924fce580f 100644 --- a/crates/ui-egui/locales/fi-formats.json +++ b/crates/ui-egui/locales/fi-formats.json @@ -130,10 +130,10 @@ "Making the denoised picture… {}%": "Tehdään kohinanpoistettua kuvaa… {}%", "Matches: {}": "Täsmäävät: {}", "Merging… {stage} {:.0}%": "Yhdistetään… {stage} {:.0}%", - "Move {n} photo{} to “{}”": "Siirrä kuvia kohteeseen ”{1}”: {n}{0:.0}", - "Move {n} photo{} to “{}”?": "Siirretäänkö kuvat kohteeseen ”{1}” ({n}){0:.0}?", + "Move {n} file{} to “{}”": "Siirrä tiedostoja kohteeseen ”{1}”: {n}{0:.0}", + "Move {n} file{} to “{}”?": "Siirretäänkö tiedostot kohteeseen ”{1}” ({n}){0:.0}?", "Move {what} to Recently Deleted?": "Siirretäänkö {what} Äskettäin poistettuihin?", - "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "Siirretty kuvia kohteeseen ”{1}”: {n}{0:.0}. Muokkaa → Kumoa siirtää ne takaisin.", + "Moved {n} file{} to “{}”. Edit → Undo moves them back.": "Siirretty tiedostoja kohteeseen ”{1}”: {n}{0:.0}. Muokkaa → Kumoa siirtää ne takaisin.", "Moved {} photo(s)": "Siirretty kuvia: {}", "Moved; {} photo(s) relinked": "Siirretty; yhdistetty uudelleen kuvia: {}", "Named ({named_n})": "Nimetyt ({named_n})", @@ -319,11 +319,16 @@ "Panel move was not applied: {error}": "Paneelin siirtoa ei otettu käyttöön: {error}", "{name} is installed": "{name} on asennettu", "{name} is installed and in use: face recognition is on": "{name} on asennettu ja käytössä: kasvojentunnistus on päällä", + "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} s, kuvakooderi {encoder:.1} s", "Bring photos in with File › Import Photos… ({keys}).": "Tuo kuvia valitsemalla Tiedosto › Tuo kuvia… ({keys}).", "View › Detail View ({keys}).": "Näytä › Tarkastelunäkymä ({keys}).", "File › Export… · File › Print… ({keys}).": "Tiedosto › Vie… · Tiedosto › Tulosta… ({keys}).", "{n} folder{} could not be read": "Kansiot, joita ei voitu lukea: {n}{:.0}", "{n} file{} skipped (not a supported photo type)": "Ohitetut tiedostot (ei tuettu valokuvatyyppi): {n}{:.0}", + "It leads back to itself through “{}”: change the rules of one album on the loop (Edit Smart Album…)": "Se johtaa takaisin itseensä albumin ”{}” kautta: muuta jonkin silmukan albumin sääntöjä (Muokkaa älyalbumia…)", + "Add {n} photo{} to “{}”": "Lisää kuvia albumiin ”{1}”: {n}{0:.0}", + "Add “{keyword}” to {n} photo{}": "Lisää ”{keyword}” kuviin: {n}{:.0}", + "{n} already there": "jo albumissa: {n}", "Rule {n} of {m}: {what}. Move with the arrow keys": "Sääntö {n}/{m}: {what}. Siirrä nuolinäppäimillä", "Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "Ryhmä {n}/{m}: täsmää {mode}, sisällä: {count}. Siirrä nuolinäppäimillä", ", rating {} of 5": ", luokitus: {} / 5" diff --git a/crates/ui-egui/locales/fi.json b/crates/ui-egui/locales/fi.json index b6e61397ac..46082b14c3 100644 --- a/crates/ui-egui/locales/fi.json +++ b/crates/ui-egui/locales/fi.json @@ -189,6 +189,7 @@ "Basic": "Perus", "Before": "Ennen", "Before the last template": "Ennen viimeistä mallipohjaa", + "Before/After": "Ennen/jälkeen", "Before/After (Y)": "Ennen/jälkeen (Y)", "Before/After Settings": "Ennen/jälkeen-asetukset", "Before/After Split": "Ennen/jälkeen jaettuna", @@ -440,6 +441,7 @@ "Crop & Rotate": "Rajaa ja kierrä", "Crop & Rotate (C)": "Rajaa ja kierrä (C)", "Crop Aspect": "Rajauksen kuvasuhde", + "Crop Overlay": "Rajauksen peittokuva", "Crop, Rotate, Geometry": "Rajaus, kierto, geometria", "Cropped": "Rajattu", "Cross Process": "Ristiinkäsittely", @@ -2193,6 +2195,7 @@ "Wednesday": "keskiviikko", "What's New": "Mitä uutta", "When pins show on the photo (Shift+H cycles)": "Milloin nastat näkyvät kuvassa (Shift+H vaihtaa)", + "White": "Valkoinen", "White Balance": "Valkotasapaino", "White Balance Selector": "Valkotasapainon valitsin", "White Balance Selector (W)": "Valkotasapainon valitsin (W)", @@ -2390,6 +2393,9 @@ "Dropped Files": "Pudotetut tiedostot", "Finish Lightroom catalog import before adding photos": "Viimeistele Lightroom-luettelon tuonti ennen kuvien lisäämistä", "Import dropped files without review": "Tuo pudotetut tiedostot ilman tarkistusta", + "Loupe Overlay": "Luupin peittokuva", + "View Options…": "Näyttöasetukset…", + "View → Loupe Overlay → View Options chooses the lines Info 1 and Info 2 show.": "Näytä → Luupin peittokuva → Näyttöasetukset valitsee rivit, jotka Info 1 ja Info 2 näyttävät.", "Lens Profiles": "Objektiiviprofiilit", "Download lens profiles?": "Ladataanko objektiiviprofiilit?", "LightCraft can correct distortion and vignetting for many lenses using the open lens database (lensfun, about {size} MB).": "LightCraft voi korjata monien objektiivien vääristymän ja vinjetoinnin avoimen objektiivitietokannan avulla (lensfun, noin {size} Mt).", @@ -2413,11 +2419,35 @@ "Top bar": "Yläpalkki", "Tool strip": "Työkalupalkki", "Bottom bar": "Alapalkki", + "AI masks": "Tekoälymaskit", + "Device": "Laite", + "Last photo": "Viimeisin kuva", + "Remote worker": "Etätyöskentelijä", + "Run on": "Suorita", + "Automatic (GPU when available)": "Automaattinen (GPU, jos saatavilla)", + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer.": "Kohde- ja Kuvaile-maskit analysoivat jokaisen kuvan kerran, näytönohjaimella, ellei Suoritin ole valittuna tai ”Käytä GPU:ta renderöintiin” ole pois päältä. Suorittimella se kestää paljon kauemmin.", + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "Automaattinen suorittaa mallin Macin näytönohjaimella. Valitse Suoritin, jos tekoälymaskit epäonnistuvat siellä; suorittimella ne kestävät paljon kauemmin.", "User Templates": "Käyttäjän mallipohjat", "Delete Folder": "Poista kansio", "Folder name": "Kansion nimi", "Its templates move to User Templates.": "Sen mallipohjat siirretään kansioon Käyttäjän mallipohjat.", "Stopped at the scan limit: there may be more photos": "Skannauksen raja saavutettiin: valokuvia voi olla lisää", + "Keywords and presets apply to new files only, not to photos already in Local": "Avainsanat ja esiasetukset koskevat vain uusia tiedostoja, eivät kuvia, jotka ovat jo Paikallisessa", + "This album is in a loop, so it shows nothing": "Tämä albumi on silmukassa, joten se ei näytä mitään", + "It tests itself: change its rules (Edit Smart Album…)": "Se testaa itseään: muuta sen sääntöjä (Muokkaa älyalbumia…)", + "Filter settings": "Suodata asetuksia", + "No setting matches what is typed.": "Mikään asetus ei vastaa kirjoitettua.", + "Try one word, or part of one: the names of tabs and sections, labels and explanations are all looked through.": "Kokeile yhtä sanaa tai sen osaa: haku kattaa välilehtien ja osioiden nimet, otsikot ja selitykset.", + "A smart album's rules choose its photos: change them with Edit Smart Album…": "Älyalbumin säännöt valitsevat sen kuvat: muuta niitä komennolla Muokkaa älyalbumia…", + "Add keywords in the Keyword List": "Lisää avainsanoja avainsanaluettelossa", + "Already on these photos": "Jo näissä kuvissa", + "An album folder holds albums, not photos: drop on an album inside it": "Albumikansio sisältää albumeja, ei kuvia: pudota kuvat sen sisällä olevalle albumille", + "Can't add to a smart album": "Älyalbumiin ei voi lisätä", + "Can't add to an album folder": "Albumikansioon ei voi lisätä", + "Can't go inside itself": "Ei voi siirtää itsensä sisään", + "Demo photos have no file on disk, so they can't be moved": "Demokuvilla ei ole tiedostoa levyllä, joten niitä ei voi siirtää", + "Give photos a keyword in the Keyword List (Window → Keywords, K): drop them on it there": "Anna kuville avainsana avainsanaluettelossa (Ikkuna → Avainsanat, K): pudota ne siellä avainsanan päälle", + "Same Content as Another Photo": "Sama sisältö kuin toisella kuvalla", "Reduce Motion": "Vähennä liikettä", "Reduce motion": "Vähennä liikettä", "Turns off zoom and spinner animations. Fades stay.": "Poistaa zoomaus- ja pyörivät animaatiot käytöstä. Häivytykset säilyvät.", @@ -2432,5 +2462,11 @@ "Stack — click to expand (S)": "Pino — napsauta laajentaaksesi (S)", "Stars on hover": "Tähdet osoitettaessa", "Stars on hover: flags and colour labels always show; the stars and the edited mark appear while a photo is hovered or selected.": "Tähdet osoitettaessa: liput ja värimerkinnät näkyvät aina; tähdet ja muokattu-merkki näkyvät, kun kuvaa osoitetaan tai se on valittuna.", - "Virtual copy": "Virtuaalikopio" + "Virtual copy": "Virtuaalikopio", + "Album name (empty outside an album view)": "Albumin nimi (tyhjä albumnäkymän ulkopuolella)", + "Export date (YYYYMMDD)": "Vientipäivämäärä (YYYYMMDD)", + "Export time (HHMM)": "Vientiaika (HHMM)", + "Insert variable": "Lisää muuttuja", + "Insert…": "Lisää…", + "none ({album}, {date}, {hour})": "ei mitään ({album}, {date}, {hour})" } diff --git a/crates/ui-egui/locales/fr-formats.json b/crates/ui-egui/locales/fr-formats.json index 4833055b7d..4eb8a1384e 100644 --- a/crates/ui-egui/locales/fr-formats.json +++ b/crates/ui-egui/locales/fr-formats.json @@ -306,10 +306,10 @@ "{what} merge added at {mp}: its full size, {full}, needs more memory than this computer has": "Fusion de {what} ajoutée en {mp} : la taille complète, {full}, demande plus de mémoire que n’en a cet ordinateur", "{what} merge added at {mp}, the largest a panorama can be (its full size is {full})": "Fusion de {what} ajoutée en {mp}, la plus grande taille possible pour un panorama (taille complète : {full})", "Already in “{}”": "Déjà dans « {} »", - "Move {n} photo{} to “{}”": "Déplacer {n} photo{} vers « {} »", - "Move {n} photo{} to “{}”?": "Déplacer {n} photo{} vers « {} » ?", + "Move {n} file{} to “{}”": "Déplacer {n} fichier{} vers « {} »", + "Move {n} file{} to “{}”?": "Déplacer {n} fichier{} vers « {} » ?", "Listing folders — folders: {folders}, files: {files}": "Liste des dossiers — dossiers : {folders}, fichiers : {files}", - "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "{n} photo{0} déplacée{0} vers « {1} ». Modifier → Annuler les remet en place.", + "Moved {n} file{} to “{}”. Edit → Undo moves them back.": "{n} fichier{0} déplacé{0} vers « {1} ». Modifier → Annuler les remet en place.", "Drop to review {n} item{} for import": "Déposez pour vérifier {n} élément{} avant l'import", "Drop to import {n} item{}": "Déposez pour importer {n} élément{}", "Drop to import {n} preset{}": "Déposez pour importer {n} préréglage{}", @@ -325,9 +325,14 @@ "Panel move was not applied: {error}": "Le déplacement du panneau n'a pas été appliqué : {error}", "{name} is installed": "{name} est installé", "{name} is installed and in use: face recognition is on": "{name} est installé et utilisé : la reconnaissance des visages est activée", + "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} s, encodeur d’image {encoder:.1} s", "Bring photos in with File › Import Photos… ({keys}).": "Importez des photos avec Fichier › Importer des photos… ({keys}).", "View › Detail View ({keys}).": "Affichage › Vue de détail ({keys}).", "File › Export… · File › Print… ({keys}).": "Fichier › Exporter… · Fichier › Imprimer… ({keys}).", + "It leads back to itself through “{}”: change the rules of one album on the loop (Edit Smart Album…)": "Il revient sur lui-même via l'album « {} » : modifiez les règles d'un album de la boucle (Modifier l'album intelligent…)", + "Add {n} photo{} to “{}”": "Ajouter {n} photo{} à « {} »", + "{n} already there": "{n} déjà présent(s)", + "Add “{keyword}” to {n} photo{}": "Ajouter « {keyword} » à {n} photo{}", "Rule {n} of {m}: {what}. Move with the arrow keys": "Règle {n} sur {m} : {what}. Déplacer avec les flèches", "Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "Groupe {n} sur {m} : correspondre à {mode}, {count} à l’intérieur. Déplacer avec les flèches", ", rating {} of 5": ", note : {} sur 5" diff --git a/crates/ui-egui/locales/fr.json b/crates/ui-egui/locales/fr.json index 77a33e3164..c2e0413574 100644 --- a/crates/ui-egui/locales/fr.json +++ b/crates/ui-egui/locales/fr.json @@ -45,6 +45,7 @@ "Import photos with File → Import Photos…, or drop them here": "Importez des photos avec Fichier → Importer des photos… ou déposez-les ici", "This row covers more than one disk: drop on a folder inside it": "Cette ligne couvre plusieurs disques : déposez-les sur un dossier qu’elle contient", "Local photos aren't in the library yet: Add to My Photos first, then move them": "Les photos locales ne sont pas encore dans la bibliothèque : Ajouter à Mes photos d’abord, puis déplacez-les", + "Demo photos have no file on disk, so they can't be moved": "Les photos de démonstration n’ont pas de fichier sur le disque : on ne peut pas les déplacer", "Add to Selected Photos": "Ajouter aux photos sélectionnées", "Add to Target Album": "Ajouter à l'album cible", "Add to this mask": "Ajouter à ce masque", @@ -139,6 +140,7 @@ "Before/After (Y)": "Avant/Après (Y)", "Before/After Settings": "Réglages Avant/Après", "Before/After Split": "Avant/Après divisé", + "Before/After": "Avant/Après", "Before/After Split Top/Bottom": "Avant/Après divisé haut/bas", "Before/After Top/Bottom": "Avant/Après haut/bas", "Begin Interaction": "Commencer l'interaction", @@ -344,6 +346,7 @@ "Cut": "Couper", "Cut pages": "Couper les pages", "Cycle Crop Overlay": "Parcourir les incrustations de recadrage", + "Crop Overlay": "Incrustation de recadrage", "Cycle Crop Overlay Orientation": "Parcourir les orientations de l'incrustation de recadrage", "Cycle Info Overlay": "Parcourir les incrustations d'informations", "Cycle Mask Overlay Color": "Parcourir les couleurs de l'incrustation du masque", @@ -1598,6 +1601,7 @@ "XMP sidecars": "Fichiers annexes XMP", "Year": "Année", "Yellow": "Jaune", + "White": "Blanc", "Yellow Hue": "Teinte jaune", "Yellow Luminance": "Luminance jaune", "Yellow Saturation": "Saturation jaune", @@ -1997,6 +2001,9 @@ "Appearance Settings…": "Réglages d’apparence…", "Add to favorites": "Ajouter aux favoris", "Remove from favorites": "Retirer des favoris", + "Filter settings": "Filtrer les réglages", + "No setting matches what is typed.": "Aucun réglage ne correspond à la saisie.", + "Try one word, or part of one: the names of tabs and sections, labels and explanations are all looked through.": "Essayez un mot ou une partie de mot : la recherche porte sur les noms des onglets et des sections, les libellés et les explications.", "Appearance": "Apparence", "Appearance Mode": "Mode d’apparence", "Sync with System": "Synchroniser avec le système", @@ -2433,6 +2440,10 @@ "The photos are imported once a library is open": "Les photos seront importées dès qu'une bibliothèque sera ouverte", "Open a library first, then drop the presets again": "Ouvrez d'abord une bibliothèque, puis déposez à nouveau les préréglages", "This library couldn't be checked:": "Impossible de vérifier cette bibliothèque :", + "Mixer": "Mélangeur", + "HSL": "TSL", + "Adjust": "Régler", + "Color Mixer Layout": "Disposition du mélangeur de couleurs", "Camera preview": "Aperçu de l'appareil", "The camera's own JPEG, shown until LightCraft has rendered the raw. Judge colour and tone on the rendered photo.": "Le JPEG de l'appareil photo, affiché jusqu'à ce que LightCraft ait rendu le fichier RAW. Jugez la couleur et les tons sur la photo rendue.", "Profile: from the file (the camera's own correction)": "Profil : du fichier (correction de l'appareil)", @@ -2705,6 +2716,7 @@ "Use sRGB": "Utiliser sRGB", "View Options": "Options d'affichage", "View Options…": "Options d'affichage…", + "View → Loupe Overlay → View Options chooses the lines Info 1 and Info 2 show.": "Affichage → Incrustation de la loupe → Options d'affichage choisit les lignes que montrent Info 1 et Info 2.", "View → View Options chooses the lines Info 1 and Info 2 show.": "Affichage → Options d'affichage choisit les lignes que montrent Infos 1 et Infos 2.", "Visualize HDR": "Visualiser le HDR", "When pins show on the photo (Shift+H cycles)": "Quand les épingles s'affichent sur la photo (Maj+H pour parcourir)", @@ -3619,6 +3631,14 @@ "Tool strip": "Barre d’outils", "Bottom bar": "Barre inférieure", "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Empêcher le scintillement G-SYNC/FreeSync (au prochain démarrage)", + "AI masks": "Masques IA", + "Device": "Appareil", + "Last photo": "Dernière photo", + "Remote worker": "Processus distant", + "Run on": "Exécuter sur", + "Automatic (GPU when available)": "Automatique (GPU si disponible)", + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer.": "Les masques Objet et Décrire analysent chaque photo une fois, sur la carte graphique sauf si Processeur est choisi ou si « Utiliser le GPU pour le rendu » est désactivé. Sur le processeur, c’est beaucoup plus long.", + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "Automatique exécute le modèle sur la carte graphique du Mac. Choisissez Processeur si les masques IA y échouent ; sur le processeur, ils sont beaucoup plus longs.", "User Templates": "Modèles utilisateur", "Delete Folder": "Supprimer le dossier", "Folder name": "Nom du dossier", @@ -3645,6 +3665,18 @@ "Welcome": "Bienvenue", "Next": "Suivant", "Get Started": "Commencer", + "Keywords and presets apply to new files only, not to photos already in Local": "Les mots-clés et les préréglages ne s'appliquent qu'aux nouveaux fichiers, pas aux photos déjà dans Local", + "This album is in a loop, so it shows nothing": "Cet album est pris dans une boucle : il n'affiche rien", + "It tests itself: change its rules (Edit Smart Album…)": "Il se teste lui-même : modifiez ses règles (Modifier l'album intelligent…)", + "Can't add to an album folder": "Impossible d’ajouter à un dossier d’albums", + "An album folder holds albums, not photos: drop on an album inside it": "Un dossier d’albums contient des albums, pas des photos : déposez-les sur un album à l’intérieur", + "Can't add to a smart album": "Impossible d’ajouter à un album intelligent", + "A smart album's rules choose its photos: change them with Edit Smart Album…": "Les règles d’un album intelligent choisissent ses photos : modifiez-les avec Modifier l'album intelligent…", + "Add keywords in the Keyword List": "Ajoutez des mots-clés dans la Liste des mots-clés", + "Give photos a keyword in the Keyword List (Window → Keywords, K): drop them on it there": "Pour donner un mot-clé à des photos, utilisez la Liste des mots-clés (Fenêtre → Mots-clés, K) : déposez-les sur le mot-clé", + "Already on these photos": "Déjà sur ces photos", + "Can't go inside itself": "Ne peut pas aller dans lui-même", + "Same Content as Another Photo": "Même contenu qu'une autre photo", "Reduce Motion": "Réduire les animations", "Reduce motion": "Réduire les animations", "Turns off zoom and spinner animations. Fades stay. Follows the system's Reduce Motion until you change it here.": "Désactive les animations du zoom et des indicateurs d’activité. Les fondus restent. Suit le réglage Réduire les animations du système tant que vous ne le changez pas ici.", @@ -3657,5 +3689,11 @@ "Stack — click to collapse (S)": "Pile — cliquer pour replier (S)", "Virtual copy": "Copie virtuelle", "Right-click ▸ Locate Missing File… to find it again.": "Clic droit → Localiser le fichier manquant… pour le retrouver.", - "Right-click ▸ Reload from Disk to try again.": "Clic droit → Recharger depuis le disque pour réessayer." + "Right-click ▸ Reload from Disk to try again.": "Clic droit → Recharger depuis le disque pour réessayer.", + "Album name (empty outside an album view)": "Nom de l'album (vide hors vue d'album)", + "Export date (YYYYMMDD)": "Date d'export (YYYYMMDD)", + "Export time (HHMM)": "Heure d'export (HHMM)", + "Insert variable": "Insérer une variable", + "Insert…": "Insérer…", + "none ({album}, {date}, {hour})": "aucun ({album}, {date}, {hour})" } diff --git a/crates/ui-egui/locales/id-formats.json b/crates/ui-egui/locales/id-formats.json index 129971f036..c492fcbb01 100644 --- a/crates/ui-egui/locales/id-formats.json +++ b/crates/ui-egui/locales/id-formats.json @@ -44,10 +44,10 @@ "LightCraft could not open its window: {e}\n\nThe log file has the details: {path}": "LightCraft tidak dapat membuka jendela: {e}\n\nDetailnya ada di file log: {path}", "Matches: {}": "Cocok: {}", "Merging… {stage} {:.0}%": "Menggabungkan… {stage} {:.0}%", - "Move {n} photo{} to “{}”": "Pindahkan {n} foto{0:.0} ke “{1}”", - "Move {n} photo{} to “{}”?": "Pindahkan {n} foto{0:.0} ke “{1}”?", + "Move {n} file{} to “{}”": "Pindahkan {n} file{0:.0} ke “{1}”", + "Move {n} file{} to “{}”?": "Pindahkan {n} file{0:.0} ke “{1}”?", "Move {what} to Recently Deleted?": "Pindahkan {what} ke Baru dihapus?", - "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "{n} foto dipindahkan ke “{1}”{0:.0}. Pilih Edit → Urungkan untuk mengembalikannya.", + "Moved {n} file{} to “{}”. Edit → Undo moves them back.": "{n} file dipindahkan ke “{1}”{0:.0}. Pilih Edit → Urungkan untuk mengembalikannya.", "Named ({named_n})": "Bernama ({named_n})", "Paste into {n} photo{} — only settings that were copied are pasted": "Tempel ke {n} foto{:.0} — hanya menempelkan pengaturan yang disalin", "Preset: {name}": "Preset: {name}", @@ -322,11 +322,16 @@ "Creates {stacks} stack{} from {photos} of {scope}": "Membuat {stacks} tumpukan dari {photos} foto ({scope}){:.0}", "{n} selected photo{} · {pages} page{}": "{n} foto dipilih · {pages} halaman{:.0}{:.0}", "{n} photo{} in view · {slides} slide{} · {time}": "{n} foto di tampilan · {slides} slide · {time}{:.0}{:.0}", + "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} dtk, penyandi gambar {encoder:.1} dtk", "Bring photos in with File › Import Photos… ({keys}).": "Masukkan foto melalui File › Impor foto… ({keys}).", "View › Detail View ({keys}).": "Tampilan › Tampilan Detail ({keys}).", "File › Export… · File › Print… ({keys}).": "File › Ekspor… · File › Cetak… ({keys}).", "{n} folder{} could not be read": "Folder yang tidak bisa dibaca: {n}{:.0}", "{n} file{} skipped (not a supported photo type)": "File yang dilewati (bukan jenis foto yang didukung): {n}{:.0}", + "It leads back to itself through “{}”: change the rules of one album on the loop (Edit Smart Album…)": "Album ini kembali ke dirinya sendiri melalui album “{}”: ubah aturan salah satu album dalam perulangan (Edit album pintar…)", + "Add {n} photo{} to “{}”": "Tambahkan {n} foto{0:.0} ke “{1}”", + "Add “{keyword}” to {n} photo{}": "Tambahkan “{keyword}” ke {n} foto{:.0}", + "{n} already there": "{n} sudah ada", "Rule {n} of {m}: {what}. Move with the arrow keys": "Aturan {n} dari {m}: {what}. Pindahkan dengan tombol panah", "Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "Grup {n} dari {m}: cocokkan {mode}, isi: {count}. Pindahkan dengan tombol panah", ", rating {} of 5": ", rating: {} dari 5" diff --git a/crates/ui-egui/locales/id.json b/crates/ui-egui/locales/id.json index c4816c93a7..80ff3ed757 100644 --- a/crates/ui-egui/locales/id.json +++ b/crates/ui-egui/locales/id.json @@ -193,6 +193,7 @@ "Basic": "Dasar", "Before": "Sebelum", "Before the last template": "Sebelum templat terakhir diterapkan", + "Before/After": "Sebelum/Sesudah", "Before/After (Y)": "Sebelum/Sesudah (Y)", "Before/After Settings": "Pengaturan Sebelum/Sesudah", "Before/After Split": "Sebelum/Sesudah: terbagi", @@ -439,6 +440,7 @@ "Crop & Rotate": "Pangkas & putar", "Crop & Rotate (C)": "Pangkas & putar (C)", "Crop Aspect": "Aspek pangkas", + "Crop Overlay": "Overlay pangkas", "Crop, Rotate, Geometry": "Pangkas, putar, geometri", "Cropped": "Dipangkas", "Cross Process": "Cross Process", @@ -2186,6 +2188,7 @@ "We": "Rb", "Wednesday": "Rabu", "What's New": "Yang baru", + "White": "Putih", "White Balance": "Keseimbangan putih", "White Balance Selector": "Pemilih keseimbangan putih", "White Balance Selector (W)": "Pemilih keseimbangan putih (W)", @@ -2403,6 +2406,9 @@ "Dropped Files": "File yang dijatuhkan", "Finish Lightroom catalog import before adding photos": "Selesaikan impor katalog Lightroom sebelum menambahkan foto", "Import dropped files without review": "Impor file yang dijatuhkan tanpa tinjauan", + "Loupe Overlay": "Overlay loupe", + "View Options…": "Opsi Tampilan…", + "View → Loupe Overlay → View Options chooses the lines Info 1 and Info 2 show.": "Tampilan → Overlay loupe → Opsi Tampilan memilih baris yang ditampilkan Info 1 dan Info 2.", "Lens Profiles": "Profil lensa", "Download lens profiles?": "Unduh profil lensa?", "LightCraft can correct distortion and vignetting for many lenses using the open lens database (lensfun, about {size} MB).": "LightCraft dapat mengoreksi distorsi dan vinyet untuk banyak lensa menggunakan basis data lensa terbuka (lensfun, sekitar {size} MB).", @@ -2427,11 +2433,35 @@ "Top bar": "Bilah atas", "Tool strip": "Bilah alat", "Bottom bar": "Bilah bawah", + "AI masks": "Masker AI", + "Device": "Perangkat", + "Last photo": "Foto terakhir", + "Remote worker": "Worker jarak jauh", + "Run on": "Jalankan di", + "Automatic (GPU when available)": "Otomatis (GPU jika tersedia)", + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer.": "Masker Objek dan Deskripsikan menganalisis setiap foto sekali, di kartu grafis kecuali CPU dipilih atau “Gunakan GPU untuk rendering” dimatikan. Di prosesor hal itu jauh lebih lama.", + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "Otomatis menjalankan model di kartu grafis Mac. Pilih CPU jika masker AI gagal di sana; di prosesor prosesnya jauh lebih lama.", "User Templates": "Templat pengguna", "Delete Folder": "Hapus folder", "Folder name": "Nama folder", "Its templates move to User Templates.": "Templatnya dipindahkan ke Templat pengguna.", "Stopped at the scan limit: there may be more photos": "Berhenti pada batas pemindaian: mungkin masih ada foto", + "Keywords and presets apply to new files only, not to photos already in Local": "Kata kunci dan prasetel hanya berlaku untuk berkas baru, bukan foto yang sudah ada di Lokal", + "This album is in a loop, so it shows nothing": "Album ini berada dalam perulangan, jadi tidak menampilkan apa pun", + "It tests itself: change its rules (Edit Smart Album…)": "Album ini menjadikan dirinya sendiri syarat: ubah aturannya (Edit album pintar…)", + "Filter settings": "Filter pengaturan", + "No setting matches what is typed.": "Tidak ada pengaturan yang cocok dengan yang diketik.", + "Try one word, or part of one: the names of tabs and sections, labels and explanations are all looked through.": "Coba satu kata atau sebagiannya: yang dicari adalah nama tab dan bagian, label, serta penjelasan.", + "A smart album's rules choose its photos: change them with Edit Smart Album…": "Aturan album pintar menentukan fotonya: ubah dengan Edit album pintar…", + "Add keywords in the Keyword List": "Tambahkan kata kunci di Daftar kata kunci", + "Already on these photos": "Sudah ada pada foto ini", + "An album folder holds albums, not photos: drop on an album inside it": "Folder album berisi album, bukan foto: jatuhkan ke album di dalamnya", + "Can't add to a smart album": "Tidak dapat menambahkan ke album pintar", + "Can't add to an album folder": "Tidak dapat menambahkan ke folder album", + "Can't go inside itself": "Tidak dapat dimasukkan ke dalam dirinya sendiri", + "Demo photos have no file on disk, so they can't be moved": "Foto demo tidak memiliki file di disk, sehingga tidak dapat dipindahkan", + "Give photos a keyword in the Keyword List (Window → Keywords, K): drop them on it there": "Beri foto kata kunci di Daftar kata kunci (Jendela → Kata kunci, K): jatuhkan ke kata kunci di sana", + "Same Content as Another Photo": "Konten sama dengan foto lain", "Reduce Motion": "Kurangi gerakan", "Reduce motion": "Kurangi gerakan", "Turns off zoom and spinner animations. Fades stay.": "Menonaktifkan animasi zoom dan indikator putar. Efek memudar tetap ada.", @@ -2446,5 +2476,11 @@ "Stack — click to expand (S)": "Tumpukan — klik untuk meluaskan (S)", "Stars on hover": "Bintang saat kursor di atas", "Stars on hover: flags and colour labels always show; the stars and the edited mark appear while a photo is hovered or selected.": "Bintang saat kursor di atas: bendera dan label warna selalu tampil; bintang dan tanda telah diedit muncul saat kursor berada di atas foto atau foto dipilih.", - "Virtual copy": "Salinan virtual" + "Virtual copy": "Salinan virtual", + "Album name (empty outside an album view)": "Nama album (kosong di luar tampilan album)", + "Export date (YYYYMMDD)": "Tanggal ekspor (YYYYMMDD)", + "Export time (HHMM)": "Waktu ekspor (HHMM)", + "Insert variable": "Sisipkan variabel", + "Insert…": "Sisipkan…", + "none ({album}, {date}, {hour})": "tidak ada ({album}, {date}, {hour})" } diff --git a/crates/ui-egui/locales/it-formats.json b/crates/ui-egui/locales/it-formats.json index ca1418892c..96a493f446 100644 --- a/crates/ui-egui/locales/it-formats.json +++ b/crates/ui-egui/locales/it-formats.json @@ -303,9 +303,9 @@ "Color space: Rec. 2020 {curve} (HDR AVIF)": "Spazio colore: Rec. 2020 {curve} (AVIF HDR)", "{n} selected photo{} · {pages} page{}": "Foto selezionate: {n} · pagine: {pages}{:.0}{:.0}", "Already in “{}”": "Già in “{}”", - "Move {n} photo{} to “{}”": "Sposta foto in “{1}” ({n}){0:.0}", - "Move {n} photo{} to “{}”?": "Spostare le foto in “{1}” ({n})?{0:.0}", - "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "Foto spostate in “{1}”: {n}{0:.0}. Modifica → Annulla le riporta indietro.", + "Move {n} file{} to “{}”": "Sposta file in “{1}” ({n}){0:.0}", + "Move {n} file{} to “{}”?": "Spostare i file in “{1}” ({n})?{0:.0}", + "Moved {n} file{} to “{}”. Edit → Undo moves them back.": "File spostati in “{1}”: {n}{0:.0}. Modifica → Annulla li riporta indietro.", "Listing folders — folders: {folders}, files: {files}": "Elenco delle cartelle — cartelle: {folders}, file: {files}", "Drop to review {n} item{} for import": "Rilascia per rivedere prima dell'importazione (elementi: {n}){:.0}", "Drop to import {n} item{}": "Rilascia per importare (elementi: {n}){:.0}", @@ -322,11 +322,16 @@ "Panel move was not applied: {error}": "Lo spostamento del pannello non è stato applicato: {error}", "{name} is installed": "{name} è installato", "{name} is installed and in use: face recognition is on": "{name} è installato e in uso: il riconoscimento dei volti è attivo", + "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} s, codificatore d’immagine {encoder:.1} s", "Bring photos in with File › Import Photos… ({keys}).": "Importa le foto con File › Importa foto… ({keys}).", "View › Detail View ({keys}).": "Visualizza › Vista dettaglio ({keys}).", "File › Export… · File › Print… ({keys}).": "File › Esporta… · File › Stampa… ({keys}).", "{n} folder{} could not be read": "Cartelle non leggibili: {n}{:.0}", "{n} file{} skipped (not a supported photo type)": "File saltati (non è un tipo di foto supportato): {n}{:.0}", + "It leads back to itself through “{}”: change the rules of one album on the loop (Edit Smart Album…)": "Ritorna su se stesso attraverso l'album “{}”: modifica le regole di un album del ciclo (Modifica album smart…)", + "Add {n} photo{} to “{}”": "Aggiungi {n} foto{0:.0} a “{1}”", + "{n} already there": "{n} già presenti", + "Add “{keyword}” to {n} photo{}": "Aggiungi “{keyword}” a {n} foto{:.0}", "Rule {n} of {m}: {what}. Move with the arrow keys": "Regola {n} di {m}: {what}. Sposta con le frecce", "Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "Gruppo {n} di {m}: corrispondenza {mode}, {count} all’interno. Sposta con le frecce", ", rating {} of 5": ", valutazione: {} su 5" diff --git a/crates/ui-egui/locales/it.json b/crates/ui-egui/locales/it.json index 2388641baf..292b13ec0e 100644 --- a/crates/ui-egui/locales/it.json +++ b/crates/ui-egui/locales/it.json @@ -45,6 +45,7 @@ "Import photos with File → Import Photos…, or drop them here": "Importa le foto con File → Importa foto…, oppure trascinale qui", "This row covers more than one disk: drop on a folder inside it": "Questa riga comprende più di un disco: rilascia su una cartella al suo interno", "Local photos aren't in the library yet: Add to My Photos first, then move them": "Le foto locali non sono ancora nella libreria: prima Aggiungi a Le mie foto, poi spostale", + "Demo photos have no file on disk, so they can't be moved": "Le foto dimostrative non hanno un file su disco, quindi non si possono spostare", "Add to Selected Photos": "Aggiungi alle foto selezionate", "Add to Target Album": "Aggiungi all'album di destinazione", "Add to this mask": "Aggiungi a questa maschera", @@ -140,6 +141,7 @@ "Before/After (Y)": "Prima/Dopo (Y)", "Before/After Settings": "Impostazioni Prima/Dopo", "Before/After Split": "Prima/Dopo diviso", + "Before/After": "Prima/Dopo", "Before/After Split Top/Bottom": "Prima/Dopo diviso sopra/sotto", "Before/After Top/Bottom": "Prima/Dopo sopra/sotto", "Begin Interaction": "Inizia interazione", @@ -345,6 +347,7 @@ "Cut": "Taglia", "Cut pages": "Taglia pagine", "Cycle Crop Overlay": "Cambia sovrapposizione del ritaglio", + "Crop Overlay": "Sovrapposizione del ritaglio", "Cycle Crop Overlay Orientation": "Cambia orientamento della sovrapposizione del ritaglio", "Cycle Info Overlay": "Cambia sovrapposizione delle informazioni", "Cycle Mask Overlay Color": "Cambia colore della sovrapposizione maschera", @@ -1629,6 +1632,7 @@ "XMP sidecars": "File XMP collaterali", "Year": "Anno", "Yellow": "Giallo", + "White": "Bianco", "Yellow Hue": "Tonalità giallo", "Yellow Luminance": "Luminanza giallo", "Yellow Saturation": "Saturazione giallo", @@ -1832,12 +1836,14 @@ "Edit in Other Editor (⌥⌘E) opens the copy in this application (an app name on macOS, a program path elsewhere).": "Modifica nell'altro editor (⌥⌘E) apre la copia in questa applicazione (il nome di un'app su macOS, il percorso di un programma altrove).", "Edit in PhotoCraft": "Modifica in PhotoCraft", "External Editing": "Modifica esterna", + "Filter settings": "Filtra impostazioni", "Found automatically": "Trovato automaticamente", "HDR": "HDR", "LUT-based": "Basato su LUT", "Left: the standard (SDR) range up to SDR white. Right: the HDR range, one band per stop above SDR white (the orange line: the HDR headroom). With Visualize HDR range on, the bands take its colours.": "A sinistra: la gamma standard (SDR) fino al bianco SDR. A destra: la gamma HDR, una fascia per ogni stop sopra il bianco SDR (la linea arancione: il margine HDR). Con Visualizza gamma HDR attivo, le fasce ne prendono i colori.", "Matrix/TRC": "Matrice/TRC", "Monitor profile": "Profilo monitor", + "No setting matches what is typed.": "Nessuna impostazione corrisponde al testo digitato.", "None (the display is treated as sRGB)": "Nessuno (lo schermo viene trattato come sRGB)", "Other editor": "Altro editor", "Photo → Edit In → Edit in PhotoCraft (⇧⌘E, or right-click a photo) renders a copy with your edits, stacks it with the original and opens it in PhotoCraft. Save there and the copy updates here. As PSD, PhotoCraft saves straight back to it. Leave the location empty unless you use a portable copy.": "Foto → Modifica in → Modifica in PhotoCraft (⇧⌘E, o clic destro su una foto) esegue il rendering di una copia con le tue modifiche, la impila con l'originale e la apre in PhotoCraft. Salva lì e la copia si aggiorna qui. Come PSD, PhotoCraft salva direttamente su di essa. Lascia vuota la posizione a meno che tu non usi una copia portatile.", @@ -1846,6 +1852,7 @@ "Photos stay in All Photos. Deleting a folder also deletes its albums. You can undo this.": "Le foto restano in Tutte le foto. Eliminando una cartella si eliminano anche i suoi album. Puoi annullare l'operazione.", "Primaries (x, y)": "Primari (x, y)", "Profiles assigned in your desktop's colour settings are usually in ~/.local/share/icc.": "I profili assegnati nelle impostazioni colore del desktop di solito sono in ~/.local/share/icc.", + "Try one word, or part of one: the names of tabs and sections, labels and explanations are all looked through.": "Prova una parola, o parte di una: vengono cercati i nomi di schede e sezioni, le etichette e le spiegazioni.", "Progressive": "Progressivo", "SDR": "SDR", "Use Screen Profile": "Usa profilo dello schermo", @@ -2396,7 +2403,6 @@ "Use Defaults": "Usa predefiniti", "Show briefly when photo changes": "Mostra brevemente al cambio di foto", "Camera & Lens": "Fotocamera e obiettivo", - "View → View Options chooses the lines Info 1 and Info 2 show.": "Visualizza → Opzioni di visualizzazione sceglie le righe di Info 1 e Info 2.", "Blur Amount": "Quantità di sfocatura", "Boost": "Enfasi", "In Focus": "A fuoco", @@ -2445,6 +2451,10 @@ "The photos are imported once it ends": "Le foto verranno importate dopo", "An import is running. Drop photos when it has finished": "Un'importazione è in corso. Trascina le foto quando è finita", "Finish Lightroom catalog import before adding photos": "Termina l'importazione del catalogo Lightroom prima di aggiungere foto", + "Mixer": "Miscelatore", + "HSL": "HSL", + "Adjust": "Regola", + "Color Mixer Layout": "Disposizione del miscelatore colore", "Profile: from the file (the camera's own correction)": "Profilo: dal file (correzione della fotocamera)", "Downloading the lens database…": "Download del database degli obiettivi…", "This file names no lens.": "Questo file non indica alcun obiettivo.", @@ -2542,6 +2552,7 @@ "Click to show clipping warnings for shadows and highlights.": "Fai clic per mostrare gli avvisi di taglio per ombre e luci.", "Hide this wheel's effect": "Nascondi l'effetto di questa ruota", "Loupe Overlay": "Sovrapposizione lente", + "View → Loupe Overlay → View Options chooses the lines Info 1 and Info 2 show.": "Visualizza → Sovrapposizione lente → Opzioni di visualizzazione sceglie le righe di Info 1 e Info 2.", "Grid: add the next photo to the selection": "Griglia: aggiungi la foto successiva alla selezione", "Grid: add the previous photo to the selection": "Griglia: aggiungi la foto precedente alla selezione", "Grid: first photo of the view": "Griglia: prima foto della vista", @@ -2599,6 +2610,14 @@ "Top bar": "Barra superiore", "Tool strip": "Barra degli strumenti", "Bottom bar": "Barra inferiore", + "AI masks": "Maschere IA", + "Device": "Dispositivo", + "Last photo": "Ultima foto", + "Remote worker": "Processo remoto", + "Run on": "Esegui su", + "Automatic (GPU when available)": "Automatico (GPU se disponibile)", + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer.": "Le maschere Oggetto e Descrivi analizzano ogni foto una volta, sulla scheda grafica a meno che sia scelta la CPU o «Usa la GPU per il rendering» sia disattivato. Sul processore richiede molto più tempo.", + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "Automatico esegue il modello sulla scheda grafica del Mac. Scegli CPU se lì le maschere IA non funzionano; sul processore richiedono molto più tempo.", "User Templates": "Modelli utente", "Delete Folder": "Elimina cartella", "Folder name": "Nome della cartella", @@ -2626,6 +2645,18 @@ "Next": "Avanti", "Get Started": "Inizia", "Stopped at the scan limit: there may be more photos": "Fermati al limite di scansione: potrebbero esserci altre foto", + "Keywords and presets apply to new files only, not to photos already in Local": "Parole chiave e preset si applicano solo ai file nuovi, non alle foto già in Locale", + "This album is in a loop, so it shows nothing": "Questo album è in un ciclo, quindi non mostra nulla", + "It tests itself: change its rules (Edit Smart Album…)": "Verifica se stesso: modifica le sue regole (Modifica album smart…)", + "Can't add to an album folder": "Impossibile aggiungere a una cartella di album", + "An album folder holds albums, not photos: drop on an album inside it": "Una cartella di album contiene album, non foto: rilascia su un album al suo interno", + "Can't add to a smart album": "Impossibile aggiungere a un album smart", + "A smart album's rules choose its photos: change them with Edit Smart Album…": "Le regole di un album smart scelgono le sue foto: cambiale con Modifica album smart…", + "Add keywords in the Keyword List": "Aggiungi le parole chiave nell'Elenco parole chiave", + "Give photos a keyword in the Keyword List (Window → Keywords, K): drop them on it there": "Per dare una parola chiave alle foto usa l'Elenco parole chiave (Finestra → Parole chiave, K): rilasciale lì sulla parola chiave", + "Already on these photos": "Già presente su queste foto", + "Can't go inside itself": "Non può andare dentro se stessa", + "Same Content as Another Photo": "Stesso contenuto di un'altra foto", "Reduce Motion": "Riduci movimento", "Reduce motion": "Riduci movimento", "Turns off zoom and spinner animations. Fades stay. Follows the system's Reduce Motion until you change it here.": "Disattiva le animazioni dello zoom e degli indicatori di attività. Le dissolvenze restano. Segue l’impostazione Riduci movimento del sistema finché non la cambi qui.", @@ -2638,5 +2669,11 @@ "Stack — click to collapse (S)": "Pila — clic per comprimere (S)", "Virtual copy": "Copia virtuale", "Right-click ▸ Locate Missing File… to find it again.": "Clic destro → Trova file mancante… per ritrovarlo.", - "Right-click ▸ Reload from Disk to try again.": "Clic destro → Ricarica dal disco per riprovare." + "Right-click ▸ Reload from Disk to try again.": "Clic destro → Ricarica dal disco per riprovare.", + "Album name (empty outside an album view)": "Nome dell'album (vuoto fuori dalla vista album)", + "Export date (YYYYMMDD)": "Data di esportazione (YYYYMMDD)", + "Export time (HHMM)": "Ora di esportazione (HHMM)", + "Insert variable": "Inserisci variabile", + "Insert…": "Inserisci…", + "none ({album}, {date}, {hour})": "nessuno ({album}, {date}, {hour})" } diff --git a/crates/ui-egui/locales/ja-formats.json b/crates/ui-egui/locales/ja-formats.json index 8cf5d56c85..9138a78640 100644 --- a/crates/ui-egui/locales/ja-formats.json +++ b/crates/ui-egui/locales/ja-formats.json @@ -44,10 +44,10 @@ "LightCraft could not open its window: {e}\n\nThe log file has the details: {path}": "LightCraftのウィンドウを開けませんでした: {e}\n\n詳しくはログファイルをご覧ください: {path}", "Matches: {}": "一致条件:{}", "Merging… {stage} {:.0}%": "合成中… {stage} {:.0}%", - "Move {n} photo{} to “{}”": "{n}枚を「{1}」に移動{0:.0}", - "Move {n} photo{} to “{}”?": "{n}枚を「{1}」に移動しますか?{0:.0}", + "Move {n} file{} to “{}”": "{n}件のファイルを「{1}」に移動{0:.0}", + "Move {n} file{} to “{}”?": "{n}件のファイルを「{1}」に移動しますか?{0:.0}", "Move {what} to Recently Deleted?": "{what}を「最近削除した写真」に移動しますか?", - "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "{n}枚を「{1}」に移動しました。編集 → 取り消す で元に戻せます。{0:.0}", + "Moved {n} file{} to “{}”. Edit → Undo moves them back.": "{n}件のファイルを「{1}」に移動しました。編集 → 取り消す で元に戻せます。{0:.0}", "Named ({named_n})": "名前付き({named_n})", "Paste into {n} photo{} — only settings that were copied are pasted": "{n}枚に貼り付け{:.0}(コピーされた設定だけを適用)", "Preset: {name}": "プリセット:{name}", @@ -325,9 +325,14 @@ "Panel move was not applied: {error}": "パネルの移動は適用されませんでした:{error}", "{name} is installed": "{name} をインストールしました", "{name} is installed and in use: face recognition is on": "{name} をインストールして使用中です:顔認識はオンです", + "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} 秒(画像エンコーダー {encoder:.1} 秒)", "Bring photos in with File › Import Photos… ({keys}).": "ファイル › 写真を読み込む… ({keys}) で写真を読み込みます。", "View › Detail View ({keys}).": "表示 › 詳細表示 ({keys})。", "File › Export… · File › Print… ({keys}).": "ファイル › 書き出す… · ファイル › 印刷… ({keys})。", + "It leads back to itself through “{}”: change the rules of one album on the loop (Edit Smart Album…)": "アルバム「{}」を通じて自分自身に戻っています。循環しているアルバムのどれかの条件を変更してください(スマートアルバムを編集…)", + "Add {n} photo{} to “{}”": "{n}枚を「{1}」に追加{0:.0}", + "{n} already there": "{n}枚は追加済み", + "Add “{keyword}” to {n} photo{}": "写真{n}枚に「{keyword}」を追加{:.0}", "Rule {n} of {m}: {what}. Move with the arrow keys": "条件 {n}/{m}:{what}。矢印キーで移動", "Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "グループ {n}/{m}:一致条件 {mode}、中に {count} 件。矢印キーで移動", ", rating {} of 5": "、評価: 5段階中{}" diff --git a/crates/ui-egui/locales/ja.json b/crates/ui-egui/locales/ja.json index d68575ac8c..d154bb0835 100644 --- a/crates/ui-egui/locales/ja.json +++ b/crates/ui-egui/locales/ja.json @@ -46,6 +46,7 @@ "Import photos with File → Import Photos…, or drop them here": "「ファイル → 写真を読み込む…」から読み込むか、ここに写真をドロップしてください", "This row covers more than one disk: drop on a folder inside it": "この行は複数のディスクにまたがっています。中のフォルダにドロップしてください", "Local photos aren't in the library yet: Add to My Photos first, then move them": "ローカルの写真はまだライブラリにありません。先に「マイフォトに追加」してから移動してください", + "Demo photos have no file on disk, so they can't be moved": "デモの写真にはディスク上のファイルがないため、移動できません", "Add to Selected Photos": "選択した写真に追加", "Add to Target Album": "追加先アルバムに追加", "Add to this mask": "このマスクに追加", @@ -140,6 +141,7 @@ "Before/After (Y)": "編集前/編集後(Y)", "Before/After Settings": "編集前/編集後の設定", "Before/After Split": "編集前/編集後の分割表示", + "Before/After": "編集前/編集後", "Before/After Split Top/Bottom": "編集前/編集後の上下分割表示", "Before/After Top/Bottom": "編集前/編集後の上下表示", "Begin Interaction": "操作を開始", @@ -334,6 +336,7 @@ "Custom template…": "カスタムテンプレート…", "Custom…": "カスタム…", "Cycle Crop Overlay": "切り抜きの重ね表示を切り替え", + "Crop Overlay": "切り抜きの重ね表示", "Cycle Crop Overlay Orientation": "切り抜きの重ね表示の向きを切り替え", "Cycle Info Overlay": "情報オーバーレイを切り替え", "Cycle Mask Overlay Color": "マスクの重ね表示の色を切り替え", @@ -1525,6 +1528,7 @@ "XMP sidecars": "XMPサイドカーファイル", "Year": "年", "Yellow": "イエロー", + "White": "ホワイト", "Yellow Hue": "イエローの色相", "Yellow Luminance": "イエローの輝度", "Yellow Saturation": "イエローの彩度", @@ -1943,6 +1947,9 @@ "Not saved": "保存されていません", "A folder is being synchronized": "フォルダを同期中です", "Wait for the import to finish": "読み込みが終わるまでお待ちください", + "Filter settings": "設定を絞り込む", + "No setting matches what is typed.": "入力に一致する設定はありません。", + "Try one word, or part of one: the names of tabs and sections, labels and explanations are all looked through.": "単語またはその一部で試してください。タブとセクションの名前、ラベル、説明文が検索されます。", "Appearance": "外観", "Appearance Mode": "外観モード", "Sync with System": "システムと同期", @@ -2400,6 +2407,14 @@ "The photos are imported once it ends": "終わりしだい写真を読み込みます", "An import is running. Drop photos when it has finished": "読み込み中です。完了してから写真をドロップしてください", "Finish Lightroom catalog import before adding photos": "写真を追加する前に Lightroom カタログの読み込みを完了してください", + "Mixer": "ミキサー", + "HSL": "HSL", + "Adjust": "調整", + "Color Mixer Layout": "カラーミキサーの表示", + "Loupe Overlay": "ルーペのオーバーレイ", + "View Options…": "表示オプション…", + "View Options": "表示オプション", + "View → Loupe Overlay → View Options chooses the lines Info 1 and Info 2 show.": "表示 → ルーペのオーバーレイ → 表示オプション で、情報1と情報2に表示する行を選びます。", "Camera preview": "カメラのプレビュー", "The camera's own JPEG, shown until LightCraft has rendered the raw. Judge colour and tone on the rendered photo.": "LightCraft が RAW を現像するまで表示される、カメラ自身の JPEG です。色とトーンは現像後の写真で判断してください。", "Profile: from the file (the camera's own correction)": "プロファイル: ファイル内(カメラ自身の補正)", @@ -2434,6 +2449,14 @@ "Tool strip": "ツールバー", "Bottom bar": "下部バー", "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "G-SYNC/FreeSyncのちらつきを防ぐ(次回起動時に適用)", + "AI masks": "AIマスク", + "Device": "デバイス", + "Last photo": "直前の写真", + "Remote worker": "リモートワーカー", + "Run on": "実行先", + "Automatic (GPU when available)": "自動(GPUがあれば使用)", + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer.": "オブジェクトと説明で選択のマスクは、写真ごとに一度だけ解析します。CPUを選んだ場合や「描画にGPUを使用」がオフの場合を除き、グラフィックカードで行います。処理装置ではかなり時間がかかります。", + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "自動ではMacのグラフィックカードでモデルを実行します。そこでAIマスクが失敗する場合はCPUを選んでください。処理装置ではかなり時間がかかります。", "User Templates": "ユーザーテンプレート", "Delete Folder": "フォルダを削除", "Folder name": "フォルダ名", @@ -2460,6 +2483,18 @@ "Welcome": "ようこそ", "Next": "次へ", "Get Started": "始める", + "Keywords and presets apply to new files only, not to photos already in Local": "キーワードとプリセットは新しいファイルにのみ適用され、すでにローカルにある写真には適用されません", + "This album is in a loop, so it shows nothing": "このアルバムは循環しているため、何も表示されません", + "It tests itself: change its rules (Edit Smart Album…)": "自分自身を条件にしています。条件を変更してください(スマートアルバムを編集…)", + "Can't add to an album folder": "アルバムフォルダには追加できません", + "An album folder holds albums, not photos: drop on an album inside it": "アルバムフォルダに入れられるのはアルバムだけです:中のアルバムにドロップしてください", + "Can't add to a smart album": "スマートアルバムには追加できません", + "A smart album's rules choose its photos: change them with Edit Smart Album…": "スマートアルバムの写真はルールで決まります:「スマートアルバムを編集…」で変更してください", + "Add keywords in the Keyword List": "キーワードはキーワードリストで追加します", + "Give photos a keyword in the Keyword List (Window → Keywords, K): drop them on it there": "写真にキーワードを付けるには、キーワードリスト(ウィンドウ → キーワード、K)で、そのキーワードにドロップしてください", + "Already on these photos": "すでにこの写真にあります", + "Can't go inside itself": "自分の中には入れられません", + "Same Content as Another Photo": "他の写真と同じ内容", "Reduce Motion": "動きを減らす", "Reduce motion": "動きを減らす", "Turns off zoom and spinner animations. Fades stay. Follows the system's Reduce Motion until you change it here.": "ズームとスピナーのアニメーションをオフにします。フェードはそのまま残ります。ここで変更するまで、システムの「視差効果を減らす」設定に従います。", @@ -2472,5 +2507,11 @@ "Stack — click to collapse (S)": "スタック — クリックして折りたたむ (S)", "Virtual copy": "仮想コピー", "Right-click ▸ Locate Missing File… to find it again.": "右クリック → 見つからないファイルを指定… で、ファイルをもう一度指定できます。", - "Right-click ▸ Reload from Disk to try again.": "右クリック → ディスクから再読み込み で、もう一度試せます。" + "Right-click ▸ Reload from Disk to try again.": "右クリック → ディスクから再読み込み で、もう一度試せます。", + "Album name (empty outside an album view)": "アルバム名(アルバム表示外では空)", + "Export date (YYYYMMDD)": "書き出し日 (YYYYMMDD)", + "Export time (HHMM)": "書き出し時刻 (HHMM)", + "Insert variable": "変数を挿入", + "Insert…": "挿入…", + "none ({album}, {date}, {hour})": "なし ({album}, {date}, {hour})" } diff --git a/crates/ui-egui/locales/ka-formats.json b/crates/ui-egui/locales/ka-formats.json index 373fafdefa..46b74662cc 100644 --- a/crates/ui-egui/locales/ka-formats.json +++ b/crates/ui-egui/locales/ka-formats.json @@ -306,10 +306,10 @@ "{n} selected photos · {pages} pages": "მონიშნული ფოტო: {n} · გვერდი: {pages}", "{n} selected photo{} · {pages} page{}": "არჩეული ფოტო: {n} · გვერდი: {pages}{:.0}{:.0}", "Already in “{}”": "უკვე „{}“-შია", - "Move {n} photo{} to “{}”": "ფოტოს გადატანა „{1}“-ში: {n}{0:.0}", - "Move {n} photo{} to “{}”?": "გადავიდეს „{1}“-ში ფოტო: {n}{0:.0}?", + "Move {n} file{} to “{}”": "ფაილის გადატანა „{1}“-ში: {n}{0:.0}", + "Move {n} file{} to “{}”?": "გადავიდეს „{1}“-ში ფაილი: {n}{0:.0}?", "Listing folders — folders: {folders}, files: {files}": "საქაღალდეების ჩამოთვლა — საქაღალდეები: {folders}, ფაილები: {files}", - "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "„{1}“-ში გადავიდა ფოტო: {n}{0:.0}. რედაქტირება → დაბრუნება მათ უკან აბრუნებს.", + "Moved {n} file{} to “{}”. Edit → Undo moves them back.": "„{1}“-ში გადავიდა ფაილი: {n}{0:.0}. რედაქტირება → დაბრუნება მათ უკან აბრუნებს.", "Drop to review {n} item{} for import": "ჩააგდეთ იმპორტამდე გადასახედად (ელემენტები: {n}){:.0}", "Drop to import {n} item{}": "ჩააგდეთ იმპორტისთვის (ელემენტები: {n}){:.0}", "Drop to import {n} preset{}": "ჩააგდეთ პრესეტების იმპორტისთვის: {n}{:.0}", @@ -325,11 +325,16 @@ "Panel move was not applied: {error}": "პანელის გადატანა არ შესრულდა: {error}", "{name} is installed": "{name} დაინსტალირებულია", "{name} is installed and in use: face recognition is on": "{name} დაინსტალირებულია და გამოიყენება: სახეების ამოცნობა ჩართულია", + "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} წმ, გამოსახულების ენკოდერი {encoder:.1} წმ", "Bring photos in with File › Import Photos… ({keys}).": "ფოტოების შემოსატანად გამოიყენეთ ფაილი › ფოტოების იმპორტი… ({keys}).", "View › Detail View ({keys}).": "ხედი › დეტალური ხედი ({keys}).", "File › Export… · File › Print… ({keys}).": "ფაილი › ექსპორტი… · ფაილი › დაბეჭდვა… ({keys}).", "{n} folder{} could not be read": "საქაღალდეები, რომლებიც ვერ წაიკითხა: {n}{:.0}", "{n} file{} skipped (not a supported photo type)": "გამოტოვებული ფაილები (მხარდაუჭერელი ფოტოს ტიპია): {n}{:.0}", + "It leads back to itself through “{}”: change the rules of one album on the loop (Edit Smart Album…)": "ის საკუთარ თავს უბრუნდება ალბომის „{}“ გავლით: შეცვალეთ ციკლში მყოფი ერთ-ერთი ალბომის წესები (სმარტ-ალბომის რედაქტირება…)", + "Add {n} photo{} to “{}”": "დაამატეთ ფოტო „{1}“-ში: {n}{0:.0}", + "{n} already there": "{n} უკვე არის", + "Add “{keyword}” to {n} photo{}": "დაამატეთ „{keyword}“ ფოტოებს: {n}{:.0}", "Rule {n} of {m}: {what}. Move with the arrow keys": "წესი {n}/{m}: {what}. გადაადგილება ისრებით", "Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "ჯგუფი {n}/{m}: დამთხვევა {mode}, შიგნით {count}. გადაადგილება ისრებით", ", rating {} of 5": ", შეფასება: {} 5-დან" diff --git a/crates/ui-egui/locales/ka.json b/crates/ui-egui/locales/ka.json index c99377c7a6..5ecc1538b7 100644 --- a/crates/ui-egui/locales/ka.json +++ b/crates/ui-egui/locales/ka.json @@ -87,6 +87,7 @@ "AI Denoise and Find Missing Photos. Each row has the task's name, a progress bar, the count and what it is working": "AI ხმაურის მოცილება და დაკარგული ფოტოების მოძებნა. თითოეულ სტრიქონს აქვს ამოცანის სახელი, პროგრესის ზოლი, რაოდენობა და ის, რაზეც", "AI Mask Model Status": "AI ნიღბების მოდელის მდგომარეობა", "AI RAW denoise": "RAW-ის AI ხმაურის მოცილება", + "AI masks": "AI ნიღბები", "AI masks with SAM 3 (Object and Describe in the Masking panel): click an object to select it (⌥-click leaves a": "AI ნიღბები SAM 3-ით (ობიექტი და აღწერა ნიღბვის პანელში): დაწკაპეთ ობიექტზე მის მოსანიშნად (⌥-დაწკაპუნება ტოვებს", "ARW) gives the merged DNG the colour each photo has when opened alone (issue #965). An HDR merge of CR2s used to come": "ARW) ფოტოების გაერთიანება გაერთიანებულ DNG-ს აძლევს იმ ფერს, რომელიც თითო ფოტოს ცალკე გახსნისას აქვს (ხარვეზი #965). CR2-ების HDR გაერთიანება ადრე", "About": "პროგრამის შესახებ", @@ -232,7 +233,9 @@ "Auto-Tag from Tracklog…": "მდებარეობის მინიჭება მარშრუტის ჟურნალიდან…", "Add Locations": "მდებარეობების დამატება", "Automatic": "ავტომატური", + "Automatic (GPU when available)": "ავტომატური (GPU, თუ არის)", "Automatic renders the Detail view at the size it is shown, up to the photo's own pixels. Choose a size to cap it: smaller is faster.": "ავტომატური რეჟიმი დეტალურ ხედს ასახავს იმ ზომით, რომლითაც ის ჩანს, ფოტოს საკუთარ პიქსელებამდე. ზღვრისთვის აირჩიეთ ზომა: პატარა უფრო სწრაფია.", + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "ავტომატური რეჟიმი მოდელს Mac-ის ვიდეობარათზე უშვებს. აირჩიეთ CPU, თუ AI ნიღბები იქ ვერ მუშაობს; პროცესორზე ისინი გაცილებით დიდხანს გრძელდება.", "Automatic uses the graphics card where it is faster than the processor: both are timed on this computer the first time a photo is made.": "ავტომატური რეჟიმი იყენებს ვიდეობარათს, როცა ის პროცესორზე სწრაფია: ორივეს დრო ამ კომპიუტერზე იზომება, როცა ფოტო პირველად მზადდება.", "Automatically Write Changes into XMP": "ცვლილებების XMP-ში ავტომატურად ჩაწერა", "Automatically write changes into XMP sidecars": "ცვლილებების XMP თანმხლებ ფაილებში ავტომატურად ჩაწერა", @@ -254,6 +257,7 @@ "Before/After (Y)": "მანამდე/შემდეგ (Y)", "Before/After Settings": "მანამდე/შემდეგ პარამეტრები", "Before/After Split": "მანამდე/შემდეგ, გაყოფილი", + "Before/After": "მანამდე/შემდეგ", "Before/After Split Top/Bottom": "მანამდე/შემდეგ, გაყოფილი ზემოთ/ქვემოთ", "Before/After Top/Bottom": "მანამდე/შემდეგ ზემოთ/ქვემოთ", "Begin Interaction": "ურთიერთქმედების დაწყება", @@ -520,6 +524,7 @@ "Cut pages": "გვერდების ამოჭრა", "Cut, Copy, Paste and Select All. Esc in them gives back the text from before you started typing (in the Info panel it": "ხელმისაწვდომია ამოჭრა, კოპირება, ჩასმა და ყველაფრის მონიშვნა. Esc მათში აკრეფის დაწყებამდე არსებულ ტექსტს აბრუნებს (ინფორმაციის პანელში", "Cycle Crop Overlay": "ჩამოჭრის ზედდების მონაცვლეობა", + "Crop Overlay": "ჩამოჭრის ზედდება", "Cycle Crop Overlay Orientation": "ჩამოჭრის ზედდების ორიენტაციის მონაცვლეობა", "Cycle Info Overlay": "ინფორმაციის ზედდების მონაცვლეობა", "Cycle Mask Overlay Color": "ნიღბის ზედდების ფერის მონაცვლეობა", @@ -601,6 +606,7 @@ "Detect Faces": "სახეების ამოცნობა", "Detect Faces (Photo menu) needs it: a small one-time download.": "სახეების ამოცნობას (მენიუ „ფოტო“) ეს სჭირდება: მცირე, ერთჯერადი ჩამოტვირთვა.", "Develop": "დამუშავება", + "Device": "მოწყობილობა", "Develop a photo": "ფოტოს დამუშავება", "Diagonal": "დიაგონალური", "Dialogs": "დიალოგები", @@ -1101,6 +1107,7 @@ "Last GPU fallback": "GPU-დან ბოლო გადართვა", "Last commit": "ბოლო კომიტი", "Last loupe render": "ლუპის ბოლო რენდერი", + "Last photo": "ბოლო ფოტო", "Last view": "ბოლო ხედი", "Lateral Chromatic Aberration": "განივი ქრომატული აბერაცია", "Layer": "შრე", @@ -1399,6 +1406,7 @@ "ONNX model": "ONNX მოდელი", "Object": "ობიექტი", "Object Mask": "ობიექტის ნიღაბი", + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer.": "ობიექტისა და აღწერის ნიღბები თითო ფოტოს ერთხელ აანალიზებს, ვიდეობარათზე, თუ CPU არ არის არჩეული და „რენდერირებისთვის GPU-ის გამოყენება“ გამორთული არ არის. პროცესორზე ეს გაცილებით დიდხანს გრძელდება.", "Object and Describe masks use SAM 3, Meta's segmentation model. It isn't part of LightCraft, and everything else works without it.": "ნიღბები „ობიექტი“ და „აღწერა“ იყენებს SAM 3-ს, Meta-ს სეგმენტაციის მოდელს. ის LightCraft-ის ნაწილი არ არის და ყველაფერი დანარჩენი მის გარეშეც მუშაობს.", "October 2026": "ოქტომბერი 2026", "Off": "გამორთული", @@ -1593,7 +1601,8 @@ "Set Keyword Shortcut…": "საკვანძო სიტყვების მალსახმობის დაყენება…", "Add or Remove Keyword Shortcut": "საკვანძო სიტყვების მალსახმობის დამატება ან მოხსნა", "Keyword Shortcut": "საკვანძო სიტყვების მალსახმობი", - "Part of the keyword shortcut": "საკვანძო სიტყვების მალსახმობის ნაწილი", "Put agents to work": "აგენტების სამუშაოზე დაყენება", + "Part of the keyword shortcut": "საკვანძო სიტყვების მალსახმობის ნაწილი", + "Put agents to work": "აგენტების სამუშაოზე დაყენება", "Put the locations you removed from Local back (no files change)": "ლოკალურიდან მოშორებული მდებარეობების დაბრუნება (ფაილები არ იცვლება)", "Quality": "ხარისხი", "Query Photos": "ფოტოების მოთხოვნა", @@ -1690,6 +1699,7 @@ "Relinked": "ხელახლა დაკავშირებულია", "Reload Changed Files": "შეცვლილი ფაილების ხელახლა ჩატვირთვა", "Reload from Disk": "დისკიდან ხელახლა ჩატვირთვა", + "Remote worker": "დისტანციური დამმუშავებელი", "Remove": "მოშორება", "Remove (H)": "მოშორება (H)", "Remove CA": "ქრომატული აბერაციის მოცილება", @@ -1793,6 +1803,7 @@ "Rule problems are shown in your language and name the field the way the menu does (\"Title: needs something to look": "წესების პრობლემები ნაჩვენებია თქვენს ენაზე და ველს ისე ასახელებს, როგორც მენიუ („დასახელება: საჭიროა საძიებო", "Rule values are checked: a rating of 9, a date like 2026-13 or \"banana\", a \"between\" whose dates are the wrong": "წესების მნიშვნელობები მოწმდება: შეფასება 9, თარიღი, როგორიცაა 2026-13 ან „banana“, „შორის“, რომლის თარიღებიც არასწორი", "Rules": "წესები", + "Run on": "გაშვება", "SAM 3 download stopped: it resumes where it left off next time.": "SAM 3-ის ჩამოტვირთვა შეწყდა: შემდეგ ჯერზე იქიდან გაგრძელდება, სადაც შეჩერდა.", "SDR": "SDR", "SDR Brightness": "SDR სიკაშკაშე", @@ -2307,6 +2318,7 @@ "XMP sidecars": "XMP თანმხლები ფაილები", "Year": "წელი", "Yellow": "ყვითელი", + "White": "თეთრი", "Yellow Hue": "ყვითლის ფერის ტონი", "Yellow Luminance": "ყვითლის სიკაშკაშე", "Yellow Saturation": "ყვითლის გაჯერება", @@ -3153,6 +3165,8 @@ "Delete Cell": "უჯრის წაშლა", "Click a cell to move, resize or arrange it": "დაწკაპეთ უჯრაზე მის გადასაადგილებლად, ზომის შესაცვლელად ან დასალაგებლად", "Loupe Overlay": "ლუპის ზედდება", + "View Options…": "ხედის პარამეტრები…", + "View → Loupe Overlay → View Options chooses the lines Info 1 and Info 2 show.": "ხედი → ლუპის ზედდება → ხედის პარამეტრები ირჩევს სტრიქონებს, რომლებსაც Info 1 და Info 2 აჩვენებს.", "2026-10-21": "2026-10-21", "Sharper resampling in HDR and panorama merges": "უფრო მკვეთრი ხელახალი დისკრეტიზაცია HDR-ისა და პანორამის გაერთიანებებში", "Merged photos (HDR and panorama) are resampled with a sharper filter (Lanczos-3 instead of bilinear). Moving a": "გაერთიანებული ფოტოები (HDR და პანორამა) ხელახლა დისკრეტიზდება უფრო მკვეთრი ფილტრით (Lanczos-3 ბიწრფივის ნაცვლად). ფოტოს", @@ -3728,6 +3742,22 @@ "Folder name": "საქაღალდის სახელი", "Its templates move to User Templates.": "მისი შაბლონები გადავა „მომხმარებლის შაბლონებში“.", "Stopped at the scan limit: there may be more photos": "სკანირების ლიმიტზე გაჩერდა: შესაძლოა სხვა ფოტოებიც არის", + "Keywords and presets apply to new files only, not to photos already in Local": "საკვანძო სიტყვები და პრესეტები მხოლოდ ახალ ფაილებზე მოქმედებს და არა იმ ფოტოებზე, რომლებიც უკვე ლოკალშია", + "This album is in a loop, so it shows nothing": "ეს ალბომი ციკლშია, ამიტომ არაფერს აჩვენებს", + "It tests itself: change its rules (Edit Smart Album…)": "ის საკუთარ თავს ამოწმებს: შეცვალეთ მისი წესები (სმარტ-ალბომის რედაქტირება…)", + "Filter settings": "პარამეტრების გაფილტვრა", + "No setting matches what is typed.": "აკრეფილს არც ერთი პარამეტრი არ ემთხვევა.", + "Try one word, or part of one: the names of tabs and sections, labels and explanations are all looked through.": "სცადეთ ერთი სიტყვა ან მისი ნაწილი: იძებნება ჩანართებისა და სექციების სახელებში, წარწერებსა და განმარტებებში.", + "Can't add to an album folder": "ალბომების საქაღალდეში დამატება შეუძლებელია", + "An album folder holds albums, not photos: drop on an album inside it": "ალბომების საქაღალდეში ალბომებია, არა ფოტოები: ჩააგდეთ მასში არსებულ ალბომზე", + "Can't add to a smart album": "სმარტ-ალბომში დამატება შეუძლებელია", + "A smart album's rules choose its photos: change them with Edit Smart Album…": "სმარტ-ალბომის ფოტოებს მისი წესები ირჩევს: შეცვალეთ „სმარტ-ალბომის რედაქტირება…“-ით", + "Add keywords in the Keyword List": "საკვანძო სიტყვები დაამატეთ საკვანძო სიტყვების სიაში", + "Give photos a keyword in the Keyword List (Window → Keywords, K): drop them on it there": "ფოტოებისთვის საკვანძო სიტყვის მისაცემად გამოიყენეთ საკვანძო სიტყვების სია (ფანჯარა → საკვანძო სიტყვები, K): ჩააგდეთ იქ სასურველ სიტყვაზე", + "Already on these photos": "ამ ფოტოებს უკვე აქვთ", + "Can't go inside itself": "საკუთარ თავში ვერ მოხვდება", + "Demo photos have no file on disk, so they can't be moved": "სადემონსტრაციო ფოტოებს დისკზე ფაილი არ აქვთ, ამიტომ მათი გადატანა შეუძლებელია", + "Same Content as Another Photo": "იგივე შიგთავსი, რაც სხვა ფოტოს", "Reduce Motion": "მოძრაობის შემცირება", "Reduce motion": "მოძრაობის შემცირება", "Turns off zoom and spinner animations. Fades stay. Follows the system's Reduce Motion until you change it here.": "გამორთავს მასშტაბირებისა და მიმდინარეობის ინდიკატორის ანიმაციებს. გაბუნდოვნება შენარჩუნდება. სანამ აქ არ შეცვლით, სისტემის „მოძრაობის შემცირების“ პარამეტრს მისდევს.", @@ -3740,5 +3770,11 @@ "Stack — click to collapse (S)": "დასტა — დააწკაპუნეთ ჩასაკეცად (S)", "Virtual copy": "ვირტუალური ასლი", "Right-click ▸ Locate Missing File… to find it again.": "მარჯვენა დაწკაპუნება → დაკარგული ფაილის მოძებნა… ფაილის ხელახლა საპოვნელად.", - "Right-click ▸ Reload from Disk to try again.": "მარჯვენა დაწკაპუნება → დისკიდან ხელახლა ჩატვირთვა, ხელახლა საცდელად." + "Right-click ▸ Reload from Disk to try again.": "მარჯვენა დაწკაპუნება → დისკიდან ხელახლა ჩატვირთვა, ხელახლა საცდელად.", + "Album name (empty outside an album view)": "ალბომის სახელი (ცარიელია ალბომის ხედის გარეთ)", + "Export date (YYYYMMDD)": "ექსპორტის თარიღი (YYYYMMDD)", + "Export time (HHMM)": "ექსპორტის დრო (HHMM)", + "Insert variable": "ცვლადის ჩასმა", + "Insert…": "ჩასმა…", + "none ({album}, {date}, {hour})": "არცერთი ({album}, {date}, {hour})" } diff --git a/crates/ui-egui/locales/pl-formats.json b/crates/ui-egui/locales/pl-formats.json index 1ceeb7db52..ded03cc37f 100644 --- a/crates/ui-egui/locales/pl-formats.json +++ b/crates/ui-egui/locales/pl-formats.json @@ -302,10 +302,10 @@ "Color space: Rec. 2020 {curve} (HDR AVIF)": "Przestrzeń kolorów: Rec. 2020 {curve} (HDR AVIF)", "{n} selected photo{} · {pages} page{}": "Wybrane zdjęcia: {n} · stron: {pages}{:.0}{:.0}", "Already in “{}”": "Już w „{}”", - "Move {n} photo{} to “{}”": "Przenieś do „{1}” — zdjęcia: {n}{0:.0}", - "Move {n} photo{} to “{}”?": "Przenieść do „{1}” — zdjęcia: {n}{0:.0}?", + "Move {n} file{} to “{}”": "Przenieś do „{1}” — pliki: {n}{0:.0}", + "Move {n} file{} to “{}”?": "Przenieść do „{1}” — pliki: {n}{0:.0}?", "Listing folders — folders: {folders}, files: {files}": "Przeglądanie folderów — foldery: {folders}, pliki: {files}", - "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "Przeniesiono do „{1}” — zdjęcia: {n}{0:.0}. Edytuj → Cofnij przywróci je.", + "Moved {n} file{} to “{}”. Edit → Undo moves them back.": "Przeniesiono do „{1}” — pliki: {n}{0:.0}. Edytuj → Cofnij przywróci je.", "Drop to review {n} item{} for import": "Upuść, aby przejrzeć przed importem (elementy: {n}){:.0}", "Drop to import {n} item{}": "Upuść, aby zaimportować (elementy: {n}){:.0}", "Drop to import {n} preset{}": "Upuść, aby zaimportować ustawienia wstępne: {n}{:.0}", @@ -322,11 +322,16 @@ "Panel move was not applied: {error}": "Przeniesienie panelu nie zostało zastosowane: {error}", "{name} is installed": "{name} jest zainstalowany", "{name} is installed and in use: face recognition is on": "{name} jest zainstalowany i używany: rozpoznawanie twarzy jest włączone", + "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} s, koder obrazu {encoder:.1} s", "Bring photos in with File › Import Photos… ({keys}).": "Zdjęcia importujesz przez Plik › Importuj zdjęcia… ({keys}).", "View › Detail View ({keys}).": "Widok › Widok szczegółów ({keys}).", "File › Export… · File › Print… ({keys}).": "Plik › Eksportuj… · Plik › Drukuj… ({keys}).", "{n} folder{} could not be read": "Nie udało się odczytać folderów: {n}{:.0}", "{n} file{} skipped (not a supported photo type)": "Pominięte pliki (nieobsługiwany typ zdjęcia): {n}{:.0}", + "It leads back to itself through “{}”: change the rules of one album on the loop (Edit Smart Album…)": "Wraca do siebie przez album „{}”: zmień reguły jednego z albumów w pętli (Edytuj album inteligentny…)", + "Add {n} photo{} to “{}”": "Dodaj do „{1}” — zdjęcia: {n}{0:.0}", + "{n} already there": "{n} już tam jest", + "Add “{keyword}” to {n} photo{}": "Dodaj „{keyword}” do zdjęć: {n}{:.0}", "Rule {n} of {m}: {what}. Move with the arrow keys": "Reguła {n} z {m}: {what}. Przenoś strzałkami", "Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "Grupa {n} z {m}: dopasuj {mode}, w środku {count}. Przenoś strzałkami", ", rating {} of 5": ", ocena: {} na 5" diff --git a/crates/ui-egui/locales/pl.json b/crates/ui-egui/locales/pl.json index 12f9b320b1..56bd9891eb 100644 --- a/crates/ui-egui/locales/pl.json +++ b/crates/ui-egui/locales/pl.json @@ -135,6 +135,7 @@ "Before/After (Y)": "Przed/Po (Y)", "Before/After Settings": "Ustawienia porównania przed/po", "Before/After Split": "Podział przed/po", + "Before/After": "Przed/Po", "Before/After Split Top/Bottom": "Podział przed/po góra/dół", "Before/After Top/Bottom": "Przed/Po góra/dół", "Begin Interaction": "Rozpocznij interakcję", @@ -332,6 +333,7 @@ "Cut": "Wytnij", "Cut pages": "Wytnij strony", "Cycle Crop Overlay": "Przełącz nakładkę kadrowania", + "Crop Overlay": "Nakładka kadrowania", "Cycle Crop Overlay Orientation": "Przełącz orientację nakładki kadrowania", "Cycle Info Overlay": "Przełącz nakładkę informacji", "Cycle Mask Overlay Color": "Przełącz kolor nakładki maski", @@ -1563,6 +1565,7 @@ "XMP sidecars": "Pliki pomocnicze XMP", "Year": "Rok", "Yellow": "Żółty", + "White": "Biały", "Yellow Hue": "Odcień żółci", "Yellow Luminance": "Luminancja żółci", "Yellow Saturation": "Nasycenie żółci", @@ -2264,6 +2267,9 @@ "End Slideshow": "Zakończ pokaz slajdów", "Contact Sheet PDF…": "Arkusz stykowy PDF…", "Edit in PhotoCraft": "Edytuj w PhotoCraft", + "Filter settings": "Filtruj ustawienia", + "No setting matches what is typed.": "Żadne ustawienie nie pasuje do wpisanego tekstu.", + "Try one word, or part of one: the names of tabs and sections, labels and explanations are all looked through.": "Wpisz jedno słowo lub jego część: przeszukiwane są nazwy kart i sekcji, etykiety oraz objaśnienia.", "Edit in Other Editor": "Edytuj w innym edytorze", "Open Original in Other Editor (RAW, no copy)": "Otwórz oryginał w innym edytorze (RAW, bez kopii)", "Save Current Settings as New Effect Preset…": "Zapisz bieżące ustawienia jako nowe ustawienie wstępne efektu…", @@ -2327,6 +2333,13 @@ "The photos are imported once it ends": "Zdjęcia zostaną zaimportowane potem", "An import is running. Drop photos when it has finished": "Import jest w toku. Upuść zdjęcia, gdy się zakończy", "Finish Lightroom catalog import before adding photos": "Zakończ import katalogu Lightrooma, zanim dodasz zdjęcia", + "Mixer": "Mikser", + "HSL": "HSL", + "Adjust": "Dostosuj", + "Color Mixer Layout": "Układ miksera kolorów", + "Loupe Overlay": "Nakładka lupy", + "View Options…": "Opcje widoku…", + "View → Loupe Overlay → View Options chooses the lines Info 1 and Info 2 show.": "Widok → Nakładka lupy → Opcje widoku wybiera wiersze, które pokazują Info 1 i Info 2.", "Profile: from the file (the camera's own correction)": "Profil: z pliku (korekcja aparatu)", "Downloading the lens database…": "Pobieranie bazy obiektywów…", "This file names no lens.": "Ten plik nie podaje obiektywu.", @@ -2358,6 +2371,16 @@ "Top bar": "Górny pasek", "Tool strip": "Pasek narzędzi", "Bottom bar": "Dolny pasek", + "AI masks": "Maski AI", + "Device": "Urządzenie", + "Last photo": "Ostatnie zdjęcie", + "Remote worker": "Zdalny proces", + "Not loaded yet": "Jeszcze nie wczytano", + "Run on": "Uruchamiaj na", + "Automatic (GPU when available)": "Automatycznie (GPU, gdy jest)", + "CPU": "CPU", + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer.": "Maski Obiekt i Opisz analizują każde zdjęcie raz, na karcie graficznej, chyba że wybrano CPU albo opcja „Użyj procesora graficznego do renderowania” jest wyłączona. Na procesorze trwa to znacznie dłużej.", + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "Automatycznie uruchamia model na karcie graficznej Maca. Wybierz CPU, jeśli maski AI tam zawodzą; na procesorze trwa to znacznie dłużej.", "User Templates": "Szablony użytkownika", "Delete Folder": "Usuń folder", "Folder name": "Nazwa folderu", @@ -2385,6 +2408,19 @@ "Next": "Dalej", "Get Started": "Zaczynamy", "Stopped at the scan limit: there may be more photos": "Zatrzymano na limicie skanowania: możliwe, że jest więcej zdjęć", + "Keywords and presets apply to new files only, not to photos already in Local": "Słowa kluczowe i ustawienia predefiniowane dotyczą tylko nowych plików, nie zdjęć, które już są w Lokalnych", + "This album is in a loop, so it shows nothing": "Ten album jest w pętli, więc niczego nie pokazuje", + "It tests itself: change its rules (Edit Smart Album…)": "Sprawdza samego siebie: zmień jego reguły (Edytuj album inteligentny…)", + "Can't add to an album folder": "Nie można dodać do folderu albumów", + "An album folder holds albums, not photos: drop on an album inside it": "Folder albumów zawiera albumy, nie zdjęcia: upuść na album w jego wnętrzu", + "Can't add to a smart album": "Nie można dodać do albumu inteligentnego", + "A smart album's rules choose its photos: change them with Edit Smart Album…": "O zdjęciach albumu inteligentnego decydują jego reguły: zmienisz je przez Edytuj album inteligentny…", + "Add keywords in the Keyword List": "Dodawaj słowa kluczowe na Liście słów kluczowych", + "Give photos a keyword in the Keyword List (Window → Keywords, K): drop them on it there": "Aby nadać zdjęciom słowo kluczowe, użyj Listy słów kluczowych (Okno → Słowa kluczowe, K): upuść je tam na to słowo", + "Already on these photos": "Już mają je te zdjęcia", + "Can't go inside itself": "Nie może trafić do siebie samego", + "Demo photos have no file on disk, so they can't be moved": "Zdjęcia demonstracyjne nie mają pliku na dysku, więc nie można ich przenieść", + "Same Content as Another Photo": "Ta sama zawartość co inne zdjęcie", "Reduce Motion": "Ogranicz ruch", "Reduce motion": "Ogranicz ruch", "Turns off zoom and spinner animations. Fades stay. Follows the system's Reduce Motion until you change it here.": "Wyłącza animacje powiększania i wskaźników pracy. Zanikanie i przenikanie zostają. Dopóki nie zmienisz tego tutaj, program stosuje systemowe ustawienie Ogranicz ruch.", @@ -2397,5 +2433,11 @@ "Stack — click to collapse (S)": "Stos — kliknij, aby zwinąć (S)", "Virtual copy": "Kopia wirtualna", "Right-click ▸ Locate Missing File… to find it again.": "Kliknij prawym przyciskiem → Znajdź brakujący plik…, aby go odnaleźć ponownie.", - "Right-click ▸ Reload from Disk to try again.": "Kliknij prawym przyciskiem → Wczytaj ponownie z dysku, aby spróbować jeszcze raz." + "Right-click ▸ Reload from Disk to try again.": "Kliknij prawym przyciskiem → Wczytaj ponownie z dysku, aby spróbować jeszcze raz.", + "Album name (empty outside an album view)": "Nazwa albumu (pusta poza widokiem albumu)", + "Export date (YYYYMMDD)": "Data eksportu (YYYYMMDD)", + "Export time (HHMM)": "Czas eksportu (HHMM)", + "Insert variable": "Wstaw zmienną", + "Insert…": "Wstaw…", + "none ({album}, {date}, {hour})": "brak ({album}, {date}, {hour})" } diff --git a/crates/ui-egui/locales/pt-br-formats.json b/crates/ui-egui/locales/pt-br-formats.json index 4c9450a3d2..d6361782ef 100644 --- a/crates/ui-egui/locales/pt-br-formats.json +++ b/crates/ui-egui/locales/pt-br-formats.json @@ -61,10 +61,10 @@ "LightCraft could not open its window: {e}\n\nThe log file has the details: {path}": "O LightCraft não conseguiu abrir sua janela: {e}\n\nO arquivo de log tem os detalhes: {path}", "Matches: {}": "Correspondências: {}", "Merging… {stage} {:.0}%": "Mesclando… {stage} {:.0}%", - "Move {n} photo{} to “{}”": "Mover {n} foto{0} para “{1}”", - "Move {n} photo{} to “{}”?": "Mover {n} foto{0} para “{1}”?", + "Move {n} file{} to “{}”": "Mover {n} arquivo{0} para “{1}”", + "Move {n} file{} to “{}”?": "Mover {n} arquivo{0} para “{1}”?", "Move {what} to Recently Deleted?": "Mover {what} para Excluídos recentemente?", - "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "{n} foto{0} movida{0} para “{1}”. Editar → Desfazer as traz de volta.", + "Moved {n} file{} to “{}”. Edit → Undo moves them back.": "{n} arquivo{0} movido{0} para “{1}”. Editar → Desfazer os traz de volta.", "Named ({named_n})": "Nomeadas ({named_n})", "Paste into {n} photo{} — only settings that were copied are pasted": "Colar em {n} foto{} — somente os ajustes copiados são colados", "Preset: {name}": "Predefinição: {name}", @@ -325,9 +325,14 @@ "Panel move was not applied: {error}": "A movimentação do painel não foi aplicada: {error}", "{name} is installed": "{name} está instalado", "{name} is installed and in use: face recognition is on": "{name} está instalado e em uso: o reconhecimento facial está ativado", + "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} s, codificador de imagem {encoder:.1} s", "Bring photos in with File › Import Photos… ({keys}).": "Traga fotos com Arquivo › Importar fotos… ({keys}).", "View › Detail View ({keys}).": "Exibir › Exibição de detalhe ({keys}).", "File › Export… · File › Print… ({keys}).": "Arquivo › Exportar… · Arquivo › Imprimir… ({keys}).", + "It leads back to itself through “{}”: change the rules of one album on the loop (Edit Smart Album…)": "Ele volta para si mesmo pelo álbum “{}”: mude as regras de um álbum do ciclo (Editar álbum inteligente…)", + "Add {n} photo{} to “{}”": "Adicionar {n} foto{0} a “{1}”", + "{n} already there": "já no álbum: {n}", + "Add “{keyword}” to {n} photo{}": "Adicionar “{keyword}” a {n} foto{}", "Rule {n} of {m}: {what}. Move with the arrow keys": "Regra {n} de {m}: {what}. Mova com as setas", "Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "Grupo {n} de {m}: igualar {mode}, {count} dentro. Mova com as setas", ", rating {} of 5": ", avaliação: {} de 5" diff --git a/crates/ui-egui/locales/pt-br.json b/crates/ui-egui/locales/pt-br.json index d2e96211f0..592de957bf 100644 --- a/crates/ui-egui/locales/pt-br.json +++ b/crates/ui-egui/locales/pt-br.json @@ -47,6 +47,7 @@ "Import photos with File → Import Photos…, or drop them here": "Importe fotos com Arquivo → Importar fotos… ou solte-as aqui", "This row covers more than one disk: drop on a folder inside it": "Esta linha abrange mais de um disco: solte em uma pasta dentro dela", "Local photos aren't in the library yet: Add to My Photos first, then move them": "As fotos locais ainda não estão na biblioteca: primeiro Adicionar às Minhas fotos, depois mova-as", + "Demo photos have no file on disk, so they can't be moved": "As fotos de demonstração não têm arquivo no disco, então não podem ser movidas", "Add to Selected Photos": "Adicionar às fotos selecionadas", "Add to Target Album": "Adicionar ao álbum de destino", "Add to this mask": "Adicionar a esta máscara", @@ -144,6 +145,7 @@ "Before/After (Y)": "Antes/Depois (Y)", "Before/After Settings": "Configurações de Antes/Depois", "Before/After Split": "Divisão Antes/Depois", + "Before/After": "Antes/Depois", "Before/After Split Top/Bottom": "Divisão Antes/Depois topo/base", "Before/After Top/Bottom": "Antes/Depois topo/base", "Begin Interaction": "Iniciar interação", @@ -352,6 +354,7 @@ "Cut": "Recortar", "Cut pages": "Recortar páginas", "Cycle Crop Overlay": "Alternar sobreposição de recorte", + "Crop Overlay": "Sobreposição de recorte", "Cycle Crop Overlay Orientation": "Alternar orientação da sobreposição de recorte", "Cycle Info Overlay": "Alternar sobreposição de informações", "Cycle Mask Overlay Color": "Alternar cor da sobreposição da máscara", @@ -1622,6 +1625,7 @@ "XMP sidecars": "Sidecars XMP", "Year": "Ano", "Yellow": "Amarelo", + "White": "Branco", "Yellow Hue": "Matiz do amarelo", "Yellow Luminance": "Luminância do amarelo", "Yellow Saturation": "Saturação do amarelo", @@ -1941,6 +1945,9 @@ "Not saved": "Não salvo", "A folder is being synchronized": "Uma pasta está sendo sincronizada", "Wait for the import to finish": "Aguarde a importação terminar", + "Filter settings": "Filtrar ajustes", + "No setting matches what is typed.": "Nenhum ajuste corresponde ao que foi digitado.", + "Try one word, or part of one: the names of tabs and sections, labels and explanations are all looked through.": "Tente uma palavra ou parte dela: a busca inclui os nomes das abas e seções, os rótulos e as explicações.", "Appearance": "Aparência", "Appearance Mode": "Modo de aparência", "Sync with System": "Sincronizar com o sistema", @@ -2246,6 +2253,13 @@ "The photos are imported once it ends": "As fotos serão importadas depois", "An import is running. Drop photos when it has finished": "Uma importação está em andamento. Solte as fotos quando ela terminar", "Finish Lightroom catalog import before adding photos": "Conclua a importação do catálogo do Lightroom antes de adicionar fotos", + "Mixer": "Misturador", + "HSL": "HSL", + "Adjust": "Ajustar", + "Color Mixer Layout": "Disposição do misturador de cores", + "Loupe Overlay": "Sobreposição da lupa", + "View Options…": "Opções de exibição…", + "View → Loupe Overlay → View Options chooses the lines Info 1 and Info 2 show.": "Exibir → Sobreposição da lupa → Opções de exibição escolhe as linhas que Info 1 e Info 2 mostram.", "Camera preview": "Prévia da câmera", "The camera's own JPEG, shown until LightCraft has rendered the raw. Judge colour and tone on the rendered photo.": "O JPEG da própria câmera, mostrado até o LightCraft renderizar o RAW. Avalie cor e tom na foto renderizada.", "Profile: from the file (the camera's own correction)": "Perfil: do arquivo (correção da própria câmera)", @@ -2280,6 +2294,14 @@ "Tool strip": "Barra de ferramentas", "Bottom bar": "Barra inferior", "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Evitar cintilação de G-SYNC/FreeSync (no próximo início)", + "AI masks": "Máscaras de IA", + "Device": "Dispositivo", + "Last photo": "Última foto", + "Remote worker": "Processo remoto", + "Run on": "Executar em", + "Automatic (GPU when available)": "Automático (GPU quando houver)", + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer.": "As máscaras Objeto e Descrever analisam cada foto uma vez, na placa de vídeo, a menos que CPU esteja escolhida ou “Usar a GPU para renderização” esteja desligado. No processador isso demora muito mais.", + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "Automático executa o modelo na placa de vídeo do Mac. Escolha CPU se as máscaras de IA falharem nela; no processador elas demoram muito mais.", "User Templates": "Modelos do usuário", "Delete Folder": "Excluir pasta", "Folder name": "Nome da pasta", @@ -2306,6 +2328,18 @@ "Welcome": "Bem-vindo", "Next": "Próximo", "Get Started": "Começar", + "Keywords and presets apply to new files only, not to photos already in Local": "Palavras-chave e predefinições valem só para arquivos novos, não para fotos que já estão em Local", + "This album is in a loop, so it shows nothing": "Este álbum está em um ciclo, então não mostra nada", + "It tests itself: change its rules (Edit Smart Album…)": "Ele testa a si mesmo: mude as regras dele (Editar álbum inteligente…)", + "Can't add to an album folder": "Não é possível adicionar a uma pasta de álbuns", + "An album folder holds albums, not photos: drop on an album inside it": "Uma pasta de álbuns contém álbuns, não fotos: solte em um álbum dentro dela", + "Can't add to a smart album": "Não é possível adicionar a um álbum inteligente", + "A smart album's rules choose its photos: change them with Edit Smart Album…": "As regras de um álbum inteligente escolhem suas fotos: altere-as com Editar álbum inteligente…", + "Add keywords in the Keyword List": "Adicione palavras-chave na Lista de palavras-chave", + "Give photos a keyword in the Keyword List (Window → Keywords, K): drop them on it there": "Para dar uma palavra-chave às fotos, use a Lista de palavras-chave (Janela → Palavras-chave, K): solte-as lá sobre ela", + "Already on these photos": "Já estão nestas fotos", + "Can't go inside itself": "Não pode ficar dentro de si mesma", + "Same Content as Another Photo": "Mesmo conteúdo que outra foto", "Reduce Motion": "Reduzir movimento", "Reduce motion": "Reduzir movimento", "Turns off zoom and spinner animations. Fades stay. Follows the system's Reduce Motion until you change it here.": "Desativa as animações de zoom e dos indicadores de atividade. As transições de opacidade continuam. Segue o ajuste Reduzir movimento do sistema até você alterá-lo aqui.", @@ -2318,5 +2352,11 @@ "Stack — click to collapse (S)": "Pilha — clique para recolher (S)", "Virtual copy": "Cópia virtual", "Right-click ▸ Locate Missing File… to find it again.": "Clique com o botão direito → Localizar arquivo ausente… para encontrá-lo de novo.", - "Right-click ▸ Reload from Disk to try again.": "Clique com o botão direito → Recarregar do disco para tentar de novo." + "Right-click ▸ Reload from Disk to try again.": "Clique com o botão direito → Recarregar do disco para tentar de novo.", + "Album name (empty outside an album view)": "Nome do álbum (vazio fora de uma visualização de álbum)", + "Export date (YYYYMMDD)": "Data de exportação (YYYYMMDD)", + "Export time (HHMM)": "Hora de exportação (HHMM)", + "Insert variable": "Inserir variável", + "Insert…": "Inserir…", + "none ({album}, {date}, {hour})": "nenhum ({album}, {date}, {hour})" } diff --git a/crates/ui-egui/locales/ru-formats.json b/crates/ui-egui/locales/ru-formats.json index 87ba31bbaa..37053b60f1 100644 --- a/crates/ui-egui/locales/ru-formats.json +++ b/crates/ui-egui/locales/ru-formats.json @@ -306,10 +306,10 @@ "{what} merge added at {mp}: its full size, {full}, needs more memory than this computer has": "{what}: слияние добавлено в размере {mp}: для полного размера ({full}) не хватает памяти этого компьютера", "{what} merge added at {mp}, the largest a panorama can be (its full size is {full})": "{what}: слияние добавлено в размере {mp} — это наибольший размер панорамы (полный размер: {full})", "Already in “{}”": "Уже в «{}»", - "Move {n} photo{} to “{}”": "Переместить в «{1}» фото: {n}{0:.0}", - "Move {n} photo{} to “{}”?": "Переместить в «{1}» фото: {n}{0:.0}?", + "Move {n} file{} to “{}”": "Переместить в «{1}» файлов: {n}{0:.0}", + "Move {n} file{} to “{}”?": "Переместить в «{1}» файлов: {n}{0:.0}?", "Listing folders — folders: {folders}, files: {files}": "Просмотр папок — папок: {folders}, файлов: {files}", - "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "В «{1}» перемещено фото: {n}{0:.0}. Правка → Отменить вернёт их.", + "Moved {n} file{} to “{}”. Edit → Undo moves them back.": "В «{1}» перемещено файлов: {n}{0:.0}. Правка → Отменить вернёт их.", "Drop to review {n} item{} for import": "Отпустите для проверки перед импортом (элементов: {n}){:.0}", "Drop to import {n} item{}": "Отпустите для импорта (элементов: {n}){:.0}", "Drop to import {n} preset{}": "Отпустите для импорта пресетов: {n}{:.0}", @@ -325,9 +325,14 @@ "Panel move was not applied: {error}": "Перемещение панели не применено: {error}", "{name} is installed": "Модель {name} установлена", "{name} is installed and in use: face recognition is on": "Модель {name} установлена и используется: распознавание лиц включено", + "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} с, кодировщик изображения {encoder:.1} с", "Bring photos in with File › Import Photos… ({keys}).": "Фотографии добавляются через Файл › Импорт фото… ({keys}).", "View › Detail View ({keys}).": "Вид › Режим детализации ({keys}).", "File › Export… · File › Print… ({keys}).": "Файл › Экспорт… · Файл › Печать… ({keys}).", + "It leads back to itself through “{}”: change the rules of one album on the loop (Edit Smart Album…)": "Он возвращается к себе через альбом «{}»: измените условия одного из альбомов в цикле (Изменить смарт-альбом…)", + "Add {n} photo{} to “{}”": "Добавить в «{1}» фото: {n}{0:.0}", + "{n} already there": "{n} уже там", + "Add “{keyword}” to {n} photo{}": "Добавить «{keyword}» к фото: {n}{:.0}", "Rule {n} of {m}: {what}. Move with the arrow keys": "Условие {n} из {m}: {what}. Перемещение стрелками", "Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "Группа {n} из {m}: совпадение {mode}, внутри {count}. Перемещение стрелками", ", rating {} of 5": ", оценка: {} из 5" diff --git a/crates/ui-egui/locales/ru.json b/crates/ui-egui/locales/ru.json index 3fef8d0757..dda0cd9bf3 100644 --- a/crates/ui-egui/locales/ru.json +++ b/crates/ui-egui/locales/ru.json @@ -221,6 +221,7 @@ "Import photos with File → Import Photos…, or drop them here": "Импортируйте фото через Файл → Импорт фото… или перетащите их сюда", "This row covers more than one disk: drop on a folder inside it": "Эта строка охватывает несколько дисков: перетащите на папку внутри неё", "Local photos aren't in the library yet: Add to My Photos first, then move them": "Локальных фото ещё нет в библиотеке: сначала «Добавить в «Мои фото»», затем перемещайте", + "Demo photos have no file on disk, so they can't be moved": "У демонстрационных фото нет файла на диске, поэтому их нельзя переместить", "Add to Selected Photos": "Добавить к выбранным фото", "Add to Target Album": "Добавить в целевой альбом", "Add to this mask": "Добавить к этой маске", @@ -310,6 +311,7 @@ "Before/After (Y)": "До/после (Y)", "Before/After Settings": "Настройки «до/после»", "Before/After Split": "Разделение «до/после»", + "Before/After": "До/после", "Before/After Split Top/Bottom": "Разделение «до/после» сверху/снизу", "Before/After Top/Bottom": "До/после сверху/снизу", "Begin Interaction": "Начать взаимодействие", @@ -489,6 +491,7 @@ "Cut": "Вырезать", "Cut pages": "Вырезать страницы", "Cycle Crop Overlay": "Переключить сетку кадрирования", + "Crop Overlay": "Сетка кадрирования", "Cycle Crop Overlay Orientation": "Переключить ориентацию сетки кадрирования", "Cycle Info Overlay": "Переключить информационную накладку", "Cycle Mask Overlay Color": "Переключить цвет наложения маски", @@ -1576,6 +1579,7 @@ "XMP sidecars": "XMP-файлы", "Year": "Год", "Yellow": "Жёлтый", + "White": "Белый", "Yellow Hue": "Тон жёлтого", "Yellow Luminance": "Яркость жёлтого", "Yellow Saturation": "Насыщенность жёлтого", @@ -1870,6 +1874,9 @@ "Not saved": "Не сохранено", "A folder is being synchronized": "Папка синхронизируется", "Wait for the import to finish": "Дождитесь завершения импорта", + "Filter settings": "Фильтр настроек", + "No setting matches what is typed.": "Нет настроек, соответствующих введённому.", + "Try one word, or part of one: the names of tabs and sections, labels and explanations are all looked through.": "Попробуйте одно слово или его часть: поиск ведётся по названиям вкладок и разделов, подписям и пояснениям.", "Appearance": "Оформление", "Appearance Mode": "Режим оформления", "Sync with System": "Как в системе", @@ -2608,6 +2615,13 @@ "The photos are imported once it ends": "Фото будут импортированы после этого", "An import is running. Drop photos when it has finished": "Импорт уже выполняется. Перетащите фото, когда он закончится", "Finish Lightroom catalog import before adding photos": "Завершите импорт каталога Lightroom, прежде чем добавлять фото", + "Mixer": "Микшер", + "HSL": "HSL", + "Adjust": "Настройка", + "Color Mixer Layout": "Вид цветового микшера", + "Loupe Overlay": "Накладка лупы", + "View Options…": "Параметры вида…", + "View → Loupe Overlay → View Options chooses the lines Info 1 and Info 2 show.": "Вид → Накладка лупы → Параметры вида выбирает строки, которые показывают Info 1 и Info 2.", "Camera preview": "Превью камеры", "The camera's own JPEG, shown until LightCraft has rendered the raw. Judge colour and tone on the rendered photo.": "Собственный JPEG камеры, показанный, пока LightCraft не обработает RAW. Оценивайте цвет и тон по обработанному фото.", "Profile: from the file (the camera's own correction)": "Профиль: из файла (коррекция самой камеры)", @@ -2642,6 +2656,14 @@ "Tool strip": "Панель инструментов", "Bottom bar": "Нижняя панель", "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Предотвращать мерцание G-SYNC/FreeSync (после перезапуска)", + "AI masks": "ИИ-маски", + "Device": "Устройство", + "Last photo": "Последнее фото", + "Remote worker": "Удалённый обработчик", + "Run on": "Выполнять на", + "Automatic (GPU when available)": "Автоматически (GPU, если есть)", + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer.": "Маски «Объект» и «Описать» анализируют каждое фото один раз — на видеокарте, если не выбран ЦП и не выключено «Использовать GPU для рендеринга». На процессоре это намного дольше.", + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "«Автоматически» запускает модель на видеокарте Mac. Если ИИ-маски там не работают, выберите ЦП; на процессоре они намного дольше.", "User Templates": "Пользовательские шаблоны", "Delete Folder": "Удалить папку", "Folder name": "Название папки", @@ -2668,6 +2690,18 @@ "Welcome": "Добро пожаловать", "Next": "Далее", "Get Started": "Начать", + "Keywords and presets apply to new files only, not to photos already in Local": "Ключевые слова и пресеты применяются только к новым файлам, а не к фото, которые уже есть в «Локальных»", + "This album is in a loop, so it shows nothing": "Этот альбом попал в цикл, поэтому ничего не показывает", + "It tests itself: change its rules (Edit Smart Album…)": "Он проверяет сам себя: измените его условия (Изменить смарт-альбом…)", + "Can't add to an album folder": "Нельзя добавить в папку альбомов", + "An album folder holds albums, not photos: drop on an album inside it": "В папке альбомов лежат альбомы, а не фото: бросьте на альбом внутри неё", + "Can't add to a smart album": "Нельзя добавить в смарт-альбом", + "A smart album's rules choose its photos: change them with Edit Smart Album…": "Фото смарт-альбома определяются его правилами: измените их через «Изменить смарт-альбом…»", + "Add keywords in the Keyword List": "Добавляйте ключевые слова в списке ключевых слов", + "Give photos a keyword in the Keyword List (Window → Keywords, K): drop them on it there": "Чтобы задать фото ключевое слово, используйте список ключевых слов (Окно → Ключевые слова, K): бросьте фото там на нужное слово", + "Already on these photos": "Уже есть у этих фото", + "Can't go inside itself": "Нельзя поместить внутрь себя", + "Same Content as Another Photo": "То же содержимое, что у другого фото", "Reduce Motion": "Уменьшить движение", "Reduce motion": "Уменьшить движение", "Turns off zoom and spinner animations. Fades stay. Follows the system's Reduce Motion until you change it here.": "Отключает анимацию масштабирования и индикаторов работы. Плавные затухания остаются. Пока вы не измените это здесь, действует системная настройка «Уменьшение движения».", @@ -2680,5 +2714,11 @@ "Stack — click to collapse (S)": "Стопка — щёлкните, чтобы свернуть (S)", "Virtual copy": "Виртуальная копия", "Right-click ▸ Locate Missing File… to find it again.": "Щёлкните правой кнопкой → Указать отсутствующий файл…, чтобы найти его снова.", - "Right-click ▸ Reload from Disk to try again.": "Щёлкните правой кнопкой → Перезагрузить с диска, чтобы повторить попытку." + "Right-click ▸ Reload from Disk to try again.": "Щёлкните правой кнопкой → Перезагрузить с диска, чтобы повторить попытку.", + "Album name (empty outside an album view)": "Название альбома (пусто вне просмотра альбома)", + "Export date (YYYYMMDD)": "Дата экспорта (YYYYMMDD)", + "Export time (HHMM)": "Время экспорта (HHMM)", + "Insert variable": "Вставить переменную", + "Insert…": "Вставить…", + "none ({album}, {date}, {hour})": "нет ({album}, {date}, {hour})" } diff --git a/crates/ui-egui/locales/sv-formats.json b/crates/ui-egui/locales/sv-formats.json index fcb15a5eda..c84bcb2bdd 100644 --- a/crates/ui-egui/locales/sv-formats.json +++ b/crates/ui-egui/locales/sv-formats.json @@ -299,9 +299,9 @@ "…and {more} more": "…och {more} till", "Already in “{}”": "Already in “{}”", "Color space: Rec. 2020 {curve} (HDR AVIF)": "Color space: Rec. 2020 {curve} (HDR AVIF)", - "Move {n} photo{} to “{}”": "Move {n} photo{} to “{}”", - "Move {n} photo{} to “{}”?": "Move {n} photo{} to “{}”?", - "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "Moved {n} photo{} to “{}”. Edit → Undo moves them back.", + "Move {n} file{} to “{}”": "Move {n} file{} to “{}”", + "Move {n} file{} to “{}”?": "Move {n} file{} to “{}”?", + "Moved {n} file{} to “{}”. Edit → Undo moves them back.": "Moved {n} file{} to “{}”. Edit → Undo moves them back.", "{n} selected photos · {pages} pages": "{n} selected photos · {pages} pages", "{in_trash} catalog photos are in this library's Recently Deleted and stay there; restore them from Recently Deleted to see them.": "{in_trash} katalogfoton finns i Nyligen raderade i det här biblioteket och ligger kvar där; återställ dem från Nyligen raderade för att se dem.", "{skipped} catalog images were not imported because their records in the catalog are incomplete.": "{skipped} catalog images were not imported because their records in the catalog are incomplete.", @@ -314,6 +314,7 @@ "Inside: {names}": "Inuti: {names}", "Where should the Lightroom catalog “{catalog}” go?": "Vart ska Lightroom-katalogen ”{catalog}” importeras?", "Merge into the open library “{library}” ({count} photo{})": "Slå samman med det öppna biblioteket ”{library}” ({count} foto{:.0})", + "{title}: {line}": "{title}: {line}", "Photo: {name}": "Foto: {name}", "Panel layout could not be restored: {error}": "Panellayouten kunde inte återställas: {error}", "Panel move was not applied: {error}": "Panelflytten tillämpades inte: {error}", @@ -322,11 +323,24 @@ "Creates {stacks} stack{} from {photos} of {scope}": "Skapar staplar: {stacks} · foton: {photos} av {scope}{:.0}", "{n} selected photo{} · {pages} page{}": "Markerade foton: {n} · sidor: {pages}{:.0}{:.0}", "{n} photo{} in view · {slides} slide{} · {time}": "Foton i vyn: {n} · bilder: {slides} · {time}{:.0}{:.0}", + "Can't read this folder: {}": "Det går inte att läsa den här mappen: {}", + "LightCraft can correct distortion and vignetting for many lenses using the open lens database (lensfun, about {size} MB).": "LightCraft kan korrigera distorsion och vinjettering för många objektiv med hjälp av den öppna objektivdatabasen (lensfun, cirka {size} MB).", + "No lens profile found for {}.": "Ingen objektivprofil hittades för {}.", + "Profile: {} (lens database)": "Profil: {} (objektivdatabas)", + "The drive with this library's previews is almost full: {free} free of {total}. The preview cache takes {cache} and grows as the library does. To keep it smaller, set a size limit in Settings → Performance.": "Enheten med det här bibliotekets förhandsgranskningar är nästan full: {free} ledigt av {total}. Cachen för förhandsgranskningar tar {cache} och växer i takt med biblioteket. Om du vill hålla den mindre anger du en storleksgräns under Inställningar → Prestanda.", + "The lens database is not installed (about {size} MB).": "Objektivdatabasen är inte installerad (cirka {size} MB).", + "{n} photos got their lens profile": "{n} foton fick sin objektivprofil", + "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} s, bildkodare {encoder:.1} s", "Bring photos in with File › Import Photos… ({keys}).": "Importera foton via Fil › Importera foton… ({keys}).", "View › Detail View ({keys}).": "Visa › Detaljvy ({keys}).", "File › Export… · File › Print… ({keys}).": "Fil › Exportera… · Fil › Skriv ut… ({keys}).", "{n} folder{} could not be read": "Mappar som inte gick att läsa: {n}{:.0}", "{n} file{} skipped (not a supported photo type)": "Hoppade över filer (fotoformat som inte stöds): {n}{:.0}", + "It leads back to itself through “{}”: change the rules of one album on the loop (Edit Smart Album…)": "Det leder tillbaka till sig självt via albumet ”{}”: ändra reglerna för ett av albumen i loopen (Redigera smart album…)", + "Adjustments: {n}": "Justeringar: {n}", + "Add {n} photo{} to “{}”": "Lägg till foton i ”{1}”: {n}{0:.0}", + "Add “{keyword}” to {n} photo{}": "Lägg till ”{keyword}” på foton: {n}{:.0}", + "{n} already there": "redan i albumet: {n}", "Rule {n} of {m}: {what}. Move with the arrow keys": "Regel {n} av {m}: {what}. Flytta med piltangenterna", "Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "Grupp {n} av {m}: matcha {mode}, antal i gruppen: {count}. Flytta med piltangenterna", ", rating {} of 5": ", betyg: {} av 5" diff --git a/crates/ui-egui/locales/sv.json b/crates/ui-egui/locales/sv.json index a5604c37fe..a15af4747d 100644 --- a/crates/ui-egui/locales/sv.json +++ b/crates/ui-egui/locales/sv.json @@ -133,7 +133,7 @@ "any": "någon", "Any camera": "Valfri kamera", "Any keyword": "Valfritt nyckelord", - "Any lens": "Valfri lins", + "Any lens": "Valfritt objektiv", "Any Searchable Text": "All sökbar text", "Aperture": "Bländare", "Appearance": "Utseende", @@ -661,7 +661,7 @@ "Effect": "Effekt", "Effects": "Effekter", "Empty Recently Deleted": "Töm Nyligen raderade", - "Enable Lens Corrections": "Aktivera linskorrigeringar", + "Enable Lens Corrections": "Aktivera objektivkorrigeringar", "Enable Painting": "Aktivera målning", "Enable Profile Corrections": "Aktivera profilkorrigeringar", "End": "Slut", @@ -908,8 +908,8 @@ "HDR TIFF needs 32-bit float.": "HDR TIFF kräver 32-bitars flyttal.", "HDR with Last Settings": "HDR med senaste inställningar", "HDR…": "HDR…", - "Heal": "Läk", - "Heal the small, soft dark spots sensor dust leaves on smooth areas": "Läk de små, mjuka mörka fläckar som sensordamm lämnar på jämna ytor", + "Heal": "Retuschera", + "Heal the small, soft dark spots sensor dust leaves on smooth areas": "Retuschera de små, mjuka mörka fläckar som sensordamm lämnar på jämna ytor", "Height": "Höjd", "Height (px)": "Höjd (px)", "Help": "Hjälp", @@ -943,7 +943,7 @@ "Hue": "Nyans", "Hue Range": "Nyansintervall", "I have read these terms and accept them for my own use": "Jag har läst villkoren och godkänner dem för eget bruk", - "Identity plate": "Identitetsplåt", + "Identity plate": "Namnskylt", "If file exists": "Om filen finns", "If your library can't be opened at launch (open in another program, unreadable, on a drive that isn't connected,": "Om ditt bibliotek inte kan öppnas vid start (öppet i ett annat program, oläsbart, på en enhet som inte är ansluten,", "ignored before) chooses the graphics backend; `off` renders on the CPU. The GPU now starts after the window": "ignorerades tidigare) väljer grafikbakänden; `off` renderar på CPU:n. GPU:n startar nu efter att fönstret", @@ -1117,9 +1117,9 @@ "leaves no DNG and keeps the raw. Smart previews are written the same way; a damaged one (cut short by a crash or": "lämnar ingen DNG och behåller rawfilen. Smarta förhandsgranskningar skrivs på samma sätt; en skadad (avbruten av en krasch eller", "Left": "Vänster", "Left: the standard (SDR) range up to SDR white. Right: the HDR range, one band per stop above SDR white (the orange line: the HDR headroom). With Visualize HDR range on, the bands take its colours.": "Vänster: standardomfånget (SDR) upp till SDR-vitt. Höger: HDR-omfånget, ett band per steg över SDR-vitt (den orange linjen: HDR-marginalen). När Visualisera HDR-omfång är på får banden dess färger.", - "Lens": "Lins", + "Lens": "Objektiv", "Lens Blur": "Linsoskärpa", - "Lens Corrections": "Linskorrigeringar", + "Lens Corrections": "Objektivkorrigeringar", "Level": "Nivå", "Library": "Bibliotek", "Library Folders": "Biblioteksmappar", @@ -1222,8 +1222,8 @@ "Match": "Matcha", "Match Total Exposures": "Matcha total exponering", "Matrix/TRC": "Matris/TRC", - "Matte": "Matte", - "Matte Soft": "Matte mjuk", + "Matte": "Matt", + "Matte Soft": "Matt mjuk", "Med": "Medel", "Medium Contrast": "Medelkontrast", "Megapixels": "Megapixel", @@ -1398,12 +1398,12 @@ "No keywords match": "Inga nyckelord matchar", "No keywords yet": "Inga nyckelord än", "No Label": "Ingen etikett", - "No lens data embedded in this file (DNG lens opcodes only).": "Inga linsdata finns inbäddade i den här filen (endast DNG-linsopkoder).", - "No lens data embedded in this file.": "Inga linsdata finns inbäddade i den här filen.", + "No lens data embedded in this file (DNG lens opcodes only).": "Inga objektivdata finns inbäddade i den här filen (endast DNG-objektivopkoder).", + "No lens data embedded in this file.": "Inga objektivdata finns inbäddade i den här filen.", "No masks yet. Choose a mask type above.": "Inga masker än. Välj en masktyp ovan.", "No matching commands": "Inga matchande kommandon", "No matching photos": "Inga matchande foton", - "No Matte": "Ingen matte", + "No Matte": "Ingen matthet", "No metadata found": "Inga metadata hittades", "No model credits were built into this copy.": "Inga modellkrediteringar finns inbyggda i den här kopian.", "No named people in these photos": "Inga namngivna personer i de här fotona", @@ -1442,7 +1442,7 @@ "Nothing to compare": "Inget att jämföra", "Nothing to survey": "Inget att granska", "now develop from the raw data instead of the camera's embedded JPEG, so a B&W or other picture style set in the": "framkallas nu från rådata i stället för kamerans inbäddade JPEG, så en svartvit eller annan bildstil som ställts in i", - "Nudge Develop Value": "Knuffa framkallningsvärde", + "Nudge Develop Value": "Flytta framkallningsvärde stegvis", "Numbered JPEG files (name-001.jpg…) in a new folder named in the next step.": "Numrerade JPEG-filer (namn-001.jpg…) i en ny mapp som du namnger i nästa steg.", "Object": "Objekt", "Object and Describe masks use SAM 3, Meta's segmentation model. It isn't part of LightCraft, and everything else works without it.": "Masker av typen Objekt och Beskriv använder SAM 3, Metas segmenteringsmodell. Den ingår inte i LightCraft, och allt annat fungerar utan den.", @@ -1561,7 +1561,7 @@ "Photos that arrive in this folder (tethering, a scanner, a sync app) are added as soon as they're complete.": "Foton som hamnar i den här mappen (tethering, en skanner, en synkapp) läggs till så fort de är kompletta.", "photos waiting": "foton väntar", "Photos); importing (also by drag and drop), Find Missing Photos, Build / Discard Smart Previews, the Rename preview,": "Foton); import (även med dra och släpp), Hitta saknade foton, Skapa/släng smarta förhandsgranskningar, förhandsgranskningen för Byt namn,", - "Pick": "Plocka", + "Pick": "Välj", "pick": "vald", "Pick a colour on the photo with the eyedropper.": "Välj en färg i fotot med pipetten.", "Pick a date": "Välj ett datum", @@ -1714,7 +1714,7 @@ "Red Luminance": "Röd luminans", "Red Primary": "Röd primärfärg", "Red Saturation": "Röd mättnad", - "Red/Cyan Fringe": "Röd/cyan fransning", + "Red/Cyan Fringe": "Röd/cyan färgkant", "Redo": "Gör om", "Reference": "Referens", "Reference the files where they are": "Referera till filerna där de ligger", @@ -2185,7 +2185,7 @@ "the graphics card is not used": "grafikkortet används inte", "The graphics card is set up when the next photo is made.": "Grafikkortet konfigureras när nästa foto skapas.", "The import reads the catalog without changing it and adds its photos, edits, keywords and collections to the library open now.": "Importen läser katalogen utan att ändra den och lägger till dess foton, redigeringar, nyckelord och samlingar i biblioteket som är öppet nu.", - "The intro plays once before the first photo; the ending after the last photo when Repeat is off. The identity plate is the one set under Overlays. Titles fade like slides and random order never moves them.": "Introt spelas en gång före det första fotot; avslutningen efter det sista fotot när Upprepa är av. Identitetsplåten är den som angetts under Överlägg. Titlar tonas som bilderna och slumpmässig ordning flyttar dem aldrig.", + "The intro plays once before the first photo; the ending after the last photo when Repeat is off. The identity plate is the one set under Overlays. Titles fade like slides and random order never moves them.": "Introt spelas en gång före det första fotot; avslutningen efter det sista fotot när Upprepa är av. Namnskylten är den som angetts under Överlägg. Titlar tonas som bilderna och slumpmässig ordning flyttar dem aldrig.", "The intro screen, before the first photo.": "Introskärmen, före det första fotot.", "the JPEG uses `IMG_0001.JPG.xmp`.": "JPEG-filen använder `IMG_0001.JPG.xmp`.", "The layout image can't be shown": "Layoutbilden kan inte visas", @@ -2439,6 +2439,267 @@ "★ Favorites": "★ Favoriter", "日本語": "日本語", "繁體中文(台灣)": "繁體中文(台灣)", + "\"24.0-70.0 mm f/2.8\". Those cameras don't write a lens name, so the lens field was empty and you couldn't filter or": "\"24.0-70.0 mm f/2.8\". De kamerorna skriver inget objektivnamn, så objektivfältet var tomt och du kunde inte filtrera eller", + "\"Albums\" header takes it back to the top level; Esc cancels; holding a dragged album or photos near the top or bottom edge of the sidebar scrolls it). Drop on the top or bottom half of another album,": "Rubriken \"Album\" tar den tillbaka till översta nivån; Esc avbryter; håller du ett draget album eller foton nära sidofältets över- eller nederkant rullas det). Släpp på övre eller nedre halvan av ett annat album,", + "\"Canon CRX adaptive QP value 172\" or \"175\". They now decode from the sensor data. Photos imported before this": "\"Canon CRX adaptive QP value 172\" eller \"175\". Nu avkodas de från sensordata. Foton som importerats före denna", + "\"File exists\".": "\"File exists\".", + "\"HEIC/HEIF support isn't included in this build\" for each `.heic`/`.heif` at import.": "\"HEIC/HEIF-stöd ingår inte i det här bygget\" för varje `.heic`/`.heif` vid import.", + "\"If file exists\" works per folder as usual, and an original is never written over.": "\"Om filen finns\" fungerar per mapp som vanligt, och ett original skrivs aldrig över.", + "\"LightCraft stopped unexpectedly\" and why, instead of \"could not open its window\", and the next start renders": "\"LightCraft har stoppats oväntat\" och varför, i stället för \"kunde inte öppna sitt fönster\", och nästa start renderar", + "\"Rendering…\" on the photo": "\"Renderar…\" på fotot", + "#1236). The D7000, D5100, D800, D800E, Df, D4, D3, D3S, D700, D300, D300S, D600, D610, D810, D4S, D5600,": "#1236). D7000, D5100, D800, D800E, Df, D4, D3, D3S, D700, D300, D300S, D600, D610, D810, D4S, D5600,", + "#1440): a Sony α1 face reads 8 MB instead of 70 MB, an A7S III face about 1 MB instead of 24 MB, several times": "#1440): för ett ansikte i en Sony α1-bild läses 8 MB i stället för 70 MB, i en A7S III-bild ungefär 1 MB i stället för 24 MB, flera gånger", + "#1447), or keeps the photo you had when the folder holds it. Before, the photo from the previous view stayed active:": "#1447), eller behåller fotot du hade när mappen innehåller det. Tidigare förblev fotot från föregående vy aktivt:", + "(\"Failed to associate portal window with parent window\" in the portal's log): tiling compositors put it beside the": "(\"Failed to associate portal window with parent window\" i portalens logg): fönsterhanterare med tiling lade den bredvid", + "(`album.setRules` takes `name`).": "(`album.setRules` tar `name`).", + "(`id`, `parent?`, `before?`) and `album.sort`.": "(`id`, `parent?`, `before?`) och `album.sort`.", + "(`render in.raw -o out.jxl`). Quality as for JPEG, or Lossless; Effort (Fast / Normal) trades time for a": "(`render in.raw -o out.jxl`). Kvalitet som för JPEG, eller Förlustfri; Ansträngning (Snabb / Normal) väger tid mot en", + "(`slideshow.exportStatus` for the result).": "(`slideshow.exportStatus` för resultatet).", + "(checked on one CC0 iPhone 12 Pro ProRAW). Photos without mattes are unchanged.": "(kontrollerat på en CC0-bild i iPhone 12 Pro ProRAW). Foton utan segmenteringsmasker är oförändrade.", + "(Esc keeps the old angle; a decimal comma works too), or click the Straighten value; hovering any slider's value now says it can be typed.": "(Esc behåller den gamla vinkeln; decimalkomma fungerar också), eller klicka på värdet för Räta upp; när du hovrar över ett reglagevärde står det nu att det kan skrivas in.", + "(folders open on click) or finds them as you type part of a name or folder (↑ / ↓ and Enter to pick); albums that": "(mappar öppnas vid klick) eller hittar dem medan du skriver en del av ett namn eller en mapp (↑ / ↓ och Enter för att välja); album som", + "(issue #1455), up to 512 MP and 65,000 pixels on the long edge, as in Lightroom. When the full size needs more": "(ärende #1455), upp till 512 MP och 65 000 pixlar på långsidan, som i Lightroom. När full storlek kräver mer", + "(issue #256): the correction the camera records in the file is applied under Lens Corrections ▸ Enable Profile": "(ärende #256): korrigeringen som kameran registrerar i filen tillämpas under Objektivkorrigeringar → Aktivera profil", + "(issue #706; before, the import skipped it as \"already in the library\" while the grid showed it deleted). The": "(ärende #706; tidigare hoppade importen över den som \"redan i biblioteket\" medan rutnätet visade den som raderad). Den", + "(issue #735).": "(ärende #735).", + "(issue #782).": "(ärende #782).", + "(issues #187, #298). Importing files that are in Recently Deleted asks whether to leave them there, restore them": "(ärenden #187, #298). När du importerar filer som finns i Nyligen raderade får du frågan om du vill låta dem vara kvar där, återställa dem", + "(its width over its height was 0 / 0, which stopped debug builds); it shows as a single pixel's colour.": "(dess bredd genom höjd var 0 / 0, vilket stoppade debug-byggen); den visas som färgen på en enda pixel.", + "(macOS, Windows, Linux, FreeBSD, Nix) now really are built with HEIC support; a build without it reports": "(macOS, Windows, Linux, FreeBSD, Nix) byggs nu verkligen med HEIC-stöd; ett bygge utan det rapporterar", + "(now 0.05 s). The scan looks up only the files it finds and the contents it reads, on its own thread.": "(nu 0,05 s). Genomsökningen slår bara upp de filer den hittar och det innehåll den läser, i en egen tråd.", + "(Space, G, X, ⌫) and ⌘ shortcuts were not affected.": "(Blanksteg, G, X, ⌫) och ⌘-kortkommandon påverkades inte.", + "(with their edits) or import them as new; the trash view's Photo menu has Empty Recently Deleted.": "(med sina redigeringar) eller importera dem som nya; skräpvyns Foto-meny har Töm Nyligen raderade.", + "(~0.6 s per slider tick); now the list is saved only after it changes, and a slider tick takes ~2 ms.": "(~0,6 s per reglagesteg); nu sparas listan bara när den har ändrats, och ett reglagesteg tar ~2 ms.", + ")": ")", + "**Import Lightroom Catalog…** with that catalog, or Cancel. `lightcraft-cli --library` refuses those folders too.": "**Importera Lightroom-katalog…** med den katalogen, eller Avbryt. `lightcraft-cli --library` vägrar också öppna de mapparna.", + "**JPEG:** numbered files (`Holiday-001.jpg`, `Holiday-002.jpg`…) in a new folder.": "**JPEG:** numrerade filer (`Holiday-001.jpg`, `Holiday-002.jpg`…) i en ny mapp.", + "**PDF:** one page per slide at 1024, 1920 or 3840 pixels on the long side, at a JPEG quality you choose. Each page": "**PDF:** en sida per bild med 1024, 1920 eller 3840 pixlar på långsidan, med en JPEG-kvalitet du väljer. Varje sida", + "**Photos already in your library get theirs in the background**: LightCraft reads just the few kilobytes of each": "**Foton som redan finns i biblioteket får sina i bakgrunden**: LightCraft läser bara de få kilobyte i varje", + "**Video:** AV1 video in an MP4 (or WebM) file at 720p or 1080p, 24 or 30 frames per second: each slide stays up for": "**Video:** AV1-video i en MP4-fil (eller WebM) med 720p eller 1080p, 24 eller 30 bilder per sekund: varje bild visas i", + "**Z zooms to it**: Toggle Zoom centres on the focus point, so checking that the subject is sharp is one key": "**Z zoomar till den**: Växla zoom centrerar på fokuspunkten, så att kontrollera att motivet är skarpt kräver bara en tangent", + "0.3 MB of JPEG instead of 5.6 MB and is ready several times sooner; Nikon and Panasonic raws with a mid-sized": "0,3 MB JPEG i stället för 5,6 MB och är klar flera gånger snabbare; raw-filer från Nikon och Panasonic med en medelstor", + "1200D (Rebel T5) and 100D (Rebel SL1) now count as clipped (issue #1272). They used to stop at 81–98% of white, so": "1200D (Rebel T5) och 100D (Rebel SL1) räknas nu som klippta (ärende #1272). De stannade tidigare vid 81–98 % av vitt, så", + "12–32 mm kit zoom was off by about 5 % of the image width at the corners before. Files shot with the correction off": "12–32 mm-kitzoom avvek tidigare med ungefär 5 % av bildbredden i hörnen. Filer som fotograferats med korrigeringen avstängd", + "1440 px at the corners, where it was up to 17 px off before. The camera's lateral chromatic aberration table is read": "1440 px i hörnen, där det tidigare var upp till 17 px fel. Kamerans tabell för lateral kromatisk aberration läses", + "150 dpi · sRGB · current edits · fit without cropping": "150 dpi · sRGB · aktuella redigeringar · anpassa utan beskärning", + "16 GB, 355 MP with 32 GB) and the message says so. The merge also frees each photo's pixels once they are": "16 GB, 355 MP med 32 GB) och meddelandet säger det. Sammanfogningen frigör också varje fotos pixlar så snart de är", + "16-bit Rec. 2020 PQ. Not in the web version yet.": "16-bitars Rec. 2020 PQ. Inte i webbversionen än.", + "2026-10-02": "2026-10-02", + "2026-10-05": "2026-10-05", + "2026-10-07": "2026-10-07", + "2026-10-08": "2026-10-08", + "2026-10-09": "2026-10-09", + "2026-10-10": "2026-10-10", + "2026-10-11": "2026-10-11", + "2026-10-12": "2026-10-12", + "2026-10-13": "2026-10-13", + "2026-10-14": "2026-10-14", + "3396 K, one on the Shade preset 7493 K. As for #730, only the numbers change: edits made on the old relative": "3396 K, ett med förinställningen Skugga 7493 K. Liksom för #730 ändras bara siffrorna: redigeringar gjorda på den gamla relativa", + "67,000 photos that step went from 37 ms to under 1 ms. Still worked out whole: an edit to more than 256 photos, a": "67 000 foton gick det steget från 37 ms till under 1 ms. Räknas fortfarande ut i sin helhet: en redigering av fler än 256 foton, en", + "[camera preview colour](camera-preview-colour.md#spectral-camera-matrices-and-the-order-of-precedence).": "[kamerans förhandsgranskningsfärg](camera-preview-colour.md#spectral-camera-matrices-and-the-order-of-precedence).", + "`*.jpg` case-sensitively, so `.JPG` and `.NEF` files were hidden — issues #342 and #705).": "`*.jpg` skiftlägeskänsligt, så `.JPG`- och `.NEF`-filer doldes — ärenden #342 och #705).", + "`--import ` takes HEIC": "`--import ` tar med HEIC", + "`--memory` sessions keep their promise to save nothing (issues #164, #169): UI changes made in one no longer": "`--memory`-sessioner håller sitt löfte att inte spara något (ärenden #164, #169): gränssnittsändringar som görs i en sådan session inte längre", + "`.jpg`) have always been taken for the cache's, and are renamed with it.": "`.jpg`) har alltid räknats som cachens och byter namn tillsammans med den.", + "`.lrcat-data` folders, or the `.lrcat`) no longer makes an empty LightCraft library inside it (issue #891). The": "`.lrcat-data`-mappar, eller `.lrcat`) skapar inte längre ett tomt LightCraft-bibliotek inuti den (ärende #891).", + "`destinationMode: \"sameAsOriginal\"` (or `\"specificFolder\"`) to `app.export`; `dir` is then not needed.": "`destinationMode: \"sameAsOriginal\"` (eller `\"specificFolder\"`) till `app.export`; `dir` behövs då inte.", + "`develop.curve` are kept in order, and a sidecar curve with a \"NaN\" or \"inf\" point is ignored.": "`develop.curve` behålls i ordning, och en kurva i en sidecar-fil med en \"NaN\"- eller \"inf\"-punkt ignoreras.", + "`export.photosImports`. See [Add to Apple Photos](apple-photos.md).": "`export.photosImports`. Se [Lägg till i Apple Photos](apple-photos.md).", + "`lightcraft-cli --library` given a library's own file (`catalog.snap`) opens its folder instead of failing with": "`lightcraft-cli --library` som får ett biblioteks egen fil (`catalog.snap`) öppnar dess mapp i stället för att misslyckas med", + "`lightcraft-cli run --import ` (and the MCP tools that take folders) now picks up HEIC, HEIF and Nikon NRW": "`lightcraft-cli run --import ` (och MCP-verktygen som tar mappar) tar nu med HEIC, HEIF och Nikon NRW", + "`lightcraft-cli` logs warnings on stderr too (issue #168); `LIGHTCRAFT_LOG` or `RUST_LOG` picks another level.": "`lightcraft-cli` loggar varningar även på stderr (ärende #168); `LIGHTCRAFT_LOG` eller `RUST_LOG` väljer en annan nivå.", + "`mask.brushStroke {connect: true}` does the same for agents.": "`mask.brushStroke {connect: true}` gör samma sak för agenter.", + "`publicDomain` (rules and agents keep using the ids; `album.ruleFields` adds `choiceLabels`).": "`publicDomain` (regler och agenter använder fortfarande id:na; `album.ruleFields` lägger till `choiceLabels`).", + "`Shift+6–9` labels and advances. `Shift+P` picks and advances in Photo Grid and Square Grid; it opens Presets in other views. With Auto Advance on, Shift still moves only once.": "`Shift+6–9` sätter etikett och går vidare. `Shift+P` flaggar som vald och går vidare i Fotorutnät och Kvadratiskt rutnät; i andra vyer öppnar det Förinställningar. Med Gå vidare automatiskt på flyttar Shift ändå bara en gång.", + "`slideshow.overlays`; `slideshow.preview` now also returns where each overlay landed.": "`slideshow.overlays`; `slideshow.preview` returnerar nu även var varje överlägg hamnade.", + "`slideshow.playback`; `view.slideshow` takes any of them for one run (`interval` still sets the slide duration).": "`slideshow.playback`; `view.slideshow` tar vilken som helst av dem för en körning (`interval` anger fortfarande visningstiden per bild).", + "`{file}`, `{date}`, `{exposure}` (\"1/250 s at f/8\"), `{iso}`, `{focal}`, `{camera}`, `{lens}`, `{rating}` and the": "`{file}`, `{date}`, `{exposure}` (\"1/250 s vid f/8\"), `{iso}`, `{focal}`, `{camera}`, `{lens}`, `{rating}` och", + "A `thumbs` folder that holds nothing but the cache says that it is one (`CACHEDIR.TAG`), so backup programs that": "En `thumbs`-mapp som inte innehåller något annat än cachen anger att den är en sådan (`CACHEDIR.TAG`), så att säkerhetskopieringsprogram som", + "a cast shadow (opacity, offset, radius, angle), and a backdrop colour with an optional colour wash (a gradient from a": "en slagskugga (opacitet, förskjutning, radie, vinkel) och en fondfärg med valfri färgslöja (en gradient från en", + "A crop a hair wide (or of no size), set by an agent or read from a sidecar, no longer crashes or hangs the": "En beskärning som är hårfint bred (eller utan storlek), satt av en agent eller läst från en sidecar-fil, kraschar eller låser inte längre", + "A crop of no size (from an agent or a sidecar) no longer gives the Detail view a photo of no size to lay out": "En beskärning utan storlek (från en agent eller en sidecar-fil) ger inte längre Detalj-vyn ett foto utan storlek att lägga ut", + "A crop of no size with healing spots or masks no longer crashes the render: samples outside the picture read its": "En beskärning utan storlek med retuscheringsfläckar eller masker kraschar inte längre renderingen: sampel utanför bilden läser dess", + "A damaged or crafted raw can no longer make LightCraft set aside gigabytes of memory before finding out the file is": "En skadad eller manipulerad raw-fil kan inte längre få LightCraft att reservera gigabyte av minne innan det upptäcker att filen är", + "A demo photo whose stored size was damaged (a width of 4294967295) is rendered at its own size instead of": "Ett demofoto vars lagrade storlek var skadad (en bredd på 4294967295) renderas i sin egen storlek i stället för", + "A dialog taller than the window no longer runs off it (issue #781): on a 1366×768 screen the Export dialog's title": "En dialogruta som är högre än fönstret går inte längre utanför det (ärende #781): på en 1366×768-skärm har exportdialogrutans rubrik", + "A dialog's confirm button says it's the next step": "En dialogrutas bekräftelseknapp visar att den är nästa steg", + "A double-click on the thumb is a single step in History and Undo. Its first click no longer nudges the value to": "Ett dubbelklick på reglagehandtaget är ett enda steg i Historik och Ångra. Dess första klick flyttar inte längre värdet till", + "A face model uses the GPU only when a check shows it gives the same results faster.": "En ansiktsmodell använder GPU:n bara när en kontroll visar att den ger samma resultat snabbare.", + "A file named `portable.txt` next to the LightCraft program makes it keep its settings, logs and downloaded": "En fil med namnet `portable.txt` bredvid LightCraft-programmet gör att det sparar sina inställningar, loggar och nedladdade", + "a flag taken off in Picks, a rating that falls under the filter bar's. With it off, as before, the photo leaves the": "en flagga som tagits bort i Valda, ett betyg som hamnar under filterfältets. När det är av försvinner fotot, som tidigare, ur", + "A Folders section in the sidebar lists the folders your photos were imported from; choose one to see its photos.": "Avsnittet Mappar i sidofältet listar mapparna som dina foton importerades från; välj en för att se dess foton.", + "A label follows its folder when it is renamed or moved in LightCraft, together with the labels of the folders": "En etikett följer med sin mapp när den byter namn eller flyttas i LightCraft, tillsammans med etiketterna för mapparna", + "A library holding thousands of presets (a Lightroom collection imported whole: 11 000 presets, a 42 MB": "Ett bibliotek med tusentals förinställningar (en Lightroom-samling importerad i sin helhet: 11 000 förinställningar, en 42 MB", + "A library whose catalog file was damaged (or edited by hand) in a way that still reads no longer crashes": "Ett bibliotek vars katalogfil har skadats (eller redigerats för hand) på ett sätt som fortfarande går att läsa kraschar inte längre", + "A library with no photos now opens on the Photo Grid with the sidebar (Square Grid stays as it is), instead of a": "Ett bibliotek utan foton öppnas nu i Fotorutnät med sidofältet (Kvadratiskt rutnät förblir som det är), i stället för en", + "A Lightroom Classic catalog whose changes are all still in its `.lrcat-wal` file (a new catalog Lightroom has": "En Lightroom Classic-katalog vars ändringar fortfarande alla ligger i dess `.lrcat-wal`-fil (en ny katalog som Lightroom har", + "a line, a tab per level, synonyms in braces, keywords left out of export in brackets). Capture One, darktable, Adobe": "en rad, en tabb per nivå, synonymer inom klammerparenteser, nyckelord som utesluts från export inom hakparenteser). Capture One, darktable, Adobe", + "a magazine cover's masthead and cover lines, so you can frame a shot for the page it is made for. It fits inside": "ett tidningsomslags namnvinjett och puffar, så att du kan komponera en bild för sidan den är gjord för. Den ryms inom", + "A name the library doesn't have is marked as a new keyword before you press Return, so a misspelling no longer": "Ett namn som inte finns i biblioteket markeras som ett nytt nyckelord innan du trycker på Retur, så att en felstavning inte längre", + "a photo stop matching the view keeps it in the view: a keyword given in a smart album of photos without keywords,": "får ett foto att sluta matcha vyn behåller det i vyn: ett nyckelord som ges i ett smart album med foton utan nyckelord,", + "A photo that has no folder on disk (a demo photo, or one in the web version's browser storage) or whose folder": "Ett foto som inte har någon mapp på disken (ett demofoto, eller ett i webbversionens webbläsarlagring) eller vars mapp", + "A photo that runs into a bug in LightCraft while it renders (in a raw decoder or the editing pipeline) now fails": "Ett foto som stöter på en bugg i LightCraft medan det renderas (i en raw-avkodare eller i redigeringskedjan) misslyckas nu", + "A photo the folder lists is there for the scan, also where its file could not be opened by its path (a folder": "Ett foto som mappen listar finns med i genomsökningen, även där dess fil inte kunde öppnas via sökvägen (en mapp", + "A photo whose Defringe amount was stored far past the sliders' 20 (in a damaged catalog or sidecar) no longer": "Ett foto vars värde för Ta bort kantfärg lagrats långt över reglagens 20 (i en skadad katalog eller sidecar-fil) inte längre", + "A photo whose file was replaced (Reload Changed Files after an outside edit) no longer keeps the faces recognition": "Ett foto vars fil har ersatts (Läs in ändrade filer igen efter en extern redigering) behåller inte längre ansiktsigenkänningen", + "A preset whose lens-profile switch is off no longer turns off the lens corrections built into a DNG (iPhone ProRAW": "En förinställning vars reglage för objektivprofil är av stänger inte längre av objektivkorrigeringarna som är inbyggda i en DNG (iPhone ProRAW", + "A raw file whose black level is stored as \"not a number\" (or infinity), or a floating-point DNG with such": "En raw-fil vars svartnivå lagrats som \"inte ett tal\" (eller oändlighet), eller en flyttals-DNG med sådana", + "A selection without keywords now says \"No keywords yet\" where its chips would be.": "En markering utan nyckelord visar nu \"Inga nyckelord än\" där dess nyckelordsbrickor skulle vara.", + "A slideshow can now open with an intro screen and close with an ending screen, like Lightroom Classic's Titles": "Ett bildspel kan nu börja med en introskärm och avslutas med en slutskärm, som Titlar i Lightroom Classic", + "A small edit (a keyword, a rating, a flag, a slider) no longer has the grid's list worked out again from every": "En liten ändring (ett nyckelord, ett betyg, en flagga, ett reglage) gör inte längre att rutnätets lista räknas ut igen från varje", + "A smart album can include or exclude another smart album: \"Keywords contain travel\" and \"Album isn't Excluded Photos\"": "Ett smart album kan inkludera eller utesluta ett annat smart album: \"Nyckelord innehåller travel\" och \"Album är inte Excluded Photos\"", + "A smart album whose rules no longer check (an album they test was deleted) is marked ⚠ in the sidebar; its tooltip": "Ett smart album vars regler inte längre går att kontrollera (ett album de testar har raderats) markeras med ⚠ i sidofältet; dess knappbeskrivning", + "A spot with Feather at 0 no longer draws black pixels exactly on its radius. This also fixes spots at 0% Opacity": "En fläck med Fjädring på 0 ritar inte längre svarta pixlar exakt på sin radie. Detta åtgärdar också fläckar med 0 % Opacitet", + "A star, the moon or a light that moves between the photos of a bracket (a night bracket on a tripod) no longer": "En stjärna, månen eller ett ljus som rör sig mellan fotona i en gaffling (en nattgaffling på stativ) inte längre", + "A Synchronize Folder scan no longer asks the disk about every photo of the library in the folder (is its file": "En genomsökning med Synkronisera mapp frågar inte längre disken om varje foto i biblioteket i mappen (finns dess fil", + "a Synchronize scan began (now under 1 s), 2.6 s before an import review (now 0.05 s) and 1.7 s before an import": "en genomsökning med Synkronisera började (nu under 1 s), 2,6 s före en importgranskning (nu 0,05 s) och 1,7 s före en import", + "A template file that can't be used (damaged, from a newer LightCraft, too large) is listed as skipped instead of": "En mallfil som inte kan användas (skadad, från en nyare LightCraft, för stor) listas som överhoppad i stället för", + "A thumbnail of the photo open in Detail is made from its already decoded preview instead of decoding the file": "En miniatyr av fotot som är öppet i Detalj skapas från dess redan avkodade förhandsgranskning i stället för att avkoda filen", + "A view can hold its photos until you refresh it": "En vy kan behålla sina foton tills du uppdaterar den", + "A zoomed view keeps the GPU copy of the original while it is on screen: pausing for a few seconds between pans no": "En zoomad vy behåller GPU-kopian av originalet medan den visas på skärmen: en paus på några sekunder mellan panoreringar inte längre", + "Activity stack": "Aktivitetsstack", + "Add a cell": "Lägg till en cell", + "Add a Face Recognition Model": "Lägg till en modell för ansiktsigenkänning", + "Add Print Cell": "Lägg till utskriftscell", + "Add to Apple Photos (macOS)": "Lägg till i Apple Photos (macOS)", + "adjust or switch them off, and DNG export keeps them. Lateral chromatic aberration data is not applied: our": "justera eller stänga av dem, och DNG-export behåller dem. Data för lateral kromatisk aberration används inte: vår", + "advance (the next two slides render while the current one is up, so a fade never waits or flashes).": "framåt (de två nästa bilderna renderas medan den aktuella visas, så en toning aldrig väntar eller blinkar).", + "after a rename, an `.XMP` sidecar. Adding photos or a folder, Browse Folder (Local), drag-and-drop, the CLI and the": "efter ett namnbyte, en `.XMP`-sidecarfil. Att lägga till foton eller en mapp, Bläddra i mapp (Lokalt), dra och släpp, CLI:t och", + "again.": "igen.", + "Agents list and stop tasks with `activity.list` and `activity.cancel`; `ui.inspect` reports them as `activity`.": "Agenter listar och stoppar uppgifter med `activity.list` och `activity.cancel`; `ui.inspect` rapporterar dem som `activity`.", + "Agents use `app.newLibrary {path, name}`, `app.recentLibraries` and `app.clearRecentLibraries`.": "Agenter använder `app.newLibrary {path, name}`, `app.recentLibraries` och `app.clearRecentLibraries`.", + "Agents: `app.export {addToPhotos, photosAlbum}`, `export.addToPhotos {paths}` for files already on disk, and": "Agenter: `app.export {addToPhotos, photosAlbum}`, `export.addToPhotos {paths}` för filer som redan finns på disk, och", + "Agents: `view.sidebarSection`, `view.sidebarMoveSection`, `view.sidebarReset`; `ui.set` takes `sidebar`.": "Agenter: `view.sidebarSection`, `view.sidebarMoveSection`, `view.sidebarReset`; `ui.set` tar `sidebar`.", + "AI Denoise and Find Missing Photos. Each row has the task's name, a progress bar, the count and what it is working": "AI-brusreducering och Sök efter saknade foton. Varje rad visar uppgiftens namn, en förloppsindikator, antalet och vad den arbetar", + "AI RAW denoise": "AI-brusreducering för raw", + "Album folders fold with the same disclosure triangle as Local, By Date, Folders and Keywords.": "Albummappar fälls ihop med samma triangel som Lokalt, Efter datum, Mappar och Nyckelord.", + "Album rule is \"is\" or \"isn't\" an album, picked with the album picker.": "Albumregeln är \"är\" eller \"är inte\" ett album, valt med albumväljaren.", + "album that is gone, or an empty group is reported with its rule (\"rule 2.1: no rating 0–5 is 9\")": "album som inte längre finns, eller en tom grupp rapporteras med sin regel (\"regel 2.1: inget betyg 0–5 är 9\")", + "album, Delete changes nothing: its rules decide what it shows.": "album ändrar Radera ingenting: dess regler avgör vad det visar.", + "Album, New Smart Album, Rename Keyword, Merge Keywords and similar dialogs, or the name field under unnamed faces for": "Album, Nytt smart album, Byt namn på nyckelord, Sammanfoga nyckelord och liknande dialogrutor, eller namnfältet under namnlösa ansikten för", + "Albums tree": "Albumträd", + "all again.": "alla igen.", + "alone, so the photo's preview and thumbnail sources and its neighbours' were decoded from the raw again on every": "ensamt, så fotots källor för förhandsgranskning och miniatyr och dess grannars avkodades från raw-filen igen vid varje", + "also holds files of yours (a library opened on a photo folder that had one) is not tagged, and your files in it": "även innehåller dina egna filer (ett bibliotek som öppnats på en fotomapp som hade en) märks inte, och dina filer i den", + "an edit to more than 256 photos, and each new minute for an album that asks about \"the last N days\" are still": "en redigering av fler än 256 foton, och varje ny minut för ett album som frågar om \"de senaste N dagarna\" är fortfarande", + "An empty library leads to Import": "Ett tomt bibliotek leder till Importera", + "An export enlarged far past the photo's size (20000 typed for 2000 with Don't Enlarge off) no longer ends": "En export som förstorats långt över fotots storlek (20000 inskrivet för 2000 med Förstora inte avstängt) slutar inte längre", + "An HDR merged from raws that LightCraft colours from the camera's JPEG (CR2, NEF, ARW…) now opens at the same": "En HDR sammanfogad från raw-filer som LightCraft färgsätter från kamerans JPEG (CR2, NEF, ARW…) öppnas nu med samma", + "An uncompressed Leaf Aptus 22 MOS no longer opens as a dark, colourless picture of its sensor mosaic: it imports": "En okomprimerad Leaf Aptus 22 MOS öppnas inte längre som en mörk, färglös bild av sensorns mosaik: den importeras", + "and a dark theme card, each previewing its theme (dark: Charcoal, the look so far, or Midnight;": "och ett kort för mörkt tema, som vart och ett förhandsgranskar sitt tema (mörkt: Kol, utseendet hittills, eller Midnatt;", + "and a section with nothing in it says so instead of disappearing.": "och ett avsnitt utan innehåll säger det i stället för att försvinna.", + "and a smaller export look like the full-size result scaled down; 1:1 views and full-size exports are unchanged.": "och en mindre export ser ut som resultatet i full storlek nedskalat; 1:1-vyer och exporter i full storlek är oförändrade.", + "and a view that asks about \"the last N days\".": "och en vy som frågar om \"de senaste N dagarna\".", + "and CR3, instead of opening flat and desaturated (issue #310). Photos already imported pick it up when re-rendered.": "och CR3, i stället för att öppnas platta och avmättade (ärende #310). Foton som redan importerats får det när de renderas om.", + "and exports don't change. Agents use `app.displayProfile`. See [display profiles](display-profiles.md).": "och exporter ändras inte. Agenter använder `app.displayProfile`. Se [bildskärmsprofiler](display-profiles.md).", + "and its Cancel / OK buttons were off screen, so it couldn't be confirmed. Now its options scroll and the title and": "och dess knappar Avbryt/OK hamnade utanför skärmen, så den gick inte att bekräfta. Nu rullar dess alternativ, och rubriken och", + "and new photos never reuse an id in use. What was repaired is written to the log.": "och nya foton återanvänder aldrig ett id som används. Det som reparerades skrivs till loggen.", + "and other files with embedded distortion / vignetting corrections), matching what the preset does elsewhere.": "och andra filer med inbäddade korrigeringar för distorsion/vinjettering), i linje med vad förinställningen gör på andra ställen.", + "and press Return; Esc keeps the old value.": "och tryck på Return; Esc behåller det gamla värdet.", + "and Survey, following rotation and crops; the Info panel says how it focused (`AF-C · Wide · Animal Eye Tracking`).": "och Översikt, med hänsyn till rotation och beskärningar; panelen Info visar hur den fokuserade (`AF-C · Wide · Animal Eye Tracking`).", + "and the control bar says Intro or End while one is up (the photo count only counts photos).": "och kontrollfältet visar Intro eller Slut medan en sådan visas (fotoantalet räknar bara foton).", + "and the fit to the photo's own JPEG still come first, so photos that had a fitted look keep it. See": "och anpassningen till fotots egen JPEG kommer fortfarande först, så foton som hade ett anpassat utseende behåller det. Se", + "and WB2000. The compressed ones (NX1, NX30, NX300, NX500, NX2000, NX3000, NX3300, NX mini) still open from their": "och WB2000. De komprimerade (NX1, NX30, NX300, NX500, NX2000, NX3000, NX3300, NX mini) öppnas fortfarande från sin", + "Animal Eye Tracking": "Ögonspårning för djur", + "Another library was opened since the photos were dropped: nothing was moved": "Ett annat bibliotek öppnades efter att fotona släpptes: ingenting flyttades", + "answered there too. In such a folder the scan saves less, and its checks now start after the listing where they": "besvaras där också. I en sådan mapp sparar genomsökningen mindre, och dess kontroller startar nu efter listningen där de", + "Any Searchable Text also finds the state / province, alt text, people and a virtual copy's name.": "All sökbar text hittar även delstat/provins, alternativtext, personer och en virtuell kopias namn.", + "app, and with LightCraft fullscreen it was hidden altogether, so Import Photos… looked like a hang until the": "appen, och med LightCraft i helskärm doldes den helt, så Importera foton… såg ut som om programmet hängt sig tills", + "Appearance lists the modes and themes. On Linux, Auto follows the desktop portal's colour scheme": "Utseende listar lägena och temana. På Linux följer Auto skrivbordsportalens färgschema", + "Apple ProRAW's gain table map (its local tone mapping, `ProfileGainTableMap`) is now read and kept when a photo is": "Apple ProRAW:s gain table map (dess lokala tonmappning, `ProfileGainTableMap`) läses nu och behålls när ett foto", + "Apply Mask Effect": "Använd maskeffekt", + "Apply Print Template": "Använd utskriftsmall", + "Apply Slideshow Template": "Använd bildspelsmall", + "apply their effect inside the circle, as Lightroom does, instead of outside it (issue #1815). A mask inverted in": "tillämpar sin effekt inuti cirkeln, som Lightroom gör, i stället för utanför den (ärende #1815). En mask inverterad i", + "Arabic names and other Arabic text in headings, chosen tabs and other bold places are now drawn bold, as Latin text": "Arabiska namn och annan arabisk text i rubriker, valda flikar och andra feta ställen ritas nu i fetstil, som latinsk text", + "are left as they are. Note that files there named exactly like the cache's own (`ab/ab…` with 32 hex digits and": "lämnas som de är. Observera att filer där med exakt samma namn som cachens egna (`ab/ab…` med 32 hexadecimala siffror och", + "are unchanged; photos imported before this change get it when imported again.": "är oförändrade; foton som importerats före denna ändring får det när de importeras igen.", + "are unchanged; the guidance does not guarantee a build will fit every 16 GB machine.": "är oförändrade; riktlinjerna garanterar inte att ett bygge får plats på varje maskin med 16 GB.", + "Arrange Print Cell": "Ordna utskriftscell", + "Arrange the left sidebar your way: drag Albums, Local, By Date, Folders or Keywords by its header to move it (a line": "Ordna det vänstra sidofältet som du vill: dra Album, Lokalt, Efter datum, Mappar eller Nyckelord i rubriken för att flytta avsnittet (en linje", + "ARW) gives the merged DNG the colour each photo has when opened alone (issue #965). An HDR merge of CR2s used to come": "ARW) ger den sammanfogade DNG-filen den färg varje foto har när det öppnas ensamt (ärende #965). En HDR-sammanfogning av CR2-filer brukade bli", + "as 1/250), File Extension, Video Duration, Copy Name, In a Stack, Alt Text, City, State / Province, Country, Long": "som 1/250), Filändelse, Videolängd, Kopiera namn, I en stapel, Alternativtext, Ort, Delstat/provins, Land, Lång", + "as a raw and shows its embedded preview (preview only, with the reason), as the compressed MOS files do.": "som raw och visar sin inbäddade förhandsgranskning (endast förhandsgranskning, med orsaken), som de komprimerade MOS-filerna gör.", + "as before.": "som tidigare.", + "as Exposure would; the edges between bright and dark regions stay as sharp as before. This is rendering process 2:": "som Exponering skulle; kanterna mellan ljusa och mörka områden förblir lika skarpa som tidigare. Detta är renderingsprocess 2:", + "as it changes, without polling.": "när den ändras, utan avfrågning.", + "As Shot temperature and tint as its photos, and changing the white balance no longer turns it green. Sony ARW": "Som tagen-temperatur och -tonvärde som sina foton, och att ändra vitbalansen gör den inte längre grön. Sony ARW", + "ASCII (an umlaut, a curly apostrophe, a dash), about every name the folder does not list. Names it does list are": "ASCII (ett omljudstecken, en typografisk apostrof, ett tankstreck), om varje namn som mappen inte listar. Namn som den listar är", + "Aspect Ratio (a 24 MP photo cropped to a square is 16 MP).": "Bildförhållande (ett foto på 24 MP beskuret till kvadrat är 16 MP).", + "at the camera JPEG's size (6016 × 4016 for the D600 and D610, 4288 × 2848 for the D5000, as the D90 already": "i kamera-JPEG:ens storlek (6016 × 4016 för D600 och D610, 4288 × 2848 för D5000, som D90 redan", + "at their import settings). See `docs/sony-ilce7rm6-lens-corrections.md`.": "med sina importinställningar). Se `docs/sony-ilce7rm6-lens-corrections.md`.", + "Auto Layout": "Auto layout", + "Auto use the same model. Custom white balances on these photos render slightly differently than before.": "Auto använder samma modell. Anpassade vitbalanser på dessa foton renderas något annorlunda än tidigare.", + "bad (issue #1512): a compressed PEF whose data is too short for the size it declares, an uncompressed TIFF-based": "felaktiga (ärende #1512): en komprimerad PEF vars data är för kort för storleken den anger, en okomprimerad TIFF-baserad", + "becomes a keyword unnoticed. The suggestions further down stay put while you type.": "blir ett nyckelord utan att det märks. Förslagen längre ned ligger kvar medan du skriver.", + "before it looks at the first file. In a library of 3.5 million photos that held the window for about 6 s before": "innan den tittar på den första filen. I ett bibliotek med 3,5 miljoner foton höll det upp fönstret i cirka 6 s innan", + "before, and becomes the Kelvin value with the same look the next time it is edited. A photo imported earlier shows": "tidigare, och blir det Kelvinvärde som ger samma utseende nästa gång det redigeras. Ett foto som importerats tidigare visar", + "before. Agents use `slideshow.layout`, and `slideshow.preview` returns one composed slide as a PNG.": "tidigare. Agenter använder `slideshow.layout`, och `slideshow.preview` returnerar en sammansatt bild som PNG.", + "behaviour, `fresh` imports a clean copy and deletes the old record).": "beteende, `fresh` importerar en ren kopia och raderar den gamla posten).", + "behind. A photo that can't be read is skipped and named in the message at the end. Agents use `slideshow.export`": "kvar. Ett foto som inte kan läsas hoppas över och nämns i meddelandet i slutet. Agenter använder `slideshow.export`", + "belonged to another command moves to the new one. Menus show the new keys; agents use `app.setShortcut`.": "tillhörde ett annat kommando flyttas till det nya. Menyerna visar de nya tangenterna; agenter använder `app.setShortcut`.", + "beside the After's, and a window asked for again while the first was still decoding (a pan, the layout settling)": "bredvid Efter-vyns, och ett fönster som begärdes igen medan det första fortfarande avkodades (en panorering, layouten som sätter sig)", + "beside them is; they used to stay at regular weight.": "bredvid dem; tidigare förblev de i normal stil.", + "between slides (a crossfade, or through black, white or any colour; 0 cuts), random order (every photo once per": "mellan bilder (en korstoning, eller via svart, vitt eller valfri färg; 0 ger raka snitt), slumpmässig ordning (varje foto en gång per", + "Blown highlights in CR2 files from the Canon EOS 50D, 60D, 450D (Rebel XSi), 500D (Rebel T1i), 550D (Rebel T2i),": "Utbrända högdagrar i CR2-filer från Canon EOS 50D, 60D, 450D (Rebel XSi), 500D (Rebel T1i), 550D (Rebel T2i),", + "Bold text in other scripts": "Fet text i andra skriftsystem", + "Bridge and Photo Supreme (its Formatted Vocabulary File) use the same files, so keyword lists move between them and": "Bridge och Photo Supreme (dess Formatted Vocabulary File) använder samma filer, så nyckelordslistor kan flyttas mellan dem och", + "brings in something (Import N Photos, Merge, Save, Create, Download…). Delete and Remove stay plain, so a destructive": "tar in något (Importera N foton, Sammanfoga, Spara, Skapa, Hämta…). Radera och Ta bort förblir neutrala, så en destruktiv", + "browsers, for example) show it in HDR; **viewers that don't read `cICP` show the PQ values as if they were sRGB**,": "webbläsare, till exempel) visar den i HDR; **visningsprogram som inte läser `cICP` visar PQ-värdena som om de vore sRGB**,", + "Building from source": "Bygga från källkod", + "built-in profile: straight lines near the edges stay straight and the framing matches the camera's JPEG. It works": "inbyggd profil: raka linjer nära kanterna förblir raka och inramningen matchar kamerans JPEG. Det fungerar", + "burst by file name, so the first file is the cover.": "bildserien efter filnamn, så att den första filen blir omslaget.", + "buttons stay visible. Long lists in dialogs (What's New, All Metadata, Keyboard Shortcuts) get shorter to fit.": "knapparna förblir synliga. Långa listor i dialogrutor (Nyheter, Alla metadata, Kortkommandon) blir kortare för att få plats.", + "by double-clicking it, delete one with − after a confirmation. Right-click for more: create inside, Put New Keywords": "genom att dubbelklicka på den, radera en med − efter en bekräftelse. Högerklicka för mer: skapa inuti, Lägg nya nyckelord", + "C-RAWs imported earlier, Photo ▸ Reload from Disk picks up the raw data.": "C-RAW-filer som importerats tidigare får rådata när du väljer Foto → Läs in igen från disk.", + "Cached thumbnails are redrawn.": "Cachade miniatyrer ritas om.", + "Camera & Lens": "Kamera och objektiv", + "camera JPEG can't be fitted no longer open with the neutral fallback: they start from colour matrices fitted to the": "kamera-JPEG inte kan anpassas öppnas inte längre med den neutrala reservprofilen: de utgår från färgmatriser anpassade till", + "camera JPEG. Photos already imported pick the change up on Reload.": "kamera-JPEG:en. Foton som redan importerats får ändringen vid Läs in igen.", + "camera's embedded JPEG while a raw decodes, the previous render while an edit renders, or the magnified frame": "kamerans inbäddade JPEG medan en raw-fil avkodas, den föregående renderingen medan en redigering renderas, eller den förstorade bilden", + "camera's measured spectral sensitivities, from the Academy Software Foundation's rawtoaces-data. A camera profile": "kamerans uppmätta spektrala känslighet, från Academy Software Foundations rawtoaces-data. En kameraprofil", + "camera's own colour matrices, as Lightroom does, instead of shifting the colours of the as-shot rendering: a grey": "kamerans egna färgmatriser, som Lightroom gör, i stället för att förskjuta färgerna i Som tagen-renderingen: en grå", + "camera's own zoom to fill the frame) and vignetting, as with Panasonic and Sony files. The Optics profile controls": "kamerans egen zoom för att fylla bilden) och vinjettering, som med Panasonic- och Sony-filer. Profilkontrollerna under Optik", + "Camera-look deep shadows": "Djupa skuggor som i kameran", + "can be attached to a report without hunting for the settings folder (issue #260).": "kan bifogas till en rapport utan att du behöver leta efter inställningsmappen (ärende #260).", + "Can't be moved here": "Kan inte flyttas hit", + "can't be picked, such as one that would make an album include itself, are greyed with the reason. Esc with a dropdown or calendar open in a dialog": "kan inte väljas, till exempel ett som skulle få ett album att inkludera sig självt, är nedtonade med orsaken. Esc med en rullgardinsmeny eller kalender öppen i en dialogruta", + "Canon CR2 and Pentax PEF raws get the same starting look fitted to the camera's own JPEG as ARW, NEF, RW2, RAF": "Raw-filer i Canon CR2 och Pentax PEF får samma utgångsutseende anpassat till kamerans egen JPEG som ARW, NEF, RW2, RAF", + "Canon CR2 highlights": "Högdagrar i Canon CR2", + "Canon CR2 raws no longer open too dark with blocked-up shadows: the black level was measured over border columns": "Raw-filer i Canon CR2 öppnas inte längre för mörka med igensatta skuggor: svartnivån mättes över kantkolumner", + "Canon CR3 raws now develop from their sensor data: lossless RAW and C-RAW, checked sample for sample on the EOS": "Raw-filer i Canon CR3 framkallas nu från sina sensordata: förlustfri RAW och C-RAW, kontrollerade sampel för sampel på EOS", + "Canon CRW, Minolta MRW, Sigma X3F, Kodak KDC, Leaf MOS and Epson ERF files that LightCraft can't decode yet": "Canon CRW-, Minolta MRW-, Sigma X3F-, Kodak KDC-, Leaf MOS- och Epson ERF-filer som LightCraft inte kan avkoda ännu", + "Canon EOS R5 Mark II": "Canon EOS R5 Mark II", + "Canon EOS R7 C-RAW files develop from their sensor data too, instead of opening from their embedded JPEG. For R7": "C-RAW-filer från Canon EOS R7 framkallas också från sina sensordata, i stället för att öppnas från sin inbäddade JPEG. För R7", + "Canon PowerShot G9 raws open with the camera's white balance (White Balance ▸ As Shot); it used to start from a": "Raw-filer från Canon PowerShot G9 öppnas med kamerans vitbalans (Vitbalans → Som tagen); förut utgick de från en", + "carries Huffman tables made for its own picture instead of the standard example tables. Every viewer opens them": "har Huffman-tabeller gjorda för sin egen bild i stället för standardens exempeltabeller. Alla visningsprogram öppnar dem", + "carries the slide duration and fade, so a PDF viewer's presentation mode plays it as a slideshow, and \"Automatically": "innehåller visningstid per bild och toning, så att en PDF-läsares presentationsläge spelar upp den som ett bildspel, och \"Automatiskt", + "cells": "celler", + "cells overlap": "celler överlappar", + "Center": "Center", + "centre show nothing. More cameras will follow. Details: [focus-points.md](focus-points.md).": "mitten visar ingenting. Fler kameror kommer. Detaljer: [focus-points.md](focus-points.md).", + "centre, and can be turned off under Lens Corrections. Vignetting correction from the file comes later.": "mitten, och kan stängas av under Objektivkorrigeringar. Vinjetteringskorrigering från filen kommer senare.", + "change to an album, a stack or the keyword list, an album shown in its own order, Recently Added, Missing Photos,": "byte till ett album, en stapel eller nyckelordslistan, ett album som visas i sin egen ordning, Nyligen tillagda, Saknade foton,", + "changed doesn't put its faces on the new one (issue #1524).": "ändrats lägger inte sina ansikten på den nya (ärende #1524).", + "changing pixels along their edge. The hard edge now leaves pixels on the radius unchanged.": "ändrade pixlar längs kanten. Den hårda kanten lämnar nu pixlar på radien oförändrade.", + "Checking the GPU for faces": "Kontrollerar GPU:n för ansiktsigenkänning", + "Checking the GPU…": "Kontrollerar GPU:n…", + "Chinese (Simplified and Traditional), Japanese and Brazilian Portuguese.": "kinesiska (förenklad och traditionell), japanska och brasiliansk portugisiska.", + "choice is never the eye-catching default.": "val är aldrig det iögonfallande standardvalet.", + "choice next to that (Restore them / Import as new / Leave them) now starts on Restore. Files dropped on the window": "valet bredvid (Återställ dem / Importera som ny / Låt dem vara) börjar nu på Återställ. Filer som dras till fönstret", + "Choice values read as words in every language: \"Public Domain\", \"Picked\", \"Black & White\" rather than ids like": "Värden för val läses som ord på alla språk: \"Allmän egendom\", \"Vald\", \"Svartvitt\" i stället för id:n som", + "Choose Monitor Profile": "Välj bildskärmsprofil", + "choose what to do: import the new photos and relink the moved ones (the defaults), move the missing ones to Recently": "välja vad som ska göras: importera de nya fotona och länka om de flyttade (standardvalen), flytta de saknade till Nyligen", + "Choosing a date under By Date or a keyword under Keywords shows those photos from All Photos, as their counts": "Om du väljer ett datum under Efter datum eller ett nyckelord under Nyckelord visas de fotona från Alla foton, eftersom deras antal", + "Choosing a Lightroom Classic catalog folder in File → Open Library… (or one of its `Previews.lrdata` /": "Om du väljer en Lightroom Classic-katalogmapp i Arkiv → Öppna bibliotek… (eller en av dess `Previews.lrdata` /", + "choosing a profile file.": "att välja en profilfil.", + "chose) and ends on a page saying it was installed, with a \"Launch LightCraft\" box. It used to finish without a word,": "valde) och avslutas med en sida som säger att den installerades, med en ruta för \"Starta LightCraft\". Tidigare slutfördes den utan att säga något,", + "Classic (issue #956). With the second, each photo is exported into the folder its original is in, plus the": "Classic (ärende #956). Med det andra exporteras varje foto till mappen där originalet ligger, plus", + "Cleaner HDR merges": "Renare HDR-sammanfogningar", + "Clear Print Layout": "Rensa utskriftslayout", + "Click a cell to move, resize or arrange it": "Klicka på en cell för att flytta, ändra storlek på eller ordna den", + "Click to hide clipping warnings for shadows and highlights.": "Klicka för att dölja klippningsvarningar för skuggor och högdagrar.", + "Click to show clipping warnings for shadows and highlights.": "Klicka för att visa klippningsvarningar för skuggor och högdagrar.", "Blur Amount": "Oskärpemängd", "Boost": "Förstärkning", "In Focus": "I fokus", @@ -2447,6 +2708,669 @@ "Tip: select the subject precisely with an Object mask (Masking, M), then choose that mask here.": "Tips: markera motivet exakt med en Objekt-mask (Maskering, M) och välj sedan den masken här.", "Brush Refinement": "Penselförfining", "Focus": "Fokus", + "Focus point": "Fokuspunkt", + "Folder colour labels": "Färgetiketter för mappar", + "folder scans, exports (and the contact sheet PDF), Synchronize Folder, Build / Smart Previews, Lightroom catalog import, Photo Merge, model downloads, the face scan,": "mappgenomsökningar, exporter (och kontaktkartans PDF), Synkronisera mapp, Bygg / Smarta förhandsgranskningar, import av Lightroom-katalog, Fotosammanfogning, modellhämtningar, ansiktsgenomsökningen,", + "folder's `slideshow-templates` folder, shared by all your libraries.": "mappens `slideshow-templates`-mapp, som delas av alla dina bibliotek.", + "folder, fold that folder first (the bottom of an open folder means \"inside\"). Agents use `album.reorder`": "mapp, fäll ihop den mappen först (nederkanten av en öppen mapp betyder \"inuti\"). Agenter använder `album.reorder`", + "Folder…. The folder and the folders inside it are scanned in the background for photos added on disk, photos whose": "Mapp…. Mappen och mapparna i den genomsöks i bakgrunden efter foton som lagts till på disken, foton vars", + "follow.": "följa.", + "For scripts: a size set with `ui.resize` is remembered like any other, so a script that needs a size sets it.": "För skript: en storlek som ställs in med `ui.resize` sparas som alla andra, så ett skript som behöver en storlek ställer in den.", + "for\").": "för\").", + "Formats": "Format", + "formats. On an E-1 photo the starting render moved from ΔE00 11.3 to 8.3 against Lightroom's. Photos already": "format. På ett E-1-foto minskade startrenderingens avvikelse från Lightrooms från ΔE00 11,3 till 8,3. Foton som redan", + "forward); what was read is remembered for the session, so a full cache still lets go of what is not in use first.": "framåt); det som lästs sparas under sessionen, så en full cache släpper fortfarande först det som inte används.", + "from or written through such a link.": "från eller skrivs genom en sådan länk.", + "From the command line: `lightcraft-cli merge hdr-batch FOLDER`.": "Från kommandoraden: `lightcraft-cli merge hdr-batch FOLDER`.", + "from the grid onto a keyword get it.": "från rutnätet till ett nyckelord får det.", + "Fujifilm lens corrections": "Objektivkorrigeringar för Fujifilm", + "Fujifilm RAFs from 59 camera models now get the lens correction the camera stores in the file: distortion (with the": "Fujifilm RAF-filer från 59 kameramodeller får nu den objektivkorrigering som kameran lagrar i filen: distorsion (med", + "Full screen is not remembered (the app opens as a window), and neither is where on the desktop the window was:": "Helskärm sparas inte (appen öppnas som ett fönster), och inte heller var på skrivbordet fönstret låg:", + "full-range/matrix signalling is honoured (iPhone photos are full range), chroma is upsampled like libheif, grids": "signaleringen av fullt omfång/matris följs (iPhone-foton har fullt omfång), kroma uppsamplas som i libheif, rutnät", + "Full-resolution panoramas": "Panoramor i full upplösning", + "functions, and one Undo restores the entire drag.": "funktioner, och en enda Ångra återställer hela dragningen.", + "further ⇧-clicks carry on from the last point, as in Lightroom. Change the brush size, feather or flow before the": "ytterligare ⇧-klick fortsätter från den senaste punkten, som i Lightroom. Ändra penselstorlek, fjädring eller flöde före", + "give the offered keyword and keep the cursor in the box for the next one; Return alone still adds what you typed.": "ger det föreslagna nyckelordet och behåller textmarkören i rutan för nästa; bara Retur lägger fortfarande till det du skrev.", + "go by that can leave it out. It is safe to delete while LightCraft is closed, as before. A `thumbs` folder that": "går efter som kan utelämna den. Det går att radera den medan LightCraft är stängt, som tidigare. En `thumbs`-mapp som", + "Grid thumbnails and the first picture in the loupe of an unedited raw now come from the smallest JPEG the camera": "Miniatyrer i rutnätet och den första bilden i lupen för en oredigerad raw-fil kommer nu från den minsta JPEG som kameran", + "Grid: add the next photo to the selection": "Rutnät: lägg till nästa foto i markeringen", + "Grid: add the previous photo to the selection": "Rutnät: lägg till föregående foto i markeringen", + "Grid: first photo of the view": "Rutnät: vyns första foto", + "Grid: last photo of the view": "Rutnät: vyns sista foto", + "guides, at the screen's aspect or 16:9 / 4:3). Sizes are a share of the slide, so a slide looks the same on any": "stödlinjer, i skärmens bildförhållande eller 16:9 / 4:3). Storlekar är en andel av bilden, så en bild ser likadan ut på vilken", + "handle, and a program being started by another thread at that moment held a copy of the handle until it was fully": "handtag, och ett program som startades av en annan tråd i det ögonblicket höll en kopia av handtaget tills det var helt", + "Hard-edged Heal and Clone spots": "Retuscherings- och klonpunkter med hårda kanter", + "HDR and panorama merges of CR2 keep their colour": "HDR- och panoramasammanfogningar av CR2 behåller färgen", + "HDR merges keep the lens correction": "HDR-sammanfogningar behåller objektivkorrigeringen", + "HDR merges keep the white balance": "HDR-sammanfogningar behåller vitbalansen", + "HDR merges of moving lights, and many brackets at once": "HDR-sammanfogningar av rörliga ljus, och många exponeringsserier på en gång", + "HDR output": "HDR-utdata", + "HDR PNG export": "HDR-export till PNG", + "HEIC / HEIF photos (iPhone and Mac) open now: the optional `lightcraft-heif` crate (heic-rs, pure Rust) behind": "HEIC-/HEIF-foton (iPhone och Mac) kan nu öppnas: den valfria craten `lightcraft-heif` (heic-rs, ren Rust) bakom", + "HEIC colours now match libheif to within one code value (they were up to ~10 off): the HEVC stream's own": "HEIC-färger stämmer nu med libheif inom ett kodvärde (de avvek med upp till ~10): HEVC-strömmens egen", + "Help → Keyboard Shortcuts includes the number-key bindings. See [library shortcuts](library-shortcuts.md).": "Hjälp → Kortkommandon inkluderar bindningarna för siffertangenterna. Se [kortkommandon i biblioteket](library-shortcuts.md).", + "Help → Open Log Folder shows that log file in the file manager (Finder, Explorer, or the folder on Linux), so it": "Hjälp → Öppna loggmappen visar loggfilen i filhanteraren (Finder, Utforskaren eller mappen på Linux), så att den", + "Hide the sections you don't use: View ▸ Sidebar Sections, or right-click a header ▸ Hide This Section. Right-click": "Dölj de avsnitt du inte använder: Visa → Sidofältsavsnitt, eller högerklicka på en rubrik → Dölj det här avsnittet. Högerklicka", + "Hide this wheel's effect": "Dölj det här hjulets effekt", + "high-resolution cameras such as the Sony A7R VI (64 MP). Their decoded original (~800 MB) is bigger than the": "högupplösta kameror som Sony A7R VI (64 MP). Deras avkodade original (~800 MB) är större än", + "highlight recovery missed them and, darkened, they took a colour cast instead of going neutral grey.": "högdageråterställningen missade dem, och när de mörkades fick de ett färgstick i stället för att bli neutralt grå.", + "Highlights and Shadows (process 2)": "Högdagrar och skuggor (process 2)", + "Highlights and Shadows keep the fine detail of the tones they move (issue #632): pulling Highlights down on a bright": "Högdagrar och Skuggor behåller de fina detaljerna i de toner de flyttar (ärende #632): att dra ner Högdagrar på en ljus", + "hold (such as a name in brackets), which it leaves out so the file always reads back.": "rymma (som ett namn inom hakparenteser), vilket det utelämnar så att filen alltid kan läsas tillbaka.", + "Human Eye Tracking": "Ögonspårning för människor", + "ICC Profiles": "ICC-profiler", + "identity subissue in #840). The separate Make and Model tags keep their original values.": "delärendet om identitet i #840). De separata taggarna Make och Model behåller sina ursprungliga värden.", + "If LightCraft can't open a photo (its original is on a drive that isn't connected, or the file is damaged) but has": "Om LightCraft inte kan öppna ett foto (originalet ligger på en enhet som inte är ansluten, eller filen är skadad) men har", + "If the desktop app can't open its window (for example when no graphics device can be used), it now says so in a": "Om skrivbordsappen inte kan öppna sitt fönster (till exempel när ingen grafikenhet kan användas) säger den nu det i en", + "If you go back to an older version, it renders its thumbnails again as `.jpg`. This version then takes those": "Om du går tillbaka till en äldre version renderar den sina miniatyrer igen som `.jpg`. Den här versionen tar sedan de", + "image file such as a PNG logo with transparency, at a size and opacity, optionally drawn behind the photo), the": "bildfil, till exempel en PNG-logotyp med transparens, i en viss storlek och opacitet, eventuellt ritad bakom fotot), den", + "Image on Black": "Bild på svart", + "Image on White": "Bild på vitt", + "Import Lightroom Catalog… as buttons, and say that photos (and, in the desktop app, folders) can be dropped into": "Importera Lightroom-katalog… som knappar, och säger att foton (och, i skrivbordsappen, mappar) kan släppas i", + "Import Mask Effects": "Importera maskeffekter", + "import only the raws and leave the JPEGs beside them (issue #344).": "importera bara raw-filerna och lämna JPEG-filerna bredvid dem (ärende #344).", + "Import photos to get started": "Importera foton för att komma igång", + "import review checks such files, marks them \"Will be restored\" and counts them as \"in Recently Deleted\"; the": "importgranskningen kontrollerar sådana filer, markerar dem \"Kommer att återställas\" och räknar dem som \"i Nyligen raderade\"; den", + "Import Slideshow Template": "Importera bildspelsmall", + "Import when a card is connected": "Importera när ett kort ansluts", + "Imported `.cube` LUT profiles appear in the Profile menu and the profile browser, grouped by their folder, and stay": "Importerade `.cube`-LUT-profiler visas i profilmenyn och profilbläddraren, grupperade efter sin mapp, och förblir", + "imported from files (or read from sidecars) keep the hierarchy `lr:hierarchicalSubject` gives them.": "som importerats från filer (eller lästs från sidofiler) behåller den hierarki som `lr:hierarchicalSubject` ger dem.", + "imported pick it up when re-rendered.": "importerade får det när de renderas om.", + "Importing a deleted photo again": "Importera ett raderat foto igen", + "Importing a file whose photo is in Recently Deleted brings the photo back, with its edits, rating and albums": "Om du importerar en fil vars foto finns i Nyligen raderade kommer fotot tillbaka, med sina redigeringar, sitt betyg och sina album", + "Importing a large collection and opening its library no longer compare every preset with every other.": "När du importerar en stor samling och öppnar dess bibliotek jämförs inte längre varje förinställning med alla andra.", + "Importing a preset zip that unpacks to far more than any preset (a \"zip bomb\") is refused with a message naming": "Om du importerar en zip med förinställningar som packas upp till långt mer än någon förinställning (en \"zip-bomb\") vägras den med ett meddelande som anger", + "Importing XMP presets no longer lists bookkeeping fields (`Cluster`, `SortName`, `SupportsAmount2`, the as-shot": "När du importerar XMP-förinställningar listas inte längre interna fält (`Cluster`, `SortName`, `SupportsAmount2`, den som tagna", + "In a long section, the header stays at the top of the sidebar while you scroll through its rows, so you always see": "I ett långt avsnitt stannar rubriken överst i sidofältet medan du rullar genom dess rader, så att du alltid ser", + "In an album, the Delete key now takes the selected photos out of the album, as in Lightroom. It used to move them": "I ett album tar Delete-tangenten nu bort de markerade fotona ur albumet, som i Lightroom. Tidigare flyttade den dem", + "In dialogs, the confirm button is on the right with Cancel to its left, and filled with the accent when it makes or": "I dialogrutor sitter bekräftelseknappen till höger med Avbryt till vänster om den, och den fylls med accentfärgen när den skapar eller", + "in, instead of moving it back to Program Files (issue #399). If that folder has been deleted since, the upgrade": "i, i stället för att flytta tillbaka den till Program Files (ärende #399). Om den mappen har raderats sedan dess, ", + "Increase Flag Status": "Höj flaggstatus", + "Increase Grid Thumbnail Size": "Öka miniatyrstorlek i rutnätet", + "inference on a Mac through SSH. Saved masks still render and export offline.": "inferens på en Mac via SSH. Sparade masker renderas och exporteras fortfarande offline.", + "inside it; undo and redo carry them back and forth.": "inuti den; ångra och gör om flyttar dem fram och tillbaka.", + "inside Pictures, so every thumbnail (one for each photo, size and state of its edits) was listed as a photo.": "i Bilder, så varje miniatyr (en för varje foto, storlek och redigeringsläge) listades som ett foto.", + "inside the view. A plain mouse wheel over a zoomed photo pans it too.": "i vyn. Ett vanligt mushjul över ett inzoomat foto panorerar det också.", + "Inside This Keyword, Purge Unused Keywords.": "Inuti det här nyckelordet, Rensa oanvända nyckelord.", + "installs to Program Files.": "installeras i Program Files.", + "instead of opening as their embedded preview. Photos imported earlier switch over with Photo ▸ Reload from Disk.": "i stället för att öppnas som sin inbäddade förhandsgranskning. Foton som importerats tidigare byter över med Foto → Läs in igen från disk.", + "instead of quietly matching nothing or everything. New date rules start at the current year.": "i stället för att i tysthet matcha ingenting eller allt. Nya datumregler börjar vid aktuellt år.", + "into the display's own gamut; thumbnails and other previews are converted to it. Histograms, the preview caches": "till bildskärmens eget färgomfång; miniatyrer och andra förhandsgranskningar konverteras till det. Histogram, förhandsgranskningscacharna", + "iPhone ProRAW and other DNGs that carry their own segmentation mattes (DNG semantic masks) use them for the Select": "iPhone ProRAW och andra DNG-filer som har egna segmenteringsmasker (semantiska DNG-masker) använder dem för Markera", + "is a larger target that lights up on its own, and taking a keyword off several photos at once now says which": "är ett större mål som tänds av sig självt, och när du tar bort ett nyckelord från flera foton samtidigt står det nu vilka", + "is connected, the same review File → Import from Device opens. It's off by default. A card that's already in when": "ansluts, samma granskning som Arkiv → Importera från enhet öppnar. Den är av som standard. Ett kort som redan sitter i när", + "is missing (moved, drive unplugged) is not exported; it gets its own error naming it.": "saknas (flyttad, enheten urkopplad) exporteras inte; den får ett eget fel som anger den.", + "is touched. Agents use `folder.scanChanges` and `folder.synchronize`.": "rörs. Agenter använder `folder.scanChanges` och `folder.synchronize`.", + "It is not a denoise model LightCraft understands": "Det är inte en brusreduceringsmodell som LightCraft förstår", + "it slightly worse. The vignetting table is read but not applied: the camera's own JPEGs don't apply it either. This": "den något sämre. Vinjetteringstabellen läses men tillämpas inte: kamerans egna JPEG-filer tillämpar den inte heller. Detta", + "it. The list is there with no photo selected too, to set up keywords first.": "den. Listan finns också när inget foto är markerat, så att du kan ställa in nyckelord först.", + "its duration and the fades are rendered frame by frame (crossfades, or fades through the fade colour). The video has": "dess längd och toningarna renderas bildruta för bildruta (övertoningar, eller toningar via toningsfärgen). Videon har", + "its embedded JPEG or a thumbnail to show, the loupe now says so at the bottom of the photo (\"Original offline · no": "dess inbäddade JPEG eller en miniatyr att visa står det nu i lupen längst ned på fotot (\"Original offline · ingen", + "its real As Shot temperature once the file is opened (or Reload reads it).": "sin verkliga Som tagen-temperatur när filen öppnas (eller när Läs in igen läser den).", + "its text reads at 4.5:1 or more on its fill in every theme. Dialog buttons are 30 points tall, like the welcome's.": "dess text har en kontrast på 4,5:1 eller mer mot fyllningen i alla teman. Dialogknappar är 30 punkter höga, som välkomstfönstrets.", + "JPEG exports are 12–14 % smaller at the same quality, with exactly the same pixels (issue #1373): each file now": "JPEG-exporter är 12–14 % mindre med samma kvalitet, med exakt samma pixlar (ärende #1373): varje fil nu", + "JPEG get faster too.": "JPEG blir också snabbare.", + "JPEG XL compressed DNGs (DNG 1.7) now open: lossless tiles decode sample for sample (checked on synthetic files);": "JPEG XL-komprimerade DNG-filer (DNG 1.7) öppnas nu: förlustfria rutor avkodas sampel för sampel (kontrollerat på syntetiska filer);", + "JPEG XL export": "JPEG XL-export", + "Kelvin white balance for more Sony cameras": "Vitbalans i kelvin för fler Sony-kameror", + "Kelvin white balance for raws whose camera has colour matrices": "Vitbalans i kelvin för raw-filer vars kamera har färgmatriser", + "Keyword lists": "Nyckelordslistor", + "keyword only some of them have is marked with an asterisk (hover: how many). Only the × removes a keyword, from": "nyckelord som bara några av dem har markeras med en asterisk (hovra: hur många). Endast × tar bort ett nyckelord, från", + "Keyword Set ▸ Edit Set… edits a set's nine keywords in place, one field per ⌥ key, and renames it (or saves the edits as a new": "Nyckelordsuppsättning → Redigera uppsättning… redigerar en uppsättnings nio nyckelord på plats, ett fält per ⌥-tangent, och byter namn på den (eller sparar ändringarna som en ny", + "Keyword sets": "Nyckelordsuppsättningar", + "Keyword tag options decide what exported files carry: Include on Export, Export Containing Keywords, Export": "Alternativ för nyckelordstaggar avgör vad exporterade filer innehåller: Ta med vid export, Exportera överordnade nyckelord, Exportera", + "Keywording box": "Nyckelordsruta", + "Keywords has a + in its header, like Albums: Create Keyword Tag without opening the Keyword List.": "Nyckelord har ett + i rubriken, som Album: Skapa nyckelordstagg utan att öppna Nyckelordslista.", + "Keywords panel": "Panelen Nyckelord", + "keywords, dates, people and counts; a keyword leaves the folders, the dates and the counts as they are. With both": "nyckelord, datum, personer och antal; ett nyckelord lämnar mapparna, datumen och antalen som de är. Med båda", + "labels 6–9, P / U and the rest did nothing, because macOS only passes ⌘ / ⌃ combinations and function keys": "etiketter 6–9, P / U och resten gjorde ingenting, eftersom macOS bara skickar vidare ⌘- / ⌃-kombinationer och funktionstangenter", + "land in `ui.json` (where they replaced the saved settings), and the GPU crash sentinel no longer creates the": "hamnar i `ui.json` (där de ersatte de sparade inställningarna), och GPU-kraschvakten skapar inte längre", + "Languages": "Språk", + "Large libraries: Synchronize Folder, import and sidecars start sooner": "Stora bibliotek: Synkronisera mapp, import och sidecar-filer startar tidigare", + "Large preset collections": "Stora samlingar av förinställningar", + "launch. Reading a thumbnail writes nothing (but for one that went unused for a week, whose date is brought": "start. Att läsa en miniatyr skriver ingenting (utom för en som inte använts på en vecka, vars datum förs", + "launched, so reopening the library straight away could be refused with \"This library is already open in another": "startats, så att öppna biblioteket igen direkt kunde vägras med \"Det här biblioteket är redan öppet i ett annat", + "Layout Image Matte": "Matthet för layoutbild", + "Layout Image Opacity": "Opacitet för layoutbild", + "Layout image over the loupe": "Layoutbild över lupen", + "Leaf and Hasselblad raws": "Raw-filer från Leaf och Hasselblad", + "leaves a black hole where the middle photo had it clipped. With Deghost, the brightest photo's copy of it in a": "lämnar ett svart hål där mittenfotot hade det klippt. Med spökborttagning: det ljusaste fotots kopia av det i en", + "leaves out whatever Excluded Photos matches, as its rules change. The album picker shows your albums as in the sidebar": "utesluter det som Uteslutna foton matchar, i takt med att dess regler ändras. Albumväljaren visar dina album som i sidofältet", + "left out, so these photos come out a little smaller, closer to the camera's own JPEG. Crops and masks on photos": "utelämnas, så dessa foton blir lite mindre, närmare kamerans egen JPEG. Beskärningar och masker på foton", + "lens it doesn't have a name for. Newly imported photos show it.": "objektiv som den inte har något namn för. Nyimporterade foton visar det.", + "Lens names for Nikon DSLR raws": "Objektivnamn för raw-filer från Nikons DSLR-kameror", + "let go. On a 64 MP raw the first of those renders decoded the whole file again, which held up the loupe's": "släpps. På en 64 MP raw-fil avkodade den första av de renderingarna hela filen igen, vilket fördröjde lupens", + "Letter": "Letter", + "Library and views": "Bibliotek och vyer", + "Library keyboard culling": "Gallring med tangentbordet i biblioteket", + "library open now stays, and LightCraft says \"This is a Lightroom catalog, not a LightCraft library\" and offers": "biblioteket som är öppet förblir nu öppet, och LightCraft säger \"Det här är en Lightroom-katalog, inte ett LightCraft-bibliotek\" och erbjuder", + "Library sorting": "Sortering i biblioteket", + "light: Silver or Paper). New and existing installs stay dark; following the system is opt-in.": "ljust: Silver eller Papper). Nya och befintliga installationer förblir mörka; att följa systemet måste du välja själv.", + "LightCraft Effect Presets": "LightCraft-effektförinställningar", + "LightCraft program\" although nothing had it open. Nothing in the shipped app is known to hit the window today; it": "LightCraft-program\" fast inget hade det öppet. Inget i den levererade appen är känt för att träffa den tidsluckan i dag; den", + "LightCraft starts doesn't ask, and if a dialog is open or an import is running it waits until that's done.": "LightCraft startar frågar inte, och om en dialogruta är öppen eller en import pågår väntar den tills det är klart.", + "LightCraft the copy shows what you saved.": "LightCraft visar kopian det du sparade.", + "LightCraft was restarted. The bug is still written to the log (Help ▸ Open Log Folder) for a report.": "LightCraft startades om. Felet skrivs fortfarande till loggen (Hjälp → Öppna loggmappen) för en rapport.", + "LightCraft when it shows a stack, or hangs it when a folder is moved: on opening, records are put back under": "LightCraft när den visar en stapel, eller får den att hänga när en mapp flyttas: vid öppning läggs posterna tillbaka under", + "LightCraft's cached thumbnails no longer show up in Windows Photos / Gallery or other photo apps as pictures of": "LightCrafts cachade miniatyrer visas inte längre i Windows Foton / Galleri eller andra fotoappar som bilder av", + "LightCraft's window opens at the size it had when you last used it, and zoomed (macOS) / maximized if it was: it": "LightCrafts fönster öppnas i den storlek det hade när du senast använde det, och zoomat (macOS) / maximerat om det var det: det", + "LightCraft. Importing adds the keywords you don't have, in one undo step; a file it can't read says which line, or": "LightCraft. Importen lägger till de nyckelord du inte har, i ett enda ångra-steg; en fil den inte kan läsa anger vilken rad, eller", + "LightCraft: an enlargement stops at 512 megapixels, as in Lightroom, and one that needs more memory than the": "LightCraft: en förstoring stannar vid 512 megapixel, som i Lightroom, och en som behöver mer minne än", + "Lightroom Classic catalogs": "Lightroom Classic-kataloger", + "Lightroom Classic's Export PDF, Export JPEG and Export Video: the photos in view as their slides, with the layout,": "Lightroom Classics Exportera PDF, Exportera JPEG och Exportera video: fotona i vyn som bilder i bildspelet, med layouten,", + "Lightroom has no such view.": "Lightroom har ingen sådan vy.", + "Lightroom radial masks on the right side": "Lightrooms radiella masker på höger sida", + "Lightroom stays inverted, and older Radial Filters keep their Effect Outside / Invert Mask setting. Photos imported": "Lightroom förblir inverterad, och äldre radiella filter behåller sin inställning Effekt utanför / Invertera mask. Foton som importerats", + "Lightroom's `crs:Temperature` for these raws is read as the Kelvin it is (sidecars, Lightroom catalogs, presets);": "Lightrooms `crs:Temperature` för dessa raw-filer läses som de kelvin det är (sidecar-filer, Lightroom-kataloger, förinställningar);", + "like a photo that can't be opened, with the reason, instead of rendering forever; its thumbnail stops waiting too.": "som ett foto som inte kan öppnas, med orsaken, i stället för att renderas i all evighet; dess miniatyr slutar också vänta.", + "Like in Lightroom, judge noise reduction at 1:1: at small sizes the noise it removes is mostly averaged away.": "Precis som i Lightroom bör du bedöma brusreducering i 1:1: i små storlekar jämnas bruset den tar bort till största delen ut ändå.", + "like the HDR AVIF: the same brightness, with SDR white at 203 cd/m², and content light levels recorded.": "som HDR-AVIF-filen: samma ljusstyrka, med SDR-vitt på 203 cd/m², och innehållets ljusnivåer registrerade.", + "linked, or each on its own), Zoom to Fill Frame (crop the photo to fill its cell), a stroke border (colour, width),": "länkade, eller var för sig), Zooma för att fylla bildrutan (beskär fotot så att det fyller sin cell), en konturkant (färg, bredd),", + "listing itself took 4 to 5 s and is as it was.": "själva listningen tog 4 till 5 s och är som förut.", + "lit by the chosen white comes out grey and saturated colours move as the camera records them. The eyedropper and": "belyst av det valda vita blir grått och mättade färger flyttas så som kameran registrerar dem. Pipetten och", + "Local folders select a photo": "Lokala mappar markerar ett foto", + "Local photos aren't in the library yet: Add to My Photos first, then move them": "Lokala foton finns inte i biblioteket än: Lägg till i Mina foton först och flytta dem sedan", + "Lock On AF": "Lock On AF", + "Long-running tasks show in one place, top left under the top bar, as in Lightroom Classic (issue #345): imports and": "Långvariga uppgifter visas på ett ställe, uppe till vänster under det övre fältet, som i Lightroom Classic (ärende #345): importer och", + "longer frees it, which cost a re-upload of about a second on the next pan (800 MB for a 64 MP raw). It is freed": "frigör det längre, vilket kostade en ny uppladdning på ungefär en sekund vid nästa panorering (800 MB för en 64 MP raw-fil). Det frigörs", + "looks right everywhere, export a JPEG with HDR output on (an SDR image plus a gain map).": "ser rätt ut överallt, exportera en JPEG med HDR-utdata på (en SDR-bild plus en förstärkningskarta).", + "Lossy JPEG XL files in Display P3 or Rec. 2020 now open in their real colours; saturated colours used to come in": "Förlustbringande JPEG XL-filer i Display P3 eller Rec. 2020 öppnas nu i sina verkliga färger; mättade färger kom tidigare in", + "lossy tiles decode too, keeping the raw values above 1.0 instead of clipping them (checked on one real file). A tile that cannot be decoded makes the file open from its embedded": "förlustbringande rutor avkodas också, och raw-värdena över 1,0 behålls i stället för att klippas (kontrollerat på en verklig fil). En ruta som inte kan avkodas gör att filen öppnas från sin inbäddade", + "Loupe Info 1": "Lupinfo 1", + "Loupe Info 2": "Lupinfo 2", + "Loupe Overlay": "Lupöverlägg", + "Loupe View": "Lupvy", + "Luminance and colour noise reduction no longer look much stronger in grid thumbnails and the filmstrip than in": "Brusreducering av luminans och färg ser inte längre mycket starkare ut i rutnätsminiatyrer och filmremsan än i", + "M50, R100 and R8. CR3 files the decoder can't read yet still open from their embedded JPEG, as before.": "M50, R100 och R8. CR3-filer som avkodaren inte kan läsa än öppnas fortfarande från sin inbäddade JPEG, som tidigare.", + "M50, R100, R8 and RP (on the RP also in 1.6× crop mode). CR3 files the decoder can't read yet still open from their embedded JPEG, as before.": "M50, R100, R8 och RP (på RP även i beskärningsläget 1,6×). CR3-filer som avkodaren inte kan läsa än öppnas fortfarande från sin inbäddade JPEG, som tidigare.", + "macOS, Linux packages, AppImage, Flatpak), and says so if it isn't installed, before making a copy.": "macOS, Linux-paket, AppImage, Flatpak), och säger till om det inte är installerat, innan en kopia görs.", + "made a lock test flaky, and the fix closes the window for good.": "gjorde ett låstest instabilt, och korrigeringen stänger luckan för gott.", + "made from the old pixels: they are made again from the new file, and a scan still busy with the old file when it": "skapade från de gamla pixlarna: de skapas igen från den nya filen, och en skanning som fortfarande arbetar med den gamla filen när den", + "magnified preview isn't taken for the photo when checking focus at 1:1.": "förstorad förhandsgranskning tas inte för fotot när du kontrollerar skärpan i 1:1.", + "makes it inside that folder (`dialog.newAlbum`, `dialog.newFolder`, `dialog.smartAlbum`, `dialog.newSmartAlbum` take `parent`).": "skapar den i den mappen (`dialog.newAlbum`, `dialog.newFolder`, `dialog.smartAlbum`, `dialog.newSmartAlbum` tar `parent`).", + "Manage Effect Presets…": "Hantera effektförinställningar…", + "Managed by Printer (Adobe RGB)": "Hanteras av skrivaren (Adobe RGB)", + "Managed by Printer (sRGB)": "Hanteras av skrivaren (sRGB)", + "many Photos added, or why it added none. Export with Previous and export presets repeat it.": "många foton som lades till, eller varför inga lades till. Exportera med föregående och exportförinställningar upprepar det.", + "map); the option is per photo, so presets and Copy Settings carry it.": "karta); alternativet gäller per foto, så förinställningar och Kopiera inställningar för det med sig.", + "Mask Effect Presets": "Maskeffektförinställningar", + "means no (it used to count as yes), and a value that is neither yes nor no is refused.": "betyder nej (det räknades tidigare som ja), och ett värde som varken är ja eller nej vägras.", + "memory than the computer has, the panorama is made as large as fits (five 51 MP photos: up to 166 MP with": "minne än datorn har görs panoramat så stort som ryms (fem foton på 51 MP: upp till 166 MP med", + "menu, and Return in the painter's box starts painting.": "menyn, och Return i målningsrutan startar målningen.", + "merges used to open at about 7000 K / +115 where the photos show 4000–5300 K / +8. HDRs merged before this keep": "sammanfogningar öppnades tidigare vid ungefär 7000 K / +115 där fotona visar 4000–5300 K / +8. HDR-bilder som sammanfogats före detta behåller", + "Merging uses about a quarter less memory: three 67 MP raws need 3.8 GB instead of 4.8 GB.": "Sammanfogning använder ungefär en fjärdedel mindre minne: tre raw-filer på 67 MP kräver 3,8 GB i stället för 4,8 GB.", + "message box that names the log file, instead of quitting without a trace (issue #260).": "en meddelanderuta som anger loggfilen, i stället för att avsluta utan att lämna något spår (ärende #260).", + "missing ones.": "saknade.", + "missing. And a share that drops after the scan has listed a folder no longer turns that folder's photos into": "saknas. Och en nätverksresurs som försvinner efter att genomsökningen har listat en mapp gör inte längre den mappens foton till", + "Models are installed separately after accepting their terms; no weights are bundled. See [setup and limitations](denoise.md).": "Modellerna installeras separat efter att du har godkänt deras villkor; inga vikter medföljer. Se [installation och begränsningar](denoise.md).", + "models in a `LightCraftData` folder beside it instead of the per-user settings folder (issue #1200), as": "modeller i en `LightCraftData`-mapp bredvid den i stället för i inställningsmappen per användare (ärende #1200), som", + "Monitor profiles": "Bildskärmsprofiler", + "More Canon EOS R6 Mark II C-RAW files decode": "Fler C-RAW-filer från Canon EOS R6 Mark II avkodas", + "Move Mask Effect to Group": "Flytta maskeffekt till grupp", + "Move Photos": "Flytta foton", + "Move Print Cell": "Flytta utskriftscell", + "Move Print Cell to Page": "Flytta utskriftscell till sida", + "moved from ΔE00 7.6 to 5.2 against Lightroom's.": "flyttades från ΔE00 7,6 till 5,2 jämfört med Lightrooms.", + "Multi": "Flera", + "My Preset": "Min förinställning", + "name (`catalog.snap.tmp`, `model.onnx.part`): the link is removed and a new file made in its place, so the file it": "namn (`catalog.snap.tmp`, `model.onnx.part`): länken tas bort och en ny fil skapas i dess ställe, så filen den", + "name. Whole names, one chip per keyword, stays the default.": "namn. Hela namn, en bricka per nyckelord, är fortfarande standard.", + "names.": "namn.", + "neutral default.": "neutralt standardvärde.", + "never restore anything. Agents: `library.import` → `onDeleted` defaults to `restore` (`skip` keeps the old": "återställer aldrig något. Agenter: `library.import` → `onDeleted` har `restore` som standard (`skip` behåller det gamla", + "New fields: Keyword Count (\"2 or more\", \"exactly 2\"…), People and People Count (named faces), Shutter Speed (written": "Nya fält: Antal nyckelord (\"2 eller fler\", \"exakt 2\"…), Personer och Antal personer (namngivna ansikten), Slutartid (skrivs", + "new photos (and Reset) get it, photos you already edited keep their look until you choose Photo ▸ Update to Current": "nya foton (och Återställ) får den, foton du redan har redigerat behåller sitt utseende tills du väljer Foto → Uppdatera till aktuell", + "New Print Page": "Ny utskriftssida", + "Next History Step": "Nästa historiksteg", + "Next Slide": "Nästa bild", + "next to it while you rotate (issue #534). For an exact angle, type it in the new Angle field under Straighten and press Return": "bredvid den medan du roterar (ärende #534). För en exakt vinkel skriver du den i det nya fältet Vinkel under Räta upp och trycker på Return", + "Nikon D600, D610 and D5000": "Nikon D600, D610 och D5000", + "Nikon D850, Canon EOS 5D Mark III and others) now show white balance in Kelvin, as a DNG does and as Lightroom": "Nikon D850, Canon EOS 5D Mark III med flera) visar nu vitbalansen i kelvin, som en DNG gör och som Lightroom", + "Nikon lens corrections": "Objektivkorrigeringar för Nikon", + "Nikon raws without coloured edge bars": "Nikon-raw-filer utan färgade kantränder", + "Nikon Z 6II, Z 8 and D5300 colour profiles": "Färgprofiler för Nikon Z 6II, Z 8 och D5300", + "No clipping detected in this preview.": "Ingen klippning upptäcktes i den här förhandsgranskningen.", + "No faces by that name": "Inga ansikten med det namnet", + "no longer saves it). Return in those dialogs now confirms them, and their name opens selected. More fields will": "sparar den inte längre). Return i de dialogrutorna bekräftar dem nu, och deras namn öppnas markerat. Fler fält kommer", + "No named people yet. Name the faces below to start.": "Inga namngivna personer än. Namnge ansiktena nedan för att börja.", + "No people yet": "Inga personer än", + "No person by that name": "Ingen person med det namnet", + "no sound yet. It is AV1 rather than Lightroom's H.264, which has no open encoder we can ship; current browsers,": "inget ljud än. Det är AV1 i stället för Lightrooms H.264, som saknar en öppen kodare vi kan leverera; aktuella webbläsare,", + "No unnamed faces. Faces found in your photos appear here until you name them.": "Inga namnlösa ansikten. Ansikten som hittas i dina foton visas här tills du namnger dem.", + "Noise reduction looks the same at every size": "Brusreduceringen ser likadan ut i alla storlekar", + "Not loaded yet": "Inte inläst än", + "note saying what is missing. Agents use `slideshow.templates.*`, and `slideshow.preview {template}` renders a template": "anteckning som anger vad som saknas. Agenter använder `slideshow.templates.*`, och `slideshow.preview {template}` renderar en mall", + "Nothing already edited changes: a Custom white balance set on the old relative scale renders pixel for pixel as": "Inget som redan redigerats ändras: en anpassad vitbalans som ställts in på den gamla relativa skalan renderas pixel för pixel som", + "Nothing else changes: the same files are found new, already there, moved or missing, and sidecars get the same": "Inget annat ändras: samma filer hittas som nya, redan befintliga, flyttade eller saknade, och sidecar-filer får samma", + "noticeably duller.": "märkbart mattare.", + "now import as \"preview only\" with their embedded JPEG instead of failing. A raw whose data is damaged but whose": "importeras nu som \"endast förhandsgranskning\" med sin inbäddade JPEG i stället för att misslyckas. En raw-fil vars data är skadade men vars", + "now measured on the masked columns alone (8 corpus bodies, EOS 40D to 5DS R). On a 6D photo the starting render": "mäts nu enbart på de maskerade kolumnerna (8 kamerahus i korpusen, EOS 40D till 5DS R). På ett foto från 6D blir startrenderingen", + "now stays, like its preview, until another photo or view is shown.": "stannar nu kvar, liksom dess förhandsgranskning, tills ett annat foto eller en annan vy visas.", + "of a portrait photo): masked sensor columns were being developed as part of the picture (issues #976, #914). The": "av ett stående foto): maskerade sensorkolumner framkallades som en del av bilden (ärenden #976, #914). Den", + "of a portrait photo): masked sensor columns were being developed as part of the picture (issues #976, #914,": "av ett stående foto): maskerade sensorkolumner framkallades som en del av bilden (ärenden #976, #914,", + "of quietly rendering everything on the CPU, much more slowly. Help ▸ System Info says why. On NixOS this happens": "i stället för att i tysthet rendera allt på CPU:n, mycket långsammare. Hjälp → Systeminfo anger varför. På NixOS händer detta", + "Off by default (HEVC patents are the distributor's call, same as PhotoCraft); official builds pass `--features heif`.": "Av som standard (HEVC-patent är distributörens sak, precis som i PhotoCraft); officiella byggen skickar `--features heif`.", + "Older raw cameras": "Äldre raw-kameror", + "older versions refuse it, as with every format change.": "äldre versioner vägrar öppna det, som vid varje formatändring.", + "Olympus E-10 raws open with the camera's white balance (White Balance ▸ As Shot) and without the grey haze in": "Raw-filer från Olympus E-10 öppnas med kamerans vitbalans (Vitbalans → Som tagen) och utan det grå diset i", + "Olympus ORF raws get the starting look fitted to the camera's own JPEG too, instead of opening flat and grey (the": "Även ORF-raw-filer från Olympus får startutseendet anpassat efter kamerans egen JPEG, i stället för att öppnas platta och grå (de", + "On a person's page, the ↑ control on a suggested face confirms it and all shown suggestions with equal or higher": "På en persons sida bekräftar ↑-kontrollen på ett föreslaget ansikte det och alla visade förslag med lika hög eller högre", + "On Linux and FreeBSD, file dialogs (Import Photos…, Open Library, Export, presets, keyword lists…) are children of": "På Linux och FreeBSD är fildialogrutor (Importera foton…, Öppna bibliotek, Exportera, förinställningar, nyckelordslistor…) underordnade", + "On macOS the system does not tell LightCraft when a window is zoomed from the Window menu or resized after a": "På macOS meddelar systemet inte LightCraft när ett fönster zoomas från Fönster-menyn eller storleksändras efter en", + "On macOS, photos are shown through the profile of the screen the window is on while no monitor profile is chosen in": "På macOS visas foton genom profilen för skärmen som fönstret ligger på så länge ingen bildskärmsprofil har valts i", + "On macOS, ratings `0–5`, labels `6–9` and pick/unflag `P/U` now reach the app even when shown in the native menu (issue #283; adapted from PR #261).": "På macOS når betyg `0–5`, etiketter `6–9` och vald/ta bort flagga `P/U` nu appen även när de visas i den inbyggda menyn (ärende #283; anpassat från PR #261).", + "On macOS, single-key shortcuts that appear in the menu bar now work: E, C, H, M, ⇧P, I, K, D, ratings 0–5,": "På macOS fungerar nu kortkommandon med en tangent som visas i menyraden: E, C, H, M, ⇧P, I, K, D, betyg 0–5,", + "on the CPU and explains how to turn the GPU back on.": "på CPU:n och förklarar hur du slår på GPU:n igen.", + "on the CPU, are not waited for).": "på CPU:n, väntas inte in).", + "on the DLL search path without its `dxil.dll` (issue #471): DirectX 12 shaders now always compile with the": "i DLL-sökvägen utan sin `dxil.dll` (ärende #471): DirectX 12-shaders kompileras nu alltid med", + "on the top bar it comes back zoomed. The other way round, a window you drag out until it is as wide as the": "i det övre fältet kommer det tillbaka zoomat. Omvänt blir ett fönster som du drar ut tills det är lika brett som", + "On Windows and Linux, Ctrl+C outside a text field copies edit settings and Ctrl+V pastes them (⇧Ctrl+V: Paste": "På Windows och Linux kopierar Ctrl+C utanför ett textfält redigeringsinställningar och Ctrl+V klistrar in dem (⇧Ctrl+V: Klistra in", + "on; ✕ stops the tasks that can stop. Three rows show, then \"+N more\". The separate export panel and the progress": "pågår; × stoppar de uppgifter som kan stoppas. Tre rader visas, sedan \"+N till\". Den separata exportpanelen och förloppet", + "once you zoom out or move on.": "när du zoomar ut eller går vidare.", + "One kind of button": "En sorts knapp", + "One photo fills each page inside the margins.": "Ett foto fyller varje sida innanför marginalerna.", + "one that overflows.": "den som flödar över.", + "only convert between the camera's multipliers and Kelvin; the colour look is what it was.": "konverterar bara mellan kamerans multiplikatorer och kelvin; färgutseendet är detsamma som förut.", + "only the header and the preview are read, as for other raws.": "läses bara filhuvudet och förhandsgranskningen, som för andra raw-filer.", + "open and hasn't written back yet) imports instead of failing with \"unsupported SQLite schema format\".": "öppen och inte har skrivit tillbaka än) importeras i stället för att misslyckas med \"unsupported SQLite schema format\".", + "Open Library knows a Lightroom catalog": "Öppna bibliotek känner igen en Lightroom-katalog", + "Open Original in Other Editor (RAW, no copy)": "Öppna original i annat redigeringsprogram (RAW, ingen kopia)", + "opened a library, older versions refuse it, as with every format change.": "öppnat ett bibliotek vägrar äldre versioner öppna det, som vid varje formatändring.", + "Opening a library no longer rewrites the date of every thumbnail it shows, which made them all look new at each": "Att öppna ett bibliotek skriver inte längre om datumet för varje miniatyr det visar, vilket fick alla att se nya ut vid varje", + "Opening Synchronize Folder, an import review or an import no longer makes a table of every photo in the library": "Att öppna Synkronisera mapp, en importgranskning eller en import skapar inte längre en tabell över varje foto i biblioteket", + "Optics, Geometry and Calibration (issue #316).": "Optik, Geometri och Kalibrering (ärende #316).", + "Optional remote SAM 3: keep the native editor local and run Object, Describe, and detail": "Valfri fjärr-SAM 3: behåll den inbyggda redigeraren lokalt och kör Objekt, Beskriv och detalj", + "or drop photos and folders into this window": "eller släpp foton och mappar i det här fönstret", + "or drop photos into this window": "eller släpp foton i det här fönstret", + "or the edge of another folder, to place it before or after it: that folder is then ordered by hand. Right-click ▸": "eller kanten på en annan mapp för att placera den före eller efter den: den mappen ordnas då manuellt. Högerklicka →", + "or unchecks a range of photos (issue #338).": "eller bockar ur ett intervall av foton (ärende #338).", + "original again to find the haze colour. On a 64 MP raw (Sony A7R VI) that took ~0.2 s of CPU per pan and per": "originalet igen för att hitta disets färg. På en raw-fil på 64 MP (Sony A7R VI) tog det ~0,2 s CPU-tid per panorering och per", + "other file-naming tokens, with a size, colour, opacity and an optional soft shadow (opacity, offset, radius, angle).": "andra filnamnstoken, med storlek, färg, opacitet och en valfri mjuk slagskugga (opacitet, förskjutning, radie, vinkel).", + "out green and dark.": "ut gröna och mörka.", + "out, a folder that went read-only) used to be written only to the library, with a line in the log, so the sidecar": "ut, en mapp som blev skrivskyddad) skrevs tidigare bara till biblioteket, med en rad i loggen, så att sidecar-filen", + "out. Clear Recent Libraries empties the list.": "ut. Rensa senaste bibliotek tömmer listan.", + "Outside the crop box, where dragging rotates the photo, the pointer is a curved double arrow, and the angle is shown": "Utanför beskärningsramen, där dragning roterar fotot, är pekaren en krökt dubbelpil, och vinkeln visas", + "over one by one as they are used; the rest stay until the cache makes room.": "över en i taget när de används; resten ligger kvar tills cachen gör plats.", + "overlays and the intro and ending screens, in view order.": "överlägg och intro- och slutskärmarna, i visningsordning.", + "owns every shared sidecar name in the library: 2.4 s a write in that library, now under 1 s.": "äger varje delat sidecar-namn i biblioteket: 2,4 s per skrivning i det biblioteket, nu under 1 s.", + "Page": "Sida", + "Page Options": "Sidalternativ", + "Panasonic and Leica raws (RW2, RWL) are now corrected for lens distortion the way the camera corrects its own JPEG": "Raw-filer från Panasonic och Leica (RW2, RWL) korrigeras nu för objektivdistorsion på samma sätt som kameran korrigerar sin egen JPEG", + "panel. Each is switched on on its own and has a background colour and, centred on it, your identity plate (the one": "panelen. Var och en slås på för sig och har en bakgrundsfärg och, centrerad på den, din namnskylt (den", + "panels closed, from 71 ms).": "paneler stängda, från 71 ms).", + "Panning a photo zoomed to 1:1, or moving a slider while zoomed, no longer decodes the whole raw again each time on": "Att panorera ett foto zoomat till 1:1, eller att flytta ett skjutreglage medan det är zoomat, avkodar inte längre hela raw-filen igen varje gång på", + "Panorama and HDR Panorama merges keep the resolution of their photos instead of stopping at 40 megapixels": "Panorama- och HDR-panoramasammanfogningar behåller sina fotons upplösning i stället för att stanna vid 40 megapixel", + "pass, a new order each time round), repeat (off: the slideshow ends after the last photo) and preparing previews in": "genomgång, en ny ordning varje varv), upprepa (av: bildspelet slutar efter det sista fotot) och förberedelse av förhandsgranskningar i", + "past that a write is skipped (the image stays in memory and is written by a later render), so a slow disk can't": "efter det hoppas en skrivning över (bilden stannar i minnet och skrivs av en senare rendering), så att en långsam disk inte kan", + "Pause / Resume Slideshow": "Pausa/återuppta bildspel", + "Pentax raws without black borders": "Pentax-raw-filer utan svarta kanter", + "Photo Above": "Foto ovanför", + "Photo Below": "Foto nedanför", + "Photo Grid marked nothing, and Detail, the histogram and the photo info showed a photo that isn't in the folder.": "Fotorutnät markerade ingenting, och Detalj, histogrammet och fotoinformationen visade ett foto som inte finns i mappen.", + "photo has yet too. Filter it, tick a keyword to give it to the selected photos (a dash: only some have it), or click": "fotot har ännu också. Filtrera, bocka för ett nyckelord för att ge det till de markerade fotona (ett streck: bara vissa har det), eller klicka", + "Photo Merge of Canon CR2 (and other raws whose colour LightCraft fits from the camera's own JPEG, such as NEF and": "Fotosammanfogning av Canon CR2 (och andra raw-filer vars färg LightCraft anpassar efter kamerans egen JPEG, till exempel NEF och", + "photo's rating as stars, and any number of text overlays (up to 16) built from tokens: `{caption}`, `{title}`,": "fotots betyg som stjärnor, och valfritt antal textöverlägg (upp till 16) byggda av token: `{caption}`, `{title}`,", + "photo: only the photos the edit touched are asked about again and put at their place in the order. In a library of": "foto: bara de foton som redigeringen berörde tillfrågas igen och placeras på sin plats i ordningen. I ett bibliotek med", + "PhotoCraft does. If that folder can't be written, the usual folder is used and the log says why.": "PhotoCraft gör. Om den mappen inte går att skriva till används den vanliga mappen och loggen anger varför.", + "photos along the areas they clipped: right next to a clipped area, a photo's colour isn't used. It showed most when": "foton längs områdena de klippte: precis intill ett klippt område används inte ett fotos färg. Det syntes mest när", + "Photos deleted (or moved) by another app no longer stay in a Local folder, failing to load and logging an error": "Foton som raderats (eller flyttats) av en annan app ligger inte längre kvar i en lokal mapp, där de inte gick att läsa in och loggade ett fel", + "Photos edited in HDR: JPEG with an HDR gain map (looks right everywhere, brighter highlights on HDR displays), AVIF as 10-bit, PNG and JPEG XL as 16-bit Rec. 2020 PQ; TIFF needs 32-bit float": "Foton redigerade i HDR: JPEG med en HDR-förstärkningskarta (ser rätt ut överallt, ljusare högdagrar på HDR-skärmar), AVIF som 10-bitars, PNG och JPEG XL som 16-bitars Rec. 2020 PQ; TIFF kräver 32-bitars flyttal", + "Photos from Nikon DSLRs like the D700, D750, D80 or D5300 now show which lens they were taken with, for example": "Foton från Nikons systemkameror som D700, D750, D80 eller D5300 visar nu vilket objektiv de togs med, till exempel", + "Photos that start matching still appear at once, and deleting a photo or taking it out of the album or folder": "Foton som börjar matcha visas fortfarande direkt, och om du raderar ett foto eller tar ut det ur albumet eller mappen", + "Photos that tie on the sort key (equal ratings, one import batch, a burst shot within the same second) now sort by": "Foton som har samma sorteringsnyckel (lika betyg, samma importbatch, en bildserie inom samma sekund) sorteras nu efter", + "Photos with deep shadows no longer have to extend the first measured tone in a straight line to black.": "Foton med djupa skuggor behöver inte längre förlänga den första uppmätta tonen i en rak linje till svart.", + "Photos you import show up here. Nothing is copied or moved unless you choose to.": "Foton som du importerar visas här. Ingenting kopieras eller flyttas om du inte väljer det.", + "pile up threads and memory.": "samla på sig trådar och minne.", + "pointed to is never changed (issue #1502).": "som den pekar på ändras aldrig (ärende #1502).", + "Portable mode": "Portabelt läge", + "preset pickers in Import and Settings ▸ Import scroll the same way.": "förinställningsväljarna i Import och Inställningar → Import rullar på samma sätt.", + "presets.json) stays responsive. Every command used to re-serialize the whole list to see whether it had changed": "presets.json) fortsätter att svara snabbt. Varje kommando brukade serialisera om hela listan för att se om den hade ändrats", + "press the new keys (Esc cancels), × removes it, ↺ restores the original, Reset All undoes every change. A key that": "tryck på de nya tangenterna (Esc avbryter), × tar bort det, ↺ återställer originalet, Återställ alla ångrar alla ändringar. En tangent som", + "preview is intact does the same.": "förhandsgranskningen är intakt gör samma sak.", + "Preview or Photos. Moving the window to another screen is followed; **Use Screen Profile** goes back to it after": "Preview eller Photos. När fönstret flyttas till en annan skärm följer profilen med; **Använd skärmprofil** går tillbaka till den efter", + "preview, with the reason, instead of showing a black tile. A JPEG XL preview stored in the DNG is used like an": "förhandsgranskning, med orsaken, i stället för att visa en svart ruta. En JPEG XL-förhandsgranskning som lagras i DNG-filen används som en", + "previews for up to a second.": "förhandsgranskningar i upp till en sekund.", + "Previews match exports on Mac screens": "Förhandsgranskningar matchar exporter på Mac-skärmar", + "Previous History Step": "Föregående historiksteg", + "Previous Slide": "Föregående bild", + "Print Settings": "Utskriftsinställningar", + "Print Templates": "Utskriftsmallar", + "Print to PDF": "Skriv ut till PDF", + "Process. See [process versions](process-versions.md).": "Process. Se [processversioner](process-versions.md).", + "profile overrides for memory-constrained builders (issue #1196), including why packaging": "profilåsidosättningar för byggare med begränsat minne (ärende #1196), inklusive varför paketering", + "projected, so it needs less memory than before at any size (an 81 MP stitch: 4.4 GB instead of 6.2 GB).": "projiceras, så den behöver mindre minne än tidigare i alla storlekar (en sammanfogning på 81 MP: 4,4 GB i stället för 6,2 GB).", + "promise, instead of filtering whatever album or folder was open, which often showed nothing (issue #341).": "lovar, i stället för att filtrera det album eller den mapp som var öppen, vilket ofta inte visade något (ärende #341).", + "ProRAW the way the iPhone renders it, turn on Profile ▸ Camera local tone mapping (shown for photos that carry the": "ProRAW så som iPhone renderar det aktiverar du Profil → Kamerans lokala tonmappning (visas för foton som har", + "Quitting while a task that can be stopped is running asks first (\"Quit Anyway\" stops it).": "Om du avslutar medan en uppgift som kan stoppas körs får du en fråga först (\"Avsluta ändå\" stoppar den).", + "Radial masks brought over from Lightroom Classic (catalog import, XMP sidecars, edits inside DNGs and presets) now": "Radiella masker som förts över från Lightroom Classic (katalogimport, XMP-sidofiler, redigeringar i DNG-filer och förinställningar) nu", + "ran beside it.": "kördes bredvid den.", + "Ratings, flags, labels, keywords, collections/sets, virtual copies and supported edits migrate;": "Betyg, flaggor, etiketter, nyckelord, samlingar/uppsättningar, virtuella kopior och redigeringar som stöds migreras;", + "Raw files whose raw data sits in a private block of a TIFF (Phase One / Leaf IIQ, Canon EOS-1D / 1Ds and Kodak DCS": "Raw-filer vars rådata ligger i ett privat block i en TIFF (Phase One / Leaf IIQ, Canon EOS-1D / 1Ds och Kodak DCS", + "raw whose tile claims far more samples than it holds, and an ARW6 with a broken tile are refused first. All 74": "raw-fil vars ruta påstår sig innehålla långt fler sampel än den har, och en ARW6 med en trasig ruta avvisas först. Alla 74", + "Raws from 52 camera models (22 Canon, 11 Nikon, 11 Sony, 3 Fujifilm and 5 others, plus their other names) whose": "Raw-filer från 52 kameramodeller (22 Canon, 11 Nikon, 11 Sony, 3 Fujifilm och 5 andra, plus deras andra namn) vars", + "Raws from cameras that correct their own JPEG for lens distortion (Panasonic and Fujifilm with that setting on, the": "Raw-filer från kameror som korrigerar sin egen JPEG för objektivdistorsion (Panasonic och Fujifilm med den inställningen på,", + "Raws from older Nikon bodies no longer show a thin coloured or dark bar along one edge (the right edge, or the top": "Raw-filer från äldre Nikon-hus visar inte längre en tunn färgad eller mörk rand längs en kant (högerkanten, eller överkanten", + "Raws from the 52 camera models whose colour matrices LightCraft has measured (Sony ILCE-7M3, ILCE-7M4, ILCE-7RM3,": "Raw-filer från de 52 kameramodeller vars färgmatriser LightCraft har mätt upp (Sony ILCE-7M3, ILCE-7M4, ILCE-7RM3,", + "Raws from the Nikon D600, D610 and D5000 no longer show a bright line down the right edge (issue #1627). Their": "Raw-filer från Nikon D600, D610 och D5000 visar inte längre en ljus linje längs högerkanten (ärende #1627). Deras", + "Raws from the Nikon Z 6II, Z 8 and D5300 now start from a colour profile built from a few hundred photos from each camera, the same way the": "Raw-filer från Nikon Z 6II, Z 8 och D5300 utgår nu från en färgprofil som byggts av några hundra foton från varje kamera, på samma sätt som", + "Raws from the Nikon Z 6II, Z 8 and Z f now open with the camera's own distortion correction, as Lightroom applies a": "Raw-filer från Nikon Z 6II, Z 8 och Z f öppnas nu med kamerans egen distorsionskorrigering, så som Lightroom tillämpar en", + "Raws from the Pentax KP, KF, K-3 Mark III (and Monochrome), K-70, K-1, K-1 Mark II, K-S1, K-S2 and 645Z no longer": "Raw-filer från Pentax KP, KF, K-3 Mark III (och Monochrome), K-70, K-1, K-1 Mark II, K-S1, K-S2 och 645Z visar inte längre", + "raws of other cameras keep the as-shot shift of issue #510. The two Kelvin scales come from different matrices and": "raw-filer från andra kameror behåller förskjutningen av Som tagen från ärende #510. De två Kelvinskalorna kommer från olika matriser och", + "Raws whose preview is in Adobe RGB (Sony α1 among others) no longer read the whole file for their grid thumbnail:": "Raw-filer vars förhandsgranskning är i Adobe RGB (bland annat Sony α1) läser inte längre hela filen för sin miniatyr i rutnätet:", + "Read Focus Points": "Läs fokuspunkter", + "Read Focus Points in the Background": "Läs fokuspunkter i bakgrunden", + "read from the white-balance presets the camera stores in every ARW: a photo shot at 3400 K on the camera reads": "läses från de vitbalansförinställningar som kameran lagrar i varje ARW: ett foto som tagits med 3400 K på kameran visar", + "Reading focus points": "Läser fokuspunkter", + "Recently Deleted is listed with All Photos, Recently Added and Picks under My Photos.": "Nyligen raderade visas tillsammans med Alla foton, Nyligen tillagda och Valda under Mina foton.", + "Recheck Preview-Only Raws": "Kontrollera raw-filer med bara förhandsgranskning igen", + "recipes can override inherited settings. Default release profiles and application behavior": "recept kan åsidosätta ärvda inställningar. Standardprofiler för releaser och programmets beteende", + "Recognition": "Igenkänning", + "relinked to the file it is imported from. Browsing a folder in Local, Auto Import and a Lightroom catalog import": "omlänkat till filen som det importeras från. När du bläddrar i en mapp i Lokalt, Automatisk import och en import av Lightroom-katalog", + "remembered.": "sparas.", + "Rename Mask Effect": "Byt namn på maskeffekt", + "Rename Mask Effect Group": "Byt namn på maskeffektgrupp", + "Rename Person": "Byt namn på person", + "Rename Slideshow Template": "Byt namn på bildspelsmall", + "render with Clarity, Dehaze, Texture or Highlights / Shadows on: their blurs are held to the picture's size.": "renderas med Klarhet, Ta bort dis, Textur eller Högdagrar / Skuggor på: deras oskärpa begränsas till bildens storlek.", + "renders a screen as a PNG.": "renderar en skärm som PNG.", + "replaced are listed as \"Previous settings\" until you quit: click that to go back.": "ersatts listas som \"Föregående inställningar\" tills du avslutar: klicka på det för att gå tillbaka.", + "reports each row's `label`.": "rapporterar varje rads `label`.", + "Reset Print Settings": "Återställ utskriftsinställningar", + "Resetting a slider": "Återställning av reglage", + "Reshuffle, another source, filter or sort, or new rules for the smart album shows what matches now.": "Blanda om, en annan källa, ett annat filter eller en annan sortering, eller nya regler för det smarta albumet visar vad som matchar nu.", + "Resize Print Cell": "Ändra storlek på utskriftscell", + "Resting the pointer on a slider's name or its thumb now says that a double-click resets it (\"Exposure — double-click": "Om du vilar pekaren på ett reglages namn eller dess handtag visas nu att ett dubbelklick återställer det (\"Exponering – dubbelklicka", + "Restore All": "Återställ alla", + "restore the photo too and say \"Restored 1 photo from Recently Deleted\". A deleted photo whose file was moved is": "återställer också fotot och säger \"Återställde 1 foto från Nyligen raderade\". Ett raderat foto vars fil har flyttats är", + "Return presses OK in Choose Edit Settings to Copy (⇧⌘C) and Paste Selected Settings (⇧⌘V), and Esc cancels them": "Return trycker på OK i Välj redigeringsinställningar att kopiera (⇧⌘C) och Klistra in markerade inställningar (⇧⌘V), och Esc avbryter dem", + "Right-click a folder (or a disk other than the startup disk) in the sidebar's Folders section ▸ Set Color Label ▸ a colour or None. The row": "Högerklicka på en mapp (eller en annan disk än startdisken) i sidofältets avsnitt Mappar → Ange färgetikett → en färg eller Ingen. Raden", + "Right-click a folder (or a disk other than the startup disk) in the sidebar's Folders section ▸ Synchronize": "Högerklicka på en mapp (eller en annan disk än startdisken) i sidofältets avsnitt Mappar → Synkronisera", + "Right-click a folder ▸ New ▸ Create Album… / Create Smart Album… / Create Smart Album from Filter… / Create Folder…": "Högerklicka på en mapp → Ny → Skapa album… / Skapa smart album… / Skapa smart album från filter… / Skapa mapp…", + "Right-click a photo ▸ Edit In ▸ Edit in PhotoCraft (or Photo ▸ Edit In, ⇧⌘E) renders a copy with your edits, stacks it": "Högerklicka på ett foto → Redigera i → Redigera i PhotoCraft (eller Foto → Redigera i, ⇧⌘E) renderar en kopia med dina redigeringar, staplar den", + "Right-click Search Photos, a slider's typed value, the Info panel's fields, the name field of New Album, Rename": "Högerklicka på Sök foton, ett reglages inskrivna värde, fälten i panelen Info, namnfältet i Nytt album, Byt namn", + "Right-click ▸ Put New Keywords Inside This Keyword: new keywords, made with + or typed in the box above, go inside": "Högerklicka → Lägg nya nyckelord inuti detta nyckelord: nya nyckelord, som skapas med + eller skrivs i rutan ovanför, hamnar inuti", + "Rule problems are shown in your language and name the field the way the menu does (\"Title: needs something to look": "Regelproblem visas på ditt språk och anger fältet på samma sätt som menyn (\"Titel: behöver något att söka", + "Rule values are checked: a rating of 9, a date like 2026-13 or \"banana\", a \"between\" whose dates are the wrong": "Regelvärden kontrolleras: betyget 9, ett datum som 2026-13 eller \"banana\", ett \"mellan\" vars datum står i fel", + "Run face models on the CPU only": "Kör ansiktsmodeller bara på CPU:n", + "runs in the background with a row in the activity stack (✕ stops it); everything it does is one undo step, and no file on disk": "körs i bakgrunden med en rad i aktivitetsstapeln (× stoppar den); allt den gör är ett enda ångra-steg, och ingen fil på disken", + "samples, no longer crashes LightCraft at 1:1 or on export: the bad values read as black.": "sampel, får inte längre LightCraft att krascha vid 1:1 eller vid export: de felaktiga värdena läses som svart.", + "Samsung SRW files without compression now open as raws: NX5, NX10, NX11, NX20, NX200, NX210, NX1000, NX1100, EX1": "Samsung SRW-filer utan komprimering öppnas nu som raw-filer: NX5, NX10, NX11, NX20, NX200, NX210, NX1000, NX1100, EX1", + "Save Current Settings as New Effect Preset…": "Spara aktuella inställningar som ny effektförinställning…", + "Save Mask Effect": "Spara maskeffekt", + "Save Print Template": "Spara utskriftsmall", + "Save Slideshow Template": "Spara bildspelsmall", + "Save the current settings as a template of your own; right-click it to update it with the current settings, rename,": "Spara de aktuella inställningarna som en egen mall; högerklicka på den för att uppdatera den med de aktuella inställningarna, byta namn,", + "saved in an earlier version now shifts the other way; set it again (or re-run Auto / the white-balance picker).": "som sparats i en tidigare version förskjuts nu åt andra hållet; ange den igen (eller kör Auto / vitbalansväljaren igen).", + "Saving the catalog and resuming a model download no longer write through a link left at the temporary file's": "När katalogen sparas och en modellhämtning återupptas skrivs det inte längre via en länk som lämnats kvar vid den tillfälliga filens", + "says what to fix, and `albums.list` reports `problems`.": "säger vad som ska åtgärdas, och `albums.list` rapporterar `problems`.", + "scale keep their look, and As Shot shows the real temperature once the file is opened.": "skala behåller sitt utseende, och Som tagen visar den verkliga temperaturen när filen har öppnats.", + "scale. Each stays up for its own duration (by default the slide duration) and fades in and out like a slide.": "skala. Var och en visas under sin egen längd (som standard visningstiden per bild) och tonas in och ut som en bild.", + "screen and nearly as tall counts as zoomed.": "skärmen och nästan lika hög räknas som inzoomad.", + "screen readers). Each darkens a little when hovered and more when pressed, shows a ring where the keyboard is, and": "skärmläsare). Var och en mörknar lite när pekaren är över den och mer när den trycks ned, visar en ring där tangentbordsfokus är, och", + "screen. They are saved with the library.": "skärm. De sparas med biblioteket.", + "search by lens. LightCraft now reads the lens range Nikon keeps in its own maker note, the way Lightroom shows a": "söka efter objektiv. LightCraft läser nu objektivets omfång som Nikon lagrar i sin egen tillverkarnotering (maker note), så som Lightroom visar en", + "second colour, at an angle and opacity) and a background image (a photo from the library, at an opacity).": "andra färg, med en vinkel och en opacitet) och en bakgrundsbild (ett foto från biblioteket, med en opacitet).", + "secondary, danger (filled red) and ghost, in three sizes, with an icon or without, and an icon alone (named for": "sekundär, fara (fylld röd) och ghost, i tre storlekar, med eller utan ikon, och enbart en ikon (namngiven för", + "Sections are easier to tell apart: a hairline between them, the fold chevron in the same column as the rows'": "Avsnitten är lättare att skilja åt: en hårfin linje mellan dem, fällchevronen i samma kolumn som radernas", + "See [remote Metal inference](ai-masks.md#remote-metal-inference).": "Se [fjärrinferens med Metal](ai-masks.md#remote-metal-inference).", + "Select All and multi-selection show every selected photo in the grid and filmstrip, not only the active one": "Markera allt och flermarkering visar alla markerade foton i rutnätet och filmremsan, inte bara det aktiva", + "Select Only Active Photo": "Markera bara aktivt foto", + "Selected Settings). Ctrl+V only reaches LightCraft while the system clipboard holds text; otherwise use Edit ▸ Paste Edit": "markerade inställningar). Ctrl+V når bara LightCraft medan systemets urklipp innehåller text; annars använder du Redigera → Klistra in redigering", + "sensor data runs a few columns of filler past the picture, which stayed in the image; these bodies now develop": "sensordata har några kolumner utfyllnad efter bilden, som blev kvar i bilden; dessa hus framkallas nu", + "Set Effect for New Masks": "Ange effekt för nya masker", + "Set Print Cell Photo": "Ange foto för utskriftscell", + "Set Print Settings": "Ange utskriftsinställningar", + "set under Overlays: its text or image) or a line of text of its own, in the plate's colour or one you pick, at a": "som anges under Överlägg: dess text eller bild) eller en egen textrad, i skyltens färg eller en som du väljer, med en", + "set). An empty field leaves its key empty instead of moving the keywords after it; editing Recent Keywords and naming": "uppsättning). Ett tomt fält lämnar sin tangent tom i stället för att flytta nyckelorden efter det; redigering av Senaste nyckelord och namngivning", + "Setting or clearing a colour label shows a brief bottom confirmation, like rating a photo; custom label names appear in the message too.": "När du anger eller rensar en färgetikett visas en kort bekräftelse längst ned, som när du ger ett foto betyg; anpassade etikettnamn visas också i meddelandet.", + "settings folder there. The same goes for the temporary session offered when the library can't be opened.": "inställningsmappen där. Detsamma gäller den tillfälliga session som erbjuds när biblioteket inte kan öppnas.", + "Settings stays put when you change tabs": "Inställningar stannar kvar när du byter flik", + "Settings → Confirm before moving photos to another folder on disk turns it back on": "Inställningar → Bekräfta innan foton flyttas till en annan mapp på disken aktiverar det igen", + "Settings → Import → Cameras and Cards has an option to open the import review as soon as a camera or memory card": "Inställningar → Import → Kameror och kort har ett alternativ för att öppna importgranskningen så snart en kamera eller ett minneskort", + "Settings ▸ Display (issue #787). On P3 screens previews used to look more saturated than the exported files in": "Inställningar → Visning (ärende #787). På P3-skärmar såg förhandsgranskningar tidigare mer mättade ut än de exporterade filerna i", + "Settings ▸ Display ▸ Choose Profile… shows photos through your monitor's ICC profile (matrix/TRC or LUT-based), so": "Inställningar → Visning → Välj profil… visar foton genom bildskärmens ICC-profil (matris/TRC eller LUT-baserad), så", + "Settings ▸ General ▸ External Editing: the format (PSD or TIFF), colour space and bit depth for PhotoCraft and for": "Inställningar → Allmänt → Extern redigering: format (PSD eller TIFF), färgrymd och bitdjup för PhotoCraft och för", + "Settings ▸ Interface ▸ Appearance Mode: Sync with System, Dark Mode or Light Mode, above a light": "Inställningar → Gränssnitt → Utseendeläge: Synka med systemet, Mörkt läge eller Ljust läge, ovanför ett ljust", + "settings, one after the other: each stack, and photos taken less than a second apart at different exposures.": "inställningar, en efter en: varje stapel, och foton som tagits med mindre än en sekunds mellanrum med olika exponeringar.", + "Settings.": "Inställningar.", + "share of the slide, so slides look the same on any screen. They are saved with the library. Agents use": "andel av bilden, så att bilderna ser likadana ut på alla skärmar. De sparas med biblioteket. Agenter använder", + "Shortcuts are editable: Help ▸ Keyboard Shortcuts (⌘/) lists every command with a search box; click a shortcut and": "Kortkommandon kan redigeras: Hjälp → Kortkommandon (⌘/) listar alla kommandon med en sökruta; klicka på ett kortkommando och", + "show a black (or, on the 645Z, white) band along one or more edges (issue #1271). The sensor's masked border is": "visar en svart (eller, på 645Z, vit) rand längs en eller flera kanter (ärende #1271). Sensorns maskerade kant är", + "show as a partial import.": "visas som en delvis import.", + "Show Focus Point": "Visa fokuspunkt", + "show full screen\" asks the viewer to open it that way.": "visa i helskärm\" ber visningsprogrammet att öppna den så.", + "Show in Folders": "Visa i mappar", + "Show Info Overlay": "Visa infoöverlägg", + "Show Layout Image": "Visa layoutbild", + "show no dialogs and take `INSTALLFOLDER=...`.": "visar inga dialogrutor och tar emot `INSTALLFOLDER=...`.", + "Show this wheel's effect": "Visa det här hjulets effekt", + "Showing a Local folder now makes its first photo the active one, as albums and the other sources do (issue": "När en lokal mapp visas blir nu dess första foto det aktiva, som för album och de andra källorna (ärende", + "shown still takes it out of the view.": "visas tar den ändå ur vyn.", + "shows and as in Lightroom, and Tint values in Lightroom XMP sidecars now render as they do there. A custom Tint": "visar och som i Lightroom, och tonvärden i XMP-sidofiler från Lightroom renderas nu som där. Ett anpassat tonvärde", + "shows only a little of come out closer to the camera's JPEG.": "visar bara lite av blir nu närmare kamerans JPEG.", + "shows the label's dot before its photo count. Agents use `folder.label` (`path`, `label`); `library.folders`": "visar etikettens punkt före antalet foton. Agenter använder `folder.label` (`path`, `label`); `library.folders`", + "shows where it will go), or right-click a header for Move Up / Move Down.": "visar var det hamnar), eller högerklicka på en rubrik för Flytta upp / Flytta ned.", + "side panels open, the frame after a keyword went from about 156 ms to about 54 ms in that library (2 ms with the": "sidopanelerna öppna gick bildrutan efter ett nyckelord från cirka 156 ms till cirka 54 ms i det biblioteket (2 ms med", + "side under it. A long list stops after eight lines with \"+N more\", and the suggestions say only the keyword's own": "sida under det. En lång lista slutar efter åtta rader med \"+N till\", och förslagen anger bara nyckelordets eget", + "Sidebar sections": "Sidofältsavsnitt", + "sidecar lookup always did; the Add Photos dialog on Linux did not until 0.5.0 (GTK and the desktop portal match": "sökningen efter sidofiler alltid har gjort; dialogrutan Lägg till foton på Linux gjorde det inte förrän 0.5.0 (GTK och skrivbordsportalen matchar", + "sidecar, a preset or an agent) no longer crashes LightCraft; the point stays between them. Curve points sent to": "sidofil, en förinställning eller en agent) får inte längre LightCraft att krascha; punkten stannar mellan dem. Kurvpunkter som skickas till", + "similarity as one undo step. Hover or focus that face and press A for the same action; hidden suggestions stay hidden.": "likhet som ett ångra-steg. Hovra över eller fokusera det ansiktet och tryck på A för samma åtgärd; dolda förslag förblir dolda.", + "Size rules measure the photo as shown: Megapixels now counts the cropped photo, like Long Edge, Short Edge and": "Storleksregler mäter fotot som det visas: Megapixel räknar nu det beskurna fotot, liksom Långsida, Kortsida och", + "sky no longer flattens the twigs, lines and texture in it, and lifting Shadows keeps the texture of dark areas, much": "himmel plattar inte längre till kvistarna, linjerna och texturen i den, och när du lyfter Skuggor behålls texturen i mörka partier, mycket", + "Sky, Subject and Background masks instead of our heuristics, so the sky is selected where the camera found it": "maskerna Himmel, Motiv och Bakgrund i stället för våra heuristiker, så himlen markeras där kameran hittade den", + "Slider drags follow the pointer more closely": "Reglagedragningar följer pekaren närmare", + "Slider drags on large raws": "Reglagedragningar på stora raw-filer", + "slider step; a slider step now takes ~5 ms on the GPU.": "reglagesteg; ett reglagesteg tar nu ~5 ms på GPU:n.", + "Slides can now be laid out like Lightroom Classic's Slideshow Layout, Options and Backdrop panels: margins (all four": "Bilder kan nu läggas ut som i Lightroom Classics bildspelspaneler Layout, Alternativ och Fond: marginaler (alla fyra", + "Slides can now carry Lightroom Classic's Slideshow overlays: an identity plate (a line of text in a colour, or an": "Bilder kan nu ha Lightroom Classics bildspelsöverlägg: en namnskylt (en textrad i en färg, eller en", + "Slideshow Export Status": "Exportstatus för bildspel", + "Slideshow export: PDF, JPEG and video": "Bildspelsexport: PDF, JPEG och video", + "Slideshow intro and ending screens": "Intro- och slutskärmar för bildspel", + "Slideshow Layout Settings": "Layoutinställningar för bildspel", + "Slideshow layout, options and backdrop": "Layout, alternativ och fond för bildspel", + "Slideshow Options…": "Bildspelsalternativ…", + "Slideshow Overlay Settings": "Överläggsinställningar för bildspel", + "Slideshow overlays": "Bildspelsöverlägg", + "Slideshow playback": "Uppspelning av bildspel", + "Slideshow Playback Settings": "Uppspelningsinställningar för bildspel", + "Slideshow Slide Preview": "Förhandsgranskning av bildspelsbild", + "Slideshow Title Settings": "Titelinställningar för bildspel", + "smaller file; Progressive files show a coarse version first. 8- or 16-bit, sRGB, Display P3 or Rec. 2020 (lossless": "mindre fil; progressiva filer visar en grov version först. 8 eller 16 bitar, sRGB, Display P3 eller Rec. 2020 (förlustfri", + "Smaller JPEG exports": "Mindre JPEG-exporter", + "Smart album rules": "Regler för smarta album", + "smart preview\" or \"This photo can't be opened\", the reason on hover) instead of showing that preview as if it were": "smart förhandsgranskning\" eller \"Det här fotot kan inte öppnas\", med orsaken när du hovrar) i stället för att visa den förhandsgranskningen som om den vore", + "so a successful install looked like nothing had happened (issues #18, #399). Silent installs (`/qn`, `/passive`)": "så en lyckad installation såg ut som om ingenting hade hänt (ärenden #18, #399). Tysta installationer (`/qn`, `/passive`)", + "so the picture looks flat and washed out there. That's how PQ PNG works, not a broken file: for a picture that": "så bilden ser platt och urblekt ut där. Så fungerar PQ PNG, det är inte en trasig fil: för en bild som", + "soft shadow, with the caption and rating under the photo), Edge to Edge (photos cropped to fill the screen), Cinema": "mjuk skugga, med bildtext och betyg under fotot), Kant till kant (foton beskurna för att fylla skärmen), Bio", + "Some EOS R6 Mark II C-RAW files (about 1 in 50 in one photographer's library) opened as their preview with": "Vissa C-RAW-filer från EOS R6 Mark II (ungefär 1 av 50 i en fotografs bibliotek) öppnades som sin förhandsgranskning med", + "Sony A7R II (and other) raws whose camera JPEG is lens-corrected no longer open grey and too dark (issue #232): the": "Raw-filer från Sony A7R II (och andra) vars kamera-JPEG är objektivkorrigerad öppnas inte längre grå och för mörka (ärende #232):", + "Sony A7R IVA) now start from colours closer to the camera's. The starting look was being fitted against a JPEG that": "Sony A7R IVA) utgår nu från färger närmare kamerans. Startutseendet anpassades mot en JPEG som", + "Sony A7R VI (ILCE-7RM6) raws are corrected for lens distortion from the table the camera records in each file,": "Raw-filer från Sony A7R VI (ILCE-7RM6) korrigeras för objektivdistorsion utifrån tabellen som kameran sparar i varje fil,", + "Sony and Fujifilm profiles were made, instead of fitting each photo's colour on its own. Colours that one photo": "Sony- och Fujifilm-profilerna togs fram, i stället för att anpassa varje fotos färg för sig. Färger som ett foto", + "Sony ILCA-99M2, ILCA-77M2, SLT-A33, DSC-RX10, ILCE-3500 and ILCE-7S raws now show white balance in Kelvin too,": "Raw-filer från Sony ILCA-99M2, ILCA-77M2, SLT-A33, DSC-RX10, ILCE-3500 och ILCE-7S visar nu också vitbalans i Kelvin,", + "Sony α1 (ILCE-1) and A7S III (ILCE-7SM3) raws for now; manual-focus shots and Wide shots that only report the frame": "raw-filer från Sony α1 (ILCE-1) och A7S III (ILCE-7SM3) tills vidare; bilder med manuell fokus och Wide-bilder som bara anger ramen", + "Sort Contents A–Z (or + ▸ Sort Albums A–Z at the top level) goes back to by name. To put a folder after an open": "Sortera innehåll A–Ö (eller + → Sortera album A–Ö på översta nivån) återgår till namnordning. För att lägga en mapp efter en öppen", + "started yet another decode.": "startade ännu en avkodning.", + "starting look is fitted to the camera JPEG away from edges when the misaligned edges spoil the fit on all pixels.": "startutseendet anpassas till kamerans JPEG en bit från kanterna när de feljusterade kanterna förstör anpassningen över alla pixlar.", + "stayed behind the edit. LightCraft now says once that the sidecars are waiting, tries again every few seconds once": "låg kvar efter redigeringen. LightCraft säger nu en gång att sidofilerna väntar, försöker igen med några sekunders mellanrum när", + "Still tallied from every photo on each edit: the filter bar's lists of cameras, lenses and keywords.": "Räknas fortfarande fram ur varje foto vid varje redigering: filterfältets listor över kameror, objektiv och nyckelord.", + "stopping the others, and a template whose identity plate image or background photo isn't there still applies, with a": "stoppa de andra, och en mall vars namnskyltsbild eller bakgrundsfoto saknas används ändå, med en", + "stored that is big enough, not always from the largest one. On a Sony A7R VI file a 512 px thumbnail decodes": "sparad som är tillräckligt stor, inte alltid från den största. På en fil från Sony A7R VI avkodas en miniatyr på 512 px", + "Straight brush strokes with ⇧-click": "Raka penseldrag med ⇧-klick", + "Subfolder if you give one (say `Exports`), so a batch from several folders lands next to each set of originals.": "Undermapp om du anger en (till exempel `Exports`), så att en batch från flera mappar hamnar bredvid varje uppsättning original.", + "submenus for Source, File, Date, Keywords & People, Description, Camera Info, Location, Size, Develop and Assisted": "undermenyer för Källa, Fil, Datum, Nyckelord och människor, Beskrivning, Kamerainfo, Plats, Storlek, Framkalla och Assisterad", + "Switch to & Containing to see the keywords with the keywords containing them, or to Will Export to see what": "Byt till & innehåller för att se nyckelorden tillsammans med de nyckelord som innehåller dem, eller till Kommer att exporteras för att se vad", + "Switching libraries": "Byte av bibliotek", + "Synchronize Folder asks a network share less": "Synkronisera mapp frågar en nätverksresurs mindre", + "Synonyms. Exports now write keyword names to `dc:subject` and their paths to `lr:hierarchicalSubject`, and keywords": "Synonymer. Exporter skriver nu nyckelordsnamn till `dc:subject` och deras sökvägar till `lr:hierarchicalSubject`, och nyckelord", + "System Info, All Metadata and What's New end with one Close button, like About, instead of Cancel and OK": "Systeminfo, Alla metadata och Nyheter avslutas med en Stäng-knapp, som Om, i stället för Avbryt och OK", + "T) now matches.": "T) matchar nu.", + "take their tiles' ICC profile, and `imir` mirrors the way libheif writes it. Importing a HEIC reads its size from": "tar sina rutors ICC-profil, och `imir` speglar på samma sätt som libheif skriver det. Vid import av en HEIC läses storleken från", + "Template name": "Mallnamn", + "Text fields": "Textfält", + "that had not changed: 4.6 to 7.1 s of questions after the listing (about 3 ms a photo), now under 0.05 s. The": "som inte hade ändrats: 4,6 till 7,1 s frågor efter listningen (cirka 3 ms per foto), nu under 0,05 s. ", + "that light already reaches (left of the image area Canon records), 4 % of the range too high on the EOS 6D. It is": "som ljus redan når (till vänster om bildområdet som Canon sparar), 4 % av omfånget för högt på EOS 6D. Det är", + "that may be listed but not searched, a path longer than the system takes): such photos used to be listed as": "som kan listas men inte genomsökas, en sökväg längre än systemet klarar): sådana foton listades tidigare som", + "the area the camera itself frames, a few pixels smaller than before.": "området som kameran själv ramar in, några pixlar mindre än förut.", + "the arrow to see its photos.": "pilen för att se dess foton.", + "The catalog format is now version 3 (`Album.order`, `Op::SetAlbumOrder`). Once this version has opened a library,": "Katalogformatet är nu version 3 (`Album.order`, `Op::SetAlbumOrder`). När den här versionen har öppnat ett bibliotek,", + "The catalog format is now version 4 (`Catalog.folder_records`, `Op::SetFolderRecord`). Once this version has": "Katalogformatet är nu version 4 (`Catalog.folder_records`, `Op::SetFolderRecord`). När den här versionen har", + "The chips at the top of the Keywords panel are the keywords of every selected photo, not only the active one's; a": "Brickorna överst i panelen Nyckelord är nyckelorden för alla markerade foton, inte bara det aktivas; en", + "The choice is saved in export presets and Export with Previous. Agents pass": "Valet sparas i exportförinställningar och i Exportera med föregående. Agenter skickar", + "The colour is described by the PNG `cICP` chunk, not an ICC profile. HDR-aware viewers (current Chromium-based": "Färgen beskrivs av PNG-blocket `cICP`, inte av en ICC-profil. HDR-medvetna visningsprogram (aktuella Chromium-baserade", + "the container instead of decoding it; small previews use the file's embedded thumbnail. The release packages": "behållaren i stället för att avkoda den; små förhandsgranskningar använder filens inbäddade miniatyr. Releasepaketen", + "The copy is a 16-bit PSD by default, which PhotoCraft saves straight back to with File ▸ Save; when you come back to": "Kopian är som standard en 16-bitars PSD, som PhotoCraft sparar direkt tillbaka till med Arkiv → Spara; när du kommer tillbaka till", + "The count beside each smart album in the left panel follows an edit the same way: the album asks only the photos": "Antalet bredvid varje smart album i den vänstra panelen följer en redigering på samma sätt: albumet frågar bara de foton", + "The desktop app keeps a log file: `logs/lightcraft.log` in its settings folder (Linux `~/.config/lightcraft/logs/`),": "Skrivbordsappen för en loggfil: `logs/lightcraft.log` i sin inställningsmapp (Linux `~/.config/lightcraft/logs/`),", + "The disk is still asked wherever a listing can't be sure what a file system would say: about a name that is": "Disken tillfrågas fortfarande där en listning inte kan vara säker på vad ett filsystem skulle svara: om ett namn som är", + "the edit touched, where it asked every photo of the library after each edit (about 25 ms an album in that library).": "som redigeringen berörde, där det tidigare frågade alla foton i biblioteket efter varje redigering (cirka 25 ms per album i det biblioteket).", + "The English and Simplified Chinese build guides now describe command-local job and release": "Bygghandledningarna på engelska och förenklad kinesiska beskriver nu kommandolokala jobb och release", + "The Export dialog has **Add to Apple Photos**, with an optional album. The files are exported to your folder as": "Exportdialogrutan har **Lägg till i Apple Photos**, med ett valfritt album. Filerna exporteras till din mapp som", + "The Export dialog has Export to: Specific folder (as before) or Same folder as original photo, like Lightroom": "Exportdialogrutan har Exportera till: Angiven mapp (som förut) eller Samma mapp som originalfotot, som i Lightroom", + "The export runs in the background with its row in the activity stack; ✕ stops it and leaves no half-written file": "Exporten körs i bakgrunden med en egen rad i aktivitetsstapeln; × stoppar den och lämnar ingen halvskriven fil", + "The export watermark can be drawn on every slide's photo too (\"Use export watermark\" takes the one you last": "Exportvattenstämpeln kan också ritas på varje bilds foto (\"Använd exportvattenstämpel\" tar den du senast", + "The eye on the Light, Color and Detail section headers now hides their adjustments, as it already did for Effects,": "Ögat på avsnittsrubrikerna Ljus, Färg och Detalj döljer nu deras justeringar, som det redan gjorde för Effekter,", + "the file, instead of asking for gigabytes of memory, which could end LightCraft.": "filen, i stället för att begära flera gigabyte minne, vilket kunde få LightCraft att avslutas.", + "the files are reachable, and says when they're written. `library.retrySidecars` does it on request.": "filerna går att nå, och meddelar när de har skrivits. `library.retrySidecars` gör det på begäran.", + "the first time a library opens after this update, \"Tidying the thumbnail cache\" shows in the activity stack": "första gången ett bibliotek öppnas efter den här uppdateringen visas \"Städar miniatyrcachen\" i aktivitetsstapeln", + "The first time, macOS asks whether LightCraft may control Photos. Photos may ask about duplicates; files it skips": "Första gången frågar macOS om LightCraft får styra Photos. Photos kan fråga om dubbletter; filer som det hoppar över", + "The Hasselblad Lunar's raws (a Sony NEX-7 inside) now develop from their sensor data with every editing tool,": "Raw-filerna från Hasselblad Lunar (en Sony NEX-7 inuti) framkallas nu från sina sensordata med alla redigeringsverktyg,", + "the highlights were darkened or saturated.": "högdagrarna mörkades eller mättades.", + "The Import Photos review opens bigger and can be resized; its photo grid fills it (issue #337). Shift-click checks": "Granskningen i Importera foton öppnas större och kan ändras i storlek; fotorutnätet fyller den (ärende #337). Shift-klick markerar", + "The interface is available in Spanish (issue #371), German and Russian (Edit ▸ Language), alongside English,": "Gränssnittet finns på spanska (ärende #371), tyska och ryska (Redigera → Språk), förutom engelska,", + "The intro plays once before the first photo; the ending after the last photo when Repeat is off (while repeating": "Introt spelas en gång före det första fotot; avslutningen efter det sista fotot när Upprepa är av (vid upprepning", + "The kept original no longer pushes everything else out of the cache: on a 64 MP raw it filled the cache share": "Det behållna originalet tränger inte längre ut allt annat ur cachen: på en raw-fil på 64 MP fyllde det cacheandelen", + "The keyword set's buttons and the suggestions follow the selection too; the typing boxes get the Cut / Copy / Paste": "Nyckelordsuppsättningens knappar och förslagen följer också markeringen; skrivrutorna får Klipp ut / Kopiera / Klistra in", + "the keyword they are inside: \"Places › Italy\" once, on a line of its own, with Rome, Venice and the others side by": "nyckelordet de ligger inuti: \"Platser › Italien\" en gång, på en egen rad, med Rom, Venedig och de andra sida vid", + "The Keywords panel ends with a Keyword List, as in Lightroom Classic: every keyword with its photo count, those no": "Panelen Nyckelord avslutas med en Nyckelordslista, som i Lightroom Classic: varje nyckelord med sitt antal foton, de som inte", + "the LightCraft window. The xdg-desktop-portal picker used to open as a separate top-level window on Wayland": "LightCraft-fönstret. Väljaren från xdg-desktop-portal öppnades tidigare som ett separat toppnivåfönster i Wayland", + "the list of every keyword is one click away however many keywords the selected photos have. What is folded is": "listan över alla nyckelord är ett klick bort hur många nyckelord de markerade fotona än har. Det som är hopfällt är", + "the loupe (issue #960). Their radii are now set in the original photo's pixels, so a thumbnail, the fitted loupe": "lupen (ärende #960). Deras radier anges nu i originalfotots pixlar, så att en miniatyr, den anpassade lupen", + "The loupe says \"Rendering…\" at the bottom of the photo when what it shows isn't the finished photo yet: the": "Lupen visar \"Renderar…\" längst ned på fotot när det den visar inte är det färdiga fotot ännu: ", + "the My Photos title to bring one back, or choose Reset Sidebar Sections. The arrangement is remembered.": "rubriken Mina foton för att få tillbaka ett, eller välj Återställ sidofältets avsnitt. Arrangemanget sparas.", + "The open library's name shows under My Photos at the top of the left panel and in the window title.": "Namnet på det öppna biblioteket visas under Mina foton överst i den vänstra panelen och i fönstertiteln.", + "the other editor (Edit in Other Editor, now ⌥⌘E), and where PhotoCraft is if you use a portable copy.": "det andra redigeringsprogrammet (Redigera i annat program, nu ⌥⌘E), och var PhotoCraft finns om du använder en portabel kopia.", + "the overlays and the intro and ending screens. Click one to apply it; point at one to see it on the selected photo in": "överläggen och intro- och slutskärmarna. Klicka på en för att använda den; peka på en för att se den på det markerade fotot i", + "the photo, follows zoom and pan, and ⌥⌘O shows or hides it. The same menu sets its opacity and a matte that": "fotot, följer zoomning och panorering, och ⌥⌘O visar eller döljer det. Samma meny ställer in dess opacitet och en matthet som", + "the photo.": "fotot.", + "The place names list towns of 15,000 people or more: in a smaller one, City gets the nearest larger town.": "Ortnamnen omfattar orter med 15 000 invånare eller fler: för en mindre ort anger Ort närmaste större ort.", + "The Presets panel builds only the rows in view (and their thumbnails) instead of every preset on every frame; the": "Panelen Förinställningar bygger bara de rader som syns (och deras miniatyrer) i stället för alla förinställningar i varje bildruta; ", + "the preview beside it without changing anything.": "förhandsgranskningen bredvid utan att ändra något.", + "the raw, so it keeps its look.": "raw-filen, så att den behåller sin look.", + "The rule editor marks each rule that needs fixing right under it and keeps OK disabled until they are fixed. An": "Regelredigeraren markerar varje regel som behöver rättas direkt under den och håller OK inaktiverad tills de är rättade. En", + "The rule editor's field menu is grouped: Rating, Pick Flag, Color Label and Any Searchable Text at the top, then": "Regelredigerarens fältmeny är grupperad: Betyg, Flagga som vald, Färgetikett och All sökbar text överst, sedan", + "The same photos give the same HDR whatever order they are selected in; before, a different order could change a": "Samma foton ger samma HDR oavsett i vilken ordning de markeras; tidigare kunde en annan ordning ändra en", + "The Settings window keeps its top edge and width when you switch tabs, so the tab row no longer jumps around": "Inställningsfönstret behåller sin överkant och bredd när du byter flik, så att flikraden inte längre hoppar runt", + "the shadows: the black level recorded in the file is now subtracted.": "skuggorna: den svartnivå som är registrerad i filen dras nu av.", + "the show runs until you stop it, so the ending doesn't come up). Random order never moves them, ←/→ step across them,": "bildspelet pågår tills du stoppar det, så avslutningen visas inte). Slumpmässig ordning flyttar dem aldrig, ←/→ stegar över dem,", + "The side panels keep a tally an edit cannot have changed: a rating or a slider changes none of the folders,": "Sidopanelerna håller en räkning som en redigering inte kan ha ändrat: ett betyg eller ett reglage ändrar ingen av mapparna,", + "The starting look fitted from a raw's camera JPEG now uses its darkest tones too (issue #1307).": "Startlooken som anpassas från en raw-fils kamera-JPEG använder nu även dess mörkaste toner (ärende #1307).", + "the system places it.": "systemet placerar den.", + "The thumbnail cache is no longer taken for your photos": "Miniatyrcachen tas inte längre för dina foton", + "The thumbnail cache no longer follows a shard folder (`thumbs/ab/`) that is a symlink or junction to somewhere": "Miniatyrcachen följer inte längre en delmapp (`thumbs/ab/`) som är en symbolisk länk eller knutpunkt (junction) till någon", + "The Tint slider works the right way round (issues #188, #321): left adds green, right adds magenta, as its track": "Reglaget Färgton fungerar åt rätt håll (ärenden #188, #321): vänster lägger till grönt, höger lägger till magenta, som dess skena", + "The titles **Keywords** and **Keyword List** in the Keywords panel fold their sections shut and open again, so": "Rubrikerna **Nyckelord** och **Nyckelordslista** i panelen Nyckelord fäller ihop sina avsnitt och öppnar dem igen, så", + "The top bar has an Import button, beside Export, in every library.": "Det övre fältet har en Importera-knapp, bredvid Exportera, i varje bibliotek.", + "The top bar's appearance button cycles Auto, Light, Dark (a monitor, sun or moon), and View ▸": "Det övre fältets utseendeknapp växlar mellan Auto, Ljus och Mörk (en skärm, sol eller måne), och Visa →", + "The window opens at the size you left it": "Fönstret öppnas i den storlek du lämnade det", + "the window. The shortcut they show is the one Import Photos… has now.": "fönstret. Kortkommandot de visar är det som Importera foton… har nu.", + "The Windows app no longer quits at launch with \"Parent device is lost\" when another program's `dxcompiler.dll` is": "Windows-appen avslutas inte längre vid start med \"Parent device is lost\" när ett annat programs `dxcompiler.dll` är", + "The Windows installer asks where to install LightCraft (Program Files by default; upgrades keep the folder you": "Windows-installationsprogrammet frågar var LightCraft ska installeras (Program Files som standard; uppgraderingar behåller mappen du", + "Their files and XMP sidecars move on disk. Edit → Undo moves them back.": "Deras filer och XMP-sidofiler flyttas på disken. Redigera → Ångra flyttar tillbaka dem.", + "their old white balance; merge them again.": "sin gamla vitbalans; sammanfoga dem igen.", + "their own ids, stacks keep only photos that exist (at least two), folders inside themselves move to the top,": "sina egna id:n, staplar behåller bara foton som finns (minst två), mappar inuti sig själva flyttas till toppen,", + "them saves a new set.": "dem sparar en ny uppsättning.", + "there in another case, a link, a name Windows reads another way (`aux.jpg`, a `~`, a `:`, a dot or a space at the": "där med andra versaler/gemener, en länk, ett namn som Windows läser på ett annat sätt (`aux.jpg`, ett `~`, ett `:`, en punkt eller ett blanksteg i", + "there, has it a sidecar): it has just listed the folder, and reads the answers off the listing. On a network share": "där, har den en sidofil): den har just listat mappen och läser svaren ur listningen. På en nätverksresurs", + "They are now kept under a name that is no picture's. The ones already there are taken over, not rendered again:": "De sparas nu under ett namn som inte tillhör någon bild. De som redan finns tas över i stället för att renderas igen:", + "This does not change colour matrices, camera calibration or RAW noise rendering.": "Detta ändrar inte färgmatriser, kamerakalibrering eller brusrendering för RAW.", + "This page setup is not valid": "Sidinställningarna är inte giltiga", + "This row covers more than one disk: drop on a folder inside it": "Den här raden omfattar mer än en disk: släpp på en mapp inuti den", + "Thumbnail cache stays in its folder": "Miniatyrcachen stannar i sin mapp", + "Thumbnails and previews are written to the cache on disk by one background writer instead of a new thread for": "Miniatyrer och förhandsgranskningar skrivs till cachen på disken av en enda bakgrundsskrivare i stället för en ny tråd för", + "Thumbnails of raw files appear sooner": "Miniatyrer av raw-filer visas snabbare", + "TIFFs) are no longer opened as a thumbnail-sized ordinary image. They are recognised as raws LightCraft can't decode": "TIFF-filer) öppnas inte längre som en vanlig bild i miniatyrstorlek. De känns igen som raw-filer som LightCraft inte kan avkoda", + "time is typed, and picking a day replaces one). Typing still works, and \"2026-10-01 10:00\" (a space for the": "tid skrivs, och att välja en dag ersätter en). Det går fortfarande att skriva, och \"2026-10-01 10:00\" (ett blanksteg för", + "to Recently Deleted, so they also left their folder's view (issue #1805). They stay in the library and in their": "till Nyligen raderade, så de försvann också från mappens vy (ärende #1805). De finns kvar i biblioteket och i sina", + "to reset it\"), in every language (issue #1436).": "för att återställa den\"), på alla språk (ärende #1436).", + "to save it as UTF-8. Exporting warns about keywords Capture One won't import, and names any keyword the format can't": "att spara den som UTF-8. Vid export varnas för nyckelord som Capture One inte importerar, och varje nyckelord som formatet inte kan", + "to the menu bar and the app ignored those keys, assuming the menu bar would handle them. Keys outside the menus": "till menyraden och appen ignorerade de tangenterna i tron att menyraden skulle hantera dem. Tangenter utanför menyerna", + "Told when there is no GPU": "Meddelar när det inte finns någon GPU", + "too, but not applied by default: our demosaic already hides most of that colour fringing, and the table on top made": "också, men används inte som standard: vår demosaicing döljer redan det mesta av de färgkanterna, och tabellen ovanpå gjorde", + "Tool Overlay: Always": "Verktygsöverlägg: Alltid", + "Tool Overlay: Auto": "Verktygsöverlägg: Auto", + "Tool Overlay: Never": "Verktygsöverlägg: Aldrig", + "Tool Overlay: Selected": "Verktygsöverlägg: Markerade", + "Tracking": "Spårning", + "Trackpads: pinch to zoom around the pointer and scroll with two fingers to pan the photo; panning keeps the photo": "Styrplattor: nyp för att zooma runt pekaren och scrolla med två fingrar för att panorera fotot; panorering håller fotot", + "triangles, a highlight under the pointer. A folded section shows how many rows it holds, counts of 0 are fainter,": "trianglar, en markering under pekaren. Ett hopfällt avsnitt visar hur många rader det innehåller, antal 0 är svagare,", + "two dates of a \"between\" can't be picked out of order; Esc closes just the calendar. It picks dates, not times (a": "två datum i ett \"mellan\" kan inte väljas i fel ordning; Esc stänger bara kalendern. Den väljer datum, inte tider (en", + "Type an exact value into any slider (issue #322): click the number next to its name, type (`1.5`, `-20`, `5600`)": "Skriv ett exakt värde i valfritt reglage (ärende #322): klicka på talet bredvid dess namn, skriv (`1.5`, `-20`, `5600`)", + "Typing in **Add keyword** offers the library's matching keywords right under the box. ↓ and Return (or a click)": "När du skriver i **Lägg till nyckelord** föreslås bibliotekets matchande nyckelord direkt under rutan. ↓ och Retur (eller ett klick)", + "under the pointer. It used to be centred, so every tab of a different height moved it.": "under pekaren. Det var tidigare centrerat, så varje flik med en annan höjd flyttade det.", + "Unknown date": "Okänt datum", + "Update Mask Effect": "Uppdatera maskeffekt", + "Update Slideshow Template": "Uppdatera bildspelsmall", + "Upgrading from a Windows installer older than 0.6 (such as 0.5.0) keeps LightCraft in the folder it was installed": "Uppgradering från ett Windows-installationsprogram äldre än 0.6 (till exempel 0.5.0) behåller LightCraft i mappen det installerades", + "Use Defaults": "Använd standardvärden", + "used to open at 1600 × 1000 every time. Double-click the top bar to zoom the window, quit, and it is zoomed when": "öppnades tidigare i 1600 × 1000 varje gång. Dubbelklicka på det övre fältet för att zooma fönstret, avsluta, så är det zoomat när", + "usual and then added to Photos, into a top-level album of that name (made when it's missing). The toast says how": "som vanligt och läggs sedan till i Photos, i ett album på toppnivå med det namnet (skapas om det saknas). Notisen anger hur", + "View Options": "Visningsalternativ", + "View Options…": "Visningsalternativ…", + "View → Loupe Overlay → View Options chooses the lines Info 1 and Info 2 show.": "Visa → Lupp-överlägg → Visningsalternativ väljer vilka rader Info 1 och Info 2 visar.", + "View → View Options chooses the lines Info 1 and Info 2 show.": "Visa → Visningsalternativ väljer vilka rader Info 1 och Info 2 visar.", + "VLC and recent phones and TVs play it.": "VLC och nya telefoner och tv-apparater spelar upp den.", + "watermark preview for it, no longer crashes LightCraft; the export is capped at the encoders' 65,535 pixels.": "vattenstämpelförhandsgranskning för den, kraschar inte längre LightCraft; exporten begränsas till kodarnas 65 535 pixlar.", + "way round, \"in the last 0 days\", a colour label that doesn't exist, \"contains\" with nothing to look for, an": "fel håll, \"de senaste 0 dagarna\", en färgetikett som inte finns, \"innehåller\" utan något att söka efter, en", + "when a `cargo` build runs outside `nix develop` (no Vulkan loader); start it from there.": "när ett `cargo`-bygge körs utanför `nix develop` (ingen Vulkan-laddare); starta det därifrån.", + "When a folder holds several file types, the Import Photos review has a toggle per type (`ARW · 120`, `JPG · 120`):": "När en mapp innehåller flera filtyper har granskningen i Importera foton en växlingsknapp per typ (`ARW · 120`, `JPG · 120`):", + "When GPU rendering is on but no graphics processor can be found, LightCraft now says so once at start-up instead": "När GPU-rendering är på men ingen grafikprocessor hittas meddelar LightCraft nu det en gång vid start i stället", + "When the graphics driver resets the GPU while LightCraft is exporting or rendering (issue #1337, seen on Windows": "När grafikdrivrutinen återställer GPU:n medan LightCraft exporterar eller renderar (ärende #1337, sett på Windows", + "when the preview renders in a few milliseconds (it waits at most 40 % of a frame for it; slower renders, such as": "när förhandsgranskningen renderas på några millisekunder (den väntar högst 40 % av en bildruta på den; långsammare renderingar, som", + "Where the camera focused": "Där kameran fokuserade", + "where the pointer landed, and a single click on the thumb leaves the value alone.": "där pekaren hamnade, och ett enkelklick på reglageknappen lämnar värdet orört.", + "which section you are in and can fold it from there.": "vilket avsnitt du är i och kan fälla ihop det därifrån.", + "While it plays, moving the pointer shows a small control bar: previous, play / pause, next, the slide number and": "Medan det spelas visar en rörelse med pekaren ett litet kontrollfält: föregående, spela upp/pausa, nästa, bildnumret och", + "while the 1:1 detail is on its way. It appears once that has lasted half a second, so quick renders never show it.": "medan 1:1-detaljen är på väg. Den visas när det har pågått en halv sekund, så snabba renderingar visar den aldrig.", + "while they are renamed (it can be stopped, and goes on at the next open).": "medan de döps om (det kan stoppas och fortsätter vid nästa öppning).", + "White balance on DNGs (and other raws with a colour matrix) re-develops the photo for the new white through the": "Vitbalans på DNG-filer (och andra raw-filer med en färgmatris) framkallar om fotot för den nya vitpunkten genom", + "White on Black": "Vitt på svart", + "white, empty Point Color slots…) as settings that couldn't be carried over.": "vit, tomma Punktfärg-platser…) som inställningar som inte kunde föras över.", + "Wide": "Bred", + "Wide (16:9 with black bars, the title in the corner, fades through black and a closing card) and Shooting Data (the": "Bred (16:9 med svarta kanter, titeln i hörnet, toningar via svart och ett avslutande kort) och Fotograferingsdata (", + "Width & Height": "Bredd och höjd", + "windows and toasts are gone.": "fönster och notiser är borta.", + "With **HDR output** on, a photo edited in HDR can now be exported as a **16-bit PNG** with the PQ curve in Rec. 2020,": "Med **HDR-utdata** på kan ett foto redigerat i HDR nu exporteras som **16-bitars PNG** med PQ-kurvan i Rec. 2020,", + "With a GPU, a slider drag's preview is drawn in the same frame as the slider moves instead of one frame later,": "Med en GPU ritas förhandsgranskningen vid reglagedragning i samma bildruta som reglaget flyttas i stället för en bildruta senare,", + "With automatic XMP writing on, an edit to a photo whose folder can't be written (a network share that dropped": "Med automatisk XMP-skrivning på kan en redigering av ett foto vars mapp inte går att skriva till (en nätverksresurs som tappade", + "With Dehaze on, panning a photo zoomed to 1:1 or moving a slider while zoomed no longer samples the whole": "Med Ta bort dis på samplar panorering av ett foto zoomat till 1:1, eller flyttning av ett reglage under zoom, inte längre hela", + "With no filter set, the count of the source is taken from the list instead of from a second pass over the library.": "Utan något filter tas antalet för källan från listan i stället för från en andra genomgång av biblioteket.", + "with NVIDIA), LightCraft still stops, because its window can't keep drawing on the lost device, but it now says": "med NVIDIA), avslutas LightCraft fortfarande, eftersom fönstret inte kan fortsätta rita på den förlorade enheten, men nu anges", + "With several photos selected, the Keywords panel says how many photos its keywords belong to. The × on a keyword": "Med flera foton markerade anger panelen Nyckelord hur många foton dess nyckelord hör till. × på ett nyckelord", + "With that, the frame after a keyword is at about 29 ms there. New rules, a change to an album or the keyword list,": "Därmed ligger bildrutan efter ett nyckelord på omkring 29 ms där. Nya regler, en ändring i ett album eller nyckelordslistan,", + "With the brush, click once, then ⇧-click somewhere else: the brush paints a straight line between the two, and": "Med penseln: klicka en gång och ⇧-klicka sedan någon annanstans: penseln målar en rak linje mellan de två, och", + "with the Dock at a side of the screen, or of a window already as wide as the screen. Zoomed by a double-click": "med Dock vid en sida av skärmen, eller för ett fönster som redan är lika brett som skärmen. Zoomat med ett dubbelklick", + "with the logs of the two previous runs beside it, so warnings and crashes of a run started from a desktop menu or the": "med loggarna från de två föregående körningarna bredvid, så att varningar och krascher från en körning startad från en skrivbordsmeny eller", + "with the original and opens it in PhotoCraft. LightCraft finds PhotoCraft where its installer put it (Windows,": "med originalet och öppnar den i PhotoCraft. LightCraft hittar PhotoCraft där installationsprogrammet placerade det (Windows,", + "with those edits went from about 3.7 s to 1.9 s. Photos look the same as before.": "med de redigeringarna gick från cirka 3,7 s till 1,9 s. Fotona ser ut som förut.", + "with Z lenses and with F-mount lenses on the FTZ adapter, follows the in-body stabilisation's shift of the optical": "med Z-objektiv och med F-objektiv på FTZ-adaptern, följer den inbyggda stabiliseringens förskjutning av den optiska", + "without applying it.": "utan att använda den.", + "Write Waiting XMP Sidecars": "Skriv väntande XMP-sidofiler", + "Writing one photo's XMP sidecar (Save Metadata to File, or automatically after an edit) no longer works out who": "När ett fotos XMP-sidofil skrivs (Spara metadata till fil, eller automatiskt efter en redigering) räknas inte längre ut vem", + "XMP presets apply their red / green / blue curves only when they also have the master curve and all three channel": "XMP-förinställningar använder sina röda/gröna/blå kurvor bara när de också har huvudkurvan och alla tre kanal-", + "XMP sidecars catch up after a network share comes back": "XMP-sidofiler kommer ikapp när en nätverksresurs är tillbaka", + "Yes/no fields (Has Edits, Cropped, Has GPS…) read Yes / No instead of true / false. A rule sent as `\"false\"` now": "Ja/nej-fält (Har redigeringar, Beskuren, Har GPS…) visar Ja/Nej i stället för sant/falskt. En regel skickad som `\"false\"` nu", + "yet and import as \"preview only\", with the reason.": "ännu och importeras som \"endast förhandsgranskning\", med orsaken.", + "you come back; un-zoom it and it goes back to the size it had before.": "du kommer tillbaka; avzooma det så återgår det till storleken det hade innan.", + "Your library is empty": "Ditt bibliotek är tomt", + "yours (issues #610, #1066). They were ordinary `.jpg` files in the library's `thumbs` folder, which is usually": "dina (ärenden #610, #1066). De var vanliga `.jpg`-filer i bibliotekets mapp `thumbs`, som oftast är", + "Zone": "Zon", + "Zoom to Focus Point": "Zooma till fokuspunkt", + "zoom, so it goes by the window's size, and when in doubt takes the window for a window of the size it has: it": "zoom, så det utgår från fönstrets storlek, och i tveksamma fall tar det fönstret för ett fönster av den storlek det har: det", + "Zoomed 64 MP raws stay decoded": "Zoomade raw-filer på 64 MP förblir avkodade", + "Zooming in with Before/After side by side decodes the original once: the Before side used to decode its own copy": "Att zooma in med Före/Efter sida vid sida avkodar originalet en gång: Före-sidan avkodade tidigare sin egen kopia", + "⇧-click and the line tapers from the old values to the new ones. The whole line is one undo step.": "⇧-klicka så smalnar linjen av från de gamla värdena till de nya. Hela linjen är ett ångrasteg.", "Blur": "Oskärpa", "Paint what should stay sharp": "Måla det som ska förbli skarpt", "Paint what should be blurred": "Måla det som ska bli oskarpt", @@ -2488,6 +3412,82 @@ "Dropped Files": "Släppta filer", "Finish Lightroom catalog import before adding photos": "Slutför importen av Lightroom-katalogen innan du lägger till foton", "Import dropped files without review": "Importera släppta filer utan granskning", + "White": "Vit", + "Before/After": "Före/efter", + "Crop Overlay": "Beskärningsöverlägg", + "A manual slideshow shows each slide until → or ← changes it. Exports still use the slide duration.": "I ett manuellt bildspel visas varje bild tills du byter med → eller ←. Exporter använder ändå visningstiden per bild.", + "Always merge into the open library": "Sammanfoga alltid med det öppna biblioteket", + "Another library was opened since this window appeared: nothing was imported": "Ett annat bibliotek öppnades efter att det här fönstret visades: ingenting importerades", + "Ask me": "Fråga mig", + "Ask me lists your recent libraries at launch. Holding Alt (Option on a Mac) as the window appears asks once.": "Med Fråga mig visas dina senaste bibliotek vid start. Håll ned Alt (Option på en Mac) när fönstret visas för att få frågan en gång.", + "Ask where to import it": "Fråga var det ska importeras", + "At launch": "Vid start", + "Burst: how alike (loose … strict)": "Bildserie: hur lika (löst … strikt)", + "Burst: shots at most this far apart": "Bildserie: högst så här lång tid mellan bilderna", + "Checking recent libraries": "Kontrollerar senaste bibliotek", + "Choose the library to open.": "Välj det bibliotek som ska öppnas.", + "Close a dialog by clicking outside it": "Stäng en dialogruta genom att klicka utanför den", + "Create a new library": "Skapa ett nytt bibliotek", + "Create Library and Import": "Skapa bibliotek och importera", + "Don't ask again (always merge into the open library)": "Fråga inte igen (sammanfoga alltid med det öppna biblioteket)", + "Last opened": "Senast öppnat", + "LightCraft opens the new library, then imports the catalog into it. Its folder must be new or empty.": "LightCraft öppnar det nya biblioteket och importerar sedan katalogen till det. Dess mapp måste vara ny eller tom.", + "Lower it when a panning or moving burst splits into several groups.": "Sänk värdet när en panorerad eller rörlig bildserie delas upp i flera grupper.", + "No horizon or vertical lines to level by": "Ingen horisont eller lodräta linjer att räta upp efter", + "No recent libraries. Open one from a folder, or make a new one.": "Inga senaste bibliotek. Öppna ett från en mapp eller skapa ett nytt.", + "Not answering yet: the drive may be asleep or offline": "Svarar inte än: enheten kan vara i viloläge eller offline", + "Not found: moved, renamed or on a disconnected drive": "Hittades inte: flyttat, omdöpt eller på en frånkopplad enhet", + "Open": "Öppna", + "Open a library first, then drop the presets again": "Öppna ett bibliotek först och släpp sedan förinställningarna igen", + "Open Another…": "Öppna ett annat…", + "Open now": "Öppna nu", + "Open the last library": "Öppna det senaste biblioteket", + "Photos whose capture time can't be read were left as they were": "Foton vars tagningstid inte kan läsas lämnades som de var", + "Remove from List": "Ta bort från listan", + "Show briefly when photo changes": "Visa kort när fotot byts", + "Show message when loading or rendering photos": "Visa meddelande när foton läses in eller renderas", + "Show Metadata For": "Visa metadata för", + "The active photo's capture time can't be read": "Det aktiva fotots tagningstid kan inte läsas", + "The catalog's photos, collections and edits join the ones already in this library.": "Katalogens foton, samlingar och redigeringar läggs till dem som redan finns i det här biblioteket.", + "The import reads the catalog without changing it. Next, choose whether its photos, edits, keywords and collections join the library open now or go into a new library.": "Importen läser katalogen utan att ändra den. Välj sedan om dess foton, redigeringar, nyckelord och samlingar ska läggas till i det bibliotek som är öppet nu eller i ett nytt bibliotek.", + "The library is empty: the catalog's photos, collections and edits become its first.": "Biblioteket är tomt: katalogens foton, samlingar och redigeringar blir de första i det.", + "The library itself stays where it is.": "Själva biblioteket ligger kvar där det är.", + "The library's catalog can't be read:": "Bibliotekets katalog kan inte läsas:", + "The photos are imported once a library is open": "Fotona importeras när ett bibliotek är öppet", + "There is no LightCraft library in this folder any more": "Det finns inte längre något LightCraft-bibliotek i den här mappen", + "This is a file, not a library folder": "Det här är en fil, inte en biblioteksmapp", + "This library couldn't be checked": "Det gick inte att kontrollera det här biblioteket", + "This library couldn't be checked:": "Det gick inte att kontrollera det här biblioteket:", + "To be asked again: Settings → General → When importing a Lightroom catalog.": "Om du vill få frågan igen: Inställningar → Allmänt → När en Lightroom-katalog importeras.", + "When importing a Lightroom catalog": "När en Lightroom-katalog importeras", + "Auto-Collapse Iconic Panels": "Fäll ihop ikonpaneler automatiskt", + "Cache limit": "Cachegräns", + "Checking for updates…": "Söker efter uppdateringar…", + "Close other panels in group": "Stäng andra paneler i gruppen", + "Close panel window": "Stäng panelfönstret", + "Close tab group": "Stäng flikgrupp", + "Collapse column": "Komprimera kolumn", + "Collapse to Icons": "Komprimera till ikoner", + "Could not check for updates:\n{error}": "Det gick inte att söka efter uppdateringar:\n{error}", + "Expand column": "Expandera kolumn", + "Expand Panels": "Expandera paneler", + "Field": "Fält", + "Float tab group": "Gör flikgruppen flytande", + "Hold {key} to undock": "Håll ned {key} för att lossa", + "LightCraft Updates": "LightCraft-uppdateringar", + "LightCraft {version} is currently the newest version available.": "LightCraft {version} är den senaste tillgängliga versionen.", + "Move group to": "Flytta gruppen till", + "Move panel column": "Flytta panelkolumn", + "Move panel window": "Flytta panelfönster", + "Move tab group": "Flytta flikgrupp", + "Open a Library": "Öppna ett bibliotek", + "Open a library first, then drop the model again": "Öppna ett bibliotek först och släpp sedan modellen här igen", + "Operator": "Operator", + "Organize into": "Ordna i", + "Other preset": "Annan förinställning", + "Recently deleted files": "Nyligen raderade filer", + "Resize": "Ändra storlek", + "Unit": "Enhet", "Lens Profiles": "Objektivprofiler", "Download lens profiles?": "Hämta objektivprofiler?", "LightCraft can correct distortion and vignetting for many lenses using the open lens database (lensfun, about {size} MB).": "LightCraft kan korrigera distorsion och vinjettering för många objektiv med den öppna objektivdatabasen (lensfun, cirka {size} MB).", @@ -2502,6 +3502,155 @@ "lensfun's open lens database (CC BY-SA 3.0) corrects distortion and vignetting for many lenses. It is only downloaded when you choose to.": "lensfuns öppna objektivdatabas (CC BY-SA 3.0) korrigerar distorsion och vinjettering för många objektiv. Den hämtas bara när du väljer det.", "Import Thumbnail Size": "Miniatyrstorlek vid import", "Click to type a value, drag to change it": "Klicka för att ange ett värde, dra för att ändra det", + "clipped highlights.": "klippta högdagrar.", + "Closer camera colour for lens-corrected raws": "Närmare kamerafärg för objektivkorrigerade raw-filer", + "closes just that.": "stänger bara det.", + "Closing a library releases its lock explicitly (issue #680). On Linux and macOS the lock used to go with the file": "När ett bibliotek stängs släpps dess lås uttryckligen (ärende #680). På Linux och macOS följde låset tidigare med filen", + "codecs' `heif` feature — 8- and 10-bit, alpha, grid tiles, the container's rotation/mirror/crop, ICC, EXIF and XMP.": "codecs `heif`-funktion — 8 och 10 bitar, alfa, rutnätsrutor, behållarens rotation/spegling/beskärning, ICC, EXIF och XMP.", + "Color Overlay": "Färgöverlägg", + "Color Overlay on B&W": "Färgöverlägg på svartvitt", + "Colour labels tint thumbnail surrounds in Square Grid and the Detail filmstrip, and a translucent footer along the bottom of the photo in Photo Grid. Label confirmations use a matching pale colour.": "Färgetiketter färgar ytan runt miniatyrerna i Kvadratiskt rutnät och filmremsan i Detalj, och en genomskinlig sidfot längs fotots nederkant i Fotorutnät. Bekräftelser av etiketter använder en matchande blek färg.", + "colours are right on wide-gamut and calibrated displays instead of oversaturated. The Detail view renders straight": "färgerna blir rätt på skärmar med brett färgomfång och kalibrerade skärmar i stället för övermättade. Detaljvyn renderar direkt", + "comes back as large as you left it, but not as a zoomed window. That is so after a zoom from the Window menu": "kommer tillbaka lika stort som du lämnade det, men inte som ett zoomat fönster. Så är det efter en zoomning från menyn Fönster", + "Compare and Reference View panes say \"Rendering…\" (or that the photo can't be opened) the same way, so a": "Rutorna i Jämför och Referensvy säger \"Renderar…\" (eller att fotot inte kan öppnas) på samma sätt, så en", + "compiler built into Windows (FXC). `WGPU_DX12_COMPILER=dxc` uses a `dxcompiler.dll` instead.": "kompilatorn som är inbyggd i Windows (FXC). `WGPU_DX12_COMPILER=dxc` använder en `dxcompiler.dll` i stället.", + "computer has is refused with the size it would take, before it starts.": "datorn har avvisas med det utrymme det skulle kräva, innan det startar.", + "Confirm before moving photos to another folder on disk": "Bekräfta innan foton flyttas till en annan mapp på disken", + "Confirm matching faces together": "Bekräfta matchande ansikten tillsammans", + "Contact Sheet PDF": "Kontaktark-PDF", + "contains it: `Canon EOS R6` stays `Canon EOS R6`, rather than `Canon Canon EOS R6` (the camera": "innehåller den: `Canon EOS R6` förblir `Canon EOS R6` i stället för `Canon Canon EOS R6` (kamerans", + "controls work as they did. With the default layout (no margins, border, shadow or backdrop) it plays the photos as": "kontrollerna fungerar som förut. Med standardlayouten (inga marginaler, kant, skugga eller fond) spelar den upp fotona som", + "Coolpix A, D3000, D40X, D60, D80, D2Xs, D200, D3200, D3100, D5000, D40, D50, D70, D70s and Nikon 1 V1 now show": "Coolpix A, D3000, D40X, D60, D80, D2Xs, D200, D3200, D3100, D5000, D40, D50, D70, D70s och Nikon 1 V1 visar nu", + "correction on (24–70 mm, 100 mm macro, 200–600 mm) the render lines up with the camera's JPEG within 0.68 px at": "korrigering på (24–70 mm, 100 mm makro, 200–600 mm) stämmer renderingen överens med kamerans JPEG inom 0,68 px vid", + "correction, checked against Sony's exports; other Sony bodies record the same tables, but they stay uncorrected until": "korrigering, kontrollerad mot Sonys exporter; andra Sony-kameror registrerar samma tabeller, men de förblir okorrigerade tills", + "Corrections, on by default for newly imported photos, with the same framing as the camera's JPEG. At 12 mm the": "Korrigeringar, på som standard för nyimporterade foton, med samma inramning som kamerans JPEG. Vid 12 mm", + "counted from every photo.": "räknas från alla foton.", + "covers lossless, Compressed and Compressed HQ (ARW 6.0) ARWs alike. The A7R IVA (ILCE-7RM4A) has its own distortion": "gäller förlustfria, Compressed och Compressed HQ (ARW 6.0) ARW-filer likadant. A7R IVA (ILCE-7RM4A) har sin egen distorsions-", + "CPU": "CPU", + "crashes LightCraft each time it renders: the amount acts as 20.": "kraschar LightCraft varje gång det renderas: mängden behandlas som 20.", + "Create keywords with + (inside the one you picked, with synonyms, and given to the selection if you like), edit one": "Skapa nyckelord med + (inuti det du valde, med synonymer, och tilldelat markeringen om du vill), redigera ett", + "Crop (issue #295): a Lock toggle keeps the aspect ratio on every handle, Custom takes your own ratio (Apply), and": "Beskär (ärende #295): en Lås-knapp behåller bildförhållandet på alla handtag, Anpassad tar ditt eget förhållande (Använd), och", + "Crop rotation": "Beskärningsrotation", + "Culling.": "Gallring.", + "current edits": "aktuella ändringar", + "curves, as Lightroom does: a preset with just one channel curve (or no master curve) leaves the channels alone.": "kurvor, som Lightroom gör: en förinställning med bara en kanalkurva (eller ingen huvudkurva) låter kanalerna vara.", + "Custom AF Area": "Anpassat AF-område", + "Cut, Copy, Paste and Select All. Esc in them gives back the text from before you started typing (in the Info panel it": "Klipp ut, Kopiera, Klistra in och Markera allt. Esc i dem återställer texten från innan du började skriva (i panelen Info", + "Cycle Flag": "Växla flagga", + "Cycle Tool Overlay": "Växla verktygsöverlägg", + "D60, D80 and D2Xs now show the area the camera itself frames, a few pixels smaller than before.": "D60, D80 och D2Xs visar nu området som kameran själv ramar in, några pixlar mindre än tidigare.", + "D7000, D5100, D800, D800E, Df, D4, D3, D3S, D700, D300, D300S, D600, D610, D810, D4S, D5600, Coolpix A, D3000, D40X,": "D7000, D5100, D800, D800E, Df, D4, D3, D3S, D700, D300, D300S, D600, D610, D810, D4S, D5600, Coolpix A, D3000, D40X,", + "dark sky is now removed too.": "mörk himmel tas nu också bort.", + "darkens the photo outside it. The layout stays chosen across launches.": "mörkar fotot utanför den. Layouten förblir vald mellan starter.", + "Date rules have a calendar button: pick a day, a month or a whole year (Year / Month / Day), in your language; the": "Datumregler har en kalenderknapp: välj en dag, en månad eller ett helt år (År / Månad / Dag), på ditt språk;", + "Daylight, Cloudy, Shade, Tungsten, Fluorescent and Flash presets set real temperatures (issue #730). The matrices": "Förinställningarna Dagsljus, Molnigt, Skugga, Glödlampa, Lysrör och Blixt ställer in verkliga temperaturer (ärende #730). Matriserna", + "Decrease Flag Status": "Sänk flaggstatus", + "Decrease Grid Thumbnail Size": "Minska miniatyrstorlek i rutnätet", + "default cache share (768 MB), so it was evicted as soon as it was stored. The original of the photo shown in Detail": "standardandel av cachen (768 MB), så den rensades ut så fort den lagrats. Originalet för fotot som visas i Detalj", + "Dehaze while zoomed in": "Ta bort dis vid inzoomning", + "Delete Cell": "Radera cell", + "Delete in an album removes from the album only": "Radera i ett album tar bara bort från albumet", + "Delete Mask Effect": "Radera maskeffekt", + "Delete Print Cell": "Radera utskriftscell", + "Delete Print Template": "Radera utskriftsmall", + "Delete Slideshow Template": "Radera bildspelsmall", + "Deleted, read the metadata updates. A folder on a disk that isn't connected is reported as such. Synchronizing": "raderade, läsa in metadatauppdateringarna. En mapp på en disk som inte är ansluten rapporteras som sådan. Synkronisering", + "deletes a keyword from the whole library.": "raderar ett nyckelord från hela biblioteket.", + "demosaic already lines the colour planes up. Details and measurements: `docs/fuji-lens-corrections.md`.": "demosaicingen riktar redan in färgplanen. Detaljer och mätningar: `docs/fuji-lens-corrections.md`.", + "depending on the graphics card. On a Windows laptop with an AMD Radeon 780M, a full-size export of a 24 MP raw": "beroende på grafikkortet. På en bärbar Windows-dator med AMD Radeon 780M, en export i full storlek av en 24 MP raw-fil", + "Detail has a per-photo AI Denoise switch and Amount. Bayer RAW photos use a disposable cache, with matching previews and exports and pure-Rust CPU/GPU inference.": "Detalj har ett reglage för AI-brusreducering per foto och Mängd. Bayer-RAW-foton använder en tillfällig cache, med matchande förhandsgranskningar och exporter och CPU/GPU-inferens i ren Rust.", + "Detail view that pointed at an empty grid. The grid and Detail view offer Import Photos… and, in the desktop app,": "Detaljvy som pekade på ett tomt rutnät. Rutnätet och Detaljvyn erbjuder Importera foton… och, i skrivbordsappen,", + "Detection": "Detektering", + "dialog was found and closed.": "dialogrutan hittades och stängdes.", + "Dialogs": "Dialogrutor", + "Dialogs fit the window": "Dialogrutor anpassas till fönstret", + "Dialogs that fit look as before.": "Dialogrutor som får plats ser ut som förut.", + "Dialogs' buttons and About's Discord link are drawn by one button component: primary (filled with the accent),": "Dialogrutornas knappar och Discord-länken i Om ritas av en och samma knappkomponent: primär (fylld med accentfärgen),", + "did). On the D600 and D610 the white level is also measured inside the picture, so the filler can't pass for": "gjorde). På D600 och D610 mäts även vitnivån inuti bilden, så att utfyllnaden inte kan tas för", + "didn't line up with the raw near the edges. Photos you already imported pick this up when their previews are rebuilt.": "stämde inte med raw-filen nära kanterna. Foton du redan har importerat får detta när deras förhandsgranskningar byggs om.", + "differ by about 7–10 % on the ILCE-7M3; which one is off is still open.": "skiljer sig med cirka 7–10 % på ILCE-7M3; vilken som är fel är fortfarande oklart.", + "Dimensions": "Dimensioner", + "directives. See README → Quick start → Logs.": "direktiv. Se README → Quick start → Logs.", + "Display profile not used": "Skärmprofilen används inte", + "DNG camera identity": "DNG-kameraidentitet", + "DNG export and Convert to DNG no longer duplicate the camera make when the model already": "DNG-export och Konvertera till DNG duplicerar inte längre kameratillverkaren när modellen redan", + "Dock can be attached to a bug report. `LIGHTCRAFT_LOG` works as before; `RUST_LOG` takes env_logger-style": "Dock kan bifogas till en buggrapport. `LIGHTCRAFT_LOG` fungerar som förut; `RUST_LOG` tar env_logger-liknande", + "does the photos it was made from. HDRs merged before this don't have it; merge them again.": "gör de foton den skapades av. HDR-bilder som sammanfogats före detta har det inte; sammanfoga dem igen.", + "does: As Shot reads the file's white (an ILCE-7M3 sample: 4268 K / +7), the Temp slider runs 2000–50000 K and the": "gör: Som tagen läser filens vitbalans (ett ILCE-7M3-exempel: 4268 K / +7), reglaget Temp går 2000–50000 K och", + "Don't ask again": "Fråga inte igen", + "Drag a keyword onto another to nest it, or onto the list's title to bring it back to the top level; photos dragged": "Dra ett nyckelord till ett annat för att lägga det inuti, eller till listans rubrik för att flytta det tillbaka till översta nivån; foton som dras", + "Drag an album or folder onto a folder to move it there (a closed folder opens after 0.6 s under the pointer; a": "Dra ett album eller en mapp till en mapp för att flytta dit (en stängd mapp öppnas efter 0,6 s under pekaren; en", + "Drag anywhere inside the selected radial gradient's ellipse to move it, including rotated": "Dra var som helst inuti den markerade radiella gradientens ellips för att flytta den, även när den är roterad", + "dragging a handle into the image edge stops there instead of pushing the crop out of shape.": "om du drar ett handtag mot bildkanten stannar det där i stället för att förvränga beskärningen.", + "Dragging a slider no longer re-renders the edited photo's filmstrip thumbnail on every frame; it follows once you": "Att dra ett reglage renderar inte längre om det redigerade fotots miniatyr i filmremsan för varje bildruta; den följer efter när du", + "Dragging a Tone Curve point that sits very close to its neighbours (two clicks side by side, or a curve from a": "Att dra en punkt i Tonkurva som ligger mycket nära sina grannar (två klick bredvid varandra, eller en kurva från en", + "Duplicate Mask Effect": "Duplicera maskeffekt", + "E-1, E-400 and XZ-2 corpus files: all accepted), with white balance relative to the as-shot look as for the other": "E-1, E-400 och XZ-2 korpusfiler: alla godkända), med vitbalansen relativ till utseendet Som tagen, som för de andra", + "each image (issue #1522). When renders come in faster than the disk takes them, at most 128 MB of images wait;": "varje bild (ärende #1522). När renderingar kommer in snabbare än disken hinner ta emot dem väntar högst 128 MB bilder;", + "each of those questions is a round trip. Measured on a hard disk over SMB, for folders of 1,600 to 2,400 photos": "var och en av de frågorna är en tur och retur. Uppmätt på en hårddisk över SMB, för mappar med 1 600 till 2 400 foton", + "Each sits at one of nine anchors of the slide or of the photo, moved by an offset, and never leaves the slide.": "Var och en sitter vid ett av nio ankare på bilden eller på fotot, flyttad med en förskjutning, och lämnar aldrig bilden.", + "Each such bug used to take one of the render threads with it, so after a few of them no photo rendered until": "Varje sådan bugg tog tidigare med sig en av renderingstrådarna, så efter några av dem renderades inget foto förrän", + "each time you look (issue #1392): the next time you browse the folder, in a later session, they're left out. A photo you had rated, flagged or": "varje gång du tittar (ärende #1392): nästa gång du bläddrar i mappen, i en senare session, utelämnas de. Ett foto som du hade betygsatt, flaggat eller", + "Edge, Short Edge, Aspect Ratio (landscape / portrait / square), Cropped and Treatment (in color / black & white).": "sida, Kortsida, Bildförhållande (liggande / stående / kvadrat), Beskuren och Behandling (i färg / svartvitt).", + "edge.": "kant.", + "edit at 1:1, every zoom out and every step to the next photo.": "redigering vid 1:1, varje utzoomning och varje steg till nästa foto.", + "Edit In": "Redigera i", + "edited earlier may shift by a few pixels.": "redigerats tidigare kan förskjutas några pixlar.", + "edited stays, marked missing, so its changes aren't lost; photos in My Photos are unchanged.": "redigerat finns kvar, markerat som saknat, så att ändringarna inte går förlorade; foton i Mina foton är oförändrade.", + "Editing a smart album's name and rules is one step: both or neither, and one undo takes both back": "Att redigera ett smart albums namn och regler är ett steg: båda eller inget, och en ångring tar tillbaka båda", + "Edits keep up in a large library": "Redigeringar hänger med i ett stort bibliotek", + "ellipses and radial components in compound masks. Edge and rotation handles keep their existing": "ellipser och radiella komponenter i sammansatta masker. Kant- och rotationshandtag behåller sina befintliga", + "else (issue #1504): trimming or clearing the cache can't delete files outside it, and thumbnails are never read": "annat (ärende #1504): när cachen trimmas eller rensas kan inga filer utanför den raderas, och miniatyrer läses aldrig", + "embedded JPEG.": "inbäddad JPEG.", + "End Slideshow": "Avsluta bildspel", + "end), a folder the scan did not walk to its end, and, in a folder that holds any name with a character outside": "slut), en mapp som genomsökningen inte gick igenom till slutet och, i en mapp som innehåller något namn med ett tecken utanför", + "end. Space pauses, ← / → step (a cut), Esc ends. A slide's time starts once it is shown sharp.": "slut. Blanksteg pausar, ← / → går ett steg (med ett snitt), Esc avslutar. En bilds tid börjar först när den visas skarp.", + "ending. They are saved with the library. Agents use `slideshow.titles`, and `slideshow.preview {title: \"intro\"}`": "avslutning. De sparas med biblioteket. Agenter använder `slideshow.titles` och `slideshow.preview {title: \"intro\"}`", + "every selected photo; a chip's menu acts on the selection (add to all, remove, show photos, edit) and no longer": "varje markerat foto; menyn på en bricka verkar på markeringen (lägg till i alla, ta bort, visa foton, redigera) och inte längre", + "everything about how a slideshow looks and plays: the playback timing and fades, the layout, options and backdrop,": "allt om hur ett bildspel ser ut och spelas upp: uppspelningens tidsinställning och toningar, layouten, alternativen och fonden,", + "existing LightCraft edits are preserved by default. Source settings/history are archived, unsupported": "befintliga LightCraft-redigeringar behålls som standard. Källinställningar/historik arkiveras, fält som inte stöds", + "Existing smart previews are refreshed when their originals are online, and cached renders are redrawn.": "Befintliga smarta förhandsgranskningar uppdateras när deras original är online, och cachade renderingar ritas om.", + "Expanded Flexible Spot": "Utökad flexibel punkt", + "Export as JPEG XL (issue #247): Format ▸ JPEG XL in the Export dialog, `format: \"jxl\"` for agents and the CLI": "Exportera som JPEG XL (ärende #247): Format → JPEG XL i dialogrutan Exportera, `format: \"jxl\"` för agenter och CLI:t", + "Export can write PSD too (flat, 8- or 16-bit).": "Exporten kan även skriva PSD (sammanslagen, 8 eller 16 bitar).", + "Export Effect Presets": "Exportera effektförinställningar", + "Export Effect Presets…": "Exportera effektförinställningar…", + "Export Mask Effects": "Exportera maskeffekter", + "Export next to the originals": "Exportera bredvid originalen", + "export or delete it, and import templates others share with you. Your templates are `.json` files in the settings": "exportera eller radera den, och importera mallar som andra delar med dig. Dina mallar är `.json`-filer i inställnings-", + "exported files will carry for the selection.": "exporterade filer kommer att ha för markeringen.", + "exported or converted to DNG. It is not applied by default: Lightroom Classic renders ProRAW without it. To see a": "exporteras eller konverteras till DNG. Den används inte som standard: Lightroom Classic renderar ProRAW utan den. För att se en", + "exported with).": "exporterades med).", + "Exporting a photo more than 65,535 times as long as it is wide (a one-pixel strip), or opening the Export dialog's": "Export av ett foto som är mer än 65 535 gånger så långt som det är brett (en remsa på en pixel), eller öppning av dialogrutan Exportera", + "Exports with noise reduction, Texture, Clarity, Dehaze or Highlights and Shadows can be much faster on the GPU,": "Exporter med brusreducering, Textur, Klarhet, Ta bort dis eller Högdagrar och Skuggor kan gå mycket snabbare på GPU:n,", + "exposure, ISO, focal length, camera and lens under each photo on a dark backdrop).": "exponering, ISO, brännvidd, kamera och objektiv under varje foto på en mörk fond).", + "Face models (ONNX)": "Ansiktsmodeller (ONNX)", + "Face Models on the GPU": "Ansiktsmodeller på GPU:n", + "Face tracking": "Ansiktsspårning", + "Face Tracking": "Ansiktsspårning", + "Faces are kept in the thumbnail cache at a few fixed sizes, so moving the thumbnail slider no longer renders them": "Ansikten sparas i miniatyrcachen i några fasta storlekar, så när du drar i miniatyrreglaget renderas de inte längre", + "Faces load faster in the People view": "Ansikten läses in snabbare i vyn Människor", + "Faces on unedited raws are cut from the camera's preview inside the file instead of developing the raw (issue": "Ansikten på oredigerade raw-filer klipps ut ur kamerans förhandsgranskning i filen i stället för att raw-filen framkallas (ärende", + "Faster GPU exports": "Snabbare GPU-exporter", + "faster on an external hard disk. A face whose preview is too small, and any edited photo, is still developed from": "snabbare på en extern hårddisk. Ett ansikte vars förhandsgranskning är för liten, och alla redigerade foton, framkallas fortfarande från", + "Favorite Mask Effect": "Favoritmaskeffekt", + "favourites across restarts (issue #328).": "favoriter mellan omstarter (ärende #328).", + "few pixels.": "några pixlar.", + "fields are reported, and the original Lightroom database stays read-only. Rendering is approximate.": "fält rapporteras, och den ursprungliga Lightroom-databasen förblir skrivskyddad. Renderingen är ungefärlig.", + "File extensions match whatever their letter case: `IMG_0001.JPG` and `DSC_0002.NEF` as Nikon writes them, `.Jpg`": "Filändelser matchas oavsett skiftläge: `IMG_0001.JPG` och `DSC_0002.NEF` som Nikon skriver dem, `.Jpg`", + "file is gone, photos whose file was renamed or moved within the folder, and XMP sidecars changed by other apps; then": "filen saknas, foton vars fil har bytt namn eller flyttats inom mappen och XMP-sidofiler som ändrats av andra appar; sedan", + "file name, then id, instead of import order. Recently Added keeps a batch in file name order, and Auto-Stack orders a": "filnamn, sedan id, i stället för importordning. Nyligen tillagda håller en batch i filnamnsordning, och Autostapla ordnar en", + "file that hold the focus point (about 100 photos a second from a spinning disk), with a *Reading focus points* row": "fil som innehåller fokuspunkten (ungefär 100 foton per sekund från en snurrande disk), med en rad *Läser fokuspunkter*", + "File → Import Lightroom Catalog… opens `.lrcat` directly, with originals referenced in place.": "Arkiv → Importera Lightroom-katalog… öppnar `.lrcat` direkt, med originalen refererade där de ligger.", + "File ▸ Import Keywords… and Export Keywords… read and write keyword list files as Lightroom Classic does (a keyword": "Arkiv →Importera nyckelord… och Exportera nyckelord… läser och skriver nyckelordslistfiler som Lightroom Classic gör (ett nyckelord", + "File ▸ New Library… asks for a name, then where to put it, and opens the new library (issue #902).": "Arkiv →Nytt bibliotek… frågar efter ett namn och sedan var det ska ligga, och öppnar det nya biblioteket (ärende #902).", + "File ▸ Open Recent Library lists the last 8 libraries; ones that are gone (moved, drive disconnected) are greyed": "Arkiv →Öppna senaste bibliotek listar de 8 senaste biblioteken; de som har försvunnit (flyttats, enheten frånkopplad) är nedtonade", + "Filename captions": "Filnamn som bildtext", + "files also Adobe RGB and ProPhoto), metadata as for JPEG. With HDR output, photos edited in HDR are written as": "filer även Adobe RGB och ProPhoto), metadata som för JPEG. Med HDR-utdata skrivs foton som redigerats i HDR som", + "files in the test corpus still decode.": "filer i testkorpusen avkodas fortfarande.", + "files, the same files as `library.import` (issue #1080). They used to be skipped without a word.": "filer, samma filer som `library.import` (ärende #1080). Tidigare hoppades de över utan ett ord.", + "Five built-in templates of our own: Plain Black (the photo on black), Gallery Wall (a light wall, a white mat and a": "Fem egna inbyggda mallar: Enkel svart (fotot på svart), Gallerivägg (en ljus vägg, ett vitt passepartout och en", + "Flexible Spot": "Flexibel punkt", "Face recognition is on": "Ansiktsigenkänning är på", "Face recognition is off. Turn it on to get name suggestions and see look-alike faces together.": "Ansiktsigenkänning är av. Slå på den för att få namnförslag och se liknande ansikten tillsammans.", "Turn on": "Slå på", @@ -2517,11 +3666,218 @@ "Top bar": "Övre fältet", "Tool strip": "Verktygsfält", "Bottom bar": "Nedre fältet", + "(Restore All is there too). The row used to bring every hidden location back at once (issue #2114).": "(Återställ alla finns också kvar). Raden brukade ta tillbaka alla dolda platser på en gång (ärende #2114).", + "(View ▸ Zoom to Focus Point turns this off). Photos without a point zoom as before.": "(Visa → Zooma till fokuspunkt stänger av detta). Foton utan punkt zoomar som tidigare.", + "**View ▸ Show Focus Point** (⌥F) draws the autofocus frame the camera recorded over the photo, in Detail, Compare": "**Visa → Visa fokuspunkt** (⌥F) ritar autofokusramen som kameran registrerade ovanpå fotot, i Detalj, Jämför", + "7078 drone panorama's 512 px thumbnail took 38 s and now takes about a second, with the same look; your edits still": "7078 tog 38 s för sin miniatyr på 512 px och tar nu ungefär en sekund, med samma utseende; dina redigeringar", + "`photo.setReference` refuses an `id` that is not a photo id (a string, a negative or fractional": "`photo.setReference` vägrar ett `id` som inte är ett foto-id (en sträng, ett negativt tal eller ett", + "A crop ratio no longer flips to the photo's orientation (issue #2253): after X turns the crop portrait, picking": "Ett beskärningsförhållande växlar inte längre till fotots orientering (ärende #2253): när X har gjort beskärningen stående och du väljer", + "A folder with tens of thousands of photos, above all on a network share, can take minutes to list before": "En mapp med tiotusentals foton, särskilt på en nätverksresurs, kan ta minuter att lista innan", + "A merge that names the same photo more than once (through `ids` on the control channel, MCP or the CLI) now merges": "En sammanfogning som anger samma foto mer än en gång (via `ids` på kontrollkanalen, MCP eller CLI) sammanfogar nu", + "A pinch no longer re-renders the photo at every zoom step": "En nypning renderar inte längre om fotot vid varje zoomsteg", + "A preset that couldn't be saved is no longer lost silently": "En förinställning som inte kunde sparas går inte längre förlorad i tysthet", + "A raw sidecar used to name all of them for every photo. Settings LightCraft really doesn't apply, such as `Look`,": "En raw-sidofil brukade ange alla för varje foto. Inställningar som LightCraft verkligen inte tillämpar, som `Look`,", + "A smart album rule on File Path (contains, doesn't contain, is, isn't, starts with, ends with, is empty, isn't": "En regel för smart album på Sökväg (innehåller, innehåller inte, är, är inte, börjar med, slutar med, är tomt, är inte", + "adjustments and an ongoing drag still work. A slider reached with Tab takes the arrow keys but not the wheel:": "och en pågående dragning fungerar fortfarande. Ett reglage som nås med Tab tar emot piltangenterna men inte hjulet:", + "AI Denoise on DirectX 12 with NVIDIA GTX 10-series cards": "AI-brusreducering på DirectX 12 med NVIDIA GTX 10-seriens kort", + "AI Denoise on the GPU under DirectX 12 (the Windows default) gives the same result as on the CPU again on an NVIDIA": "AI-brusreducering på GPU:n under DirectX 12 (standard i Windows) ger åter samma resultat som på CPU:n på ett NVIDIA", + "An HDR made with Photo ▸ Photo Merge ▸ HDR now keeps the lens correction the photos carry (Sony's, Panasonic's": "En HDR skapad med Foto → Fotosammanfogning → HDR behåller nu objektivkorrigeringen som fotona har med sig (Sonys, Panasonics", + "and `metadata.reverseGeocode` takes `maxDistance` (metres): past it, City stays empty (State and Country still fill)": "och `metadata.reverseGeocode` tar `maxDistance` (meter): bortom det förblir Ort tomt (Region och Land fylls fortfarande i)", + "and a Synchronize button that started a job with nothing to do. Files it skipped (already in the library elsewhere,": "och en Synkronisera-knapp som startade ett jobb utan något att göra. Filer som hoppades över (redan på annat ställe i biblioteket,", + "and Cancel stops a download that is still looking the name up (issue #1532). The lookup used to block with no time": "och Avbryt stoppar en nedladdning som fortfarande slår upp namnet (ärende #1532). Uppslagningen brukade blockera utan", + "and comes back between two screen updates. Scrolling back over it now scrolls the panel instead of unexpectedly": "och kommer tillbaka mellan två skärmuppdateringar. Att rulla tillbaka över det rullar nu panelen i stället för att oväntat", + "and Leica's, and the one some DNGs carry, e.g. from drones): Optics ▸ Enable Lens Corrections straightens it as it": "och Leicas, och den som vissa DNG-filer har, t.ex. från drönare): Optik → Aktivera objektivkorrigeringar rätar ut den som den", + "and the reply names the town it found as `nearestCity`.": "och svaret anger orten den hittade som `nearestCity`.", + "another ratio (4 × 5, 2 × 3…) keeps it portrait, as in Lightroom, and a Custom ratio taller than wide gives a": "ett annat förhållande (4 × 5, 2 × 3…) förblir den stående, som i Lightroom, och ett anpassat förhållande som är högre än brett ger en", + "apply. Loupe previews larger than the biggest copy, 1:1 views and exports still read the full image.": "gäller fortfarande. Förhandsgranskningar i luppen som är större än den största kopian, 1:1-vyer och exporter läser fortfarande hela bilden.", + "Applying a template can't be undone with Edit ▸ Undo (slideshow settings are library preferences), so the settings it": "Att använda en mall kan inte ångras med Redigera → Ångra (bildspelsinställningarna är biblioteksinställningar), så de inställningar den", + "are still reported.": "rapporteras fortfarande.", + "back up once nothing is left unsaved.": "säkerhetskopiera när inget längre är osparat.", + "bar all that time, as if it had stopped. It now says how many folders and files it has listed so far, with a bar": "förloppsindikator hela den tiden, som om den hade stannat. Nu visas hur många mappar och filer som har listats hittills, med en förloppsindikator", + "before this keep the masks they got: Photo ▸ Read Metadata from File reads a sidecar's again.": "innan detta behåller de masker de fick: Foto → Läs metadata från fil läser in en sidofils masker igen.", + "Before, the failure was only logged, and the preset could be lost without any warning.": "Tidigare loggades felet bara, och förinställningen kunde gå förlorad utan någon varning.", + "Bright windows in an HDR made with Photo ▸ Photo Merge ▸ HDR no longer take a magenta tinge from the brighter": "Ljusa fönster i en HDR skapad med Foto → Fotosammanfogning → HDR får inte längre en magentaton från den ljusare", + "Browsing a folder under Local now records it as browsed, so the photos in folders you use aren't forgotten after": "När du bläddrar i en mapp under Lokalt registreras den nu som bläddrad, så att fotona i mappar du använder inte glöms bort efter", + "by side, and `keyword:\"new york\"` a keyword of two words.": "bredvid varandra, och `keyword:\"new york\"` ett nyckelord med två ord.", + "catalog; a pin no longer silently becomes another library's photo with the same numeric ID.": "katalog; en låsning blir inte längre i tysthet ett annat biblioteks foto med samma numeriska ID.", + "Change them in Settings ▸ Slideshow (View ▸ Slideshow Options…); they are saved with the library. Agents use": "Ändra dem i Inställningar → Bildspel (Visa → Bildspelsalternativ…); de sparas med biblioteket. Agenter använder", + "changing the photo. Click or drag the slider again to adjust it with the vertical wheel; keyboard arrow": "ändra fotot. Klicka eller dra i reglaget igen för att justera det med det vertikala hjulet; justeringar med piltangenterna", + "channels came out shifted and the denoised photo was wrong without any error. Vulkan was not affected.": "kanaler blev förskjutna och det brusreducerade fotot blev fel utan något felmeddelande. Vulkan påverkades inte.", + "Check for Updates…": "Sök efter uppdateringar…", + "cleared): the backup copies the stored library, so it left out the changes that couldn't be saved (issue #1508). It": "rensat): säkerhetskopian kopierar det lagrade biblioteket, så ändringarna som inte kunde sparas utelämnades (ärende #1508). Den", + "click it to scroll-adjust it. Sideways scrolling still adjusts the slider under the pointer without selecting it": "klicka på det för att justera det genom att rulla. Rullning i sidled justerar fortfarande reglaget under pekaren utan att markera det", + "compared as before.": "jämförs som tidigare.", + "Constrain Crop tightens the crop you see": "Begränsa beskärning gör beskärningen du ser snävare", + "corners came out up to 6.5 % brighter than in the camera's JPEG. The corrected photo now lines up with the camera's": "hörn blev upp till 6,5 % ljusare än i kamerans JPEG. Det korrigerade fotot stämmer nu överens med kamerans", + "corners left by the correction are gone, and the Crop tool shows the tighter crop. Before, it only applied when the": "hörn som korrigeringen lämnade är borta, och Beskärningsverktyget visar den snävare beskärningen. Tidigare gällde det bara när", + "counts as unsaved, like other changes: the top bar warns, saving is retried, and quitting asks first (issue #2266).": "räknas som osparad, liksom andra ändringar: det övre fältet varnar, sparningen görs om och avslutning frågar först (ärende #2266).", + "empty) no longer builds new text for every photo. On a synthetic library of 312,000 photos, a File Path \"contains\"": "tomt) bygger inte längre ny text för varje foto. I ett syntetiskt bibliotek med 312 000 foton tog en Sökväg-regel med ”innehåller”", + "Escape now leaves Reference for Detail without changing the active photo or its edits; the next": "Esc lämnar nu Referens för Detalj utan att ändra det aktiva fotot eller dess redigeringar; nästa", + "Escape returns to the grid. A dialog, tool or Lights Out still handles Escape first.": "Esc återgår till rutnätet. En dialogruta, ett verktyg eller Nedsläckt hanterar fortfarande Esc först.", + "every photo of the view again: at about 180,000 photos a batch cost the window a tenth of a second, over and over": "varje foto i vyn igen: vid cirka 180 000 foton kostade en batch fönstret en tiondels sekund, om och om igen", + "Fewer false \"not imported\" warnings for Lightroom raws": "Färre felaktiga ”inte importerad”-varningar för raw-filer från Lightroom", + "Fill Location from GPS: no more neighbouring town in City": "Fyll i plats från GPS: ingen grannort längre i Ort", + "first.": "först.", + "folder browsed every day from the sidebar was forgotten anyway and read again from scratch on the next visit,": "mapp som du bläddrade i varje dag från sidofältet glömdes ändå bort och lästes in från början vid nästa besök,", + "folder; Edit ▸ Undo puts them back in the album. Photo ▸ Remove from Album does the same and now shows the key.": "mapp; Redigera → Ångra lägger tillbaka dem i albumet. Foto → Ta bort från album gör samma sak och visar nu kortkommandot.", + "for as long as the import ran. Changing one photo's capture time or crop is quicker too.": "så länge importen pågick. Att ändra ett fotos tagningstid eller beskärning går också snabbare.", + "framing. Other recent Fujifilm bodies whose tables have nine knots are read the same way, but only the X-T4 was": "inramning. Andra nya Fujifilm-hus vars tabeller har nio knutpunkter läses på samma sätt, men bara X-T4 har", + "Fujifilm lens corrections that match the camera": "Objektivkorrigeringar för Fujifilm som matchar kameran", + "Full-frame 3:2 Bayer A7CR raws with distortion Auto or forced Auto now use their embedded distortion table. The corrected render is closer to the camera JPEG geometry. Off files keep their original geometry. APS-C, aspect crops and lossless M/S remain excluded.": "Raw-filer från A7CR i fullformat, 3:2 och Bayer med distorsion Auto eller tvingad Auto använder nu sin inbäddade distorsionstabell. Den korrigerade renderingen ligger närmare kamerans JPEG-geometri. Filer med Av behåller sin ursprungliga geometri. APS-C, beskärningar av bildförhållandet och förlustfri M/S är fortfarande uteslutna.", + "GeForce GTX 1070. The driver ran the denoise network's output stores wrong, so every second pixel's colour": "GeForce GTX 1070. Drivrutinen utförde brusreduceringsnätverkets skrivningar av utdata fel, så att varannan pixels färg", + "Geometry slider, Upright or a lens correction while it is ticked, shrinks the crop about its centre until the blank": "Geometri-reglage, Uppräta eller en objektivkorrigering medan den är ikryssad, krymper beskärningen kring mitten tills de tomma", + "Geometry ▸ Constrain Crop now changes the crop itself, as in Lightroom (issue #1927). Ticking it, or moving a": "Geometri → Begränsa beskärning ändrar nu själva beskärningen, som i Lightroom (ärende #1927). Att kryssa i den, eller flytta ett", + "Grid and filmstrip thumbnails of DNGs that Lightroom merged (HDR, Panorama, HDR Panorama) now develop from the": "Miniatyrer i rutnätet och filmremsan av DNG-filer som Lightroom har sammanfogat (HDR, Panorama, HDR-panorama) framkallas nu från de", + "grid at once and every photo after it moves up. View ▸ Refresh View (also in the sort menu while the hold is on),": "rutnätet på en gång och varje foto efter det flyttas upp. Visa → Uppdatera vy (finns också i sorteringsmenyn medan ordningen hålls kvar),", + "hard edges such as clipped highlights.": "skarpa kanter som klippta högdagrar.", + "Hidden Local locations come back one at a time": "Dolda lokala platser kommer tillbaka en i taget", + "Importing raws with Lightroom XMP sidecars no longer lists settings Lightroom writes only for itself as adjustments": "Import av raw-filer med XMP-sidofiler från Lightroom listar inte längre inställningar som Lightroom bara skriver för egen del som justeringar", + "In Recently Deleted, Set as Reference Photo is greyed out, and a refusal says to restore the photo.": "I Nyligen raderade är Ange som referensfoto nedtonat, och en vägran uppmanar dig att återställa fotot.", + "in the activity stack you can stop. Photo ▸ Read Focus Points runs it by hand.": "i aktivitetsstacken som du kan stoppa. Foto → Läs fokuspunkter kör det manuellt.", + "In the browser version, a library file that exists but can't be read at start-up is no longer taken for a missing": "I webbläsarversionen tas en biblioteksfil som finns men inte kan läsas vid start inte längre för en saknad", + "In the browser version, File ▸ Back Up Library… no longer reports success while a save is failing (storage full or": "I webbläsarversionen rapporterar Arkiv → Säkerhetskopiera bibliotek… inte längre att det lyckades medan en sparning misslyckas (lagringsutrymmet fullt eller", + "it once (issue #1947). Naming one photo three times no longer \"merges\" it with itself, and a long repeated list no": "det en gång (ärende #1947). Att ange ett foto tre gånger ”sammanfogar” det inte längre med sig självt, och en lång upprepad lista", + "it; re-entering Reference chooses a live photo, and restoring the deleted photo makes it pinnable again.": "den; att gå in i Referens igen väljer ett befintligt foto, och om du återställer det raderade fotot kan det låsas igen.", + "keyword left how many photos, and that Edit ▸ Undo puts it back.": "nyckelord som togs bort från hur många foton, och att Redigera → Ångra lägger tillbaka det.", + "Leaving a selected slider disarms its vertical mouse-wheel adjustment (issue #1355), even when the pointer leaves": "Att lämna ett markerat reglage avaktiverar dess justering med det vertikala mushjulet (ärende #1355), även när pekaren lämnar", + "Lens corrections": "Objektivkorrigeringar", + "lenses got no distortion correction at all (more than half of those checked from the XF16-55 and XF70-300), and": "objektiv fick ingen distorsionskorrigering alls (mer än hälften av de kontrollerade från XF16-55 och XF70-300), och", + "Lightroom catalog import": "Import av Lightroom-katalog", + "limit, and each of a server's addresses then got the whole connect timeout of its own.": "tidsgräns, och varje adress hos en server fick sedan hela anslutningstidsgränsen för sig.", + "Local folders you browse are kept": "Lokala mappar du bläddrar i behålls", + "longer decodes the photo again for every entry.": "avkodar inte längre fotot på nytt för varje post.", + "measured. Thumbnails are redrawn when the library next shows them.": "mätts. Miniatyrerna ritas om nästa gång biblioteket visar dem.", + "Merged photos (HDR and panorama) are resampled with a sharper filter (Lanczos-3 instead of bilinear). Moving a": "Sammanfogade foton (HDR och panorama) omsamplas med ett skarpare filter (Lanczos-3 i stället för bilinjärt). Att flytta ett", + "Missing or Recently Deleted photos cannot be pinned. Deleting the pinned reference stops drawing": "Saknade foton och foton i Nyligen raderade kan inte låsas. Om du raderar den låsta referensen slutar den ritas", + "Model downloads (AI denoise, faces, SAM) give up on a server name that doesn't resolve within the connect timeout,": "Modellnedladdningar (AI-brusreducering, ansikten, SAM) ger upp om ett servernamn inte kan slås upp inom anslutningstidsgränsen,", + "Model downloads time out on a name that doesn't resolve": "Modellnedladdningar avbryts efter en tidsgräns när ett namn inte kan slås upp", + "now refuses to start and says how many changes are unsaved and why. LightCraft retries the save with every change;": "vägrar nu att starta och anger hur många ändringar som är osparade och varför. LightCraft försöker spara igen vid varje ändring;", + "number) instead of pinning the active photo; only an absent or null `id` means the active photo.": "bråktal) i stället för att låsa det aktiva fotot; bara ett saknat `id` eller null betyder det aktiva fotot.", + "one (issue #1507). LightCraft used to open the library without it, showing an incomplete catalog that the next save": "fil (ärende #1507). LightCraft öppnade tidigare biblioteket utan den och visade en ofullständig katalog som nästa sparning", + "Opening or creating a different library clears the pinned reference. Photo IDs belong to one": "Om du öppnar eller skapar ett annat bibliotek rensas den låsta referensen. Foto-ID:n hör till en", + "or \"doesn't contain\" rule took about 17 ms per pass instead of about 62 ms, around 3.5 times faster, with the same": "eller ”innehåller inte” cirka 17 ms per genomgång i stället för cirka 62 ms, ungefär 3,5 gånger snabbare, med samma", + "or failed switch keeps both the reference and the Compare pair.": "eller misslyckad växling behåller både referensen och Jämför-paret.", + "or unreadable) are still listed.": "eller oläsbara) listas fortfarande.", + "photo by half a pixel used to lose a third of its finest detail; now it keeps most of it, without halos around": "foto en halv pixel brukade förlora en tredjedel av de finaste detaljerna; nu behålls det mesta, utan halor kring", + "Photo Merge takes each photo once": "Fotosammanfogning tar med varje foto en gång", + "photo was shown outside the Crop tool, so in the Crop panel, where the checkbox is, nothing seemed to change. A crop": "fotot visades utanför Beskärningsverktyget, så i beskärningspanelen, där kryssrutan finns, verkade inget hända. En beskärning", + "Photo ▸ Photo Merge ▸ HDR for Each Bracket Set merges every bracket among the selected photos with the last HDR": "Foto → Fotosammanfogning → HDR för varje gafflingsserie sammanfogar varje gaffling bland de markerade fotona med de senaste HDR", + "photos matched; about 6 ms of that is only reading the paths. Paths and rule text with letters beyond A–Z are": "matchade foton; cirka 6 ms av det är bara att läsa sökvägarna. Sökvägar och regeltext med bokstäver utöver A–Z", + "Pinching the loupe now keeps the size the fit view is rendered at until the gesture is quiet, as it already did for": "När du nyper i luppen behålls nu storleken som den anpassade vyn renderas i tills gesten har avstannat, som det redan gjordes för", + "Portrait crop ratios stay portrait": "Stående beskärningsförhållanden förblir stående", + "portrait crop.": "stående beskärning.", + "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Förhindra G-SYNC/FreeSync-flimmer (gäller vid nästa start)", + "Quotes keep several words together: `person:\"Jane Doe\"` finds exactly that person, `\"jane doe\"` those words side": "Citattecken håller ihop flera ord: `person:\"Jane Doe\"` hittar exakt den personen, `\"jane doe\"` de orden", + "read; reload the page to try again.": "läsas; läs in sidan igen för att försöka på nytt.", + "Reference view reliability": "Referensvyns tillförlitlighet", + "Restore the photo to use it as the reference": "Återställ fotot för att använda det som referens", + "screen with the photo's corner (issue #2267).": "skärmen med fotots hörn (ärende #2267).", + "Scrolling past editing sliders": "Rullning förbi redigeringsreglage", + "Search finds people": "Sökning hittar personer", + "Set them in Settings ▸ Slideshow ▸ Overlays; the slide preview there and View ▸ Slideshow show them. Sizes are a": "Ställ in dem i Inställningar → Bildspel → Överlägg; bildförhandsgranskningen där och Visa → Bildspel visar dem. Storlekar är en", + "Set them in Settings ▸ Slideshow ▸ Titles; the preview there switches between the photo's slide, the intro and the": "Ställ in dem i Inställningar → Bildspel → Titlar; förhandsgranskningen där växlar mellan fotots bild, introt och", + "Set them in Settings ▸ Slideshow, which now shows the selected photo as a slide as you change them (with the margin": "Ställ in dem i Inställningar → Bildspel, som nu visar det markerade fotot som en bild medan du ändrar dem (med marginal", + "Settings ▸ Interface ▸ Keywords of the selection ▸ **Grouped by parent** lays the selected photos' keywords out by": "Inställningar → Gränssnitt → Markeringens nyckelord → **Grupperade efter överordnad** ordnar de markerade fotonas nyckelord efter", + "Settings ▸ Slideshow now opens with a template browser, like Lightroom Classic's Template Browser. A template holds": "Inställningar → Bildspel öppnas nu med en mallbläddrare, som Template Browser i Lightroom Classic. En mall innehåller", + "setup, the crop's \"constrain to image\" option, and the lens profile's strength when it is at its default of 100 %.": "upplägg, beskärningens alternativ ”begränsa till bild” och objektivprofilens styrka när den har standardvärdet 100 %.", + "Sharper resampling in HDR and panorama merges": "Skarpare omsampling vid HDR- och panoramasammanfogning", + "Slideshow templates": "Bildspelsmallar", + "small copies of the raw image Lightroom keeps inside the file (256 to 2048 px), not from the whole merge. A 23836 ×": "små kopior av raw-bilden som Lightroom sparar i filen (256 till 2048 px), inte från hela sammanfogningen. Ett drönarpanorama på 23836 ×", + "Smart albums check File Path rules faster": "Smarta album kontrollerar Sökväg-regler snabbare", + "Sony A7CR distortion correction": "Distorsionskorrigering för Sony A7CR", + "switch over with Photo ▸ Reload from Disk.": "växla över med Foto → Läs in igen från disk.", + "Switching library from Reference view goes to the grid instead of an empty Reference canvas. A refused": "Byte av bibliotek från referensvyn går till rutnätet i stället för till en tom referensarbetsyta. Ett avvisat", + "Synchronize Folder checks a single photo. Its row in the activity stack used to sit at \"0 of 64085\" with an empty": "Synkronisera mapp kontrollerar ett enda foto. Dess rad i aktivitetsstacken stod förut kvar på \"0 av 64085\" med en tom", + "Synchronize Folder on a folder that is up to date": "Synkronisera mapp på en mapp som redan är uppdaterad", + "Synchronize Folder shows that it is listing the folder": "Synkronisera mapp visar att den listar mappen", + "that moves on its own, and then counts the photos it checks. The dialog says the same.": "som rör sig av sig själv, och räknar sedan fotona som den kontrollerar. Dialogrutan visar samma sak.", + "that weren't imported: `CompatibleVersion`, the camera and lens profile checksums, the lens profile's name, file and": "som inte importerades: `CompatibleVersion`, kontrollsummorna för kamera- och objektivprofilen, objektivprofilens namn, fil och", + "The Before label stays in view when zoomed in": "Etiketten Före syns även när du zoomat in", + "the number of days set in Settings → Performance. Only the `library.browse` command recorded it before, so a": "det antal dagar som angetts i Inställningar → Prestanda. Förut registrerades det bara av kommandot `library.browse`, så en", + "The offline place names list towns of 15,000 people or more, so a photo taken in a smaller one got the nearest larger": "Offlinelistan med ortnamn omfattar orter med 15 000 invånare eller fler, så ett foto som tagits i en mindre ort fick närmaste större", + "The photo grid keeps up with imports into a large library": "Fotorutnätet hänger med i importer till ett stort bibliotek", + "the render sizes and windows. Before, each frame of a pinch asked for a new full-frame render at a new size.": "renderingsstorlekarna och fönstren. Förut begärde varje bildruta i en nypgest en ny rendering i full storlek med en ny storlek.", + "The warp also supplies the geometry needed by the lens-aligned camera-look fit in PR #1586. The pairing code is a separate change. Details and numeric validation are in `docs/sony-lens-corrections.md`.": "Förvrängningen ger också den geometri som behövs för anpassningen till kamerans look, linjerad efter objektivet, i PR #1586. Koden för parningen är en separat ändring. Detaljer och numerisk validering finns i `docs/sony-lens-corrections.md`.", + "they are checked the same way. Photos imported earlier get the correction with Photo ▸ Reload from Disk (when still": "de kontrolleras på samma sätt. Foton som importerats tidigare får korrigeringen med Foto → Läs in igen från disk (när de fortfarande", + "Thumbnails of Lightroom HDR and panorama merges in a second": "Miniatyrer av HDR- och panoramasammanslagningar från Lightroom på en sekund", + "to date with the folder and has one Close button. It used to show four greyed choices, two of them still ticked,": "uppdaterat med mappen och har en enda Stäng-knapp. Förut visades fyra nedtonade val, varav två fortfarande var ikryssade,", + "To delete photos from the library from an album, use Photo ▸ Delete Photo or right-click ▸ Delete Photo. In a smart": "Om du vill radera foton från biblioteket när du är i ett album använder du Foto → Radera foto eller högerklick → Radera foto. I ett smart", + "town in City, sometimes another municipality (issue #2242). The Fill Location tooltip and the command help now say so,": "ort i Ort, ibland en annan kommun (ärende #2242). Knappbeskrivningen för Fyll i plats och kommandohjälpen säger nu detta,", + "Typing a person's name in Search Photos finds the photos with that named face (issue #1449).": "Om du skriver en persons namn i Sök foton hittas fotona med det namngivna ansiktet (ärende #1449).", + "under Optics ▸ Enable Lens Corrections, on by default for newly imported photos. On 33 photos shot with the camera's": "under Optik → Aktivera objektivkorrigeringar, påslaget som standard för nyimporterade foton. På 33 foton tagna med kamerans", + "View ▸ Export Slideshow… (or the Export buttons at the end of Settings ▸ Slideshow) writes the slideshow out, like": "Visa → Exportera bildspel… (eller Exportera-knapparna längst ned i Inställningar → Bildspel) skriver ut bildspelet, som", + "View ▸ Hold View Until Refreshed (off unless you turn it on; kept with the library). With it on, an edit that makes": "Visa → Behåll vyn tills den uppdaterats (av om du inte slår på det; sparas med biblioteket). När det är påslaget gäller att en redigering som", + "View ▸ Loupe Overlay ▸ Choose Layout Image… draws a PNG with transparency over the photo in the loupe, such as": "Visa → Lupöverlägg → Välj layoutbild… ritar en PNG med transparens över fotot i lupen, till exempel", + "View ▸ Slideshow (⌥⌘↩) now plays with Lightroom Classic's Playback settings: how long each slide stays up, a fade": "Visa → Bildspel (⌥⌘↩) spelas nu upp med uppspelningsinställningarna från Lightroom Classic: hur länge varje bild visas, en toning", + "View ▸ Slideshow plays the composed slides, prepared ahead off the UI thread like before, so fades and the playback": "Visa → Bildspel spelar upp de sammansatta bilderna, som förut förberedda i förväg utanför gränssnittstråden, så att toningar och uppspelningens", + "Web: an unreadable library is not opened": "Webb: ett oläsbart bibliotek öppnas inte", + "Web: no backup that misses unsaved changes": "Webb: ingen säkerhetskopia som saknar osparade ändringar", + "When presets.json can't be written (a full disk, or the browser's storage quota), the new or changed preset now": "När presets.json inte kan skrivas (full disk eller webbläsarens lagringskvot) kommer den nya eller ändrade förinställningen nu att", + "When the scan finds nothing to import, relink, remove or read, the Synchronize Folder dialog says the library is up": "När genomsökningen inte hittar något att importera, länka om, ta bort eller läsa, säger dialogrutan Synkronisera mapp att biblioteket är", + "which is slow on a network share.": "vilket går långsamt på en nätverksresurs.", + "While photos are imported into a large library, the grid takes in each batch as it arrives instead of reading": "Medan foton importeras till ett stort bibliotek tar rutnätet emot varje batch när den kommer i stället för att läsa", + "With several locations removed from Local, \"Show N hidden locations\" now lists them, so each comes back on its own": "När flera platser har tagits bort från Lokalt listar \"Visa N dolda platser\" nu dem, så att var och en kan tas tillbaka för sig", + "would write over the stored copy. It now leaves the library unopened, saves nothing and says which file couldn't be": "skulle skriva över den lagrade kopian. Nu lämnas biblioteket oöppnat, ingenting sparas och du får veta vilken fil som inte kunde", + "X-T4 raws now read the lens's own distortion and vignetting tables the way the camera does. Many photos from zoom": "X-T4-råfiler läser nu objektivets egna distorsions- och vinjetteringstabeller på samma sätt som kameran. Många foton från zoom", + "you draw by hand is kept as drawn, and unticking keeps the tighter crop.": "som du ritar för hand behålls som du ritat den, och om du kryssar ur behålls den snävare beskärningen.", + "Zoomed in, the \"Before\" label (\\ key or the Before view) now sits at the canvas' corner instead of leaving the": "Inzoomat sitter etiketten \"Före\" (tangenten \\ eller vyn Före) nu i arbetsytans hörn i stället för att lämna", + "✕ on the row stops the listing too, not only the checks after it.": "× på raden stoppar även listningen, inte bara kontrollerna efter den.", + "1 photo got its lens profile": "1 foto fick sin objektivprofil", + "Camera preview": "Kamerans förhandsgranskning", + "Cancel Pending Photo Action": "Avbryt väntande fotoåtgärd", + "default": "standard", + "Downloading the lens database": "Laddar ner objektivdatabasen", + "Downloading the lens database…": "Laddar ner objektivdatabasen…", + "For example, a timelapse library can prepare nothing while a wedding library prepares everything.": "Ett timelapse-bibliotek kan till exempel inte förbereda något alls, medan ett bröllopsbibliotek förbereder allt.", + "Grid thumbnails and the previews the loupe shows, kept on disk so photos open at once next time. Automatic makes room for every photo in this library (about 1.5 MB a photo). 50 GB: normal · 200 GB: better, for several weddings or large shoots.": "Miniatyrerna i rutnätet och förhandsgranskningarna som luppen visar sparas på disken så att fotona öppnas direkt nästa gång. Automatisk ger plats åt varje foto i det här biblioteket (cirka 1,5 MB per foto). 50 GB: normalt · 200 GB: bättre, för flera bröllop eller stora fotograferingar.", + "Hot pixel limit": "Gränsvärde för heta pixlar", + "Looking up lens profiles": "Söker objektivprofiler", + "Photos ahead": "Foton i förväg", + "Prepare photos in the background": "Förbered foton i bakgrunden", + "Preview cache": "Cache för förhandsgranskningar", + "Profile: from the file (the camera's own correction)": "Profil: från filen (kamerans egen korrigering)", + "Remove Hot Pixels": "Ta bort heta pixlar", + "Remove Hot Pixels (Detail) leaves a raw unchanged when more than this share of its photosites would be replaced: such a photo doesn't look like hot pixels on a sensor.": "Ta bort heta pixlar (Detalj) lämnar en raw-fil oförändrad när mer än den här andelen av dess sensorpixlar skulle ersättas: ett sådant foto ser inte ut som heta pixlar på en sensor.", + "Starts once you step through a few photos. Uses about 1.5 MB of disk a photo, and the computer's spare time.": "Startar när du har stegat igenom några foton. Använder cirka 1,5 MB disk per foto och datorns lediga tid.", + "Stop using": "Sluta använda", + "The camera's own JPEG, shown until LightCraft has rendered the raw. Judge colour and tone on the rendered photo.": "Kamerans egen JPEG, som visas tills LightCraft har renderat raw-filen. Bedöm färg och ton på det renderade fotot.", + "The lens database could not be downloaded. LightCraft tries again the next time it starts.": "Objektivdatabasen kunde inte laddas ner. LightCraft försöker igen nästa gång programmet startar.", + "The next photos are opened and kept ready to edit, so the first slider move on them is quick. Uses memory: a few hundred MB a photo.": "Nästa foton öppnas och hålls redo för redigering, så att den första reglaget du drar i går snabbt. Använder minne: några hundra MB per foto.", + "This file names no lens.": "Den här filen anger inget objektiv.", + "Which photos": "Vilka foton", + "While you go through photos in the loupe, the next ones are made ready before you reach them, and when the computer is otherwise idle the previews of every photo in view are built. The photo on screen always comes first; the work shows in the activity list, where it can be stopped.": "Medan du går igenom foton i luppen förbereds nästa foton innan du kommer till dem, och när datorn annars är ledig byggs förhandsgranskningarna för alla foton i vyn. Fotot på skärmen kommer alltid först; arbetet visas i aktivitetslistan, där det kan stoppas.", + "AI masks": "AI-masker", + "Device": "Enhet", + "Last photo": "Senaste foto", + "Remote worker": "Fjärrarbetare", + "Run on": "Kör på", + "Automatic (GPU when available)": "Automatisk (GPU när den finns)", + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer.": "Objekt- och Beskriv-masker analyserar varje foto en gång, på grafikkortet om inte CPU är vald eller ”Använd GPU:n för rendering” är av. På processorn tar det mycket längre tid.", + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "Automatisk kör modellen på Macens grafikkort. Välj CPU om AI-masker misslyckas där; på processorn tar de mycket längre tid.", "User Templates": "Användarmallar", "Delete Folder": "Radera mapp", "Folder name": "Mappnamn", "Its templates move to User Templates.": "Dess mallar flyttas till Användarmallar.", "Stopped at the scan limit: there may be more photos": "Stoppade vid skanningsgränsen: det kan finnas fler foton", + "Keywords and presets apply to new files only, not to photos already in Local": "Nyckelord och förinställningar gäller bara nya filer, inte foton som redan finns i Lokalt", + "This album is in a loop, so it shows nothing": "Det här albumet ingår i en loop och visar därför ingenting", + "It tests itself: change its rules (Edit Smart Album…)": "Det testar sig självt: ändra dess regler (Redigera smart album…)", + "Filter settings": "Filtrera inställningar", + "No setting matches what is typed.": "Ingen inställning matchar det som skrivits.", + "Try one word, or part of one: the names of tabs and sections, labels and explanations are all looked through.": "Prova ett ord eller en del av ett: namnen på flikar och avsnitt, etiketter och förklaringar genomsöks.", + "name for a saved preset": "namn på en sparad förinställning", + "Saved as a preset": "Sparat som förinställning", + "Set on every photo this import adds, after its XMP sidecar and the preset above; photos the library already has are left alone. A slider left at its default changes nothing. Nothing is saved unless you save it as a preset.": "Anges på varje foto som den här importen lägger till, efter dess XMP-sidofil och förinställningen ovanför; foton som redan finns i biblioteket lämnas orörda. Ett reglage som står kvar på standardvärdet ändrar ingenting. Ingenting sparas om du inte sparar det som en förinställning.", + "A smart album's rules choose its photos: change them with Edit Smart Album…": "Ett smart albums regler väljer dess foton: ändra dem med Redigera smart album…", + "Add keywords in the Keyword List": "Lägg till nyckelord i nyckelordslistan", + "Already on these photos": "Finns redan på de här fotona", + "An album folder holds albums, not photos: drop on an album inside it": "En albummapp innehåller album, inte foton: släpp på ett album i den", + "Can't add to a smart album": "Kan inte läggas till i ett smart album", + "Can't add to an album folder": "Kan inte läggas till i en albummapp", + "Can't go inside itself": "Kan inte läggas inuti sig själv", + "Demo photos have no file on disk, so they can't be moved": "Demofoton har ingen fil på disken och kan därför inte flyttas", + "Give photos a keyword in the Keyword List (Window → Keywords, K): drop them on it there": "Ge foton ett nyckelord i nyckelordslistan (Fönster → Nyckelord, K): släpp dem på det där", + "Same Content as Another Photo": "Samma innehåll som ett annat foto", "Reduce Motion": "Minska rörelse", "Reduce motion": "Minska rörelse", "Turns off zoom and spinner animations. Fades stay.": "Stänger av zoom- och snurranimationer. Toningar finns kvar.", @@ -2536,5 +3892,11 @@ "Stack — click to expand (S)": "Stapel — klicka för att expandera (S)", "Stars on hover": "Stjärnor vid pekaren", "Stars on hover: flags and colour labels always show; the stars and the edited mark appear while a photo is hovered or selected.": "Stjärnor vid pekaren: flaggor och färgetiketter visas alltid; stjärnorna och märket för redigerad visas när pekaren är över ett foto eller när det är markerat.", - "Virtual copy": "Virtuell kopia" + "Virtual copy": "Virtuell kopia", + "Album name (empty outside an album view)": "Albumnamn (tomt utanför en albumvy)", + "Export date (YYYYMMDD)": "Exportdatum (YYYYMMDD)", + "Export time (HHMM)": "Exporttid (HHMM)", + "Insert variable": "Infoga variabel", + "Insert…": "Infoga…", + "none ({album}, {date}, {hour})": "ingen ({album}, {date}, {hour})" } diff --git a/crates/ui-egui/locales/uk-formats.json b/crates/ui-egui/locales/uk-formats.json index 3871bc75af..02d5708de0 100644 --- a/crates/ui-egui/locales/uk-formats.json +++ b/crates/ui-egui/locales/uk-formats.json @@ -306,10 +306,10 @@ "{what} merge added at {mp}: its full size, {full}, needs more memory than this computer has": "{what}: об’єднання додано в розмірі {mp}: для повного розміру ({full}) бракує пам’яті цього комп’ютера", "{what} merge added at {mp}, the largest a panorama can be (its full size is {full})": "{what}: об’єднання додано в розмірі {mp} — це найбільший розмір панорами (повний розмір: {full})", "Already in “{}”": "Уже в «{}»", - "Move {n} photo{} to “{}”": "Перемістити до «{1}» фото: {n}{0:.0}", - "Move {n} photo{} to “{}”?": "Перемістити до «{1}» фото: {n}{0:.0}?", + "Move {n} file{} to “{}”": "Перемістити до «{1}» файлів: {n}{0:.0}", + "Move {n} file{} to “{}”?": "Перемістити до «{1}» файлів: {n}{0:.0}?", "Listing folders — folders: {folders}, files: {files}": "Перегляд тек — тек: {folders}, файлів: {files}", - "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "До «{1}» переміщено фото: {n}{0:.0}. Редагування → Скасувати поверне їх.", + "Moved {n} file{} to “{}”. Edit → Undo moves them back.": "До «{1}» переміщено файлів: {n}{0:.0}. Редагування → Скасувати поверне їх.", "Drop to review {n} item{} for import": "Відпустіть для перегляду перед імпортом (елементів: {n}){:.0}", "Drop to import {n} item{}": "Відпустіть для імпорту (елементів: {n}){:.0}", "Drop to import {n} preset{}": "Відпустіть для імпорту наборів налаштувань: {n}{:.0}", @@ -325,9 +325,14 @@ "Panel move was not applied: {error}": "Переміщення панелі не застосовано: {error}", "{name} is installed": "{name} установлено", "{name} is installed and in use: face recognition is on": "{name} установлено й використовується: розпізнавання облич увімкнено", + "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} с, кодувальник зображення {encoder:.1} с", "Bring photos in with File › Import Photos… ({keys}).": "Фотографії імпортуйте через Файл › Імпортувати фото… ({keys}).", "View › Detail View ({keys}).": "Вигляд › Детальне подання ({keys}).", "File › Export… · File › Print… ({keys}).": "Файл › Експортувати… · Файл › Друк… ({keys}).", + "It leads back to itself through “{}”: change the rules of one album on the loop (Edit Smart Album…)": "Він повертається до себе через альбом «{}»: змініть правила одного з альбомів у циклі (Редагувати смарт-альбом…)", + "Add {n} photo{} to “{}”": "Додати до «{1}» фото: {n}{0:.0}", + "{n} already there": "{n} уже там", + "Add “{keyword}” to {n} photo{}": "Додати «{keyword}» до фото: {n}{:.0}", "Rule {n} of {m}: {what}. Move with the arrow keys": "Правило {n} з {m}: {what}. Переміщення стрілками", "Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "Група {n} з {m}: збіг {mode}, усередині {count}. Переміщення стрілками", ", rating {} of 5": ", оцінка: {} з 5" diff --git a/crates/ui-egui/locales/uk.json b/crates/ui-egui/locales/uk.json index 2772aeb8e2..50b3c37ba2 100644 --- a/crates/ui-egui/locales/uk.json +++ b/crates/ui-egui/locales/uk.json @@ -325,6 +325,7 @@ "Window": "Вікно", "Wrote the XMP sidecars that were waiting": "XMP-файли, що очікували, записано", "Yellow": "Жовтий", + "White": "Білий", "Yes": "Так", "Zoom": "Масштаб", "Zoom In": "Збільшити", @@ -398,6 +399,7 @@ "Can't be moved here": "Сюди перемістити не можна", "This row covers more than one disk: drop on a folder inside it": "Цей рядок охоплює кілька дисків: перетягніть на теку всередині нього", "Local photos aren't in the library yet: Add to My Photos first, then move them": "Локальних фото ще немає в бібліотеці: спершу «Додати до моїх фото», потім переміщуйте", + "Demo photos have no file on disk, so they can't be moved": "Демонстраційні фото не мають файлу на диску, тому їх не можна перемістити", "Add to Selected Photos": "Додати до вибраних фото", "Add to Target Album": "Додати до цільового альбому", "Add to this mask": "Додати до цієї маски", @@ -478,6 +480,7 @@ "Before/After (Y)": "До/після (Y)", "Before/After Settings": "Налаштування до/після", "Before/After Split": "Розділення до/після", + "Before/After": "До/після", "Before/After Split Top/Bottom": "Розділення до/після зверху/знизу", "Before/After Top/Bottom": "До/після зверху/знизу", "Begin Interaction": "Почати взаємодію", @@ -621,6 +624,7 @@ "Change Time": "Змінити час", "Custom template…": "Власний шаблон…", "Cycle Crop Overlay": "Перемкнути накладання кадрування", + "Crop Overlay": "Накладання кадрування", "Cycle Crop Overlay Orientation": "Перемкнути орієнтацію накладання кадрування", "Cycle Info Overlay": "Перемкнути накладання інформації", "Cycle Mask Overlay Color": "Перемкнути колір накладання маски", @@ -2191,6 +2195,9 @@ "Appearance Settings…": "Налаштування вигляду…", "Add to favorites": "Додати до вибраного", "Remove from favorites": "Видалити з вибраного", + "Filter settings": "Фільтр налаштувань", + "No setting matches what is typed.": "Немає налаштувань, що відповідають введеному.", + "Try one word, or part of one: the names of tabs and sections, labels and explanations are all looked through.": "Спробуйте одне слово або його частину: пошук ведеться за назвами вкладок і розділів, підписами та поясненнями.", "Appearance": "Вигляд", "Appearance Mode": "Режим вигляду", "Sync with System": "Як у системі", @@ -2398,6 +2405,13 @@ "The photos are imported once it ends": "Фото буде імпортовано після цього", "An import is running. Drop photos when it has finished": "Імпорт уже виконується. Перетягніть фото, коли він завершиться", "Finish Lightroom catalog import before adding photos": "Завершіть імпорт каталогу Lightroom, перш ніж додавати фото", + "Mixer": "Змішувач", + "HSL": "HSL", + "Adjust": "Налаштування", + "Color Mixer Layout": "Вигляд змішувача кольорів", + "Loupe Overlay": "Накладання лупи", + "View Options…": "Параметри перегляду…", + "View → Loupe Overlay → View Options chooses the lines Info 1 and Info 2 show.": "Вигляд → Накладання лупи → Параметри перегляду вибирає рядки, які показують Info 1 та Info 2.", "Camera preview": "Прев'ю камери", "The camera's own JPEG, shown until LightCraft has rendered the raw. Judge colour and tone on the rendered photo.": "Власний JPEG камери, показаний, доки LightCraft не обробить RAW. Оцінюйте колір і тон за обробленим фото.", "Profile: from the file (the camera's own correction)": "Профіль: з файлу (корекція самої камери)", @@ -2432,6 +2446,14 @@ "Tool strip": "Панель інструментів", "Bottom bar": "Нижня панель", "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Запобігати мерехтінню G-SYNC/FreeSync (після перезапуску)", + "AI masks": "ШІ-маски", + "Device": "Пристрій", + "Last photo": "Останнє фото", + "Remote worker": "Віддалений обробник", + "Run on": "Виконувати на", + "Automatic (GPU when available)": "Автоматично (ГП, якщо є)", + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer.": "Маски «Об’єкт» і «Описати» аналізують кожне фото один раз — на відеокарті, якщо не вибрано ЦП і не вимкнено «Використовувати ГП для рендерингу». На процесорі це значно довше.", + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "«Автоматично» запускає модель на відеокарті Mac. Якщо ШІ-маски там не працюють, виберіть ЦП; на процесорі вони значно довші.", "User Templates": "Власні шаблони", "Delete Folder": "Видалити теку", "Folder name": "Назва теки", @@ -2458,6 +2480,18 @@ "Welcome": "Ласкаво просимо", "Next": "Далі", "Get Started": "Почати", + "Keywords and presets apply to new files only, not to photos already in Local": "Ключові слова та пресети застосовуються лише до нових файлів, а не до фото, що вже є в «Локальних»", + "This album is in a loop, so it shows nothing": "Цей альбом потрапив у цикл, тому нічого не показує", + "It tests itself: change its rules (Edit Smart Album…)": "Він перевіряє сам себе: змініть його правила (Редагувати смарт-альбом…)", + "Can't add to an album folder": "Не можна додати до теки альбомів", + "An album folder holds albums, not photos: drop on an album inside it": "У теці альбомів лежать альбоми, а не фото: киньте на альбом усередині неї", + "Can't add to a smart album": "Не можна додати до смарт-альбому", + "A smart album's rules choose its photos: change them with Edit Smart Album…": "Фото смарт-альбому визначаються його правилами: змініть їх через «Редагувати смарт-альбом…»", + "Add keywords in the Keyword List": "Додавайте ключові слова у списку ключових слів", + "Give photos a keyword in the Keyword List (Window → Keywords, K): drop them on it there": "Щоб задати фото ключове слово, скористайтеся списком ключових слів (Вікно → Ключові слова, K): киньте фото там на потрібне слово", + "Already on these photos": "Уже є в цих фото", + "Can't go inside itself": "Не можна помістити всередину себе", + "Same Content as Another Photo": "Той самий вміст, що й в іншого фото", "Reduce Motion": "Зменшити рух", "Reduce motion": "Зменшити рух", "Turns off zoom and spinner animations. Fades stay. Follows the system's Reduce Motion until you change it here.": "Вимикає анімацію масштабування та індикаторів роботи. Плавні згасання залишаються. Доки ви не зміните це тут, діє системне налаштування «Зменшити рух».", @@ -2470,5 +2504,11 @@ "Stack — click to collapse (S)": "Стос — клацніть, щоб згорнути (S)", "Virtual copy": "Віртуальна копія", "Right-click ▸ Locate Missing File… to find it again.": "Клацніть правою кнопкою → Знайти відсутній файл…, щоб знайти його знову.", - "Right-click ▸ Reload from Disk to try again.": "Клацніть правою кнопкою → Перезавантажити з диска, щоб спробувати ще раз." + "Right-click ▸ Reload from Disk to try again.": "Клацніть правою кнопкою → Перезавантажити з диска, щоб спробувати ще раз.", + "Album name (empty outside an album view)": "Назва альбому (порожньо поза переглядом альбому)", + "Export date (YYYYMMDD)": "Дата експорту (YYYYMMDD)", + "Export time (HHMM)": "Час експорту (HHMM)", + "Insert variable": "Вставити змінну", + "Insert…": "Вставити…", + "none ({album}, {date}, {hour})": "немає ({album}, {date}, {hour})" } diff --git a/crates/ui-egui/locales/vi-formats.json b/crates/ui-egui/locales/vi-formats.json index 883b61f05e..75606d1563 100644 --- a/crates/ui-egui/locales/vi-formats.json +++ b/crates/ui-egui/locales/vi-formats.json @@ -130,10 +130,10 @@ "Making the denoised picture… {}%": "Đang tạo ảnh đã khử nhiễu… {}%", "Matches: {}": "Khớp: {}", "Merging… {stage} {:.0}%": "Đang ghép… {stage} {:.0}%", - "Move {n} photo{} to “{}”": "Move {n} photo{} to “{}”", - "Move {n} photo{} to “{}”?": "Move {n} photo{} to “{}”?", + "Move {n} file{} to “{}”": "Move {n} file{} to “{}”", + "Move {n} file{} to “{}”?": "Move {n} file{} to “{}”?", "Move {what} to Recently Deleted?": "Chuyển {what} vào Đã xóa gần đây?", - "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "Moved {n} photo{} to “{}”. Edit → Undo moves them back.", + "Moved {n} file{} to “{}”. Edit → Undo moves them back.": "Moved {n} file{} to “{}”. Edit → Undo moves them back.", "Moved {} photo(s)": "Đã di chuyển {} ảnh", "Moved; {} photo(s) relinked": "Đã di chuyển; liên kết lại {} ảnh", "Named ({named_n})": "Có tên ({named_n})", @@ -319,11 +319,16 @@ "Panel move was not applied: {error}": "Việc di chuyển bảng chưa được áp dụng: {error}", "{name} is installed": "{name} đã được cài đặt", "{name} is installed and in use: face recognition is on": "{name} đã được cài đặt và đang dùng: nhận diện khuôn mặt đã bật", + "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} giây, bộ mã hóa ảnh {encoder:.1} giây", "Bring photos in with File › Import Photos… ({keys}).": "Đưa ảnh vào bằng Tệp › Nhập ảnh… ({keys}).", "View › Detail View ({keys}).": "Xem › Chế độ xem chi tiết ({keys}).", "File › Export… · File › Print… ({keys}).": "Tệp › Xuất… · Tệp › In… ({keys}).", "{n} folder{} could not be read": "Thư mục không đọc được: {n}{:.0}", "{n} file{} skipped (not a supported photo type)": "Đã bỏ qua tệp (không phải loại ảnh được hỗ trợ): {n}{:.0}", + "It leads back to itself through “{}”: change the rules of one album on the loop (Edit Smart Album…)": "Album này quay lại chính nó qua album «{}»: hãy đổi quy tắc của một album trong vòng lặp (Chỉnh sửa album thông minh…)", + "Add {n} photo{} to “{}”": "Thêm {n} ảnh{0:.0} vào “{1}”", + "Add “{keyword}” to {n} photo{}": "Thêm “{keyword}” vào {n} ảnh{:.0}", + "{n} already there": "{n} đã có sẵn", "Rule {n} of {m}: {what}. Move with the arrow keys": "Quy tắc {n}/{m}: {what}. Di chuyển bằng phím mũi tên", "Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "Nhóm {n}/{m}: khớp {mode}, bên trong: {count}. Di chuyển bằng phím mũi tên", ", rating {} of 5": ", xếp hạng: {} trên 5" diff --git a/crates/ui-egui/locales/vi.json b/crates/ui-egui/locales/vi.json index bd5c8bc112..5eba595eed 100644 --- a/crates/ui-egui/locales/vi.json +++ b/crates/ui-egui/locales/vi.json @@ -182,6 +182,7 @@ "Balance": "Cân bằng", "Basic": "Cơ bản", "Before": "Trước", + "Before/After": "Trước/Sau", "Before/After (Y)": "Trước/Sau (Y)", "Before/After Settings": "Cài đặt Trước/Sau", "Before/After Split": "Chia Trước/Sau", @@ -409,6 +410,7 @@ "Crop & Rotate": "Cắt và xoay", "Crop & Rotate (C)": "Cắt và xoay (C)", "Crop Aspect": "Tỷ lệ cắt", + "Crop Overlay": "Lớp phủ cắt", "Crop, Rotate, Geometry": "Cắt, xoay, hình học", "Cropped": "Đã cắt", "Cross Process": "Cross Process", @@ -2003,6 +2005,7 @@ "We": "T4", "Wednesday": "Thứ Tư", "What's New": "Có gì mới", + "White": "Trắng", "White Balance": "Cân bằng trắng", "White Balance Selector": "Bộ chọn cân bằng trắng", "White Balance Selector (W)": "Bộ chọn cân bằng trắng (W)", @@ -2723,6 +2726,7 @@ "Use Defaults": "Dùng mặc định", "View Options": "Tùy chọn hiển thị", "View Options…": "Tùy chọn hiển thị…", + "View → Loupe Overlay → View Options chooses the lines Info 1 and Info 2 show.": "Xem → Lớp phủ kính lúp → Tùy chọn xem chọn các dòng mà Info 1 và Info 2 hiển thị.", "View → View Options chooses the lines Info 1 and Info 2 show.": "Xem → Tùy chọn hiển thị để chọn các dòng hiển thị trong Thông tin 1 và Thông tin 2.", "When importing a Lightroom catalog": "Khi nhập danh mục Lightroom", "Width & Height": "Chiều rộng & Chiều cao", @@ -2741,11 +2745,35 @@ "Top bar": "Thanh trên cùng", "Tool strip": "Thanh công cụ", "Bottom bar": "Thanh dưới cùng", + "AI masks": "Mặt nạ AI", + "Device": "Thiết bị", + "Last photo": "Ảnh gần nhất", + "Remote worker": "Worker từ xa", + "Run on": "Chạy trên", + "Automatic (GPU when available)": "Tự động (GPU nếu có)", + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer.": "Mặt nạ Đối tượng và Mô tả phân tích mỗi ảnh một lần, trên card đồ họa trừ khi chọn CPU hoặc tắt “Dùng GPU để kết xuất”. Trên bộ xử lý việc này lâu hơn nhiều.", + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "Tự động chạy mô hình trên card đồ họa của máy Mac. Hãy chọn CPU nếu mặt nạ AI bị lỗi ở đó; trên bộ xử lý chúng chạy lâu hơn nhiều.", "User Templates": "Mẫu người dùng", "Delete Folder": "Xóa thư mục", "Folder name": "Tên thư mục", "Its templates move to User Templates.": "Các mẫu trong đó sẽ được chuyển vào Mẫu người dùng.", "Stopped at the scan limit: there may be more photos": "Đã dừng ở giới hạn quét: có thể còn ảnh khác", + "Keywords and presets apply to new files only, not to photos already in Local": "Từ khóa và cài đặt sẵn chỉ áp dụng cho tệp mới, không áp dụng cho ảnh đã có trong Cục bộ", + "This album is in a loop, so it shows nothing": "Album này nằm trong một vòng lặp nên không hiển thị gì", + "It tests itself: change its rules (Edit Smart Album…)": "Album này tự kiểm tra chính nó: hãy đổi quy tắc của nó (Chỉnh sửa album thông minh…)", + "Filter settings": "Lọc cài đặt", + "No setting matches what is typed.": "Không có cài đặt nào khớp với nội dung đã nhập.", + "Try one word, or part of one: the names of tabs and sections, labels and explanations are all looked through.": "Hãy thử một từ hoặc một phần của từ: tên các tab và mục, nhãn và phần giải thích đều được tìm.", + "A smart album's rules choose its photos: change them with Edit Smart Album…": "Quy tắc của album thông minh chọn ảnh của nó: thay đổi bằng Chỉnh sửa album thông minh…", + "Add keywords in the Keyword List": "Thêm từ khóa trong Danh sách từ khóa", + "Already on these photos": "Đã có trên các ảnh này", + "An album folder holds albums, not photos: drop on an album inside it": "Thư mục album chứa album, không chứa ảnh: hãy thả vào một album bên trong nó", + "Can't add to a smart album": "Không thể thêm vào album thông minh", + "Can't add to an album folder": "Không thể thêm vào thư mục album", + "Can't go inside itself": "Không thể đặt vào chính nó", + "Demo photos have no file on disk, so they can't be moved": "Ảnh demo không có tệp trên đĩa nên không thể di chuyển", + "Give photos a keyword in the Keyword List (Window → Keywords, K): drop them on it there": "Gán từ khóa cho ảnh trong Danh sách từ khóa (Cửa sổ → Từ khóa, K): hãy thả ảnh lên từ khóa ở đó", + "Same Content as Another Photo": "Cùng nội dung với ảnh khác", "Reduce Motion": "Giảm chuyển động", "Reduce motion": "Giảm chuyển động", "Turns off zoom and spinner animations. Fades stay.": "Tắt hiệu ứng phóng to và biểu tượng xoay. Hiệu ứng mờ dần vẫn được giữ nguyên.", @@ -2760,5 +2788,11 @@ "Stack — click to expand (S)": "Chồng — nhấp để mở rộng (S)", "Stars on hover": "Sao khi rê chuột", "Stars on hover: flags and colour labels always show; the stars and the edited mark appear while a photo is hovered or selected.": "Sao khi rê chuột: cờ và nhãn màu luôn hiển thị; sao và dấu đã chỉnh sửa xuất hiện khi ảnh được rê chuột qua hoặc được chọn.", - "Virtual copy": "Bản sao ảo" + "Virtual copy": "Bản sao ảo", + "Album name (empty outside an album view)": "Tên album (trống ngoài chế độ xem album)", + "Export date (YYYYMMDD)": "Ngày xuất (YYYYMMDD)", + "Export time (HHMM)": "Giờ xuất (HHMM)", + "Insert variable": "Chèn biến", + "Insert…": "Chèn…", + "none ({album}, {date}, {hour})": "không có ({album}, {date}, {hour})" } diff --git a/crates/ui-egui/locales/zh-hans-formats.json b/crates/ui-egui/locales/zh-hans-formats.json index 360f2f43f9..1c4bee97fb 100644 --- a/crates/ui-egui/locales/zh-hans-formats.json +++ b/crates/ui-egui/locales/zh-hans-formats.json @@ -44,10 +44,10 @@ "LightCraft could not open its window: {e}\n\nThe log file has the details: {path}": "LightCraft 无法打开窗口:{e}\n\n详细信息见日志文件:{path}", "Matches: {}": "匹配项:{0}", "Merging… {stage} {:.0}%": "合成中… {stage} {0:.0}%", - "Move {n} photo{} to “{}”": "将 {n} 张照片移到“{1}”{0:.0}", - "Move {n} photo{} to “{}”?": "将 {n} 张照片移到“{1}”?{0:.0}", + "Move {n} file{} to “{}”": "将 {n} 个文件移到“{1}”{0:.0}", + "Move {n} file{} to “{}”?": "将 {n} 个文件移到“{1}”?{0:.0}", "Move {what} to Recently Deleted?": "将 {what} 移到最近删除?", - "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "已将 {n} 张照片移到“{1}”{0:.0}。编辑 → 撤销 可移回。", + "Moved {n} file{} to “{}”. Edit → Undo moves them back.": "已将 {n} 个文件移到“{1}”{0:.0}。编辑 → 撤销 可移回。", "Named ({named_n})": "已命名({named_n})", "Paste into {n} photo{} — only settings that were copied are pasted": "粘贴到 {n} 张照片 — 仅粘贴已复制的设置{0:.0}", "Preset: {name}": "预设:{name}", @@ -325,9 +325,14 @@ "Panel move was not applied: {error}": "面板移动未应用:{error}", "{name} is installed": "{name} 已安装", "{name} is installed and in use: face recognition is on": "{name} 已安装并在使用:人脸识别已开启", + "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} 秒,图像编码器 {encoder:.1} 秒", "Bring photos in with File › Import Photos… ({keys}).": "通过 文件 › 导入照片… ({keys}) 导入照片。", "View › Detail View ({keys}).": "视图 › 详细视图 ({keys})。", "File › Export… · File › Print… ({keys}).": "文件 › 导出… · 文件 › 打印… ({keys})。", + "It leads back to itself through “{}”: change the rules of one album on the loop (Edit Smart Album…)": "它通过相册“{0}”回到自身:请更改循环中某个相册的规则(编辑智能相册…)", + "Add {n} photo{} to “{}”": "将 {n} 张照片添加到“{1}”{0:.0}", + "{n} already there": "{n} 张已在其中", + "Add “{keyword}” to {n} photo{}": "将“{keyword}”添加到 {n} 张照片{:.0}", "Rule {n} of {m}: {what}. Move with the arrow keys": "规则 {n}/{m}:{what}。用方向键移动", "Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "组 {n}/{m}:匹配{mode},内含 {count} 项。用方向键移动", ", rating {} of 5": ",评分:{}/5" diff --git a/crates/ui-egui/locales/zh-hans.json b/crates/ui-egui/locales/zh-hans.json index 9a117ea928..25495f0504 100644 --- a/crates/ui-egui/locales/zh-hans.json +++ b/crates/ui-egui/locales/zh-hans.json @@ -47,6 +47,7 @@ "Import photos with File → Import Photos…, or drop them here": "使用“文件 → 导入照片…”导入照片,或将照片拖放到此处", "This row covers more than one disk: drop on a folder inside it": "此行涵盖多个磁盘:请拖放到其中的文件夹", "Local photos aren't in the library yet: Add to My Photos first, then move them": "本地照片尚未在图库中:请先“添加到我的照片”,再移动", + "Demo photos have no file on disk, so they can't be moved": "演示照片在磁盘上没有文件,因此无法移动", "Add to Selected Photos": "添加到所选照片", "Add to Target Album": "添加到目标相册", "Add to this mask": "添加到此蒙版", @@ -143,6 +144,7 @@ "Before/After (Y)": "修改前/修改后 (Y)", "Before/After Settings": "修改前/修改后设置", "Before/After Split": "修改前/修改后分屏", + "Before/After": "修改前/修改后", "Before/After Split Top/Bottom": "修改前/修改后上下分屏", "Before/After Top/Bottom": "修改前/修改后上下排列", "Begin Interaction": "开始交互", @@ -350,6 +352,7 @@ "Cut": "剪切", "Cut pages": "剪切页面", "Cycle Crop Overlay": "切换裁切叠加", + "Crop Overlay": "裁切叠加", "Cycle Crop Overlay Orientation": "切换裁切叠加方向", "Cycle Info Overlay": "切换信息叠加", "Cycle Mask Overlay Color": "切换蒙版叠加颜色", @@ -1598,6 +1601,7 @@ "XMP sidecars": "XMP 附属文件", "Year": "年", "Yellow": "黄色", + "White": "白色", "Yellow Hue": "黄色色相", "Yellow Luminance": "黄色明度", "Yellow Saturation": "黄色饱和度", @@ -1935,6 +1939,9 @@ "Not saved": "未保存", "A folder is being synchronized": "正在同步文件夹", "Wait for the import to finish": "请等待导入完成", + "Filter settings": "筛选设置", + "No setting matches what is typed.": "没有与输入内容匹配的设置。", + "Try one word, or part of one: the names of tabs and sections, labels and explanations are all looked through.": "请尝试一个词或词的一部分:会搜索标签页和分区的名称、标签和说明。", "Appearance": "外观", "Appearance Mode": "外观模式", "Sync with System": "与系统同步", @@ -2245,6 +2252,13 @@ "The photos are imported once it ends": "结束后即导入这些照片", "An import is running. Drop photos when it has finished": "正在导入。导入完成后再拖放照片", "Finish Lightroom catalog import before adding photos": "添加照片前,请先完成 Lightroom 目录的导入", + "Mixer": "混合器", + "HSL": "HSL", + "Adjust": "调整", + "Color Mixer Layout": "颜色混合器布局", + "Loupe Overlay": "放大镜叠加", + "View Options…": "视图选项…", + "View → Loupe Overlay → View Options chooses the lines Info 1 and Info 2 show.": "视图 → 放大镜叠加 → 视图选项 用于选择“信息 1”和“信息 2”显示的行。", "Camera preview": "相机预览", "The camera's own JPEG, shown until LightCraft has rendered the raw. Judge colour and tone on the rendered photo.": "相机自己的 JPEG,在 LightCraft 渲染出原始文件之前显示。请在渲染后的照片上判断颜色和影调。", "Profile: from the file (the camera's own correction)": "配置文件:来自文件(相机自身的校正)", @@ -2435,6 +2449,14 @@ "Top bar": "顶部栏", "Tool strip": "工具栏", "Bottom bar": "底部栏", + "AI masks": "AI 蒙版", + "Device": "设备", + "Last photo": "上一张照片", + "Remote worker": "远程工作进程", + "Run on": "运行位置", + "Automatic (GPU when available)": "自动(有 GPU 时使用)", + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer.": "“对象”和“描述”蒙版对每张照片只分析一次;除非选择了 CPU 或关闭了“使用 GPU 渲染”,否则在显卡上进行。在处理器上分析要慢得多。", + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "“自动”会在 Mac 的显卡上运行模型。如果 AI 蒙版在那里失败,请选择 CPU;在处理器上会慢得多。", "User Templates": "用户模板", "Delete Folder": "删除文件夹", "Folder name": "文件夹名称", @@ -2461,6 +2483,18 @@ "Welcome": "欢迎", "Next": "下一步", "Get Started": "开始使用", + "Keywords and presets apply to new files only, not to photos already in Local": "关键词和预设仅应用于新文件,不适用于已在“本地”中的照片", + "This album is in a loop, so it shows nothing": "此相册处于循环中,因此不显示任何内容", + "It tests itself: change its rules (Edit Smart Album…)": "它引用了自身:请更改其规则(编辑智能相册…)", + "Can't add to an album folder": "无法添加到相册文件夹", + "An album folder holds albums, not photos: drop on an album inside it": "相册文件夹里放的是相册,不是照片:请拖到其中的某个相册上", + "Can't add to a smart album": "无法添加到智能相册", + "A smart album's rules choose its photos: change them with Edit Smart Album…": "智能相册的照片由其规则决定:请用“编辑智能相册…”更改规则", + "Add keywords in the Keyword List": "请在关键字列表中添加关键字", + "Give photos a keyword in the Keyword List (Window → Keywords, K): drop them on it there": "要给照片添加关键字,请使用关键字列表(窗口 → 关键字,K),把照片拖到那里的关键字上", + "Already on these photos": "这些照片已有", + "Can't go inside itself": "不能放入自身", + "Same Content as Another Photo": "与另一张照片内容相同", "Reduce Motion": "减少动态效果", "Reduce motion": "减少动态效果", "Turns off zoom and spinner animations. Fades stay. Follows the system's Reduce Motion until you change it here.": "关闭缩放和旋转指示器的动画。淡入淡出效果保留。在你于此处更改之前,跟随系统的“减弱动态效果”设置。", @@ -2473,5 +2507,11 @@ "Stack — click to collapse (S)": "堆叠 — 单击折叠 (S)", "Virtual copy": "虚拟副本", "Right-click ▸ Locate Missing File… to find it again.": "右键单击 → 定位缺失的文件…,即可重新找到它。", - "Right-click ▸ Reload from Disk to try again.": "右键单击 → 从磁盘重新读取,即可重试。" + "Right-click ▸ Reload from Disk to try again.": "右键单击 → 从磁盘重新读取,即可重试。", + "Album name (empty outside an album view)": "相册名称(在相册视图外为空)", + "Export date (YYYYMMDD)": "导出日期 (YYYYMMDD)", + "Export time (HHMM)": "导出时间 (HHMM)", + "Insert variable": "插入变量", + "Insert…": "插入…", + "none ({album}, {date}, {hour})": "无 ({album}, {date}, {hour})" } diff --git a/crates/ui-egui/locales/zh-hant-formats.json b/crates/ui-egui/locales/zh-hant-formats.json index 1b550e4c07..9222de8f8b 100644 --- a/crates/ui-egui/locales/zh-hant-formats.json +++ b/crates/ui-egui/locales/zh-hant-formats.json @@ -58,10 +58,10 @@ "LightCraft could not open its window: {e}\n\nThe log file has the details: {path}": "LightCraft 無法開啟視窗:{e}\n\n詳細資訊請見記錄檔:{path}", "Matches: {}": "符合條件:{}", "Merging… {stage} {:.0}%": "正在合併… {stage} {:.0}%", - "Move {n} photo{} to “{}”": "將 {n} 張照片移到「{1}」{0:.0}", - "Move {n} photo{} to “{}”?": "將 {n} 張照片移到「{1}」?{0:.0}", + "Move {n} file{} to “{}”": "將 {n} 個檔案移到「{1}」{0:.0}", + "Move {n} file{} to “{}”?": "將 {n} 個檔案移到「{1}」?{0:.0}", "Move {what} to Recently Deleted?": "要將{what}移至「最近刪除」嗎?", - "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "已將 {n} 張照片移到「{1}」{0:.0}。編輯 → 復原 可移回。", + "Moved {n} file{} to “{}”. Edit → Undo moves them back.": "已將 {n} 個檔案移到「{1}」{0:.0}。編輯 → 復原 可移回。", "Named ({named_n})": "已命名({named_n})", "Paste into {n} photo{} — only settings that were copied are pasted": "貼上至 {n} 張照片{:.0} — 只貼上已複製的設定", "Preset: {name}": "預設集:{name}", @@ -325,9 +325,14 @@ "Panel move was not applied: {error}": "面板移動未套用:{error}", "{name} is installed": "{name} 已安裝", "{name} is installed and in use: face recognition is on": "{name} 已安裝並在使用中:臉部辨識已開啟", + "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} 秒,影像編碼器 {encoder:.1} 秒", "Bring photos in with File › Import Photos… ({keys}).": "透過 檔案 › 匯入照片… ({keys}) 匯入照片。", "View › Detail View ({keys}).": "檢視 › 詳細檢視 ({keys})。", "File › Export… · File › Print… ({keys}).": "檔案 › 匯出… · 檔案 › 列印… ({keys})。", + "It leads back to itself through “{}”: change the rules of one album on the loop (Edit Smart Album…)": "它透過相簿「{}」回到自身:請變更循環中某個相簿的規則(編輯智慧型相簿…)", + "Add {n} photo{} to “{}”": "將 {n} 張照片加入「{1}」{0:.0}", + "{n} already there": "{n} 張已在其中", + "Add “{keyword}” to {n} photo{}": "將「{keyword}」加入 {n} 張照片{:.0}", "Rule {n} of {m}: {what}. Move with the arrow keys": "規則 {n}/{m}:{what}。用方向鍵移動", "Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "群組 {n}/{m}:符合{mode},內含 {count} 項。用方向鍵移動", ", rating {} of 5": ",評分:{}/5" diff --git a/crates/ui-egui/locales/zh-hant.json b/crates/ui-egui/locales/zh-hant.json index 3a6a783e9b..625de79bb2 100644 --- a/crates/ui-egui/locales/zh-hant.json +++ b/crates/ui-egui/locales/zh-hant.json @@ -47,6 +47,7 @@ "Import photos with File → Import Photos…, or drop them here": "使用「檔案 → 匯入照片…」,或將照片拖放至此", "This row covers more than one disk: drop on a folder inside it": "此列涵蓋多個磁碟:請拖放到其中的資料夾", "Local photos aren't in the library yet: Add to My Photos first, then move them": "本機照片尚未在照片庫中:請先「加入我的照片」,再移動", + "Demo photos have no file on disk, so they can't be moved": "示範照片在磁碟上沒有檔案,因此無法移動", "Add to Selected Photos": "加入選取的照片", "Add to Target Album": "加入目標相簿", "Add to this mask": "加入此遮色片", @@ -143,6 +144,7 @@ "Before/After (Y)": "編輯前/後(Y)", "Before/After Settings": "編輯前/後設定", "Before/After Split": "編輯前/後分割檢視", + "Before/After": "編輯前/後", "Before/After Split Top/Bottom": "編輯前/後上下分割檢視", "Before/After Top/Bottom": "編輯前/後上下檢視", "Begin Interaction": "開始互動", @@ -351,6 +353,7 @@ "Cut": "剪下", "Cut pages": "剪下頁面", "Cycle Crop Overlay": "切換裁切疊加", + "Crop Overlay": "裁切疊加", "Cycle Crop Overlay Orientation": "切換裁切疊加方向", "Cycle Info Overlay": "切換資訊疊加", "Cycle Mask Overlay Color": "切換遮色片疊加色彩", @@ -1604,6 +1607,7 @@ "XMP sidecars": "XMP 附屬檔案", "Year": "年", "Yellow": "黃色", + "White": "白色", "Yellow Hue": "黃色色相", "Yellow Luminance": "黃色明度", "Yellow Saturation": "黃色飽和度", @@ -1941,6 +1945,9 @@ "Not saved": "未儲存", "A folder is being synchronized": "正在同步資料夾", "Wait for the import to finish": "請等待匯入完成", + "Filter settings": "篩選設定", + "No setting matches what is typed.": "沒有符合輸入內容的設定。", + "Try one word, or part of one: the names of tabs and sections, labels and explanations are all looked through.": "請嘗試一個詞或詞的一部分:會搜尋分頁和區段的名稱、標籤和說明。", "Appearance": "外觀", "Appearance Mode": "外觀模式", "Sync with System": "與系統同步", @@ -2202,6 +2209,13 @@ "The photos are imported once it ends": "結束後即匯入這些照片", "An import is running. Drop photos when it has finished": "正在匯入。匯入完成後再拖放照片", "Finish Lightroom catalog import before adding photos": "新增照片前,請先完成 Lightroom 目錄的匯入", + "Mixer": "混合器", + "HSL": "HSL", + "Adjust": "調整", + "Color Mixer Layout": "混色器版面", + "Loupe Overlay": "放大鏡疊加", + "View Options…": "檢視選項…", + "View → Loupe Overlay → View Options chooses the lines Info 1 and Info 2 show.": "檢視 → 放大鏡疊加 → 檢視選項 可選擇「資訊 1」和「資訊 2」顯示的行。", "Camera preview": "相機預覽", "The camera's own JPEG, shown until LightCraft has rendered the raw. Judge colour and tone on the rendered photo.": "相機自己的 JPEG,在 LightCraft 算繪出原始檔之前顯示。請在算繪後的照片上判斷色彩與色調。", "Profile: from the file (the camera's own correction)": "設定檔:來自檔案(相機本身的校正)", @@ -2436,6 +2450,14 @@ "Tool strip": "工具列", "Bottom bar": "底部列", "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "防止 G-SYNC/FreeSync 閃爍(下次啟動時生效)", + "AI masks": "AI 遮色片", + "Device": "裝置", + "Last photo": "上一張照片", + "Remote worker": "遠端工作程序", + "Run on": "執行位置", + "Automatic (GPU when available)": "自動(有 GPU 時使用)", + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer.": "「物件」和「描述」遮色片對每張照片只分析一次;除非選擇了 CPU 或關閉了「使用 GPU 算繪」,否則在顯示卡上進行。在處理器上分析要慢得多。", + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "「自動」會在 Mac 的顯示卡上執行模型。如果 AI 遮色片在那裡失敗,請選擇 CPU;在處理器上會慢得多。", "User Templates": "使用者範本", "Delete Folder": "刪除資料夾", "Folder name": "資料夾名稱", @@ -2462,6 +2484,18 @@ "Welcome": "歡迎", "Next": "下一步", "Get Started": "開始使用", + "Keywords and presets apply to new files only, not to photos already in Local": "關鍵字和預設集僅套用於新檔案,不適用於已在「本機」中的照片", + "This album is in a loop, so it shows nothing": "此相簿處於循環中,因此不顯示任何內容", + "It tests itself: change its rules (Edit Smart Album…)": "它引用了自身:請變更其規則(編輯智慧型相簿…)", + "Can't add to an album folder": "無法加入相簿資料夾", + "An album folder holds albums, not photos: drop on an album inside it": "相簿資料夾裡放的是相簿,不是照片:請拖到其中的某個相簿上", + "Can't add to a smart album": "無法加入智慧型相簿", + "A smart album's rules choose its photos: change them with Edit Smart Album…": "智慧型相簿的照片由其規則決定:請用「編輯智慧型相簿…」變更規則", + "Add keywords in the Keyword List": "請在關鍵字清單中加入關鍵字", + "Give photos a keyword in the Keyword List (Window → Keywords, K): drop them on it there": "要替照片加入關鍵字,請使用關鍵字清單(視窗 → 關鍵字,K),把照片拖到那裡的關鍵字上", + "Already on these photos": "這些照片已有", + "Can't go inside itself": "不能放入自身", + "Same Content as Another Photo": "與另一張照片內容相同", "Reduce Motion": "減少動態效果", "Reduce motion": "減少動態效果", "Turns off zoom and spinner animations. Fades stay. Follows the system's Reduce Motion until you change it here.": "關閉縮放與旋轉指示器的動畫。淡入淡出效果保留。在你於此處更改之前,跟隨系統的「減少動態效果」設定。", @@ -2474,5 +2508,11 @@ "Stack — click to collapse (S)": "堆疊 — 按一下以收合 (S)", "Virtual copy": "虛擬副本", "Right-click ▸ Locate Missing File… to find it again.": "按右鍵 → 尋找遺失的檔案…,即可重新找到它。", - "Right-click ▸ Reload from Disk to try again.": "按右鍵 → 從磁碟重新載入,即可重試。" + "Right-click ▸ Reload from Disk to try again.": "按右鍵 → 從磁碟重新載入,即可重試。", + "Album name (empty outside an album view)": "相簿名稱(在相簿檢視外為空)", + "Export date (YYYYMMDD)": "匯出日期 (YYYYMMDD)", + "Export time (HHMM)": "匯出時間 (HHMM)", + "Insert variable": "插入變數", + "Insert…": "插入…", + "none ({album}, {date}, {hour})": "無 ({album}, {date}, {hour})" } diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index ccc36677d3..8abb6fcd52 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -106,6 +106,8 @@ impl LightcraftApp { #[cfg(test)] missing_count_test_delay: None, shadow: None, + drawing_offscreen: false, + drop_cancel_requested: false, synthetic: vec![], pointer_cleanup: false, drop_hover: vec![], @@ -236,6 +238,19 @@ impl LightcraftApp { } } + /// End a Brush stroke being painted, if one is: what already went to the photo stays (its undo step is + /// closed), what didn't is dropped. The pointer still held paints nothing more until it is let go. + /// Other gestures are left alone. + pub(crate) fn cancel_brush_gesture(&mut self) { + let Some(crate::panels::detail::Gesture::Brush { live, .. }) = &self.gesture else { return }; + let went_live = live.is_some(); + self.gesture = None; + self.brush_live = None; + if went_live { + let _ = self.session.execute("develop.endInteraction", &serde_json::json!({})); + } + } + /// Run a UI or engine command by id. The single entry point for every frontend path. pub fn run(&mut self, id: &str, params: Value) -> Result { self.run_typed(id, params).map_err(|e| e.message) @@ -244,10 +259,20 @@ impl LightcraftApp { /// [`LightcraftApp::run`], keeping what kind of error a refusal is: for code that decides on it /// (offer a model's download, treat a cancel as one) instead of reading the message. pub fn run_typed(&mut self, id: &str, params: Value) -> Result { + // a brush stroke being painted belongs to the mask and photo it started on: picking another (also by + // stepping through the photos with the arrow keys) ends it first, so its next live update or its release + // can't land on the one picked; so does Undo, which takes the live stroke away (the next update would + // otherwise replace the stroke before it) + if brush_stroke_ends_before(id) { + self.cancel_brush_gesture(); + } // (seen before and after each command, so a selection changed and changed back between two // UI passes still counts as changed) self.selection_changes(); let r = self.run_command(id, params); + // the panel a command left on show is noted now, not at the next frame, success or not: the next command + // of the same frame (a script, queued shortcuts) sees it (Close Panel, B, Done = the column stays hidden) + self.ui.note_right(); self.selection_changes(); r } @@ -303,15 +328,12 @@ impl LightcraftApp { { self.ui.tool.clear(); } - if r.is_ok() && id == "mask.adjust" { - // Judge local adjustments on the photo, without the selection overlay obscuring them. - // Keep it hidden after release; O / the overlay eye can show it again. - self.ui.mask_overlay = false; - } - if r.is_ok() && matches!(id, "mask.add" | "mask.addComponent" | "mask.duplicate" | "mask.select") { - // A new or newly picked mask shows its overlay again, as in Lightroom: hidden by a slider - // drag above, it stayed hidden while the Overlay menu still named a mode (issue #1800). - self.ui.mask_overlay = true; + // (a mask's sliders don't switch the overlay off, and creating or picking a mask doesn't + // switch it on: one rule decides when it shows, see `panels::detail::overlay_mask`) + if r.is_ok() && !self.ui.mask_overlay_hidden.is_empty() { + // a mask an undo, a history step or pasted settings took away frees its id for the next new + // mask: whether O hid its overlay goes with it + crate::panels::masking::forget_missing_overlays(self); } if r.is_ok() { // These commands finish synchronously, so their completion would otherwise @@ -465,32 +487,48 @@ impl LightcraftApp { panels::slideshow::tick(self, ctx, now); } - /// Announce the end of a Build Previews run. + /// A task waiting in line whose lane freed while nothing was asked starts now (commands start them too); then the + /// run in progress is looked at, so that one started here is polled for its end from this frame on. + pub(crate) fn tick_preview_builds(&mut self, ctx: &egui::Context) { + self.session.start_waiting(); + self.preview_build_status(ctx); + } + + /// Announce the end of a Build Previews run, and of those a build waiting in line replaced before it was announced + /// (in one toast, oldest first). A build is announced once: its `reported` flag says so, not where it lives. fn preview_build_status(&mut self, ctx: &egui::Context) { use std::sync::atomic::Ordering; - let Some(b) = self.session.preview_build.clone() else { return }; - let key = std::sync::Arc::as_ptr(&b) as usize; - if b.finished.load(Ordering::Relaxed) { - if self.ui.preview_build_seen != Some((key, true)) { - self.ui.preview_build_seen = Some((key, true)); - let (done, failed) = (b.done.load(Ordering::Relaxed), b.failed.load(Ordering::Relaxed)); - let plural = if done == 1 { "" } else { "s" }; - let mut msg = match (b.error(), b.what) { - (Some(e), what) => format!("{}: {e}", if what.is_empty() { "previews" } else { what }), - (None, "") => crate::i18n::tr_format!("Previews ready for {done} photo{plural}", done = done, plural = plural), - (None, what) => { - crate::i18n::tr_format!("Done ({what}): {done} photo{plural}", done = done, plural = plural, what = crate::i18n::tr(what)) - } - }; - if failed > 0 { - msg.push_str(&crate::i18n::tr_format!(" · {failed} couldn't be rendered", failed = failed)); - } - self.toast(ctx, msg); + let mut ended = self.session.take_unreported_builds(); + match self.session.preview_build.clone() { + Some(b) if b.finished.load(Ordering::Relaxed) => ended.push(b), + Some(_) => { + // The activity stack shows the run while it works; poll for the end. + ctx.request_repaint_after(std::time::Duration::from_millis(250)); } - } else { - // The activity stack shows the run while it works; poll for the end. - ctx.request_repaint_after(std::time::Duration::from_millis(250)); + None => {} } + let msgs: Vec = ended.iter().filter(|b| !b.reported.swap(true, Ordering::Relaxed)).map(|b| Self::build_message(b)).collect(); + if !msgs.is_empty() { + self.toast(ctx, msgs.join("; ")); + } + } + + /// How a finished Build Previews run ended, as the toast words it. + fn build_message(b: &lightcraft_engine::cmd::previews::PreviewBuild) -> String { + use std::sync::atomic::Ordering; + let (done, failed) = (b.done.load(Ordering::Relaxed), b.failed.load(Ordering::Relaxed)); + let plural = if done == 1 { "" } else { "s" }; + let mut msg = match (b.error(), b.what) { + (Some(e), what) => format!("{}: {e}", if what.is_empty() { "previews" } else { what }), + (None, "") => crate::i18n::tr_format!("Previews ready for {done} photo{plural}", done = done, plural = plural), + (None, what) => { + crate::i18n::tr_format!("Done ({what}): {done} photo{plural}", done = done, plural = plural, what = crate::i18n::tr(what)) + } + }; + if failed > 0 { + msg.push_str(&crate::i18n::tr_format!(" · {failed} couldn't be rendered", failed = failed)); + } + msg } /// Announce when saving the library starts failing (changes then live only in memory and are @@ -599,8 +637,8 @@ impl LightcraftApp { ctx.request_repaint(); } if let Some(mask) = polled.refine { - // a new selection from a click or a description: show it, as `run` does for new masks - self.ui.mask_overlay = true; + // (a new selection from a click or a description shows by the overlay rule while its + // mask has no settings: `panels::detail::overlay_mask`) self.ui.detail_due = Some((now + 0.3, mask)); } if let Some(e) = polled.messages.into_iter().last() { @@ -731,6 +769,36 @@ impl LightcraftApp { self.perf.max_update_ms = self.perf.max_update_ms.max(self.perf.update_ms); } + /// Ends drags that must not go on, before any panel or dialog sees the frame: Esc gives up a + /// drag and is taken, so a dialog open over it doesn't also close; and a drag outlives its + /// button in no layout (full screen and the slideshow don't run the panels that end it). + /// The frame a button is released in is left to the drop targets, except in full screen, which has none. + fn end_drags(&mut self, ctx: &egui::Context) { + if self.drawing_offscreen { + return; + } + let escape_requested = std::mem::take(&mut self.drop_cancel_requested); + if !self.ui.drag_active() { + return; + } + let (esc, down, released) = ctx.input(|i| (i.key_pressed(egui::Key::Escape), i.pointer.any_down(), i.pointer.any_released())); + let esc = escape_requested || esc; + // a release is left to the drop targets, except in full screen, where there are none: the + // drag ends on that frame, so an Esc on the next one can't find it still going + if !esc && (down || (released && !self.ui.fullscreen)) { + return; + } + if esc { + widgets::take_escape(ctx); + } + if self.ui.dragging_album.take().is_some() { + panels::left::forget_hover(self, ctx); + } + self.ui.dragging_photos = None; + self.ui.dragging_section = None; + self.ui.dragging_keyword = None; + } + /// Lay out the whole window: input/setup for the known UI phase, then presentation, then the /// frame bookkeeping. A hidden `run_logic` never reaches this. pub fn ui(&mut self, ui: &mut egui::Ui) { @@ -775,3 +843,21 @@ pub(crate) fn sam_download_ended(download: &lightcraft_engine::segment::Download None => None, } } + +/// Commands that end a Brush stroke being painted before they run ([`LightcraftApp::run_typed`]): the ones that pick +/// another mask or photo, and Undo / Redo, which change the strokes under it. +pub(crate) fn brush_stroke_ends_before(id: &str) -> bool { + matches!( + id, + "mask.select" + | "library.select" + | "library.next" + | "library.previous" + | "library.up" + | "library.down" + | "slideshow.next" + | "slideshow.previous" + | "edit.undo" + | "edit.redo" + ) +} diff --git a/crates/ui-egui/src/app/frame.rs b/crates/ui-egui/src/app/frame.rs index d52e7d38c6..5859bcbe56 100644 --- a/crates/ui-egui/src/app/frame.rs +++ b/crates/ui-egui/src/app/frame.rs @@ -94,10 +94,11 @@ impl LightcraftApp { // after the poll: a lookup that just finished is cleared, so photos queued meanwhile are looked up now crate::lens_db::tick(self); updates_ui::tick(self, ctx); - self.preview_build_status(ctx); + self.tick_preview_builds(ctx); self.save_status(ctx); self.ai_mask_detail(ctx, now); self.place_names_outcome(ctx); + panels::detail::settle_wheel_edit(self, ctx); self.slideshow_tick(ctx, now); panels::denoise::pump_background(self, ctx, now); panels::faces::pump_background(self, ctx, now); @@ -465,14 +466,19 @@ impl LightcraftApp { // Freeze this frame's notice barrier before `notices::show` can dismiss a prompt: the same // click or key must never be acted on again by the dialog drawn after it. let notice_blocks = panels::notices::blocks_input(self); + self.end_drags(&ctx); // what the panels below read to refuse a right-click's menu while photos are carried widgets::set_carrying(&ctx, self.ui.dragging_photos.is_some() && ctx.input(|i| i.pointer.primary_down())); if std::mem::take(&mut self.ui.quit) { ctx.send_viewport_cmd(egui::ViewportCommand::Close); } self.library_changed(&ctx); + // (a tool panel opened some other way still remembers the panel it took the place of) + self.ui.note_right(); // panels set it again this frame while the pointer rests on a preset or profile self.hover_preview = None; + // (and the mask pin or component row under the pointer: the overlay shows that mask) + self.ui.mask_hover_prev = self.ui.mask_hover.take(); if self.ui.fullscreen { // full-screen preview: the photo alone on black egui::CentralPanel::default() @@ -497,6 +503,7 @@ impl LightcraftApp { // host frames, and resetting it above must only hide it from this pass's dialogs. panels::notices::restore_prompt_pointer(self, &ctx); } + self.repaint_on_mask_hover_change(&ctx); (self.next_widgets, self.next_widget_hits) = widgets::take_registries(&ctx); self.end_frame(&ctx, t0); return; @@ -523,10 +530,13 @@ impl LightcraftApp { panels::activity::show(self, &ctx); export_task::poll_photos(self, &ctx); pick::poll(self, &ctx); - panels::grid::drag_feedback(self, &ctx); - panels::left::album_drag_feedback(self, &ctx); - panels::left::section_drag_feedback(self, &ctx); - panels::keyword_list::drag_feedback(self, &ctx); + // (each ends its drag when the button is up, which an offscreen frame's pointer never is) + if !self.drawing_offscreen { + panels::grid::drag_feedback(self, &ctx); + panels::left::album_drag_feedback(self, &ctx); + panels::left::section_drag_feedback(self, &ctx); + panels::keyword_list::drag_feedback(self, &ctx); + } panels::toast(self, &ctx); drop_overlay::show(self, &ctx); // AppKit moves the window on a drag anywhere in the title-bar band unless the window isn't @@ -538,10 +548,20 @@ impl LightcraftApp { // frames, and resetting it above must only hide it from this pass's dialogs. panels::notices::restore_prompt_pointer(self, &ctx); } + self.repaint_on_mask_hover_change(&ctx); (self.next_widgets, self.next_widget_hits) = widgets::take_registries(&ctx); self.text_focus = crate::text_field::typing(&ctx); self.end_frame(&ctx, t0); } + + /// The pointer moved onto another mask pin or component row, or off them, this frame: the overlay drawn earlier in the + /// frame still showed the last one (it falls back to it while panels set the new one), so one more frame shows + /// the new one at once rather than at the next input (CodeRabbit on #2920). + pub(crate) fn repaint_on_mask_hover_change(&self, ctx: &egui::Context) { + if self.ui.mask_hover != self.ui.mask_hover_prev { + ctx.request_repaint(); + } + } } /// Import commits batches at most once per host frame. The first layout pass and a hidden diff --git a/crates/ui-egui/src/app/input.rs b/crates/ui-egui/src/app/input.rs index 2c611240ad..7c75c8567b 100644 --- a/crates/ui-egui/src/app/input.rs +++ b/crates/ui-egui/src/app/input.rs @@ -127,6 +127,11 @@ impl LightcraftApp { /// the fonts are not installed (the pass would draw nothing and the events would be lost). pub fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) { self.prepare_raw_input(ctx, raw); + // The framework routes Escape to its captured press or focused control and removes it + // from egui input. The app's drop targets must see that cancellation too, before a + // primary release in the same pass can commit a drop. Keep the key for the framework. + self.drop_cancel_requested |= self.ui.drag_active() + && raw.events.iter().any(|event| matches!(event, egui::Event::Key { key: egui::Key::Escape, pressed: true, repeat: false, .. })); // last, on what egui gets: the framework's key stage takes the clipboard events out of egui's input crate::shortcuts::note_clipboard(ctx, raw); } diff --git a/crates/ui-egui/src/app/screenshot.rs b/crates/ui-egui/src/app/screenshot.rs index e6942a64f1..d29c009a0b 100644 --- a/crates/ui-egui/src/app/screenshot.rs +++ b/crates/ui-egui/src/app/screenshot.rs @@ -292,7 +292,9 @@ impl LightcraftApp { // shadow the window's own input for its pass. It goes after the pass numbers agree, because the fork also // brought the window's pass count and `set_input` expects the hooks to have run for this context's last pass. super::shell::prepare(self, &view.ctx); + self.drawing_offscreen = true; view.run(headless::HeadlessView::raw_input(size, ppp, time, vec![]), |ui| self.draw_window(ui)); + self.drawing_offscreen = false; let img = capture.then(|| { let mut tex = self.renderer.cpu_textures(); if let (Some((t, ..)), Some(px)) = (&self.merge.preview, &self.merge.preview_pixels) { diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 31c5d0dce2..91f0c6efd1 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -158,7 +158,7 @@ pub fn inspect(app: &LightcraftApp, ctx: &egui::Context) -> Value { "export": {"running": app.export.as_ref().map(crate::export_task::ExportTask::status), "last": app.last_export_result}, "import": app.import.as_ref().map(crate::import::ImportTask::status), "tasks": app.tasks.labels(), - // every long-running task in flight, as the activity stack shows them (`activity.list`) + // every long-running task in flight and every task waiting in line (`activity.list`); the stack draws the running ones "activity": app.session.activity.list(), // commands waiting on a native file dialog shown off the UI thread (`pick`) "fileDialogs": app.pending_picks.iter().map(|p| p.command.clone()).collect::>(), @@ -431,10 +431,21 @@ pub fn handle(app: &mut LightcraftApp, ctx: &egui::Context, req: &ControlRequest } u.collapsed_sidebar.clear(); u.toast = app.ui.toast.clone(); + // the panel a tool panel took the place of, to put back when it closes, survives a ui.set + u.tool_return = app.ui.tool_return; + u.right_seen = app.ui.right_seen; + // (and what a panel toggle replaced, so pressing its key again still puts that back) + u.toggle_return = app.ui.toggle_return.clone(); + u.right_shown_by_f8 = app.ui.right_shown_by_f8; u.dialog = app.ui.dialog.clone(); u.status = app.ui.status.clone(); + let right_changed = u.right != app.ui.right; crate::docking::cancel_replaced_gesture(app, u.docking.as_deref()); app.ui = u; + if right_changed { + // noted now, as a command does: the next request may open a tool before a frame is drawn + app.ui.note_right(); + } crate::i18n::set_language(app.ui.language); ctx.request_repaint(); ok(serde_json::to_value(&app.ui).unwrap_or_default()) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 79ed20eb4d..862530f3ea 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -1296,7 +1296,8 @@ fn all_metadata_body(ui: &mut egui::Ui, t: &Tokens, dlg: &mut Dialog) { egui::Grid::new(format!("meta-{g}")).num_columns(2).spacing([16.0, 3.0]).striped(true).show(ui, |ui| { for (n, v) in list { ui.label(egui::RichText::new(n).color(t.text_dim)); - ui.add(egui::Label::new(egui::RichText::new(v).color(t.text_label)).wrap()); + // values (serial numbers, lens names) are copied out of here; the field names are not + ui.add(egui::Label::new(egui::RichText::new(v).color(t.text_label)).wrap().selectable(true)); ui.end_row(); } }); @@ -1851,7 +1852,7 @@ fn keyword_tag_body(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, conf if editing.is_none() { if let Some(p) = parent.as_ref() { - option(ui, caller, "check:keywordInside", crate::i18n::tr_format!("Put inside “{parent}”", parent = p.replace('|', " › ")), inside, true); + option(ui, caller, "check:keywordInside", crate::panels::keyword_list::put_inside_label(p), inside, true); } option( ui, @@ -1919,9 +1920,9 @@ fn delete_effects_body(ui: &mut egui::Ui, t: &Tokens, dlg: &mut Dialog) { /// The body of the MovePhotos dialog. fn move_photos_body(ui: &mut egui::Ui, t: &Tokens, dlg: &mut Dialog) { - let Dialog::MovePhotos { ids, name, dont_ask, .. } = dlg else { return }; - let n = ids.len(); - ui.label(crate::i18n::tr_format!("Move {n} photo{} to “{}”?", if n == 1 { "" } else { "s" }, name, n = n)); + let Dialog::MovePhotos { name, files, dont_ask, .. } = dlg else { return }; + let n = *files; + ui.label(crate::i18n::tr_format!("Move {n} file{} to “{}”?", if n == 1 { "" } else { "s" }, name, n = n)); ui.label(egui::RichText::new(crate::i18n::tr("Their files and XMP sidecars move on disk. Edit → Undo moves them back.")).color(t.text_dim)); ui.add_space(4.0); use craft::ui::choice::Checkbox; diff --git a/crates/ui-egui/src/dialogs/confirm.rs b/crates/ui-egui/src/dialogs/confirm.rs index 20adb92620..5bd4b514c0 100644 --- a/crates/ui-egui/src/dialogs/confirm.rs +++ b/crates/ui-egui/src/dialogs/confirm.rs @@ -178,11 +178,12 @@ pub fn confirm_dialog(app: &mut LightcraftApp, dlg: &Dialog) -> Result crate::panels::denoise::install(app, info, *accepted), Dialog::FaceModel { path, info, accepted } => crate::panels::faces::install(app, path, info, *accepted), Dialog::AllMetadata { .. } | Dialog::SystemInfo { .. } | Dialog::WhatsNew | Dialog::Welcome { .. } => Ok(serde_json::Value::Null), - Dialog::Cull { reject_below, pick_best, stack_groups, burst_gap, similarity } => { + Dialog::Cull { reject_below, pick_best, stack_groups, burst_gap, similarity, reset_bursts } => { app.ui.cull_burst = Some((*burst_gap, *similarity)); app.ui.cull_stack = *stack_groups; let mut p = cull_params(*reject_below, *pick_best, *burst_gap, *similarity); p["stackGroups"] = json!(stack_groups); + p["resetBursts"] = json!(reset_bursts); app.run("photo.analyze", p) } Dialog::SmartRules { id, name, rules, parent, .. } => { diff --git a/crates/ui-egui/src/dialogs/cull.rs b/crates/ui-egui/src/dialogs/cull.rs index d1c1ebd3c4..7d3a3f5263 100644 --- a/crates/ui-egui/src/dialogs/cull.rs +++ b/crates/ui-egui/src/dialogs/cull.rs @@ -117,7 +117,7 @@ pub(crate) fn gap_control( /// Production culling controls; the parent dialog still owns Cancel/OK and modality. pub(super) fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, _t: &Tokens, dlg: &mut Dialog) { - let Dialog::Cull { reject_below, pick_best, burst_gap, similarity, .. } = dlg else { return }; + let Dialog::Cull { reject_below, pick_best, stack_groups, burst_gap, similarity, reset_bursts } = dlg else { return }; let n = app.session.selection.ids.len(); let scope = if n > 1 { crate::i18n::tr_format!("the {n} selected photos", n = n) @@ -144,11 +144,26 @@ pub(super) fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, _t: &Tokens, dlg: let shown = Checkbox::new(Bind::bound(pick_best)).id_salt("cull-pick-best").label(crate::i18n::tr("Pick the sharpest photo of each burst")).show(ui); register(ui, "check:cullPick", &shown.response); + let shown = Checkbox::new(Bind::bound(stack_groups)) + .id_salt("cull-stack-groups") + .label(crate::i18n::tr("Stack each burst, best photo on top")) + .show(ui); + register(ui, "check:cullStack", &shown.response); ui.add_space(6.0); gap(ui, burst_gap); number(ui, "field:cullSimilar", "Burst: how alike (loose … strict)", similarity, true); clamp_cull_burst(burst_gap, similarity); Text::new(crate::i18n::tr("Lower it when a panning or moving burst splits into several groups.")).shade(Shade::Muted).show(ui); + let shown = Checkbox::new(Bind::bound(reset_bursts)) + .id_salt("cull-reset-bursts") + .label(crate::i18n::tr("Regroup bursts I arranged by hand")) + .show(ui); + register(ui, "check:cullResetBursts", &shown.response); + Text::new(crate::i18n::tr( + "Put bursts right by dragging in Window → Bursts: the first photo of a burst is its pick, and culling again keeps what you arranged.", + )) + .shade(Shade::Muted) + .show(ui); Text::new(crate::i18n::tr("Scores stay on the photos: filter or make smart albums with Focus and Best of Similar Shots.")) .shade(Shade::Muted) .show(ui); diff --git a/crates/ui-egui/src/dialogs/cull_wave110_tests.rs b/crates/ui-egui/src/dialogs/cull_wave110_tests.rs index 62a5888c46..e4ab1e197c 100644 --- a/crates/ui-egui/src/dialogs/cull_wave110_tests.rs +++ b/crates/ui-egui/src/dialogs/cull_wave110_tests.rs @@ -84,7 +84,8 @@ fn cull_controls_edit_the_real_draft_then_confirm_and_reopen() { fn production_cull_body_mounts_sdk_controls_without_clamping_typed_values() { let ctx = framework_context(); let mut app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services::default()); - let mut dialog = Dialog::Cull { reject_below: 25.0, pick_best: false, burst_gap: 1800.0, similarity: 1.0, stack_groups: false }; + let mut dialog = + Dialog::Cull { reject_below: 25.0, pick_best: false, burst_gap: 1800.0, similarity: 1.0, stack_groups: false, reset_bursts: false }; let mut roles = Vec::new(); for _ in 0..3 { let mut frame_out = ctx.run_ui(egui::RawInput::default(), |root_ui| { diff --git a/crates/ui-egui/src/dialogs/export/core.rs b/crates/ui-egui/src/dialogs/export/core.rs index 7f15265c5a..d34f89d940 100644 --- a/crates/ui-egui/src/dialogs/export/core.rs +++ b/crates/ui-egui/src/dialogs/export/core.rs @@ -37,10 +37,16 @@ pub(super) fn field(ui: &mut egui::Ui, label: &str, add: impl FnOnce(&mut egu /// Each format/option remains independently addressable, with one roving keyboard group. pub(super) fn choices(ui: &mut egui::Ui, label: &str, id: &str, options: &[(V, &str)], value: &mut V) { let body = |ui: &mut egui::Ui, _: &mut craft::ui::contract::BodyCx<'_>| { - ui.horizontal_wrapped(|ui| { - for (i, (value, label)) in options.iter().enumerate() { - let response = Radio::new(*value).id_salt((id, i)).label(crate::i18n::tr(label).to_owned()).show(ui); - register(format!("button:{id}-{i}"), &response); + let columns = if id == "exportWmAnchor" { 3 } else { options.len().max(1) }; + ui.vertical(|ui| { + for (row, options) in options.chunks(columns).enumerate() { + ui.horizontal_wrapped(|ui| { + for (col, (value, label)) in options.iter().enumerate() { + let i = row * columns + col; + let response = Radio::new(*value).id_salt((id, i)).label(crate::i18n::tr(label).to_owned()).show(ui); + register(format!("button:{id}-{i}"), &response); + } + }); } }); }; @@ -63,7 +69,8 @@ pub(super) fn choices(ui: &mut egui let width = if one_line <= 560.0 { ui.available_width().max(one_line) } else { ui.available_width() }.max(1.0); let size = measure(&mut *ui, width); let (rect, _) = ui.allocate_exact_size(egui::vec2(width, size.y.max(24.0)), egui::Sense::hover()); - RadioGroup::new(crate::i18n::tr(label).to_owned(), Bind::bound(value)).id_salt(id).show_at(ui, rect, body); + let nav = if id == "exportWmAnchor" { craft::behavior::NavShape::bounded_grid(3) } else { craft::behavior::NavShape::Flat }; + RadioGroup::new(crate::i18n::tr(label).to_owned(), Bind::bound(value)).id_salt(id).nav(nav).show_at(ui, rect, body); }); } @@ -582,8 +589,35 @@ fn export_destination_rows(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Token }); }); } + let subfolder_widget = "field:exportSubfolder"; + let subfolder_id = crate::text_field::id(subfolder_widget); field(ui, "Subfolder", |ui| { - text(ui, "field:exportSubfolder", "Subfolder", &mut opts.subfolder, "none"); + trailing_button_row(ui, |ui| { + let entries = [ + Entry::new("{album}", "{album}").stepped(false).description(crate::i18n::tr("Album name (empty outside an album view)")), + Entry::new("{date}", "{date}").stepped(false).description(crate::i18n::tr("Export date (YYYYMMDD)")), + Entry::new("{hour}", "{hour}").stepped(false).description(crate::i18n::tr("Export time (HHMM)")), + ]; + let mut chosen = ""; + let (rect, _) = ui.allocate_exact_size(egui::vec2(90.0, 24.0), egui::Sense::hover()); + let shown = Select::new(crate::i18n::tr("Insert variable"), Bind::bound(&mut chosen), &entries) + .id_salt("exportSubfolderTags") + .placeholder(crate::i18n::tr("Insert…")) + .show_at(ui, rect); + register("combo:exportSubfolderTags", &shown.response); + if !craft::ui::runtime::measure::active(ui.ctx()) && ui.is_enabled() && !chosen.is_empty() { + crate::import::insert_at_cursor(ui.ctx(), subfolder_id, &mut opts.subfolder, chosen); + } + crate::import::template_field( + ui, + subfolder_widget, + crate::i18n::tr("Subfolder"), + &mut opts.subfolder, + subfolder_id, + crate::i18n::tr("none ({album}, {date}, {hour})"), + ui.available_width(), + ); + }); }); use lightcraft_engine::export::Conflict as K; choices(ui, "If file exists", "exportConflict", &[(K::Unique, "Add number"), (K::Overwrite, "Overwrite"), (K::Skip, "Skip")], &mut opts.conflict); diff --git a/crates/ui-egui/src/dialogs/faces.rs b/crates/ui-egui/src/dialogs/faces.rs index 8e6844b245..0da3bda4ec 100644 --- a/crates/ui-egui/src/dialogs/faces.rs +++ b/crates/ui-egui/src/dialogs/faces.rs @@ -579,7 +579,7 @@ pub fn open_download_dialog(app: &mut LightcraftApp, m: &Value) { app.ui.dialog = Some(crate::state::Dialog::FaceModel { path: String::new(), info, accepted: false }); } -/// Photo ▸ Detect Faces without the detector: offer to download it (its terms first), the same as in Settings. +/// Photo ▸ Metadata ▸ Detect Faces without the detector: offer to download it (its terms first), the same as in Settings. pub fn offer_detector(app: &mut LightcraftApp) { let list = app.session.execute("faces.models.list", &json!({})).unwrap_or(Value::Null); if let Some(m) = list["models"].as_array().and_then(|a| a.iter().find(|m| m["role"] == "detector" && m["installed"] != true)) { diff --git a/crates/ui-egui/src/dialogs/import.rs b/crates/ui-egui/src/dialogs/import.rs index b2c3b9a94b..56f9fe7e76 100644 --- a/crates/ui-egui/src/dialogs/import.rs +++ b/crates/ui-egui/src/dialogs/import.rs @@ -50,7 +50,7 @@ pub(crate) use scan::{HELD_RESOLVES, ScanEnd, scan_by_hand, stall_scan, stall_sc pub use scan::{ScanTask, browse, open, poll_scan, running}; #[cfg(test)] pub(crate) use tags::tag_toggle; -pub(crate) use tags::{tag_help, template_field, unknown_tags_warning}; +pub(crate) use tags::{insert_at_cursor, tag_help, template_field, unknown_tags_warning}; pub use task::{ImportTask, start, start_paths, tick}; #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] @@ -154,10 +154,46 @@ impl ImportDialog { } } } + /// Candidate `i` is a file whose photo is only browsed (Local): the scan offers it (it isn't in the + /// library). Importing it brings that record into the library where + /// the file is, whatever the transfer mode. + pub fn is_browsed(&self, i: usize) -> bool { + self.candidates.get(i).is_some_and(|c| c.error.is_none() && c.duplicate.is_none() && c.local) + } /// Candidate `i` can be checked: a readable file the library doesn't have, or one whose photo - /// is in Recently Deleted — even with "Leave them", a click picks it (issue #1285). + /// is in Recently Deleted — even with "Leave them", a click picks it (issue #1285). A browsed + /// photo can't be copied or moved: the engine would add it in place, so copying leaves it out + /// (and brings in its first twin instead, [`ImportDialog::is_copy_twin`]). pub fn importable(&self, i: usize) -> bool { self.candidates.get(i).is_some_and(|c| c.error.is_none() && (c.duplicate.is_none() || self.is_trashed(i))) + && !(self.copy && self.candidates.get(i).is_some_and(|c| c.local)) + || self.is_copy_twin(i) + } + /// Copying leaves a browsed photo out, so a file with the same bytes that no library photo has + /// is what brings that content in: candidate `i` is that file (the scan names the browsed photo + /// it stands in for, `browsed_twin`, on the first one only). + pub fn is_copy_twin(&self, i: usize) -> bool { + self.copy + && self.candidates.get(i).is_some_and(|c| { + c.browsed_twin.is_some() && !c.local && c.error.is_none() && c.duplicate.as_deref() == Some("content") && c.existing.is_none() + }) + } + /// Choose how the files are brought in. Switching to copying offers the file that stands in for + /// a browsed photo ([`ImportDialog::is_copy_twin`]), checked; switching to adding in place takes + /// it away again. + pub fn set_transfer(&mut self, copy: bool, move_files: bool) { + let switched = copy != self.copy; + self.copy = copy; + self.move_files = copy && move_files; + for i in (0..self.candidates.len()).filter(|_| switched) { + if self.candidates[i].browsed_twin.is_some() && !self.candidates[i].local { + // (a dialog read back may hold fewer check marks than candidates) + let twin = self.is_copy_twin(i); + if let Some(checked) = self.checked.get_mut(i) { + *checked = twin; + } + } + } } /// Candidate `i` is checked by Check All and the file type toggles: with "Leave them", a file in /// Recently Deleted is only checked by hand. @@ -174,7 +210,7 @@ impl ImportDialog { } /// Any file of type `ty` is checked. pub fn type_checked(&self, ty: &str) -> bool { - self.candidates.iter().zip(&self.checked).any(|(c, on)| *on && file_type(c) == ty) + self.candidates.iter().zip(&self.checked).enumerate().any(|(i, (c, on))| *on && self.importable(i) && file_type(c) == ty) } /// Check (the importable ones) or uncheck every file of type `ty`: the raws only, say, and not /// the JPEGs kept beside them (issue #344). @@ -255,6 +291,22 @@ impl ImportDialog { o => Ok(Some(o.to_string())), } } + /// Importing checked candidate `i` as it stands joins the library with the browsed record it + /// names, as the engine's `Promote` does: a browsed file the library doesn't have, or one whose + /// content is in Recently Deleted under "Import as new" (which replaces the trashed photo). + /// "Restore them" brings the trashed photo back instead and "Leave them" skips the file. + fn promotes_browsed(&self, i: usize) -> bool { + !self.copy + && self.checked.get(i).copied().unwrap_or(false) + && self.candidates.get(i).is_some_and(|c| c.local && c.error.is_none()) + && (self.is_browsed(i) || (self.is_trashed(i) && self.on_deleted == "fresh")) + } + /// Keywords or a preset are set while a checked browsed photo would join the library as it is: + /// the engine applies them to new files only, so the review says so. + fn options_skip_browsed(&self) -> bool { + let has_options = !self.keywords().is_empty() || !self.preset.is_empty() || !self.metadata_preset.is_empty(); + has_options && (0..self.candidates.len()).any(|i| self.promotes_browsed(i)) + } fn keywords(&self) -> Vec { self.keywords.split(',').map(str::trim).filter(|k| !k.is_empty()).map(str::to_string).collect() } @@ -298,6 +350,139 @@ mod tests { assert!(app.import.is_none()); } + /// A file whose photo is only browsed (Local) comes from the scan as an ordinary candidate that + /// still names its record: offered when adding in place; copying or moving would not copy it + /// (the engine adds it where it is), so there it counts as already in the library. + #[test] + fn a_browsed_photo_is_importable_only_when_adding_in_place() { + let mut d = dialog(); + d.candidates[5].local = true; + assert!(d.is_browsed(5) && d.importable(5)); + assert_eq!(dup_counts(&d), (0, 1, 0), "adding in place: not skipped"); + d.copy = true; + assert!(!d.importable(5), "copying leaves it where it is"); + assert!(!d.selected_paths().contains(&"img5.jpg".to_string())); + assert_eq!(dup_counts(&d), (1, 1, 0)); + assert!(!d.is_browsed(3), "a duplicate isn't browsed"); + // its library twin is in Recently Deleted: still offered in place ("Import as new" brings it in), never copied + d.copy = false; + d.candidates[4].local = true; + d.candidates[4].duplicate = Some("content".into()); + d.set_trashed(vec![false, false, false, false, true, false]); + assert!(d.importable(4)); + d.copy = true; + assert!(!d.importable(4), "copying would add it where it is"); + } + + /// a.png and b.png are browsed copies of one content, c.png and d.png new files with it; the scan + /// names a.png on c.png only (as in `twins_of_a_browsed_photo_are_copies_in_the_source_not_library_duplicates`). + fn browsed_twins() -> ImportDialog { + let a = ImportCandidate { path: "a.png".into(), local: true, existing: Some(1), ..Default::default() }; + let twin = |path: &str, local: bool, stands_in: bool| ImportCandidate { + path: path.into(), + local, + duplicate: Some("content".into()), + browsed_twin: stands_in.then(|| "a.png".into()), + ..Default::default() + }; + ImportDialog::new(vec![a, twin("b.png", true, false), twin("c.png", false, true), twin("d.png", false, false)]) + } + + /// Adding in place the browsed photo is the one brought in and its twins are copies in the + /// source, not photos the library has. + #[test] + fn twins_of_a_browsed_photo_are_copies_in_the_source_not_in_the_library() { + let d = browsed_twins(); + assert_eq!(d.selected_paths(), ["a.png"]); + assert_eq!(dup_counts(&d), (0, 3, 0), "three identical copies, none already in the library"); + } + + /// Copying leaves the browsed photo out (the engine would add it where it is), so the first + /// twin that is a file of its own is what copying brings in: the content isn't in the library. + #[test] + fn copying_brings_in_the_first_twin_of_a_browsed_photo() { + let mut d = browsed_twins(); + d.copy = true; + assert!(!d.importable(0) && !d.importable(1), "browsed photos are not copied"); + assert!(d.importable(2), "the first copy that is a file of its own is"); + assert!(!d.importable(3), "the next one is a copy of it"); + d.checked[2] = true; + assert_eq!(d.selected_paths(), ["c.png"]); + assert_eq!(dup_counts(&d), (1, 2, 0), "a (browsed) counts as there already; b and d are copies; c is offered"); + // back in place: it is a copy again + d.copy = false; + assert!(!d.importable(2)); + assert_eq!(d.selected_paths(), ["a.png"]); + } + + /// Switching to Copy checks the twin that copying brings in, and switching back unchecks it. + #[test] + fn switching_the_transfer_checks_the_twin_that_copying_brings_in() { + let mut d = browsed_twins(); + d.set_transfer(true, false); + assert_eq!(d.selected_paths(), ["c.png"]); + d.set_transfer(false, false); + assert_eq!(d.selected_paths(), ["a.png"]); + assert!(!d.checked[2]); + } + + /// Choosing the transfer already chosen doesn't undo what was checked by hand. + #[test] + fn choosing_the_transfer_again_keeps_a_manual_uncheck() { + let mut d = browsed_twins(); + d.set_transfer(true, false); + d.checked[2] = false; + d.set_transfer(true, true); + assert!(d.selected_paths().is_empty(), "Move after Copy keeps the choice"); + } + + /// A file type's toggle is on only for files that can be imported now. + #[test] + fn a_file_type_toggle_ignores_browsed_photos_that_copying_cannot_import() { + let mut c = ImportCandidate { path: "a.png".into(), local: true, ..Default::default() }; + c.format = "PNG".into(); + let mut d = ImportDialog::new(vec![c]); + d.copy = true; + assert!(!d.type_checked("PNG")); + d.copy = false; + assert!(d.type_checked("PNG")); + } + + /// The review warns that keywords and presets skip a browsed photo only when it matters. + #[test] + fn keywords_and_presets_are_flagged_only_when_a_browsed_photo_would_skip_them() { + let c = ImportCandidate { path: "a.png".into(), local: true, ..Default::default() }; + let mut d = ImportDialog::new(vec![c]); + assert!(!d.options_skip_browsed(), "nothing set, nothing to skip"); + d.keywords = "beach".into(); + assert!(d.options_skip_browsed()); + d.checked[0] = false; + assert!(!d.options_skip_browsed(), "unchecked: not imported anyway"); + d.checked[0] = true; + d.copy = true; + assert!(!d.options_skip_browsed(), "copying doesn't offer it"); + } + + /// A browsed photo whose content is in Recently Deleted is promoted only by "Import as new" (the + /// engine's `Fresh`, which purges the trashed twin); "Restore them" brings the trashed photo back + /// and "Leave them" skips the file, so neither imports the browsed record and the notice stays off. + #[test] + fn the_notice_follows_the_engines_promotion_of_a_browsed_photo_with_a_trashed_twin() { + let c = ImportCandidate { path: "a.png".into(), local: true, duplicate: Some("content".into()), existing: Some(7), ..Default::default() }; + let mut d = ImportDialog::new(vec![c]); + d.set_trashed(vec![true]); + d.keywords = "beach".into(); + d.set_on_deleted("restore"); + assert!(d.checked[0] && !d.options_skip_browsed(), "Restore brings the trashed photo back, not the browsed one"); + d.set_on_deleted("fresh"); + assert!(d.checked[0] && d.options_skip_browsed(), "Import as new promotes the browsed record without the keywords"); + d.set_on_deleted(""); + assert!(!d.checked[0] && !d.options_skip_browsed(), "Leave them: unchecked"); + d.set_on_deleted("fresh"); + d.copy = true; + assert!(!d.options_skip_browsed(), "copying doesn't offer it"); + } + /// Identical copies inside the source folder are not "already in the library" (a fresh library /// said "8 already in the library"). #[test] diff --git a/crates/ui-egui/src/dialogs/import/body.rs b/crates/ui-egui/src/dialogs/import/body.rs index dca39ddd5a..b29d143e43 100644 --- a/crates/ui-egui/src/dialogs/import/body.rs +++ b/crates/ui-egui/src/dialogs/import/body.rs @@ -118,8 +118,12 @@ pub(crate) fn note_dialog_bottom(ui: &egui::Ui) { /// the same bytes as one earlier in the list (no library photo) is a copy in the source. pub(super) fn dup_counts(d: &ImportDialog) -> (usize, usize, usize) { let trashed = d.trashed.iter().filter(|t| **t).count(); - let in_source = d.candidates.iter().filter(|c| c.duplicate.as_deref() == Some("content") && c.existing.is_none()).count(); - let dups = d.candidates.iter().filter(|c| c.duplicate.is_some()).count().saturating_sub(trashed).saturating_sub(in_source); + // (a copy of a browsed photo that copying brings in, because it leaves the browsed one out, is neither) + let twins = (0..d.candidates.len()).filter(|i| d.is_copy_twin(*i)).count(); + let in_source = d.candidates.iter().filter(|c| c.duplicate.as_deref() == Some("content") && c.existing.is_none()).count() - twins; + // (a browsed photo isn't offered while copying: it counts as already there) + let browsed = if d.copy { (0..d.candidates.len()).filter(|i| d.is_browsed(*i)).count() } else { 0 }; + let dups = (d.candidates.iter().filter(|c| c.duplicate.is_some()).count() + browsed).saturating_sub(trashed + twins).saturating_sub(in_source); (dups, in_source, trashed) } @@ -313,21 +317,18 @@ fn body_inner(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDialog) .on_hover_text(crate::i18n::tr("Reference the files where they are")) .clicked() { - d.copy = false; - d.move_files = false; + d.set_transfer(false, false); } let can_copy = app.session.library.as_ref().is_some_and(|l| l.on_disk) || app.services.pick_folder.is_some(); let r = ui.add_enabled_ui(can_copy, |ui| choice(ui, "importCopy", crate::i18n::tr("Copy"), d.copy && !d.move_files)).inner; if r.on_hover_text(crate::i18n::tr("Copy the files (into the library's Originals/, or a folder you choose)")).clicked() { - d.copy = true; - d.move_files = false; + d.set_transfer(true, false); } let r = ui.add_enabled_ui(can_copy, |ui| choice(ui, "importMove", crate::i18n::tr("Move"), d.copy && d.move_files)).inner; if r.on_hover_text(crate::i18n::tr("Move the files (into the library's Originals/, or a folder you choose), removing them from the source")) .clicked() { - d.copy = true; - d.move_files = true; + d.set_transfer(true, true); } }); let r = ui.label( @@ -427,6 +428,14 @@ fn body_inner(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDialog) ); } } + if d.options_skip_browsed() { + let t = Tokens::get(ui.ctx()); + ui.label( + egui::RichText::new(crate::i18n::tr("Keywords and presets apply to new files only, not to photos already in Local")) + .color(t.text_dim) + .small(), + ); + } if d.trashed.iter().any(|t| *t) { field(ui, "In Recently Deleted", |ui| { if let Some(value) = controls::select( @@ -714,9 +723,11 @@ fn candidate_cell(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDial let badge = match (&c.duplicate, &c.error) { // checked with "Leave them", the file goes without `onDeleted`: the engine restores it (Some(_), _) if in_trash && on => Some(if d.on_deleted == "fresh" { "Will be replaced" } else { "Will be restored" }), + (Some(_), _) if d.is_copy_twin(i) => None, (Some(_), _) if in_trash => Some("In Recently Deleted"), (Some(r), _) if r == "path" => Some("In library"), (Some(_), _) => Some("Duplicate"), + (None, None) if d.copy && d.is_browsed(i) => Some("In library"), (None, Some(_)) => Some("Unreadable"), _ => None, }; diff --git a/crates/ui-egui/src/dialogs/import/scan.rs b/crates/ui-egui/src/dialogs/import/scan.rs index 9902262856..112b9f15fd 100644 --- a/crates/ui-egui/src/dialogs/import/scan.rs +++ b/crates/ui-egui/src/dialogs/import/scan.rs @@ -359,7 +359,7 @@ pub fn poll_scan(app: &mut LightcraftApp, ctx: &egui::Context) { } // what the library doesn't know yet joins the Local view let queue: Vec = - out.candidates.iter().filter(|c| c.duplicate != Some("path".into()) && c.error.is_none()).map(|c| c.path.clone()).collect(); + out.candidates.iter().filter(|c| c.duplicate != Some("path".into()) && !c.local && c.error.is_none()).map(|c| c.path.clone()).collect(); if !queue.is_empty() { let undo0 = app.session.undo.len(); let total = queue.len(); @@ -391,7 +391,7 @@ pub fn poll_scan(app: &mut LightcraftApp, ctx: &egui::Context) { }) .collect(); d.set_trashed(trashed); - d.copy = task.copy; + d.set_transfer(task.copy, false); // only an album the review offers (it may have been deleted while the scan ran) d.album = task.album.filter(|id| app.session.catalog.album(lightcraft_catalog::AlbumId(*id)).is_some_and(|a| !a.folder && !a.is_smart())); d.sources = task.sources; diff --git a/crates/ui-egui/src/dialogs/import/task.rs b/crates/ui-egui/src/dialogs/import/task.rs index 18179685f3..c0fcabdc26 100644 --- a/crates/ui-egui/src/dialogs/import/task.rs +++ b/crates/ui-egui/src/dialogs/import/task.rs @@ -204,6 +204,10 @@ impl ImportRun { /// import runs: replacing `app.import` would stop its worker. pub fn start(app: &mut LightcraftApp, d: &ImportDialog) -> Result { busy_synchronizing(app)?; + // a Lightroom catalog import owns the catalog until it ends (its photos may share a file's content), as for a drop + if app.lightroom.is_some() { + return Err(crate::i18n::tr("Finish Lightroom catalog import before adding photos").to_string()); + } if !d.in_library(app) { return Err("another library was opened since the photos were scanned: nothing was imported".into()); } diff --git a/crates/ui-egui/src/dialogs/settings.rs b/crates/ui-egui/src/dialogs/settings.rs index 9021333f7f..766c95a82a 100644 --- a/crates/ui-egui/src/dialogs/settings.rs +++ b/crates/ui-egui/src/dialogs/settings.rs @@ -1,5 +1,5 @@ -//! The Settings dialog (⌘,): General, Import, Performance, Display, Interface, Slideshow, Faces, -//! AI Denoise. +//! The Settings dialog (⌘,): General, Import, Performance (incl. where AI masks run), Display, +//! Interface, Slideshow, Faces, AI Denoise. //! //! Changes apply immediately (no OK/Cancel). Where they are stored: //! - **app settings** ([`crate::state::AppSettings`]: startup view, delete confirmation, GPU, @@ -87,13 +87,23 @@ const PAGE_SIZE: egui::Vec2 = egui::vec2(560.0, 640.0); const PAGE_MIN_HEIGHT: f32 = 120.0; /// The share of the page's room the pinned slide preview of the Slideshow tab takes, when the page -/// has more room than it needs to keep [`PAGE_MIN_HEIGHT`] for itself. +/// has more room than it needs to keep [`PINNED_PAGE_MIN_HEIGHT`] for itself. const PINNED_PREVIEW_SHARE: f32 = 0.4; /// What the preview's heading, the one-line hint under the slide, its Photo / Intro / Ending /// choice and the rule under it take around the slide (at the default spacing, about 82 pt). const PREVIEW_CHROME: f32 = 82.0; +/// What the same takes once the page has been drawn a second time (measured, at the default +/// spacing: 104 pt). The room a pinned preview leaves for the page is checked against this, not +/// against [`PREVIEW_CHROME`], so a window just tall enough never ends up with a page below +/// its least and a dialog that grows a point on this tab. +const PREVIEW_CHROME_DRAWN: f32 = 104.0; + +/// The least room the page keeps under the pinned preview: a few rows, with the filter row above +/// them in the smallest window (900 x 560) that the preview is still pinned in. +const PINNED_PAGE_MIN_HEIGHT: f32 = 100.0; + /// The Settings window's content: the tab bar, which stays put, above the page of `tab` /// ([`body`]), which scrolls when it is taller than the room for it, with a scroll handle that /// shows without the pointer on it. `max_height` is the room the app window leaves for both: the @@ -111,51 +121,105 @@ pub fn window(app: &mut LightcraftApp, ui: &mut egui::Ui, tab: &mut String, max_ // the next frame, so a text box on the page being left is drawn once more and saves what was // typed in it (the click took the focus from it). let shown = tab.clone(); + // The filter, above the tabs it looks through. What is typed is kept from one frame of the + // window to the next only: Settings opened again starts with it empty. + let filter_id = egui::Id::unique("settings-filter"); + let pass = ui.ctx().cumulative_pass_nr(); + let kept: Option = ui.data(|d| d.get_temp(filter_id)); + let mut filter = kept.filter(|k| k.pass == pass || k.pass.checked_add(1) == Some(pass)).unwrap_or_default(); + filter.pass = pass; + let had_text = !filter.text.is_empty(); + let to_first = controls::live(ui) && ui.is_enabled() && crate::text_field::focused(ui.ctx(), "field:settingsFilter") && { + use craft::ui::runtime::keys::{self, Intent, MoveMods, NavMove}; + let id = Some(crate::text_field::id("field:settingsFilter")); + let mut intents = keys::intents_of(ui.ctx(), id, false); + let down = intents.take_exact(&Intent::Move(NavMove::Down, MoveMods::PLAIN)); + if down { + keys::settle(ui.ctx(), id, &intents); + } + down || ui.input(|i| i.key_pressed(egui::Key::ArrowDown)) + }; + let escape_pressed = ui.input(|i| i.key_pressed(egui::Key::Escape)) + || (controls::live(ui) + && ui.is_enabled() + && had_text + && !crate::dialogs::popup_open(ui.ctx()) + && craft::ui::runtime::keys::with_window_intents(ui.ctx(), false, |intents| intents.take(craft::ui::runtime::keys::Intent::Cancel))); + let typed = crate::text_field::TextField::singleline("field:settingsFilter", &mut filter.text) + .hint(crate::i18n::tr("Filter settings")) + .width(ui.available_width()) + .show(ui); + let filter_row = ui.cursor().top() - top; + // Esc with something typed empties the filter and is used up by that, wherever the focus is + // (in the box, or on a section that was found); the focus goes back to the box. Not while the + // dialog is disabled behind a prompt or the library window: that owns the keys (`dialogs::show`). + let owns_keys = ui.is_enabled(); + let escape = owns_keys && had_text && !crate::widgets::escape_taken(ui.ctx()) && escape_pressed; + if owns_keys && (typed.cancelled() || escape) { + filter.text.clear(); + if had_text { + crate::widgets::take_escape(ui.ctx()); + crate::text_field::focus(ui.ctx(), "field:settingsFilter"); + } + } + // (an emptied filter forgets what it read: the pages are read afresh the next time it is + // used, so what is found is what they show then) + if filter.text.trim().is_empty() { + filter.sections = None; + } + // ↓ in the box goes to the first section found + let open_first = typed.ending == Some(crate::text_field::Ending::Return); + // (with something typed the page is what was found, of any tab: no tab is the open one) + let filtering = !filter.text.trim().is_empty(); ui.horizontal_wrapped(|ui| { ui.spacing_mut().item_spacing = egui::vec2(4.0, 4.0); for (id, label) in TABS { - if crate::widgets::text_button(ui, &format!("settingsTab-{id}"), label, shown == *id).clicked() { + if crate::widgets::text_button(ui, &format!("settingsTab-{id}"), label, shown == *id && !filtering).clicked() { *tab = id.to_string(); ui.ctx().request_repaint(); + // (a tab opened is its page asked for: the filter gives way) + filter.text.clear(); } } }); ui.separator(); + // With something typed, the page gives way to the sections found, of whatever tab. + let words = filter.text.trim().to_lowercase(); + let now = ui.input(|i| i.time); + let found = (!words.is_empty()).then(|| filter.found(app, &words, now)); + let mut goto = None; // (a point less than the room left, so rounding never makes the dialog's own scroll area scroll) let room = max_height - (ui.cursor().top() - top) - 1.0; - if room < PAGE_MIN_HEIGHT { - body(app, ui, shown.as_str()); - register(ui, "settings:page", ui.min_rect()); - return; - } let mut height = room.min(PAGE_SIZE.y); // The slide preview stays above the page on Slideshow: hovering a template in the Template // Browser previews it there, so it has to stay in view however far down the templates are // scrolled to. With its heading and choice it takes [`PINNED_PREVIEW_SHARE`] of the room - // (at least the least tall slide); where that leaves less than [`PAGE_MIN_HEIGHT`] for the - // page, it scrolls with the page instead (as in the short window above). + // (at least the least tall slide); where that leaves less than [`PINNED_PAGE_MIN_HEIGHT`] for the + // page, it scrolls with the page instead (as in the short window above). What was found + // is drawn in its place while the filter has something typed. let mut pinned = false; - if shown == "slideshow" { - let slide_h = (height * PINNED_PREVIEW_SHARE - PREVIEW_CHROME).max(crate::panels::slide_layout::PREVIEW_MIN_H); - if height - (slide_h + PREVIEW_CHROME) >= PAGE_MIN_HEIGHT { + if shown == "slideshow" && found.is_none() && room >= PAGE_MIN_HEIGHT { + // (the filter row is taken off the page, not off the preview: the slide is as large as it was) + let slide_h = ((room + filter_row).min(PAGE_SIZE.y) * PINNED_PREVIEW_SHARE - PREVIEW_CHROME).max(crate::panels::slide_layout::PREVIEW_MIN_H); + if height - (slide_h + PREVIEW_CHROME_DRAWN) >= PINNED_PAGE_MIN_HEIGHT { let before = ui.cursor().top(); crate::panels::slide_layout::preview(app, ui, &Tokens::get(ui.ctx()), slide_h); ui.add_space(2.0); ui.separator(); - height = (height - (ui.cursor().top() - before)).max(PAGE_MIN_HEIGHT); + height = (height - (ui.cursor().top() - before)).max(PINNED_PAGE_MIN_HEIGHT); pinned = true; } } - // A page that goes on below shows its scroll handle all the time: without it, a page a line - // or two too long looks cut off, not scrollable. - ui.spacing_mut().scroll.dormant_handle_opacity = 0.6; - let page = egui::ScrollArea::vertical() - .id_salt(("settings-page", shown.as_str())) - .max_height(height) - .min_scrolled_height(height) - .auto_shrink([false, false]) - .show(ui, |ui| { - ui.add_space(2.0); + let mut page = |ui: &mut egui::Ui| match &found { + Some(found) => goto = results(ui, found, &words, open_first, to_first), + None => { + // (a section chosen that starts its tab, with no heading of its own: the page goes to its top) + if ui + .data(|d| d.get_temp::<(&'static str, String)>(egui::Id::unique(GOTO))) + .is_some_and(|(to, section)| to == tab.as_str() && section.is_empty()) + { + ui.scroll_to_cursor(Some(egui::Align::TOP)); + } if pinned { slideshow_tab(app, ui, &Tokens::get(ui.ctx()), false); } else { @@ -163,6 +227,269 @@ pub fn window(app: &mut LightcraftApp, ui: &mut egui::Ui, tab: &mut String, max_ } // (what the page took: wider than the room for it would mean a control is cut off) register(ui, "settings:page", ui.min_rect()); + } + }; + if room < PAGE_MIN_HEIGHT { + page(ui); + } else { + // A page that goes on below shows its scroll handle all the time: without it, a page a + // line or two too long looks cut off, not scrollable. + ui.spacing_mut().scroll.dormant_handle_opacity = 0.6; + let salt = if found.is_some() { "found" } else { shown.as_str() }; + let area = egui::ScrollArea::vertical() + .id_salt(("settings-page", salt)) + .max_height(height) + .min_scrolled_height(height) + .auto_shrink([false, false]) + .show(ui, |ui| { + ui.add_space(2.0); + page(ui); + }); + register(ui, "settings:pageRoom", area.inner_rect); + } + // A section chosen from what was found: its tab opens (on the next frame, as a clicked tab + // does), the filter is emptied, and the section's heading is scrolled to when it is drawn. + let goto_id = egui::Id::unique(GOTO); + if let Some((to, section)) = goto { + *tab = to.to_string(); + filter.text.clear(); + ui.data_mut(|d| d.insert_temp(goto_id, (to, section))); + ui.ctx().request_repaint(); + } else if ui.data(|d| d.get_temp::<(&'static str, String)>(goto_id)).is_some_and(|(to, _)| to == tab.as_str()) { + // (the page it was for has been drawn: its heading has had its chance) + ui.data_mut(|d| d.remove::<(&'static str, String)>(goto_id)); + } + ui.data_mut(|d| d.insert_temp(filter_id, filter)); +} + +/// Where the section to scroll to is kept between the click on a result and its page being drawn. +const GOTO: &str = "settings-goto"; + +/// A section of Settings as the filter knows it: the tab it is on, its heading's English name +/// (empty for what a tab draws above its first heading) and every piece of text it draws. +#[derive(Clone)] +struct Section { + tab: &'static str, + name: String, + texts: Vec, +} + +/// The filter's state between frames: what is typed, and the sections of every tab with their +/// text, read once for the language, library and display profile they were read in. (What is +/// typed is kept only from one pass to the next: a pass in which Settings is not drawn loses it.) +#[derive(Clone, Default)] +struct Filter { + pass: u64, + text: String, + sections: Option<(String, std::sync::Arc>)>, +} + +impl Filter { + /// The sections that have every word of `words` (lower case), in the order of the tabs. + fn found(&mut self, app: &mut LightcraftApp, words: &str, now: f64) -> Vec
{ + let of = format!( + "{}|{}|{:?}", + app.ui.language.code(), + app.session.library.as_ref().map(|l| l.dir.display().to_string()).unwrap_or_default(), + // (the Display page says which profile is in use) + app.renderer.display_id() + ); + let sections = match &self.sections { + Some((read_for, sections)) if *read_for == of => sections.clone(), + _ => { + let sections = std::sync::Arc::new(sections(app, now)); + self.sections = Some((of, sections.clone())); + sections + } + }; + sections.iter().filter(|section| section.has(words)).cloned().collect() + } +} + +impl Section { + /// The name of the section's tab, in the language shown. + fn tab_name(&self) -> &'static str { + TABS.iter().find(|(id, _)| *id == self.tab).map_or("", |(_, label)| crate::i18n::tr(label)) + } + + /// Whether the section, with the name of its tab, has every word of `words` (lower case). + fn has(&self, words: &str) -> bool { + let all = format!("{} {}", self.tab_name(), self.texts.join(" ")).to_lowercase(); + words.split_whitespace().all(|word| all.contains(word)) + } + + /// What the section is called in the list of what was found: its tab, then its heading. + fn title(&self) -> String { + let tab = self.tab_name(); + if self.name.is_empty() { tab.to_string() } else { format!("{tab} › {}", crate::i18n::tr(&self.name)) } + } +} + +/// The key [`sections`] sets in the context it reads the pages in. +const READING_FOR_FILTER: &str = "settingsReadingForFilter"; + +/// Whether `ctx` is the context the filter reads the pages in ([`sections`]): a page draws as usual but starts no work +/// (a render, say) for text nobody sees. +pub(crate) fn reading_for_filter(ctx: &egui::Context) -> bool { + ctx.data(|d| d.get_temp::(egui::Id::unique(READING_FOR_FILTER))).unwrap_or(false) +} + +/// Every section of every tab with the text it draws, read by drawing each tab's page once in a +/// context of its own: nothing of it reaches the screen, the list of widgets or the window's own +/// memory, and whatever a tab draws is found without a list kept by hand. Drawing a page asks +/// what opening its tab asks (the smart previews folder, the installed models): the answers the +/// app keeps (the installed denoise models) are filled as opening the tab fills them, and those a +/// page keeps in its own context (the smart previews folder, the face models) are asked again. +/// The pages know they are only being read ([`reading_for_filter`]): the slide preview of +/// Slideshow is not asked to render, as nothing of it is shown. No setting is +/// changed by it, as nothing is clicked. What a page does not draw is not found: the choices of +/// a closed list, tooltips, and rows scrolled out of a list inside a page. +fn sections(app: &mut LightcraftApp, now: f64) -> Vec
{ + fn texts(shape: &egui::Shape, out: &mut Vec<(f32, String)>) { + match shape { + egui::Shape::Text(text) => out.push((text.pos.y, text.galley.job.text.clone())), + egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| texts(shape, out)), + _ => {} + } + } + let scratch = egui::Context::default(); + if let Err(error) = app.try_install_framework(&scratch) { + log::warn!("Settings filter: {error}"); + return Vec::new(); + } + scratch.data_mut(|d| d.insert_temp(egui::Id::unique(READING_FOR_FILTER), true)); + crate::theme::install_fonts(&scratch); + // (tall enough that no page is cut off: what is outside the screen is not drawn) + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(PAGE_SIZE.x + 32.0, 20_000.0)); + let mut all = Vec::new(); + for (tab, _) in TABS { + // (on the window's clock: what a page remembers with the time it asked is not left stamped + // with another) + let input = egui::RawInput { screen_rect: Some(screen), time: Some(now), ..Default::default() }; + let mut output = scratch.run_ui(input, |ui| { + ui.set_width(PAGE_SIZE.x); + body(app, ui, tab); }); - register(ui, "settings:pageRoom", page.inner_rect); + // (the font atlas this context made is for no screen: said so, or dropping it is an error) + output.textures_delta.clear(); + // the page's headings, top to bottom, and each text under the last heading above it + let mut headings: Vec<(f32, String)> = crate::widgets::take_registry(&scratch) + .into_iter() + .filter_map(|(id, r)| Some((r.top(), id.strip_prefix("heading:")?.to_string()))) + .collect(); + headings.sort_by(|a, b| a.0.total_cmp(&b.0)); + let mut drawn = Vec::new(); + output.shapes.iter().for_each(|clipped| texts(&clipped.shape, &mut drawn)); + drawn.sort_by(|a, b| a.0.total_cmp(&b.0)); + let mut of_tab: Vec
= std::iter::once(String::new()) + .chain(headings.iter().map(|(_, name)| name.clone())) + .map(|name| Section { tab, name, texts: Vec::new() }) + .collect(); + for (y, text) in drawn { + // (a text counts as under a heading from a little above the heading's own top) + let under = headings.iter().take_while(|(top, _)| *top <= y + 1.0).count(); + if let Some(section) = of_tab.get_mut(under) + && !text.trim().is_empty() + { + section.texts.push(text); + } + } + all.extend(of_tab.into_iter().filter(|section| !section.texts.is_empty())); + } + all +} + +/// The sections found, each a row to choose (`settingsFound:{tab}:{section}`): its tab and +/// heading, and under them the first texts of it that have a word of `words`. Gives the section +/// chosen, by a click, by Return or Space with the focus on it, or (`open_first`) by Return in +/// the filter, which chooses the first. `focus_first` gives the first row the keyboard focus. +fn results(ui: &mut egui::Ui, found: &[Section], words: &str, open_first: bool, focus_first: bool) -> Option<(&'static str, String)> { + let t = Tokens::get(ui.ctx()); + if found.is_empty() { + ui.add_space(8.0); + ui.label(RichText::new(crate::i18n::tr("No setting matches what is typed.")).color(t.text_label)); + hint(ui, &t, "Try one word, or part of one: the names of tabs and sections, labels and explanations are all looked through."); + return None; + } + use craft::ui::buttons::Button; + use craft::ui::contract::{Props as _, Show as _, Sizing}; + use craft::ui::runtime::focus::{self, FocusTarget}; + + let real = controls::live(ui); + let mut chosen = (real && ui.is_enabled() && open_first).then(|| found.first().map(|first| (first.tab, first.name.clone()))).flatten(); + for (place, section) in found.iter().enumerate() { + let heading = crate::i18n::tr(§ion.name); + let detail = section + .texts + .iter() + .map(String::as_str) + .filter(|text| *text != heading && words.split_whitespace().any(|word| text.to_lowercase().contains(word))) + .take(2) + .collect::>() + .join("\n"); + let id = egui::Id::unique(("settings-result", section.tab, §ion.name)); + if real && ui.is_enabled() && focus_first && place == 0 { + focus::request(ui.ctx(), FocusTarget::Id(id)); + } + let row = Button::new(section.title()).id(id).detail(detail).align(craft::ui::primitives::HAlign::Start).sizing(Sizing::FillWidth).show(ui); + if real { + crate::widgets::register_response(format!("settingsFound:{}:{}", section.tab, section.name), row.response.rect, &row.response); + if ui.is_enabled() && row.clicked() { + chosen = Some((section.tab, section.name.clone())); + } + } + } + chosen +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::Services; + + /// One pass of the Settings window with the filter holding `text` and Escape pressed, in a ui + /// that is disabled (`dialogs::show` does that while a prompt or the library window owns input) + /// or not; what the filter holds afterwards. + fn text_after_escape(enabled: bool) -> String { + let mut app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, ..Default::default() }); + let ctx = egui::Context::default(); + crate::app::install_runtime(&ctx).expect("fresh filter test runtime"); + crate::theme::install_fonts(&ctx); + let mut tab = "general".to_string(); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 900.0)); + let mut pass = |app: &mut LightcraftApp, events: Vec, enabled: bool| { + let input = egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }; + let mut output = ctx.run_ui(input, |ui| { + if !enabled { + ui.disable(); + } + window(app, ui, &mut tab, 800.0); + }); + output.textures_delta.clear(); + }; + let filter_id = egui::Id::unique("settings-filter"); + // (a pass draws the window, which keeps its filter for the pass after it) + pass(&mut app, Vec::new(), true); + ctx.data_mut(|d| { + let mut kept: Filter = d.get_temp(filter_id).expect("the window keeps its filter"); + kept.text = "sidecar".into(); + d.insert_temp(filter_id, kept); + }); + let escape = egui::Event::Key { + key: egui::Key::Escape, + physical_key: Some(egui::Key::Escape), + pressed: true, + repeat: false, + modifiers: egui::Modifiers::NONE, + }; + pass(&mut app, vec![escape], enabled); + let kept: Filter = ctx.data(|d| d.get_temp(filter_id)).expect("the filter is kept"); + kept.text + } + + #[test] + fn escape_empties_the_filter_only_while_the_dialog_owns_the_keys() { + assert_eq!(text_after_escape(true), "", "Escape empties what was typed"); + assert_eq!(text_after_escape(false), "sidecar", "behind a prompt or the library window it is not the dialog's"); + } } diff --git a/crates/ui-egui/src/dialogs/settings/appearance.rs b/crates/ui-egui/src/dialogs/settings/appearance.rs index 03fc744b31..a914ae3582 100644 --- a/crates/ui-egui/src/dialogs/settings/appearance.rs +++ b/crates/ui-egui/src/dialogs/settings/appearance.rs @@ -6,7 +6,7 @@ use super::{RichText, Tokens, register}; /// use is outlined. Applied on the next frame ([`LightcraftApp::sync_theme`]). pub(super) fn appearance(ui: &mut egui::Ui, t: &Tokens, s: &mut crate::state::AppSettings, system: Option) { use crate::state::{AppearanceMode as M, DarkTheme, LightTheme}; - heading(ui, t, crate::i18n::tr("Appearance")); + heading(ui, t, "Appearance"); ui.label(RichText::new(crate::i18n::tr("Appearance Mode")).color(t.text_label)); ui.horizontal_wrapped(|ui| { choices(ui, "settingsAppearance", &[(M::Auto, "Sync with System"), (M::Dark, "Dark Mode"), (M::Light, "Light Mode")], &mut s.appearance_mode); diff --git a/crates/ui-egui/src/dialogs/settings/display.rs b/crates/ui-egui/src/dialogs/settings/display.rs index 0a158ebfba..416139b3c1 100644 --- a/crates/ui-egui/src/dialogs/settings/display.rs +++ b/crates/ui-egui/src/dialogs/settings/display.rs @@ -1,7 +1,7 @@ use super::appearance::appearance; use super::widgets::{check, choices, heading, hint, path_label, row}; -use crate::widgets::register; use super::{GridBadges, LightcraftApp, RichText, Tokens, Value, json}; +use crate::widgets::register; // ---------------------------------------------------------------------------------- Interface @@ -14,7 +14,7 @@ pub(super) fn display_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens fn monitor_profile_sdk(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { use craft::ui::contract::{Props as _, Show as _}; let real = !ui.is_sizing_pass() && !craft::ui::runtime::measure::active(ui.ctx()); - heading(ui, t, crate::i18n::tr("Monitor profile")); + heading(ui, t, "Monitor profile"); let current = app.renderer.display().cloned(); let screen = current.as_ref().is_some_and(|d| d.path == crate::SCREEN_PROFILE); row(ui, t, crate::i18n::tr("Profile"), |ui| { @@ -114,10 +114,10 @@ pub(super) fn interface_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Toke app.ui.settings.reduce_motion = None; } }); - heading(ui, t, crate::i18n::tr("Filmstrip")); + heading(ui, t, "Filmstrip"); check(ui, "settings.filmNames", &mut app.ui.settings.film_names, "Show file names"); check(ui, "settings.filmBadges", &mut app.ui.settings.film_badges, "Show ratings, flags and edit badges"); - heading(ui, t, crate::i18n::tr("Grid")); + heading(ui, t, "Grid"); row(ui, t, crate::i18n::tr("Ratings & flags"), |ui| { choices( ui, @@ -128,7 +128,7 @@ pub(super) fn interface_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Toke }); hint(ui, t, "Stars on hover: flags and colour labels always show; the stars and the edited mark appear while a photo is hovered or selected."); check(ui, "settings.showFilenames", &mut app.ui.show_filenames, "Square Grid: show file names and formats"); - heading(ui, t, crate::i18n::tr("Keywords")); + heading(ui, t, "Keywords"); row(ui, t, crate::i18n::tr("Keywords of the selection"), |ui| { use crate::state::KeywordChips as K; choices(ui, "settingsKeywordChips", &[(K::Paths, "Whole names"), (K::Grouped, "Grouped by parent")], &mut app.ui.settings.keyword_chips); @@ -138,22 +138,22 @@ pub(super) fn interface_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Toke t, crate::i18n::tr("Grouped: keywords inside the same keyword share a line naming it, and long lists and the suggestions are shortened."), ); - heading(ui, t, crate::i18n::tr("Detail View")); + heading(ui, t, "Detail View"); check(ui, "settings.navigator", &mut app.ui.navigator, "Show the Navigator while zoomed in"); row(ui, t, crate::i18n::tr("Info overlay"), |ui| { use crate::state::InfoOverlay as I; choices(ui, "settingsInfo", &[(I::Off, "Off"), (I::Basic, "Info 1"), (I::Exposure, "Info 2")], &mut app.ui.info_overlay); }); - hint(ui, t, crate::i18n::tr("View → View Options chooses the lines Info 1 and Info 2 show.")); + hint(ui, t, crate::i18n::tr("View → Loupe Overlay → View Options chooses the lines Info 1 and Info 2 show.")); } -/// View ▸ View Options (⌘J), Lightroom Classic's Loupe View tab: whether the info overlay shows and +/// View ▸ Loupe Overlay ▸ View Options… (⌘J), Lightroom Classic's Loupe View tab: whether the info overlay shows and /// which, the three lines each of Info 1 and Info 2 shows, which of them shows briefly when the /// photo changes, and whether the loupe shows its loading and rendering message /// (`view.viewOptions`). Changes apply as they are made. pub(in super::super) fn view_options(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { use crate::state::{InfoOverlay as I, LoupeInfo, LoupeInfoField as F}; - heading(ui, t, crate::i18n::tr("Loupe View")); + heading(ui, t, "Loupe View"); let mut show = app.ui.info_overlay != I::Off; if check(ui, "viewOptions.showInfo", &mut show, "Show Info Overlay") { app.ui.info_overlay = if show { I::Basic } else { I::Off }; @@ -164,7 +164,7 @@ pub(in super::super) fn view_options(app: &mut LightcraftApp, ui: &mut egui::Ui, }); }); for (n, title, defaults) in [(1, "Loupe Info 1", LoupeInfo::INFO1), (2, "Loupe Info 2", LoupeInfo::INFO2)] { - heading(ui, t, crate::i18n::tr(title)); + heading(ui, t, title); let lines = if n == 1 { &mut app.ui.settings.loupe_info.info1 } else { &mut app.ui.settings.loupe_info.info2 }; for (i, line) in lines.iter_mut().enumerate() { let id = format!("viewOptionsInfo{n}Line{}", i + 1); @@ -238,7 +238,7 @@ pub(in super::super) fn view_options(app: &mut LightcraftApp, ui: &mut egui::Ui, app.ui.settings.loupe_info.briefly = if briefly { info } else { I::Off }; } } - heading(ui, t, crate::i18n::tr("General")); + heading(ui, t, "General"); check(ui, "viewOptions.loupeMessages", &mut app.ui.settings.loupe_messages, "Show message when loading or rendering photos"); } diff --git a/crates/ui-egui/src/dialogs/settings/general.rs b/crates/ui-egui/src/dialogs/settings/general.rs index bafe39f147..cff1644214 100644 --- a/crates/ui-egui/src/dialogs/settings/general.rs +++ b/crates/ui-egui/src/dialogs/settings/general.rs @@ -24,7 +24,7 @@ pub(super) fn general_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens &mut app.ui.settings.lightroom_import, ); }); - heading(ui, t, crate::i18n::tr("Startup")); + heading(ui, t, "Startup"); row(ui, t, crate::i18n::tr("Open in"), |ui| { choices( ui, @@ -33,13 +33,13 @@ pub(super) fn general_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens &mut app.ui.settings.startup_view, ); }); - heading(ui, t, crate::i18n::tr("Culling")); + heading(ui, t, "Culling"); check(ui, "settings.autoAdvance", &mut app.ui.auto_advance, "Auto Advance: move to the next photo after rating or flagging"); check(ui, "settings.confirmDelete", &mut app.ui.settings.confirm_delete, "Confirm before moving photos to Recently Deleted"); check(ui, "settings.askBeforeMove", &mut app.ui.settings.ask_before_move, "Confirm before moving photos to another folder on disk"); - heading(ui, t, crate::i18n::tr("Dialogs")); + heading(ui, t, "Dialogs"); check(ui, "settings.closeDialogsOutside", &mut app.ui.settings.close_dialogs_outside, "Close a dialog by clicking outside it"); - heading(ui, t, crate::i18n::tr("External Editing")); + heading(ui, t, "External Editing"); row(ui, t, crate::i18n::tr("PhotoCraft"), |ui| { field( ui, @@ -79,7 +79,7 @@ pub(super) fn general_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens /// The live General Library/launch section. Host UI state still owns the launch preference. fn library_launch_section(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { - heading(ui, t, crate::i18n::tr("Library")); + heading(ui, t, "Library"); let location = match &app.session.library { Some(l) => l.dir.display().to_string(), None => crate::i18n::tr("In memory — nothing is saved").to_string(), @@ -145,7 +145,7 @@ mod general_library_launch_flow_tests; #[cfg(not(target_arch = "wasm32"))] fn lens_profiles(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { use lightcraft_engine::lensfun_download::{self, Offer}; - heading(ui, t, crate::i18n::tr("Lens profiles")); + heading(ui, t, "Lens profiles"); let running = app.session.lensfun.running(); // (the user's own folder, LIGHTCRAFT_LENSFUN_DIR, is read instead and never replaced) let own = std::env::var_os(lightcraft_engine::lens_profiles::ENV).is_some_and(|v| !v.is_empty()); diff --git a/crates/ui-egui/src/dialogs/settings/import.rs b/crates/ui-egui/src/dialogs/settings/import.rs index 62b13f3491..4ec4670a95 100644 --- a/crates/ui-egui/src/dialogs/settings/import.rs +++ b/crates/ui-egui/src/dialogs/settings/import.rs @@ -64,7 +64,7 @@ fn camera_entries(app: &LightcraftApp, ui: &egui::Ui, raw_default: &str) -> std: pub(super) fn import_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { let d = app.session.import_defaults.clone(); - heading(ui, t, crate::i18n::tr("Raw defaults")); + heading(ui, t, "Raw defaults"); hint(ui, t, crate::i18n::tr("Settings new raw photos start from. Changing them doesn't touch photos already in the library.")); row(ui, t, crate::i18n::tr("Raw photos"), |ui| { if let Some(v) = preset_combo(app, ui, "settingsRawPreset", crate::i18n::tr("Raw default"), d.raw_preset.as_deref(), "LightCraft Default") { @@ -118,13 +118,13 @@ pub(super) fn import_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) } }); } - heading(ui, t, crate::i18n::tr("Other images (JPEG, PNG, TIFF, HEIC…)")); + heading(ui, t, "Other images (JPEG, PNG, TIFF, HEIC…)"); row(ui, t, crate::i18n::tr("Non-raw photos"), |ui| { if let Some(v) = preset_combo(app, ui, "settingsOtherPreset", crate::i18n::tr("Other preset"), d.other_preset.as_deref(), "None") { let _ = app.run("library.preferences", json!({"import": {"otherPreset": v}})); } }); - heading(ui, t, crate::i18n::tr("Metadata")); + heading(ui, t, "Metadata"); hint(ui, t, crate::i18n::tr("Added to photos you import that don't already have it.")); for (key, label, hint_text, value) in [("copyright", "Copyright", "© 2026 Your Name", d.copyright.clone()), ("creator", "Creator", "Your Name", d.creator.clone())] @@ -166,7 +166,7 @@ pub(super) fn import_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) } }); } - heading(ui, t, crate::i18n::tr("XMP sidecars")); + heading(ui, t, "XMP sidecars"); let mut xmp = app.session.xmp; if check(ui, "settings.autoWriteXmp", &mut xmp.auto_write, "Automatically write changes into XMP sidecars") { let _ = app.run("library.xmpPreferences", json!({"autoWrite": xmp.auto_write})); @@ -180,14 +180,14 @@ pub(super) fn import_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) } }); if !cfg!(target_arch = "wasm32") { - heading(ui, t, crate::i18n::tr("Dropped Files")); + heading(ui, t, "Dropped Files"); check(ui, "settings.importDropped", &mut app.ui.settings.import_dropped_directly, "Import dropped files without review"); - heading(ui, t, crate::i18n::tr("Cameras and Cards")); + heading(ui, t, "Cameras and Cards"); let mut on_card = d.show_on_card; if check(ui, "settings.importOnCard", &mut on_card, "Show the import review when a camera or card is connected") { let _ = app.run("library.preferences", json!({"import": {"showOnCard": on_card}})); } - heading(ui, t, crate::i18n::tr("Auto Import")); + heading(ui, t, "Auto Import"); hint(ui, t, crate::i18n::tr("Photos that arrive in this folder (tethering, a scanner, a sync app) are added as soon as they're complete.")); row(ui, t, crate::i18n::tr("Watched folder"), |ui| { match &d.auto_folder { diff --git a/crates/ui-egui/src/dialogs/settings/libraries.rs b/crates/ui-egui/src/dialogs/settings/libraries.rs index 57cd17f92c..85af712ae2 100644 --- a/crates/ui-egui/src/dialogs/settings/libraries.rs +++ b/crates/ui-egui/src/dialogs/settings/libraries.rs @@ -100,6 +100,10 @@ fn switch_library(app: &mut LightcraftApp, path: &str) -> Result app.ui.reference = None; app.ui.compare = None; app.ui.brief_info = crate::state::BriefInfo::default(); + // (masks hidden with O, and the hovered mask, are keyed by photo ID too) + app.ui.mask_overlay_hidden.clear(); + app.ui.mask_hover = None; + app.ui.mask_hover_prev = None; // a keyword picked in the Keyword List belongs to the library being left app.ui.keyword_list_selected = None; if app.ui.view == crate::state::ViewMode::Reference { diff --git a/crates/ui-egui/src/dialogs/settings/performance.rs b/crates/ui-egui/src/dialogs/settings/performance.rs index 07da02b7df..12e518ff55 100644 --- a/crates/ui-egui/src/dialogs/settings/performance.rs +++ b/crates/ui-egui/src/dialogs/settings/performance.rs @@ -9,7 +9,7 @@ use super::{ pub(super) fn performance_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { use lightcraft_engine::gpu; - heading(ui, t, crate::i18n::tr("Rendering")); + heading(ui, t, "Rendering"); #[cfg(target_os = "windows")] check(ui, "settings.composeWindow", &mut app.ui.settings.compose_window, "Prevent G-SYNC/FreeSync flicker (applies at next launch)"); check(ui, "settings.gpu", &mut app.ui.settings.gpu, "Use the GPU for rendering"); @@ -68,7 +68,7 @@ pub(super) fn performance_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &To ); preview_cache_section(app, ui, t); background_prep(app, ui, t); - heading(ui, t, crate::i18n::tr("Local folders")); + heading(ui, t, "Local folders"); row(ui, t, crate::i18n::tr("Forget unchanged photos"), |ui| { let opts = [(0u32, "Never"), (7, "After 7 days"), (30, "After 30 days"), (90, "After 90 days"), (365, "After a year")]; let mut v = app.session.forget_local_days; @@ -85,13 +85,66 @@ pub(super) fn performance_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &To ); #[cfg(not(target_arch = "wasm32"))] smart_previews(app, ui, t); + ai_masks(app, ui, t); +} + +/// Where AI masks (SAM 3) run: the choice (`segment.settings {runOn}`), what they run on, why not on +/// the GPU, and how long the last photo took (`segment.model.status` → `backend`), as Settings ▸ +/// Faces shows its models' processor. The same lines whatever the state, so nothing moves when the +/// model loads. +fn ai_masks(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { + if !lightcraft_engine::segment::Segmenter::AVAILABLE { + return; + } + heading(ui, t, "AI masks"); + let current = app.session.segmenter.run_on().name(); + let mut run_on = current; + if row(ui, t, "Run on", |ui| choices(ui, "settingsAiMasksRunOn", &[("auto", "Automatic (GPU when available)"), ("cpu", "CPU")], &mut run_on)) + && let Err(e) = app.run("segment.settings", json!({"runOn": run_on})) + { + app.toast(ui.ctx(), e); + } + let g = &app.session.segmenter; + let b = g.backend(); + let device = if g.remote_endpoint().is_some() { + crate::i18n::tr("Remote worker").to_string() + } else { + b["device"].as_str().map_or_else(|| crate::i18n::tr("Not loaded yet").to_string(), str::to_string) + }; + let text = match b["fallback"].as_str() { + Some(why) if g.remote_endpoint().is_none() => format!("{device} ({why})"), + _ => device, + }; + row(ui, t, "Device", |ui| { + let r = ui.add(egui::Label::new(RichText::new(text.clone()).color(t.text)).truncate()).on_hover_text(text); + register(ui, "settings:aiMasksDevice", r.rect); + }); + let took = match (b["analyzeMs"].as_u64().or(b["encodeMs"].as_u64()), b["encodeMs"].as_u64()) { + (Some(all), Some(encoder)) => { + crate::i18n::tr_format!("{all:.1} s, image encoder {encoder:.1} s", all = all as f64 / 1000.0, encoder = encoder as f64 / 1000.0) + } + _ => "—".to_string(), + }; + row(ui, t, "Last photo", |ui| { + let r = ui.label(RichText::new(took).color(t.text)); + register(ui, "settings:aiMasksTime", r.rect); + }); + hint( + ui, + t, + crate::i18n::tr(if cfg!(target_os = "macos") { + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer." + } else { + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer." + }), + ); } /// Settings ▸ Performance ▸ Prepare photos in the background (notes 47 and 48): per mode, what /// is made ready before the user gets to it (`prefs.backgroundPrep`), app-wide or for this library. fn background_prep(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { use lightcraft_engine::prep::{Mode, Scope}; - heading(ui, t, crate::i18n::tr("Prepare photos in the background")); + heading(ui, t, "Prepare photos in the background"); hint( ui, t, @@ -191,7 +244,7 @@ fn smart_previews(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { if loc.is_null() { return; } - heading(ui, t, crate::i18n::tr("Smart previews")); + heading(ui, t, "Smart previews"); let path = loc["path"].as_str().unwrap_or_default().to_string(); let available = loc["available"].as_bool().unwrap_or(true); let custom = loc["custom"].as_bool().unwrap_or(false); @@ -318,7 +371,7 @@ mod clear_preview_cache_port_tests; /// The Preview cache subsection. Showing it alone does not probe GPU availability or local folders. fn preview_cache_section(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { - heading(ui, t, crate::i18n::tr("Preview cache")); + heading(ui, t, "Preview cache"); let cur = app.session.cache_mb; row(ui, t, crate::i18n::tr("Size limit"), |ui| { let gb = lightcraft_engine::media::default_disk_cache_bytes(app.session.catalog.len()).div_ceil(1 << 30); diff --git a/crates/ui-egui/src/dialogs/settings/slide_layout.rs b/crates/ui-egui/src/dialogs/settings/slide_layout.rs index c1e9da2145..4dcd0589b9 100644 --- a/crates/ui-egui/src/dialogs/settings/slide_layout.rs +++ b/crates/ui-egui/src/dialogs/settings/slide_layout.rs @@ -274,14 +274,16 @@ pub fn preview(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, max_h: f3 ui.ctx().data_mut(|d| d.insert_temp(mem, (key, now))); } let still = if last == key { now - since } else { 0.0 }; - // the first preview (or another photo's) at once, a changing layout once it has settled - if current.is_none() || still >= DEBOUNCE { + // the first preview (or another photo's) at once, a changing layout once it has settled (none while the + // Settings filter only reads the page for its text: nothing of it is shown) + let reading = super::reading_for_filter(ui.ctx()); + if !reading && (current.is_none() || still >= DEBOUNCE) { let side = crate::panels::detail::texture_side(ui.ctx()); let edge = app.ui.settings.loupe_edge(pw.max(ph) as f32, usize::MAX, side); if let Some(job) = app.session.slide_job_look(&s, &overlays, id, pw, ph, Some(edge), false) { app.renderer.request(Slot::SlidePreview, job, 90); } - } else { + } else if !reading { ui.ctx().request_repaint_after(std::time::Duration::from_secs_f64((DEBOUNCE - still).clamp(0.01, DEBOUNCE))); } let say = diff --git a/crates/ui-egui/src/dialogs/settings/slideshow.rs b/crates/ui-egui/src/dialogs/settings/slideshow.rs index 8bcf0a778c..75926e00ee 100644 --- a/crates/ui-egui/src/dialogs/settings/slideshow.rs +++ b/crates/ui-egui/src/dialogs/settings/slideshow.rs @@ -1,7 +1,7 @@ use super::display::duration_slider; use super::widgets::{check, choices, heading, hint, row}; -use crate::widgets::register; use super::{LightcraftApp, Tokens, Value, json}; +use crate::widgets::register; /// The Slideshow tab: the slide preview, then the settings, in one column the width of the page /// (the page scrolls; a column beside the preview would be wider than the window). Without @@ -24,11 +24,11 @@ pub(super) fn slideshow_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Toke export_section(app, ui, t); } -/// Export: PDF, JPEG sequence or video of the slideshow (View ▸ Export Slideshow…). +/// Export: PDF, JPEG sequence or video of the slideshow (View ▸ Slideshow ▸ Export Slideshow…). fn export_section(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { use craft::ui::buttons::Button as FrameworkButton; use craft::ui::contract::{Props as _, Show as _}; - heading(ui, t, crate::i18n::tr("Export")); + heading(ui, t, "Export"); let running = app.session.slideshow_export.as_ref().is_some_and(|r| r.running()); #[cfg(test)] let mut controls = Vec::new(); @@ -68,7 +68,7 @@ fn export_section(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { fn playback_section(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { use lightcraft_engine::slideshow::{FADE_MAX, SLIDE_MAX, SLIDE_MIN}; - heading(ui, t, crate::i18n::tr("Playback")); + heading(ui, t, "Playback"); let s = app.session.slideshow.clone(); let mut v = s.manual; if check(ui, "settings.slideshowManual", &mut v, "Manual slideshow") { diff --git a/crates/ui-egui/src/dialogs/settings/widgets.rs b/crates/ui-egui/src/dialogs/settings/widgets.rs index e436235055..7dcc8c1cf7 100644 --- a/crates/ui-egui/src/dialogs/settings/widgets.rs +++ b/crates/ui-egui/src/dialogs/settings/widgets.rs @@ -1,4 +1,4 @@ -use super::{LABEL_W, RichText, Tokens, register}; +use super::{GOTO, LABEL_W, RichText, Tokens, register}; /// `path` shortened to fit `max` (as `width` measures it) by dropping leading folders, after /// either kind of separator, so that its end stays (`…/Pictures/Library`, @@ -61,7 +61,15 @@ pub(super) fn field(ui: &mut egui::Ui, field: crate::text_field::TextField<'_>) pub(crate) fn heading(ui: &mut egui::Ui, t: &Tokens, text: &str) { ui.add_space(4.0); - ui.label(RichText::new(crate::i18n::tr(text)).font(t.semibold(12.5)).color(t.text)); + // `text` is the heading's English name (its message key). It is shown translated and + // registered as `heading:{text}` whatever the language, where a section starts: for the + // filter, scripts and tests that look for one. + let r = ui.label(RichText::new(crate::i18n::tr(text)).font(t.semibold(12.5)).color(t.text)); + register(ui, format!("heading:{text}"), r.rect); + // (chosen from what the filter found: the section is brought to the top of the page) + if ui.data(|d| d.get_temp::<(&'static str, String)>(egui::Id::unique(GOTO))).is_some_and(|(_, section)| section == text) { + r.scroll_to_me(Some(egui::Align::TOP)); + } } pub(crate) fn row(ui: &mut egui::Ui, t: &Tokens, label: &str, add: impl FnOnce(&mut egui::Ui) -> R) -> R { diff --git a/crates/ui-egui/src/dialogs/slideshow_export.rs b/crates/ui-egui/src/dialogs/slideshow_export.rs index 1b3f01874a..4c91baf5a1 100644 --- a/crates/ui-egui/src/dialogs/slideshow_export.rs +++ b/crates/ui-egui/src/dialogs/slideshow_export.rs @@ -1,4 +1,4 @@ -//! View ▸ Export Slideshow…: the dialog's choices go to `app.slideshowExport`, which asks where +//! View ▸ Slideshow ▸ Export Slideshow…: the dialog's choices go to `app.slideshowExport`, which asks where //! to write (a PDF or video file, or the folder of a JPEG sequence) and starts the engine's //! `slideshow.export` in the background. The export's row in the activity stack shows its //! progress and ✕ (the engine owns the row); [`poll`] tells the user how it ended. @@ -79,7 +79,7 @@ pub fn poll(app: &mut LightcraftApp, ctx: &egui::Context) { } /// A labelled row (fixed label column). -/// View ▸ Export Slideshow…: what to write (PDF, JPEG sequence, video) and how big; where comes +/// View ▸ Slideshow ▸ Export Slideshow…: what to write (PDF, JPEG sequence, video) and how big; where comes /// after (a save dialog). pub(super) fn slideshow_export_body(app: &mut LightcraftApp, ui: &mut egui::Ui, settings: &mut lightcraft_engine::slideshow_export::ExportSettings) { use lightcraft_engine::slideshow_export::{ExportSettings, Format}; diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rs index 661273dd97..8f8b06f470 100644 --- a/crates/ui-egui/src/docking.rs +++ b/crates/ui-egui/src/docking.rs @@ -478,6 +478,7 @@ pub(crate) fn reveal_command(app: &mut crate::LightcraftApp, id: &str) -> Result Some(Panel::Library) } else if (id.starts_with("panel.") && id != "panel.close" && id != "panel.presets" || id == "view.rightPanel" + || id == "view.colorMixer" || id.starts_with("section.") || id.starts_with("tool.") && id != "tool.none") && app.ui.right != crate::state::RightPanel::None diff --git a/crates/ui-egui/src/headless/tests.rs b/crates/ui-egui/src/headless/tests.rs index fbbc180f3a..47ece4675e 100644 --- a/crates/ui-egui/src/headless/tests.rs +++ b/crates/ui-egui/src/headless/tests.rs @@ -772,7 +772,7 @@ fn adding_a_face_model_shows_its_terms_and_installs_only_once_accepted() { let _ = std::fs::remove_dir_all(&dir); } -/// Photo > Detect Faces without the detector offers the download: the terms first, nothing fetched before they are +/// Photo > Metadata > Detect Faces without the detector offers the download: the terms first, nothing fetched before they are /// accepted, and the model's row in Settings has its Download button. #[test] fn detect_faces_without_the_detector_offers_the_download_and_fetches_nothing_before_acceptance() { @@ -1873,6 +1873,37 @@ fn settle_waits_for_file_system_checks() { assert_eq!(check(&mut h), Some(true)); } +/// A file-system check that panics is no pending work for ever: the count drops (so `busy()` and `settle` go on) and the check can be asked again. +#[test] +fn a_file_system_check_that_panics_is_not_pending_for_ever() { + use std::sync::atomic::{AtomicUsize, Ordering}; + static ASKED: AtomicUsize = AtomicUsize::new(0); + fn panics(_: &str) -> bool { + ASKED.fetch_add(1, Ordering::SeqCst); + panic!("a listing that dies"); + } + let mut h = demo([800.0, 600.0]); + h.settle(SETTLE); + let check = |h: &mut Headless| { + let raw = HeadlessView::raw_input(h.size, 1.0, 0.0, vec![]); + h.view.run(raw, |ui| { + let _ = crate::panels::left::fs_cached(ui, "test-panics", "x", 0.0, panics); + }); + }; + check(&mut h); + let t0 = Instant::now(); + while crate::panels::left::fs_cached_running(&h.view.ctx) > 0 && t0.elapsed() < SETTLE { + std::thread::sleep(Duration::from_millis(2)); + } + assert_eq!(crate::panels::left::fs_cached_running(&h.view.ctx), 0, "the dead check no longer counts as running"); + check(&mut h); + let t0 = Instant::now(); + while ASKED.load(Ordering::SeqCst) < 2 && t0.elapsed() < SETTLE { + std::thread::sleep(Duration::from_millis(2)); + } + assert_eq!(ASKED.load(Ordering::SeqCst), 2, "and it is asked again, not stuck as running"); +} + /// Photo > Rename Photos…: the dialog previews and renames the selection. #[test] fn rename_dialog_renames_the_selection() { @@ -3288,6 +3319,41 @@ fn cmd_q_quits() { assert!(h.quit_requested()); } +/// File → Import from Folder… on a folder that was browsed in Local offers its photos, adding +/// them in place (they aren't "In library" yet), and confirming brings them into the library. +#[test] +fn import_from_folder_offers_the_photos_browsed_in_local() { + let mut h = demo([1300.0, 900.0]); + let t = Duration::from_secs(10); + let dir = std::env::temp_dir().join(format!("lc-ui-browsed-import-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let img = lightcraft_raster::Rgba8::from_fn(24, 16, |x, y| [(x * 9) as u8, (y * 12) as u8, 80, 255]); + let o = lightcraft_engine::export::ExportOptions { format: lightcraft_engine::export::ExportFormat::Png, ..Default::default() }; + for (i, name) in ["a.png", "b.png"].iter().enumerate() { + let mut img = img.clone(); + img.data[0][0] = i as u8; // different bytes per file + std::fs::write(dir.join(name), lightcraft_engine::export::encode_image(&img, &o).unwrap()).unwrap(); + } + let library_before = h.app.session.catalog.photos().filter(|p| !p.local).count(); + let r = h.request("engine.execute", json!({"command": "library.browse", "params": {"path": dir.to_string_lossy()}}), t); + assert_eq!(r["ok"], true, "{r}"); + h.settle(SETTLE); + assert_eq!(h.app.session.catalog.photos().filter(|p| p.local).count(), 2, "both browsed"); + let r = h.request("engine.execute", json!({"command": "file.addFolder", "params": {"path": dir.to_string_lossy()}}), t); + assert_eq!(r["ok"], true, "{r}"); + h.settle(SETTLE); + let Some(crate::state::Dialog::Import { opts }) = &h.app.ui.dialog else { panic!("no import review: {:?}", h.app.ui.dialog) }; + assert_eq!(opts.candidates.len(), 2); + assert!(opts.candidates.iter().all(|c| c.duplicate.is_none()), "browsed is not \"In library\": {:?}", opts.candidates); + assert_eq!(opts.selected_paths().len(), 2, "both offered, checked"); + assert_eq!(h.request("ui.dialog.confirm", json!({}), t)["ok"], true); + h.settle(SETTLE); + assert_eq!(h.app.session.catalog.photos().filter(|p| !p.local).count(), library_before + 2, "both joined the library"); + assert_eq!(h.app.session.catalog.photos().filter(|p| p.local).count(), 0); + let _ = std::fs::remove_dir_all(&dir); +} + /// File → Import from Folder… opens the import review for a folder (searched recursively). #[test] fn add_folder_opens_the_import_review() { @@ -4187,6 +4253,12 @@ fn import_copy_renames_into_destination() { let _ = std::fs::remove_dir_all(&base); } +/// The instant this machine reads as the tests' clock time: an undated file takes the file's +/// date in the host's zone, so a fixed epoch would file it on the day before west of UTC. +fn filed_at() -> u64 { + lightcraft_engine::import::local_instant("2026-01-14T05:58:48").and_then(|s| u64::try_from(s).ok()).unwrap_or(0) +} + /// Import review, Copy, Folders → Custom template…: the default `{date:%Y}/{date:%Y%m%d}` /// files copies under `2026/20260114/`, the example line shows the full destination, and a /// template that would climb out of the destination is refused. @@ -4199,13 +4271,10 @@ fn import_copy_into_a_custom_folder_template() { let img = lightcraft_raster::Rgba8 { width: 8, height: 8, data: vec![[40, 3, 9, 255]; 64] }; let png = lightcraft_codecs::encode_png(&lightcraft_codecs::EncodeImage::rgba8(&img), &lightcraft_codecs::EncodeMeta::default()).unwrap(); std::fs::write(src.join("IMG_01.png"), png).unwrap(); - // undated files are filed by the file's date (2026-01-14T05:58:48) - std::fs::File::options() - .write(true) - .open(src.join("IMG_01.png")) - .unwrap() - .set_modified(std::time::UNIX_EPOCH + Duration::from_secs(1_768_370_328)) - .unwrap(); + // Undated files are filed by the file's date, read in the host's zone (issue #2284), so + // the file is pinned to the instant this machine reads as 2026-01-14T05:58:48. + let when = std::time::UNIX_EPOCH + Duration::from_secs(filed_at()); + std::fs::File::options().write(true).open(src.join("IMG_01.png")).unwrap().set_modified(when).unwrap(); let dest_s = dest.to_string_lossy().to_string(); let services = crate::Services { png: None, pick_folder: Some(Box::new(move || Some(dest_s.clone()))), ..Default::default() }; let mut session = lightcraft_engine::Session::with_demo().with_fs(); @@ -4258,12 +4327,8 @@ fn import_move_into_a_folder_template() { let img = lightcraft_raster::Rgba8 { width: 8, height: 8, data: vec![[40 + i, 3, 9, 255]; 64] }; let png = lightcraft_codecs::encode_png(&lightcraft_codecs::EncodeImage::rgba8(&img), &lightcraft_codecs::EncodeMeta::default()).unwrap(); std::fs::write(src.join(format!("IMG_0{i}.png")), png).unwrap(); - std::fs::File::options() - .write(true) - .open(src.join(format!("IMG_0{i}.png"))) - .unwrap() - .set_modified(std::time::UNIX_EPOCH + Duration::from_secs(1_768_370_328)) - .unwrap(); + let when = std::time::UNIX_EPOCH + Duration::from_secs(filed_at()); + std::fs::File::options().write(true).open(src.join(format!("IMG_0{i}.png"))).unwrap().set_modified(when).unwrap(); } let dest_s = dest.to_string_lossy().to_string(); let services = crate::Services { png: None, pick_folder: Some(Box::new(move || Some(dest_s.clone()))), ..Default::default() }; @@ -4715,7 +4780,7 @@ fn info_overlay_toasts_are_painted_in_the_users_language() { } } -/// ⌘J opens View ▸ View Options; its menus choose Info 1's and Info 2's lines, Use Defaults puts +/// ⌘J opens View ▸ Loupe Overlay ▸ View Options…; its menus choose Info 1's and Info 2's lines, Use Defaults puts /// them back, and `view.viewOptions` sets them for an agent (refusing a line it doesn't know). #[test] fn view_options_choose_the_info_overlay_lines() { diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 3afb3779c6..0de2dc19f2 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -495,6 +495,20 @@ pub fn source_title(session: &lightcraft_engine::Session) -> String { } } +/// For a smart album on a loop (it includes itself through the albums it tests, so it holds no +/// photos): what the album's empty view says, as its title and what to do about it, naming the +/// album the loop goes through. `None` for an album that is not on a loop. +pub fn album_loop_note(catalog: &lightcraft_catalog::Catalog, id: lightcraft_catalog::AlbumId) -> Option<(String, String)> { + let through = catalog.album_loops_through(id)?; + let body = if through == id { + tr("It tests itself: change its rules (Edit Smart Album…)").to_string() + } else { + let name = catalog.album(through).map(|a| a.name.clone()).unwrap_or_default(); + tr_format!("It leads back to itself through “{}”: change the rules of one album on the loop (Edit Smart Album…)", name) + }; + Some((tr("This album is in a loop, so it shows nothing").to_string(), body)) +} + /// A date group heading (`2026-09-20`, `2026-09`, `2026`) in the UI language: the grid's full /// form, or the date sidebar's `short` one ("Sunday, 20" / "September" / "2026"). English keeps the /// catalog's own wording; every other language formats it with its `*-formats.json` date diff --git a/crates/ui-egui/src/lens_db.rs b/crates/ui-egui/src/lens_db.rs index 67933e7041..8ee309436e 100644 --- a/crates/ui-egui/src/lens_db.rs +++ b/crates/ui-egui/src/lens_db.rs @@ -185,7 +185,7 @@ fn database_name(camera: &str, lens: &str) -> Option { /// none. pub fn readout(app: &LightcraftApp, p: &lightcraft_catalog::Photo) -> String { use lightcraft_develop::LensSource; - match p.embedded_lens.map(|l| l.source) { + match p.embedded_lens.as_deref().map(|l| l.source) { Some(LensSource::File) => crate::i18n::tr("Profile: from the file (the camera's own correction)").to_string(), Some(LensSource::Database) => { let name = database_name(&p.meta.camera, &p.meta.lens).unwrap_or_else(|| p.meta.lens.trim().to_string()); @@ -219,10 +219,10 @@ mod tests { assert_eq!(super::readout(&app, &p), "No lens profile found for EF35mm f/1.4L II USM."); p.meta.lens.clear(); assert_eq!(super::readout(&app, &p), "This file names no lens."); - p.embedded_lens = Some(EmbeddedLens::default()); + p.embedded_lens = Some(Box::default()); assert_eq!(super::readout(&app, &p), "Profile: from the file (the camera's own correction)"); p.meta.lens = "EF70-200mm f/2.8L IS II USM".into(); - p.embedded_lens = Some(EmbeddedLens { source: LensSource::Database, ..Default::default() }); + p.embedded_lens = Some(Box::new(EmbeddedLens { source: LensSource::Database, ..Default::default() })); // the database's name for it, or the file's own without a database (LIGHTCRAFT_LENSFUN_DIR may be set) let r = super::readout(&app, &p); assert!(r.starts_with("Profile: ") && r.contains("70-200mm f/2.8L IS II USM") && r.ends_with(" (lens database)"), "{r}"); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 71f41ceab3..844037535d 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -239,6 +239,11 @@ pub struct LightcraftApp { pub(crate) missing_count_test_delay: Option, /// Offscreen context for headless screenshots of the windowed app. shadow: Option, + /// The frame being laid out is the offscreen one of a headless screenshot: it has no pointer of + /// its own, so it must not end a drag the window's pointer is still holding. + drawing_offscreen: bool, + /// Escape seen before the framework routes the input away from egui. + drop_cancel_requested: bool, /// Synthetic input events (from the control channel) injected one step per frame. pub synthetic: Vec, /// A gesture was canceled after its synthetic pointer press reached egui. The next @@ -618,6 +623,11 @@ pub fn split_presets(dropped: Vec) -> (Vec, Vec) { #[derive(Default)] pub struct Caches { keyword_tree: Option<(u64, std::sync::Arc>)>, + /// The Bursts panel's bursts, by the view's generation. + bursts: Option<(u64, panels::bursts::Shown)>, + /// Every burst of the library (pick first), by the view's generation: what a drag in the + /// Bursts panel compares with, so a frame of the drag builds no index of its own. + burst_index: Option<(u64, panels::bursts::All)>, /// The Keywording box's read-only names (with containing keywords, or Will Export), by library /// revision, selection and view. keyword_names: Option<(u64, u64, std::sync::Arc>)>, diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index eb4ca075d7..b861dbc94f 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -13,6 +13,7 @@ mod run; mod ui_commands; pub use files::{confirm_delete, delete_in_album, reveal_label, show_in_folders_enabled}; +pub(crate) use run::resize_brush; pub use run::{parse_rgb, run_ui_command}; pub use ui_commands::{LANGUAGE_COMMANDS, UI_COMMANDS, language_from_command, ui_commands}; diff --git a/crates/ui-egui/src/menus/menubar.rs b/crates/ui-egui/src/menus/menubar.rs index dfca8e766e..c2e9dd8fad 100644 --- a/crates/ui-egui/src/menus/menubar.rs +++ b/crates/ui-egui/src/menus/menubar.rs @@ -120,9 +120,9 @@ pub fn native_menu_structure(bar: &[(String, Vec)], keymap: &crate::sh /// Top-level menus in order (the macOS app menu is added by the host). pub const MENUS: &[&str] = &["File", "Edit", "View", "Photo", "Window", "Help"]; -/// Order and grouping per menu: command ids, `---` separators and `@Submenu` placeholders. -/// Entries with a menu path that aren't listed are appended at the end of their menu, before any -/// [`LAST`] item. +/// Order and grouping per menu: command ids, `---` separators and `@Submenu` placeholders. Every +/// command with a menu path has a slot here, or its submenu does (a test checks it); an entry left +/// out would still be appended at the end of its menu, before any [`LAST`] item. const LAYOUT: &[(&str, &[&str])] = &[ ( "File", @@ -130,12 +130,15 @@ const LAYOUT: &[(&str, &[&str])] = &[ "file.addPhotos", "file.addFolder", "@Import from Device", + "file.importLightroom", "---", "app.newLibrary", "app.openLibrary", "@Open Recent Library", "file.backupLibrary", "file.restoreLibrary", + "file.findMissing", + "library.compact", "---", "dialog.newAlbum", "dialog.newFolder", @@ -151,6 +154,9 @@ const LAYOUT: &[(&str, &[&str])] = &[ "app.exportPrevious", "@Export with Preset", "---", + "dialog.print", + "dialog.contactSheet", + "---", "library.toggleAutoWriteXmp", "@Previews", "---", @@ -179,6 +185,7 @@ const LAYOUT: &[(&str, &[&str])] = &[ "view.focusSearch", "---", "app.settings", + "@Language", ], ), ( @@ -186,35 +193,20 @@ const LAYOUT: &[(&str, &[&str])] = &[ &[ "view.photoGrid", "view.squareGrid", - "@Grid Info", - "view.thumbSizeUp", - "view.thumbSizeDown", "view.detail", "view.compare", "view.survey", + "view.reference", "view.people", "---", - "view.leftPanel", - "@Sidebar Sections", - "view.photoCounts", - "view.faceBoxes", - "view.focusPoint", - "view.zoomToFocus", - "view.filmstrip", - "view.histogram", - "view.navigator", - "view.infoOverlay", - "@Loupe Overlay", - "@Appearance", - "---", - "view.fullScreenPreview", - "view.lightsOut", - "view.enterFullScreen", - "---", - "view.showOriginal", - "view.beforeAfter", - "view.beforeAfterSplit", - "@Before/After Settings", + "@Grid Info", + "view.thumbSizeUp", + "view.thumbSizeDown", + "@Sort", + "@Stacks", + "view.filterBar", + "library.toggleFilters", + "library.clearFilter", "---", "view.zoomIn", "view.zoomOut", @@ -225,38 +217,39 @@ const LAYOUT: &[(&str, &[&str])] = &[ "view.clipping", "view.visualizeHdr", "view.softProof", - "view.maskOverlay", - "view.maskOverlayAll", - "view.maskOverlayMode", - "view.maskOverlayColor", - "view.maskPins", - "@Tool Overlay", - "view.cropOverlay", + "view.visualizeSpots", "---", - "@Sort", - "@Stacks", - "view.filterBar", - "library.toggleFilters", - "library.clearFilter", - "library.refresh", - "library.holdView", + "@Loupe Overlay", + "@Before/After", + "@Mask Overlay", + "@Tool Overlay", + "@Crop Overlay", "---", "compare.swap", "compare.makeSelect", "---", - "view.viewOptions", + "view.fullScreenPreview", + "view.lightsOut", + "view.enterFullScreen", + "@Slideshow", + "---", + "@Appearance", ], ), ( "Photo", &[ + "@Edit In", + "---", "@Add to Album", + "photo.addToLibrary", "---", "@Set Rating", "@Set Flag", "@Set Color Label", - "@Metadata Preset", "view.autoAdvance", + "dialog.cull", + "library.findSimilar", "---", "photo.rotateLeft", "photo.rotateRight", @@ -265,36 +258,38 @@ const LAYOUT: &[(&str, &[&str])] = &[ "---", "version.create", "photo.virtualCopy", + "photo.duplicate", "@Stack", "@Photo Merge", + "photo.convertToDng", "---", "develop.auto", "develop.treatment", "develop.reset", + "develop.matchExposure", "develop.updateProcess", "dialog.createPreset", "---", - "photo.saveMetadataToFile", - "photo.readMetadataFromFile", - "photo.reload", - "photo.readFocusPoints", + "@Metadata", + "---", "app.showInFinder", "app.showInFolders", "dialog.rename", - "dialog.captureTime", - "photo.tagFromTracklog", + "photo.reload", "tool.enablePainting", "---", "album.removePhotos", "photo.delete", "photo.restore", "photo.deletePermanently", + "library.emptyRecentlyDeleted", ], ), ( "Window", &[ "panel.edit", + "panel.profiles", "panel.crop", "panel.remove", "panel.masking", @@ -305,9 +300,21 @@ const LAYOUT: &[(&str, &[&str])] = &[ "panel.activity", "panel.info", "panel.keywords", + "panel.bursts", "---", "@Edit Sections", "@Tools", + "---", + "view.leftPanel", + "view.rightPanel", + "@Sidebar Sections", + "view.photoCounts", + "view.filmstrip", + "view.histogram", + "view.navigator", + "---", + "view.secondWindow", + "ui.dock.reset", ], ), ( @@ -320,10 +327,12 @@ const LAYOUT: &[(&str, &[&str])] = &[ "app.github", "app.artcraft", "---", + "app.help", "app.whatsNew", "app.shortcuts", "app.systemInfo", "app.openLogFolder", + "@Debug", "---", "app.checkForUpdates", "app.about", @@ -331,12 +340,58 @@ const LAYOUT: &[(&str, &[&str])] = &[ ), ]; -/// Items that always end their menu in their own separator group, after the entries appended -/// because the layout doesn't list them (Quit is the last item of the in-window File menu). +/// Order and grouping inside submenus: (menu, submenu, slots). Slots are as in [`LAYOUT`] (ids of +/// entries with that submenu path, `---`, `@Nested` submenus), plus `*` for the parameterized +/// items [`expanded`] builds. A submenu without a row here lists those first, then its entries. +const SUBMENUS: &[(&str, &str, &[&str])] = &[ + ("View", "Sort", &["*", "---", "library.refresh", "library.holdView"]), + ("View", "Loupe Overlay", &["view.infoOverlay", "view.viewOptions", "view.focusPoint", "view.zoomToFocus", "view.faceBoxes", "---", "*"]), + ( + "View", + "Before/After", + &[ + "view.showOriginal", + "view.beforeAfter", + "view.beforeAfterSplit", + "view.beforeAfterTopBottom", + "view.beforeAfterSplitTopBottom", + "---", + "beforeAfter.copyAfterToBefore", + "beforeAfter.copyBeforeToAfter", + "beforeAfter.swap", + "beforeAfter.resetBefore", + ], + ), + ("View", "Mask Overlay", &["view.maskOverlay", "view.maskOverlayAll", "view.maskPins", "---", "*"]), + ( + "Photo", + "Metadata", + &[ + "dialog.allMetadata", + "photo.copyMetadata", + "photo.pasteMetadata", + "@Metadata Preset", + "---", + "photo.saveMetadataToFile", + "photo.readMetadataFromFile", + "photo.readFocusPoints", + "---", + "dialog.captureTime", + "photo.tagFromTracklog", + "metadata.reverseGeocode", + "metadata.downloadPlaceNames", + "---", + "faces.detect", + ], + ), +]; + +/// Items that always end their menu in their own separator group (Quit is the last item of the +/// in-window File menu). const LAST: &[&str] = &["app.quit"]; -/// Registry entries that are reached another way (parameterized commands are expanded into -/// submenus below; others duplicate a dialog command). +/// Registry entries that are reached another way: parameterized commands and the items of +/// hand-built submenus are made by [`expanded`]; the others duplicate a dialog command. const HIDDEN: &[&str] = &[ "photo.rate", "photo.flag", @@ -351,6 +406,14 @@ const HIDDEN: &[&str] = &[ "album.create", "library.import", "preset.create", + // File ▸ Previews ▸ Discard Preview Cache + "library.clearPreviews", + // View ▸ Loupe Overlay + "view.chooseLayoutImage", + "view.layoutImage", + // View ▸ Mask Overlay (each mode and colour, then the cycle item) + "view.maskOverlayMode", + "view.maskOverlayColor", ]; /// The selection includes a photo in Recently Deleted. @@ -440,6 +503,7 @@ pub fn checked(app: &LightcraftApp, id: &str) -> Option { "panel.activity" => panel(RightPanel::Activity), "panel.info" => panel(RightPanel::Info), "panel.keywords" => panel(RightPanel::Keywords), + "panel.bursts" => panel(RightPanel::Bursts), "panel.presets" => Some(u.presets), "library.toggleAutoWriteXmp" => Some(app.session.xmp.auto_write), _ => None, @@ -523,7 +587,14 @@ pub(crate) fn expanded(app: &LightcraftApp, name: &str) -> Option> None, ), MenuNode::Separator, - item("library.clearPreviews", Value::Null, "Discard Preview Cache", None, true, None), + item( + "library.clearPreviews", + Value::Null, + "Discard Preview Cache", + crate::shortcuts::shortcut_of(&app.ui.settings.keymap, "library.clearPreviews"), + true, + None, + ), ] } "Set Rating" => (0..=5u8) @@ -650,6 +721,39 @@ pub(crate) fn expanded(app: &LightcraftApp, name: &str) -> Option> } v } + "Mask Overlay" => { + // each mode and colour of the Masking panel's overlay, then the item that steps on + use lightcraft_engine::pipeline::MaskView; + let mode = MaskView::parse(&app.ui.mask_overlay_mode).unwrap_or_default(); + let mut v: Vec = MaskView::ALL + .into_iter() + .map(|m| item("view.maskOverlayMode", json!({"mode": m.name()}), m.label(), None, true, Some(m == mode))) + .collect(); + let keymap = &app.ui.settings.keymap; + v.push(item( + "view.maskOverlayMode", + Value::Null, + "Cycle Mask Overlay Mode", + crate::shortcuts::shortcut_of(keymap, "view.maskOverlayMode"), + true, + None, + )); + v.push(MenuNode::Separator); + let colors = crate::panels::masking::OVERLAY_COLORS.into_iter().zip(crate::panels::masking::OVERLAY_COLOR_NAMES); + v.extend(colors.map(|(c, name)| { + let hex = format!("#{:02x}{:02x}{:02x}", c[0], c[1], c[2]); + item("view.maskOverlayColor", json!({"color": hex}), name, None, true, Some(app.ui.mask_overlay_color == c)) + })); + v.push(item( + "view.maskOverlayColor", + Value::Null, + "Cycle Mask Overlay Color", + crate::shortcuts::shortcut_of(keymap, "view.maskOverlayColor"), + true, + None, + )); + v + } "Tool Overlay" => { // when the spot and mask pins show; the last item steps to the next mode (Shift+H) use crate::state::ToolOverlay; @@ -806,13 +910,11 @@ pub(crate) fn expanded(app: &LightcraftApp, name: &str) -> Option> "Add to Album" => { let targets = app.session.selected(); let sel = !targets.is_empty(); - // albums hold library photos (issue #684): a Local-only selection is told what to do first + // albums hold library photos (issue #684): a Local-only selection finds them off, and Add to My + // Photos is the Photo menu's own item right below this submenu (not repeated in it: one command, + // one row) let local_only = crate::panels::grid::local_only(app, &targets); let mut v: Vec = vec![]; - if local_only { - v.push(item("photo.addToLibrary", Value::Null, crate::i18n::tr("Add to My Photos First"), None, false, None)); - v.push(MenuNode::Separator); - } let mut albums: Vec<_> = app.session.catalog.albums().filter(|a| !a.folder && !a.is_smart()).map(|a| (a.name.clone(), a.id.0)).collect(); albums.sort_by_key(|(n, _)| n.to_lowercase()); let any = !albums.is_empty(); @@ -867,6 +969,48 @@ fn tidy(v: Vec) -> Vec { out } +/// How deep `@Nested` submenus in [`SUBMENUS`] may go (a slot naming its own submenu stops here). +const MAX_SUBMENU_DEPTH: usize = 3; + +/// The items of submenu `name` in menu `title`: its [`SUBMENUS`] slots when it has a row there +/// (else the parameterized items of [`expanded`]), then the entries with this submenu path that +/// no slot names, the ones opening a dialog last after a separator. +fn submenu_items(app: &LightcraftApp, entries: &[MenuEntry], used: &mut [bool], title: &str, name: &str, depth: usize) -> Vec { + let here = |e: &MenuEntry| e.menu.len() == 2 && e.menu[0] == title && e.menu[1] == name; + let slots = SUBMENUS.iter().find(|(t, s, _)| *t == title && *s == name).map_or(&["*"][..], |(_, _, l)| *l); + let mut children = Vec::new(); + for slot in slots { + if *slot == "---" { + children.push(MenuNode::Separator); + } else if *slot == "*" { + children.extend(expanded(app, name).unwrap_or_default()); + } else if let Some(nested) = slot.strip_prefix('@') { + if depth < MAX_SUBMENU_DEPTH { + let items = submenu_items(app, entries, used, title, nested, depth + 1); + children.push(MenuNode::Submenu { label: nested.to_string(), children: items }); + } + } else if let Some(i) = entries.iter().position(|e| e.id == *slot && here(e)) { + if let Some(u) = used.get_mut(i) { + *u = true; + } + children.push(node(app, &entries[i])); + } + } + let mut dialogs = Vec::new(); + for (e, u) in entries.iter().zip(used.iter_mut()) { + if !*u && here(e) { + *u = true; + // commands that open a dialog go last, after a separator + if e.label.ends_with('…') { dialogs.push(node(app, e)) } else { children.push(node(app, e)) } + } + } + if !dialogs.is_empty() { + children.push(MenuNode::Separator); + children.extend(dialogs); + } + children +} + /// The whole menu bar: (title, items) per menu in [`MENUS`] order. pub fn menu_bar(app: &LightcraftApp) -> Vec<(String, Vec)> { let entries: Vec = @@ -877,34 +1021,18 @@ pub fn menu_bar(app: &LightcraftApp) -> Vec<(String, Vec)> { let layout = LAYOUT.iter().find(|(t, _)| t == title).map(|(_, l)| *l).unwrap_or(&[]); let mut items = Vec::new(); let mut last = Vec::new(); - let sub = |name: &str, used: &mut [bool]| -> Vec { - let mut children = expanded(app, name).unwrap_or_default(); - let mut dialogs = Vec::new(); - for (i, e) in entries.iter().enumerate() { - if !used[i] && e.menu.len() == 2 && e.menu[0] == *title && e.menu[1] == name { - used[i] = true; - // commands that open a dialog go last, after a separator - if e.label.ends_with('…') { dialogs.push(node(app, e)) } else { children.push(node(app, e)) } - } - } - if !dialogs.is_empty() { - children.push(MenuNode::Separator); - children.extend(dialogs); - } - children - }; for slot in layout { if *slot == "---" { items.push(MenuNode::Separator); } else if let Some(name) = slot.strip_prefix('@') { - let children = sub(name, &mut used); + let children = submenu_items(app, &entries, &mut used, title, name, 1); items.push(MenuNode::Submenu { label: name.to_string(), children }); } else if let Some(i) = entries.iter().position(|e| e.id == *slot && e.menu.first().map(String::as_str) == Some(title)) { used[i] = true; if LAST.contains(slot) { last.push(node(app, &entries[i])) } else { items.push(node(app, &entries[i])) } } } - // everything else that names this menu + // anything the layout doesn't place yet (a test keeps this empty) items.push(MenuNode::Separator); let mut extra_subs: Vec = Vec::new(); for (i, e) in entries.iter().enumerate() { @@ -919,7 +1047,7 @@ pub fn menu_bar(app: &LightcraftApp) -> Vec<(String, Vec)> { } } for name in extra_subs { - let children = sub(&name, &mut used); + let children = submenu_items(app, &entries, &mut used, title, &name, 1); items.push(MenuNode::Submenu { label: name, children }); } if !last.is_empty() { diff --git a/crates/ui-egui/src/menus/menubar/tests.rs b/crates/ui-egui/src/menus/menubar/tests.rs index a79dbaefe1..3e1b5b3b12 100644 --- a/crates/ui-egui/src/menus/menubar/tests.rs +++ b/crates/ui-egui/src/menus/menubar/tests.rs @@ -278,25 +278,11 @@ fn bar_follows_the_registry_and_state() { } #[test] -fn quit_ends_the_file_menu_after_unlisted_entries() { - let app = app(); - // the File menu has registry entries the layout doesn't list (appended as fallbacks) - let listed = LAYOUT.iter().find(|(t, _)| *t == "File").unwrap().1; - let unlisted: Vec = crate::menus::menu_entries(&app) - .into_iter() - .filter(|e| e.menu.first().map(String::as_str) == Some("File") && !listed.contains(&e.id.as_str()) && !HIDDEN.contains(&e.id.as_str())) - .map(|e| e.id) - .collect(); - assert!(!unlisted.is_empty(), "no fallback File entries to order"); - let bar = menu_bar(&app); +fn quit_ends_the_file_menu_alone_in_its_group() { + let bar = menu_bar(&app()); let file = &bar.iter().find(|(t, _)| t == "File").unwrap().1; - // Quit is the last item, alone in its separator group assert!(matches!(file.last(), Some(MenuNode::Item { id, .. }) if id == "app.quit"), "{file:?}"); assert_eq!(file.get(file.len() - 2), Some(&MenuNode::Separator)); - // every fallback entry is still reachable, before Quit - for id in &unlisted { - assert!(find(&file[..file.len() - 1], id).is_some(), "{id} missing before Quit"); - } } #[test] @@ -788,7 +774,7 @@ fn shortcut_text_orders_mac_modifiers_control_option_shift_command() { assert_eq!(shortcut_text("Cmd+Alt+Shift+C", false), "Ctrl+Alt+Shift+C", "other platforms keep the binding as written"); } -/// Every item of a menu, submenus included. +/// Every item of a menu, submenus included, in order. fn flat(nodes: &[MenuNode]) -> Vec<&MenuNode> { nodes .iter() @@ -800,6 +786,126 @@ fn flat(nodes: &[MenuNode]) -> Vec<&MenuNode> { .collect() } +/// The app in each view whose menus differ (grid, loupe with a mask, compare). +fn apps_in_every_view() -> Vec { + [ViewMode::PhotoGrid, ViewMode::Detail, ViewMode::Compare] + .into_iter() + .map(|v| { + let mut a = app(); + a.ui.view = v; + a.ui.right = RightPanel::Masking; + a + }) + .collect() +} + +/// Given every command that names a menu, Then the layout gives it a place: a slot in its +/// menu's [`LAYOUT`] row (one-level path), or a submenu that [`LAYOUT`] or [`SUBMENUS`] places +/// (two-level path). Nothing lands in an unsorted group at the end. +#[test] +fn every_menu_command_has_a_place_in_the_layout() { + let placed = |e: &crate::menus::MenuEntry| -> bool { + let Some(title) = e.menu.first() else { return true }; + let top = LAYOUT.iter().filter(|(t, _)| t == title).flat_map(|(_, l)| l.iter().copied()); + match e.menu.get(1) { + None => top.clone().any(|s| s == e.id), + Some(sub) => { + let nested = SUBMENUS.iter().filter(|(t, _, _)| t == title).flat_map(|(_, _, l)| l.iter().copied()); + top.chain(nested).any(|s| s.strip_prefix('@') == Some(sub.as_str())) + } + } + }; + let unplaced: Vec = crate::menus::menu_entries(&app()) + .into_iter() + .filter(|e| !HIDDEN.contains(&e.id.as_str()) && !placed(e)) + .map(|e| format!("{} ({})", e.id, e.menu.join(" ▸ "))) + .collect(); + assert!(unplaced.is_empty(), "commands without a place in LAYOUT: {unplaced:#?}"); +} + +/// Given the grid, the loupe or Compare with library photos selected, When a menu is opened, +/// Then no command shows up twice in it (with the same parameters), under the same label or +/// another one. The one repeat on purpose: Custom… ends File ▸ Export with Preset with the +/// Export dialog. +#[test] +fn no_menu_offers_the_same_command_twice() { + const ON_PURPOSE: &[(&str, &str)] = &[("dialog.export", "Custom…")]; + for a in apps_in_every_view() { + for (title, items) in menu_bar(&a) { + let mut seen: Vec<(&str, &Value, &str)> = Vec::new(); + for n in flat(&items) { + let MenuNode::Item { id, params, label, .. } = n else { continue }; + if ON_PURPOSE.contains(&(id.as_str(), label.as_str())) { + continue; + } + if let Some((_, _, first)) = seen.iter().find(|(i, p, _)| i == id && *p == params) { + panic!("{title} ({:?}): `{id}` {params} twice, as {first:?} and {label:?}", a.ui.view); + } + seen.push((id, params, label)); + } + } + } +} + +/// Given any view, Then every menu fits a laptop screen without scrolling: at most 40 rows, +/// a separator counting as half a row (about 45 fit on a 14-inch MacBook's screen). +#[test] +fn every_menu_fits_a_laptop_screen() { + for a in apps_in_every_view() { + for (title, items) in menu_bar(&a) { + let seps = items.iter().filter(|n| **n == MenuNode::Separator).count(); + let rows = items.len() - seps; + let height = rows as f32 + seps as f32 / 2.0; + assert!(height <= 40.0, "{title} ({:?}): {rows} rows and {seps} separators", a.ui.view); + } + } +} + +/// Given the loupe, When a mask overlay mode or colour is chosen in View ▸ Mask Overlay, Then +/// it is the one in use and the only one checked; the cycle items stay for their keys. +#[test] +fn mask_overlay_menu_lists_modes_and_colors_with_the_current_one_checked() { + use lightcraft_engine::pipeline::MaskView; + let mut a = app(); + a.ui.view = ViewMode::Detail; + let mask_menu = |a: &LightcraftApp| -> Vec { + let bar = menu_bar(a); + let view = &bar.iter().find(|(t, _)| t == "View").expect("View menu").1; + view.iter() + .find_map(|n| match n { + MenuNode::Submenu { label, children } if label == "Mask Overlay" => Some(children.clone()), + _ => None, + }) + .expect("View ▸ Mask Overlay") + }; + let checked_of = |kids: &[MenuNode], id: &str| -> Vec { + kids.iter() + .filter_map(|n| match n { + MenuNode::Item { id: i, params, checked: Some(true), .. } if i == id => Some(params.clone()), + _ => None, + }) + .collect() + }; + let kids = mask_menu(&a); + for id in ["view.maskOverlay", "view.maskOverlayAll", "view.maskPins"] { + assert!(find(&kids, id).is_some(), "{id} in Mask Overlay"); + } + let modes = kids.iter().filter(|n| matches!(n, MenuNode::Item { id, params, .. } if id == "view.maskOverlayMode" && !params.is_null())).count(); + assert_eq!(modes, MaskView::ALL.len()); + let colors = kids.iter().filter(|n| matches!(n, MenuNode::Item { id, params, .. } if id == "view.maskOverlayColor" && !params.is_null())).count(); + assert_eq!(colors, crate::panels::masking::OVERLAY_COLORS.len()); + for id in ["view.maskOverlayMode", "view.maskOverlayColor"] { + assert!(kids.iter().any(|n| matches!(n, MenuNode::Item { id: i, params, .. } if i == id && params.is_null())), "the cycle item {id} stays"); + let catalog_path = super::super::ui_commands::UI_COMMANDS.iter().find(|c| c.0 == id).map(|c| c.3); + assert_eq!(catalog_path, Some("View>Mask Overlay"), "the command catalog (ui.menu.list) places {id} where the menu does"); + } + run_item(&mut a, "view.maskOverlayMode", json!({"mode": MaskView::WhiteOnBlack.name()})).unwrap(); + run_item(&mut a, "view.maskOverlayColor", json!({"color": "#28c846"})).unwrap(); + let kids = mask_menu(&a); + assert_eq!(checked_of(&kids, "view.maskOverlayMode"), vec![json!({"mode": MaskView::WhiteOnBlack.name()})]); + assert_eq!(checked_of(&kids, "view.maskOverlayColor"), vec![json!({"color": "#28c846"})]); +} + /// Given the menu bar, Then an item that turns something on or off is named for the thing, /// with its check mark saying whether it is on: "Filmstrip ✓", never "Show Filmstrip ✓". /// Show Original is a view (\), not a switch: it keeps Lightroom's name. diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index a4462659e5..45200b7249 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -3,22 +3,92 @@ use super::ui_commands::{UI_COMMANDS, language_from_command}; use super::{BeforeAfter, Dialog, LightcraftApp, PickRequest, Picked, RightPanel, Value, ViewMode, Zoom, json, thumb_size_view}; fn panel(app: &mut LightcraftApp, ctx: &egui::Context, p: RightPanel, name: &str) { - if app.ui.right == p && crate::docking::exposed(app, crate::docking::Panel::Tools) { - app.ui.right = RightPanel::None; + // toggled off: back to exactly what the right column showed before (in the same frame: no flash, no jump), + // closed when it was closed (note 21) + let exposed = crate::docking::exposed(app, crate::docking::Panel::Tools); + let tool_before = app.ui.tool.clone(); + let on = app.ui.toggle_panel(p, exposed); + // toggled off: the panel put back brings its own tool back (Masking's Brush, Remove's Heal or Clone) + let tool_restored = !on && app.ui.tool != tool_before; + if !on { app.toast(ctx, crate::i18n::tr_format!("{name} Off", name = crate::i18n::tr(name))); } else { - app.ui.right = p; app.toast(ctx, crate::i18n::tr_format!("{name} On", name = crate::i18n::tr(name))); if p.is_edit_tool() && !matches!(app.ui.view, ViewMode::Detail) { app.ui.view = ViewMode::Detail; } } - if p != RightPanel::Masking && app.ui.tool != "wbPicker" { + if !tool_restored && p != RightPanel::Masking && app.ui.tool != "wbPicker" { app.ui.tool.clear(); } + app.ui.note_right(); let _ = app.session.end_interaction(); } +/// `view.colorMixer`: the Color Mixer's tab, Adjust mode, HSL group and Color-mode band, each +/// optional; the Edit panel opens on it. Returns the layout now shown. +fn color_mixer_layout(app: &mut LightcraftApp, p: &Value) -> Result { + use crate::panels::edit::{MIXER_ADJUST, MIXER_GROUPS, MIXER_TABS}; + let choose = |key: &str, items: &[(&str, &str)]| -> Result, String> { + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(Value::String(v)) if items.iter().any(|(_, k)| k == v) => Ok(Some(v.clone())), + Some(other) => { + let keys: Vec<&str> = items.iter().map(|(_, k)| *k).collect(); + Err(format!("view.colorMixer: `{key}` must be one of {}, not {other}", keys.join(", "))) + } + } + }; + let bands: Vec<(&str, &str)> = lightcraft_develop::MIXER_BANDS.iter().map(|b| (*b, *b)).collect(); + let (tab, adjust, group, band) = + (choose("tab", &MIXER_TABS)?, choose("adjust", &MIXER_ADJUST)?, choose("group", &MIXER_GROUPS)?, choose("band", &bands)?); + if let Some(v) = tab { + app.ui.mixer_tab = v; + } + if let Some(v) = adjust { + app.ui.mixer_adjust = v; + } + if let Some(v) = group { + app.ui.mixer_group = v; + } + if let Some(v) = band { + app.ui.mixer_mode = v; + } + // coming from another panel puts its tool down (Masking's colour picker would keep taking the photo's clicks), + // as the panel switch does; the White Balance picker and the mixer's own tools stay + let mixer_tool = matches!(app.ui.tool.as_str(), "pointColor" | "tat:hue" | "tat:sat" | "tat:lum"); + if app.ui.right != RightPanel::Edit && app.ui.tool != "wbPicker" && !mixer_tool { + app.ui.tool.clear(); + } + crate::panels::edit::drop_hidden_mixer_tool(app); + // (a drag in Remove or Masking is finished first, so later edits aren't previews of it) + let _ = app.session.end_interaction(); + app.ui.right = RightPanel::Edit; + app.ui.view = ViewMode::Detail; + // (full-screen preview and a slideshow show only the photo: the mixer would not appear) + if app.ui.slideshow.is_some() { + crate::panels::slideshow::end(app); + } + app.ui.fullscreen = false; + if !app.ui.section_open("color") { + app.ui.toggle_section("color"); + } + // (Solo Mode closes the Light section that holds the Curve: its targeted adjustment would go on adjusting a + // curve no longer shown) + if app.ui.single_panel && app.ui.tool == "tat:curve" { + app.ui.tool.clear(); + } + if !app.ui.flyout_open("mixer") { + app.ui.toggle_flyout("mixer"); + } + // (a B&W photo shows its B&W mix, never the Point Color tab; the choice is kept for colour photos) + let bw = app.session.active().and_then(|id| app.session.develop_of(id)).is_some_and(|d| crate::is_bw(&d)); + let tab = if bw { "mixer" } else { app.ui.mixer_tab.as_str() }; + // (the band the panel shows: a value from before the bands, such as "hue", shows the first) + let band = lightcraft_develop::MIXER_BANDS.iter().copied().find(|b| *b == app.ui.mixer_mode).unwrap_or("red"); + Ok(json!({"tab": tab, "adjust": app.ui.mixer_adjust, "group": app.ui.mixer_group, "band": band})) +} + /// With the Remove panel open, choose the Remove brush unless one already is, so painting works /// straight away; another tool still on (the White Balance eyedropper) gives way. Mode ▸ None is /// for choosing in the panel itself. @@ -30,20 +100,26 @@ fn remove_brush(app: &mut LightcraftApp) { /// `[` / `]` (size ×`k`) and ⇧`[` / ⇧`]` (feather +`df`) for the brush in use: the Remove tool's /// (and its selected spot's) or the Masking brush's. -fn adjust_brush(app: &mut LightcraftApp, k: f32, df: f32) -> Value { +pub(crate) fn adjust_brush(app: &mut LightcraftApp, k: f32, df: f32) -> Value { + let v = resize_brush(app, k, df); + if app.ui.right == RightPanel::Remove && app.session.active_spot.is_some() { + let mut p = json!({}); + if k != 1.0 { + p["size"] = json!(app.ui.remove_size); + } + if df != 0.0 { + p["feather"] = json!(app.ui.remove_feather); + } + let _ = app.run("spot.update", p); + } + v +} + +/// The brush in use alone, size ×`k` and feather +`df`, for the next stroke: no spot changes. +pub(crate) fn resize_brush(app: &mut LightcraftApp, k: f32, df: f32) -> Value { if app.ui.right == RightPanel::Remove { app.ui.remove_size = (app.ui.remove_size * k).clamp(0.001, 0.25); app.ui.remove_feather = (app.ui.remove_feather + df).clamp(0.0, 100.0); - if app.session.active_spot.is_some() { - let mut p = json!({}); - if k != 1.0 { - p["size"] = json!(app.ui.remove_size); - } - if df != 0.0 { - p["feather"] = json!(app.ui.remove_feather); - } - let _ = app.run("spot.update", p); - } json!({"size": app.ui.remove_size, "feather": app.ui.remove_feather}) } else { app.ui.brush_size = (app.ui.brush_size * k).clamp(0.002, 0.5); @@ -637,6 +713,9 @@ fn ui_commands_4(app: &mut LightcraftApp, _ctx: &egui::Context, id: &str, p: &Va if app.ui.right != RightPanel::None && crate::docking::exposed(app, crate::docking::Panel::Tools) { app.ui.right_hidden = app.ui.right; app.ui.right = RightPanel::None; + // noted now, not at the frame's end: a command after it in the same frame (a batch of control + // requests) opens a tool on the hidden column, not on the panel F8 hid + app.ui.note_right(); if app.ui.tool != "wbPicker" { app.ui.tool.clear(); } @@ -647,6 +726,9 @@ fn ui_commands_4(app: &mut LightcraftApp, _ctx: &egui::Context, id: &str, p: &Va p => p, }; app.ui.right = p; + // (a tool shown again this way still closes to the panel before it; noted now, as for hiding) + app.ui.right_shown_by_f8 = Some(p); + app.ui.note_right(); if p.is_edit_tool() && !matches!(app.ui.view, ViewMode::Detail) { app.ui.view = ViewMode::Detail; } @@ -686,7 +768,7 @@ fn ui_commands_4(app: &mut LightcraftApp, _ctx: &egui::Context, id: &str, p: &Va } "view.zoomToggle" => { // the same ratio a click on the photo zooms to; zooming in centres on the camera's focus - // point when the photo has one (View ▸ Zoom to Focus Point) + // point when the photo has one (View ▸ Loupe Overlay ▸ Zoom to Focus Point) let zoom_in = app.ui.zoom == Zoom::Fit; app.ui.zoom = if zoom_in { Zoom::Percent(app.ui.click_zoom as f32) } else { Zoom::Fit }; app.ui.zoom_anim = true; @@ -793,8 +875,25 @@ fn ui_commands_5(app: &mut LightcraftApp, ctx: &egui::Context, id: &str, p: &Val Ok(Value::Null) } "view.maskOverlay" => { - app.ui.mask_overlay = p.get("show").and_then(Value::as_bool).unwrap_or(!app.ui.mask_overlay); - Ok(json!({"maskOverlay": app.ui.mask_overlay})) + // O shows or hides what is on screen now: an overlay that showed by itself (a mask + // without settings yet) is hidden for that mask + let selected = app.session.active().and_then(|id| app.session.develop_of(id)).and_then(|d| { + app.session + .active_mask + .and_then(|mid| d.masks.iter().find(|m| m.id == mid).map(|m| (mid, crate::panels::detail::overlay_shown(app, m)))) + }); + let shown = selected.is_some_and(|s| s.1) || (selected.is_none() && app.ui.mask_overlay); + let show = p.get("show").and_then(Value::as_bool).unwrap_or(!shown); + app.ui.mask_overlay = show; + let photo = app.session.active(); + if let Some(key) = selected.and_then(|s| photo.map(|p| (p, s.0))) { + // each hidden mask stays hidden until O shows it again (not until another is hidden) + app.ui.mask_overlay_hidden.retain(|k| *k != key); + if !show { + app.ui.mask_overlay_hidden.push(key); + } + } + Ok(json!({"maskOverlay": show})) } "view.maskOverlayAll" => { app.ui.mask_overlay_all = !app.ui.mask_overlay_all; @@ -1032,6 +1131,10 @@ fn ui_commands_7(app: &mut LightcraftApp, ctx: &egui::Context, id: &str, p: &Val panel(app, ctx, RightPanel::Activity, "History"); Ok(Value::Null) } + "panel.bursts" => { + panel(app, ctx, RightPanel::Bursts, "Bursts"); + Ok(Value::Null) + } "panel.presets" => { app.ui.presets = !app.ui.presets || !crate::docking::exposed(app, crate::docking::Panel::Presets); if app.ui.presets && app.ui.view != ViewMode::Detail { @@ -1040,7 +1143,7 @@ fn ui_commands_7(app: &mut LightcraftApp, ctx: &egui::Context, id: &str, p: &Val Ok(Value::Null) } "tool.done" => { - // Return commits a tool panel (crop, remove, red eye, masking): back to Edit + // Return commits a tool panel (crop, remove, red eye, masking): back to the panel before it use RightPanel::*; if app.ui.dialog.is_none() && matches!(app.ui.right, Crop | Remove | RedEye | Masking) { if app.ui.right == Crop { @@ -1048,10 +1151,12 @@ fn ui_commands_7(app: &mut LightcraftApp, ctx: &egui::Context, id: &str, p: &Val } let _ = app.session.end_interaction(); app.ui.tool.clear(); - app.ui.right = Edit; + // back to the panel shown before the tool (hidden if it was) + app.ui.right = app.ui.leave_tool(); } Ok(Value::Null) } + "view.colorMixer" => color_mixer_layout(app, p), "panel.close" => { app.ui.right = RightPanel::None; app.ui.presets = false; @@ -1083,6 +1188,21 @@ fn ui_commands_8(app: &mut LightcraftApp, _ctx: &egui::Context, id: &str, p: &Va }), s if s.starts_with("tool.") => { let tool = &s["tool.".len()..]; + // a Brush stroke ends before another tool takes over (its release would go unseen: the next + // stroke would carry on from it), and before a Brush request that makes a new mask or component + // (what was painted stays on the mask it was painted on); a live one closes its undo step, so a + // new mask isn't folded into the "Brush" step + let creates = p.get("new").and_then(Value::as_bool) == Some(true) || p.get("op").is_some(); + if (tool != "brush" || creates) + && let Some(crate::panels::detail::Gesture::Brush { live, .. }) = &app.gesture + { + let went_live = live.is_some(); + app.gesture = None; + app.brush_live = None; + if went_live { + let _ = app.run("develop.endInteraction", json!({})); + } + } match tool { "none" => app.ui.tool.clear(), "guidedUpright" => { @@ -1112,7 +1232,6 @@ fn ui_commands_8(app: &mut LightcraftApp, _ctx: &egui::Context, id: &str, p: &Va return Some(Err(e)); } app.ui.brush_erase = false; - app.ui.mask_overlay = true; } app.ui.right = RightPanel::Masking; app.ui.view = ViewMode::Detail; @@ -1326,7 +1445,14 @@ fn ui_commands_10(app: &mut LightcraftApp, ctx: &egui::Context, id: &str, p: &Va "photo.openOriginalInExternal" => open_original_in(app, ctx, p), "dialog.cull" => { let (burst_gap, similarity) = app.ui.cull_burst.unwrap_or((10.0, 0.93)); - app.ui.dialog = Some(Dialog::Cull { reject_below: 0.0, pick_best: true, stack_groups: app.ui.cull_stack, burst_gap, similarity }); + app.ui.dialog = Some(Dialog::Cull { + reject_below: 0.0, + pick_best: true, + stack_groups: app.ui.cull_stack, + burst_gap, + similarity, + reset_bursts: false, + }); Ok(Value::Null) } "app.whatsNew" => { diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 8c0bae289e..d240c41a27 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -72,9 +72,9 @@ pub const UI_COMMANDS: &[UiCommand] = &[ ("view.survey", "Survey", Some("N"), "View"), ("view.people", "People", None, "View"), ("view.person", "Show Person", None, ""), - ("view.faceBoxes", "Face Boxes", None, "View"), - ("view.focusPoint", "Focus Point", Some("Alt+F"), "View"), - ("view.zoomToFocus", "Zoom to Focus Point", None, "View"), + ("view.faceBoxes", "Face Boxes", None, "View>Loupe Overlay"), + ("view.focusPoint", "Focus Point", Some("Alt+F"), "View>Loupe Overlay"), + ("view.zoomToFocus", "Zoom to Focus Point", None, "View>Loupe Overlay"), ("view.reduceMotion", "Reduce Motion", None, ""), ("view.reference", "Reference View", Some("Shift+R"), "View"), ("photo.setReference", "Set as Reference Photo", None, ""), @@ -82,14 +82,14 @@ pub const UI_COMMANDS: &[UiCommand] = &[ ("compare.set", "Show in Compare", None, ""), ("compare.makeSelect", "Make Candidate the Select", None, "View"), ("view.autoAdvance", "Auto Advance", None, "Photo"), - ("view.filmstrip", "Filmstrip", Some("/"), "View"), - ("view.leftPanel", "My Photos Panel", Some("Cmd+Shift+L"), "View"), - ("view.rightPanel", "Right Panel", None, "View"), - ("view.beforeAfter", "Before/After Side by Side", Some("Y"), "View"), - ("view.beforeAfterSplit", "Before/After Split", Some("Shift+Y"), "View"), - ("view.beforeAfterTopBottom", "Before/After Top/Bottom", Some("Alt+Y"), "View"), - ("view.beforeAfterSplitTopBottom", "Before/After Split Top/Bottom", Some("Alt+Shift+Y"), "View"), - ("view.showOriginal", "Show Original", Some("\\"), "View"), + ("view.filmstrip", "Filmstrip", Some("/"), "Window"), + ("view.leftPanel", "My Photos Panel", Some("Cmd+Shift+L"), "Window"), + ("view.rightPanel", "Right Panel", None, "Window"), + ("view.beforeAfter", "Before/After Side by Side", Some("Y"), "View>Before/After"), + ("view.beforeAfterSplit", "Before/After Split", Some("Shift+Y"), "View>Before/After"), + ("view.beforeAfterTopBottom", "Before/After Top/Bottom", Some("Alt+Y"), "View>Before/After"), + ("view.beforeAfterSplitTopBottom", "Before/After Split Top/Bottom", Some("Alt+Shift+Y"), "View>Before/After"), + ("view.showOriginal", "Show Original", Some("\\"), "View>Before/After"), ("view.zoomFit", "Zoom to Fit", Some("Cmd+0"), "View"), ("view.zoom100", "Zoom 100%", Some("Cmd+Alt+0"), "View"), ("view.zoomToggle", "Toggle Zoom", Some("Z"), "View"), @@ -106,14 +106,14 @@ pub const UI_COMMANDS: &[UiCommand] = &[ ("view.visualizeHdr", "Visualize HDR", None, "View"), // in grids S expands/collapses stacks (the engine command it shadows) ("view.softProof", "Soft Proofing", Some("S"), "View"), - ("view.histogram", "Histogram", Some("Cmd+Shift+H"), "View"), - ("view.maskOverlay", "Mask Overlay", Some("O"), "View"), + ("view.histogram", "Histogram", Some("Cmd+Shift+H"), "Window"), + ("view.maskOverlay", "Mask Overlay", Some("O"), "View>Mask Overlay"), // Ctrl+Shift+O / Cmd+Shift+O: every mask's region at once, not just the selected one - ("view.maskOverlayAll", "All Mask Overlays", Some("Cmd+Shift+O"), "View"), + ("view.maskOverlayAll", "All Mask Overlays", Some("Cmd+Shift+O"), "View>Mask Overlay"), // Shift+O in the Masking panel (elsewhere it cycles the crop overlay) - ("view.maskOverlayMode", "Cycle Mask Overlay Mode", None, "View"), - ("view.maskOverlayColor", "Cycle Mask Overlay Color", None, "View"), - ("view.maskPins", "Mask Pins", None, "View"), + ("view.maskOverlayMode", "Cycle Mask Overlay Mode", None, "View>Mask Overlay"), + ("view.maskOverlayColor", "Cycle Mask Overlay Color", None, "View>Mask Overlay"), + ("view.maskPins", "Mask Pins", None, "View>Mask Overlay"), // {mode?: auto | always | selected | never}: when spot and mask pins show (steps to the next // mode when omitted; Shift+H, like Classic's H for pins, since H opens Remove). View ▸ Tool // Overlay and the Remove panel list the modes. @@ -122,8 +122,8 @@ pub const UI_COMMANDS: &[UiCommand] = &[ // A while the Crop panel is open: the aspect lock as a first-class row. Visualize Spots keeps // the key outside the panel; the two are a contextual pair in shortcuts::handle ("crop.lockAspect", "Lock Aspect Ratio", Some("A"), ""), - ("view.cropOverlay", "Cycle Crop Overlay", Some("Shift+O"), "View"), - ("view.cropOverlayOrientation", "Cycle Crop Overlay Orientation", None, "View"), + ("view.cropOverlay", "Cycle Crop Overlay", Some("Shift+O"), "View>Crop Overlay"), + ("view.cropOverlayOrientation", "Cycle Crop Overlay Orientation", None, "View>Crop Overlay"), ("view.back", "Back to Grid", Some("Escape"), ""), ("tool.done", "Done", Some("Enter"), ""), ("view.filterBar", "Filter Bar", Some("Shift+F"), "View"), @@ -135,13 +135,13 @@ pub const UI_COMMANDS: &[UiCommand] = &[ ("view.fullScreenPreview", "Full Screen Preview", Some("F"), "View"), ("view.lightsOut", "Lights Out", Some("Shift+L"), "View"), ("view.enterFullScreen", "Enter Full Screen", Some("Cmd+Shift+F"), "View"), - ("view.infoOverlay", "Cycle Info Overlay", Some("Cmd+I"), "View"), - ("view.viewOptions", "View Options…", Some("Cmd+J"), "View"), + ("view.infoOverlay", "Cycle Info Overlay", Some("Cmd+I"), "View>Loupe Overlay"), + ("view.viewOptions", "View Options…", Some("Cmd+J"), "View>Loupe Overlay"), ("view.chooseLayoutImage", "Choose Layout Image…", None, "View"), ("view.layoutImage", "Layout Image", Some("Cmd+Alt+O"), "View"), ("view.layoutImageOpacity", "Layout Image Opacity", None, ""), ("view.layoutImageMatte", "Layout Image Matte", None, ""), - ("view.navigator", "Navigator", None, "View"), + ("view.navigator", "Navigator", None, "Window"), ("panel.edit", "Edit Panel", Some("E"), "Window"), ("panel.profiles", "Profile Browser", None, "Window"), ("panel.crop", "Crop & Rotate", Some("C"), "Window"), @@ -157,7 +157,11 @@ pub const UI_COMMANDS: &[UiCommand] = &[ // Edit Keyword Tag for the keyword picked in the Keyword List ("panel.editKeywords", "Edit Keywords", Some("Cmd+Shift+K"), ""), ("panel.activity", "History", None, "Window"), + ("panel.bursts", "Bursts", None, "Window"), ("panel.close", "Close Panel", None, ""), + // the Color Mixer's layout {tab?: mixer|point, adjust?: hsl|color, group?: hue|sat|lum|all, + // band?: red…magenta}: opens it in the Edit panel (the sliders are the mixer.* controls) + ("view.colorMixer", "Color Mixer Layout", None, ""), // {solo?}: true opens just that section (⌥-click on its header); otherwise opens or closes it ("section.light", "Light", Some("Cmd+1"), "Window>Edit Sections"), ("section.color", "Color", Some("Cmd+2"), "Window>Edit Sections"), @@ -181,13 +185,13 @@ pub const UI_COMMANDS: &[UiCommand] = &[ ("dialog.newAlbum", "New Album…", Some("Cmd+N"), "File"), ("dialog.newFolder", "New Folder…", Some("Cmd+Shift+N"), "File"), ("dialog.smartAlbum", "New Smart Album…", None, "File"), - ("view.photoCounts", "Photo Counts", None, "View"), + ("view.photoCounts", "Photo Counts", None, "Window"), ("view.sidebarSection", "Show Sidebar Section", None, ""), ("view.sidebarMoveSection", "Move Sidebar Section", None, ""), ("view.sidebarReset", "Reset Sidebar Sections", None, ""), - ("view.slideshow", "Slideshow", Some("Cmd+Alt+Enter"), "View"), - ("view.slideshowOptions", "Slideshow Options…", None, "View"), - ("dialog.slideshowExport", "Export Slideshow…", None, "View"), + ("view.slideshow", "Slideshow", Some("Cmd+Alt+Enter"), "View>Slideshow"), + ("view.slideshowOptions", "Slideshow Options…", None, "View>Slideshow"), + ("dialog.slideshowExport", "Export Slideshow…", None, "View>Slideshow"), ("app.slideshowExport", "Export Slideshow", None, ""), // the slideshow's playback controls (Space, ←/→ and Esc while it plays) ("slideshow.togglePause", "Pause / Resume Slideshow", None, ""), @@ -203,7 +207,7 @@ pub const UI_COMMANDS: &[UiCommand] = &[ ("view.appearance", "Next Appearance Mode", None, ""), // {theme: charcoal | midnight | silver | paper}: pick a theme and fix the mode to its family. ("view.theme", "Theme", None, ""), - ("dialog.allMetadata", "All Metadata…", None, "Photo"), + ("dialog.allMetadata", "All Metadata…", None, "Photo>Metadata"), ("dialog.faceModel", "Add Face Model…", None, ""), ("dialog.newSmartAlbum", "New Smart Album from Filter…", Some("Cmd+Alt+N"), "File"), ("dialog.createPreset", "Create Preset…", Some("Cmd+Shift+P"), "Photo"), @@ -282,7 +286,7 @@ pub const UI_COMMANDS: &[UiCommand] = &[ ("app.openSamModelFolder", "Show in File Manager", None, ""), ("dialog.rename", "Rename Photos…", Some("F2"), "Photo"), ("dialog.labelNames", "Edit Color Label Names…", None, ""), - ("dialog.captureTime", "Edit Capture Time…", None, "Photo"), - ("photo.tagFromTracklog", "Auto-Tag from Tracklog…", None, "Photo"), + ("dialog.captureTime", "Edit Capture Time…", None, "Photo>Metadata"), + ("photo.tagFromTracklog", "Auto-Tag from Tracklog…", None, "Photo>Metadata"), ("app.exportPrevious", "Export with Previous", Some("Cmd+Alt+Shift+E"), "File"), ]; diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 91fbb89f9c..ba8107f3e6 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -2,6 +2,7 @@ pub mod activity; pub mod bottombar; +pub mod bursts; pub mod chips; pub mod compare; pub mod crop_overlay; @@ -28,11 +29,12 @@ pub mod right; pub(crate) mod scroll_focus; pub mod second; pub mod slideshow; +pub mod spot_outline; pub mod strip; pub mod topbar; pub mod unnamed; -use egui::{Align2, Rect, pos2, vec2}; +use egui::{Rect, pos2, vec2}; use crate::LightcraftApp; pub use crate::dialogs; @@ -113,12 +115,23 @@ pub fn toast(app: &mut LightcraftApp, ctx: &egui::Context) { ctx.request_repaint_after(std::time::Duration::from_millis(30)); } -/// Paint a centred, dimmed message (empty states). +/// Paint a centred, dimmed message (empty states). Each line wraps to the area, so a long one (a +/// translation, an album named in it) is not cut off at its edges. pub fn empty_message(ui: &egui::Ui, rect: Rect, title: &str, body: &str) { let t = Tokens::get(ui.ctx()); let p = ui.painter(); - p.text(rect.center() - vec2(0.0, 12.0), Align2::CENTER_CENTER, crate::i18n::tr(title), t.semibold(18.0), t.text_label); - p.text(rect.center() + vec2(0.0, 14.0), Align2::CENTER_CENTER, crate::i18n::tr(body), t.font(13.0), t.text_dim); + let wrap = (rect.width() - 32.0).max(120.0); + let lay = |text: &str, font: egui::FontId, color: egui::Color32| { + let mut job = egui::text::LayoutJob::simple(text.to_owned(), font, color, wrap); + job.halign = egui::Align::Center; + p.layout_job(job) + }; + let title = lay(crate::i18n::tr(title), t.semibold(18.0), t.text_label); + let body = lay(crate::i18n::tr(body), t.font(13.0), t.text_dim); + // as one block, centred: one line each sits where the two lines always sat + let top = rect.center().y - (title.size().y + 8.0 + body.size().y) / 2.0; + p.galley(pos2(rect.center().x, top), title.clone(), t.text_label); + p.galley(pos2(rect.center().x, top + title.size().y + 8.0), body, t.text_dim); } /// A button under an empty state's message: the command it runs, its label, and the id it is diff --git a/crates/ui-egui/src/panels/activity.rs b/crates/ui-egui/src/panels/activity.rs index efc0b861c6..da53c75d5a 100644 --- a/crates/ui-egui/src/panels/activity.rs +++ b/crates/ui-egui/src/panels/activity.rs @@ -22,8 +22,13 @@ pub const MAX_ROWS: usize = 3; /// The stack's width (points). pub const WIDTH: f32 = 280.0; +/// Inner margin around the activity stack frame (points). const MARGIN: i8 = 8; +/// Size of the ✕ cancel cross (points). const CROSS: f32 = 16.0; +/// Height of the grip strip at the top of the stack (points): a drag there always moves the stack, also when the +/// task list overflows and a drag over its rows scrolls it (touch screens). +const HANDLE_H: f32 = 10.0; fn measuring(ui: &egui::Ui) -> bool { ui.is_sizing_pass() || craft::ui::runtime::measure::active(ui.ctx()) @@ -41,6 +46,7 @@ pub fn count_text(t: &TaskInfo) -> String { } } +/// Format bytes as a decimal megabyte string ("1.2", "42"). fn megabytes(bytes: u64) -> String { let mb = bytes as f64 / 1_048_576.0; if mb < 10.0 { format!("{mb:.1}") } else { format!("{:.0}", mb.floor()) } @@ -64,7 +70,8 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { if craft::ui::runtime::measure::active(ctx) { return; } - let all = app.session.activity.list(); + // Waiting tasks have no visible progress yet; automation still sees them in activity.list. + let all: Vec = app.session.activity.list().into_iter().filter(|t| !t.waiting).collect(); if all.is_empty() { app.activity_expanded = false; return; @@ -78,36 +85,71 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { let t = Tokens::get(ctx); let shown = if app.activity_expanded { tasks.len() } else { tasks.len().min(MAX_ROWS) }; let hidden = tasks.len().saturating_sub(shown); - let max_height = (ctx.content_rect().height() - t.top_bar_h - 60.0).max(80.0); let mut cancel = None; let mut toggle = false; let frame = egui::Frame::NONE.fill(t.chrome).stroke(Stroke::new(1.0, t.field_border)).corner_radius(6).inner_margin(Margin::same(MARGIN)); - egui::Area::new(egui::Id::unique("activity-stack")).order(egui::Order::Middle).fixed_pos(pos2(8.0, t.top_bar_h + 8.0)).show(ctx, |ui| { - // An area lays out in the size it had last frame, and the scroll area would take that as all the room there - // is: the stack would never grow when rows are added. Give it the whole height below the top bar instead - // (the scroll area keeps to `max_height`). - ui.set_max_height((ctx.content_rect().height() - t.top_bar_h - 16.0).max(80.0)); - frame.show(ui, |ui| { - let inner = WIDTH - 2.0 * (f32::from(MARGIN) + 1.0); - ui.set_width(inner); - ui.spacing_mut().item_spacing.y = 3.0; - egui::ScrollArea::vertical().max_height(max_height).auto_shrink([false, true]).show(ui, |ui| { - for (i, task) in tasks.iter().take(shown).enumerate() { - if i > 0 { - ui.add_space(6.0); - } - if row(ui, &t, task, inner) { - cancel = Some(task.id); - } + let area_resp = egui::Area::new(egui::Id::unique("activity-stack")) + .order(egui::Order::Middle) + .default_pos(pos2(8.0, t.top_bar_h + 8.0)) + .movable(true) + .constrain(true) + .show(ctx, |ui| { + // An area lays out in the size it had last frame, and the scroll area would take that as all the room there + // is: the stack would never grow when rows are added. Give it the whole height below its position instead + // (the scroll area keeps to `max_scroll_h`). + let has_footer = hidden > 0 || (app.activity_expanded && tasks.len() > MAX_ROWS); + // the footer (or the frame's margins alone) and the grip strip with its spacing + let footer_reserve = if has_footer { 44.0 } else { 20.0 } + HANDLE_H + 3.0; + let space_below = (ctx.content_rect().bottom() - ui.cursor().top() - 16.0).max(0.0); + // Cap at the true viewport capacity so the stack never claims more height + // than the viewport can provide, even when it is shorter than `footer_reserve`. + let max_stack_h = (ctx.content_rect().height() - 16.0).max(0.0); + let available_h = space_below.clamp(max_stack_h.min(footer_reserve), max_stack_h); + ui.set_max_height(available_h); + let frame_resp = frame.show(ui, |ui| { + let inner = WIDTH - 2.0 * (f32::from(MARGIN) + 1.0); + ui.set_width(inner); + ui.spacing_mut().item_spacing.y = 3.0; + let mut interactive_hovered = false; + // the grip: not a widget, so a drag on it is the area's (moves the stack), never the list's + let (grip, _) = ui.allocate_exact_size(vec2(inner, HANDLE_H), Sense::hover()); + register(ui, "activity:handle", grip); + for dy in [-1.5, 1.5] { + let y = grip.center().y + dy; + ui.painter().line_segment([pos2(grip.center().x - 12.0, y), pos2(grip.center().x + 12.0, y)], Stroke::new(1.0, t.text_dim)); } + let max_scroll_h = (available_h - footer_reserve).max(0.0); + egui::ScrollArea::vertical().max_height(max_scroll_h).min_scrolled_height(0.0).auto_shrink([false, true]).show(ui, |ui| { + for (i, task) in tasks.iter().take(shown).enumerate() { + if i > 0 { + ui.add_space(6.0); + } + let (clicked, hovered) = row_with_hover(ui, &t, task, inner); + if clicked { + cancel = Some(task.id); + } + interactive_hovered |= hovered; + } + }); + if has_footer { + ui.add_space(4.0); + let text = if hidden > 0 { tr_format!("+{n} more", n = hidden) } else { tr("Show less").to_string() }; + let (clicked, hovered) = more_control_with_hover(ui, &t, &text); + toggle = clicked; + interactive_hovered |= hovered; + } + interactive_hovered }); - if hidden > 0 || (app.activity_expanded && tasks.len() > MAX_ROWS) { - ui.add_space(4.0); - let text = if hidden > 0 { tr_format!("+{n} more", n = hidden) } else { tr("Show less").to_string() }; - toggle = more_control(ui, &t, &text); - } + frame_resp.inner }); - }); + let interactive_hovered = area_resp.inner; + if area_resp.response.dragged() { + ctx.set_cursor_icon(egui::CursorIcon::Grabbing); + } else if interactive_hovered { + ctx.set_cursor_icon(egui::CursorIcon::PointingHand); + } else if area_resp.response.hovered() { + ctx.set_cursor_icon(egui::CursorIcon::Grab); + } if let Some(id) = cancel { self::cancel(app, id); } @@ -122,9 +164,10 @@ pub(crate) fn cancel(app: &mut LightcraftApp, id: u64) { let _ = app.session.execute("activity.cancel", &json!({"id": id})); } -/// One task: name and ✕, the bar, the detail line. True when ✕ was clicked. -fn row(ui: &mut egui::Ui, t: &Tokens, task: &TaskInfo, width: f32) -> bool { +/// One task: name and ✕, the bar, the detail line. Returns `(cancel_clicked, cross_hovered)`. +fn row_with_hover(ui: &mut egui::Ui, t: &Tokens, task: &TaskInfo, width: f32) -> (bool, bool) { let mut clicked = false; + let mut cross_hovered = false; let r = ui.vertical(|ui| { ui.set_width(width); ui.horizontal(|ui| { @@ -136,7 +179,7 @@ fn row(ui: &mut egui::Ui, t: &Tokens, task: &TaskInfo, width: f32) -> bool { ui.add(egui::Label::new(RichText::new(tr(&task.label)).font(t.font(12.5)).color(t.text)).truncate()); }); if cross { - clicked = cancel_control(ui, task.id); + (clicked, cross_hovered) = cancel_control(ui, task.id); } }); bar(ui, task, width); @@ -148,11 +191,11 @@ fn row(ui: &mut egui::Ui, t: &Tokens, task: &TaskInfo, width: f32) -> bool { if !measuring(ui) { register(ui, format!("activity:row:{}", task.id), r.response.rect); } - clicked + (clicked, cross_hovered) } /// Per-task ids, not labels, identify both the sensed SDK control and the cancel command. -fn cancel_control(ui: &mut egui::Ui, task_id: u64) -> bool { +fn cancel_control(ui: &mut egui::Ui, task_id: u64) -> (bool, bool) { let widget = format!("activity:cancel:{task_id}"); let measuring = measuring(ui); let (rect, _) = ui.allocate_exact_size(vec2(CROSS, CROSS), Sense::hover()); @@ -165,11 +208,11 @@ fn cancel_control(ui: &mut egui::Ui, task_id: u64) -> bool { if !measuring { crate::widgets::register_response(widget, rect, &shown.response); } - !measuring && shown.clicked() + (!measuring && shown.clicked(), !measuring && shown.response.hovered()) } /// Keep the compact label-sized target; the SDK Link adds natural Tab/Space/Enter activation. -fn more_control(ui: &mut egui::Ui, t: &Tokens, text: &str) -> bool { +fn more_control_with_hover(ui: &mut egui::Ui, t: &Tokens, text: &str) -> (bool, bool) { let measuring = measuring(ui); // show_at does not allocate: reserve the same text-sized row as the native label, // rather than importing a push button's larger padded minimum into the activity stack. @@ -183,7 +226,17 @@ fn more_control(ui: &mut egui::Ui, t: &Tokens, text: &str) -> bool { if !measuring { crate::widgets::register_response("activity:more", rect, &shown.response); } - !measuring && shown.clicked() + (!measuring && shown.clicked(), !measuring && shown.response.hovered()) +} + +#[cfg(test)] +fn row(ui: &mut egui::Ui, t: &Tokens, task: &TaskInfo, width: f32) -> bool { + row_with_hover(ui, t, task, width).0 +} + +#[cfg(test)] +fn more_control(ui: &mut egui::Ui, t: &Tokens, text: &str) -> bool { + more_control_with_hover(ui, t, text).0 } /// The progress bar, named after its task for screen readers; while the amount of work isn't diff --git a/crates/ui-egui/src/panels/bursts.rs b/crates/ui-egui/src/panels/bursts.rs new file mode 100644 index 0000000000..3a78f16f5f --- /dev/null +++ b/crates/ui-egui/src/panels/bursts.rs @@ -0,0 +1,362 @@ +//! Window ▸ Bursts: Assisted Culling's bursts among the photos in view (with the hidden members of +//! their collapsed stacks), each a row of thumbnails with its pick first, to put right by hand. +//! +//! Drag a photo to another place in its burst (to the front, and it becomes the pick), into +//! another burst, onto *New burst* or onto *Not in a burst*; drag a burst by its title onto +//! another to merge them. Photos dragged from the grid drop here too. A drag is the grid's photo +//! drag ([`crate::state::UiState::dragging_photos`]: its label, Esc and release), and a drop is one +//! `photo.moveToBurst`, so one undo step. +//! +//! Widgets: `burst:{n}` (a burst's title, `n` its number), `burstPhoto:{id}`, `burstPick:{n}`, +//! `burst:new`, `burst:none`. + +use std::collections::{HashMap, HashSet}; +use std::sync::Arc; + +use egui::{Align2, Color32, Rect, Sense, Stroke, StrokeKind, pos2, vec2}; +use lightcraft_catalog::{Flag, PhotoId}; +use serde_json::{Value, json}; + +use crate::LightcraftApp; +use crate::theme::Tokens; +use crate::widgets::register; + +/// Thumbnail cells: side, gap, row inset. +const CELL: f32 = 68.0; +const GAP: f32 = 6.0; +const INSET: f32 = 20.0; +/// A burst's title row. +const TITLE_H: f32 = 30.0; + +/// The bursts shown, by the view's generation (which follows every catalog change). +pub type Shown = Arc)>>; + +/// The bursts among the photos in view and the hidden members of their stacks, in view order. +fn bursts(app: &mut LightcraftApp) -> Shown { + let (generation, ids) = app.session.visible_shared(); + if let Some((g, b)) = &app.caches.bursts + && *g == generation + { + return b.clone(); + } + let cat = &app.session.catalog; + // each photo in view, then the hidden members of its stack: a burst whose photos are all + // hidden in another burst's collapsed stack is listed too, after that stack's top + let mut anchors: Vec = Vec::with_capacity(ids.len()); + for id in ids.iter() { + anchors.push(*id); + if let Some(st) = cat.stack_of(*id) { + anchors.extend(st.photos.iter().copied().filter(|p| p != id)); + } + } + let scope: HashSet = anchors.iter().copied().collect(); + let b: Shown = Arc::new(cat.bursts_among(&anchors, Some(&scope))); + app.caches.bursts = Some((generation, b.clone())); + b +} + +/// Every burst of the library: its number → its photos, pick first. +pub type All = Arc>>; + +/// Every burst of the library, built once per view generation (it follows every catalog change). +fn all_bursts(app: &mut LightcraftApp) -> All { + let (generation, _) = app.session.visible_shared(); + if let Some((g, b)) = &app.caches.burst_index + && *g == generation + { + return b.clone(); + } + let b: All = Arc::new(app.session.catalog.burst_index()); + app.caches.burst_index = Some((generation, b.clone())); + b +} + +/// A [`Target::Burst`] slot after every photo of the burst: a drop on its title or after its +/// last photo. +const LAST: usize = usize::MAX; + +/// Where a drop under the pointer would put the dragged photos. +#[derive(Clone, Copy, PartialEq, Debug)] +enum Target { + /// Burst `n` at `slot` (a place among its photos as shown, the dragged ones included; + /// [`LAST`]: after every photo of the burst, those out of view too), dropped on the left half + /// of the photo at `slot` (`true`: right before it) or the right half of the one before. + Burst(u32, usize, bool), + New, + Nowhere, +} + +/// Where the pointer is over the panel, and what a drop there would do (with the line marking it). +type Drop = Option<(Target, Option)>; + +pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { + let t = Tokens::get(ui.ctx()); + egui::ScrollArea::vertical().id_salt("bursts-scroll").auto_shrink([false, false]).show(ui, |ui| { + ui.spacing_mut().item_spacing.y = 0.0; + super::left::drag_auto_scroll(app, ui); + super::right::header(ui, "Bursts"); + let shown = bursts(app); + let dragged: Option> = app.ui.dragging_photos.as_ref().map(|v| v.iter().copied().map(PhotoId).collect()); + let pointer = ui.input(|i| i.pointer.latest_pos()).filter(|p| ui.clip_rect().contains(*p)); + let mut target: Drop = None; + let width = ui.available_width(); + let explain = if shown.is_empty() { + "Photo → Assisted Culling… groups look-alike shots into bursts. They show here to put right by hand." + } else { + "Drag a photo to its place: the first of a burst is its pick. Drag one into another burst, or a burst by its title onto another to merge them." + }; + egui::Frame::NONE.inner_margin(egui::Margin { left: INSET as i8, right: INSET as i8, top: 0, bottom: 10 }).show(ui, |ui| { + ui.set_width(width - 2.0 * INSET); + ui.label(egui::RichText::new(crate::i18n::tr(explain)).color(t.text_dim).size(12.0)); + }); + for (k, (g, photos)) in shown.iter().enumerate() { + burst_rows(app, ui, &t, (k, *g, photos), pointer, dragged.is_some(), &mut target); + } + // drop places for a new burst and for none: there while there are bursts, or a drag + if !shown.is_empty() || dragged.is_some() { + drop_zones(ui, &t, pointer, dragged.is_some(), &mut target); + } + if let Some(ids) = dragged + && let Some((tgt, mark)) = target + { + drop_on(app, ui, &shown, &ids, tgt, mark); + } + ui.add_space(12.0); + }); +} + +/// Burst `g` (the `k`th shown): its title, then its photos in rows. Sets `target` when the pointer +/// is over it. +fn burst_rows( + app: &mut LightcraftApp, + ui: &mut egui::Ui, + t: &Tokens, + (k, g, photos): (usize, u32, &[PhotoId]), + pointer: Option, + dragging: bool, + target: &mut Drop, +) { + let width = ui.available_width(); + let cols = (((width - 2.0 * INSET + GAP) / (CELL + GAP)).floor() as usize).max(1); + let title = burst_title(app, ui, t, (k, g, photos.len()), pointer, dragging, target); + let n = photos.len(); + // the photos, in rows + let rows = n.div_ceil(cols); + let (area, _) = ui.allocate_exact_size(vec2(width, rows as f32 * (CELL + GAP) + GAP), Sense::hover()); + let cell_at = |i: usize| { + let (r, c) = (i / cols, i % cols); + Rect::from_min_size(pos2(area.left() + INSET + c as f32 * (CELL + GAP), area.top() + r as f32 * (CELL + GAP)), vec2(CELL, CELL)) + }; + for (i, id) in photos.iter().enumerate() { + let r = cell_at(i); + if let Some(badge) = photo_cell(app, ui, *id, r) { + register(ui, format!("burstPick:{g}"), badge); + } + // a drop on a photo's left half goes before it, on its right half after it + if let Some(p) = pointer + && r.expand(GAP / 2.0).contains(p) + { + let slot = if p.x < r.center().x { i } else { i + 1 }; + let edge = if slot == i { r.left() - GAP / 2.0 } else { r.right() + GAP / 2.0 }; + *target = Some((Target::Burst(g, slot, slot == i), Some(Rect::from_min_max(pos2(edge - 1.5, r.top()), pos2(edge + 1.5, r.bottom()))))); + } + } + if target.is_none() + && let Some(p) = pointer + && area.contains(p) + { + // the room after the last photo: last + let last = cell_at(n.saturating_sub(1)); + *target = Some(( + Target::Burst(g, LAST, false), + Some(Rect::from_min_max(pos2(last.right() + GAP / 2.0 - 1.5, last.top()), pos2(last.right() + GAP / 2.0 + 1.5, last.bottom()))), + )); + } + if dragging && matches!(target, Some((Target::Burst(tg, ..), _)) if *tg == g) { + ui.painter().rect_stroke(title.union(area).shrink2(vec2(8.0, 1.0)), 4.0, Stroke::new(1.0, t.accent.gamma_multiply(0.6)), StrokeKind::Inside); + } +} + +/// Burst `g`'s title (the `k`th shown, of `n` photos): a drop there puts the photos last; +/// dragged, it takes the burst along. +fn burst_title( + app: &mut LightcraftApp, + ui: &mut egui::Ui, + t: &Tokens, + (k, g, n): (usize, u32, usize), + pointer: Option, + dragging: bool, + target: &mut Drop, +) -> Rect { + let width = ui.available_width(); + let (title, resp) = ui.allocate_exact_size(vec2(width, TITLE_H), Sense::click_and_drag()); + register(ui, format!("burst:{g}"), title); + let p = ui.painter(); + let name = format!("{} {}", crate::i18n::tr("Burst"), k + 1); + p.text(pos2(title.left() + INSET, title.center().y), Align2::LEFT_CENTER, name, t.semibold(12.5), t.text); + let count = crate::i18n::tr_format!("{n} photo{}", if n == 1 { "" } else { "s" }, n = n); + p.text(pos2(title.right() - INSET, title.center().y), Align2::RIGHT_CENTER, count, t.font(11.5), t.text_dim); + if resp.hovered() && !dragging { + ui.ctx().set_cursor_icon(egui::CursorIcon::Grab); + } + // the whole burst, also its photos out of view + if resp.drag_started() { + app.ui.dragging_photos = Some(all_bursts(app).get(&g).map(|m| m.iter().map(|p| p.0).collect()).unwrap_or_default()); + } + if pointer.is_some_and(|p| title.contains(p)) { + *target = Some((Target::Burst(g, LAST, false), None)); + } + title +} + +/// The drop places for a new burst and for none. Sets `target` when a drag is over one. +fn drop_zones(ui: &mut egui::Ui, t: &Tokens, pointer: Option, dragging: bool, target: &mut Drop) { + let width = ui.available_width(); + ui.add_space(8.0); + for (key, label, tgt) in [("burst:new", "New burst", Target::New), ("burst:none", "Not in a burst", Target::Nowhere)] { + let (row, _) = ui.allocate_exact_size(vec2(width, 40.0), Sense::hover()); + let zone = row.shrink2(vec2(INSET, 4.0)); + register(ui, key, zone); + let over = dragging && pointer.is_some_and(|p| zone.contains(p)); + let stroke = if over { Stroke::new(1.5, t.accent) } else { Stroke::new(1.0, t.divider) }; + ui.painter().rect_stroke(zone, 6.0, stroke, StrokeKind::Inside); + ui.painter().text(zone.center(), Align2::CENTER_CENTER, crate::i18n::tr(label), t.font(12.0), if over { t.text } else { t.text_dim }); + if over { + *target = Some((tgt, None)); + } + } +} + +/// One photo of a burst: its thumbnail, the pick's badge (returned), the active photo's outline; +/// a click selects it, a drag takes it along. +fn photo_cell(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, r: Rect) -> Option { + let t = Tokens::get(ui.ctx()); + let photo = app.session.catalog.photo(id).cloned()?; + let pick = photo.analysis.is_some_and(|a| a.best); + let resp = ui.interact(r, egui::Id::unique(("burst-photo", id.0)), Sense::click_and_drag()); + register(ui, format!("burstPhoto:{}", id.0), r); + // Any thumbnail will do at this size: one is asked for only when there is none, so the grid's + // larger ones are never asked again at this size (and back) every frame. Above the grid's own + // priorities: a member hidden in a collapsed stack isn't in the grid, which evicts the rest. + if app.renderer.thumb(id).is_none() && !app.renderer.is_pending(crate::render::Slot::Thumb(id)) { + let px = (CELL * ui.ctx().pixels_per_point()).ceil() as usize; + super::grid::request_thumb(app, id, px, 12); + } + let p = ui.painter(); + p.rect_filled(r, 3.0, Color32::from_gray(30)); + let shown = match app.renderer.thumb(id) { + Some(tex) => { + let fit = super::detail::fit_texture_rect(r, tex.size); + p.image(tex.tex.id(), fit, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); + fit + } + None => r, + }; + if photo.flag == Flag::Reject { + p.rect_filled(shown, 0.0, Color32::from_black_alpha(110)); + } + let state = app.session.selection.state_of(id); + if state == lightcraft_engine::SelectionState::Active { + p.rect_stroke(shown, 0.0, Stroke::new(2.0, Color32::WHITE), StrokeKind::Outside); + } else if state != lightcraft_engine::SelectionState::NotSelected { + p.rect_stroke(shown, 0.0, Stroke::new(2.0, Color32::from_gray(170)), StrokeKind::Outside); + } + let badge = pick.then(|| { + let g = p.layout_no_wrap(crate::i18n::tr("Pick").into(), t.semibold(9.5), Color32::WHITE); + let badge = Rect::from_min_size(r.min + vec2(3.0, 3.0), vec2(g.size().x + 10.0, 14.0)); + p.rect_filled(badge, 7.0, t.accent); + p.galley(pos2(badge.left() + 5.0, badge.center().y - g.size().y / 2.0), g, Color32::WHITE); + badge + }); + if photo.flag == Flag::Pick { + crate::icons::paint( + p, + Rect::from_min_size(pos2(r.right() - 16.0, r.bottom() - 16.0), vec2(13.0, 13.0)), + crate::icons::Icon::FlagPick, + t.pick, + ); + } + let focus = photo.analysis.map(|a| a.sharpness.round() as i32).unwrap_or_default(); + let resp = resp.on_hover_text(format!("{} · {} {focus}", photo.file_name, crate::i18n::tr("Focus"))); + if resp.clicked() { + let _ = app.run("library.select", json!({"ids": [id.0]})); + } + if resp.drag_started() { + app.ui.dragging_photos = Some(vec![id.0]); + } + badge +} + +/// Photos dragged over `tgt`: the mark where they would go, the label saying what a drop does, +/// and on release the move. +fn drop_on(app: &mut LightcraftApp, ui: &mut egui::Ui, shown: &Shown, ids: &[PhotoId], tgt: Target, mark: Option) { + let t = Tokens::get(ui.ctx()); + let released = ui.input(|i| i.pointer.any_released()); + // only photos culling scored can be in a burst + if ids.iter().any(|id| app.session.catalog.photo(*id).is_none_or(|p| p.analysis.is_none())) { + ui.ctx().set_cursor_icon(egui::CursorIcon::NotAllowed); + let why = if ids.len() == 1 { "Run Assisted Culling on it first" } else { "Run Assisted Culling on these photos first" }; + super::grid::drag_hint(ui.ctx(), crate::i18n::tr(why).into()); + if released { + app.toast( + ui.ctx(), + crate::i18n::tr("Only photos Assisted Culling scored can be in a burst: run Photo → Assisted Culling… on them first"), + ); + app.ui.dragging_photos = None; + } + return; + } + let (params, hint) = match tgt { + Target::Burst(g, slot, before) => { + let all = all_bursts(app); + let members = shown.iter().find(|(n, _)| *n == g).map(|(_, m)| m.as_slice()).unwrap_or(&[]); + // the place in the whole burst (members the view leaves out included) once the dragged + // photos have left theirs: right before the photo dropped on, or right after the one + // whose right half it was (members out of view between them stay on their side) + let rest: Vec = all.get(&g).map(|m| m.iter().copied().filter(|p| !ids.contains(p)).collect()).unwrap_or_default(); + let at = |m: &PhotoId| rest.iter().position(|p| p == m); + let next = members.get(slot..).and_then(|after| after.iter().find(|m| !ids.contains(m))); + let index = if slot == LAST { + rest.len() + } else if let Some(i) = next.filter(|_| before).and_then(at) { + i + } else { + members[..slot.min(members.len())] + .iter() + .rev() + .find(|m| !ids.contains(m)) + .and_then(|m| rest.iter().position(|p| p == m)) + .map_or(0, |i| i + 1) + }; + // the dragged photos are a whole other burst (one lookup: the first one's burst) + let from = ids.first().and_then(|id| app.session.catalog.photo(*id)).and_then(|p| p.analysis).and_then(|a| a.group); + let whole = from + .filter(|n| *n != g) + .and_then(|n| all.get(&n)) + .is_some_and(|m| m.len() > 1 && m.len() == ids.len() && m.iter().all(|p| ids.contains(p))); + let hint = if whole { + "Merge into this burst" + } else if index == 0 && slot < members.len() { + if ids.len() == 1 { "Make it the pick" } else { "Put first: the first is the pick" } + } else if ids.iter().all(|id| members.contains(id)) { + "Move here" + } else { + "Move to this burst" + }; + let index = if index >= rest.len() { Value::Null } else { json!(index) }; + (json!({"ids": ids.iter().map(|p| p.0).collect::>(), "burst": g, "index": index}), hint) + } + Target::New => (json!({"ids": ids.iter().map(|p| p.0).collect::>(), "burst": "new"}), "New burst"), + Target::Nowhere => (json!({"ids": ids.iter().map(|p| p.0).collect::>(), "burst": null}), "Take out of its burst"), + }; + if let Some(mark) = mark { + ui.painter().rect_filled(mark, 1.5, t.accent); + } + super::grid::drag_hint(ui.ctx(), crate::i18n::tr(hint).into()); + if released { + if let Err(e) = app.run("photo.moveToBurst", params) { + app.toast(ui.ctx(), e); + } + app.ui.dragging_photos = None; + } +} diff --git a/crates/ui-egui/src/panels/compare.rs b/crates/ui-egui/src/panels/compare.rs index fd589794b2..4e5f6be217 100644 --- a/crates/ui-egui/src/panels/compare.rs +++ b/crates/ui-egui/src/panels/compare.rs @@ -228,7 +228,7 @@ fn frame_of(photo: &lightcraft_catalog::Photo) -> lightcraft_pipeline::geometry: photo.height.max(1) as usize, &photo.develop, true, - photo.embedded_lens.as_ref(), + photo.embedded_lens.as_deref(), ) } diff --git a/crates/ui-egui/src/panels/detail.rs b/crates/ui-egui/src/panels/detail.rs index 86ae9c5cd7..6e1840751b 100644 --- a/crates/ui-egui/src/panels/detail.rs +++ b/crates/ui-egui/src/panels/detail.rs @@ -14,6 +14,7 @@ use crate::state::{BeforeAfter, RightPanel, ToolOverlay, Zoom}; use crate::theme::Tokens; use crate::widgets::{register, register_geometry}; +mod brush; mod crop; mod filmstrip; mod geometry; @@ -25,6 +26,8 @@ mod masks; mod retouch; mod window; +pub(crate) use brush::settle_wheel_edit; +use brush::{brush_drag, brush_wheel}; #[cfg(test)] pub(crate) use crop::crop_angle_label; use crop::crop_overlay; @@ -75,6 +78,9 @@ pub enum Gesture { /// Pen pressure (0..1) at each point; empty when no pen pressure was reported (a mouse) or the /// brush's Pen Pressure switch is off. pressure: Vec, + /// A stroke whose effect shows while painting: when (app time) it last went to the photo and + /// how many points it had then; `None` until it first does (its undo step is open meanwhile). + live: Option<(f64, usize)>, }, Spot { points: Vec, @@ -163,7 +169,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { // the full-screen preview shows the photo only: no tool overlays let right = if fullscreen { RightPanel::None } else { app.ui.right }; let crop_tool = right == RightPanel::Crop; - let frame = Frame::with_lens(photo.width.max(1) as usize, photo.height.max(1) as usize, &d, !crop_tool, photo.embedded_lens.as_ref()); + let frame = Frame::with_lens(photo.width.max(1) as usize, photo.height.max(1) as usize, &d, !crop_tool, photo.embedded_lens.as_deref()); let aspect = frame.aspect() as f32; let ppp = ui.ctx().pixels_per_point(); let area = canvas.shrink(loupe_margin(fullscreen, crop_tool)); @@ -184,6 +190,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { let mut target_rect = fit_rect(main_area, display_aspect, app.ui.zoom, native, ppp, app.ui.pan); let mut img_rect = animated_rect(ui.ctx(), &mut app.ui.zoom_anim, target_rect); let in_pane = |pane: Rect, image: Rect| image.translate(pane.center() - main_area.center()); + brush_wheel(app, ui, &resp, right); let navigating = areas.iter().any(|&view_area| { let view_img = in_pane(view_area, img_rect); navigate_gesture(app, ui, &resp, view_area, view_img, native) || middle_pan(app, ui, &resp, view_area, view_img) @@ -537,7 +544,7 @@ fn neighbour_job( with_crop: bool, ) -> Option { let np = app.session.catalog.photo(nid)?; - let nf = Frame::with_lens(np.width.max(1) as usize, np.height.max(1) as usize, &np.develop, with_crop, np.embedded_lens.as_ref()); + let nf = Frame::with_lens(np.width.max(1) as usize, np.height.max(1) as usize, &np.develop, with_crop, np.embedded_lens.as_deref()); let na = nf.aspect() as f32; let nr = fit_rect(main_area, na, app.ui.zoom, output_px(&nf), ppp, app.ui.pan); let nw = app.ui.settings.prefetch_edge(nr.width().max(nr.height()) * ppp, output_px(&nf).into_iter().max().unwrap_or(1), texture_side); @@ -765,6 +772,9 @@ struct ToolView<'a> { /// Route the pointer to the right panel's tool on the photo, or to the general interactions. fn tool_interaction(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Response, tv: &ToolView, v: &Views) { let (map, d) = (tv.map, tv.d); + if brush_drag(app, ui, resp, tv.right, map) { + return; + } match tv.right { RightPanel::Crop => crop_overlay(app, ui, resp, map, tv.frame, d, tv.id), RightPanel::Masking => mask_overlay(app, ui, resp, map, d), @@ -1163,6 +1173,81 @@ fn targeted_drag(app: &mut LightcraftApp, resp: &egui::Response, map: &CanvasMap } } +/// Whether a slider is adjusting the photo right now. Then the mask overlay, its lines, handles +/// and pins hide so the effect itself can be judged, even an overlay switched on with O; they come +/// back as they were when the slider is let go. Sliders that shape the mask itself (Refine, +/// Smoothness, Feather, a range's edges) keep them. +pub(crate) fn adjusting(app: &LightcraftApp) -> bool { + app.ui.dragging_control.as_deref().is_some_and(|c| !shapes_graphics(c)) +} + +/// Slider ids that change what the mask graphics show rather than the photo's look. +fn shapes_graphics(id: &str) -> bool { + matches!(id, "refine" | "smoothness" | "edge" | "feather") +} + +/// The mask the overlay shows, if any. One rule: +/// overlay = O / Always, OR (the pointer on the mask's pin or on one of its component rows AND not +/// adjusting), OR (Auto AND the mask has no settings). The pointer on the mask's own row (name, eye, +/// menu) shows nothing: that is where its effect is judged, the eye switching it on and off. "Adjusting" is a slider at work ([`adjusting`], which hides every +/// overlay in [`view_overlay`]) or a mask gesture (a handle or the gradient dragged, a brush +/// stroke): hovering never shows the overlay while one runs, even with the pointer over the pin +/// being dragged. A mask with settings (its own, or a preset's) never shows by itself, so its effect +/// can be judged while it is placed or picked; a mask without settings shows what it selects, also +/// while it is drawn (there is no effect to see yet). This replaces showing the overlay again on +/// every new, picked or duplicated mask (#1800): that covered the photo exactly when the user +/// judges a mask's effect; hovering one of its component rows or its pin, or O, shows it on request. +pub(crate) fn overlay_mask<'a>(app: &LightcraftApp, d: &'a DevelopSettings) -> Option<&'a lightcraft_develop::Mask> { + if !mask_gesture(app) + && let Some(photo) = app.session.active() + && let Some(m) = + app.ui.mask_hover.or(app.ui.mask_hover_prev).filter(|(p, _)| *p == photo).and_then(|(_, id)| d.masks.iter().find(|m| m.id == id)) + { + return Some(m); + } + let m = app.session.active_mask.and_then(|id| d.masks.iter().find(|m| m.id == id))?; + overlay_shown(app, m).then_some(m) +} + +/// Whether the selected mask `m`'s overlay shows (without hovering): O / Always, or Auto and `m` +/// has no settings ([`overlay_mask`] has the whole rule). +pub(crate) fn overlay_shown(app: &LightcraftApp, m: &lightcraft_develop::Mask) -> bool { + // (a mask O hid stays hidden though O showed another since) + if app.session.active().is_some_and(|photo| app.ui.mask_overlay_hidden.contains(&(photo, m.id))) { + return false; + } + app.ui.mask_overlay || !mask_has_settings(m) +} + +/// Whether mask `m` changes the photo by itself: any adjustment off its default. (Its shape, Refine +/// Edges included, is not a setting: it is what the overlay is for.) +pub(crate) fn mask_has_settings(m: &lightcraft_develop::Mask) -> bool { + m.adjust != lightcraft_develop::LocalAdjustments::default() +} + +/// Whether a mask is being shaped on the photo right now: a handle or the gradient dragged, a brush +/// stroke. +pub(crate) fn mask_gesture(app: &LightcraftApp) -> bool { + matches!(app.gesture, Some(Gesture::MaskHandle { .. } | Gesture::Brush { .. })) +} + +/// Whether the selected mask `m` has an AI selection (an Object click or a description) still +/// being computed. Meanwhile no overlay shows for it: a stand-in would look like the result. +pub(crate) fn ai_computing(app: &LightcraftApp, m: &lightcraft_develop::Mask) -> bool { + app.session.segmenter.busy() && ai_unfinished(m) +} + +/// Whether mask `m` has an AI selection without its result yet. +fn ai_unfinished(m: &lightcraft_develop::Mask) -> bool { + m.components.iter().any(|c| matches!(&c.shape, MaskShape::Prompt { seg: None, .. } | MaskShape::Object { seg: None, .. })) +} + +/// Whether the all-masks overlay can show: some visible mask has a shape, and none has an AI +/// selection still being computed (`busy`), whose stand-in would look like the result. +pub(crate) fn all_masks_showable(d: &DevelopSettings, busy: bool) -> bool { + d.masks.iter().any(|m| m.visible && !m.components.is_empty()) && !(busy && d.masks.iter().any(|m| m.visible && ai_unfinished(m))) +} + /// The diagnostic overlay the loupe shows (an Alt-drag preview, the selected mask, Point Color's /// visualized range, Visualize Spots, the clipping warnings). pub(crate) fn view_overlay(app: &LightcraftApp, d: &DevelopSettings) -> lightcraft_pipeline::Overlay { @@ -1177,19 +1262,22 @@ pub(crate) fn view_overlay(app: &LightcraftApp, d: &DevelopSettings) -> lightcra { return o; } + // a slider at work: the effect shows, not the overlay (it returns afterwards) + let shown = !adjusting(app); // Show every visible mask's region at once (Ctrl+Shift+O / Cmd+Shift+O), ahead of the selected-mask overlay - // so the shortcut is not shadowed by the always-on single-mask overlay. - if app.ui.right == RightPanel::Masking && app.ui.mask_overlay_all && d.masks.iter().any(|m| m.visible && !m.components.is_empty()) { + // so the shortcut is not shadowed by the single-mask overlay. + if shown && app.ui.right == RightPanel::Masking && app.ui.mask_overlay_all && all_masks_showable(d, app.session.segmenter.busy()) { return Overlay::AllMasks { view: MaskView::parse(&app.ui.mask_overlay_mode).unwrap_or_default(), color: app.ui.mask_overlay_color, opacity: app.ui.mask_overlay_opacity.clamp(0.0, 100.0).round() as u8, }; } - if app.ui.right == RightPanel::Masking - && app.ui.mask_overlay - && let Some(m) = app.session.active_mask.and_then(|id| d.masks.iter().find(|m| m.id == id)) + if shown + && app.ui.right == RightPanel::Masking + && let Some(m) = overlay_mask(app, d) && !m.components.is_empty() + && !ai_computing(app, m) { return Overlay::Mask { id: m.id.min(u16::MAX as u32) as u16, @@ -1202,7 +1290,14 @@ pub(crate) fn view_overlay(app: &LightcraftApp, d: &DevelopSettings) -> lightcra return Overlay::Spots(app.ui.spots_threshold.clamp(0.0, 100.0).round() as u8); } let edit = app.ui.right == RightPanel::Edit; - if edit && app.ui.point_color_visualize && app.ui.flyout_open("pointColor") && app.ui.point_color < d.point_colors.len() { + // (a B&W photo's mixer shows its B&W mix, not Point Color) + if edit + && app.ui.point_color_visualize + && app.ui.flyout_open("mixer") + && app.ui.mixer_tab == "point" + && !crate::is_bw(d) + && app.ui.point_color < d.point_colors.len() + { return Overlay::PointColorRange(app.ui.point_color as u8); } if edit && app.ui.hdr_visualize && d.hdr.enabled { diff --git a/crates/ui-egui/src/panels/detail/brush.rs b/crates/ui-egui/src/panels/detail/brush.rs new file mode 100644 index 0000000000..09327720f2 --- /dev/null +++ b/crates/ui-egui/src/panels/detail/brush.rs @@ -0,0 +1,188 @@ +use super::geometry::CanvasMap; +use super::retouch::{SPOT_BODIES, SpotBodies, brush_circles, feather_band, grab_radius, spot_band, spot_under}; +use super::{Color32, LightcraftApp, Pos2, Rect, RightPanel, json, vec2}; +use crate::state::ViewMode; + +// ------------------------------------------------------------------------ brush by mouse + +/// The brush the pointer paints with on the photo: the Remove tool's, or the Masking brush. +fn brush_in_use(app: &LightcraftApp, right: RightPanel) -> bool { + right == RightPanel::Remove || (right == RightPanel::Masking && app.ui.tool == "brush") +} + +/// The mouse wheel over the photo resizes the brush in use for the next stroke (up: larger, ×1.1 a +/// notch) and Shift+wheel feathers it (+5 a notch). Over a Remove spot it resizes and feathers that +/// spot instead (selecting it), so a stroke just painted can still be adjusted; elsewhere it lets go +/// of the selected spot, whose settings the brush otherwise follows. +/// As in Lightroom, a smooth-scrolling mouse and a two-finger trackpad swipe do the same (a line's +/// worth of points a notch) instead of zooming or panning; pinch and ⌘-wheel still zoom. +pub(super) fn brush_wheel(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Response, right: RightPanel) { + let id = egui::Id::unique("brush-wheel"); + let now = ui.input(|i| i.time); + // the spot under the pointer now (last frame's outlines, this frame's pointer: it may have moved with the wheel) + // with each spot's radius as it is now: the wheel may have just resized it + let hovered = ui + .data(|d| d.get_temp::(egui::Id::unique(SPOT_BODIES))) + .filter(|_| right == RightPanel::Remove) + .and_then(|mut b| { + let spots = app.session.active().and_then(|p| app.session.develop_of(p)).map(|d| d.spots.clone()).unwrap_or_default(); + for (spot, _, _, r) in &mut b.bodies { + if let Some(s) = spots.get(*spot) { + *r = grab_radius(s, b.long); + } + } + spot_under(&b.bodies, b.active, resp.hover_pos()?) + }) + .map(|(index, ..)| index); + let in_use = brush_in_use(app, right) && resp.hovered(); + // one wheel gesture on a spot is one undo step: it ends after a pause, off that spot, or when the tool goes + if let Some((spot, last)) = ui.data(|d| d.get_temp::<(usize, f64)>(egui::Id::unique(WHEEL_EDIT))) { + let pressed = ui.input(|i| i.pointer.any_down()); + if !in_use || pressed || hovered != Some(spot) || now - last > WHEEL_EDIT_PAUSE { + end_wheel_edit(app, ui.ctx()); + } else { + ui.ctx().request_repaint_after(std::time::Duration::from_secs_f64(WHEEL_EDIT_PAUSE)); + } + } + if !in_use { + ui.data_mut(|d| d.remove_temp::(id)); + return; + } + let line = ui.ctx().options(|o| o.input_options.line_scroll_speed).max(1.0); + let ours = |e: &egui::Event| match e { + egui::Event::MouseWheel { unit, delta, modifiers, .. } if delta.is_finite() => { + // macOS reports most mice in points (Magic Mouse, smooth-scrolling wheels), a notched wheel in lines + let notches = if *unit == egui::MouseWheelUnit::Point { *delta / line } else { *delta }; + if *modifiers == egui::Modifiers::NONE { + Some((notches.y, 0.0)) + } else if *modifiers == egui::Modifiers::SHIFT { + // some platforms turn Shift+wheel into a sideways scroll + Some((0.0, notches.y + notches.x)) + } else { + None + } + } + _ => None, + }; + let (size, feather) = ui.input(|i| i.events.iter().filter_map(ours).fold((0.0f32, 0.0f32), |a, b| (a.0 + b.0, a.1 + b.1))); + if size != 0.0 || feather != 0.0 { + ui.input_mut(|i| i.events.retain(|e| ours(e).is_none())); + ui.data_mut(|d| d.insert_temp(id, true)); + let (k, df) = (1.1f32.powf(size.clamp(-10.0, 10.0)), 5.0 * feather.clamp(-10.0, 10.0)); + match hovered { + Some(index) => { + // the spot as it is now: the overlay saw it before this frame's edits + let current = + app.session.active().and_then(|p| app.session.develop_of(p)).and_then(|d| d.spots.get(index).map(|s| (s.size, s.feather))); + let Some((size, feather)) = current else { return }; + if app.session.active_spot != Some(index) { + let _ = app.run("spot.select", json!({"index": index})); + } + if ui.data(|d| d.get_temp::<(usize, f64)>(egui::Id::unique(WHEEL_EDIT))).is_none() { + let _ = app.run("develop.beginInteraction", json!({"label": "Edit Spot"})); + } + ui.data_mut(|d| d.insert_temp(egui::Id::unique(WHEEL_EDIT), (index, now))); + ui.ctx().request_repaint_after(std::time::Duration::from_secs_f64(WHEEL_EDIT_PAUSE)); + let mut p = json!({"index": index}); + if k != 1.0 { + p["size"] = json!((size * k as f64).clamp(0.001, 0.25)); + } + if df != 0.0 { + p["feather"] = json!((feather + df as f64).clamp(0.0, 100.0)); + } + let _ = app.run("spot.update", p); + } + None => { + deselect_spot(app, right); + let _ = crate::menus::resize_brush(app, k, df); + } + } + } + // egui glides a wheel's scroll over the next frames: none of it may pan or zoom the photo + if ui.data(|d| d.get_temp::(id)).unwrap_or(false) { + if ui.input(|i| i.smooth_scroll_delta == egui::Vec2::ZERO) { + ui.data_mut(|d| d.remove_temp::(id)); + } + ui.input_mut(|i| i.smooth_scroll_delta = egui::Vec2::ZERO); + } +} + +/// The spot a wheel gesture is editing and when it last turned, as `(index, time)`; its edits are one undo step. +const WHEEL_EDIT: &str = "brush-wheel-edit"; +/// Seconds without a turn that end a wheel gesture. +const WHEEL_EDIT_PAUSE: f64 = 0.5; + +/// Commits a wheel gesture's spot edits as one undo step. +fn end_wheel_edit(app: &mut LightcraftApp, ctx: &egui::Context) { + if ctx.data_mut(|d| d.remove_temp::<(usize, f64)>(egui::Id::unique(WHEEL_EDIT))).is_some() && app.session.interaction.is_some() { + let _ = app.run("develop.endInteraction", json!({})); + } +} + +/// Every frame, whatever is drawn: ends a wheel gesture whose loupe is gone (another view, another +/// tool), which `brush_wheel` no longer runs to end, or that has paused, so no later edit joins it. +pub(crate) fn settle_wheel_edit(app: &mut LightcraftApp, ctx: &egui::Context) { + let Some((_, last)) = ctx.data(|d| d.get_temp::<(usize, f64)>(egui::Id::unique(WHEEL_EDIT))) else { return }; + let drawn = app.ui.view == ViewMode::Detail && app.ui.right == RightPanel::Remove && !app.ui.fullscreen; + if !drawn || ctx.input(|i| i.time) - last > WHEEL_EDIT_PAUSE { + end_wheel_edit(app, ctx); + } +} + +/// Lets go of the selected Remove spot, so the brush (which shows a selected spot's settings) is the next stroke's alone. +fn deselect_spot(app: &mut LightcraftApp, right: RightPanel) { + if right == RightPanel::Remove && app.session.active_spot.is_some() { + let _ = app.run("spot.select", json!({"index": null})); + } +} + +/// ⌃⌥-drag (or ⌥-right-drag) on the photo sets the brush in use for the next stroke the way +/// Photoshop does: across for the size, up and down for the feather (down: softer), shown on the +/// circle where the drag started. True while it owns the pointer (nothing is painted). +pub(super) fn brush_drag(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Response, right: RightPanel, map: &CanvasMap) -> bool { + let id = egui::Id::unique("brush-resize"); + if !brush_in_use(app, right) { + ui.data_mut(|d| d.remove_temp::<(Pos2, f32, f32)>(id)); + return false; + } + let remove = right == RightPanel::Remove; + let current = |app: &LightcraftApp| { + if remove { (app.ui.remove_size, app.ui.remove_feather) } else { (app.ui.brush_size, app.ui.brush_feather) } + }; + let (mods, secondary) = ui.input(|i| (i.modifiers, i.pointer.secondary_down())); + if resp.drag_started() + && ((mods.ctrl && mods.alt) || (mods.alt && secondary)) + && let Some(o) = ui.input(|i| i.pointer.press_origin()) + { + deselect_spot(app, right); + let (s0, f0) = current(app); + ui.data_mut(|d| d.insert_temp(id, (o, s0, f0))); + } + let Some((o, s0, f0)) = ui.data(|d| d.get_temp::<(Pos2, f32, f32)>(id)) else { return false }; + if let Some(q) = ui.input(|i| i.pointer.latest_pos()) { + let dv = q - o; + let (s, f) = current(app); + let size = s0 * (dv.x / 200.0).exp(); + let feather = (f0 + dv.y * 0.3).clamp(0.0, 100.0); + if size != s || feather != f { + let _ = crate::menus::resize_brush(app, size / s.max(1e-6), feather - f); + } + } + let (s, f) = current(app); + let long = map.rect.width().max(map.rect.height()); + let r = s * long; + let p = ui.painter_at(app.canvas_rect.unwrap_or(map.rect)); + ui.ctx().set_cursor_icon(egui::CursorIcon::None); + let band = if remove { spot_band(feather_band(app.ui.tool == "fill", r, f)) } else { (r * (1.0 - f / 100.0), r) }; + brush_circles(&p, o, band); + let label = format!("{} {:.0} · {} {:.0}", crate::i18n::tr("Size"), s * 1000.0, crate::i18n::tr("Feather"), f); + let at = o + vec2(0.0, r + 14.0); + let galley = p.layout_no_wrap(label, egui::FontId::proportional(12.0), Color32::WHITE); + let rect = Rect::from_center_size(at, galley.size() + vec2(10.0, 4.0)); + p.rect_filled(rect, 4.0, Color32::from_black_alpha(160)); + p.galley(rect.center() - galley.size() / 2.0, galley, Color32::WHITE); + if !ui.input(|i| i.pointer.any_down()) { + ui.data_mut(|d| d.remove_temp::<(Pos2, f32, f32)>(id)); + } + true +} diff --git a/crates/ui-egui/src/panels/detail/geometry.rs b/crates/ui-egui/src/panels/detail/geometry.rs index 6e5edd1ce0..320bef86d8 100644 --- a/crates/ui-egui/src/panels/detail/geometry.rs +++ b/crates/ui-egui/src/panels/detail/geometry.rs @@ -253,7 +253,7 @@ pub(crate) fn output_px(frame: &Frame) -> [usize; 2] { pub(crate) fn focus_box(photo: &lightcraft_catalog::Photo) -> Option { let f = photo.meta.focus.as_ref()?; let d = &photo.develop; - let frame = Frame::with_lens(photo.width.max(1) as usize, photo.height.max(1) as usize, d, true, photo.embedded_lens.as_ref()); + let frame = Frame::with_lens(photo.width.max(1) as usize, photo.height.max(1) as usize, d, true, photo.embedded_lens.as_deref()); let [w, h] = output_px(&frame); let to_out = frame.out_to_norm(w, h).inverse()?; // stored on the upright photo: the user's Rotate / Flip on top, then the crop diff --git a/crates/ui-egui/src/panels/detail/info.rs b/crates/ui-egui/src/panels/detail/info.rs index 494bbc301c..60bccbb194 100644 --- a/crates/ui-egui/src/panels/detail/info.rs +++ b/crates/ui-egui/src/panels/detail/info.rs @@ -1,7 +1,7 @@ use super::geometry::focus_box; use super::{Color32, LightcraftApp, PhotoId, Pos2, Rect, Stroke, Tokens, json, pos2, register, register_geometry, vec2}; -/// Draw the camera's focus box over a photo drawn in `img` (View ▸ Focus Point): green corner +/// Draw the camera's focus box over a photo drawn in `img` (View ▸ Loupe Overlay ▸ Focus Point): green corner /// brackets with a dark keyline, the way cameras show their AF frame, never smaller than 14 pt. /// `key` names it for tests and the control channel (`canvas:focusPoint`, `compare:focusPoint:`). pub(crate) fn draw_focus_point(p: &egui::Painter, img: Rect, photo: &lightcraft_catalog::Photo, key: &str) { @@ -473,7 +473,7 @@ mod info_overlay_tests { lines } - /// View ▸ View Options: Info 1 and Info 2 each show the three lines chosen for them, in that + /// View ▸ Loupe Overlay ▸ View Options…: Info 1 and Info 2 each show the three lines chosen for them, in that /// order, without the lines set to None. #[test] fn the_info_overlay_shows_the_lines_chosen_in_view_options() { diff --git a/crates/ui-egui/src/panels/detail/lens_blur.rs b/crates/ui-egui/src/panels/detail/lens_blur.rs index f3c5404ece..229f037262 100644 --- a/crates/ui-egui/src/panels/detail/lens_blur.rs +++ b/crates/ui-egui/src/panels/detail/lens_blur.rs @@ -102,18 +102,18 @@ pub(super) fn lens_blur_brush_overlay(app: &mut LightcraftApp, ui: &mut egui::Ui let force = if app.ui.brush_pressure { ui.input(pen_force) } else { None }; match &mut app.gesture { Some(Gesture::Brush { points, .. }) if points.last() == Some(&n) => {} - Some(Gesture::Brush { points, pressure }) => { + Some(Gesture::Brush { points, pressure, .. }) => { record_pressure(pressure, points.len(), force); points.push(n); } _ => { let mut pressure = Vec::new(); record_pressure(&mut pressure, 0, force); - app.gesture = Some(Gesture::Brush { points: vec![n], pressure }); + app.gesture = Some(Gesture::Brush { points: vec![n], pressure, live: None }); } } } - if let Some(Gesture::Brush { points, pressure }) = &app.gesture { + if let Some(Gesture::Brush { points, pressure, .. }) = &app.gesture { let screen: Vec = points.iter().map(|q| map.screen(*q)).collect(); let params = crate::brush_live::LiveParams { clip, @@ -130,7 +130,7 @@ pub(super) fn lens_blur_brush_overlay(app: &mut LightcraftApp, ui: &mut egui::Ui app.brush_live = None; } if (resp.drag_stopped() || resp.clicked()) - && let Some(Gesture::Brush { points, pressure }) = app.gesture.take() + && let Some(Gesture::Brush { points, pressure, .. }) = app.gesture.take() { app.brush_live = None; let pts: Vec<[f64; 2]> = points.iter().map(|q| [q.x, q.y]).collect(); diff --git a/crates/ui-egui/src/panels/detail/masks.rs b/crates/ui-egui/src/panels/detail/masks.rs index 79a4460813..22ba89532f 100644 --- a/crates/ui-egui/src/panels/detail/masks.rs +++ b/crates/ui-egui/src/panels/detail/masks.rs @@ -1,7 +1,7 @@ use super::geometry::CanvasMap; use super::{ - Color32, DevelopSettings, Gesture, LightcraftApp, MaskShape, Point, Pos2, Rect, Stroke, StrokeKind, Tokens, ToolOverlay, json, pos2, register, - vec2, + Color32, DevelopSettings, Gesture, LightcraftApp, MaskShape, Point, Pos2, Rect, Stroke, StrokeKind, Tokens, ToolOverlay, adjusting, json, + overlay_shown, pos2, register, vec2, }; use crate::panels::masking::controls::Hit; @@ -364,7 +364,12 @@ pub(super) fn color_range_pick(app: &mut LightcraftApp, ui: &egui::Ui, resp: &eg pub(super) fn mask_overlay(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Response, map: &CanvasMap, d: &DevelopSettings) { let active = app.session.active_mask; let clip = app.canvas_rect.unwrap_or(map.rect); - let p = &ui.painter_at(clip); + let mut painter = ui.painter_at(clip); + // a slider at work: no lines, handles or pins over the effect + if adjusting(app) { + painter.set_invisible(); + } + let p = &painter; // (mask, component, handle, screen position) of everything that can be grabbed let mut grips: Vec<(u32, usize, u8, Pos2)> = Vec::new(); // pins follow Show Pins and the Tool Overlay mode (Shift+H); Auto hides them while brushing @@ -397,6 +402,15 @@ pub(super) fn mask_overlay(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &eg } } } + // the pointer on a pin shows that mask's overlay (as Lightroom Classic); of pins on top of each other, the + // selected mask's, then the nearest: the one a drag there would move ([`grip_gestures`]) + if let Some(h) = resp.hover_pos() + && let Some((mid, ..)) = grips.iter().filter(|(_, _, handle, q)| *handle == 0 && q.distance(h) < 9.0).min_by(|a, b| { + (Some(a.0) != active, a.3.distance(h)).partial_cmp(&(Some(b.0) != active, b.3.distance(h))).unwrap_or(std::cmp::Ordering::Equal) + }) + { + app.ui.mask_hover = app.session.active().map(|photo| (photo, *mid)); + } mask_keys(app, ui, map, d, &grips); object_marks(app, p, map, d, active); // Colour Range "Pick": the Masking panel owns the loupe's clicks (general_interaction @@ -665,6 +679,15 @@ fn brush_tool( clip: Rect, d: &DevelopSettings, ) { + // a live stroke cut short (no release seen): what went to the photo stays, in one step + if matches!(app.gesture, Some(Gesture::Brush { live: Some(_), .. })) + && !resp.drag_stopped() + && !resp.clicked() + && !ui.input(|i| i.pointer.any_down()) + { + app.gesture = None; + let _ = app.run("develop.endInteraction", json!({})); + } let active = app.session.active_mask; // the stroke goes into the selected mask (or a new one): in its coordinates let map = &map.for_mask_id(d, active); @@ -683,30 +706,39 @@ fn brush_tool( match &mut app.gesture { // a held, unmoving pointer records nothing: coverage builds by passes, not time (#518) Some(Gesture::Brush { points, .. }) if points.last() == Some(&n) => {} - Some(Gesture::Brush { points, pressure }) => { + Some(Gesture::Brush { points, pressure, .. }) => { record_pressure(pressure, points.len(), force); points.push(n); } + // a stroke starts with a press, not part-way through a drag: one ended for picking another mask + // or photo ([`LightcraftApp::cancel_brush_gesture`]) paints nothing more until the button is let go + _ if !(resp.drag_started() || resp.clicked()) => {} _ => { let mut pressure = Vec::new(); record_pressure(&mut pressure, 0, force); - app.gesture = Some(Gesture::Brush { points: vec![n], pressure }); + app.gesture = Some(Gesture::Brush { points: vec![n], pressure, live: None }); } } } - // the stroke being painted (the render shows it once it's committed), with the committed - // stroke's dab spacing, feather and flow (issue #517), tinted only when the overlay will - // show it: with the overlay hidden (O, or a mask slider hid it) or a colour overlay at - // opacity 0, the photo stays untinted while painting, so dodging and burning is judged on - // the photo (issue #2549) + // the overlay rule: a mask with settings shows its effect while painted (the stroke goes to the photo live), + // never tinted; the stroke is tinted only when the overlay will show it (O, or a mask without settings yet). + // With the all-masks overlay it follows the mask's visibility, and a colour overlay at opacity 0 tints nothing, + // so dodging and burning is judged on the photo (issue #2549). The tinted stroke has the committed stroke's dab + // spacing, feather and flow (issue #517); the render shows it once it's committed. use lightcraft_pipeline::MaskView; let colored = matches!(MaskView::parse(&app.ui.mask_overlay_mode).unwrap_or_default(), MaskView::Color | MaskView::ColorOnBw); // the all-masks overlay ([`view_overlay`]) shows only visible masks, and gives way to the // selected mask's when none has anything in it (a stroke goes into the selected mask, or a new one) - let visible = active.and_then(|id| d.masks.iter().find(|m| m.id == id)).is_none_or(|m| m.visible); + let mask = active.and_then(|id| d.masks.iter().find(|m| m.id == id)); + let visible = mask.is_none_or(|m| m.visible); let all = app.ui.mask_overlay_all && (visible || d.masks.iter().any(|m| m.visible && !m.components.is_empty())); - let shown = if all { visible } else { app.ui.mask_overlay } && !(colored && app.ui.mask_overlay_opacity <= 0.0); - if shown && let Some(Gesture::Brush { points, pressure }) = &app.gesture { + let red = if all { visible } else { mask.is_none_or(|m| overlay_shown(app, m)) } && !(colored && app.ui.mask_overlay_opacity <= 0.0); + if !red { + live_stroke(app, ui); + } + if let Some(Gesture::Brush { points, pressure, live: None }) = &app.gesture + && red + { let screen: Vec = points.iter().map(|q| map.screen(*q)).collect(); // opacity 0 only gets here in the image views, which ignore it: a fixed tint there let opacity = if app.ui.mask_overlay_opacity > 0.0 { app.ui.mask_overlay_opacity / 100.0 } else { 110.0 / 255.0 }; @@ -725,7 +757,7 @@ fn brush_tool( app.brush_live = None; } if (resp.drag_stopped() || resp.clicked()) - && let Some(Gesture::Brush { points, pressure }) = app.gesture.take() + && let Some(Gesture::Brush { points, pressure, live }) = app.gesture.take() { app.brush_live = None; let pts: Vec<[f64; 2]> = points.iter().map(|q| [q.x, q.y]).collect(); @@ -737,8 +769,54 @@ fn brush_tool( let _ = app.run( "mask.brushStroke", json!({"points": pts, "size": app.ui.brush_size, "feather": app.ui.brush_feather, "flow": app.ui.brush_flow, - "erase": erase, "autoMask": app.ui.brush_auto_mask, "pressure": pressure, "connect": connect}), + "erase": erase, "autoMask": app.ui.brush_auto_mask, "pressure": pressure, "connect": connect && live.is_none(), + "continue": live.is_some()}), ); + if live.is_some() { + let _ = app.run("develop.endInteraction", json!({})); + } + } +} + +/// A stroke on a mask with settings goes to the photo every moment while painting, so its effect +/// shows live (one undo step for the whole stroke). +fn live_stroke(app: &mut LightcraftApp, ui: &egui::Ui) { + let now = ui.input(|i| i.time); + let Some(Gesture::Brush { points, pressure, live }) = &app.gesture else { return }; + if !live_due(*live, points.len(), now) { + return; + } + let (pts, pressure, first) = (points.iter().map(|q| [q.x, q.y]).collect::>(), pressure.clone(), live.is_none()); + if first { + let _ = app.run("develop.beginInteraction", json!({"label": "Brush"})); + } + let erase = app.ui.brush_erase != ui.input(|i| i.modifiers.alt); + let sent = app.run( + "mask.brushStroke", + json!({"points": pts, "size": app.ui.brush_size, "feather": app.ui.brush_feather, "flow": app.ui.brush_flow, + "erase": erase, "autoMask": app.ui.brush_auto_mask, "pressure": pressure, "continue": !first}), + ); + // only a stroke that reached the photo is live: else the release would replace the mask's + // previous stroke instead of adding this one + if sent.is_ok() { + if let Some(Gesture::Brush { live, .. }) = &mut app.gesture { + *live = Some((now, pts.len())); + } + } else if first { + let _ = app.run("develop.endInteraction", json!({})); + } + ui.ctx().request_repaint_after(std::time::Duration::from_secs_f64(LIVE_STROKE_EVERY)); +} + +/// How often (seconds) a stroke whose effect shows while painting goes to the photo. +const LIVE_STROKE_EVERY: f64 = 0.12; + +/// Whether the stroke of `len` points should go to the photo now: the first time once it has two +/// points, then every [`LIVE_STROKE_EVERY`] when it grew. +fn live_due(live: Option<(f64, usize)>, len: usize, now: f64) -> bool { + match live { + None => len >= 2, + Some((at, sent)) => len > sent && (now - at >= LIVE_STROKE_EVERY || now < at || now.is_nan()), } } diff --git a/crates/ui-egui/src/panels/detail/retouch.rs b/crates/ui-egui/src/panels/detail/retouch.rs index ab314703a8..2e74a7d3a8 100644 --- a/crates/ui-egui/src/panels/detail/retouch.rs +++ b/crates/ui-egui/src/panels/detail/retouch.rs @@ -1,9 +1,36 @@ use super::geometry::CanvasMap; use super::masks::{pin, pins_live}; use super::{Color32, DevelopSettings, Gesture, LightcraftApp, Point, Pos2, Rect, Stroke, ToolOverlay, json, register, vec2}; +use crate::panels::spot_outline; +use lightcraft_develop::SpotMode; // ------------------------------------------------------------------------ remove +/// What of each Remove spot can be grabbed, as last drawn: `(spot, is source, screen points of +/// its stroke, radius)`, the selected spot and the photo's long edge on screen (for [`grab_radius`]). +/// `brush_wheel` finds the spot under the pointer in it. +#[derive(Clone, Debug, Default)] +pub(super) struct SpotBodies { + pub(super) bodies: Vec<(usize, bool, Vec, f32)>, + pub(super) active: Option, + pub(super) long: f64, +} + +/// How far from its stroke a spot is drawn (its outline) and can be grabbed, on a photo whose long edge is `long` on screen. +pub(super) fn grab_radius(s: &lightcraft_develop::Spot, long: f64) -> f32 { + feather_band(s.mode == SpotMode::Fill, (s.size * long) as f32, s.feather as f32).1 + OUTLINE_GAP +} +pub(super) const SPOT_BODIES: &str = "remove-spot-bodies"; + +/// The target or source among `bodies` under `q` (its pin or anywhere along its stroke) as `(spot, is +/// source, distance)`: the selected spot's first, then the nearest. +pub(super) fn spot_under(bodies: &[(usize, bool, Vec, f32)], active: Option, q: Pos2) -> Option<(usize, bool, f32)> { + bodies + .iter() + .filter_map(|(spot, source, pts, r)| Some((*spot, *source, spot_outline::grab_distance(pts, q, r.max(8.0))?))) + .min_by(|a, b| (Some(a.0) != active, a.2).partial_cmp(&(Some(b.0) != active, b.2)).unwrap_or(std::cmp::Ordering::Equal)) +} + /// The `spot.add` mode the Remove panel's Mode paints with, or `None` while no brush is chosen /// (Mode ▸ None, or another tool): then the photo takes no new spots, by pointer or by keyboard. pub(crate) fn spot_brush(tool: &str) -> Option<&'static str> { @@ -27,63 +54,71 @@ pub(super) fn remove_overlay(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: & let (mode, live) = (app.ui.tool_overlay, pins_live(app, resp, map)); // Auto also hides them while a new spot is painted let painting = mode == ToolOverlay::Auto && matches!(app.gesture, Some(Gesture::Spot { .. })); + // while a spot's target or source is dragged, its target's outline is hidden, so the edge being matched shows + let moving = match app.gesture { + Some(Gesture::SpotMove { spot, .. }) => Some(spot), + _ => None, + }; let p = ui.painter_at(app.canvas_rect.unwrap_or(map.rect)); let mut pins = p.clone(); if painting { pins.set_invisible(); } - // (spot, is source, screen centre, radius) of everything that can be grabbed + // (spot, is source, screen centre, radius) of every pin: the keyboard handles let mut grips: Vec<(usize, bool, Pos2, f32)> = Vec::new(); + // (spot, is source, screen points of the stroke, radius) of everything that can be grabbed: the pin, and + // anywhere within the radius of the stroke's points (the source's, shifted by its offset, for the selected spot) + let mut bodies: Vec<(usize, bool, Vec, f32)> = Vec::new(); + let clip = p.clip_rect(); for (i, s) in d.spots.iter().enumerate() { - let r = (s.size * long) as f32; + let band = feather_band(s.mode == SpotMode::Fill, (s.size * long) as f32, s.feather as f32); + let r = grab_radius(s, long); let sel = Some(i) == active; if !mode.shows(sel, live) { continue; } let p = &pins; - let col = Color32::from_white_alpha(if sel { 230 } else { 150 }); - for q in &s.points { - p.circle_stroke(map.screen(*q), r, Stroke::new(if sel { 1.5 } else { 1.0 }, col)); + let target: Vec = s.points.iter().map(|q| map.screen(*q)).collect(); + let light = if sel { Stroke::new(1.25, Color32::from_white_alpha(230)) } else { Stroke::new(1.0, Color32::from_white_alpha(120)) }; + if touches(&target, r, clip) && moving != Some(i) { + draw_spot(p, &target, band, light, false, sel); } - let Some(&t) = s.points.first() else { continue }; - let tq = map.screen(t); + let Some(&tq) = target.first() else { continue }; if let Some(o) = s.source_offset.filter(|_| sel) { - let sq = map.screen(Point::new(t.x + o.x, t.y + o.y)); - for q in &s.points { - p.circle_stroke(map.screen(Point::new(q.x + o.x, q.y + o.y)), r, Stroke::new(1.0, Color32::from_white_alpha(170))); + let source: Vec = s.points.iter().map(|q| map.screen(Point::new(q.x + o.x, q.y + o.y))).collect(); + if touches(&source, r, clip) { + draw_spot(p, &source, band, Stroke::new(1.0, Color32::from_white_alpha(150)), true, false); } + let sq = source[0]; let dir = (tq - sq).normalized(); - p.arrow(sq + dir * r, (tq - sq) - dir * (2.0 * r).min((tq - sq).length()), Stroke::new(1.0, Color32::from_white_alpha(200))); + let (from, by) = (sq + dir * r, (tq - sq) - dir * (2.0 * r).min((tq - sq).length())); + p.arrow(from, by, Stroke::new(2.5, Color32::from_black_alpha(110))); + p.arrow(from, by, Stroke::new(1.0, Color32::from_white_alpha(200))); register(ui, format!("spotSource:{i}"), Rect::from_center_size(sq, vec2(14.0, 14.0))); grips.push((i, true, sq, r)); + bodies.push((i, true, source, r)); } pin(p, tq, sel); register(ui, format!("spotPin:{i}"), Rect::from_center_size(tq, vec2(14.0, 14.0))); grips.push((i, false, tq, r)); + bodies.push((i, false, target, r)); } if spot_keys(app, ui, map, d, &grips) { return; } let r = (app.ui.remove_size as f64 * long) as f32; - // a target or source under `q`: the selected spot's first, then the nearest pin - let hit = |q: Pos2| { - grips - .iter() - .filter(|g| g.2.distance(q) < g.3.max(8.0)) - .min_by(|a, b| { - (Some(a.0) != active, a.2.distance(q)).partial_cmp(&(Some(b.0) != active, b.2.distance(q))).unwrap_or(std::cmp::Ordering::Equal) - }) - .copied() - }; + let band = feather_band(app.ui.tool == "fill", r, app.ui.remove_feather); + let hit = |q: Pos2| spot_under(&bodies, active, q); let hover = resp.hover_pos().and_then(hit); + // the mouse wheel resizes the spot under the pointer instead of the brush (`brush_wheel`, next frame) + ui.data_mut(|m| m.insert_temp(egui::Id::unique(SPOT_BODIES), SpotBodies { bodies: bodies.clone(), active, long })); let brush = spot_brush(&app.ui.tool); if let Some(h) = resp.hover_pos() { if hover.is_some() { ui.ctx().set_cursor_icon(egui::CursorIcon::Grab); } else if brush.is_some() { ui.ctx().set_cursor_icon(egui::CursorIcon::None); - p.circle_stroke(h, r, Stroke::new(1.0, Color32::WHITE)); - p.circle_stroke(h, r * (1.0 - app.ui.remove_feather / 100.0).max(0.05), Stroke::new(1.0, Color32::from_white_alpha(110))); + brush_circles(&p, h, spot_band(band)); } } let press = ui.input(|i| i.pointer.press_origin()).or(resp.interact_pointer_pos()); @@ -120,18 +155,24 @@ pub(super) fn remove_overlay(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: & } if brush.is_some() && let Some(q) = resp.interact_pointer_pos() - && (resp.drag_started() || resp.dragged() || resp.clicked()) + // the release ends the stroke where it is, but only the left button's: a middle drag pans + && (resp.drag_started() || resp.dragged() || resp.clicked() || resp.drag_stopped_by(egui::PointerButton::Primary)) { let n = map.norm(q); match &mut app.gesture { - Some(Gesture::Spot { points }) => points.push(n), + // a point every r/4 of movement; a held pointer stores nothing, and the release adds where it ended + Some(Gesture::Spot { points }) => { + let last = points.last().map(|l| map.screen(*l)); + if last.is_none_or(|l| spot_outline::adds_point(l, q, r, resp.drag_stopped_by(egui::PointerButton::Primary))) { + points.push(n); + } + } _ => app.gesture = Some(Gesture::Spot { points: vec![n] }), } } if let Some(Gesture::Spot { points }) = &app.gesture { - for q in points { - p.circle_filled(map.screen(*q), r, Color32::from_white_alpha(60)); - } + let screen: Vec = points.iter().map(|q| map.screen(*q)).collect(); + draw_spot(&p, &screen, band, Stroke::new(1.25, Color32::from_white_alpha(230)), false, true); } if (resp.drag_stopped() || resp.clicked()) && let Some(Gesture::Spot { points }) = app.gesture.take() @@ -145,6 +186,60 @@ pub(super) fn remove_overlay(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: & } } +/// Whether the discs of radius `r` at `pts` can show in `clip`. +fn touches(pts: &[Pos2], r: f32, clip: Rect) -> bool { + pts.iter().any(|q| clip.expand(r).contains(*q)) +} + +/// Where a spot of radius `r` starts and stops blending into the photo, as `pipeline::spots` does it: Heal and +/// Clone feather inside the radius (over its outer 80 % at full feather), Fill replaces all of it and feathers +/// outside, up to 0.3 radii further. +pub(super) fn feather_band(outside: bool, r: f32, feather: f32) -> (f32, f32) { + let f = (feather / 100.0).clamp(0.0, 1.0); + if outside { (r, r * (1.0 + 0.3 * f)) } else { (r * (1.0 - 0.8 * f), r) } +} + +/// How far outside the blend a spot's outline runs (screen points), so the line never covers the edge being matched. +const OUTLINE_GAP: f32 = 3.0; + +/// A spot over `pts` blending across `band`: its outline just outside the blend and, with `feather`, a faint +/// dashed line where the blend is full, so the feather between the two shows. +fn draw_spot(p: &egui::Painter, pts: &[Pos2], band: (f32, f32), light: Stroke, dashed: bool, feather: bool) { + draw_outline(p, &spot_outline::union_outline(pts, band.1 + OUTLINE_GAP), light, dashed); + if feather && band.1 - band.0 >= 3.0 && band.0 >= 2.0 { + for l in spot_outline::union_outline(pts, band.0) { + p.extend(egui::Shape::dashed_line(&l, Stroke::new(1.0, Color32::from_white_alpha(110)), 3.0, 3.0)); + } + } +} + +/// A Remove brush's `band` as its cursor shows it: the outer circle where a spot's outline will run. +pub(super) fn spot_band(band: (f32, f32)) -> (f32, f32) { + (band.0, band.1 + OUTLINE_GAP) +} + +/// The brush cursor: a solid circle at the outer edge of `band`, a faint one at its inner edge (where the blend is full). +pub(super) fn brush_circles(p: &egui::Painter, at: Pos2, band: (f32, f32)) { + for (rr, col) in [(band.1, Color32::WHITE), (band.0.max(1.0), Color32::from_white_alpha(140))] { + p.circle_stroke(at, rr, Stroke::new(2.0, Color32::from_black_alpha(90))); + p.circle_stroke(at, rr, Stroke::new(1.0, col)); + } +} + +/// A spot's outline in `light`, over a dark under-stroke so a thin line stays visible on light and dark areas alike. +fn draw_outline(p: &egui::Painter, lines: &[Vec], light: Stroke, dashed: bool) { + let dark = Stroke::new(light.width + 1.0, Color32::from_black_alpha(90)); + for stroke in [dark, light] { + for l in lines { + if dashed { + p.extend(egui::Shape::dashed_line(l, stroke, 6.0, 4.0)); + } else { + p.add(egui::Shape::line(l.clone(), stroke)); + } + } + } +} + /// Keyboard stand-ins for the Remove tool: each spot's target and source (an arrow press moves /// it a step, one undo step; Return selects the spot), and a placement point that the arrows move /// and Return turns into a new spot of the brush's size there (only while a brush is chosen, as diff --git a/crates/ui-egui/src/panels/edit.rs b/crates/ui-egui/src/panels/edit.rs index e1e90b4732..4e95c3e585 100644 --- a/crates/ui-egui/src/panels/edit.rs +++ b/crates/ui-egui/src/panels/edit.rs @@ -1,4 +1,4 @@ -//! The Edit panel: histogram, Auto/B&W, profile, and the Light / Color / Effects / Detail / Optics +//! The Edit panel: histogram, the camera, Auto/B&W, profile, and the Light / Color / Effects / Detail / Optics //! sections, built from the engine's control specs. use craft::ui::choice::Checkbox; @@ -39,7 +39,8 @@ pub(crate) use grading::{WheelGrab, WheelLock, WheelMods, wheel_pick}; pub(crate) use histogram::histogram; use histogram::soft_proofing; use lens_blur::lens_blur; -use mixer::{mixer, point_color}; +use mixer::mixer; +pub(crate) use mixer::{MIXER_ADJUST, MIXER_GROUPS, MIXER_TABS, drop_hidden_mixer_tool}; pub use sliders::{apply_slider_out, sub_title}; pub(crate) use sliders::{control, reload_preview_only}; use sliders::{hdr_row, header_buttons, profile_menu, quick_develop, reset_tip, section}; @@ -181,6 +182,22 @@ fn vignette_style( if interactive && app.session.active() == Some(owner) { picked.and_then(|index| styles.get(index).map(|(style, _, _)| *style)) } else { None } } +/// The camera photo `id` was taken with, maker and model ([`lightcraft_catalog::Meta::camera_name`]), on its own line +/// above the Edit header (widget `edit:camera`). A label, so screen readers read it; a long name is cut short with … +/// and shown whole on hover. The line keeps its height for a photo that names no camera, so the controls below stay +/// in place from one photo to the next. +fn camera_line(app: &LightcraftApp, ui: &mut egui::Ui, id: PhotoId, t: &Tokens) { + let font = t.font(12.5); + let height = ui.ctx().fonts_mut(|f| f.row_height(&font)); + egui::Frame::NONE.inner_margin(egui::Margin { left: 24, right: 22, top: 12, bottom: 0 }).show(ui, |ui| { + ui.set_min_size(vec2(ui.available_width(), height)); + if let Some(name) = app.session.catalog.photo(id).and_then(|p| p.meta.camera_name()) { + let r = ui.add(egui::Label::new(RichText::new(name).font(font).color(t.text_label)).truncate()); + register(ui, "edit:camera", r.rect); + } + }); +} + pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { light_controls::apply_pending(app, ui); color_controls::apply_pending(app, ui.ctx()); @@ -208,9 +225,10 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { if app.ui.soft_proof { soft_proofing(app, ui, id); } + camera_line(app, ui, id, &t); // header: Edit + Auto / B&W / HDR let mut reset_clicked = false; - let (hr, _) = ui.allocate_exact_size(vec2(ui.available_width(), 40.0), Sense::hover()); + let (hr, _) = ui.allocate_exact_size(vec2(ui.available_width(), 26.0), Sense::hover()); ui.painter().text(pos2(hr.left() + 24.0, hr.bottom() - 10.0), Align2::LEFT_CENTER, crate::i18n::tr("Edit"), t.semibold(15.0), t.text); egui::Frame::NONE.inner_margin(egui::Margin { left: 24, right: 22, top: 8, bottom: 14 }).show(ui, |ui| { let tip = reset_tip(&app.ui.settings.keymap, ui.ctx().os() == egui::os::OperatingSystem::Mac); @@ -373,15 +391,6 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { if open { mixer(app, ui, d); } - if !crate::is_bw(d) { - let open = app.ui.flyout_open("pointColor"); - if flyout_row(ui, "pointColor", crate::i18n::tr("Point Color"), Icon::Picker, open).clicked() { - app.ui.toggle_flyout("pointColor"); - } - if open { - point_color(app, ui, d); - } - } let open = app.ui.flyout_open("grading"); if flyout_row(ui, "grading", crate::i18n::tr("Color Grading"), Icon::Presets, open).clicked() { app.ui.toggle_flyout("grading"); diff --git a/crates/ui-egui/src/panels/edit/mixer.rs b/crates/ui-egui/src/panels/edit/mixer.rs index 85479a2790..4c09afbc8b 100644 --- a/crates/ui-egui/src/panels/edit/mixer.rs +++ b/crates/ui-egui/src/panels/edit/mixer.rs @@ -3,10 +3,49 @@ use craft::ui::contract::{Bind, Props as _, Show as _}; use super::curve::set_tat; use super::sliders::{control, sub_title}; -use super::{BAND_COLORS, Color32, DevelopSettings, Icon, LightcraftApp, Sense, Tokens, hex, json, paint, text_button, vec2}; +use super::{ + BAND_COLORS, Color32, DevelopSettings, Icon, LightcraftApp, Sense, Stroke, Tokens, apply_slider_out, controls, hex, json, paint, register, + text_button, vec2, +}; +use egui::{Align2, pos2}; // ------------------------------------------------------------------------------ colour mixer +/// The Color Mixer's tabs (Mixer | Point Color), the Mixer's Adjust choice (HSL | Color) and the +/// HSL groups (Hue | Saturation | Luminance | All), as (label, key). +pub(crate) const MIXER_TABS: [(&str, &str); 2] = [("Mixer", "mixer"), ("Point Color", "point")]; +pub(crate) const MIXER_ADJUST: [(&str, &str); 2] = [("HSL", "hsl"), ("Color", "color")]; +pub(crate) const MIXER_GROUPS: [(&str, &str); 4] = [("Hue", "hue"), ("Saturation", "sat"), ("Luminance", "lum"), ("All", "all")]; +/// The mixer bands' names, as the HSL sliders are labelled (parallel to `MIXER_BANDS`). +const BAND_NAMES: [&str; 8] = ["Red", "Orange", "Yellow", "Green", "Aqua", "Blue", "Purple", "Magenta"]; + +/// A Color Mixer targeted adjustment (`tat:hue|sat|lum`) whose button the mixer's layout no +/// longer shows is put down: a B&W photo shows Luminance's only, Point Color none, HSL only the chosen group's (all three in +/// All), Color mode all three. Dragging on the photo would otherwise change a hidden group. +pub(crate) fn drop_hidden_mixer_tool(app: &mut LightcraftApp) { + // a B&W photo's mixer is its B&W mix, with only the Luminance targeted adjustment + let bw = app.session.active().and_then(|id| app.session.develop_of(id)).is_some_and(|d| crate::is_bw(&d)); + // Point Color's picker lives on its own tab, which a B&W photo doesn't have + if app.ui.tool == "pointColor" { + if bw || app.ui.mixer_tab != "point" { + app.ui.tool.clear(); + } + return; + } + let Some(key) = app.ui.tool.strip_prefix("tat:") else { return }; + if !matches!(key, "hue" | "sat" | "lum") { + return; + } + let shown = if bw { + key == "lum" + } else { + app.ui.mixer_tab != "point" && (app.ui.mixer_adjust == "color" || app.ui.mixer_group == "all" || app.ui.mixer_group == key) + }; + if !shown { + app.ui.tool.clear(); + } +} + /// One UI-only band choice; the engine and the current frame's scalar snapshot remain unchanged. fn mixer_band_picker(ui: &mut egui::Ui, selected: usize, bw: bool) -> Option { use craft::behavior::{NavShape, Proposal}; @@ -79,7 +118,130 @@ fn mixer_band_picker(ui: &mut egui::Ui, selected: usize, bw: bool) -> Option.`) either way; a B&W photo shows its B&W mix. pub(super) fn mixer(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &DevelopSettings) { + // (the B&W mix keeps its own Luminance targeted adjustment; a picker it doesn't show is put down first) + if crate::is_bw(d) { + drop_hidden_mixer_tool(app); + mixer_by_color(app, ui, d); + return; + } + let pick = |ui: &mut egui::Ui, id: &str, items: &[(&str, &str)], current: &str| { + let at = items.iter().position(|(_, k)| *k == current).unwrap_or(0); + egui::Frame::NONE + .inner_margin(egui::Margin { left: 24, right: 22, top: 6, bottom: 2 }) + .show(ui, |ui| crate::widgets::segmented(ui, id, items, Some(at), items.len())) + .inner + .and_then(|i| items.get(i).map(|(_, k)| k.to_string())) + }; + if let Some(k) = pick(ui, "mixerTab", &MIXER_TABS, &app.ui.mixer_tab) { + app.ui.mixer_tab = k; + } + drop_hidden_mixer_tool(app); + if app.ui.mixer_tab == "point" { + point_color(app, ui, d); + return; + } + let t = Tokens::get(ui.ctx()); + egui::Frame::NONE.inner_margin(egui::Margin { left: 24, right: 22, top: 4, bottom: 0 }).show(ui, |ui| { + ui.label(egui::RichText::new(crate::i18n::tr("Adjust")).color(t.text_dim).size(11.5)); + }); + if let Some(k) = pick(ui, "mixerAdjust", &MIXER_ADJUST, &app.ui.mixer_adjust) { + app.ui.mixer_adjust = k; + drop_hidden_mixer_tool(app); + } + if app.ui.mixer_adjust == "color" { + mixer_by_color(app, ui, d); + return; + } + // HSL: Hue | Saturation | Luminance | All + egui::Frame::NONE.inner_margin(egui::Margin { left: 24, right: 22, top: 6, bottom: 2 }).show(ui, |ui| { + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 14.0; + for (label, key) in MIXER_GROUPS { + if group_tab(ui, &format!("mixerGroup-{key}"), crate::i18n::tr(label), app.ui.mixer_group == key).clicked() { + app.ui.mixer_group = key.to_string(); + drop_hidden_mixer_tool(app); + } + } + }); + }); + let groups: &[(&str, &str)] = match app.ui.mixer_group.as_str() { + "sat" => &MIXER_GROUPS[1..2], + "lum" => &MIXER_GROUPS[2..3], + "all" => &MIXER_GROUPS[..3], + _ => &MIXER_GROUPS[..1], + }; + let all = groups.len() > 1; + for (label, key) in groups { + // the group's targeted adjustment (and, in All, its heading) + egui::Frame::NONE.inner_margin(egui::Margin { left: 20, right: 22, top: if all { 8 } else { 2 }, bottom: 0 }).show(ui, |ui| { + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 6.0; + let tool = format!("tat:{key}"); + let active = app.ui.tool == tool; + let button = crate::widgets::icon_button( + ui, + &format!("tatMixer-{key}"), + Icon::Target, + vec2(24.0, 24.0), + active, + true, + "Targeted adjustment: drag up/down on the photo to adjust the colours there", + ); + // (named by its group for a screen reader: All shows three of them) + crate::widgets::screen_reader_name( + ui.ctx(), + button.id, + &format!("{} ({})", crate::i18n::tr("Targeted Adjustment"), crate::i18n::tr(label)), + ); + if button.clicked() { + set_tat(app, ui.ctx(), &tool, active); + } + if all { + let r = ui.label(egui::RichText::new(crate::i18n::tr(label)).color(t.text).strong().size(12.0)); + register(ui, format!("mixerHeading:{key}"), r.rect); + } + }); + }); + for (band, name) in lightcraft_develop::MIXER_BANDS.iter().zip(BAND_NAMES) { + let id = format!("mixer.{band}.{key}"); + let Some(spec) = controls::find(&id) else { continue }; + // labelled by the colour alone: the group says what it adjusts (a screen reader hears both) + let v = controls::get(d, &id).unwrap_or(spec.default); + // (both parts translated; the brackets read the same in every language the app has) + let spoken = format!("{} ({})", crate::i18n::tr(name), crate::i18n::tr(label)); + let owner = app.session.active(); + let out = ui.push_id(("mixer-photo", owner), |ui| crate::widgets::slider_named(ui, spec, v, true, Some(name), Some(&spoken))).inner; + apply_slider_out(app, spec, out, |app, v| app.run("develop.set", json!({"control": id, "value": v}))); + } + } +} + +/// A word tab (Hue, Saturation…): bright and underlined when it is the one shown. +fn group_tab(ui: &mut egui::Ui, id: &str, label: &str, active: bool) -> crate::widgets::HitAreaOutput { + let t = Tokens::get(ui.ctx()); + let font = t.semibold(11.5); + let galley = ui.painter().layout_no_wrap(label.to_string(), font.clone(), t.text); + let (_, r) = ui.allocate_space(vec2(galley.size().x, 20.0)); + let resp = crate::widgets::HitArea::new(label.to_owned(), ui.scope_id().with(("mixer-group", id))) + .widget(format!("button:{id}")) + .selected(active) + .show_at(ui, r); + let colour = if active || resp.hovered() { t.text } else { t.text_dim }; + ui.painter().text(pos2(r.left(), r.center().y), Align2::LEFT_CENTER, label, font, colour); + if active { + ui.painter().line_segment([pos2(r.left(), r.bottom() - 1.0), pos2(r.right(), r.bottom() - 1.0)], Stroke::new(1.5, t.text)); + } + resp.face_under_ring(); + resp +} + +/// The Mixer by colour (and a B&W photo's mix): a dot per colour, then that colour's sliders. +fn mixer_by_color(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &DevelopSettings) { let t = Tokens::get(ui.ctx()); let bands = lightcraft_develop::MIXER_BANDS; let sel = bands.iter().position(|b| *b == app.ui.mixer_mode).unwrap_or(0); diff --git a/crates/ui-egui/src/panels/edit/mixer_band_flow_tests.rs b/crates/ui-egui/src/panels/edit/mixer_band_flow_tests.rs index f30a2a611e..57dd82338e 100644 --- a/crates/ui-egui/src/panels/edit/mixer_band_flow_tests.rs +++ b/crates/ui-egui/src/panels/edit/mixer_band_flow_tests.rs @@ -94,6 +94,8 @@ impl Fixture { app.ui.open_sections = vec!["color".into()]; app.ui.open_flyouts = vec!["mixer".into()]; app.ui.mixer_mode = "red".into(); + // This suite exercises the Color-mode swatch palette; HSL is the app default. + app.ui.mixer_adjust = "color".into(); app.ui.right_width = width; app.run("develop.merge", json!({"settings":{"light":{"exposure":0.9}},"label":"Fixture redo"})).unwrap(); app.run("edit.undo", json!({})).unwrap(); @@ -830,13 +832,15 @@ fn stale_pointer_and_held_key_releases_do_not_replay_after_parent_transitions() #[test] fn neighbor_point_color_and_tat_actions_remain_distinct_from_band_choice() { let mut f = Fixture::normal(); - f.click("flyout:pointColor"); + f.click("button:mixerTab-point"); let document = f.document(); f.click("pointColor:1"); assert_eq!(f.app.ui.point_color, 1); f.click("pointColorVisualize"); assert!(f.app.ui.point_color_visualize); assert_eq!(f.document(), document); + f.click("button:mixerTab-mixer"); + assert_eq!(f.document(), document); f.choose(7); assert_eq!(f.app.ui.point_color, 1); assert!(f.app.ui.point_color_visualize); diff --git a/crates/ui-egui/src/panels/grid.rs b/crates/ui-egui/src/panels/grid.rs index faff115c57..3691cfdd80 100644 --- a/crates/ui-egui/src/panels/grid.rs +++ b/crates/ui-egui/src/panels/grid.rs @@ -330,7 +330,14 @@ fn show_inner(app: &mut LightcraftApp, ui: &mut egui::Ui) { } app.canvas_rect = Some(ui.max_rect()); if ids.is_empty() { - if !chips.is_empty() { + // an album on a loop is empty because of the loop, whatever filters are on + let loop_note = match app.session.source { + lightcraft_engine::LibrarySource::Album(id) => crate::i18n::album_loop_note(&app.session.catalog, id), + _ => None, + }; + if let Some((title, body)) = loop_note { + super::empty_message(ui, ui.max_rect(), &title, &body); + } else if !chips.is_empty() { let body = match total { Some(n) if n > 0 => { crate::i18n::tr_format!("{n} photos in {} are hidden by the filters above", crate::i18n::source_title(&app.session), n = n) @@ -1183,6 +1190,17 @@ pub fn drag_hint(ctx: &egui::Context, text: String) { ctx.data_mut(|d| d.insert_temp(egui::Id::unique("drag-photos-hint"), (frame, text))); } +/// What a drop target that refuses the dragged photos does: the label says so, the cursor shows +/// it, and a release there toasts `why` and ends the drag, changing nothing. +pub fn refuse_drop(app: &mut LightcraftApp, ctx: &egui::Context, hint: String, why: &str, released: bool) { + drag_hint(ctx, hint); + ctx.set_cursor_icon(egui::CursorIcon::NotAllowed); + if released { + app.toast(ctx, why); + app.ui.dragging_photos = None; + } +} + pub fn drag_feedback(app: &mut LightcraftApp, ctx: &egui::Context) { let Some(ids) = &app.ui.dragging_photos else { return }; let (released, down, pos) = ctx.input(|i| (i.pointer.primary_released(), i.pointer.primary_down(), i.pointer.latest_pos())); @@ -1193,7 +1211,10 @@ pub fn drag_feedback(app: &mut LightcraftApp, ctx: &egui::Context) { let Some(pos) = pos else { return }; let t = Tokens::get(ctx); let n = ids.len(); - ctx.set_cursor_icon(egui::CursorIcon::Grabbing); + // (a row that refuses them has set the not-allowed cursor this frame: it stays) + if ctx.output(|o| o.cursor_icon) != egui::CursorIcon::NotAllowed { + ctx.set_cursor_icon(egui::CursorIcon::Grabbing); + } // a drop target under the pointer says where they would go (only this frame's) let frame = ctx.cumulative_frame_nr(); let hint = ctx.data(|d| d.get_temp::<(u64, String)>(egui::Id::unique("drag-photos-hint"))).filter(|(f, _)| *f == frame).map(|(_, text)| text); diff --git a/crates/ui-egui/src/panels/keyword_list.rs b/crates/ui-egui/src/panels/keyword_list.rs index 781a9336e2..f27764c6ba 100644 --- a/crates/ui-egui/src/panels/keyword_list.rs +++ b/crates/ui-egui/src/panels/keyword_list.rs @@ -209,21 +209,28 @@ fn shown_under(ui: &egui::Ui, rect: Rect, pointer: Option) -> bool { crate::docking::drop_target(ui, rect, pointer) } +/// What the dragged keyword's label says this frame instead of its name (a row refusing it sets it). +const KEYWORD_HINT: &str = "drag-keyword-hint"; + /// A keyword being dragged, each frame (after the panels, which take the drop): its name follows /// the pointer, and the drag ends with the button's release wherever it is (the list may be gone -/// by then) or with Esc. +/// by then). Esc ends it earlier in the frame (`LightcraftApp::end_drags`). pub fn drag_feedback(app: &mut LightcraftApp, ctx: &egui::Context) { let Some(keyword) = app.ui.dragging_keyword.clone() else { return }; - let (released, down, at, esc) = - ctx.input(|i| (i.pointer.any_released(), i.pointer.any_down(), i.pointer.latest_pos(), i.key_pressed(egui::Key::Escape))); - if released || !down || esc { + let (released, down, at) = ctx.input(|i| (i.pointer.any_released(), i.pointer.any_down(), i.pointer.latest_pos())); + if released || !down { app.ui.dragging_keyword = None; return; } let Some(at) = at else { return }; let t = Tokens::get(ctx); - ctx.set_cursor_icon(egui::CursorIcon::Grabbing); - let name = keyword.rsplit('|').next().unwrap_or(&keyword).to_string(); + // (a row that refuses it has set the not-allowed cursor this frame: it stays) + if ctx.output(|o| o.cursor_icon) != egui::CursorIcon::NotAllowed { + ctx.set_cursor_icon(egui::CursorIcon::Grabbing); + } + let frame = ctx.cumulative_frame_nr(); + let hint = ctx.data(|d| d.get_temp::<(u64, String)>(egui::Id::unique(KEYWORD_HINT))).filter(|(f, _)| *f == frame).map(|(_, text)| text); + let name = hint.unwrap_or_else(|| drag_leaf(&keyword)); egui::Area::new(egui::Id::unique("drag-keyword")).order(egui::Order::Tooltip).interactable(false).fixed_pos(at + vec2(14.0, 10.0)).show( ctx, |ui| { @@ -258,13 +265,34 @@ fn drop_keyword(app: &mut LightcraftApp, ctx: &egui::Context, keyword: &str, par } } +/// The name a dragged keyword's label shows: its last level, on one line. +fn drag_leaf(keyword: &str) -> String { + spoken_path(keyword.rsplit('|').next().unwrap_or(keyword)) +} + +/// A keyword's path as it is read out: on one line, as its name is painted. +fn spoken_path(path: &str) -> String { + lightcraft_catalog::keywords::one_line(path).into_owned() +} + +/// A keyword's path as its row's hover text shows it: on one line, levels joined by ›. +fn hover_path(path: &str) -> String { + spoken_path(path).replace('|', " › ") +} + +/// The Create Keyword Tag dialog's "Put inside …" tick box: the parent keyword on one line, levels joined by ›. +pub(crate) fn put_inside_label(parent: &str) -> String { + crate::i18n::tr_format!("Put inside “{parent}”", parent = hover_path(parent)) +} + /// One keyword's row: the triangle, the tick box, the name, the count, and on hover the arrow. /// `can_fold`: the triangle opens and closes the level (not while a filter opens it). fn row(app: &mut LightcraftApp, ui: &mut egui::Ui, r: &Row, selection: &[PhotoId], ticks: &Ticks, can_fold: bool) { let t = Tokens::get(ui.ctx()); let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_H), Sense::hover()); let picked = app.ui.keyword_list_selected.as_deref().is_some_and(|k| same(k, &r.path)); - let resp = controls::show(ui, &format!("keywordRow:{}", r.path), rect, Face::Row { selected: picked }, r.path.clone(), true); + let visible_path = spoken_path(&r.path); + let resp = controls::show(ui, &format!("keywordRow:{}", r.path), rect, Face::Row { selected: picked }, visible_path.clone(), true); if measuring(ui) { return; } @@ -313,7 +341,7 @@ fn row(app: &mut LightcraftApp, ui: &mut egui::Ui, r: &Row, selection: &[PhotoId &format!("keywordCheck:{}", r.path), boxr.expand(3.0), Face::Check { state, inside: !inside.is_empty(), on }, - format!("{} {}", crate::i18n::tr("Keyword"), r.path), + format!("{} {}", crate::i18n::tr("Keyword"), visible_path), on, ); if state == Tick::No && !inside.is_empty() { @@ -365,7 +393,8 @@ fn row(app: &mut LightcraftApp, ui: &mut egui::Ui, r: &Row, selection: &[PhotoId let measure = |s: &str| ui.painter().layout_no_wrap(s.to_string(), font.clone(), t.text_label).size().x; let marks = if is_default { 10.0 } else { 0.0 } + if in_shortcut { 5.0 + measure("+") } else { 0.0 }; let room = (arrow.left() - 4.0 - (x + 34.0) - marks).max(0.0); - let name = if measure(&r.name) <= room { r.name.clone() } else { crate::widgets::elide_head(&r.name, room, measure) }; + let flat = lightcraft_catalog::keywords::one_line(&r.name); + let name = if measure(&flat) <= room { flat.to_string() } else { crate::widgets::elide_head(&flat, room, measure) }; let label = ui.painter().text(pos2(x + 34.0, cy), Align2::LEFT_CENTER, name, font.clone(), if picked { t.text } else { t.text_label }); // where new keywords go (Put New Keywords Inside This Keyword): a dot after the name let mut after = label.right(); @@ -390,7 +419,7 @@ fn row(app: &mut LightcraftApp, ui: &mut egui::Ui, r: &Row, selection: &[PhotoId ); register(ui, format!("keywordShortcut:{}", r.path), plus); } - let resp = resp.on_hover_text(r.path.replace('|', " › ")); + let resp = resp.on_hover_text(hover_path(&r.path)); if resp.clicked() { app.ui.keyword_list_selected = Some(r.path.clone()); } @@ -407,7 +436,7 @@ const INSIDE_NAMED: usize = 4; /// "Inside: Rome, Venice": the applied keywords inside a keyword, the first few by name. fn inside_said(inside: &[String]) -> Option { - let named = inside.iter().take(INSIDE_NAMED).map(String::as_str).collect::>().join(", "); + let named = inside.iter().take(INSIDE_NAMED).map(|name| spoken_path(name)).collect::>().join(", "); let more = inside.len().saturating_sub(INSIDE_NAMED); let names = if more > 0 { format!("{named} {}", crate::i18n::tr_format!("+{n} more", n = more)) } else { named }; (!inside.is_empty()).then(|| crate::i18n::tr_format!("Inside: {names}", names = names)) @@ -424,9 +453,16 @@ fn drop_target(app: &mut LightcraftApp, ui: &mut egui::Ui, rect: Rect, path: &st return; } let t = Tokens::get(ui.ctx()); - let outline = |ui: &egui::Ui| ui.painter().rect_stroke(rect.shrink2(vec2(16.0, 1.0)), 4.0, Stroke::new(1.5, t.accent), StrokeKind::Inside); + let outline = |ui: &egui::Ui| { + ui.painter().rect_stroke(rect.shrink2(vec2(16.0, 1.0)), 4.0, Stroke::new(1.5, t.accent), StrokeKind::Inside); + }; if let Some(k) = app.ui.dragging_keyword.clone() { if lightcraft_catalog::keywords::is_under(path, &k) { + // never inside itself or what is inside it: the not-allowed cursor, and the dragged + // label says why; a release does nothing + ui.ctx().set_cursor_icon(egui::CursorIcon::NotAllowed); + let frame = ui.ctx().cumulative_frame_nr(); + ui.data_mut(|d| d.insert_temp(egui::Id::unique(KEYWORD_HINT), (frame, crate::i18n::tr("Can't go inside itself").to_string()))); return; } outline(ui); @@ -434,36 +470,50 @@ fn drop_target(app: &mut LightcraftApp, ui: &mut egui::Ui, rect: Rect, path: &st drop_keyword(app, ui.ctx(), &k, Some(path)); } } else if let Some(ids) = app.ui.dragging_photos.clone() { - outline(ui); + drop_photos_on_keyword(app, ui, &ids, path, &outline); + } +} + +/// Photos dragged over the keyword row `path`: only the photos that don't have it get it. `outline` +/// marks the row when a release would give it to some. +fn drop_photos_on_keyword(app: &mut LightcraftApp, ui: &mut egui::Ui, ids: &[u64], path: &str, outline: &dyn Fn(&egui::Ui)) { + // (photos drop on the primary's release only, like the album and folder rows) + let released = ui.input(|i| i.pointer.primary_released()); + let lacking = |id: &u64| { + app.session.catalog.photo(PhotoId(*id)).is_some_and(|p| !p.meta.keywords.iter().any(|k| same(&lightcraft_catalog::keywords::clean(k), path))) + }; + let n = ids.iter().filter(|id| lacking(id)).count(); + if n == 0 { + super::grid::drag_hint(ui.ctx(), crate::i18n::tr("Already on these photos").to_string()); if released { - // only the photos that didn't have it get it - let lacking = |id: &u64| { - app.session - .catalog - .photo(PhotoId(*id)) - .is_some_and(|p| !p.meta.keywords.iter().any(|k| same(&lightcraft_catalog::keywords::clean(k), path))) - }; - let n = ids.iter().filter(|id| lacking(id)).count(); app.ui.dragging_photos = None; - match app.run("photo.setMeta", json!({"ids": ids, "addKeywords": [path]})) { - Ok(_) => app.toast( - ui.ctx(), - crate::i18n::tr_format!( - "Added “{keyword}” to {n} photo{}", - if n == 1 { "" } else { "s" }, - keyword = path.replace('|', " › "), - n = n - ), - ), - Err(e) => app.toast(ui.ctx(), e), - } } + return; + } + let keyword = hover_path(path); + super::grid::drag_hint( + ui.ctx(), + crate::i18n::tr_format!("Add “{keyword}” to {n} photo{}", if n == 1 { "" } else { "s" }, keyword = keyword, n = n), + ); + outline(ui); + if released { + app.ui.dragging_photos = None; + give_keyword(app, ui.ctx(), ids, path, n); + } +} + +/// Gives the keyword `path` to the dragged photos and toasts how many (`n`) lacked it. +fn give_keyword(app: &mut LightcraftApp, ctx: &egui::Context, ids: &[u64], path: &str, n: usize) { + let keyword = hover_path(path); + match app.run("photo.setMeta", json!({"ids": ids, "addKeywords": [path]})) { + Ok(_) => app.toast(ctx, crate::i18n::tr_format!("Added “{keyword}” to {n} photo{}", if n == 1 { "" } else { "s" }, keyword = keyword, n = n)), + Err(e) => app.toast(ctx, e), } } /// A keyword's context menu. fn menu(app: &mut LightcraftApp, ui: &mut egui::Ui, path: &str, selection: &[PhotoId]) { - let name = path.replace('|', " › "); + let name = hover_path(path); let item = |ui: &mut egui::Ui, id: &str, label: &str, enabled: bool| { let shown = MenuItem::new(label.to_owned()).id_salt(("keyword-menu", path, id)).enabled(enabled).show(ui); if !measuring(ui) { @@ -729,6 +779,36 @@ mod tests { use super::*; + /// A path holding line breaks (CR, LF, U+2028, U+2029) is read out and hovered on one line, as its + /// name is painted (CodeRabbit on #2922). + #[test] + fn a_keyword_path_with_line_breaks_is_read_and_hovered_on_one_line() { + let path = "Wedding|Bride\r\nGroom\u{2028}Guests\u{2029}Cake"; + let breaks = |s: &str| s.contains(['\r', '\n', '\u{2028}', '\u{2029}']); + assert!(!breaks(&spoken_path(path)), "{:?}", spoken_path(path)); + assert!(!breaks(&hover_path(path)), "{:?}", hover_path(path)); + assert!(hover_path(path).starts_with("Wedding › Bride"), "{:?}", hover_path(path)); + } + + /// The dragged keyword's label and the tick box's "Inside: …" name keywords on one line too (CodeRabbit on + /// #2922). + #[test] + fn a_dragged_keyword_and_the_keywords_inside_one_are_named_on_one_line() { + let breaks = |s: &str| s.contains(['\r', '\n', '\u{2028}', '\u{2029}']); + assert_eq!(drag_leaf("Wedding|Bride\nGroom"), "Bride Groom"); + let inside = inside_said(&["Rome\r\nCentre".to_string(), "Venice\u{2029}Lido".to_string()]).unwrap(); + assert!(!breaks(&inside), "{inside:?}"); + assert!(inside.contains("Rome Centre") && inside.contains("Venice Lido"), "{inside:?}"); + } + + /// The Create Keyword Tag dialog names a parent keyword holding line breaks on one line (CodeRabbit on #2922). + #[test] + fn the_put_inside_box_names_its_parent_on_one_line() { + let label = put_inside_label("Wedding|Bride\r\nGroom\u{2028}Guests"); + assert!(!label.contains(['\r', '\n', '\u{2028}', '\u{2029}']), "{label:?}"); + assert!(label.contains("Wedding › Bride Groom"), "{label:?}"); + } + fn library(keywords: &[&[&str]]) -> (Catalog, Vec) { let mut c = Catalog::new(); let mut ids = Vec::new(); diff --git a/crates/ui-egui/src/panels/left.rs b/crates/ui-egui/src/panels/left.rs index 9d7dcde09d..73b814603a 100644 --- a/crates/ui-egui/src/panels/left.rs +++ b/crates/ui-egui/src/panels/left.rs @@ -19,8 +19,10 @@ mod local; mod rows; mod sections; +use albums::albums_rows; +pub(crate) use albums::drag_auto_scroll; +pub(crate) use albums::forget_hover; pub use albums::{album_drag_feedback, auto_scroll_speed}; -use albums::{albums_rows, drag_auto_scroll}; pub(crate) use dates::browse_all_photos; use dates::date_rows; pub(crate) use folders::{created_text, folder_row_of, move_photos, moved_text}; diff --git a/crates/ui-egui/src/panels/left/albums.rs b/crates/ui-egui/src/panels/left/albums.rs index a8d9c64861..fcca8d23ca 100644 --- a/crates/ui-egui/src/panels/left/albums.rs +++ b/crates/ui-egui/src/panels/left/albums.rs @@ -1,7 +1,8 @@ use std::collections::HashMap; use super::rows::{ - AlbumDrag, MAX_DEPTH, MenuAt, Said, SideEvent, SideRow, SideSpec, entry, host_menu, rule, set_tree_open, set_tree_open_with, side_list, submenu, tree_inside, tree_open, + AlbumDrag, MAX_DEPTH, MenuAt, Said, SideEvent, SideRow, SideSpec, entry, host_menu, rule, set_tree_open, set_tree_open_with, side_list, submenu, + tree_inside, tree_open, }; use super::{Album, AlbumId, Align2, LibrarySource, LightcraftApp, Rect, Tokens, json, pos2, register, vec2}; @@ -68,7 +69,23 @@ pub(super) fn albums_rows(app: &mut LightcraftApp, ui: &mut egui::Ui, reveal: Op { set_tree_open(ui, open_id, true); } - if !m.album.folder && !m.album.is_smart() { + if m.album.folder { + refuse_photos( + app, + ui, + row.rect, + crate::i18n::tr("Can't add to an album folder"), + crate::i18n::tr("An album folder holds albums, not photos: drop on an album inside it"), + ); + } else if m.album.is_smart() { + refuse_photos( + app, + ui, + row.rect, + crate::i18n::tr("Can't add to a smart album"), + crate::i18n::tr("A smart album's rules choose its photos: change them with Edit Smart Album…"), + ); + } else { drop_target(app, ui, row.rect, &m.album); } } @@ -144,6 +161,9 @@ fn flatten( let label = if target == Some(a.id) { format!("{} +", a.name) } else { a.name.clone() }; // a smart album whose rules no longer check (an album they test was deleted) says so let problems = app.caches.smart_album_problems(&app.session.catalog).get(&a.id).cloned().unwrap_or_default(); + // an album on a loop holds nothing: its tooltip says so, and through which album (the ⚠ is + // there already: a loop is one of the problems it reports) + let loop_note = crate::i18n::album_loop_note(&app.session.catalog, a.id); let label = if problems.is_empty() { label } else { format!("⚠ {label}") }; let id = format!("album:{}", a.id.0); let mut row = SideRow::new(id.clone(), icon, label).count(n).depth(depth); @@ -158,6 +178,9 @@ fn flatten( tip.push_str(&crate::i18n::problem_line(p)); } } + if let Some((title, body)) = &loop_note { + tip.push_str(&format!("\n\n{title}\n{body}")); + } row = row.tip(tip); } rows.push(row); @@ -376,7 +399,7 @@ pub fn auto_scroll_speed(y: f32, top: f32, bottom: f32) -> f32 { /// While an album, or photos from the grid, are dragged over the sidebar: scrolls it when the /// pointer is near its top or bottom edge, so rows beyond the visible part can be reached. Call /// inside the scroll area. -pub(super) fn drag_auto_scroll(app: &LightcraftApp, ui: &egui::Ui) { +pub(crate) fn drag_auto_scroll(app: &LightcraftApp, ui: &egui::Ui) { if app.ui.dragging_album.is_none() && app.ui.dragging_photos.is_none() && app.ui.dragging_section.is_none() { return; } @@ -426,7 +449,7 @@ fn finish_drop(app: &mut LightcraftApp, ui: &egui::Ui, dragged: AlbumId, result: } /// Forgets how long the pointer rested on each folder (a new drag starts counting again). -fn forget_hover(app: &LightcraftApp, ctx: &egui::Context) { +pub(crate) fn forget_hover(app: &LightcraftApp, ctx: &egui::Context) { let ids: Vec = app.session.catalog.albums().filter(|a| a.folder).map(|a| a.id.0).collect(); ctx.data_mut(|d| { for id in ids { @@ -577,9 +600,8 @@ pub(super) fn top_level_drop_target(app: &mut LightcraftApp, ui: &mut egui::Ui, /// button is up (the drop targets act on the release frame, before this runs). pub fn album_drag_feedback(app: &mut LightcraftApp, ctx: &egui::Context) { let Some(id) = app.ui.dragging_album else { return }; - let (released, down, pos, esc) = - ctx.input(|i| (i.pointer.primary_released(), i.pointer.primary_down(), i.pointer.latest_pos(), i.key_pressed(egui::Key::Escape))); - if released || !down || esc { + let (released, down, pos) = ctx.input(|i| (i.pointer.primary_released(), i.pointer.primary_down(), i.pointer.latest_pos())); + if released || !down { app.ui.dragging_album = None; forget_hover(app, ctx); return; @@ -601,8 +623,45 @@ pub fn album_drag_feedback(app: &mut LightcraftApp, ctx: &egui::Context) { ); } -/// An album row while photos are dragged from the grid: highlighted under the pointer; a -/// release there adds them. +/// A row that can't hold photos, while photos are dragged from the grid: the not-allowed cursor +/// and a label saying so (`hint`); a release there says why (`why`) and changes nothing. +pub(super) fn refuse_photos(app: &mut LightcraftApp, ui: &mut egui::Ui, rect: Rect, hint: &str, why: &str) { + if app.ui.dragging_photos.is_none() || !pointer_over_row(ui, rect) { + return; + } + let released = ui.input(|i| i.pointer.primary_released()); + crate::panels::grid::refuse_drop(app, ui.ctx(), hint.to_string(), why, released); +} + +/// How many of the dragged photos are library photos, and how many of those the album holds already. +fn dragged_and_there(app: &LightcraftApp, a: &Album, ids: &[u64]) -> (usize, usize) { + let library = ids.iter().filter(|id| app.session.catalog.photo(lightcraft_catalog::PhotoId(**id)).is_some_and(|p| !p.local)).count(); + let dragged: std::collections::HashSet = ids.iter().copied().collect(); + (library, a.photos.iter().filter(|p| dragged.contains(&p.0)).count().min(library)) +} + +/// A drop on album `a` that would add nothing: `local` Local photos in the drag aren't in the album +/// either, so a release says why they stay out; else the library photos are all there already, and a +/// release only ends the drag. +fn drop_adds_nothing(app: &mut LightcraftApp, ui: &egui::Ui, a: &Album, local: usize, released: bool) { + if local > 0 { + let why = crate::i18n::tr_format!( + "{n} Local photo{} skipped: albums hold library photos (Add to My Photos first)", + if local == 1 { "" } else { "s" }, + n = local + ); + crate::panels::grid::refuse_drop(app, ui.ctx(), crate::panels::grid::albums_hint(), &why, released); + return; + } + crate::panels::grid::drag_hint(ui.ctx(), crate::i18n::tr_format!("Already in “{}”", a.name)); + if released { + app.ui.dragging_photos = None; + } +} + +/// An album row while photos are dragged from the grid: highlighted under the pointer, the dragged +/// label saying how many photos a release there adds (the ones the album doesn't hold yet). When it +/// holds them all it says so, and a release does nothing. fn drop_target(app: &mut LightcraftApp, ui: &mut egui::Ui, rect: Rect, a: &Album) { let Some(ids) = app.ui.dragging_photos.clone() else { return }; // only where the row can be seen: not scrolled out of the sidebar or beneath the pinned header @@ -615,37 +674,48 @@ fn drop_target(app: &mut LightcraftApp, ui: &mut egui::Ui, rect: Rect, a: &Album // light up, and a release says why let photos: Vec = ids.iter().map(|id| lightcraft_catalog::PhotoId(*id)).collect(); if crate::panels::grid::local_only(app, &photos) { - ui.ctx().set_cursor_icon(egui::CursorIcon::NotAllowed); - if released { - app.toast(ui.ctx(), crate::panels::grid::albums_hint()); - app.ui.dragging_photos = None; - } + crate::panels::grid::refuse_drop(app, ui.ctx(), crate::panels::grid::albums_hint(), &crate::panels::grid::albums_hint(), released); return; } + // of the library photos dragged, the album holds some already + let (library, there) = dragged_and_there(app, a, &ids); + let fresh = library.saturating_sub(there); + if fresh == 0 { + drop_adds_nothing(app, ui, a, ids.len() - library, released); + return; + } + crate::panels::grid::drag_hint( + ui.ctx(), + crate::i18n::tr_format!("Add {n} photo{} to “{}”", if fresh == 1 { "" } else { "s" }, a.name, n = fresh), + ); let t = Tokens::get(ui.ctx()); ui.painter().rect_stroke(rect.shrink2(vec2(8.0, 1.0)), 4.0, egui::Stroke::new(1.5, t.accent), egui::StrokeKind::Inside); if released { - drop_photos_on_album(app, ui, a, ids); + drop_photos_on_album(app, ui, a, ids, there); app.ui.dragging_photos = None; } } /// Adds the dragged photos to the album and toasts how many went in (and how many Local ones were skipped). -fn drop_photos_on_album(app: &mut LightcraftApp, ui: &egui::Ui, a: &Album, ids: Vec) { +fn drop_photos_on_album(app: &mut LightcraftApp, ui: &egui::Ui, a: &Album, ids: Vec, there: usize) { match app.run("album.addPhotos", json!({"id": a.id.0, "ids": ids})) { Ok(r) => { let name = crate::destination::album(&app.session.catalog, a); - app.toast(ui.ctx(), added_message(&name, &r)); + app.toast(ui.ctx(), added_message(&name, &r, there)); } Err(e) => app.toast(ui.ctx(), e), } } -/// "Added N photos to “album”", plus a note when Local photos were skipped. -fn added_message(name: &str, r: &serde_json::Value) -> String { +/// "Added N photos to “album”", plus a note when some were there already and when Local photos were skipped. +fn added_message(name: &str, r: &serde_json::Value, there: usize) -> String { let n = r.get("added").and_then(serde_json::Value::as_u64).unwrap_or(0); let skipped = r.get("skipped").and_then(serde_json::Value::as_u64).unwrap_or(0); let mut msg = crate::i18n::tr_format!("Added {n} photo{} to “{}”", if n == 1 { "" } else { "s" }, name, n = n); + if there > 0 { + msg.push_str(" · "); + msg.push_str(&crate::i18n::tr_format!("{n} already there", n = there)); + } if skipped > 0 { msg.push_str(" · "); msg.push_str(&skipped_note(skipped)); diff --git a/crates/ui-egui/src/panels/left/folders.rs b/crates/ui-egui/src/panels/left/folders.rs index 45ca0ca0ac..cffbd0ff8e 100644 --- a/crates/ui-egui/src/panels/left/folders.rs +++ b/crates/ui-egui/src/panels/left/folders.rs @@ -158,6 +158,26 @@ pub(crate) fn folder_row_of<'a>(tree: &'a [FolderNode], dir: &str) -> Option<&'a /// can be reached. const SPRING_OPEN_SECONDS: f64 = 0.7; +/// Whether the photo's file is directly in the folder `folder`. +fn is_in_folder(p: &lightcraft_catalog::Photo, folder: &str) -> bool { + match &p.source { + lightcraft_catalog::Source::File { path } => std::path::Path::new(path).parent().is_some_and(|d| same_folder(&d.to_string_lossy(), folder)), + _ => false, + } +} + +/// How many files a drop of `photos` on `folder` moves (`photo.moveToFolder`): the photos already +/// there stay, and virtual copies of one file move it once. +fn files_moved(photos: &[&std::sync::Arc], folder: &str) -> usize { + let mut paths = std::collections::HashSet::new(); + for p in photos.iter().filter(|p| !is_in_folder(p, folder)) { + if let lightcraft_catalog::Source::File { path } = &p.source { + paths.insert(path.as_str()); + } + } + paths.len() +} + /// A Folders row while photos are dragged from the grid: a release moves their files there on /// disk (`photo.moveToFolder`, one undo step). The row lights up and the dragged label says where /// they will go, as the same gesture onto an album only adds them to it. Held over a closed row, @@ -177,30 +197,25 @@ fn folder_drop_target(app: &mut LightcraftApp, ui: &mut egui::Ui, rect: Rect, n: Some(crate::i18n::tr("This row covers more than one disk: drop on a folder inside it")) } else if photos.iter().any(|p| p.local) { Some(crate::i18n::tr("Local photos aren't in the library yet: Add to My Photos first, then move them")) + } else if photos.iter().any(|p| !matches!(p.source, lightcraft_catalog::Source::File { .. })) { + // `photo.moveToFolder` refuses a photo with no file + Some(crate::i18n::tr("Demo photos have no file on disk, so they can't be moved")) } else { None }; - let here = |p: &lightcraft_catalog::Photo| match &p.source { - lightcraft_catalog::Source::File { path } => std::path::Path::new(path).parent().is_some_and(|d| same_folder(&d.to_string_lossy(), &n.path)), - _ => false, - }; - let all_here = !photos.is_empty() && photos.iter().all(|p| here(p)); - let count = photos.len(); + let count = files_moved(&photos, &n.path); + let all_here = !photos.is_empty() && photos.iter().all(|p| is_in_folder(p, &n.path)); let released = ui.input(|i| i.pointer.primary_released()); - let hint = match (&refused, all_here) { - (Some(_), _) => crate::i18n::tr("Can't be moved here").to_string(), - (None, true) => crate::i18n::tr_format!("Already in “{}”", name), - (None, false) => crate::i18n::tr_format!("Move {n} photo{} to “{}”", if count == 1 { "" } else { "s" }, name, n = count), - }; - crate::panels::grid::drag_hint(ui.ctx(), hint); if let Some(why) = refused { - ui.ctx().set_cursor_icon(egui::CursorIcon::NotAllowed); - if released { - app.toast(ui.ctx(), why); - app.ui.dragging_photos = None; - } + crate::panels::grid::refuse_drop(app, ui.ctx(), crate::i18n::tr("Can't be moved here").to_string(), why, released); return; } + let hint = if all_here { + crate::i18n::tr_format!("Already in “{}”", name) + } else { + crate::i18n::tr_format!("Move {n} file{} to “{}”", if count == 1 { "" } else { "s" }, name, n = count) + }; + crate::panels::grid::drag_hint(ui.ctx(), hint); if all_here { if released { app.ui.dragging_photos = None; @@ -215,7 +230,7 @@ fn folder_drop_target(app: &mut LightcraftApp, ui: &mut egui::Ui, rect: Rect, n: // said not to; the menu's Move Selected Photos Here is asked for by name and goes at once if app.ui.settings.ask_before_move { let library = app.session.library_generation(); - app.ui.dialog = Some(crate::state::Dialog::MovePhotos { ids, folder: n.path.clone(), name, dont_ask: false, library }); + app.ui.dialog = Some(crate::state::Dialog::MovePhotos { ids, folder: n.path.clone(), name, files: count, dont_ask: false, library }); } else { move_photos_here(app, ui.ctx(), Some(&ids), &n.path, &name); } @@ -271,7 +286,7 @@ pub(crate) fn moved_text(n: u64, name: &str) -> String { if n == 0 { crate::i18n::tr_format!("Already in “{}”", name) } else { - crate::i18n::tr_format!("Moved {n} photo{} to “{}”. Edit → Undo moves them back.", if n == 1 { "" } else { "s" }, name, n = n) + crate::i18n::tr_format!("Moved {n} file{} to “{}”. Edit → Undo moves them back.", if n == 1 { "" } else { "s" }, name, n = n) } } diff --git a/crates/ui-egui/src/panels/left/keywords.rs b/crates/ui-egui/src/panels/left/keywords.rs index f19aec6e3c..d4931f63ff 100644 --- a/crates/ui-egui/src/panels/left/keywords.rs +++ b/crates/ui-egui/src/panels/left/keywords.rs @@ -1,7 +1,10 @@ use std::collections::HashMap; +use super::albums::refuse_photos; use super::dates::browse_all_photos; -use super::rows::{MAX_DEPTH, MenuAt, Said, SideEvent, SideRow, SideSpec, entry, host_menu, rule, set_tree_open_with, side_list, tree_inside, tree_open}; +use super::rows::{ + MAX_DEPTH, MenuAt, Said, SideEvent, SideRow, SideSpec, entry, host_menu, rule, set_tree_open_with, side_list, tree_inside, tree_open, +}; use super::{KeywordNode, LightcraftApp, json}; /// The widget id of a keyword's row: `keyword:`. @@ -23,7 +26,7 @@ fn flatten(ui: &egui::Ui, nodes: &[KeywordNode], depth: usize, rows: &mut Vec request = Some((key.clone(), MenuAt::Point(*at))), } } + for row in &out.shown { + refuse_photos( + app, + ui, + row.rect, + crate::i18n::tr("Add keywords in the Keyword List"), + crate::i18n::tr("Give photos a keyword in the Keyword List (Window → Keywords, K): drop them on it there"), + ); + } host_menu(ui, "keywords", crate::i18n::tr("Keyword"), out.response.as_ref(), request, |ui, key| { let Some(path) = paths.get(key) else { return }; keyword_menu(app, ui, path); @@ -98,3 +110,23 @@ fn keyword_menu(app: &mut LightcraftApp, ui: &mut egui::Ui, path: &str) { let _ = app.run("keyword.delete", json!({"keyword": path})); } } + +/// A keyword row's hover text, on one line like the row's name (a path holding line breaks must not +/// spill into a tall tooltip). +fn keyword_tip(path: &str, has_children: bool) -> String { + let path = lightcraft_catalog::keywords::one_line(path); + if has_children { format!("{path} (includes the keywords below it)") } else { path.into_owned() } +} + +#[cfg(test)] +mod tests { + /// A sidebar keyword's hover text is on one line, as its name is painted (CodeRabbit on #2922). + #[test] + fn a_keyword_path_with_line_breaks_is_hovered_on_one_line() { + let path = "Wedding|Bride\r\nGroom\u{2028}Guests\u{2029}Cake"; + for children in [false, true] { + let tip = super::keyword_tip(path, children); + assert!(!tip.contains(['\r', '\n', '\u{2028}', '\u{2029}']), "{tip:?}"); + } + } +} diff --git a/crates/ui-egui/src/panels/left/local.rs b/crates/ui-egui/src/panels/left/local.rs index b8ce85d475..a229542f5a 100644 --- a/crates/ui-egui/src/panels/left/local.rs +++ b/crates/ui-egui/src/panels/left/local.rs @@ -468,22 +468,30 @@ pub(crate) fn fs_cached(ui: &egui::Ui, kind: &'static use std::sync::atomic::Ordering; let running = fs_running_counter(ui.ctx()); running.fetch_add(1, Ordering::AcqRel); - let (out, path, repaint, done) = (cell.clone(), path.to_string(), ui.ctx().clone(), running.clone()); + // (settled when the work ends however it ends: a listing that panics must not stay running, nor keep + // the count up, which `Headless::busy` waits on) + struct Settle { + cell: Cell, + count: std::sync::Arc, + repaint: egui::Context, + } + impl Drop for Settle { + fn drop(&mut self) { + self.cell.lock().unwrap_or_else(std::sync::PoisonError::into_inner).running = false; + // after the answer is stored: a frame that sees the count drop also sees the answer + self.count.fetch_sub(1, std::sync::atomic::Ordering::AcqRel); + self.repaint.request_repaint(); + } + } + let (path, settle) = (path.to_string(), Settle { cell: cell.clone(), count: running.clone(), repaint: ui.ctx().clone() }); let work = move || { let v = f(&path); - let mut e = out.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - e.value = Some(v); - e.running = false; - drop(e); - // after the answer is stored: a frame that sees the count drop also sees the answer - done.fetch_sub(1, Ordering::AcqRel); - repaint.request_repaint(); + settle.cell.lock().unwrap_or_else(std::sync::PoisonError::into_inner).value = Some(v); + drop(settle); }; #[cfg(not(target_arch = "wasm32"))] - if std::thread::Builder::new().name("lc-fs-list".into()).spawn(work).is_err() { - cell.lock().unwrap_or_else(std::sync::PoisonError::into_inner).running = false; - running.fetch_sub(1, Ordering::AcqRel); - } + // (no thread to be had: the closure is dropped unrun, which settles it) + let _ = std::thread::Builder::new().name("lc-fs-list".into()).spawn(work); #[cfg(target_arch = "wasm32")] work(); } diff --git a/crates/ui-egui/src/panels/left/rows.rs b/crates/ui-egui/src/panels/left/rows.rs index a13b743867..71af16d4b6 100644 --- a/crates/ui-egui/src/panels/left/rows.rs +++ b/crates/ui-egui/src/panels/left/rows.rs @@ -293,7 +293,7 @@ impl SideRow { SideRow { key: id.clone(), id, - label: label.into(), + label: lightcraft_catalog::keywords::one_line(&label.into()).into_owned(), spoken: None, icon: Some(icon), count: None, diff --git a/crates/ui-egui/src/panels/left/sections.rs b/crates/ui-egui/src/panels/left/sections.rs index 792306bfa6..984a2aa177 100644 --- a/crates/ui-egui/src/panels/left/sections.rs +++ b/crates/ui-egui/src/panels/left/sections.rs @@ -131,6 +131,9 @@ pub(crate) fn section_drop_before(placed: &[PlacedSection], y: f32) -> Option(ctx), craft::ui::runtime::drag::active::(ctx)); @@ -175,13 +178,6 @@ pub(super) fn adopt_drags(app: &mut LightcraftApp, ui: &egui::Ui) { pub(super) fn section_drag(app: &mut LightcraftApp, ui: &mut egui::Ui, placed: &[PlacedSection]) { let Some(dragged) = app.ui.dragging_section else { return }; let (released, pos) = ui.input(|i| (i.pointer.primary_released(), i.pointer.latest_pos())); - let esc = ui.input(|i| i.key_pressed(egui::Key::Escape)); - if esc { - // the drag's Esc, not also a dialog's or a view's - crate::widgets::take_escape(ui.ctx()); - app.ui.dragging_section = None; - return; - } let view = ui.clip_rect(); let Some(pos) = pos.filter(|p| view.contains(*p)) else { if released { @@ -228,7 +224,7 @@ pub fn section_drag_feedback(app: &mut LightcraftApp, ctx: &egui::Context) { /// tree rows have theirs), then the bold title; a click folds or unfolds the section (kept in the /// UI state, so it survives restarts), and what the section adds to its header (its button, see /// `header_button`) sits at the visible edge. A folded section says how many rows it holds (`rows`, -/// with View ▸ Show Photo Counts). `pinned`: this is the copy kept at the top of the sidebar (see +/// with Window ▸ Show Photo Counts). `pinned`: this is the copy kept at the top of the sidebar (see /// `pinned_header`). Dragged by its header, a section moves among the others. fn section_header(app: &mut LightcraftApp, ui: &mut egui::Ui, section: SidebarSection, r: Rect, rows: usize, pinned: bool) -> HeaderOutcome { let id = section.id(); @@ -455,7 +451,7 @@ pub(super) fn sidebar_title(app: &mut LightcraftApp, ui: &mut egui::Ui) { const TITLE_HEIGHT: f32 = 44.0; /// How many library photos have no file (Local browse records are not checked; see -/// `cmd::missing::checked_path`). Checking stats every file, which on a network share takes +/// `Photo::library_file`). Checking stats every file, which on a network share takes /// seconds, so it runs on a worker thread: the count shown is the last finished one, refreshed /// at most every 5 s, and at once (after the running check) when the catalog changed. The first /// count and a recount after a catalog change are pending sidebar work diff --git a/crates/ui-egui/src/panels/library_problem.rs b/crates/ui-egui/src/panels/library_problem.rs index b18ed1459a..834bdb3c9a 100644 --- a/crates/ui-egui/src/panels/library_problem.rs +++ b/crates/ui-egui/src/panels/library_problem.rs @@ -1167,9 +1167,9 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context, blocked: bool) { ui.label(RichText::new(crate::i18n::tr("LightCraft couldn't find where to keep your library.")).color(t.text)); } else { ui.label(RichText::new(crate::i18n::tr("LightCraft couldn't open the library at")).color(t.text_label)); - ui.label(RichText::new(&problem.path).font(t.semibold(12.5)).color(t.text)); + ui.add(egui::Label::new(RichText::new(&problem.path).font(t.semibold(12.5)).color(t.text)).selectable(true)); } - ui.add(egui::Label::new(RichText::new(&problem.error).color(t.caution)).wrap()); + ui.add(egui::Label::new(RichText::new(&problem.error).color(t.caution)).wrap().selectable(true)); ui.label(RichText::new(EXPLANATION).color(t.text_dim)); }, |ui| { @@ -1281,7 +1281,7 @@ fn show_chooser(app: &mut LightcraftApp, ctx: &egui::Context, problem: &LibraryP } }); if !problem.error.is_empty() { - ui.add(egui::Label::new(RichText::new(&problem.error).color(t.caution)).wrap()); + ui.add(egui::Label::new(RichText::new(&problem.error).color(t.caution)).wrap().selectable(true)); } ui.horizontal(|ui| { remove |= action_button(ui, CHOOSER_WINDOW_ID, "libraryForget", "Remove from List", selected.is_some()); diff --git a/crates/ui-egui/src/panels/masking.rs b/crates/ui-egui/src/panels/masking.rs index ebbc6528bc..7f0eb8ca91 100644 --- a/crates/ui-egui/src/panels/masking.rs +++ b/crates/ui-egui/src/panels/masking.rs @@ -200,9 +200,12 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { ui.horizontal(|ui| { ui.add(egui::Label::new(egui::RichText::new(crate::i18n::tr("Masks")).font(t.semibold(13.0)).color(t.text_label)).selectable(false)); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + // lit while the overlay is on to stay; a click does what O does let on = app.ui.mask_overlay; - if icon_button(ui, "maskOverlay", Icon::Eye, vec2(24.0, 24.0), on, true, "Show overlay (O)").clicked() { - app.ui.mask_overlay = !on; + if icon_button(ui, "maskOverlay", Icon::Eye, vec2(24.0, 24.0), on, true, "Show overlay (O)").clicked() + && let Err(e) = app.run("view.maskOverlay", json!({})) + { + app.toast(ui.ctx(), e); } let all = app.ui.mask_overlay_all; let all_mac = ui.ctx().os() == egui::os::OperatingSystem::Mac; @@ -255,6 +258,8 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { register(ui, format!("maskName:{}", m.id), Rect::from_min_size(at, g.size())); ui.painter().galley(at, g, color); let resp = if elided { resp.on_hover_text(&m.name) } else { resp }; + // the mask's own row (name, eye, menu) is where its effect is judged, the eye switching it + // on and off: the pointer on it shows no overlay (a component row under it does) // show / hide on hover (and always while hidden) // (the pointer test, not `hovered`: over the eye, the row itself no longer counts as hovered) if ui.rect_contains_pointer(r) || !m.visible { @@ -312,7 +317,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { MaskShape::Prompt { text, .. } => format!("“{text}”"), _ => menu_label(kind).to_string(), }); - ui.horizontal(|ui| { + let row = ui.horizontal(|ui| { let (r, _) = ui.allocate_exact_size(vec2(16.0, 16.0), Sense::hover()); paint(ui.painter(), r, icon, t.text_label); let op = match c.op { @@ -363,6 +368,10 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { component_row_popup(app, ui, &resp, &more, m.id, i, &label, m.components.len()); }); }); + // the pointer on a component's row shows the whole mask's overlay, to see where it is + if ui.rect_contains_pointer(row.response.rect) { + app.ui.mask_hover = app.session.active().map(|photo| (photo, m.id)); + } range_controls(app, ui, i, &c.shape); } ui.add_space(6.0); @@ -379,7 +388,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { let _ = app.run("mask.invert", json!({})); } if icon_button(ui, "maskDelete", Icon::Trash, vec2(26.0, 24.0), false, true, "Delete mask").clicked() { - let _ = app.run("mask.delete", json!({})); + delete_mask(app, None); } }); }); @@ -775,12 +784,14 @@ fn mask_menu(app: &mut LightcraftApp, ui: &mut egui::Ui, id: u32, name: &str, vi app.ui.renaming_mask = Some((id, name.to_string())); } if menu_run(ui, id, "delete", "Delete Mask", true) { - let _ = app.run("mask.delete", json!({"id": id})); + delete_mask(app, Some(id)); } } /// Overlay colours offered as swatches (the colour of the selected one is used for the tint). pub const OVERLAY_COLORS: [[u8; 3]; 5] = [[230, 30, 40], [40, 200, 70], [40, 110, 240], [250, 210, 30], [255, 255, 255]]; +/// The names of [`OVERLAY_COLORS`], in the same order (View ▸ Mask Overlay lists them). +pub const OVERLAY_COLOR_NAMES: [&str; 5] = ["Red", "Green", "Blue", "Yellow", "White"]; /// How the selected mask is shown: overlay mode, colour, opacity, pins. fn overlay_options(app: &mut LightcraftApp, ui: &mut egui::Ui) { @@ -1873,6 +1884,25 @@ fn brush_settings(app: &mut LightcraftApp, ui: &mut egui::Ui) { } } +/// Deletes mask `id` of the active photo (`None`: the active mask). A deleted mask's id is free for the next new +/// one, so whether O hid its overlay goes with it. +pub(crate) fn delete_mask(app: &mut LightcraftApp, id: Option) { + let (photo, target) = (app.session.active(), id.or(app.session.active_mask)); + let params = id.map_or_else(|| json!({}), |id| json!({"id": id})); + if app.run("mask.delete", params).is_ok() + && let (Some(photo), Some(target)) = (photo, target) + { + app.ui.mask_overlay_hidden.retain(|k| *k != (photo, target)); + } +} + +/// Forgets that O hid the overlay of a mask that no longer exists (undone, stepped back in the history, replaced by +/// pasted settings): its id goes to the next new mask, which must not start hidden. +pub(crate) fn forget_missing_overlays(app: &mut LightcraftApp) { + let session = &app.session; + app.ui.mask_overlay_hidden.retain(|(photo, id)| session.develop_of(*photo).is_some_and(|d| d.masks.iter().any(|m| m.id == *id))); +} + /// The ∩ in front of an intersecting mask component: two legs joined by a half circle, as tall as /// a lowercase letter. fn intersect_mark(painter: &egui::Painter, rect: Rect, color: egui::Color32) { diff --git a/crates/ui-egui/src/panels/right.rs b/crates/ui-egui/src/panels/right.rs index f1c10c3227..46cb88483f 100644 --- a/crates/ui-egui/src/panels/right.rs +++ b/crates/ui-egui/src/panels/right.rs @@ -1,5 +1,5 @@ //! The right-hand panel next to the tool strip: Edit, Crop, Remove, Masking, Red Eye, Info, -//! Keywords, Versions, Activity. +//! Keywords, Versions, Activity, Bursts. use egui::{Align2, Rect, Sense, pos2, vec2}; use lightcraft_catalog::PhotoId; @@ -29,10 +29,21 @@ pub(crate) use info::mixed_meta; pub(crate) use keywords::forget_stale_enter_keywords; use keywords::keywords; +/// The right column's scroll area for `panel`: one per panel, the same with or without a selected photo (the +/// Keywords panel shows its list either way). +fn scroll_salt(panel: RightPanel) -> (&'static str, RightPanel) { + ("right-scroll", panel) +} + pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { let t = Tokens::get(ui.ctx()); let frame = egui::Frame::NONE.fill(t.chrome).stroke(egui::Stroke::new(1.0, t.divider)); frame.show(ui, |ui| { + // the bursts are the view's, not a photo's: they are there without a selection + if app.ui.right == RightPanel::Bursts { + super::bursts::show(app, ui); + return; + } // (taken on every pass the panel is drawn; one from earlier than the pass before is forgotten) // (a sizing or measuring run in the pass leaves it for the real draw, which would else find it gone) let held = if ui.is_sizing_pass() || craft::ui::runtime::measure::active(ui.ctx()) { None } else { held_offset(ui.ctx()) }; @@ -41,7 +52,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { if app.ui.right == RightPanel::Keywords { // (without a selection there is no Add keyword box for Add Keywords to put the cursor in) app.ui.focus_keywords = None; - egui::ScrollArea::vertical().id_salt("right-scroll").auto_shrink([false, false]).show(ui, |ui| { + egui::ScrollArea::vertical().id_salt(scroll_salt(RightPanel::Keywords)).auto_shrink([false, false]).show(ui, |ui| { ui.spacing_mut().item_spacing.y = 0.0; if fold_header(app, ui, "keywording", "Keywords") { padded(ui, |ui| { @@ -69,7 +80,8 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { ui.spacing_mut().item_spacing.y = 0.0; super::edit::histogram(app, ui, id); } - let mut area = egui::ScrollArea::vertical().id_salt("right-scroll").auto_shrink([false, false]); + // each panel keeps its own scroll position: Edit is where it was after Masking or Crop + let mut area = egui::ScrollArea::vertical().id_salt(scroll_salt(app.ui.right)).auto_shrink([false, false]); if let Some(offset) = held { area = area.vertical_scroll_offset(offset); } @@ -101,7 +113,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { RightPanel::Keywords => keywords(app, ui, id), RightPanel::Versions => versions(app, ui, id), RightPanel::Activity => activity(app, ui, id), - RightPanel::None => {} + RightPanel::Bursts | RightPanel::None => {} } // Tab and focus requests keep the focused control in view super::scroll_focus::reveal_focus(ui, egui::Id::unique("right-scroll-focus")); diff --git a/crates/ui-egui/src/panels/right/crop.rs b/crates/ui-egui/src/panels/right/crop.rs index cba08616d8..ecd19a0fa3 100644 --- a/crates/ui-egui/src/panels/right/crop.rs +++ b/crates/ui-egui/src/panels/right/crop.rs @@ -384,7 +384,8 @@ pub(super) fn crop(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { (Upright::Full, "Full", "full"), ]; if let Some(mode) = crate::widgets::labeled_dropdown(ui, "upright", "Perspective Correction", "", &modes, d.geometry.upright) { - let _ = app.run("geometry.upright", json!({"mode": mode})); + let r = app.run("geometry.upright", json!({"mode": mode})); + upright_note(app, ui.ctx(), r.as_ref().ok()); // Guided starts drawing guides on the photo; any other mode stops it app.ui.tool = if mode == Upright::Guided { "guidedUpright".into() } else { String::new() }; } @@ -395,7 +396,8 @@ pub(super) fn crop(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { && text_button(ui, "uprightUpdate", crate::i18n::tr("Update"), false).clicked() { let mode = serde_json::to_value(d.geometry.upright).unwrap_or_default(); - let _ = app.run("geometry.upright", json!({"mode": mode})); + let r = app.run("geometry.upright", json!({"mode": mode})); + upright_note(app, ui.ctx(), r.as_ref().ok()); } if guided { let drawing = app.ui.tool == "guidedUpright"; @@ -900,6 +902,13 @@ pub(super) fn red_eye(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { }); } +/// Upright that found nothing to correct says why, as a note over the photo. +fn upright_note(app: &mut LightcraftApp, ctx: &egui::Context, result: Option<&serde_json::Value>) { + if let Some(note) = result.and_then(|r| r.get("note")).and_then(serde_json::Value::as_str) { + app.toast_for(ctx, note.to_string(), 8.0); + } +} + #[cfg(test)] #[path = "crop_checkboxes_external155_tests.rs"] mod crop_checkboxes_external155_tests; diff --git a/crates/ui-egui/src/panels/right/info.rs b/crates/ui-egui/src/panels/right/info.rs index aaab80e83f..2a63242ab7 100644 --- a/crates/ui-egui/src/panels/right/info.rs +++ b/crates/ui-egui/src/panels/right/info.rs @@ -110,7 +110,8 @@ pub(super) fn info(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { lightcraft_catalog::Source::File { path } => path.clone(), lightcraft_catalog::Source::Demo { .. } => crate::i18n::tr("Generated demo photo").into(), }; - ui.add(egui::Label::new(egui::RichText::new(path).size(12.0).color(t.text_label)).truncate()); + // Selectable so the source path can still be copied (#1885 turned plain labels off). + ui.add(egui::Label::new(egui::RichText::new(path).size(12.0).color(t.text_label)).truncate().selectable(true)); if crate::menus::ui_enabled(app, "app.showInFinder") { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { if crate::widgets::icon_button(ui, "infoReveal", Icon::Folder, vec2(20.0, 20.0), false, true, crate::menus::reveal_label()) @@ -265,7 +266,7 @@ fn camera_card(ui: &mut egui::Ui, p: &lightcraft_catalog::Photo) { } }); } - // where the camera focused, and how (View ▸ Focus Point draws it): only when known; the + // where the camera focused, and how (View ▸ Loupe Overlay ▸ Focus Point draws it): only when known; the // whole card's width, so "AF-C · Expanded Flexible Spot · Face tracking" fits if let Some(text) = focus_text(m.focus.as_ref()) { ui.add_space(3.0); diff --git a/crates/ui-egui/src/panels/right/tests.rs b/crates/ui-egui/src/panels/right/tests.rs index 1f1d60d609..2085f7300e 100644 --- a/crates/ui-egui/src/panels/right/tests.rs +++ b/crates/ui-egui/src/panels/right/tests.rs @@ -30,3 +30,61 @@ fn short_times() { assert_eq!(super::short_time("2026-09-30T12:00:05"), "Sep 30, 2026, 12:00 PM"); assert_eq!(super::short_time("2026-01-02"), "Jan 2, 2026"); } + +// Feature: the Keywords panel keeps its scroll position when a photo is selected (CodeRabbit on #3031: the +// no-selection list scrolled under another id) +#[test] +fn the_keywords_panel_scrolls_under_one_id_with_or_without_a_selection() { + use crate::state::RightPanel; + // (`show` names the no-selection list's scroll area by `scroll_salt(RightPanel::Keywords)`, as it names the + // panel's with a selection by `scroll_salt(app.ui.right)`) + assert_eq!(super::scroll_salt(RightPanel::Keywords), ("right-scroll", RightPanel::Keywords)); + assert_ne!(super::scroll_salt(RightPanel::Keywords), super::scroll_salt(RightPanel::Edit), "each panel keeps its own"); +} + +// The Keywords panel scrolled with no photo selected is the same scroll area as with one: the offset it was left at +// is there when a photo is selected (CodeRabbit on #3031) +#[test] +fn the_keywords_panel_keeps_its_offset_from_no_selection_to_a_selection() { + use crate::headless::Headless; + use serde_json::json; + use std::time::Duration; + const T: Duration = Duration::from_secs(20); + let services = crate::Services { png: None, ..Default::default() }; + let mut h = Headless::new(crate::LightcraftApp::new(lightcraft_engine::Session::with_demo(), services), [1200.0, 420.0], 1.0); + // a Keyword List longer than the panel + for i in 0..80 { + h.app.session.execute("keyword.create", &json!({"name": format!("keyword {i:02}")})).unwrap(); + } + let r = h.request("ui.set", json!({"view": "detail", "right": "keywords"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(Duration::from_secs(120)); + // with a selection: the panel's scroll area (as the panel records it) + let area = h.view.ctx.data(|d| d.get_temp::(egui::Id::unique(super::AREA))).expect("the panel's scroll area"); + let offset = |h: &Headless| egui::scroll_area::State::load(&h.view.ctx, area).map_or(0.0, |s| s.clamped_offset().y); + assert_eq!(offset(&h), 0.0); + // no selection: the list scrolled down + let r = h.request("engine.execute", json!({"command": "library.select", "params": {"ids": []}}), T); + assert_eq!(r["ok"], true, "{r}"); + for _ in 0..4 { + h.step(); + } + assert!(h.app.session.active().is_none()); + let panel = h.app.widgets.iter().find(|(w, _)| w == "panel:right_panel").map(|(_, r)| *r).expect("the right panel"); + h.request("ui.move", json!({"x": panel.center().x, "y": panel.center().y}), T); + let r = h.request("ui.scroll", json!({"dy": -300.0}), T); + assert_eq!(r["ok"], true, "{r}"); + for _ in 0..60 { + h.step(); + } + let scrolled = offset(&h); + assert!(scrolled > 50.0, "the no-selection list scrolls the panel's own area: {scrolled}"); + // a photo selected: the area keeps the offset (moved down only by the Keywords box put above the list) + let id = h.app.session.visible_cloned()[0]; + let r = h.request("engine.execute", json!({"command": "library.select", "params": {"ids": [id.0]}}), T); + assert_eq!(r["ok"], true, "{r}"); + for _ in 0..10 { + h.step(); + } + assert!(offset(&h) >= scrolled - 0.5, "the offset is kept: {} after {scrolled}", offset(&h)); +} diff --git a/crates/ui-egui/src/panels/slideshow.rs b/crates/ui-egui/src/panels/slideshow.rs index 351b8d531c..48db76c54e 100644 --- a/crates/ui-egui/src/panels/slideshow.rs +++ b/crates/ui-egui/src/panels/slideshow.rs @@ -213,7 +213,7 @@ pub fn tick(app: &mut LightcraftApp, ctx: &egui::Context, now: f64) { /// [`SlideSettings::is_plain`]: lightcraft_engine::slide::SlideSettings::is_plain fn slide_job(app: &mut LightcraftApp, id: PhotoId, area: Rect, ppp: f32, texture_side: usize) -> Option { let photo = app.session.catalog.photo(id)?.clone(); - let frame = Frame::with_lens(photo.width.max(1) as usize, photo.height.max(1) as usize, &photo.develop, true, photo.embedded_lens.as_ref()); + let frame = Frame::with_lens(photo.width.max(1) as usize, photo.height.max(1) as usize, &photo.develop, true, photo.embedded_lens.as_deref()); let native = super::detail::output_px(&frame); if !app.session.slides_plain() { let (w, h) = slide_px(area, ppp, texture_side); diff --git a/crates/ui-egui/src/panels/spot_outline.rs b/crates/ui-egui/src/panels/spot_outline.rs new file mode 100644 index 0000000000..2d3e3ac7b2 --- /dev/null +++ b/crates/ui-egui/src/panels/spot_outline.rs @@ -0,0 +1,297 @@ +//! The Remove tool's strokes on the photo (issue #2359): when a brush stroke records a point, the outline of +//! a stroke (the boundary of the union of its discs, not one ring per point) and what counts as grabbing it. +//! Pure geometry in screen points, so it is tested without a window. + +use std::collections::HashMap; +use std::f32::consts::TAU; + +use egui::Pos2; + +/// Fewest and most samples on one circle: scaled with the radius so a ring stays round at any zoom. +const SAMPLES: (f32, f32) = (24.0, 128.0); + +/// Whether a pointer at `q` adds a point to a stroke whose last stored point is `last`, in screen points, for a brush +/// of radius `r`. A point comes every `r / 4` (at least 2 points), like the mask brush's dabs, so a held or slowly +/// dragged pointer stores nothing more. On release (`end`) the stroke only has to reach `q` within `r / 8`. +pub fn adds_point(last: Pos2, q: Pos2, r: f32, end: bool) -> bool { + let d = last.distance(q); + let min = if end { r / 8.0 } else { (r / 4.0).max(2.0) }; + d.is_finite() && d > 0.0 && d >= min +} + +/// The distance from `q` to the nearest of `centres`, when it is within `r` (the stroke can be grabbed there). +pub fn grab_distance(centres: &[Pos2], q: Pos2, r: f32) -> Option { + let d = centres.iter().map(|c| c.distance(q)).filter(|d| d.is_finite()).min_by(f32::total_cmp)?; + (d < r).then_some(d) +} + +/// The boundary of the union of the discs of radius `r` at `centres`, as polylines of the arcs no other disc covers. +/// One disc, or many at the same place, gives one closed polyline (first point repeated at the end). Where discs +/// overlap, each circle contributes the arcs outside the others, from crossing to crossing, so the pieces meet and +/// are chained. Cost grows with the number of centres within `2r` of each other, so centres closer than `r / 16` to the +/// previous kept one (a held pointer in a stroke saved before points were spaced) don't count. +pub fn union_outline(centres: &[Pos2], r: f32) -> Vec> { + if !r.is_finite() || r <= 0.0 { + return Vec::new(); + } + let mut cs: Vec = Vec::new(); + for &c in centres { + if c.x.is_finite() && c.y.is_finite() && cs.last().is_none_or(|l| l.distance(c) >= r / 16.0) { + cs.push(c); + } + } + // a hostile stroke (thousands of points) is drawn from a subset: the outline stays within r/16 · stride of it + const MAX_CENTRES: usize = 1024; + if cs.len() > MAX_CENTRES { + let stride = cs.len().div_ceil(MAX_CENTRES); + cs = cs.into_iter().step_by(stride).collect(); + } + let same2 = (r * 0.01) * (r * 0.01); + // samples round a full circle: an arc gets the same angular step + let step = TAU / (r * 0.5).clamp(SAMPLES.0, SAMPLES.1).floor(); + let (mut out, mut arcs) = (Vec::new(), Vec::new()); + for (i, &c) in cs.iter().enumerate() { + let d2 = |o: &Pos2| (o.x - c.x).powi(2) + (o.y - c.y).powi(2); + // a circle on top of an earlier one adds nothing + if cs[..i].iter().any(|o| d2(o) <= same2) { + continue; + } + // the angles of this circle that another one covers: centred on the way to its centre, as wide as the + // chord where they cross (equal radii: acos(d / 2r)) + let mut covered: Vec<(f32, f32)> = Vec::new(); + for o in cs.iter().filter(|o| d2(o) > same2 && d2(o) < 4.0 * r * r) { + let (dx, dy) = (o.x - c.x, o.y - c.y); + let half = (dx.hypot(dy) / (2.0 * r)).clamp(0.0, 1.0).acos(); + let mid = dy.atan2(dx).rem_euclid(TAU); + let (lo, hi) = (mid - half, mid + half); + if lo < 0.0 { + covered.extend([(lo + TAU, TAU), (0.0, hi)]); + } else if hi > TAU { + covered.extend([(lo, TAU), (0.0, hi - TAU)]); + } else { + covered.push((lo, hi)); + } + } + covered.sort_by(|a, b| a.0.total_cmp(&b.0)); + let mut free: Vec<(f32, f32)> = Vec::new(); + let mut from = 0.0f32; + for (lo, hi) in covered { + if lo > from { + free.push((from, lo)); + } + from = from.max(hi); + } + if from < TAU { + free.push((from, TAU)); + } + // an arc that runs through angle 0 is one + if let (true, Some(&(_, end))) = (free.len() > 1 && free[0].0 == 0.0, free.last()) + && end == TAU + { + let (_, head) = free.remove(0); + if let Some(last) = free.last_mut() { + last.1 = TAU + head; + } + } + for (a, b) in free { + let m = (((b - a) / step).ceil() as usize).max(1); + let mut line: Vec = (0..=m) + .map(|k| { + let t = a + (b - a) * k as f32 / m as f32; + Pos2::new(c.x + r * t.cos(), c.y + r * t.sin()) + }) + .collect(); + // a circle nothing covers is a ring, not an arc + if b - a >= TAU { + line[m] = line[0]; + out.push(line); + } else if b - a > 1e-4 { + arcs.push(line); + } + } + } + out.extend(chain(arcs, (r * 0.01).max(0.25))); + out +} + +/// Arcs joined end to start wherever they meet within `tol`, so the outline is a few long polylines (one closed one +/// for a stroke) and not a piece per circle, with proper joins instead of butt ends at every crossing. +fn chain(arcs: Vec>, tol: f32) -> Vec> { + let cell = |p: Pos2| ((p.x / tol).floor() as i32, (p.y / tol).floor() as i32); + let first = |i: usize| arcs[i][0]; + let last = |i: usize| arcs[i][arcs[i].len() - 1]; + let grid = |at: &dyn Fn(usize) -> Pos2| { + let mut g: HashMap<(i32, i32), Vec> = HashMap::new(); + for i in 0..arcs.len() { + g.entry(cell(at(i))).or_default().push(i); + } + g + }; + // an arc whose start is within `tol` of p, `ok` to take + let find = |g: &HashMap<(i32, i32), Vec>, at: &dyn Fn(usize) -> Pos2, p: Pos2, ok: &dyn Fn(usize) -> bool| { + let (cx, cy) = cell(p); + (-1..=1) + .flat_map(|dx| (-1..=1).map(move |dy| (cx.saturating_add(dx), cy.saturating_add(dy)))) + .find_map(|c| g.get(&c)?.iter().copied().find(|&j| ok(j) && at(j).distance(p) <= tol)) + }; + let (by_start, by_end) = (grid(&first), grid(&last)); + // chains begin where no arc ends; whatever is left over is a cycle + let heads: Vec = (0..arcs.len()).filter(|&i| find(&by_end, &last, first(i), &|j| j != i).is_none()).collect(); + let mut used = vec![false; arcs.len()]; + let mut out = Vec::new(); + for i in heads.into_iter().chain(0..arcs.len()) { + if std::mem::replace(&mut used[i], true) { + continue; + } + let mut line = arcs[i].clone(); + while let Some(j) = line.last().and_then(|&end| find(&by_start, &first, end, &|j| !used[j])) { + used[j] = true; + line.extend(arcs[j].iter().skip(1)); + } + // a chain that came back to its start is closed + if let (Some(&a), Some(&b)) = (line.first(), line.last()) + && line.len() > 2 + && a.distance(b) <= tol + { + line.push(a); + } + out.push(line); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + fn length(lines: &[Vec]) -> f32 { + lines.iter().map(|l| l.windows(2).map(|w| w[0].distance(w[1])).sum::()).sum() + } + + fn outside_all(lines: &[Vec], centres: &[Pos2], r: f32) -> bool { + lines.iter().flatten().all(|p| centres.iter().all(|c| c.distance(*p) >= r * (1.0 - 1e-3))) + } + + #[test] + fn one_disc_is_one_closed_circle() { + let (c, r) = (Pos2::new(50.0, 40.0), 30.0); + let lines = union_outline(&[c], r); + assert_eq!(lines.len(), 1); + let l = &lines[0]; + assert_eq!(l.first(), l.last(), "closed"); + assert!(l.iter().all(|p| (p.distance(c) - r).abs() < 1e-3)); + assert!((length(&lines) - TAU * r).abs() < TAU * r * 0.01, "{}", length(&lines)); + } + + #[test] + fn many_identical_points_are_one_circle() { + let (c, r) = (Pos2::new(10.0, 10.0), 20.0); + let mut pts = vec![c; 40]; + pts.extend([Pos2::new(10.0, 10.0); 5]); + assert_eq!(union_outline(&pts, r), union_outline(&[c], r)); + // the same place reached again later in the stroke adds nothing either + let back = [c, Pos2::new(60.0, 10.0), c]; + assert_eq!(union_outline(&back, r).len(), 2, "two separate circles"); + } + + #[test] + fn two_overlapping_discs_leave_no_sample_inside_the_other() { + let r = 40.0; + let cs = [Pos2::new(0.0, 0.0), Pos2::new(r, 0.0)]; + let lines = union_outline(&cs, r); + assert_eq!(lines.len(), 1, "one closed outline, its two arcs joined at the crossings"); + assert!(lines[0][0].distance(lines[0][lines[0].len() - 1]) < 1e-3, "closed"); + assert!(outside_all(&lines, &cs, r)); + // each circle keeps 240° of its 360° when the centres are r apart + let want = 2.0 * TAU * r * (240.0 / 360.0); + assert!((length(&lines) - want).abs() < want * 0.02, "{} vs {want}", length(&lines)); + // the crossings of the two circles are on the outline + let h = r * 3f32.sqrt() / 2.0; + for y in [-h, h] { + assert!(lines[0].iter().any(|p| p.distance(Pos2::new(r / 2.0, y)) < 0.5), "crossing at y={y}"); + } + } + + #[test] + fn a_stroke_is_one_outline_around_its_path() { + let r = 30.0; + // a straight stroke at r/4 spacing + let cs: Vec = (0..40).map(|i| Pos2::new(i as f32 * r / 4.0, 0.0)).collect(); + let lines = union_outline(&cs, r); + assert!(outside_all(&lines, &cs, r)); + // a stadium: two straight sides of the stroke's length and the two caps + let want = 2.0 * 39.0 * r / 4.0 + TAU * r; + assert!((length(&lines) - want).abs() < want * 0.03, "{} vs {want}", length(&lines)); + assert_eq!(lines.len(), 1, "the arcs of all the circles are one closed line"); + // every outline point lies on a circle of the stroke + assert!(lines.iter().flatten().all(|p| cs.iter().any(|c| (c.distance(*p) - r).abs() < 1e-2))); + } + + /// A curved stroke's arcs are shorter than a sample step in places: the outline must still be one closed line. + #[test] + fn a_curved_stroke_is_one_closed_outline_without_gaps() { + for r in [6.0, 31.0, 80.0, 400.0] { + let cs: Vec = (0..70) + .map(|i| { + let t = i as f32 * r / 4.0; + Pos2::new(t * 0.9, r * 1.5 * (t / (6.0 * r)).sin() + t * 0.1) + }) + .collect(); + let lines = union_outline(&cs, r); + assert_eq!(lines.len(), 1, "r={r}: {} pieces", lines.len()); + let l = &lines[0]; + assert!(l[0].distance(l[l.len() - 1]) < 1e-3, "r={r}: closed"); + assert!(outside_all(&lines, &cs, r), "r={r}"); + // no step along the line is longer than a sample step of its circle (plus one crossing's worth of slack) + let step = TAU * r / (r * 0.5).clamp(SAMPLES.0, SAMPLES.1).floor(); + assert!(l.windows(2).all(|w| w[0].distance(w[1]) <= step * 1.01 + 0.5), "r={r}: gap in the outline"); + } + } + + #[test] + fn a_stationary_pointer_in_a_stroke_costs_nothing_extra() { + let r = 30.0; + let moving: Vec = (0..8).map(|i| Pos2::new(i as f32 * r / 4.0, 5.0)).collect(); + // every position held for 25 frames, as a stroke saved before points were spaced + let held: Vec = moving.iter().flat_map(|p| std::iter::repeat_n(*p, 25)).collect(); + assert_eq!(union_outline(&held, r), union_outline(&moving, r)); + } + + #[test] + fn hostile_input_gives_an_empty_or_finite_outline() { + for r in [0.0, -3.0, f32::NAN, f32::INFINITY] { + assert!(union_outline(&[Pos2::new(1.0, 1.0)], r).is_empty()); + } + assert!(union_outline(&[], 10.0).is_empty()); + let lines = union_outline(&[Pos2::new(f32::NAN, 0.0), Pos2::new(5.0, 5.0), Pos2::new(f32::INFINITY, 1.0)], 10.0); + assert_eq!(lines.len(), 1); + assert!(lines[0].iter().all(|p| p.x.is_finite() && p.y.is_finite())); + let many: Vec = (0..50_000).map(|i| Pos2::new(i as f32 * 0.7, (i % 7) as f32)).collect(); + assert!(!union_outline(&many, 40.0).is_empty()); + } + + #[test] + fn a_stroke_adds_points_a_quarter_radius_apart() { + let (last, r) = (Pos2::new(100.0, 100.0), 40.0); + let at = |dx: f32| Pos2::new(100.0 + dx, 100.0); + assert!(!adds_point(last, last, r, false), "stationary"); + assert!(!adds_point(last, at(9.0), r, false), "closer than r/4"); + assert!(adds_point(last, at(10.0), r, false)); + // a small brush still needs 2 points of movement + assert!(!adds_point(last, at(1.5), 4.0, false)); + assert!(adds_point(last, at(2.0), 4.0, false)); + // the release reaches where the pointer is once it moved r/8 + assert!(!adds_point(last, at(4.9), r, true)); + assert!(adds_point(last, at(5.0), r, true)); + assert!(!adds_point(last, last, r, true)); + assert!(!adds_point(last, Pos2::new(f32::NAN, 0.0), r, false)); + } + + #[test] + fn a_stroke_is_grabbed_anywhere_within_a_radius_of_its_points() { + let cs = [Pos2::new(0.0, 0.0), Pos2::new(20.0, 0.0), Pos2::new(40.0, 0.0)]; + assert_eq!(grab_distance(&cs, Pos2::new(40.0, 25.0), 30.0), Some(25.0)); + assert_eq!(grab_distance(&cs, Pos2::new(40.0, 30.0), 30.0), None); + assert_eq!(grab_distance(&[], Pos2::new(0.0, 0.0), 30.0), None); + } +} diff --git a/crates/ui-egui/src/services.rs b/crates/ui-egui/src/services.rs index 4c3e6a8a86..0f69a1dfdd 100644 --- a/crates/ui-egui/src/services.rs +++ b/crates/ui-egui/src/services.rs @@ -68,7 +68,7 @@ pub struct Services { pub pick_model_file: Option, /// Open dialog for preset files (`.lcpreset`, `.xmp`, `.lrtemplate`, `.zip`, `.dng`, Luminar `.lmp` / `.mplumpack`). pub pick_preset_files: Option, - /// Open dialog for a GPS track log (`.gpx`; Photo ▸ Auto-Tag from Tracklog…). + /// Open dialog for a GPS track log (`.gpx`; Photo ▸ Metadata ▸ Auto-Tag from Tracklog…). pub pick_tracklog: Option, /// Open dialog for a monitor ICC profile (`.icc` / `.icm`; Settings ▸ Display; desktop only). pub pick_display_profile: Option, diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index bcd88adf60..36d46ebe53 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -619,6 +619,9 @@ fn pressed_commands( || craft::ui::runtime::overlay::any_open(ctx, craft::ui::runtime::overlay::OpenFilter::Keys); // Esc that just took a text field's focus away (it gives back the field's text) does nothing else let popup_open = popup_open || app.text_focus; + // a drag in progress: Esc gives it up (`LightcraftApp::end_drags`) and does nothing else, even when no + // button is down any more (a hidden pass can take the release before `end_drags` sees it) + let popup_open = popup_open || app.ui.drag_active(); ctx.input(|i| { // Enter opens the active grid photo; widgets, popups and custom bindings keep the key. if grid @@ -890,7 +893,7 @@ fn delete_key(app: &mut LightcraftApp, ctx: &egui::Context) -> bool { match app.ui.right { R::Masking => { if app.session.active_mask.is_some() { - let _ = app.run("mask.delete", json!({})); + crate::panels::masking::delete_mask(app, None); } return true; } diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index c6831b15cb..44f228c295 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -33,9 +33,6 @@ pub struct UiState { pub docking_version: u32, #[serde(default = "crate::i18n::default_language")] pub language: crate::i18n::Locale, - /// The Build Previews run last announced (its identity, finished?). - #[serde(skip)] - pub preview_build_seen: Option<(usize, bool)>, /// Saving the library is failing (announced with a toast; the top bar shows a warning until /// a later save succeeds). #[serde(skip)] @@ -50,6 +47,26 @@ pub struct UiState { /// The right panel F8 (`view.rightPanel`) hid, which the next F8 shows again. #[serde(skip)] pub right_hidden: RightPanel, + /// The panel F8 just showed again, until [`UiState::note_right`] sees it: a tool coming back this way still closes + /// to the panel before it, while a tool opened any other way on a hidden column closes to the hidden column. + #[serde(skip)] + pub right_shown_by_f8: Option, + /// The panel on show before a tool panel ([`RightPanel::is_tool`]) took its place, put back + /// when the tool closes ([`RightPanel::None`]: the panel was hidden, and stays hidden). + #[serde(skip)] + pub tool_return: Option, + /// The panels toggles (a panel key or button: I, M, R, Q…) opened, each with what the right column showed before + /// it and that one's [`UiState::tool_return`], the latest last: toggling the panel on show off puts back exactly + /// that, closed included (test notes 2026-10-24 note 21), and the one below it is then on show with its own + /// record (Edit → I → K → K → I = Edit). Forgotten once another panel is shown (not when F8 hides the panel and + /// shows it again). At most [`TOGGLE_HISTORY`] deep. + #[serde(skip)] + /// Each record also holds the on-canvas tool of the panel it replaced (Masking's Brush, Remove's Heal or Clone), + /// put back with that panel (`None`: a tool opened by a command, which leaves the tool as it is). + pub toggle_return: Vec<(RightPanel, RightPanel, Option, Option)>, + /// The panel [`UiState::note_right`] last saw. + #[serde(skip)] + pub right_seen: RightPanel, /// Widths of the left sidebar and of the right panel in points (dragging their inner edge /// resizes them; within [`LEFT_WIDTH`] / [`RIGHT_WIDTH`]). pub left_width: f32, @@ -90,9 +107,23 @@ pub struct UiState { #[serde(skip)] pub proof_intent: lightcraft_engine::proof::ProofIntent, pub proof_paper_ink: bool, - /// Masking: show the selected mask as a rendered overlay (O), how (`MaskView` name, ⇧O cycles), - /// in which colour and opacity (0..100, colour views), and whether pins are drawn. + /// Masking: the selected mask's overlay switched on to stay (O, the panel's eye: "Always"), + /// how it is drawn (`MaskView` name, ⇧O cycles), in which colour and opacity (0..100, colour + /// views), and whether pins are drawn. Without it the overlay shows only by the one rule of + /// [`crate::panels::detail::overlay_mask`]: a mask without settings yet, or the mask whose pin + /// or component row the pointer is on. Not kept between sessions: the photo opens without it. + #[serde(skip)] pub mask_overlay: bool, + /// The mask whose pin or component row the pointer is on, this frame and the last (the overlay + /// shows it), with the photo it is on: a mask of the same id on another photo is another mask. + /// Not the mask's own row: there its effect is judged. + #[serde(skip)] + pub mask_hover: Option<(lightcraft_engine::catalog::PhotoId, u32)>, + #[serde(skip)] + pub mask_hover_prev: Option<(lightcraft_engine::catalog::PhotoId, u32)>, + /// The masks (of their photos) whose automatic overlay O hid, each until O shows it again. + #[serde(skip)] + pub mask_overlay_hidden: Vec<(lightcraft_engine::catalog::PhotoId, u32)>, pub mask_overlay_mode: String, pub mask_overlay_color: [u8; 3], pub mask_overlay_opacity: f32, @@ -245,8 +276,15 @@ pub struct UiState { pub dragging_section: Option, /// Selected curve channel in the Curve flyout. pub curve_channel: String, - /// Selected mixer mode: "hue" | "saturation" | "luminance" | "all". + /// The colour band shown in the Color Mixer's Color mode (one of `MIXER_BANDS`). pub mixer_mode: String, + /// The Color Mixer's tab: "mixer" | "point" (Point Color). Remembered. + pub mixer_tab: String, + /// What the Mixer adjusts by: "hsl" (eight sliders per Hue / Saturation / Luminance) | + /// "color" (one colour at a time). Remembered; HSL by default. + pub mixer_adjust: String, + /// The HSL group shown: "hue" | "sat" | "lum" | "all". Remembered. + pub mixer_group: String, /// Selected colour grading tab: "3way" | "shadows" | "midtones" | "highlights". pub grading_mode: String, /// Colour grading wheels (shadows, midtones, highlights) hidden for viewing by their eye, and @@ -394,6 +432,112 @@ pub struct UiState { pub print: crate::print_view::PrintUi, } +/// How many panel toggles [`UiState::toggle_return`] remembers (pressing I and K in turn would grow it without end). +pub const TOGGLE_HISTORY: usize = 16; + +impl UiState { + /// Notes the panel on show: a tool panel opened from another panel (or from none) remembers + /// that one, to put it back when the tool closes; any other panel forgets it. + pub fn note_right(&mut self) { + self.note_right_from(None); + } + + /// [`UiState::note_right`], told which panel a toggle ([`UiState::toggle_panel`]) just opened (its record is + /// on the history already). + fn note_right_from(&mut self, toggled: Option) { + let shown_by_f8 = self.right_shown_by_f8.take(); + if self.right == self.right_seen { + return; + } + // F8 showing a tool it hid: the panel before that tool still holds (`None` is F8's hidden column, not + // what the tool came from). A tool opened another way on the hidden column came from the hidden column. + let back_from_f8 = self.right_seen == RightPanel::None && shown_by_f8 == Some(self.right); + // A tool opened by a command, not a toggle (B, a mask tool from Crop…), is recorded like a toggle: closing + // it shows exactly what the column showed before (Info → Crop → B → Done = Crop), and the records below it + // stay (Crop closed = Info, I = Edit). That holds when the history already ends with this tool: F8 hiding it + // kept its record, and opening it again by a command on the hidden column (Info → Remove → F8 → Visualize + // Spots) closes it back to the hidden column, not to Info. + let opened_directly = self.right.is_tool() && !back_from_f8 && toggled != Some(self.right); + if opened_directly { + if self.toggle_return.len() >= TOGGLE_HISTORY { + self.toggle_return.remove(0); + } + self.toggle_return.push((self.right, self.right_seen, self.tool_return, None)); + } + // F8 hiding the panel a toggle opened keeps its record, for F8 showing it again + let f8_hid = |opened: RightPanel| self.right == RightPanel::None && self.right_hidden == opened; + if !opened_directly && self.toggle_return.last().is_some_and(|&(opened, ..)| opened != self.right && !f8_hid(opened)) { + self.toggle_return.clear(); + } + if self.right.is_tool() { + if !self.right_seen.is_tool() && !back_from_f8 { + self.tool_return = Some(self.right_seen); + } + } else if !(self.right == RightPanel::None && self.right_seen.is_tool() && self.right_hidden == self.right_seen) { + // any panel but F8 hiding the tool on show forgets it + self.tool_return = None; + } + self.right_seen = self.right; + } + + /// The panel to show when the tool panel on show closes: the one shown before it, or none + /// when the panel was hidden (Edit when nothing is known). + pub fn leave_tool(&mut self) -> RightPanel { + self.note_right(); + if let Some(back) = self.untoggle() { + return back; + } + let back = self.tool_return.take().unwrap_or(RightPanel::Edit); + if back.is_tool() { RightPanel::Edit } else { back } + } + + /// A panel toggle (`panel.info`, `panel.masking`…) for `p`: when `p` is on show (`exposed`: not hidden behind + /// another dock tab) it goes and the right column shows exactly what it showed before the toggle opened it, or + /// stays closed when it was (note 21); otherwise `p` comes up and what was there is remembered. Returns whether + /// `p` is now on. + pub fn toggle_panel(&mut self, p: RightPanel, exposed: bool) -> bool { + self.note_right(); + if self.right == p && exposed { + self.right = match self.untoggle() { + Some(back) => back, + None if p.is_tool() => self.leave_tool(), + None => RightPanel::None, + }; + self.note_right(); + false + } else { + // (a column hidden behind another dock tab comes back hidden, with no on-canvas tool: what it held + // wasn't on show) + let saved = + if exposed { (p, self.right, self.tool_return, Some(self.tool.clone())) } else { (p, RightPanel::None, self.tool_return, None) }; + if self.toggle_return.len() >= TOGGLE_HISTORY { + self.toggle_return.remove(0); + } + // (on the history before `note_right` sees `p`: the panel it replaced keeps its own record below it) + self.toggle_return.push(saved); + self.right = p; + self.note_right_from(Some(p)); + true + } + } + + /// What the toggle that opened the panel on show replaced (see [`UiState::toggle_panel`]), with its own tool + /// memory and on-canvas tool put back, or `None` when that panel wasn't opened by a toggle. + fn untoggle(&mut self) -> Option { + let &(opened, before, tool_return, _) = self.toggle_return.last()?; + if opened != self.right { + return None; + } + if let Some((.., Some(tool))) = self.toggle_return.pop() { + self.tool = tool; + } + self.tool_return = tool_return; + // seen already: `note_right` must not take the panel being left for the one this came back from + self.right_seen = before; + Some(before) + } +} + impl Default for UiState { /// Initialize the library and import review sizes as independent app preferences. fn default() -> Self { @@ -402,7 +546,6 @@ impl Default for UiState { docking: None, docking_version: crate::docking::DOCKING_VERSION, language: crate::i18n::default_language(), - preview_build_seen: None, unsaved_seen: false, frame_rate: std::env::var("LIGHTCRAFT_FPS").is_ok_and(|v| matches!(v.trim(), "1" | "on" | "true" | "yes")), luminance_map_restore: None, @@ -412,6 +555,10 @@ impl Default for UiState { right_width: RIGHT_WIDTH.default, right: RightPanel::Edit, right_hidden: RightPanel::None, + tool_return: None, + toggle_return: Vec::new(), + right_shown_by_f8: None, + right_seen: RightPanel::Edit, presets: false, preset_thumbs: false, filmstrip: true, @@ -432,7 +579,10 @@ impl Default for UiState { proof_profile: None, proof_intent: lightcraft_engine::proof::ProofIntent::Perceptual, proof_paper_ink: false, - mask_overlay: true, + mask_overlay: false, + mask_hover: None, + mask_hover_prev: None, + mask_overlay_hidden: Vec::new(), mask_overlay_mode: "color".into(), mask_overlay_color: [230, 30, 40], mask_overlay_opacity: 50.0, @@ -486,7 +636,10 @@ impl Default for UiState { dragging_album: None, dragging_section: None, curve_channel: "parametric".into(), - mixer_mode: "hue".into(), + mixer_mode: "red".into(), + mixer_tab: "mixer".into(), + mixer_adjust: "hsl".into(), + mixer_group: "hue".into(), grading_mode: "3way".into(), grading_hidden: None, tool: String::new(), @@ -550,6 +703,11 @@ impl Default for UiState { } impl UiState { + /// Whether photos, an album, a sidebar section or a keyword are being dragged. + pub fn drag_active(&self) -> bool { + self.dragging_photos.is_some() || self.dragging_album.is_some() || self.dragging_section.is_some() || self.dragging_keyword.is_some() + } + /// Which colour grading wheels (shadows, midtones, highlights) are hidden for viewing `photo`. pub fn grading_hidden_for(&self, photo: lightcraft_catalog::PhotoId) -> [bool; 3] { match self.grading_hidden { diff --git a/crates/ui-egui/src/state/dialog.rs b/crates/ui-egui/src/state/dialog.rs index 553277ec7e..62b7930ce2 100644 --- a/crates/ui-egui/src/state/dialog.rs +++ b/crates/ui-egui/src/state/dialog.rs @@ -50,7 +50,7 @@ pub enum Dialog { ContactSheet { options: lightcraft_engine::contact_sheet::Options, }, - /// View ▸ Export Slideshow…: format, size, quality, frame rate, container. + /// View ▸ Slideshow ▸ Export Slideshow…: format, size, quality, frame rate, container. SlideshowExport { settings: lightcraft_engine::slideshow_export::ExportSettings, }, @@ -184,7 +184,8 @@ pub enum Dialog { }, /// Photo ▸ Assisted Culling: reject photos below this focus score (0 = none), pick the best /// of each burst (and stack each burst, best on top, with `stack_groups`); shots at most - /// `burst_gap` seconds apart and at least `similarity` alike are a burst. + /// `burst_gap` seconds apart and at least `similarity` alike are a burst. Bursts arranged by + /// hand (Window ▸ Bursts) are kept unless `reset_bursts`. Cull { reject_below: f32, pick_best: bool, @@ -192,6 +193,8 @@ pub enum Dialog { stack_groups: bool, burst_gap: f32, similarity: f32, + #[serde(default)] + reset_bursts: bool, }, /// Help ▸ System Info: (label, value) rows. DenoiseModel { @@ -338,6 +341,9 @@ pub enum Dialog { ids: Vec, folder: String, name: String, + /// How many files the move touches (the drag label's count, `files_moved`): photos + /// already in the folder stay, and virtual copies of one file move it once. + files: usize, dont_ask: bool, /// The library the photos were dropped in (`Session::library_generation`): ids are /// numbered per library, so in another one they name other photos. @@ -371,7 +377,7 @@ pub enum Dialog { }, About, Shortcuts, - /// View ▸ View Options (⌘J): the info overlay and the lines of Info 1 and Info 2. Changes apply + /// View ▸ Loupe Overlay ▸ View Options… (⌘J): the info overlay and the lines of Info 1 and Info 2. Changes apply /// as they are made. ViewOptions, } diff --git a/crates/ui-egui/src/state/settings.rs b/crates/ui-egui/src/state/settings.rs index 737396177c..5f85ea9e6a 100644 --- a/crates/ui-egui/src/state/settings.rs +++ b/crates/ui-egui/src/state/settings.rs @@ -166,7 +166,7 @@ pub struct AppSettings { pub film_badges: bool, /// Grid: when to show the rating / flag / edited badges. pub grid_badges: GridBadges, - /// View ▸ View Options ▸ Show message when loading or rendering photos: the loupe says + /// View ▸ Loupe Overlay ▸ View Options… ▸ Show message when loading or rendering photos: the loupe says /// "Rendering…" while the photo it shows is not the finished render. pub loupe_messages: bool, /// Settings ▸ Performance ▸ Prepare photos in the background, app-wide (a library may keep its @@ -191,12 +191,12 @@ pub struct AppSettings { /// The Keywording box: whole keyword paths, or grouped by the keyword they are inside. #[serde(deserialize_with = "lenient")] pub keyword_chips: KeywordChips, - /// View ▸ Focus Point: draw the box the camera focused on (`view.focusPoint`). + /// View ▸ Loupe Overlay ▸ Focus Point: draw the box the camera focused on (`view.focusPoint`). pub focus_point: bool, - /// View ▸ Zoom to Focus Point: Toggle Zoom (Z) centres the zoomed view on the camera's focus point + /// View ▸ Loupe Overlay ▸ Zoom to Focus Point: Toggle Zoom (Z) centres the zoomed view on the camera's focus point /// when the photo has one (`view.zoomToFocus`). pub zoom_to_focus: bool, - /// View ▸ View Options: the lines the loupe's info overlay shows in Info 1 and Info 2. + /// View ▸ Loupe Overlay ▸ View Options…: the lines the loupe's info overlay shows in Info 1 and Info 2. #[serde(deserialize_with = "lenient")] pub loupe_info: LoupeInfo, /// File ▸ Import Lightroom Catalog…: ask whether the catalog merges into the open library or diff --git a/crates/ui-egui/src/state/view.rs b/crates/ui-egui/src/state/view.rs index a1fdb3b7ce..bf4de4a989 100644 --- a/crates/ui-egui/src/state/view.rs +++ b/crates/ui-egui/src/state/view.rs @@ -19,7 +19,7 @@ pub enum ViewMode { } /// The right-hand tool/panel shown next to the tool strip. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub enum RightPanel { #[default] @@ -35,9 +35,17 @@ pub enum RightPanel { Info, /// The profile browser (part of Edit). Profiles, + /// Assisted Culling's bursts, to arrange by hand (Window ▸ Bursts). + Bursts, } impl RightPanel { + /// A tool that takes the panel's place while it is used (Crop, Remove, Masking, Red Eye): on + /// closing, the panel shown before it comes back ([`UiState::leave_tool`]). + pub fn is_tool(self) -> bool { + matches!(self, RightPanel::Crop | RightPanel::Remove | RightPanel::Masking | RightPanel::RedEye) + } + pub fn is_edit_tool(self) -> bool { matches!(self, RightPanel::Edit | RightPanel::Profiles | RightPanel::Crop | RightPanel::Remove | RightPanel::Masking | RightPanel::RedEye) } @@ -175,7 +183,7 @@ impl InfoOverlay { } } -/// One line of the loupe's info overlay, chosen in View ▸ View Options (Lightroom Classic's Loupe +/// One line of the loupe's info overlay, chosen in View ▸ Loupe Overlay ▸ View Options… (Lightroom Classic's Loupe /// Info 1 / Loupe Info 2). A line with nothing to show for a photo is left out. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index 1dfec459d3..c6c27ef9f6 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -19,12 +19,14 @@ mod alt_preview; mod appearance; mod before_after; mod browse_active; +mod bursts; mod button; mod canvas_keys; mod canvas_pan; mod capture_time; mod carried_right_click; mod carried_text_field_menu; +mod color_mixer; mod compare; mod copy_paste_dialogs; mod covered_escape; @@ -37,6 +39,7 @@ mod dialog_fit; mod dialog_primary; mod dialog_settings; mod dialog_settings_blur_count; +mod dialog_settings_filter; mod dialog_settings_keyboard_contract; mod dialog_settings_keyboard_guards; mod dialog_settings_popup_contract; @@ -45,12 +48,12 @@ mod dialog_tab; mod dialogs; mod disk_space; mod docking_acceptance; +mod drag_contract; mod drop_import; mod edit_layout; mod empty_library; mod error_kinds; mod filmstrip; -mod ported_fills; mod filmstrip_drag; mod find_similar; mod focus_point; @@ -80,6 +83,7 @@ mod library_problem; mod lifecycle_037; mod lightroom_destination; mod lights_out; +mod looping_albums; mod mask_effects; mod masking; mod masking_layout; @@ -90,7 +94,9 @@ mod mode_dropdowns; mod move_folder; mod offline; mod open_lightroom; +mod panel_restore; pub(super) mod panels; +mod ported_fills; mod preset_favorites; mod preset_import; mod preview_limit; @@ -113,6 +119,7 @@ mod slider_reset; mod slideshow; mod solo_sections; mod space_hand; +mod spot_stroke; mod switch_library; mod sync; mod tallies; diff --git a/crates/ui-egui/src/tests/activity.rs b/crates/ui-egui/src/tests/activity.rs index bdeaccf4e9..0f46af39c4 100644 --- a/crates/ui-egui/src/tests/activity.rs +++ b/crates/ui-egui/src/tests/activity.rs @@ -12,6 +12,7 @@ use crate::{LightcraftApp, Services}; // generous: merges and renders run on worker threads that a busy machine (a full workspace test run) slows a lot const T: Duration = Duration::from_secs(60); +/// Build a headless instance with the procedural demo library loaded. fn demo() -> Headless { let app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, ..Default::default() }); let mut h = Headless::new(app, [1200.0, 800.0], 1.0); @@ -21,14 +22,17 @@ fn demo() -> Headless { h } +/// Check whether a widget with the given identifier is registered. fn has(h: &Headless, id: &str) -> bool { h.app.widgets.iter().any(|(w, _)| w == id) } +/// Count the number of activity row widgets registered. fn rows(h: &Headless) -> usize { h.app.widgets.iter().filter(|(w, _)| w.starts_with("activity:row:")).count() } +/// Return the bounding rectangle of the registered widget with `id`. fn rect(h: &Headless, id: &str) -> egui::Rect { h.app.widgets.iter().find(|(w, _)| w == id).map(|(_, r)| *r).unwrap_or_else(|| panic!("no widget {id}")) } @@ -110,6 +114,9 @@ fn count_text_by_unit() { cancellable: true, cancelling: false, age_ms: 600, + waiting: false, + place: 0, + lane: None, }; assert_eq!(count_text(&t), "3 of 25"); (t.done, t.total, t.unit) = (12 * 1_048_576, 340 * 1_048_576, Unit::Bytes); @@ -573,6 +580,150 @@ fn rows_added_later_grow_the_stack() { } } +/// Verify that dragging the activity stack moves the panel across frames and respects viewport constraints. +#[test] +fn activity_stack_area_is_movable() { + let mut h = demo(); + let g = h.app.session.activity.start("export", "Exporting", Cancel::Yes); + wait_visible(&mut h); + let id = egui::Id::unique("activity-stack"); + let initial_rect = h.view.ctx.memory(|m| m.area_rect(id)).expect("the stack is drawn"); + assert!(initial_rect.min.x >= 7.0 && initial_rect.min.x <= 9.0, "default pos at x=8: {initial_rect:?}"); + + // Hover cancel cross -> PointingHand + let cancel_id = format!("activity:cancel:{}", g.id()); + let r = h.request("ui.hoverWidget", json!({"id": cancel_id}), T); + assert_eq!(r["ok"], true, "{r:?}"); + h.step(); + assert_eq!(h.last_cursor, egui::CursorIcon::PointingHand, "cancel cross shows pointing hand"); + + // Hover frame padding -> Grab + let r = h.request("ui.move", json!({"x": initial_rect.min.x + 4.0, "y": initial_rect.min.y + 4.0}), T); + assert_eq!(r["ok"], true, "{r:?}"); + h.step(); + assert_eq!(h.last_cursor, egui::CursorIcon::Grab, "frame padding hover shows grab cursor"); + + // Drag the activity stack from non-interactive frame padding, verifying Grabbing cursor mid-drag + let start_pos = initial_rect.min + egui::vec2(4.0, 4.0); + let target_pos = start_pos + egui::vec2(100.0, 60.0); + let modifiers = egui::Modifiers::NONE; + h.app.synthetic.push(egui::Event::PointerMoved(start_pos)); + h.app.synthetic.push(egui::Event::PointerButton { pos: start_pos, button: egui::PointerButton::Primary, pressed: true, modifiers }); + h.step(); + for i in 1..=4 { + h.app.synthetic.push(egui::Event::PointerMoved(start_pos + (target_pos - start_pos) * (i as f32 / 4.0))); + h.step(); + } + assert_eq!(h.last_cursor, egui::CursorIcon::Grabbing, "cursor is Grabbing mid-drag"); + h.app.synthetic.push(egui::Event::PointerButton { pos: target_pos, button: egui::PointerButton::Primary, pressed: false, modifiers }); + h.step(); + h.step(); + let updated_rect = h.view.ctx.memory(|m| m.area_rect(id)).expect("the stack is drawn"); + assert!((updated_rect.min.x - (initial_rect.min.x + 100.0)).abs() < 5.0, "stack moved in x: {updated_rect:?}"); + assert!((updated_rect.min.y - (initial_rect.min.y + 60.0)).abs() < 5.0, "stack moved in y: {updated_rect:?}"); + assert!(!g.is_cancelled(), "dragging the stack does not cancel the task"); + + // Dragging beyond the right and bottom viewport edges moves toward edges and is constrained on screen + let content = h.view.ctx.content_rect(); + let before_rb = updated_rect; + let r = h.request( + "ui.drag", + json!({"x": updated_rect.min.x + 4.0, "y": updated_rect.min.y + 4.0, "toX": content.max.x + 500.0, "toY": content.max.y + 500.0, "steps": 6}), + T, + ); + assert_eq!(r["ok"], true, "{r:?}"); + h.step(); + let constrained_rb = h.view.ctx.memory(|m| m.area_rect(id)).expect("the stack is drawn"); + assert!(constrained_rb.min.x > before_rb.min.x, "stack moved right toward edge: {constrained_rb:?} vs {before_rb:?}"); + assert!(constrained_rb.min.y > before_rb.min.y, "stack moved down toward edge: {constrained_rb:?} vs {before_rb:?}"); + assert!(constrained_rb.max.x <= content.max.x + 1.0, "constrained in right: {constrained_rb:?} vs {content:?}"); + assert!(constrained_rb.max.y <= content.max.y + 1.0, "constrained in bottom: {constrained_rb:?} vs {content:?}"); + + // Dragging past the left and top edges moves toward top-left and is constrained + let before_lt = constrained_rb; + let r = h.request( + "ui.drag", + json!({"x": constrained_rb.min.x + 4.0, "y": constrained_rb.min.y + 4.0, "toX": content.min.x - 500.0, "toY": content.min.y - 500.0, "steps": 6}), + T, + ); + assert_eq!(r["ok"], true, "{r:?}"); + h.step(); + let constrained_lt = h.view.ctx.memory(|m| m.area_rect(id)).expect("the stack is drawn"); + assert!(constrained_lt.min.x < before_lt.min.x, "stack moved left toward edge: {constrained_lt:?} vs {before_lt:?}"); + assert!(constrained_lt.min.y < before_lt.min.y, "stack moved up toward edge: {constrained_lt:?} vs {before_lt:?}"); + assert!(constrained_lt.min.x >= content.min.x - 1.0, "constrained in left: {constrained_lt:?} vs {content:?}"); + assert!(constrained_lt.min.y >= content.min.y - 1.0, "constrained in top: {constrained_lt:?} vs {content:?}"); +} + +/// Verify that dragging the stack near the bottom in a short viewport keeps controls reachable and within bounds. +#[test] +fn activity_stack_short_viewport_near_bottom_keeps_controls_reachable() { + // 300 pt tall viewport exercises the height-budget path. + // Do NOT use h.settle(T): demo renders asynchronously and blocks 60 s. + // Two steps suffice for a pure-UI / height-constraint test. + let app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, ..Default::default() }); + let mut h = Headless::new(app, [600.0, 300.0], 1.0); + h.step(); + h.step(); + let guards: Vec<_> = (0..5).map(|i| h.app.session.activity.start("export", &format!("Task {i}"), Cancel::Yes)).collect(); + wait_visible(&mut h); + + let content = h.view.ctx.content_rect(); + let id = egui::Id::unique("activity-stack"); + + // At the default position the cancel and "+more" controls are within the viewport. + let cancel_id = format!("activity:cancel:{}", guards[0].id()); + assert!(has(&h, &cancel_id), "cancel button is present at default position"); + assert!(content.contains_rect(rect(&h, &cancel_id)), "cancel button within viewport at default position"); + assert!(has(&h, "activity:more"), "+more button is present at default position"); + assert!(content.contains_rect(rect(&h, "activity:more")), "+more button within viewport at default position"); + + // Cancel task 0 while controls are reachable at the default position. + click(&mut h, &cancel_id); + assert!(guards[0].is_cancelled(), "cancel button was clickable and worked"); + + // Drag the stack to 40 pt above the bottom edge. When only 40 pt remain the + // height-budget path clamps available_h to footer_reserve, so rows disappear — + // that is expected. What must hold is that the stack does not exceed the + // viewport: its max.y must stay at or below content.bottom(). + let initial_rect = h.view.ctx.memory(|m| m.area_rect(id)).expect("the stack is drawn"); + let r = h.request( + "ui.drag", + json!({"x": initial_rect.min.x + 4.0, "y": initial_rect.min.y + 4.0, "toX": initial_rect.min.x + 4.0, "toY": content.bottom() - 40.0, "steps": 6}), + T, + ); + assert_eq!(r["ok"], true, "{r:?}"); + h.step(); + let dragged_rect = h.view.ctx.memory(|m| m.area_rect(id)).expect("the stack is drawn"); + assert!(dragged_rect.max.y <= content.bottom() + 1.0, "stack stays within viewport after near-bottom drag: {dragged_rect:?} vs {content:?}"); +} + +/// The grip at the top of the stack sits outside the task list: dragging it moves the stack even when the list +/// overflows (a drag over the rows would scroll the list instead). +#[test] +fn the_grip_moves_the_stack_when_the_list_overflows() { + let app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, ..Default::default() }); + let mut h = Headless::new(app, [600.0, 300.0], 1.0); + h.step(); + h.step(); + let _guards: Vec<_> = (0..8).map(|i| h.app.session.activity.start("export", &format!("Task {i}"), Cancel::Yes)).collect(); + wait_visible(&mut h); + click(&mut h, "activity:more"); + assert!(h.app.activity_expanded, "the stack shows every task"); + let grip = rect(&h, "activity:handle"); + let first_row = h.app.widgets.iter().filter(|(w, _)| w.starts_with("activity:row:")).map(|(_, r)| r.min.y).fold(f32::MAX, f32::min); + assert!(grip.max.y <= first_row, "the grip is above the list: {grip:?} vs first row at {first_row}"); + let id = egui::Id::unique("activity-stack"); + let before = h.view.ctx.memory(|m| m.area_rect(id)).expect("the stack is drawn"); + let from = grip.center(); + let r = h.request("ui.drag", json!({"x": from.x, "y": from.y, "toX": from.x + 120.0, "toY": from.y, "steps": 6}), T); + assert_eq!(r["ok"], true, "{r:?}"); + h.step(); + h.step(); + let after = h.view.ctx.memory(|m| m.area_rect(id)).expect("the stack is drawn"); + assert!((after.min.x - (before.min.x + 120.0)).abs() < 5.0, "the grip moved the stack: {before:?} -> {after:?}"); +} + #[test] fn immediate_library_commands_and_auto_sync_show_completion() { let mut h = demo(); @@ -591,3 +742,92 @@ fn immediate_library_commands_and_auto_sync_show_completion() { assert!(h.app.run("library.compact", json!({})).is_err()); assert!(h.app.ui.toast.is_none()); } + +/// Given a preview build running and another waiting in line behind it, then the stack shows the running build only, +/// and the waiting one starts by itself, in a frame, when the build ahead of it ends. +#[test] +fn a_task_waiting_in_line_has_no_row_and_starts_when_the_lane_frees() { + use lightcraft_engine::cmd::previews::PreviewBuild; + use std::sync::atomic::Ordering; + + let mut h = demo(); + let build = std::sync::Arc::new(PreviewBuild::default()); + h.app.session.preview_build = Some(build.clone()); + let running = h.app.session.activity.start("previews", "Building previews", Cancel::Yes); + let ids: Vec = h.app.session.catalog.photos().take(1).map(|p| p.id.0).collect(); + let queued = h.app.session.execute("library.buildPreviews", &json!({"ids": ids, "edge": 256, "queue": true})).unwrap(); + let waiting = queued["queued"].as_u64().expect("it waits"); + assert_eq!(h.app.session.activity.list().len(), 2); + wait_visible(&mut h); + assert!(has(&h, &format!("activity:row:{}", running.id()))); + assert!(!has(&h, &format!("activity:row:{waiting}")) && rows(&h) == 1, "a waiting task draws no row"); + // the lane frees with no command asked: the frame loop starts it + build.finished.store(true, Ordering::Release); + drop(running); + let t0 = std::time::Instant::now(); + while h.app.session.activity.list().iter().any(|t| t.id == waiting && t.label == "Building previews") && t0.elapsed() < T { + h.step(); + let started = h.app.session.preview_build.as_ref().is_some_and(|b| !std::sync::Arc::ptr_eq(b, &build)); + if started { + break; + } + } + assert!(h.app.session.preview_build.as_ref().is_some_and(|b| !std::sync::Arc::ptr_eq(b, &build)), "the waiting build started"); + assert!(h.step_until(T, |h| h.app.session.activity.list().is_empty()), "the started build ends"); +} + +/// Given a build that ended and a build waiting behind it, when a command starts the waiting one before the frame that +/// announces the first, then the first one's end is still announced, and once. +#[test] +fn a_build_replaced_by_the_one_waiting_behind_it_is_still_announced() { + use lightcraft_engine::cmd::previews::PreviewBuild; + use std::sync::atomic::Ordering; + + let mut h = demo(); + let first = std::sync::Arc::new(PreviewBuild::default()); + first.done.store(2, Ordering::Relaxed); + h.app.session.preview_build = Some(first.clone()); + let row = h.app.session.activity.start("previews", "Building previews", Cancel::Yes); + let ids: Vec = h.app.session.catalog.photos().take(1).map(|p| p.id.0).collect(); + h.app.session.execute("library.buildPreviews", &json!({"ids": ids, "edge": 256, "queue": true})).unwrap(); + first.finished.store(true, Ordering::Release); + drop(row); + // a command in the same frame, before the app looks at the finished build + h.app.session.execute("activity.list", &json!({})).unwrap(); + assert!(h.app.session.preview_build.as_ref().is_some_and(|b| !std::sync::Arc::ptr_eq(b, &first)), "the waiting build replaced it"); + h.step(); + assert!(first.reported.load(Ordering::Relaxed), "its end was announced"); + let toast = h.app.ui.toast.as_ref().map(|t| t.0.clone()).unwrap_or_default(); + assert!(toast.contains("Previews ready for 2 photos"), "{toast}"); + assert!(h.app.session.take_unreported_builds().is_empty()); + assert!(h.step_until(T, |h| h.app.session.activity.list().is_empty()), "the started build ends"); +} + +/// Given a build that ended and a build waiting behind it, when the frame starts the waiting one, then the same frame +/// asks to be drawn again to see how it goes: nothing else repaints an idle window (the list is closed, or Full Screen +/// Preview hides it). +#[test] +fn the_frame_that_starts_a_waiting_build_asks_for_the_next_one() { + use lightcraft_engine::cmd::previews::PreviewBuild; + use std::sync::atomic::Ordering; + + let mut h = demo(); + let first = std::sync::Arc::new(PreviewBuild::default()); + h.app.session.preview_build = Some(first.clone()); + let row = h.app.session.activity.start("previews", "Building previews", Cancel::Yes); + let ids: Vec = h.app.session.catalog.photos().take(1).map(|p| p.id.0).collect(); + h.app.session.execute("library.buildPreviews", &json!({"ids": ids, "edge": 256, "queue": true})).unwrap(); + first.finished.store(true, Ordering::Release); + drop(row); + let ctx = egui::Context::default(); + // (a few empty passes let the context's own first-frame requests go by) + for _ in 0..4 { + let mut out = ctx.run_ui(egui::RawInput::default(), |_| {}); + out.textures_delta.clear(); + } + assert!(!ctx.has_requested_repaint(), "an idle context asks for nothing"); + h.app.tick_preview_builds(&ctx); + assert!(h.app.session.preview_build.as_ref().is_some_and(|b| !std::sync::Arc::ptr_eq(b, &first)), "the waiting build started"); + assert!(ctx.has_requested_repaint(), "and the frame asked to look at it again"); + assert!(h.step_until(T, |h| h.app.session.activity.list().is_empty()), "the started build ends"); +} diff --git a/crates/ui-egui/src/tests/bursts.rs b/crates/ui-egui/src/tests/bursts.rs new file mode 100644 index 0000000000..03735daf9a --- /dev/null +++ b/crates/ui-egui/src/tests/bursts.rs @@ -0,0 +1,290 @@ +//! Window ▸ Bursts: Assisted Culling's bursts as rows of thumbnails, pick first. A photo dragged +//! to the front of its burst becomes the pick; dragged into another burst, onto New Burst or Not +//! in a Burst it moves there; a burst dragged by its title merges into another; photos dragged +//! from the grid drop here too. Each drop is one undo step. + +use egui::{Pos2, Rect, pos2}; +use lightcraft_catalog::{Analysis, Flag, Op, Photo, PhotoId, Source}; +use serde_json::json; + +use crate::headless::Headless; +use crate::state::RightPanel; +use crate::{LightcraftApp, Services}; + +/// Burst 1: a (picked by culling), b, c; burst 2: d, e; f never culled. The grid, with the +/// Bursts panel open. +fn app() -> (Headless, [PhotoId; 6]) { + let mut session = lightcraft_engine::Session::new(); + let mut add = |name: &str, when: &str, culled: Option<(u32, f32, bool)>| { + let id = session.catalog.alloc_photo_id(); + let mut p = Photo::new(id, Source::File { path: format!("/nowhere/{name}") }, name, "JPEG", 300, 200, "2026-05-01T12:00:00"); + p.captured = Some(when.into()); + p.analysis = culled.map(|(g, sharpness, best)| Analysis { sharpness, group: Some(g), best, ..Default::default() }); + session.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + id + }; + let ids = [ + add("a.jpg", "2026-05-01T10:00:00", Some((1, 80.0, true))), + add("b.jpg", "2026-05-01T10:00:01", Some((1, 60.0, false))), + add("c.jpg", "2026-05-01T10:00:02", Some((1, 40.0, false))), + add("d.jpg", "2026-05-01T11:00:00", Some((2, 70.0, true))), + add("e.jpg", "2026-05-01T11:00:01", Some((2, 30.0, false))), + add("f.jpg", "2026-05-01T12:00:00", None), + ]; + session.catalog.apply(Op::SetFlag { id: ids[0], flag: Flag::Pick }).unwrap(); + let mut h = Headless::new(LightcraftApp::new(session, Services { png: None, ..Default::default() }), [1400.0, 900.0], 1.0); + let r = h.request("ui.set", json!({"view": "photoGrid"}), std::time::Duration::from_secs(10)); + assert_eq!(r["ok"], true, "{r}"); + h.app.run("panel.bursts", json!({})).unwrap(); + for _ in 0..4 { + h.step(); + } + assert_eq!(h.app.ui.right, RightPanel::Bursts); + (h, ids) +} + +fn widget(h: &Headless, id: &str) -> Rect { + h.app.widgets.iter().find(|(w, _)| w == id).map(|(_, r)| *r).unwrap_or_else(|| { + panic!("no {id} in {:?}", h.app.widgets.iter().filter(|(w, _)| w.starts_with("burst")).map(|(w, _)| w).collect::>()) + }) +} + +fn cell(h: &Headless, id: PhotoId) -> Rect { + widget(h, &format!("burstPhoto:{}", id.0)) +} + +fn press(h: &mut Headless, at: Pos2) { + h.app.synthetic.push(egui::Event::PointerMoved(at)); + h.app.synthetic.push(egui::Event::PointerButton { + pos: at, + button: egui::PointerButton::Primary, + pressed: true, + modifiers: egui::Modifiers::NONE, + }); + h.step(); +} + +fn glide(h: &mut Headless, from: Pos2, to: Pos2) { + for i in 1..=8 { + h.app.synthetic.push(egui::Event::PointerMoved(from + (to - from) * (i as f32 / 8.0))); + h.step(); + } + // (synthetic input arrives a frame or two behind) + for _ in 0..3 { + h.step(); + } +} + +fn release(h: &mut Headless, at: Pos2) { + h.app.synthetic.push(egui::Event::PointerButton { + pos: at, + button: egui::PointerButton::Primary, + pressed: false, + modifiers: egui::Modifiers::NONE, + }); + h.step(); + h.step(); +} + +fn drag(h: &mut Headless, from: Pos2, to: Pos2) { + press(h, from); + glide(h, from, to); +} + +fn hint(h: &Headless) -> Option { + h.view.ctx.data(|d| d.get_temp::<(u64, String)>(egui::Id::unique("drag-photos-hint"))).map(|(_, text)| text) +} + +fn best(h: &Headless, id: PhotoId) -> bool { + h.app.session.catalog.photo(id).unwrap().analysis.unwrap().best +} + +#[test] +fn bursts_show_their_pick_first() { + let (h, [a, b, c, d, e, f]) = app(); + // a row per burst, its pick first + let (one, two) = (widget(&h, "burst:1"), widget(&h, "burst:2")); + assert!(one.bottom() <= cell(&h, a).top() && cell(&h, e).top() >= two.bottom(), "each title above its photos"); + assert!(cell(&h, a).left() < cell(&h, b).left() && cell(&h, b).left() < cell(&h, c).left()); + assert!(cell(&h, d).left() < cell(&h, e).left()); + widget(&h, "burstPick:1"); + assert!(widget(&h, "burstPick:1").intersects(cell(&h, a)), "the pick is marked"); + // a photo culling never saw has no row; the drop places for a new burst and for none are there + assert!(!h.app.widgets.iter().any(|(w, _)| w == &format!("burstPhoto:{}", f.0))); + widget(&h, "burst:new"); + widget(&h, "burst:none"); +} + +/// A burst whose photos are all hidden in a collapsed stack of another burst's photo is still +/// listed, so it can be arranged. +#[test] +fn a_burst_hidden_in_another_bursts_stack_is_listed() { + let (mut h, [a, _, _, d, e, _]) = app(); + h.app.session.selection.ids = vec![a, d, e]; + h.app.session.selection.active = Some(a); + h.app.session.execute("stack.group", &json!({"collapsed": true})).unwrap(); + for _ in 0..4 { + h.step(); + } + let visible = h.app.session.visible_cloned(); + assert!(visible.contains(&a) && !visible.contains(&d) && !visible.contains(&e), "d and e are hidden under a: {visible:?}"); + let (one, two) = (widget(&h, "burst:1"), widget(&h, "burst:2")); + assert!(one.top() < two.top(), "listed after the burst of the stack's top"); + assert!(cell(&h, d).top() >= two.bottom() && cell(&h, e).top() >= two.bottom(), "with its photos"); +} + +#[test] +fn a_photo_dragged_to_the_front_becomes_the_pick() { + let (mut h, [a, b, c, ..]) = app(); + let to = pos2(cell(&h, a).left() + 4.0, cell(&h, a).center().y); + let from = cell(&h, c).center(); + drag(&mut h, from, to); + assert_eq!(h.app.ui.dragging_photos, Some(vec![c.0])); + assert_eq!(hint(&h).as_deref(), Some("Make it the pick")); + release(&mut h, to); + assert!(h.app.ui.dragging_photos.is_none()); + assert_eq!(h.app.session.catalog.burst(1), vec![c, a, b]); + assert!(best(&h, c) && !best(&h, a)); + assert_eq!(h.app.session.catalog.photo(c).unwrap().flag, Flag::Pick, "culling's Pick follows the pick"); + // the panel shows the new order + h.step(); + assert!(cell(&h, c).left() < cell(&h, a).left()); + // one undo step + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.catalog.burst(1), vec![a, b, c]); + assert!(best(&h, a)); +} + +#[test] +fn photos_move_between_bursts_and_bursts_merge() { + let (mut h, [a, b, c, d, e, _]) = app(); + let group = |h: &Headless, id: PhotoId| h.app.session.catalog.photo(id).unwrap().analysis.unwrap().group; + // e onto burst 1 between a and b; burst 2 is left with d alone: no burst any more + let to = pos2(cell(&h, b).left() + 4.0, cell(&h, b).center().y); + let from = cell(&h, e).center(); + drag(&mut h, from, to); + assert_eq!(hint(&h).as_deref(), Some("Move to this burst")); + release(&mut h, to); + assert_eq!(h.app.session.catalog.burst(1), vec![a, e, b, c]); + assert!(h.app.session.catalog.burst(2).is_empty() && group(&h, d).is_none()); + h.step(); + // d dragged from the grid onto burst 1's title goes last + let title = widget(&h, "burst:1").center(); + let from = widget(&h, &format!("thumb:{}", d.0)).center(); + drag(&mut h, from, title); + assert_eq!(hint(&h).as_deref(), Some("Move to this burst")); + release(&mut h, title); + assert_eq!(h.app.session.catalog.burst(1), vec![a, e, b, c, d]); + h.step(); + // b onto New Burst: a burst of its own, which c then joins by its title + let new = widget(&h, "burst:new").center(); + let from = cell(&h, b).center(); + drag(&mut h, from, new); + assert_eq!(hint(&h).as_deref(), Some("New burst")); + release(&mut h, new); + let g = group(&h, b).expect("a new burst"); + assert_eq!(h.app.session.catalog.burst(g), vec![b]); + h.step(); + let to = widget(&h, &format!("burst:{g}")).center(); + let from = cell(&h, c).center(); + drag(&mut h, from, to); + release(&mut h, to); + assert_eq!(h.app.session.catalog.burst(g), vec![b, c]); + h.step(); + // e onto Not in a Burst + let out = widget(&h, "burst:none").center(); + let from = cell(&h, e).center(); + drag(&mut h, from, out); + assert_eq!(hint(&h).as_deref(), Some("Take out of its burst")); + release(&mut h, out); + assert!(group(&h, e).is_none()); + assert_eq!(h.app.session.catalog.burst(1), vec![a, d]); + h.step(); + // a burst dragged by its title onto another merges into it + let to = widget(&h, "burst:1").center(); + let from = widget(&h, &format!("burst:{g}")).center(); + drag(&mut h, from, to); + assert_eq!(hint(&h).as_deref(), Some("Merge into this burst")); + release(&mut h, to); + assert_eq!(h.app.session.catalog.burst(1), vec![a, d, b, c]); + assert!(h.app.session.catalog.burst(g).is_empty()); +} + +#[test] +fn a_photo_never_culled_is_refused() { + let (mut h, [_, _, _, _, _, f]) = app(); + let to = widget(&h, "burst:1").center(); + let from = widget(&h, &format!("thumb:{}", f.0)).center(); + drag(&mut h, from, to); + assert_eq!(hint(&h).as_deref(), Some("Run Assisted Culling on it first")); + let commits = h.app.session.commits(); + release(&mut h, to); + assert_eq!(h.app.session.commits(), commits); + let toast = h.app.ui.toast.as_ref().map(|(t, _, _)| t.clone()).unwrap_or_default(); + assert!(toast.contains("Assisted Culling"), "{toast}"); +} + +/// A burst dragged by its title takes all its photos along, also those the view leaves out. +#[test] +fn a_burst_dragged_by_its_title_takes_its_photos_out_of_view() { + let (mut h, [a, b, c, d, e, _]) = app(); + // only the picks are in view: e (of burst 2) is left out + let r = h.app.session.execute("library.filter", &json!({"ruleSet": {"rules": [{"field": "bestOfGroup", "op": "is", "value": true}]}})).unwrap(); + assert!(r.is_object(), "{r}"); + for _ in 0..4 { + h.step(); + } + assert!(!h.app.session.visible_cloned().contains(&e), "e is out of view"); + let to = widget(&h, "burst:1").center(); + let from = widget(&h, "burst:2").center(); + drag(&mut h, from, to); + assert_eq!(hint(&h).as_deref(), Some("Merge into this burst")); + release(&mut h, to); + assert_eq!(h.app.session.catalog.burst(1), vec![a, b, c, d, e], "e came along"); + assert!(h.app.session.catalog.burst(2).is_empty()); +} + +/// A photo dropped after a shown member lands right after it in the whole burst, before the +/// members the view leaves out, not after them. +#[test] +fn a_drop_after_a_shown_photo_goes_before_the_photos_out_of_view() { + let (mut h, [a, b, c, d, _, _]) = app(); + // only the picks are in view: burst 1 shows a, its b and c are left out + h.app.session.execute("library.filter", &json!({"ruleSet": {"rules": [{"field": "bestOfGroup", "op": "is", "value": true}]}})).unwrap(); + for _ in 0..4 { + h.step(); + } + let to = pos2(cell(&h, a).right() - 4.0, cell(&h, a).center().y); + let from = cell(&h, d).center(); + drag(&mut h, from, to); + assert_eq!(hint(&h).as_deref(), Some("Move to this burst")); + release(&mut h, to); + assert_eq!(h.app.session.catalog.burst(1), vec![a, d, b, c], "right after a, before b and c"); +} + +/// Between two shown photos with one out of view between them, a drop on the left half of the +/// second goes right before it, a drop on the right half of the first right after that one. +#[test] +fn a_drop_keeps_its_side_of_a_photo_out_of_view() { + let (mut h, [a, b, c, d, _, _]) = app(); + // b is left out: burst 1 shows a, c + h.app.session.execute("library.filter", &json!({"ruleSet": {"rules": [{"field": "fileName", "op": "notContains", "value": "b.jpg"}]}})).unwrap(); + for _ in 0..4 { + h.step(); + } + assert!(!h.app.session.visible_cloned().contains(&b)); + let before_c = pos2(cell(&h, c).left() + 4.0, cell(&h, c).center().y); + let from = cell(&h, d).center(); + drag(&mut h, from, before_c); + release(&mut h, before_c); + assert_eq!(h.app.session.catalog.burst(1), vec![a, b, d, c], "right before c"); + h.app.run("edit.undo", json!({})).unwrap(); + for _ in 0..4 { + h.step(); + } + let after_a = pos2(cell(&h, a).right() - 4.0, cell(&h, a).center().y); + let from = cell(&h, d).center(); + drag(&mut h, from, after_a); + release(&mut h, after_a); + assert_eq!(h.app.session.catalog.burst(1), vec![a, d, b, c], "right after a"); +} diff --git a/crates/ui-egui/src/tests/color_mixer.rs b/crates/ui-egui/src/tests/color_mixer.rs new file mode 100644 index 0000000000..132745ccc8 --- /dev/null +++ b/crates/ui-egui/src/tests/color_mixer.rs @@ -0,0 +1,293 @@ +//! The Color Mixer laid out as in Lightroom Classic (item 13 of the evening retest): "Mixer | +//! Point Color" tabs, Adjust HSL / Color, and in HSL the Hue | Saturation | Luminance | All groups +//! of eight colour sliders, each with its targeted adjustment. HSL is the default and the choice +//! is remembered; the sliders are the same `mixer.*` controls. + +use std::time::Duration; + +use serde_json::json; + +use crate::headless::Headless; +use crate::{LightcraftApp, Services}; + +const T: Duration = Duration::from_secs(20); +const SETTLE: Duration = Duration::from_secs(120); +const BANDS: [&str; 8] = ["red", "orange", "yellow", "green", "aqua", "blue", "purple", "magenta"]; + +fn mixer() -> Headless { + let services = Services { png: None, ..Default::default() }; + let app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), services); + let mut h = Headless::new(app, [1300.0, 2600.0], 1.0); + let r = h.request("ui.set", json!({"view": "detail", "right": "edit"}), T); + assert_eq!(r["ok"], true, "{r}"); + run(&mut h, "view.colorMixer", json!({})); + h.settle(SETTLE); + h +} + +fn run(h: &mut Headless, command: &str, params: serde_json::Value) -> serde_json::Value { + let r = h.request("engine.execute", json!({"command": command, "params": params}), T); + assert_eq!(r["ok"], true, "{command}: {r}"); + h.step(); + h.step(); + r["result"].clone() +} + +fn click(h: &mut Headless, id: &str) { + let r = h.request("ui.clickWidget", json!({"id": id}), T); + assert_eq!(r["ok"], true, "{id}: {r}"); + h.step(); + h.step(); +} + +fn has(h: &Headless, id: &str) -> bool { + h.app.widgets.iter().any(|(w, _)| w == id) +} + +fn sliders(h: &Headless, part: &str) -> usize { + BANDS.iter().filter(|b| has(h, &format!("slider:mixer.{b}.{part}"))).count() +} + +#[test] +fn hsl_is_the_default_with_eight_sliders_per_group() { + let mut h = mixer(); + for id in ["button:mixerTab-mixer", "button:mixerTab-point", "button:mixerAdjust-hsl", "button:mixerAdjust-color"] { + assert!(has(&h, id), "{id}"); + } + for g in ["hue", "sat", "lum", "all"] { + assert!(has(&h, &format!("button:mixerGroup-{g}")), "{g}"); + } + assert_eq!((h.app.ui.mixer_adjust.as_str(), h.app.ui.mixer_group.as_str()), ("hsl", "hue"), "HSL, Hue first"); + assert_eq!((sliders(&h, "hue"), sliders(&h, "sat"), sliders(&h, "lum")), (8, 0, 0), "eight Hue sliders"); + assert!(has(&h, "icon:tatMixer-hue"), "with its targeted adjustment"); + click(&mut h, "button:mixerGroup-sat"); + assert_eq!((sliders(&h, "hue"), sliders(&h, "sat"), sliders(&h, "lum")), (0, 8, 0)); + assert!(has(&h, "icon:tatMixer-sat")); + click(&mut h, "button:mixerGroup-lum"); + assert_eq!((sliders(&h, "hue"), sliders(&h, "sat"), sliders(&h, "lum")), (0, 0, 8)); + // All: the three groups stacked, each with a heading and its targeted adjustment + click(&mut h, "button:mixerGroup-all"); + assert_eq!((sliders(&h, "hue"), sliders(&h, "sat"), sliders(&h, "lum")), (8, 8, 8)); + let at = |h: &Headless, id: &str| h.app.widgets.iter().find(|(w, _)| w == id).map(|(_, r)| r.top()).unwrap_or_else(|| panic!("no {id}")); + for g in ["hue", "sat", "lum"] { + assert!(has(&h, &format!("mixerHeading:{g}")) && has(&h, &format!("icon:tatMixer-{g}")), "{g}"); + } + assert!(at(&h, "mixerHeading:hue") < at(&h, "slider:mixer.red.hue")); + assert!(at(&h, "slider:mixer.magenta.hue") < at(&h, "mixerHeading:sat")); + assert!(at(&h, "slider:mixer.magenta.sat") < at(&h, "mixerHeading:lum")); + // a group's targeted adjustment arms its tool + click(&mut h, "icon:tatMixer-sat"); + assert_eq!(h.app.ui.tool, "tat:sat"); +} + +#[test] +fn the_sliders_are_the_mixer_controls() { + let mut h = mixer(); + run(&mut h, "develop.set", json!({"control": "mixer.orange.hue", "value": -30})); + let id = h.app.session.active().expect("a photo"); + assert_eq!(h.app.session.develop_of(id).expect("settings").mixer.orange.hue, -30.0); + // the same value in Color mode, Orange + run(&mut h, "view.colorMixer", json!({"adjust": "color", "band": "orange"})); + h.settle(SETTLE); + assert!(has(&h, "mixerBand:orange"), "the colour dots"); + assert_eq!((sliders(&h, "hue"), sliders(&h, "sat"), sliders(&h, "lum")), (1, 1, 1), "one colour's three sliders"); + assert!(has(&h, "slider:mixer.orange.hue")); +} + +#[test] +fn the_choice_is_remembered_and_point_color_is_a_tab() { + let mut h = mixer(); + click(&mut h, "button:mixerAdjust-color"); + assert_eq!(h.app.ui.mixer_adjust, "color"); + assert!(has(&h, "mixerBand:red")); + // kept with the UI settings (a restart) + let saved = serde_json::to_value(&h.app.ui).expect("ui state"); + let back: crate::UiState = serde_json::from_value(saved).expect("reads back"); + assert_eq!(back.mixer_adjust, "color"); + // older settings without it start in HSL + let old: crate::UiState = serde_json::from_value(json!({})).expect("defaults"); + assert_eq!((old.mixer_tab.as_str(), old.mixer_adjust.as_str(), old.mixer_group.as_str()), ("mixer", "hsl", "hue")); + // Point Color is the second tab + click(&mut h, "button:mixerTab-point"); + assert!(has(&h, "icon:pointColorPicker"), "Point Color's eyedropper"); + assert_eq!(sliders(&h, "hue") + sliders(&h, "sat") + sliders(&h, "lum"), 0); + // the command checks what it is given + let r = h.request("engine.execute", json!({"command": "view.colorMixer", "params": {"group": "chroma"}}), T); + assert_eq!(r["ok"], false, "{r}"); +} + +/// A Color Mixer targeted adjustment whose button the layout no longer shows is put down (it would +/// change a hidden group); the command leaves full-screen preview, where the mixer can't be seen. +#[test] +fn a_hidden_groups_targeted_adjustment_is_put_down_and_the_command_shows_the_mixer() { + let mut h = mixer(); + click(&mut h, "icon:tatMixer-hue"); + assert_eq!(h.app.ui.tool, "tat:hue"); + click(&mut h, "button:mixerGroup-all"); + assert_eq!(h.app.ui.tool, "tat:hue", "All shows the Hue group's button too"); + click(&mut h, "button:mixerGroup-sat"); + assert_eq!(h.app.ui.tool, "", "Saturation hides Hue's"); + click(&mut h, "icon:tatMixer-sat"); + run(&mut h, "view.colorMixer", json!({"adjust": "color"})); + assert_eq!(h.app.ui.tool, "tat:sat", "Color mode shows all three"); + run(&mut h, "view.colorMixer", json!({"tab": "point"})); + assert_eq!(h.app.ui.tool, "", "Point Color shows none"); + h.app.ui.fullscreen = true; + run(&mut h, "view.colorMixer", json!({"tab": "mixer"})); + assert!(!h.app.ui.fullscreen); +} + +/// A B&W photo's mixer shows its B&W mix: Point Color's range view can't stay on the photo. +#[test] +fn point_colors_range_view_is_off_for_a_bw_photo() { + let mut h = mixer(); + run(&mut h, "view.colorMixer", json!({"tab": "point"})); + h.app.ui.point_color_visualize = true; + h.app.ui.point_color = 0; + let id = h.app.session.active().expect("a photo"); + let mut d = (*h.app.session.develop_of(id).expect("settings")).clone(); + d.point_colors.push(Default::default()); + assert!(matches!(crate::panels::detail::view_overlay(&h.app, &d), lightcraft_pipeline::Overlay::PointColorRange(0))); + d.treatment = lightcraft_develop::Treatment::Bw; + assert!(!matches!(crate::panels::detail::view_overlay(&h.app, &d), lightcraft_pipeline::Overlay::PointColorRange(_))); +} + +/// A B&W photo's mixer always shows its Luminance targeted adjustment: the command keeps it. +#[test] +fn a_bw_photos_luminance_targeted_adjustment_stays() { + let mut h = mixer(); + run(&mut h, "develop.treatment", json!({"bw": true})); + h.app.ui.tool = "tat:lum".into(); + run(&mut h, "view.colorMixer", json!({})); + assert_eq!(h.app.ui.tool, "tat:lum"); + h.app.ui.tool = "tat:hue".into(); + run(&mut h, "view.colorMixer", json!({})); + assert_eq!(h.app.ui.tool, "", "no Hue on a B&W photo"); +} + +/// Point Color's picker is put down when its tab is left, so a click on the photo picks no colour. +#[test] +fn point_colors_picker_is_put_down_when_its_tab_is_left() { + let mut h = mixer(); + run(&mut h, "view.colorMixer", json!({"tab": "point"})); + h.app.ui.tool = "pointColor".into(); + run(&mut h, "view.colorMixer", json!({})); + assert_eq!(h.app.ui.tool, "pointColor", "still on its tab"); + run(&mut h, "view.colorMixer", json!({"tab": "mixer"})); + assert_eq!(h.app.ui.tool, "", "the Mixer tab puts it down"); +} + +/// On a B&W photo the command says the layout shown, its B&W mix, not Point Color: the choice of +/// tab is kept for colour photos. +#[test] +fn a_bw_photo_reports_the_mixer_it_shows() { + let mut h = mixer(); + run(&mut h, "develop.treatment", json!({"bw": true})); + let r = run(&mut h, "view.colorMixer", json!({"tab": "point"})); + assert_eq!(r["tab"], "mixer", "{r}"); + assert_eq!(h.app.ui.mixer_tab, "point", "kept for colour photos"); +} + +/// Opening the Color Mixer from Masking puts the Masking colour picker down, so a click on the photo is the Edit +/// panel's again, not a colour sample for a mask. +#[test] +fn the_color_mixer_command_puts_down_the_masking_picker() { + let mut h = mixer(); + let r = h.request("ui.set", json!({"right": "masking"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.app.ui.tool = "colorRange".into(); + run(&mut h, "view.colorMixer", json!({})); + assert_eq!(h.app.ui.tool, "", "the Masking picker is put down"); + // the White Balance picker is the Edit panel's own, and stays + let r = h.request("ui.set", json!({"right": "masking"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.app.ui.tool = "wbPicker".into(); + run(&mut h, "view.colorMixer", json!({})); + assert_eq!(h.app.ui.tool, "wbPicker"); +} + +/// A photo turned B&W while Point Color's picker is out puts the picker down when the panel next shows its B&W +/// mix, so a click on the photo picks no colour. +#[test] +fn point_colors_picker_is_put_down_when_the_photo_turns_bw() { + let mut h = mixer(); + run(&mut h, "view.colorMixer", json!({"tab": "point"})); + h.app.ui.tool = "pointColor".into(); + run(&mut h, "develop.treatment", json!({"bw": true})); + h.settle(SETTLE); + assert_eq!(h.app.ui.tool, "", "no Point Color on a B&W photo"); +} + +/// Another panel's targeted adjustment (Curve's) is put down too when the Color Mixer opens from Masking: only the +/// mixer's own tools stay. +#[test] +fn the_color_mixer_command_puts_down_the_curves_targeted_adjustment() { + let mut h = mixer(); + let r = h.request("ui.set", json!({"right": "masking"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.app.ui.tool = "tat:curve".into(); + run(&mut h, "view.colorMixer", json!({})); + assert_eq!(h.app.ui.tool, ""); +} + +/// The band the command reports is the one the panel shows: a remembered value from before the bands ("hue") +/// shows Red, and the reply can be fed back. +#[test] +fn the_color_mixer_reports_the_band_it_shows() { + let mut h = mixer(); + h.app.ui.mixer_mode = "hue".into(); + let r = run(&mut h, "view.colorMixer", json!({})); + assert_eq!(r["band"], "red", "{r}"); + run(&mut h, "view.colorMixer", json!({"band": r["band"]})); +} + +/// Each HSL slider sets its own band's own adjustment: a drag on a representative band of each group moves that +/// control and no other. +#[test] +fn an_hsl_slider_drag_sets_its_bands_control() { + let mut h = mixer(); + run(&mut h, "view.colorMixer", json!({"adjust": "hsl", "group": "all"})); + h.settle(SETTLE); + let mut moved: Vec = Vec::new(); + for (band, part) in [("red", "hue"), ("blue", "sat"), ("green", "lum")] { + let ctl = format!("mixer.{band}.{part}"); + let r = h.request("ui.dragWidget", json!({"id": format!("slider:{ctl}"), "fx": 0.5, "fy": 0.5, "dx": 40.0, "dy": 0.0, "steps": 8}), T); + assert_eq!(r["ok"], true, "{ctl}: {r}"); + h.settle(SETTLE); + moved.push(ctl.clone()); + let id = h.app.session.active().expect("a photo"); + let d = h.app.session.develop_of(id).expect("settings"); + for b in BANDS { + for p in ["hue", "sat", "lum"] { + let other = format!("mixer.{b}.{p}"); + let v = lightcraft_develop::controls::get(&d, &other).unwrap_or(0.0); + if moved.contains(&other) { + assert!(v > 0.0, "{other} moves with its own slider: {v}"); + } else { + assert_eq!(v, 0.0, "{other} stays when {ctl} is dragged"); + } + } + } + } +} + +/// In Solo Mode the Color Mixer command closes the Light section and its Curve, so the Curve's targeted adjustment +/// is put down; without Solo Mode the Curve stays on screen and keeps it. +#[test] +fn solo_mode_puts_down_the_curves_targeted_adjustment() { + let mut h = mixer(); + // (the Curve on screen: Light open with its Curve flyout, its targeted adjustment picked up) + if !h.app.ui.flyout_open("curve") { + h.app.ui.toggle_flyout("curve"); + } + h.app.ui.tool = "tat:curve".into(); + run(&mut h, "view.colorMixer", json!({})); + assert!(h.app.ui.section_open("light") && h.app.ui.flyout_open("curve"), "the Curve is still shown"); + assert_eq!(h.app.ui.tool, "tat:curve", "and keeps its targeted adjustment"); + // Solo Mode from Light alone: the command opens Color and closes Light + h.app.ui.single_panel = true; + h.app.ui.open_sections = vec!["light".into()]; + run(&mut h, "view.colorMixer", json!({})); + assert_eq!(h.app.ui.open_sections, ["color"], "Solo Mode closes Light"); + assert_eq!(h.app.ui.tool, "", "Solo Mode hides the Curve"); +} diff --git a/crates/ui-egui/src/tests/compare.rs b/crates/ui-egui/src/tests/compare.rs index 23c15efe58..d71c537080 100644 --- a/crates/ui-egui/src/tests/compare.rs +++ b/crates/ui-egui/src/tests/compare.rs @@ -306,7 +306,7 @@ fn compare_zoom_window_tracks_the_zoomed_pane() { photo.height.max(1) as usize, &photo.develop, true, - photo.embedded_lens.as_ref(), + photo.embedded_lens.as_deref(), ); let aspect = frame.aspect() as f32; let native = crate::panels::detail::output_px(&frame); diff --git a/crates/ui-egui/src/tests/dialog_fit.rs b/crates/ui-egui/src/tests/dialog_fit.rs index 4c0147007a..cb392a8473 100644 --- a/crates/ui-egui/src/tests/dialog_fit.rs +++ b/crates/ui-egui/src/tests/dialog_fit.rs @@ -162,3 +162,51 @@ fn gpu_status_never_moves_the_performance_controls() { let first = seen[0].1; assert!(seen.iter().all(|(_, r, _)| *r == first), "the memory buttons moved: {seen:?}"); } + +/// Settings ▸ Performance says where AI masks run and how long the last photo took (issue #932): before the model +/// loads, its two lines are there all the same, at the end of the tab, so nothing above them moves when it loads. +/// The tab is taller than the dialog, so the test scrolls to its foot first, as a user would, and clicks the +/// choice there (a press on a row scrolled out of view is refused, not delivered). +#[test] +fn performance_tab_shows_where_ai_masks_run() { + let mut h = demo([1300.0, 820.0]); + let r = h.request("ui.key", json!({"key": ",", "cmd": true}), T); + assert_eq!(r["ok"], true, "{r}"); + let r = h.request("ui.clickWidget", json!({"id": "button:settingsTab-performance"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + let has = |h: &Headless, id: &str| h.app.widgets.iter().any(|(w, _)| w == id); + if !lightcraft_engine::segment::Segmenter::AVAILABLE { + assert!(!has(&h, "settings:aiMasksDevice"), "a build without AI masks says nothing about them"); + return; + } + // (the AI masks lines end the page, below the room for it: scrolled to its foot) + let r = h.request("ui.hoverWidget", json!({"id": "settings:pageRoom"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.request("ui.scroll", json!({"dy": -5000.0}), T); + h.settle(T); + let room = rect(&h, "settings:pageRoom"); + let (device, time) = (rect(&h, "settings:aiMasksDevice"), rect(&h, "settings:aiMasksTime")); + for (what, r) in [("the choice", rect(&h, "button:settingsAiMasksRunOn-1")), ("the device line", device), ("the time line", time)] { + assert!(room.contains_rect(r), "{what} {r:?} is in view in {room:?}"); + } + assert!(device.bottom() <= time.top() + 1.0, "the device line comes first: {device:?} {time:?}"); + let choice = rect(&h, "button:settingsAiMasksRunOn-1"); + assert!(choice.bottom() <= device.top() + 1.0, "the choice of where they run comes first: {choice:?} {device:?}"); + assert!(rect(&h, "button:settingsMemory-2").bottom() < choice.top(), "after the other performance settings"); + let b = h.app.session.segmenter.backend(); + assert!(b["device"].is_null() && b["encodeMs"].is_null(), "nothing loaded or timed yet: {b}"); + // CPU, then Automatic again: the choice applies at once, and nothing moves + use lightcraft_engine::segment::{CPU_CHOSEN, RunOn}; + for (button, want) in [("button:settingsAiMasksRunOn-1", RunOn::Cpu), ("button:settingsAiMasksRunOn-0", RunOn::Auto)] { + let r = h.request("ui.clickWidget", json!({"id": button}), T); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + h.step(); + assert_eq!(h.app.session.segmenter.run_on(), want); + let fallback = h.app.session.segmenter.backend()["fallback"].clone(); + assert_eq!(fallback == CPU_CHOSEN, want == RunOn::Cpu, "{fallback}"); + // (its text says why it runs on the CPU now, so only its width changes) + assert_eq!(rect(&h, "settings:aiMasksDevice").min, device.min, "the device line stays put"); + } +} diff --git a/crates/ui-egui/src/tests/dialog_settings_filter.rs b/crates/ui-egui/src/tests/dialog_settings_filter.rs new file mode 100644 index 0000000000..1c930399ac --- /dev/null +++ b/crates/ui-egui/src/tests/dialog_settings_filter.rs @@ -0,0 +1,379 @@ +//! Settings has a filter: typing in it lists the sections, on whatever tab, whose words match, and +//! choosing one opens its tab at that section. +//! +//! Before, finding a setting meant knowing or guessing its tab: eight of them, each read through. + +use std::time::Duration; + +use serde_json::json; + +use crate::headless::Headless; +use crate::state::Dialog; +use crate::{LightcraftApp, Services}; + +const T: Duration = Duration::from_secs(20); + +fn demo(size: [f32; 2]) -> Headless { + let mut h = Headless::new(LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services::default()), size, 1.0); + // let the first renders finish (a render still running at exit can crash in GPU teardown) + h.settle(T); + h +} + +fn steps(h: &mut Headless) { + for _ in 0..4 { + h.step(); + } +} + +fn show(h: &mut Headless, tab: &str) { + let r = h.request("engine.execute", json!({"command": "app.settings", "params": {"tab": tab}}), T); + assert_eq!(r["ok"], true, "app.settings {tab}: {r}"); + h.settle(T); + steps(h); +} + +fn click(h: &mut Headless, id: &str) { + let r = h.request("ui.clickWidget", json!({"id": id}), T); + assert_eq!(r["ok"], true, "click {id}: {r}"); + steps(h); +} + +fn key(h: &mut Headless, key: &str) { + assert_eq!(h.request("ui.key", json!({"key": key}), T)["ok"], true, "{key}"); + steps(h); +} + +/// Given the filter with `text` typed into it. +fn filter(h: &mut Headless, text: &str) { + click(h, "field:settingsFilter"); + h.request("ui.key", json!({"key": "A", "cmd": true}), T); + h.request("ui.text", json!({"text": text}), T); + steps(h); +} + +fn rect(h: &Headless, id: &str) -> Option { + h.app.widgets.iter().find(|(w, _)| w == id).map(|(_, r)| *r) +} + +/// What the filter lists, top to bottom: `tab:section` of each result (`settingsFound:{tab}:{section}`). +fn found(h: &Headless) -> Vec { + let mut found: Vec<(f32, String)> = + h.app.widgets.iter().filter_map(|(id, r)| Some((r.top(), id.strip_prefix("settingsFound:")?.to_string()))).collect(); + found.sort_by(|a, b| a.0.total_cmp(&b.0)); + found.into_iter().map(|(_, id)| id).collect() +} + +fn headings(h: &Headless) -> Vec { + h.app.widgets.iter().filter_map(|(id, _)| Some(id.strip_prefix("heading:")?.to_string())).collect() +} + +/// Whether the keyboard focus is on something other than the filter box. +fn on_a_result(h: &Headless) -> bool { + h.view.ctx.memory(|m| m.focused()).is_some() && !crate::text_field::focused(&h.view.ctx, "field:settingsFilter") +} + +fn says(h: &Headless, part: &str) -> bool { + h.painted_text().iter().any(|text| text.contains(part)) +} + +#[test] +fn typing_lists_the_sections_that_match_on_whatever_tab() { + let mut h = demo([1200.0, 1000.0]); + // Given Settings open on General, which has nothing about sidecars (they are on Import) + show(&mut h, "general"); + // When "sidecar names" is typed into the filter + filter(&mut h, "sidecar names"); + // Then the section about them is listed with the tab it is on, and the page of General is not shown + assert_eq!(found(&h), ["import:XMP sidecars"]); + assert!(says(&h, "Import") && says(&h, "XMP sidecars")); + assert!(headings(&h).is_empty(), "the tab's own page gives way to what was found: {:?}", headings(&h)); + // And the tab that was open is still the one open + assert_eq!(h.app.ui.dialog, Some(Dialog::Settings { tab: "general".into() })); +} + +#[test] +fn a_word_from_a_row_a_hint_or_a_button_finds_its_section() { + let mut h = demo([1200.0, 1000.0]); + show(&mut h, "general"); + // (a row's label) + filter(&mut h, "Forget unchanged"); + assert_eq!(found(&h), ["performance:Local folders"]); + // (a button) + filter(&mut h, "Clear Cache"); + assert_eq!(found(&h), ["performance:Preview cache"]); + // (a hint, in other letter case) + filter(&mut h, "CHOOSES THE LINES"); + assert_eq!(found(&h), ["interface:Detail View"]); + // (a tab's own name finds everything on it) + filter(&mut h, "Interface"); + let on_the_tab = found(&h); + assert!(on_the_tab.len() >= 4 && on_the_tab.iter().all(|id| id.starts_with("interface:")), "{on_the_tab:?}"); + assert!(on_the_tab.contains(&"interface:Filmstrip".to_string()), "a section that does not say the word itself: {on_the_tab:?}"); +} + +#[test] +fn every_word_typed_has_to_be_there() { + let mut h = demo([1200.0, 1000.0]); + show(&mut h, "general"); + filter(&mut h, "cache"); + let cache = found(&h); + assert!(cache.len() > 1 && cache.contains(&"performance:Preview cache".to_string()), "{cache:?}"); + // When a second word narrows it + filter(&mut h, "cache disk"); + assert_eq!(found(&h), ["performance:Preview cache"]); + // And the words can come in any order + filter(&mut h, "disk cache"); + assert_eq!(found(&h), ["performance:Preview cache"]); +} + +#[test] +fn nothing_found_says_so() { + let mut h = demo([1200.0, 1000.0]); + show(&mut h, "general"); + filter(&mut h, "zebra crossing"); + assert!(found(&h).is_empty()); + assert!(says(&h, "No setting matches"), "{:?}", h.painted_text().iter().filter(|t| t.contains("match")).collect::>()); + assert!(headings(&h).is_empty()); +} + +/// Reading every page for the filter shows nothing of it, so it must not start the slide preview's render (the Slideshow +/// page asks for it when it is open, which a filter on another tab is not). +#[test] +fn typing_in_the_filter_starts_no_slide_preview_render() { + let mut h = demo([1200.0, 1000.0]); + show(&mut h, "general"); + assert!(h.app.session.active().is_some(), "a photo is active, so the preview would have one to render"); + assert_eq!(h.app.renderer.wanted(crate::render::Slot::SlidePreview), None, "none before"); + filter(&mut h, "sidecar names"); + assert_eq!(found(&h), ["import:XMP sidecars"]); + h.settle(T); + assert_eq!(h.app.renderer.wanted(crate::render::Slot::SlidePreview), None, "the filter asked for no render of the slide preview"); +} + +#[test] +fn choosing_a_result_opens_its_tab_at_that_section() { + // (a window short enough that Detail View, near the foot of Interface, is below the fold) + let mut h = demo([900.0, 560.0]); + // Given Detail View below the fold of Interface + show(&mut h, "interface"); + let (detail, room) = (rect(&h, "heading:Detail View").unwrap(), rect(&h, "settings:pageRoom").unwrap()); + assert!(detail.bottom() > room.bottom(), "Detail View {detail:?} starts out of view in {room:?}"); + show(&mut h, "general"); + filter(&mut h, "info overlay"); + assert_eq!(found(&h), ["interface:Detail View"]); + // When the result is clicked + click(&mut h, "settingsFound:interface:Detail View"); + h.settle(T); + steps(&mut h); + // Then its tab is open, the filter is empty again, and the section is in view + assert_eq!(h.app.ui.dialog, Some(Dialog::Settings { tab: "interface".into() })); + assert!(found(&h).is_empty() && !says(&h, "info overlay"), "the filter is cleared"); + let (detail, room) = (rect(&h, "heading:Detail View").unwrap(), rect(&h, "settings:pageRoom").unwrap()); + assert!(detail.top() >= room.top() - 0.5 && detail.bottom() <= room.bottom() + 0.5, "Detail View {detail:?} is in view in {room:?}"); +} + +#[test] +fn choosing_what_starts_a_tab_shows_the_top_of_its_page() { + let mut h = demo([900.0, 560.0]); + // Given General scrolled down, so that its first heading is out of view + show(&mut h, "general"); + let room = rect(&h, "settings:pageRoom").unwrap(); + h.request("ui.move", json!({"x": room.center().x, "y": room.center().y}), T); + h.request("ui.scroll", json!({"dy": -300.0}), T); + for _ in 0..60 { + h.step(); + } + assert!(rect(&h, "heading:Library").unwrap().top() < room.top(), "General is scrolled down"); + // When what is above its first heading (the language) is found and chosen + filter(&mut h, "language"); + assert!(found(&h).contains(&"general:".to_string()), "{:?}", found(&h)); + click(&mut h, "settingsFound:general:"); + h.settle(T); + for _ in 0..60 { + h.step(); + } + // Then the page is at its top again + assert!(rect(&h, "heading:Library").unwrap().top() >= room.top() - 0.5, "the top of General is in view"); +} + +#[test] +fn return_opens_the_first_result() { + let mut h = demo([1200.0, 1000.0]); + show(&mut h, "general"); + filter(&mut h, "sidecar names"); + key(&mut h, "Enter"); + h.settle(T); + steps(&mut h); + assert_eq!(h.app.ui.dialog, Some(Dialog::Settings { tab: "import".into() })); + assert!(headings(&h).contains(&"XMP sidecars".to_string())); + assert!(found(&h).is_empty()); +} + +#[test] +fn esc_empties_the_filter_and_a_second_esc_closes_settings() { + let mut h = demo([1200.0, 1000.0]); + show(&mut h, "import"); + filter(&mut h, "sidecar names"); + assert_eq!(found(&h).len(), 1); + // When Esc is pressed + key(&mut h, "Escape"); + // Then the filter is empty, the tab that was open shows its page again, and Settings is open + assert!(found(&h).is_empty()); + assert_eq!(h.app.ui.dialog, Some(Dialog::Settings { tab: "import".into() })); + assert!(headings(&h).contains(&"Raw defaults".to_string())); + // And a second Esc closes Settings + key(&mut h, "Escape"); + assert!(h.app.ui.dialog.is_none()); +} + +#[test] +fn opening_a_tab_empties_the_filter() { + let mut h = demo([1200.0, 1000.0]); + show(&mut h, "general"); + filter(&mut h, "sidecar names"); + click(&mut h, "button:settingsTab-performance"); + assert_eq!(h.app.ui.dialog, Some(Dialog::Settings { tab: "performance".into() })); + assert!(found(&h).is_empty()); + assert!(headings(&h).contains(&"Rendering".to_string()), "Performance shows its page"); +} + +#[test] +fn looking_through_the_tabs_changes_nothing_and_leaves_no_double_names() { + let mut h = demo([1200.0, 1000.0]); + show(&mut h, "general"); + // (what Settings sets: the app's own settings, the language, and what is saved with the library) + let state = |h: &mut Headless| { + ( + serde_json::to_value(&h.app.ui.settings).unwrap(), + h.app.ui.language, + h.app.ui.auto_advance, + h.app.run("library.preferences", json!({})).unwrap(), + h.app.run("library.xmpPreferences", json!({})).unwrap(), + h.app.ui.dialog.clone(), + ) + }; + let before = state(&mut h); + h.app.ui.toast = None; + filter(&mut h, "cache"); + // Then nothing changed by being looked through, and nothing was said + assert_eq!(state(&mut h), before); + assert!(h.app.ui.toast.is_none(), "{:?}", h.app.ui.toast); + // And no control of a tab that is not shown is among the widgets scripts can click + let mut ids: Vec<&String> = h.app.widgets.iter().map(|(id, _)| id).collect(); + assert!(!ids.iter().any(|id| id.as_str() == "button:settingsClearCache"), "a tab looked through off screen leaves no widgets behind"); + let all = ids.len(); + ids.sort(); + ids.dedup(); + assert_eq!(ids.len(), all, "no widget is named twice"); +} + +#[test] +fn the_filter_is_empty_when_settings_is_opened_again() { + let mut h = demo([1200.0, 1000.0]); + show(&mut h, "general"); + filter(&mut h, "sidecar names"); + // (Esc once empties it; here Settings is closed from outside with the filter still set) + h.app.ui.dialog = None; + steps(&mut h); + show(&mut h, "general"); + assert!(found(&h).is_empty() && !says(&h, "sidecar names")); + assert!(headings(&h).contains(&"Startup".to_string())); +} + +#[test] +fn what_a_page_shows_now_is_what_is_found() { + let mut h = demo([1200.0, 1000.0]); + show(&mut h, "import"); + // Given a sentence Import only shows with camera-specific defaults on, looked for and not found + filter(&mut h, "cameras appear"); + assert!(found(&h).is_empty()); + key(&mut h, "Escape"); + // When that is turned on, with Settings still open + click(&mut h, "check:settings.perCamera"); + assert!(says(&h, "cameras appear"), "the page shows the sentence now"); + // Then looking for it again finds it: the pages are read afresh each time the filter is used + filter(&mut h, "cameras appear"); + assert_eq!(found(&h), ["import:Raw defaults"]); +} + +#[test] +fn the_arrow_goes_from_the_filter_to_what_was_found_and_return_opens_it() { + let mut h = demo([1200.0, 1000.0]); + show(&mut h, "general"); + filter(&mut h, "cache disk"); + assert_eq!(found(&h), ["performance:Preview cache"]); + // When ↓ is pressed in the filter (the focus goes to the first result), then Return + key(&mut h, "ArrowDown"); + assert!(on_a_result(&h), "↓ leaves the filter for what was found"); + key(&mut h, "Enter"); + h.settle(T); + steps(&mut h); + // Then the section found is open + assert_eq!(h.app.ui.dialog, Some(Dialog::Settings { tab: "performance".into() })); + assert!(found(&h).is_empty()); +} + +#[test] +fn esc_on_a_result_empties_the_filter_and_leaves_settings_open() { + let mut h = demo([1200.0, 1000.0]); + show(&mut h, "import"); + filter(&mut h, "cache"); + assert!(!found(&h).is_empty()); + // Given the focus on a result, not in the filter + key(&mut h, "ArrowDown"); + assert!(on_a_result(&h)); + // When Esc is pressed + key(&mut h, "Escape"); + // Then the filter is emptied and Settings is still open on the tab it was on + assert_eq!(h.app.ui.dialog, Some(Dialog::Settings { tab: "import".into() })); + assert!(found(&h).is_empty() && headings(&h).contains(&"Raw defaults".to_string())); + // And the next Esc closes Settings + key(&mut h, "Escape"); + assert!(h.app.ui.dialog.is_none()); +} + +/// A section's heading goes in by its English name and is translated once: View Options' General +/// heading used to be passed already translated, so in another language it was translated again +/// and registered under the translated name, where the filter and scripts look for the English one. +#[test] +fn the_general_heading_of_view_options_is_translated_once_and_registered_by_its_english_name() { + use crate::i18n::Locale; + struct Restore(Locale); + impl Drop for Restore { + fn drop(&mut self) { + crate::i18n::set_language(self.0); + } + } + let _restore = Restore(crate::i18n::language()); + let mut h = demo([1000.0, 800.0]); + h.app.ui.language = Locale::De; + crate::i18n::set_language(Locale::De); + h.app.ui.dialog = Some(Dialog::ViewOptions); + steps(&mut h); + let shown = Locale::De.tr("General"); + assert_ne!(shown, "General", "the German catalog translates the heading"); + let headings: Vec<&str> = h.app.widgets.iter().filter_map(|(id, _)| id.strip_prefix("heading:")).collect(); + assert!(headings.contains(&"General"), "registered by its English name: {headings:?}"); + assert!(!headings.contains(&shown), "not by the translated one: {headings:?}"); + assert!(h.painted_text().iter().any(|text| text == shown), "and drawn translated: {shown}"); +} + +/// The Display page reads the profile in use, so the sections read for the filter are read again +/// when it changes (the window moved to another screen), with the filter still set. +#[test] +fn a_changed_display_profile_is_read_again_while_the_filter_has_text() { + let mut h = demo([1200.0, 1000.0]); + show(&mut h, "general"); + // Given the page's sentence about no profile, found + filter(&mut h, "treated as sRGB"); + assert!(!found(&h).is_empty(), "no display profile: the page says so"); + // When a profile is in use from now on, the filter still holding its text + let p3 = + lightcraft_engine::display::Display::from_bytes("p3.icc", &lightcraft_codecs::icc::write_named(lightcraft_codecs::NamedSpace::DisplayP3)) + .unwrap(); + h.app.renderer.set_display(Some(std::sync::Arc::new(p3))); + steps(&mut h); + // Then the old sentence is not found any more + assert!(found(&h).is_empty(), "the sections were read for the old profile: {:?}", found(&h)); +} diff --git a/crates/ui-egui/src/tests/dialogs.rs b/crates/ui-egui/src/tests/dialogs.rs index df220b3ab6..265efaf5cb 100644 --- a/crates/ui-egui/src/tests/dialogs.rs +++ b/crates/ui-egui/src/tests/dialogs.rs @@ -189,6 +189,79 @@ fn a_click_outside_an_open_dropdown_keeps_the_dialog() { assert!(h.app.ui.dialog.is_some(), "but not the dialog"); } +#[test] +fn export_subfolder_variable_dropdown() { + let mut h = demo([1400.0, 1000.0], json!({"view": "detail", "right": "edit"})); + h.app.run("dialog.export", json!({})).unwrap(); + h.step(); + h.step(); + let r = h.request("ui.clickWidget", json!({"id": "combo:exportSubfolderTags"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + assert!(crate::dialogs::popup_open(&h.view.ctx), "the subfolder tags dropdown is open"); + + // Read the production Export dialog's tree, not an unrelated legacy combo fixture. + h.view.ctx.enable_accesskit(); + let ctx = h.view.ctx.clone(); + let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 1000.0))), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| h.app.ui(ui)); + out.textures_delta.clear(); + let update = out.platform_output.accesskit_update.expect("AccessKit update produced"); + let has_combo = update.nodes.iter().any(|(_, n)| format!("{:?}", n.role()) == "ComboBox" && n.label().unwrap_or_default() == "Insert variable"); + assert!(has_combo, "production ComboBox has localized accessible name 'Insert variable'"); + + // Escape dismisses only the picker; Enter then chooses its first variable. + assert_eq!(h.request("ui.key", json!({"key": "Escape"}), T)["ok"], true); + h.step(); + h.step(); + assert!(!crate::dialogs::popup_open(&h.view.ctx)); + assert!(matches!(h.app.ui.dialog, Some(crate::state::Dialog::Export { .. }))); + let r = h.request("ui.clickWidget", json!({"id": "combo:exportSubfolderTags"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + assert!(crate::dialogs::popup_open(&h.view.ctx)); + assert_eq!(h.request("ui.key", json!({"key": "Enter"}), T)["ok"], true); + h.step(); + h.step(); + let Some(crate::state::Dialog::Export { opts, .. }) = &h.app.ui.dialog else { panic!("export dialog remains open") }; + assert!(opts.subfolder.contains("{album}"), "Enter inserts the first variable through the production picker"); + + // Test text insertion and cursor behavior for subfolder field + let subfolder_id = crate::text_field::id("field:exportSubfolder"); + let text_part = crate::text_field::text_id(subfolder_id); + let mut text = String::from("prefix_suffix"); + // Place cursor at index 7 (after "prefix_") + let mut state = egui::text_edit::TextEditState::default(); + state.cursor.set_char_range(Some(egui::text::CCursorRange::one(egui::text::CCursor::new(7)))); + state.store(&h.view.ctx, text_part); + + // Insert {date} at non-terminal cursor + crate::import::insert_at_cursor(&h.view.ctx, subfolder_id, &mut text, "{date}"); + assert_eq!(text, "prefix_{date}suffix"); + let loaded = egui::text_edit::TextEditState::load(&h.view.ctx, text_part).unwrap(); + assert_eq!(loaded.cursor.char_range().unwrap().primary.index.0, 7 + "{date}".chars().count()); + + // Replace selected range with {album} + let mut state = egui::text_edit::TextEditState::default(); + state + .cursor + .set_char_range(Some(egui::text::CCursorRange::two(egui::text::CCursor::new(7), egui::text::CCursor::new(7 + "{date}".chars().count())))); + state.store(&h.view.ctx, text_part); + crate::import::insert_at_cursor(&h.view.ctx, subfolder_id, &mut text, "{album}"); + assert_eq!(text, "prefix_{album}suffix"); + let loaded = egui::text_edit::TextEditState::load(&h.view.ctx, text_part).unwrap(); + assert_eq!(loaded.cursor.char_range().unwrap().primary.index.0, 7 + "{album}".chars().count()); + + // Replace selection with {hour} + let mut state = egui::text_edit::TextEditState::default(); + state + .cursor + .set_char_range(Some(egui::text::CCursorRange::two(egui::text::CCursor::new(7), egui::text::CCursor::new(7 + "{album}".chars().count())))); + state.store(&h.view.ctx, text_part); + crate::import::insert_at_cursor(&h.view.ctx, subfolder_id, &mut text, "{hour}"); + assert_eq!(text, "prefix_{hour}suffix"); +} + #[test] fn modal_dialogs_close_background_menus() { let mut h = demo([1400.0, 1000.0], json!({"view": "detail", "right": "edit"})); diff --git a/crates/ui-egui/src/tests/docking_acceptance.rs b/crates/ui-egui/src/tests/docking_acceptance.rs index 4618fa3279..825fa75b88 100644 --- a/crates/ui-egui/src/tests/docking_acceptance.rs +++ b/crates/ui-egui/src/tests/docking_acceptance.rs @@ -97,6 +97,16 @@ fn window_menu_reopens_closed_panels_in_their_dock_columns() { assert_eq!(crate::docking::columns(h.app.ui.docking.as_ref().unwrap(), Side::Start), [(width, vec![vec![Panel::Library]])]); } +#[test] +fn the_color_mixer_command_brings_tools_forward() { + let mut h = app(); + dock(&mut h, json!({"operation":"move","panel":"tools","target":"library","zone":"center"})); + dock(&mut h, json!({"operation":"activate","panel":"library"})); + assert!(!crate::docking::exposed_in(h.app.ui.docking.as_ref().unwrap(), Panel::Tools)); + h.app.run("view.colorMixer", json!({})).unwrap(); + assert!(crate::docking::exposed_in(h.app.ui.docking.as_ref().unwrap(), Panel::Tools), "the mixer is shown, not left behind Library"); +} + #[test] fn inactive_same_mode_commands_reveal_without_closing_or_editing() { let mut h = app(); @@ -228,6 +238,7 @@ fn dock_tab_keeps_activation_keys_and_global_command_remains_reachable() { h.view.ctx.enable_accesskit(); h.app.run("app.setShortcut", json!({"id":"panel.crop","shortcut":"K"})).unwrap(); dock(&mut h, json!({"operation":"move","panel":"tools","target":"library","zone":"center"})); + let before = h.app.ui.right; h.app.run("panel.crop", json!({})).unwrap(); h.step(); h.step(); @@ -251,7 +262,9 @@ fn dock_tab_keeps_activation_keys_and_global_command_remains_reachable() { key(&mut h, egui::Key::Enter); assert_eq!(h.app.ui.right, RightPanel::Crop, "Enter activates the tab without tool.done"); key(&mut h, egui::Key::K); - assert_eq!(h.app.ui.right, RightPanel::None, "the global crop toggle is reachable from tab focus"); + // toggled off, Crop gives back the panel it took the place of (KEY-INFO / UiState::toggle_panel) + assert_eq!(h.app.ui.right, before, "the global crop toggle is reachable from tab focus"); + assert_ne!(before, RightPanel::Crop); } #[test] diff --git a/crates/ui-egui/src/tests/drag_contract.rs b/crates/ui-egui/src/tests/drag_contract.rs new file mode 100644 index 0000000000..8c2fa24a27 --- /dev/null +++ b/crates/ui-egui/src/tests/drag_contract.rs @@ -0,0 +1,447 @@ +//! What a drag of photos (or a keyword) promises: Esc gives it up and does nothing else, every row +//! it passes over says what a drop would do, a drop that would do nothing does nothing (no undo +//! step, no toast), and a row that can't take it shows so (the not-allowed cursor and a reason). + +use std::time::Duration; + +use egui::{Pos2, Rect}; +use serde_json::json; + +use crate::headless::Headless; +use crate::{LightcraftApp, Services}; + +const T: Duration = Duration::from_secs(20); +const SETTLE: Duration = Duration::from_secs(120); + +/// The demo library in the grid with the sidebar's Albums and Keywords and the Keyword List open, +/// in a window tall enough for every row to be on screen. +fn app() -> Headless { + let services = Services { png: None, ..Default::default() }; + let mut h = Headless::new(LightcraftApp::new(lightcraft_engine::Session::with_demo(), services), [1600.0, 2600.0], 1.0); + let hidden = |id: &str| json!({"id": id, "hidden": true}); + let r = h.request( + "ui.set", + json!({ + "view": "photoGrid", "leftPanel": true, "right": "keywords", + "sidebar": ["albums", "keywords", hidden("local"), hidden("byDate"), hidden("folders")], + }), + T, + ); + assert_eq!(r["ok"], true, "{r}"); + h.settle(SETTLE); + h +} + +fn run(h: &mut Headless, command: &str, params: serde_json::Value) -> serde_json::Value { + let r = h.request("engine.execute", json!({"command": command, "params": params}), T); + assert_eq!(r["ok"], true, "{command}: {r}"); + h.settle(SETTLE); + r["result"].clone() +} + +fn widget(h: &Headless, id: &str) -> Rect { + h.app.widgets.iter().find(|(w, _)| w == id).map(|(_, r)| *r).unwrap_or_else(|| panic!("no widget {id}")) +} + +fn pointer(h: &mut Headless, at: Pos2, pressed: Option) { + h.events.push(egui::Event::PointerMoved(at)); + if let Some(pressed) = pressed { + h.events.push(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }); + } + h.step(); +} + +/// Press on `from`, then move to `to` over a few frames, holding. +fn hold(h: &mut Headless, from: Pos2, to: Pos2) { + pointer(h, from, Some(true)); + for i in 1..=8 { + pointer(h, from + (to - from) * (i as f32 / 8.0), None); + } + // a few more, so what a row says about the drop has settled + h.step(); + h.step(); +} + +fn release(h: &mut Headless, at: Pos2) { + pointer(h, at, Some(false)); + // (not settled: a toast lapses with the frames) + h.step(); + h.step(); +} + +fn esc(h: &mut Headless) { + h.events.push(egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }); + h.step(); + h.events.push(egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: false, repeat: false, modifiers: egui::Modifiers::NONE }); + h.step(); +} + +/// What the dragged label says this frame instead of the count, if a drop target set it. +fn hint(h: &Headless) -> Option { + // (only the frame just run: `step` leaves the counter at the next one) + let frame = h.view.ctx.cumulative_frame_nr(); + h.view + .ctx + .data(|d| d.get_temp::<(u64, String)>(egui::Id::unique("drag-photos-hint"))) + .filter(|(f, _)| frame.saturating_sub(*f) <= 1) + .map(|(_, text)| text) +} + +fn toast(h: &Headless) -> String { + h.app.ui.toast.clone().map(|t| t.0).unwrap_or_default() +} + +fn select(h: &mut Headless, ids: &[u64]) { + run(h, "library.select", json!({"ids": ids})); +} + +fn members(h: &Headless, album: u64) -> Vec { + h.app.session.catalog.album(lightcraft_catalog::AlbumId(album)).map(|a| a.photos.iter().map(|p| p.0).collect()).unwrap_or_default() +} + +fn keywords_of(h: &Headless, id: u64) -> Vec { + h.app.session.catalog.photo(lightcraft_catalog::PhotoId(id)).map(|p| p.meta.keywords.clone()).unwrap_or_default() +} + +/// Two photos of the grid that are not in `album`, and one that is. +fn photos_around(h: &mut Headless, album: u64) -> (Vec, u64) { + let held = members(h, album); + let shown: Vec = h.app.session.visible_cloned().iter().map(|p| p.0).collect(); + let outside: Vec = shown.iter().copied().filter(|id| !held.contains(id)).take(2).collect(); + let inside = *held.iter().find(|id| shown.contains(id)).expect("the album holds a photo the grid shows"); + (outside, inside) +} + +const GARDEN: u64 = 6; + +/// Drag the selection `ids` from its first photo to `to`, still holding. +fn drag_photos(h: &mut Headless, ids: &[u64], to: &str) -> Pos2 { + select(h, ids); + let from = widget(h, &format!("thumb:{}", ids[0])).center(); + let target = widget(h, to).center(); + hold(h, from, target); + assert_eq!(h.app.ui.dragging_photos.as_deref(), Some(ids), "the photos are being dragged"); + target +} + +#[test] +fn esc_gives_up_a_photo_drag_and_does_nothing_else() { + let mut h = app(); + let (outside, _) = photos_around(&mut h, GARDEN); + // Esc's own command (Back: lights out → on) is something the drag must not also trigger + h.app.ui.lights_out = crate::state::LightsOut::Dim; + let before = members(&h, GARDEN); + let undo = h.app.session.undo.len(); + let target = drag_photos(&mut h, &outside, &format!("source:album:{GARDEN}")); + esc(&mut h); + assert_eq!(h.app.ui.dragging_photos, None, "given up"); + assert_eq!(h.app.ui.lights_out, crate::state::LightsOut::Dim, "Esc only gave up the drag"); + assert_eq!(h.app.session.selection.ids.iter().map(|p| p.0).collect::>(), outside, "the selection stays"); + // let go over the album afterwards: nothing is added + release(&mut h, target); + assert_eq!(members(&h, GARDEN), before); + assert_eq!(h.app.session.undo.len(), undo); + assert_eq!(toast(&h), ""); +} + +/// A headless screenshot draws the UI in an offscreen context that has no pointer: it must not +/// give up the drag the window is holding. +#[test] +fn a_headless_screenshot_during_a_drag_leaves_the_drag() { + let mut h = app(); + let (outside, _) = photos_around(&mut h, GARDEN); + drag_photos(&mut h, &outside, &format!("source:album:{GARDEN}")); + let main = h.view.ctx.clone(); + h.app.headless_screenshot(&main, false); + assert_eq!(h.app.ui.dragging_photos.as_deref(), Some(&outside[..]), "the window's drag goes on"); +} + +/// The sidebar mirrors a framework drag session; the shadow's runtime must not clear the +/// window's adopted drag just because the offscreen pass has no pointer. +#[test] +fn a_headless_screenshot_during_a_framework_album_drag_leaves_the_drag() { + let mut h = app(); + let from = widget(&h, &format!("source:album:{GARDEN}")).center(); + hold(&mut h, from, from + egui::vec2(0.0, 40.0)); + assert_eq!(h.app.ui.dragging_album, Some(GARDEN)); + let main = h.view.ctx.clone(); + h.app.headless_screenshot(&main, false); + assert_eq!(h.app.ui.dragging_album, Some(GARDEN), "the shadow does not retire the sidebar drag"); + release(&mut h, from); + assert_eq!(h.app.ui.dragging_album, None, "the live window still ends the drag"); +} + +/// Esc and the button's release in one frame: the drag is given up, and Esc's own command (Back) +/// doesn't also run. +#[test] +fn esc_on_the_frame_the_button_is_released_only_gives_up_the_drag() { + let mut h = app(); + let (outside, _) = photos_around(&mut h, GARDEN); + h.app.ui.lights_out = crate::state::LightsOut::Dim; + let target = drag_photos(&mut h, &outside, &format!("source:album:{GARDEN}")); + let before = members(&h, GARDEN); + h.events.push(egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }); + h.events.push(egui::Event::PointerButton { pos: target, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }); + h.step(); + h.step(); + assert_eq!(h.app.ui.dragging_photos, None, "the drag is over"); + assert_eq!(h.app.ui.lights_out, crate::state::LightsOut::Dim, "Esc only gave up the drag"); + assert_eq!(members(&h, GARDEN), before, "Esc beat the release: nothing was added"); +} + +#[test] +fn esc_only_gives_up_an_album_or_keyword_drag() { + let mut h = app(); + h.app.ui.lights_out = crate::state::LightsOut::Dim; + // an album dragged in the sidebar + let from = widget(&h, &format!("source:album:{GARDEN}")).center(); + hold(&mut h, from, from + egui::vec2(0.0, 40.0)); + assert_eq!(h.app.ui.dragging_album, Some(GARDEN), "dragging an album"); + esc(&mut h); + assert_eq!(h.app.ui.dragging_album, None); + assert_eq!(h.app.ui.lights_out, crate::state::LightsOut::Dim, "an album drag's Esc is its own"); + release(&mut h, from); + // a keyword dragged in the Keyword List + let from = widget(&h, "keywordRow:mountains").center(); + hold(&mut h, from, from + egui::vec2(0.0, 40.0)); + assert_eq!(h.app.ui.dragging_keyword.as_deref(), Some("mountains")); + esc(&mut h); + assert_eq!(h.app.ui.dragging_keyword, None); + assert_eq!(h.app.ui.lights_out, crate::state::LightsOut::Dim, "a keyword drag's Esc is its own"); + release(&mut h, from); + // and with nothing dragged, Esc does what it did + esc(&mut h); + assert_eq!(h.app.ui.lights_out, crate::state::LightsOut::On); +} + +fn key(h: &mut Headless, key: egui::Key) { + for pressed in [true, false] { + h.events.push(egui::Event::Key { key, physical_key: None, pressed, repeat: false, modifiers: egui::Modifiers::NONE }); + h.step(); + } +} + +#[test] +fn a_drag_started_before_full_screen_ends_with_the_button_and_esc_leaves() { + let mut h = app(); + let (outside, _) = photos_around(&mut h, GARDEN); + let target = drag_photos(&mut h, &outside, &format!("source:album:{GARDEN}")); + // F while the button is still held: the layout that runs the drag's feedback is gone + key(&mut h, egui::Key::F); + assert!(h.app.ui.fullscreen, "F opened the full-screen preview"); + release(&mut h, target); + assert_eq!(h.app.ui.dragging_photos, None, "the drag ended with the button"); + key(&mut h, egui::Key::Escape); + assert!(!h.app.ui.fullscreen, "Esc leaves full screen"); +} + +/// In full screen no drop target reads the release, so the release frame ends the drag itself rather +/// than leaving it standing for one more frame (where the shortcuts no longer hold Esc back for it). +#[test] +fn esc_the_frame_after_a_release_in_full_screen_leaves_full_screen() { + let mut h = app(); + let (outside, _) = photos_around(&mut h, GARDEN); + let target = drag_photos(&mut h, &outside, &format!("source:album:{GARDEN}")); + key(&mut h, egui::Key::F); + assert!(h.app.ui.fullscreen, "F opened the full-screen preview"); + pointer(&mut h, target, Some(false)); + assert_eq!(h.app.ui.dragging_photos, None, "the release frame ended the drag"); + key(&mut h, egui::Key::Escape); + assert!(!h.app.ui.fullscreen, "and Esc then leaves full screen"); +} + +/// A right-button release over a row that refuses photos (a smart album, an album folder, a keyword +/// row) is not the drop the primary button's release is: no refusal is said. (Whether the drag itself +/// goes on after that release is the grid's `drag_feedback`, not this row's.) +#[test] +fn a_right_button_release_over_a_refusing_row_says_nothing() { + let mut h = app(); + let smart = run(&mut h, "album.createSmart", json!({"name": "Fours", "rules": {"rating": 4}}))["id"].as_u64().unwrap(); + h.settle(SETTLE); + let (outside, _) = photos_around(&mut h, GARDEN); + for row in [format!("source:album:{smart}"), "source:folder:1".to_string(), "source:keyword:mountains".to_string()] { + let target = drag_photos(&mut h, &outside, &row); + for pressed in [true, false] { + h.events.push(egui::Event::PointerButton { + pos: target, + button: egui::PointerButton::Secondary, + pressed, + modifiers: egui::Modifiers::NONE, + }); + h.step(); + } + assert_eq!(toast(&h), "", "{row}: nothing is said: {}", toast(&h)); + release(&mut h, target); + h.app.ui.toast = None; + } +} + +/// A release that a hidden pass took leaves the drag set with no button down: Esc on the next frame +/// still only gives it up, before Back can run. +#[test] +fn esc_with_a_drag_left_over_and_no_button_down_only_gives_up_the_drag() { + let mut h = app(); + let (outside, _) = photos_around(&mut h, GARDEN); + h.app.ui.lights_out = crate::state::LightsOut::Dim; + h.app.ui.dragging_photos = Some(outside); + esc(&mut h); + assert_eq!(h.app.ui.dragging_photos, None, "given up"); + assert_eq!(h.app.ui.lights_out, crate::state::LightsOut::Dim, "Esc only gave up the drag"); +} + +#[test] +fn esc_during_a_drag_leaves_a_dialog_open() { + let mut h = app(); + let (outside, _) = photos_around(&mut h, GARDEN); + drag_photos(&mut h, &outside, &format!("source:album:{GARDEN}")); + run(&mut h, "dialog.newAlbum", json!({})); + h.step(); + assert!(h.app.ui.dialog.is_some(), "a dialog opened over the drag"); + esc(&mut h); + assert_eq!(h.app.ui.dragging_photos, None, "Esc gave up the drag"); + assert!(h.app.ui.dialog.is_some(), "and only the drag"); +} + +#[test] +fn an_album_row_says_how_many_photos_a_drop_adds() { + let mut h = app(); + let (outside, inside) = photos_around(&mut h, GARDEN); + let before = members(&h, GARDEN); + // two photos that aren't in the album + let target = drag_photos(&mut h, &outside, &format!("source:album:{GARDEN}")); + let said = hint(&h).expect("the row says what a drop does"); + assert!(said.contains("2 photos") && said.contains("Garden"), "{said}"); + assert!(h.painted_text().contains(&said), "the dragged label shows it"); + release(&mut h, target); + assert_eq!(members(&h, GARDEN).len(), before.len() + 2); + assert_eq!(toast(&h), "Added 2 photos to “Garden”"); + // one that is there already and one that isn't: only the one counts, and the toast says so + let (fresh, _) = photos_around(&mut h, GARDEN); + let fresh = *fresh.first().expect("the grid shows a photo Garden still lacks"); + let pair = [inside, fresh]; + let target = drag_photos(&mut h, &pair, &format!("source:album:{GARDEN}")); + assert!(hint(&h).is_some_and(|t| t.contains("1 photo ") && !t.contains("2 ")), "{:?}", hint(&h)); + release(&mut h, target); + assert_eq!(toast(&h), "Added 1 photo to “Garden” · 1 already there"); +} + +#[test] +fn a_drop_on_an_album_that_adds_nothing_does_nothing() { + let mut h = app(); + let (_, inside) = photos_around(&mut h, GARDEN); + let before = members(&h, GARDEN); + let undo = h.app.session.undo.len(); + let target = drag_photos(&mut h, &[inside], &format!("source:album:{GARDEN}")); + let said = hint(&h).expect("the row says so"); + assert!(said.contains("Garden") && !said.starts_with("Add "), "{said}"); + assert_ne!(h.last_cursor, egui::CursorIcon::NotAllowed, "it isn't refused: it is just already there"); + release(&mut h, target); + assert_eq!(members(&h, GARDEN), before); + assert_eq!(h.app.session.undo.len(), undo, "no undo step for nothing"); + assert_eq!(toast(&h), "", "and nothing to say"); + assert_eq!(h.app.ui.dragging_photos, None); +} + +/// A drag of a photo the album holds and a Local one: nothing is added, and the row says why the +/// Local one stays out instead of only "Already in". +#[test] +fn an_album_row_explains_the_local_photos_of_a_drag_it_adds_nothing_of() { + use lightcraft_catalog::{Op, Photo, Source}; + let mut h = app(); + let (_, inside) = photos_around(&mut h, GARDEN); + let id = h.app.session.catalog.alloc_photo_id(); + let mut local = Photo::new(id, Source::File { path: "/nowhere/local.png".into() }, "local.png", "PNG", 8, 8, "2026-01-01T10:00:00"); + local.local = true; + h.app.session.catalog.apply(Op::AddPhoto { photo: Box::new(local) }).unwrap(); + let before = members(&h, GARDEN); + let undo = h.app.session.undo.len(); + let target = drag_photos(&mut h, &[inside], &format!("source:album:{GARDEN}")); + // the Local photo joins the drag (the grid shows none; a folder view's selection would) + h.app.ui.dragging_photos = Some(vec![inside, id.0]); + h.step(); + let said = hint(&h).expect("the row says what a drop does"); + assert!(said.contains("Add to My Photos first"), "{said}"); + assert_eq!(h.last_cursor, egui::CursorIcon::NotAllowed); + release(&mut h, target); + assert!(toast(&h).contains("1 Local photo skipped"), "{}", toast(&h)); + assert_eq!(members(&h, GARDEN), before); + assert_eq!(h.app.session.undo.len(), undo); + assert_eq!(h.app.ui.dragging_photos, None); +} + +#[test] +fn rows_that_cannot_hold_photos_say_so_and_refuse() { + let mut h = app(); + let smart = run(&mut h, "album.createSmart", json!({"name": "Fours", "rules": {"rating": 4}}))["id"].as_u64().unwrap(); + h.settle(SETTLE); + let (outside, _) = photos_around(&mut h, GARDEN); + let travel_folder = 1u64; + let undo = h.app.session.undo.len(); + let albums_before: Vec<_> = h.app.session.catalog.albums().map(|a| (a.id.0, a.photos.len())).collect(); + for (row, pointing_at) in [ + (format!("source:album:{smart}"), "Edit Smart Album…"), + (format!("source:folder:{travel_folder}"), "inside"), + ("source:keyword:mountains".to_string(), "Keyword List"), + ] { + let target = drag_photos(&mut h, &outside, &row); + assert_eq!(h.last_cursor, egui::CursorIcon::NotAllowed, "{row}: refused"); + assert!(hint(&h).is_some(), "{row}: the dragged label says so"); + release(&mut h, target); + assert!(toast(&h).contains(pointing_at), "{row}: the toast says why: {}", toast(&h)); + assert_eq!(h.app.ui.dragging_photos, None, "{row}"); + assert_eq!(h.app.session.undo.len(), undo, "{row}: nothing changed"); + h.app.ui.toast = None; + } + let albums_after: Vec<_> = h.app.session.catalog.albums().map(|a| (a.id.0, a.photos.len())).collect(); + assert_eq!(albums_before, albums_after); +} + +#[test] +fn a_keyword_row_says_how_many_photos_would_get_it() { + let mut h = app(); + let shown: Vec = h.app.session.visible_cloned().iter().map(|p| p.0).collect(); + let (with, without): (Vec, Vec) = shown.iter().copied().partition(|id| keywords_of(&h, *id).iter().any(|k| k == "mountains")); + assert!(!with.is_empty() && without.len() >= 2, "the demo has photos with and without the keyword"); + let pair = [with[0], without[0], without[1]]; + let target = drag_photos(&mut h, &pair, "keywordRow:mountains"); + let said = hint(&h).expect("the row says what a drop does"); + assert!(said.contains("mountains") && said.contains("2 photos"), "{said}"); + release(&mut h, target); + assert!(pair.iter().all(|id| keywords_of(&h, *id).iter().any(|k| k == "mountains"))); +} + +#[test] +fn a_drop_on_a_keyword_every_photo_has_does_nothing() { + let mut h = app(); + let shown: Vec = h.app.session.visible_cloned().iter().map(|p| p.0).collect(); + let with: Vec = shown.iter().copied().filter(|id| keywords_of(&h, *id).iter().any(|k| k == "mountains")).take(2).collect(); + assert!(!with.is_empty()); + let undo = h.app.session.undo.len(); + let target = drag_photos(&mut h, &with, "keywordRow:mountains"); + assert!(hint(&h).is_some_and(|t| !t.starts_with("Add ")), "{:?}", hint(&h)); + release(&mut h, target); + assert_eq!(h.app.session.undo.len(), undo, "no undo step for nothing"); + assert_eq!(toast(&h), ""); +} + +#[test] +fn a_keyword_cannot_be_dropped_inside_itself() { + let mut h = app(); + run(&mut h, "keyword.create", json!({"name": "Weddings", "parent": "Events"})); + let r = h.request("ui.clickWidget", json!({"id": "keywordRowToggle:Events"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(SETTLE); + let tree = |h: &Headless| (h.app.session.catalog.has_keyword("Events|Weddings"), h.app.session.catalog.has_keyword("Weddings")); + assert_eq!(tree(&h), (true, false)); + let undo = h.app.session.undo.len(); + for over in ["keywordRow:Events", "keywordRow:Events|Weddings"] { + let (from, to) = (widget(&h, "keywordRow:Events").center(), widget(&h, over).center()); + hold(&mut h, from, to + egui::vec2(60.0, 3.0)); + assert_eq!(h.app.ui.dragging_keyword.as_deref(), Some("Events"), "{over}"); + assert_eq!(h.last_cursor, egui::CursorIcon::NotAllowed, "{over}: refused"); + assert!(h.painted_text().iter().any(|t| t == "Can't go inside itself"), "{over}: the label says why: {:?}", h.painted_text()); + release(&mut h, to); + assert_eq!(tree(&h), (true, false), "{over}: nothing moved"); + assert_eq!(h.app.session.undo.len(), undo); + } +} diff --git a/crates/ui-egui/src/tests/drop_import.rs b/crates/ui-egui/src/tests/drop_import.rs index 7dffeb491c..1a8e83f7fd 100644 --- a/crates/ui-egui/src/tests/drop_import.rs +++ b/crates/ui-egui/src/tests/drop_import.rs @@ -657,6 +657,23 @@ fn a_queued_drop_waits_for_a_running_lightroom_import_instead_of_being_refused() ); } +/// The review's OK is refused while a Lightroom catalog import owns the catalog, as a drop is: nothing is imported +/// beside it (CodeRabbit on #2971). +#[test] +fn an_import_review_is_not_confirmed_while_a_lightroom_import_runs() { + let dir = Scratch::new("review-lightroom"); + let mut h = app_with_library(&dir); + h.app.ui.settings.import_dropped_directly = false; + drop_files(&mut h, &[dir.path("trip/a.png")], false); + assert!(h.step_until(SETTLE, |h| matches!(h.app.ui.dialog, Some(Dialog::Import { .. }))), "the review opens"); + let task = crate::lightroom_import::stall_import(&mut h.app); + let reply = h.request("ui.dialog.confirm", json!({}), T); + assert_ne!(reply["ok"], true, "{reply}"); + assert!(h.app.import.is_none(), "no import started"); + assert_eq!(photos(&h), 0); + drop(task); +} + /// Cancelling Open Another…'s asynchronous picker keeps the launch list up; the queued photo is /// then held for the library chosen rather than dropped behind the cancelling picker. #[test] diff --git a/crates/ui-egui/src/tests/edit_layout.rs b/crates/ui-egui/src/tests/edit_layout.rs index 7c6d79ff09..4d1a1826d8 100644 --- a/crates/ui-egui/src/tests/edit_layout.rs +++ b/crates/ui-egui/src/tests/edit_layout.rs @@ -1,6 +1,8 @@ -//! The Edit panel at its narrowest with a long profile applied: the profile row fits (#1759). +//! The Edit panel at its narrowest with a long profile applied: the profile row fits (#1759). The camera's line +//! above the Edit header. use egui::{Rect, vec2}; +use lightcraft_catalog::{Op, Photo, PhotoId, Source}; use serde_json::json; use crate::{LightcraftApp, Services, headless::HeadlessView}; @@ -26,26 +28,53 @@ fn panel(width: f32) -> (Vec, Vec<(String, Rect)>) { }); app.run("develop.profile", json!({"id": LONG_ID})).unwrap(); let photo = app.session.active().unwrap(); + let drawn = draw(&mut app, photo, width); + (drawn.texts, drawn.widgets) +} + +/// What the Edit panel drew in its last pass: its text, its widgets, and its labels' text as a screen reader gets it. +struct Drawn { + texts: Vec, + widgets: Vec<(String, Rect)>, + labels: Vec, +} + +impl Drawn { + fn rect(&self, id: &str) -> Rect { + self.widgets.iter().find(|(w, _)| w == id).unwrap_or_else(|| panic!("{id} not drawn")).1 + } + + fn text(&self, text: &str) -> &egui::epaint::TextShape { + self.texts.iter().find(|t| t.galley.job.text == text).unwrap_or_else(|| panic!("{text:?} not drawn")) + } +} + +/// The Edit panel of `photo`, `width` points wide, drawn three times. +fn draw(app: &mut LightcraftApp, photo: PhotoId, width: f32) -> Drawn { let ctx = egui::Context::default(); crate::theme::install_fonts(&ctx); crate::theme::apply(&ctx); - let mut texts = Vec::new(); - let mut widgets = Vec::new(); + ctx.enable_accesskit(); + let mut drawn = Drawn { texts: Vec::new(), widgets: Vec::new(), labels: Vec::new() }; for frame in 0..3 { let raw = HeadlessView::raw_input(vec2(width, 4000.0), 1.0, frame as f64 / 60.0, vec![]); let mut out = ctx.run_ui(raw, |ui| { egui::CentralPanel::default().frame(egui::Frame::NONE).show(ui, |ui| { - crate::panels::edit::show(&mut app, ui, photo); + crate::panels::edit::show(app, ui, photo); }); }); out.textures_delta.clear(); - texts.clear(); + drawn.texts.clear(); for shape in &out.shapes { - text_shapes(&shape.shape, &mut texts); + text_shapes(&shape.shape, &mut drawn.texts); + } + drawn.widgets = crate::widgets::take_registry(&ctx); + if let Some(update) = out.platform_output.accesskit_update.take() { + let labels = update.nodes.iter().filter(|(_, n)| format!("{:?}", n.role()) == "Label"); + drawn.labels = labels.filter_map(|(_, n)| n.value().map(str::to_string)).collect(); } - widgets = crate::widgets::take_registry(&ctx); } - (texts, widgets) + drawn } #[test] @@ -66,3 +95,24 @@ fn a_long_profile_name_leaves_the_edit_panel_its_width() { assert!(r.right() <= width, "{id} {r:?} is cut off by the {width} pt panel"); } } + +#[test] +fn the_camera_is_named_above_the_edit_header_and_a_photo_without_one_keeps_the_header_in_place() { + let mut app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services::default()); + let photo = app.session.active().unwrap(); + let camera = app.session.catalog.photo(photo).and_then(|p| p.meta.camera_name()).expect("the demo photo names its camera"); + let width = crate::state::RIGHT_WIDTH.min; + let with = draw(&mut app, photo, width); + let line = with.rect("edit:camera"); + let edit = with.text("Edit"); + assert!(line.bottom() <= edit.visual_bounding_rect().top(), "the camera {line:?} sits above Edit {:?}", edit.visual_bounding_rect()); + assert!(line.right() <= width); + assert!(with.labels.contains(&camera), "a screen reader reads {camera:?}: {:?}", with.labels); + // a photo that names no camera (a scan): no line, and the header where it was + let id = PhotoId(app.session.catalog.photos().map(|p| p.id.0).max().unwrap_or(0) + 1); + let scan = Photo::new(id, Source::Demo { scene: 1 }, "scan.png", "PNG", 3000, 2000, "2026-11-01T00:00:00"); + app.session.commit("test", Op::AddPhoto { photo: Box::new(scan) }).unwrap(); + let without = draw(&mut app, id, width); + assert!(without.widgets.iter().all(|(w, _)| w != "edit:camera")); + assert_eq!(without.text("Edit").pos, edit.pos, "the header stays in place"); +} diff --git a/crates/ui-egui/src/tests/focus_point.rs b/crates/ui-egui/src/tests/focus_point.rs index efd7f5716c..e29b865242 100644 --- a/crates/ui-egui/src/tests/focus_point.rs +++ b/crates/ui-egui/src/tests/focus_point.rs @@ -1,4 +1,4 @@ -//! Headless tests of the camera's focus point (#1480): View ▸ Focus Point draws the box where the +//! Headless tests of the camera's focus point (#1480): View ▸ Loupe Overlay ▸ Focus Point draws the box where the //! camera focused, through the user's rotation and crop; Toggle Zoom (Z) centres on it; the Info panel //! names the focus mode. @@ -158,7 +158,7 @@ fn compare_and_survey_draw_each_photos_focus_point() { } /// A photo imported before focus points were read gets its point from the background reader the frame loop drives -/// (`focus.pump`, started by itself once the library is open), and Photo ▸ Read Focus Points runs it on demand. +/// (`focus.pump`, started by itself once the library is open), and Photo ▸ Metadata ▸ Read Focus Points runs it on demand. #[test] fn the_frame_loop_reads_focus_points_for_photos_imported_earlier() { let dir = std::env::temp_dir().join(format!("lc-ui-focus-scan-{}", std::process::id())); @@ -181,7 +181,7 @@ fn the_frame_loop_reads_focus_points_for_photos_imported_earlier() { // a photo added later is read when asked (the menu item runs the command) add(&mut h.app, 9002, "later.ARW"); let spec = h.app.session.commands().into_iter().find(|c| c.id == "photo.readFocusPoints").expect("the command"); - assert_eq!(spec.menu, vec!["Photo"]); + assert_eq!(spec.menu, vec!["Photo", "Metadata"]); let r = run(&mut h, "photo.readFocusPoints", json!({})); assert_eq!(r["queued"], 1, "{r}"); assert!(h.step_until(SETTLE, |h| has_point(h, 9002))); diff --git a/crates/ui-egui/src/tests/folder_drop.rs b/crates/ui-egui/src/tests/folder_drop.rs index 497c53d7c1..941b1b5771 100644 --- a/crates/ui-egui/src/tests/folder_drop.rs +++ b/crates/ui-egui/src/tests/folder_drop.rs @@ -140,7 +140,7 @@ fn photos_dropped_on_a_folder_move_there_on_disk() { let target = folder_row(&h, &home).expect("held over, the folder opened"); // When it is brought over home: the label says where it will go glide(&mut h, parent.center(), target.center()); - assert_eq!(hint(&h).as_deref(), Some("Move 1 photo to “home”")); + assert_eq!(hint(&h).as_deref(), Some("Move 1 file to “home”")); // and released there: it asks first, nothing moved yet release(&mut h, target.center()); assert!(matches!(h.app.ui.dialog, Some(crate::state::Dialog::MovePhotos { .. })), "{:?}", h.app.ui.dialog); @@ -151,7 +151,7 @@ fn photos_dropped_on_a_folder_move_there_on_disk() { assert!(home.join("beach.png").is_file() && !trip.join("beach.png").exists(), "moved on disk"); let photo = h.app.session.catalog.photo(lightcraft_catalog::PhotoId(beach)).unwrap(); assert!(matches!(&photo.source, lightcraft_catalog::Source::File { path } if Path::new(path) == home.join("beach.png"))); - assert!(toast(&h).starts_with("Moved 1 photo to “home”. Edit → Undo moves them back."), "{}", toast(&h)); + assert!(toast(&h).starts_with("Moved 1 file to “home”. Edit → Undo moves them back."), "{}", toast(&h)); assert!(h.app.ui.dragging_photos.is_none(), "the drag ended"); // and one Undo moves it back h.app.run("edit.undo", json!({})).unwrap(); @@ -212,7 +212,6 @@ fn photos_already_in_the_folder_stay_put() { click(&mut h, &format!("libraryFolderToggle:{}", folder_key(&root))); let target = folder_row(&h, &home).expect("opened"); let garden = id_of(&h, "garden.png"); - h.app.ui.dragging_photos = Some(vec![garden]); h.app.synthetic.push(egui::Event::PointerMoved(target.center())); h.app.synthetic.push(egui::Event::PointerButton { pos: target.center(), @@ -221,6 +220,10 @@ fn photos_already_in_the_folder_stay_put() { modifiers: egui::Modifiers::NONE, }); h.step(); + h.step(); + // a drag exists only with a button down: the photos are picked up once it is + h.app.ui.dragging_photos = Some(vec![garden]); + h.step(); assert_eq!(hint(&h).as_deref(), Some("Already in “home”")); let undo = h.app.session.undo.len(); release(&mut h, target.center()); @@ -229,6 +232,96 @@ fn photos_already_in_the_folder_stay_put() { let _ = std::fs::remove_dir_all(&root); } +/// Open the folder holding `home`, add `extra_copies` photos at `trip/beach.png` (virtual copies of +/// the same file), hold the ids `pick` chooses over `home` and say what the label reads. +fn hint_over_home(tag: &str, extra_copies: usize, demo: bool, pick: impl Fn(&Headless) -> Vec) -> Option { + use lightcraft_catalog::{Op, Photo, Source}; + let (root, trip, home) = folders(tag); + let mut h = app(&[(trip.join("beach.png"), false), (home.join("garden.png"), false)]); + for _ in 0..extra_copies { + let id = h.app.session.catalog.alloc_photo_id(); + let p = + Photo::new(id, Source::File { path: trip.join("beach.png").to_string_lossy().into() }, "beach.png", "PNG", 8, 8, "2026-01-01T10:00:00"); + h.app.session.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + } + if demo { + let id = h.app.session.catalog.alloc_photo_id(); + let p = Photo::new(id, Source::Demo { scene: 1 }, "demo.jpg", "JPEG", 8, 8, "2026-01-01T10:00:00"); + h.app.session.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + } + let toggle = widget(&h, &format!("libraryFolderToggle:{}", folder_key(&root))).unwrap(); + press(&mut h, toggle.center()); + release(&mut h, toggle.center()); + let target = folder_row(&h, &home).expect("opened"); + press(&mut h, target.center()); + h.step(); + // a drag exists only with a button down: the photos are picked up once it is + h.app.ui.dragging_photos = Some(pick(&h)); + h.step(); + let text = hint(&h); + let _ = std::fs::remove_dir_all(&root); + text +} + +#[test] +fn the_label_counts_only_the_photos_a_drop_moves() { + // one already in home, one outside it + let text = hint_over_home("count", 0, false, |h| vec![id_of(h, "garden.png"), id_of(h, "beach.png")]); + assert_eq!(text.as_deref(), Some("Move 1 file to “home”")); +} + +#[test] +fn a_photo_without_a_file_is_refused_not_moved_or_already_there() { + let text = hint_over_home("demo", 0, true, |h| vec![id_of(h, "demo.jpg")]); + assert_eq!(text.as_deref(), Some("Can't be moved here")); +} + +#[test] +fn virtual_copies_of_one_file_count_once() { + // the master and a virtual copy of beach.png: one file moves + let text = + hint_over_home("copies", 1, false, |h| h.app.session.catalog.photos().filter(|p| p.file_name == "beach.png").map(|p| p.id.0).collect()); + assert_eq!(text.as_deref(), Some("Move 1 file to “home”")); +} + +/// What the question asked after the photos `pick` chooses are dropped on `home` says it moves. +fn question_over_home(tag: &str, extra_copies: usize, pick: impl Fn(&Headless) -> Vec) -> String { + use lightcraft_catalog::{Op, Photo, Source}; + let (root, trip, home) = folders(tag); + let mut h = app(&[(trip.join("beach.png"), false), (home.join("garden.png"), false)]); + assert!(h.app.ui.settings.ask_before_move); + for _ in 0..extra_copies { + let id = h.app.session.catalog.alloc_photo_id(); + let p = + Photo::new(id, Source::File { path: trip.join("beach.png").to_string_lossy().into() }, "beach.png", "PNG", 8, 8, "2026-01-01T10:00:00"); + h.app.session.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + } + click(&mut h, &format!("libraryFolderToggle:{}", folder_key(&root))); + let target = folder_row(&h, &home).expect("opened"); + press(&mut h, target.center()); + h.step(); + h.app.ui.dragging_photos = Some(pick(&h)); + h.step(); + release(&mut h, target.center()); + h.step(); + assert!(matches!(h.app.ui.dialog, Some(crate::state::Dialog::MovePhotos { .. })), "{:?}", h.app.ui.dialog); + let text = h.painted_text().into_iter().find(|t| t.starts_with("Move ") && t.ends_with('?')).unwrap_or_default(); + let _ = std::fs::remove_dir_all(&root); + text +} + +#[test] +fn the_question_counts_virtual_copies_of_one_file_once_like_the_label() { + let text = question_over_home("q-copies", 1, |h| h.app.session.catalog.photos().filter(|p| p.file_name == "beach.png").map(|p| p.id.0).collect()); + assert_eq!(text, "Move 1 file to “home”?"); +} + +#[test] +fn the_question_leaves_out_a_photo_already_in_the_folder_like_the_label() { + let text = question_over_home("q-count", 0, |h| vec![id_of(h, "garden.png"), id_of(h, "beach.png")]); + assert_eq!(text, "Move 1 file to “home”?"); +} + #[test] fn photos_that_leave_the_view_leave_the_selection() { let (root, trip, home) = folders("selection"); @@ -359,7 +452,7 @@ fn dont_ask_again_moves_the_next_drop_at_once() { // (synthetic pointer events reach the app one a frame, the press's two included: one more // frame brings the pointer to the end of the glide) h.step(); - assert_eq!(hint(&h).as_deref(), Some("Move 1 photo to “home”"), "over home"); + assert_eq!(hint(&h).as_deref(), Some("Move 1 file to “home”"), "over home"); release(&mut h, target.center()); h.step(); assert!(h.app.ui.dialog.is_none(), "not asked"); @@ -461,8 +554,8 @@ fn two_folders_with_one_name_are_told_apart_in_the_label_the_question_and_the_to glide(&mut h, row_a.center(), row_b.center()); h.step(); let label_b = hint(&h).expect("a label over b/home"); - assert!(label_a.starts_with("Move 1 photo to “home (") && label_a.ends_with("/a)”"), "{label_a}"); - assert!(label_b.starts_with("Move 1 photo to “home (") && label_b.ends_with("/b)”"), "{label_b}"); + assert!(label_a.starts_with("Move 1 file to “home (") && label_a.ends_with("/a)”"), "{label_a}"); + assert!(label_b.starts_with("Move 1 file to “home (") && label_b.ends_with("/b)”"), "{label_b}"); // and the question asked on the release says the same release(&mut h, row_b.center()); let Some(crate::state::Dialog::MovePhotos { name, .. }) = &h.app.ui.dialog else { panic!("{:?}", h.app.ui.dialog) }; @@ -470,7 +563,7 @@ fn two_folders_with_one_name_are_told_apart_in_the_label_the_question_and_the_to // and so does the toast h.step(); click(&mut h, "button:dialogOk"); - assert!(toast(&h).starts_with("Moved 1 photo to “home (") && toast(&h).contains("/b)”"), "{}", toast(&h)); + assert!(toast(&h).starts_with("Moved 1 file to “home (") && toast(&h).contains("/b)”"), "{}", toast(&h)); assert!(b.join("beach.png").is_file(), "moved into the one that was asked about"); let _ = std::fs::remove_dir_all(&root); } diff --git a/crates/ui-egui/src/tests/keyword_sidebar.rs b/crates/ui-egui/src/tests/keyword_sidebar.rs index 95c81ff0d9..bcce5dd681 100644 --- a/crates/ui-egui/src/tests/keyword_sidebar.rs +++ b/crates/ui-egui/src/tests/keyword_sidebar.rs @@ -85,3 +85,24 @@ fn probe_keyword_sidebar_cost() { } eprintln!("frame after a rating: {:?}", t.elapsed() / 10); } + +/// A keyword holding line breaks (a camera preset's whole keyword list read as one keyword by +/// 0.8.x: "Beautiful Bride\r\n Bride and Groom\r\n …") was drawn many lines tall over the rows +/// around it: the ghost text in the Keywords section. A row's name is drawn on one line. +#[test] +fn a_keyword_with_line_breaks_is_drawn_on_one_line() { + let mut s = Session::new(); + let list: Vec = (0..20).map(|i| format!("Wedding Keyword {i:02}")).collect(); + let mut p = + Photo::new(PhotoId(1), Source::File { path: "/lightcraft-kw-test/IMG_1.jpg".into() }, "IMG_1.jpg", "JPEG", 60, 40, "2026-01-01T00:00:00"); + p.meta.keywords = vec![list.join("\r\n "), "Solo".into()]; + s.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + let app = LightcraftApp::new(s, Services { png: None, ..Default::default() }); + let mut h = Headless::new(app, [1400.0, 900.0], 1.0); + let r = h.request("ui.set", json!({"view": "photoGrid", "leftPanel": true}), T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(SETTLE); + let solo = h.app.widgets.iter().find(|(w, _)| w == "label:keyword:Solo").map(|(_, r)| *r).expect("the Solo row"); + let long = h.app.widgets.iter().find(|(w, _)| w.starts_with("label:keyword:Wedding Keyword 00")).map(|(_, r)| *r).expect("the long row"); + assert!(long.height() <= solo.height() + 0.5, "one line, as tall as any name: {long:?} vs {solo:?}"); +} diff --git a/crates/ui-egui/src/tests/looping_albums.rs b/crates/ui-egui/src/tests/looping_albums.rs new file mode 100644 index 0000000000..7e49d36524 --- /dev/null +++ b/crates/ui-egui/src/tests/looping_albums.rs @@ -0,0 +1,163 @@ +//! A smart album on a loop holds nothing, and says why: its empty view and its sidebar row name +//! the album the loop goes through. An empty album that is not on a loop says nothing of loops, +//! and neither does one that only tests a looping album. + +use std::time::Duration; + +use lightcraft_catalog::{Album, AlbumId, Filter, Op}; +use serde_json::json; + +use crate::headless::Headless; +use crate::{LightcraftApp, Services}; + +const T: Duration = Duration::from_secs(20); +const SETTLE: Duration = Duration::from_secs(120); +const TITLE: &str = "This album is in a loop, so it shows nothing"; + +fn demo() -> Headless { + let services = Services { png: None, ..Default::default() }; + let app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), services); + let mut h = Headless::new(app, [1400.0, 900.0], 1.0); + let r = h.request("ui.set", json!({"view": "photoGrid", "leftPanel": true}), T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(SETTLE); + h +} + +/// A smart album with `any` of the rules. +fn smart(id: u64, name: &str, rules: serde_json::Value) -> Album { + let filter: Filter = serde_json::from_value(json!({"ruleSet": {"match": "any", "rules": rules}})).unwrap(); + Album { smart: Some(Box::new(filter)), ..Album::new(AlbumId(id), name) } +} + +fn is_in(id: u64) -> serde_json::Value { + json!({"field": "album", "op": "is", "value": id}) +} + +fn show(h: &mut Headless, album: u64) { + let r = h.request("engine.execute", json!({"command": "library.source", "params": {"kind": "album", "id": album}}), T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(SETTLE); +} + +fn painted(h: &Headless) -> Vec { + h.painted_text() +} + +/// Alpha (10) and Beta (11) test each other; Gamma (12) tests Alpha without being on the loop; +/// Delta (13) tests itself; Quiet (14) is an ordinary smart album that happens to match nothing. +fn with_a_loop() -> Headless { + let mut h = demo(); + let rating = json!({"field": "rating", "op": "gte", "value": 1}); + let none = json!({"field": "keywords", "op": "contains", "value": "no-such-keyword"}); + for album in [ + smart(10, "Alpha", json!([rating, is_in(11)])), + smart(11, "Beta", json!([rating, is_in(10)])), + smart(12, "Gamma", json!([is_in(10)])), + smart(13, "Delta", json!([rating, is_in(13)])), + smart(14, "Quiet", json!([none])), + ] { + // An edit can no longer make a loop (the catalog refuses it), but a library from before that + // rule still opens with one: the journal replays its ops the way `apply` does here, so the + // album the loop leaves on screen is the one the user still sees. + h.app.session.catalog.apply(Op::AddAlbum { album }).unwrap(); + } + h.settle(SETTLE); + h +} + +// Scenario: an album on a loop is empty, and its empty view names the album it loops through +#[test] +fn an_album_on_a_loop_says_it_is_empty_because_of_the_loop() { + let mut h = with_a_loop(); + show(&mut h, 10); + assert_eq!(h.app.session.visible_cloned().len(), 0); + let text = painted(&h); + assert!(text.iter().any(|t| t == TITLE), "{text:?}"); + assert!(text.iter().any(|t| t.contains("“Beta”") && t.contains("Edit Smart Album…")), "the body names the album the loop goes through: {text:?}"); + assert!(text.iter().all(|t| t != "No photos"), "{text:?}"); + // the other way round, and an album that tests itself + show(&mut h, 11); + assert!(painted(&h).iter().any(|t| t.contains("“Alpha”"))); + show(&mut h, 13); + let text = painted(&h); + assert!(text.iter().any(|t| t == TITLE), "{text:?}"); + assert!(text.iter().any(|t| t.starts_with("It tests itself")), "{text:?}"); +} + +// Scenario: a filter on top doesn't hide the reason +#[test] +fn the_loop_is_the_reason_even_with_a_filter_on() { + let mut h = with_a_loop(); + show(&mut h, 10); + let r = h.request("engine.execute", json!({"command": "library.filter", "params": {"rating": 3}}), T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(SETTLE); + assert!(painted(&h).iter().any(|t| t == TITLE)); +} + +// Scenario: an album that is not on a loop says nothing of loops +#[test] +fn an_empty_album_off_every_loop_does_not_blame_a_loop() { + let mut h = with_a_loop(); + // empty by its own rule + show(&mut h, 14); + let text = painted(&h); + assert!(text.iter().all(|t| t != TITLE && !t.starts_with("It leads back")), "{text:?}"); + assert!(text.iter().any(|t| t == "No photos"), "{text:?}"); + // empty because the album it tests holds nothing, but not on the loop itself + show(&mut h, 12); + assert_eq!(h.app.session.visible_cloned().len(), 0); + let text = painted(&h); + assert!(text.iter().all(|t| t != TITLE), "{text:?}"); +} + +// Scenario: the sidebar marks the looping albums, and only those (the mark predates the loop rule: +// a loop is among the problems a smart album reports) +#[test] +fn the_sidebar_marks_the_albums_on_a_loop() { + let h = with_a_loop(); + assert!(h.app.widgets.iter().any(|(w, _)| w == "source:album:10"), "the rows are on screen"); + let has = |id: u64| h.app.widgets.iter().any(|(w, _)| *w == format!("albumProblem:{id}")); + assert!(has(10) && has(11) && has(13), "the albums on a loop carry the mark"); + assert!(!has(12) && !has(14), "an album off every loop does not"); + let text = painted(&h); + assert!(text.iter().any(|t| t.starts_with('⚠') && t.contains("Alpha")), "{text:?}"); +} + +#[test] +fn the_note_names_the_album_the_loop_goes_through() { + use lightcraft_catalog::Catalog; + let mut c = Catalog::new(); + for album in [smart(1, "Alpha", json!([is_in(2)])), smart(2, "Beta", json!([is_in(1)])), smart(3, "Plain", json!([]))] { + c.apply(Op::AddAlbum { album }).unwrap(); + } + let (title, body) = crate::i18n::album_loop_note(&c, AlbumId(1)).expect("on a loop"); + assert_eq!(title, TITLE); + assert!(body.contains("Beta")); + assert!(crate::i18n::album_loop_note(&c, AlbumId(3)).is_none()); +} + +// Scenario: in a narrow grid the message wraps instead of running off its edges +#[test] +fn the_message_wraps_in_a_narrow_grid() { + let mut h = with_a_loop(); + let r = h.request("ui.resize", json!({"width": 900, "height": 700}), T); + assert_eq!(r["ok"], true, "{r}"); + show(&mut h, 10); + let canvas = h.app.canvas_rect.expect("the grid is drawn"); + let lines: Vec<(f32, usize, egui::Rect)> = h + .view + .painted_shapes() + .into_iter() + .filter_map(|s| match s { + egui::epaint::Shape::Text(t) if t.galley.job.text.starts_with("It leads back") => { + Some((t.galley.size().x, t.galley.rows.len(), t.visual_bounding_rect())) + } + _ => None, + }) + .collect(); + let (_, rows, bounds) = lines.first().copied().expect("the body is painted"); + assert!(rows > 1, "the body is wider than the grid, so it takes more than one row"); + assert!(bounds.left() >= canvas.left() && bounds.right() <= canvas.right(), "{bounds:?} stays inside {canvas:?}"); +} diff --git a/crates/ui-egui/src/tests/masking.rs b/crates/ui-egui/src/tests/masking.rs index 62a8548cdd..d28cb73a71 100644 --- a/crates/ui-egui/src/tests/masking.rs +++ b/crates/ui-egui/src/tests/masking.rs @@ -119,7 +119,9 @@ fn new_brush_starts_a_separate_mask_in_paint_mode() { click(&mut h, "maskNew:brush"); assert_eq!(h.app.session.active_mask, Some(2)); assert!(!h.app.ui.brush_erase); - assert!(h.app.ui.mask_overlay); + // a new mask has no settings: its overlay shows by itself (O stays as it was) + assert!(!h.app.ui.mask_overlay); + assert_eq!(crate::panels::detail::overlay_mask(&h.app, &develop(&h)).map(|m| m.id), Some(2)); let r = h.request("ui.set", json!({"brushSize": 0.15, "brushFeather": 0.0, "brushFlow": 100.0}), T); assert_eq!(r["ok"], true, "{r}"); brush_at(&mut h, 0.5, 0.5); @@ -138,11 +140,14 @@ fn mask_adjustments_hide_overlay_without_disabling_the_mask() { use lightcraft_pipeline::Overlay; let mut h = detail("panel.masking"); exec(&mut h, "mask.add", json!({"kind": "linear", "start": [0.5, 0.2], "end": [0.5, 0.7]})); - assert!(h.app.ui.mask_overlay); + let shown = |h: &Headless| matches!(crate::panels::detail::view_overlay(&h.app, &develop(h)), Overlay::Mask { .. }); + // a mask without settings shows what it selects, by itself (O is off) + assert!(!h.app.ui.mask_overlay); + assert!(shown(&h), "a new mask shows its overlay"); // Changing the shape needs the overlay; changing the image needs an unobscured preview. exec(&mut h, "mask.refine", json!({"value": 10.0})); - assert!(h.app.ui.mask_overlay); + assert!(shown(&h), "Refine Edges is the mask's shape, not a setting"); // The dock header pushes this adjustment below the initial viewport. Exercise the // actual visible slider rather than sending a synthetic click outside its clipped body. let panel = h.app.widgets.iter().find(|(id, _)| id == "panel:right_panel").unwrap().1; @@ -155,21 +160,28 @@ fn mask_adjustments_hide_overlay_without_disabling_the_mask() { assert!(panel.contains_rect(slider), "exposure is visible before clicking: {slider:?} in {panel:?}"); let r = h.request("ui.clickWidget", json!({"id": "slider:exposure", "fx": 0.7}), T); assert_eq!(r["ok"], true, "{r}"); - assert!(!h.app.ui.mask_overlay, "the exposure slider hides the overlay after release"); let d = develop(&h); assert!(d.masks[0].adjust.exposure > 0.0); assert!(d.masks[0].visible, "hiding the overlay must not disable the mask"); - assert_eq!(crate::panels::detail::view_overlay(&h.app, &d), Overlay::None); + // the pointer is off the row and the pin: a mask with settings shows its effect, not the overlay + h.app.ui.mask_hover = None; + h.app.ui.mask_hover_prev = None; + assert_eq!(crate::panels::detail::view_overlay(&h.app, &d), Overlay::None, "a mask with settings never shows by itself"); let mask = d.masks[0].clone(); let r = h.request("ui.key", json!({"key": "o"}), T); assert_eq!(r["ok"], true, "{r}"); - assert!(h.app.ui.mask_overlay, "O can restore the overlay"); + assert!(h.app.ui.mask_overlay, "O shows the overlay on request"); assert_eq!(develop(&h).masks[0], mask, "toggling the overlay leaves the mask and its effect unchanged"); - assert!(matches!(crate::panels::detail::view_overlay(&h.app, &develop(&h)), Overlay::Mask { .. })); + assert!(shown(&h)); + // a slider at work hides even an overlay switched on with O; it comes back when let go + h.app.ui.dragging_control = Some("exposure".into()); + assert_eq!(crate::panels::detail::view_overlay(&h.app, &develop(&h)), Overlay::None, "nothing shows while a slider is at work"); + h.app.ui.dragging_control = None; + assert!(shown(&h)); // Ctrl+Shift+O / Cmd+Shift+O shows every visible mask's region at once (the new command), ahead of the selected - // mask overlay so it is not shadowed by the always-on single-mask overlay. + // mask overlay so it is not shadowed by the single-mask overlay. exec(&mut h, "view.maskOverlayAll", json!({})); assert!(h.app.ui.mask_overlay_all, "the all-masks overlay command turns it on"); assert!(matches!(crate::panels::detail::view_overlay(&h.app, &develop(&h)), Overlay::AllMasks { .. })); @@ -177,49 +189,190 @@ fn mask_adjustments_hide_overlay_without_disabling_the_mask() { assert!(!h.app.ui.mask_overlay_all, "the all-masks overlay command toggles it off"); assert!(!matches!(crate::panels::detail::view_overlay(&h.app, &develop(&h)), Overlay::AllMasks { .. })); - // Failed edits and global adjustments must not hide the mask overlay. + // O stays on through edits: failed ones, global adjustments and the mask's own values assert!(h.app.run("mask.adjust", json!({"id": 999, "values": {"exposure": 1.0}})).is_err()); assert!(h.app.ui.mask_overlay); exec(&mut h, "develop.set", json!({"control": "light.exposure", "value": 0.5})); assert!(h.app.ui.mask_overlay); - - // Numeric edits/resets and Amount use the same command path as the sliders. for values in [json!({"exposure": 0.0}), json!({"saturation": 20.0}), json!({"amount": 50.0})] { - exec(&mut h, "view.maskOverlay", json!({"show": true})); exec(&mut h, "mask.adjust", json!({"values": values})); - assert!(!h.app.ui.mask_overlay); + assert!(h.app.ui.mask_overlay && shown(&h), "{values}"); } h.settle(SETTLE); } -/// A slider hides the overlay (above); a new mask, an added part, a duplicate or picking a mask in -/// the list shows it again, so the Overlay menu's mode is what the photo shows (issue #1800). +/// One overlay rule replaces showing the overlay again on every new, picked, duplicated or extended +/// mask (issue #1800): a mask without settings shows what it selects by itself; picking a mask that +/// has settings, adding a part to it or duplicating it shows its effect, so it can be judged; the +/// pointer on one of its component rows (or its pin), or O, shows its overlay on request. #[test] -fn a_new_or_picked_mask_shows_the_overlay_hidden_by_a_slider() { +fn a_mask_shows_its_overlay_by_itself_only_without_settings() { use lightcraft_pipeline::Overlay; let mut h = detail("panel.masking"); exec(&mut h, "mask.add", json!({"kind": "linear", "start": [0.5, 0.2], "end": [0.5, 0.7]})); let first = h.app.session.active_mask.unwrap(); - let hide = |h: &mut Headless| { - exec(h, "mask.adjust", json!({"values": {"exposure": 0.5}})); - assert!(!h.app.ui.mask_overlay); + let off_rows = |h: &mut Headless| { + h.app.ui.mask_hover = None; + h.app.ui.mask_hover_prev = None; }; let shown = |h: &Headless| matches!(crate::panels::detail::view_overlay(&h.app, &develop(h)), Overlay::Mask { .. }); - hide(&mut h); + assert!(shown(&h), "a new mask without settings shows its overlay"); + exec(&mut h, "mask.adjust", json!({"values": {"exposure": 0.5}})); + off_rows(&mut h); + assert!(!shown(&h), "with settings it shows its effect"); exec(&mut h, "mask.add", json!({"kind": "radial", "center": [0.4, 0.5], "rx": 0.2, "ry": 0.2})); + off_rows(&mut h); assert!(shown(&h), "a new mask shows its overlay"); - hide(&mut h); let r = h.request("ui.clickWidget", json!({"id": format!("mask:{first}")}), T); assert_eq!(r["ok"], true, "{r}"); assert_eq!(h.app.session.active_mask, Some(first)); - assert!(shown(&h), "picking a mask in the list shows its overlay"); + off_rows(&mut h); + assert!(!shown(&h), "picking a mask with settings shows its effect, not the overlay"); for (cmd, params) in [("mask.addComponent", json!({"kind": "radial", "op": "add", "center": [0.6, 0.5], "rx": 0.1, "ry": 0.1})), ("mask.duplicate", json!({}))] { - hide(&mut h); exec(&mut h, cmd, params); - assert!(shown(&h), "{cmd} shows the overlay"); + off_rows(&mut h); + assert!(!shown(&h), "{cmd} on a mask with settings shows its effect"); } + // on request: the pointer on one of its component rows (or its pin), or O + h.app.ui.mask_hover = h.app.session.active().zip(h.app.session.active_mask); + assert!(shown(&h), "the pointer on a component row shows the overlay"); + off_rows(&mut h); + h.request("ui.key", json!({"key": "o"}), T); + assert!(shown(&h), "O shows it"); + h.settle(SETTLE); +} + +/// O hides a mask's automatic overlay until O shows it again: hiding another mask's doesn't bring +/// the first one's back. +#[test] +fn each_mask_hidden_with_o_stays_hidden() { + use lightcraft_pipeline::Overlay; + let mut h = detail("panel.masking"); + let shown = |h: &Headless| matches!(crate::panels::detail::view_overlay(&h.app, &develop(h)), Overlay::Mask { .. }); + exec(&mut h, "mask.add", json!({"kind": "linear", "start": [0.5, 0.2], "end": [0.5, 0.7]})); + let a = h.app.session.active_mask.unwrap(); + h.request("ui.key", json!({"key": "o"}), T); + assert!(!shown(&h), "A hidden"); + exec(&mut h, "mask.add", json!({"kind": "radial", "center": [0.4, 0.5], "rx": 0.2, "ry": 0.2})); + h.app.ui.mask_hover = None; + h.app.ui.mask_hover_prev = None; + assert!(shown(&h), "B, new, shows"); + h.request("ui.key", json!({"key": "o"}), T); + assert!(!shown(&h), "B hidden"); + exec(&mut h, "mask.select", json!({"id": a})); + h.app.ui.mask_hover = None; + h.app.ui.mask_hover_prev = None; + assert!(!shown(&h), "A is still hidden"); + h.request("ui.key", json!({"key": "o"}), T); + assert!(shown(&h), "O shows A again"); + h.settle(SETTLE); +} + +/// Which hover shows a mask's overlay (the user's test notes, 31 Oct): the mask's own row (name, eye, menu) +/// shows none, so its eye can judge the effect with nothing over the photo; a component row under it shows the +/// whole mask's overlay; the pin shows it; a mask without settings keeps its overlay, also over its own row; O still +/// shows and hides it; dragging the pin hides it while it moves. +#[test] +fn the_mask_row_shows_no_overlay_and_a_component_row_does() { + use lightcraft_pipeline::Overlay; + let mut h = detail("panel.masking"); + let steps = |h: &mut Headless| { + h.step(); + h.step(); + }; + let ask = |h: &mut Headless, method: &str, params: serde_json::Value| { + let r = h.request(method, params.clone(), T); + assert_eq!(r["ok"], true, "{method} {params}: {r}"); + }; + let shown = |h: &Headless| matches!(crate::panels::detail::view_overlay(&h.app, &develop(h)), Overlay::Mask { .. }); + let visible = |h: &Headless, id: u32| develop(h).masks.iter().find(|m| m.id == id).is_some_and(|m| m.visible); + let canvas = h.app.canvas_rect.expect("the loupe"); + let away = json!({"x": canvas.left() + 6.0, "y": canvas.top() + 6.0}); + // a mask without settings: its overlay stays, whatever is hovered + exec(&mut h, "mask.add", json!({"kind": "radial", "center": [0.5, 0.5]})); + let mid = h.app.session.active_mask.expect("selected"); + steps(&mut h); + ask(&mut h, "ui.hoverWidget", json!({"id": format!("mask:{mid}")})); + steps(&mut h); + assert!(shown(&h), "no settings yet: shown, also over its own row"); + // with settings: its own row and its eye show nothing; the eye switches the effect + exec(&mut h, "mask.adjust", json!({"values": {"exposure": 1.0}})); + ask(&mut h, "ui.hoverWidget", json!({"id": format!("mask:{mid}")})); + steps(&mut h); + assert!(!shown(&h), "the pointer on the mask's own row shows no overlay"); + ask(&mut h, "ui.clickWidget", json!({"id": format!("maskVisible:{mid}")})); + steps(&mut h); + assert!(!visible(&h, mid), "the eye switched the effect off"); + assert!(!shown(&h), "with nothing over the photo"); + ask(&mut h, "ui.clickWidget", json!({"id": format!("maskVisible:{mid}")})); + steps(&mut h); + assert!(visible(&h, mid) && !shown(&h), "and on again, still with no overlay"); + // a component row: the whole mask's overlay + exec(&mut h, "mask.addComponent", json!({"op": "subtract", "kind": "linear", "start": [0.5, 0.0], "end": [0.5, 0.3]})); + steps(&mut h); + for i in 0..2 { + ask(&mut h, "ui.hoverWidget", json!({"id": format!("component:{i}")})); + steps(&mut h); + assert!(shown(&h), "the pointer on component {i} shows the mask's overlay"); + assert_eq!(h.app.ui.mask_hover.or(h.app.ui.mask_hover_prev).map(|(_, m)| m), Some(mid), "the whole mask"); + } + ask(&mut h, "ui.move", away.clone()); + steps(&mut h); + assert!(!shown(&h), "leaving the row hides it"); + // the pin + let img = h.app.image_rect.expect("the photo on screen"); + ask(&mut h, "ui.move", json!({"x": img.center().x, "y": img.center().y})); + steps(&mut h); + assert!(shown(&h), "the pointer on the pin shows the overlay"); + // dragging the pin: hidden while it moves + pointer(&mut h, json!([{"kind": "down", "x": 0.5, "y": 0.5}, {"kind": "drag", "x": 0.53, "y": 0.52}, {"kind": "drag", "x": 0.56, "y": 0.54}])); + steps(&mut h); + assert!(crate::panels::detail::mask_gesture(&h.app), "the pin is being dragged: {:?}", h.app.gesture); + assert!(!shown(&h), "no overlay while the pin is dragged"); + pointer(&mut h, json!([{"kind": "up", "x": 0.56, "y": 0.54}])); + steps(&mut h); + ask(&mut h, "ui.move", away); + steps(&mut h); + assert!(!shown(&h)); + // O over its own row + ask(&mut h, "ui.hoverWidget", json!({"id": format!("mask:{mid}")})); + exec(&mut h, "view.maskOverlay", json!({"show": true})); + steps(&mut h); + assert!(shown(&h), "O shows it, even over its own row"); + exec(&mut h, "view.maskOverlay", json!({"show": false})); + steps(&mut h); + assert!(!shown(&h), "and hides it"); +} + +/// The pointer on a mask's row, and O hiding a mask's automatic overlay, belong to that photo: on +/// another photo a mask with the same id is another mask. +#[test] +fn a_mask_hovered_or_hidden_on_one_photo_says_nothing_about_another() { + use lightcraft_pipeline::Overlay; + let mut h = detail("panel.masking"); + let first = h.app.session.active().unwrap(); + exec(&mut h, "mask.add", json!({"kind": "linear", "start": [0.5, 0.2], "end": [0.5, 0.7]})); + let mask = h.app.session.active_mask.unwrap(); + let shown = |h: &Headless| matches!(crate::panels::detail::view_overlay(&h.app, &develop(h)), Overlay::Mask { .. }); + // O hides the fresh mask's overlay on this photo + h.request("ui.key", json!({"key": "o"}), T); + assert!(!shown(&h)); + assert_eq!(h.app.ui.mask_overlay_hidden, vec![(first, mask)]); + // another photo with a fresh mask of the same id still shows it + let other = h.app.session.visible_cloned().into_iter().find(|p| *p != first).unwrap(); + exec(&mut h, "library.select", json!({"ids": [other.0]})); + exec(&mut h, "mask.add", json!({"kind": "linear", "start": [0.5, 0.2], "end": [0.5, 0.7]})); + assert_eq!(h.app.session.active(), Some(other)); + assert_eq!(h.app.session.active_mask, Some(mask), "the same id on the other photo"); + h.app.ui.mask_hover = None; + h.app.ui.mask_hover_prev = None; + assert!(shown(&h), "hidden on the first photo only"); + // a hover left over from the first photo doesn't count here + exec(&mut h, "mask.adjust", json!({"values": {"exposure": 0.5}})); + h.app.ui.mask_hover_prev = Some((first, mask)); + assert!(!shown(&h), "the first photo's hover is not this photo's"); h.settle(SETTLE); } @@ -2157,6 +2310,320 @@ fn effect_dropdown_applies_saves_and_shows_the_matching_effect() { assert_eq!(exec(&mut h, "mask.effects", json!({}))["current"], "Lift"); } +/// A mask O hid stays hidden after O shows another mask: selecting it again doesn't bring it back. +#[test] +fn a_mask_hidden_with_o_stays_hidden_after_o_shows_another() { + use lightcraft_pipeline::Overlay; + let mut h = detail("panel.masking"); + let shown = |h: &Headless| matches!(crate::panels::detail::view_overlay(&h.app, &develop(h)), Overlay::Mask { .. }); + exec(&mut h, "mask.add", json!({"kind": "linear", "start": [0.5, 0.2], "end": [0.5, 0.7]})); + let a = h.app.session.active_mask.unwrap(); + h.request("ui.key", json!({"key": "o"}), T); + assert!(!shown(&h), "A hidden"); + exec(&mut h, "mask.add", json!({"kind": "radial", "center": [0.4, 0.5], "rx": 0.2, "ry": 0.2})); + exec(&mut h, "mask.adjust", json!({"values": {"exposure": 0.5}})); + h.app.ui.mask_hover = None; + h.app.ui.mask_hover_prev = None; + assert!(!shown(&h), "B has settings: its effect shows"); + h.request("ui.key", json!({"key": "o"}), T); + assert!(shown(&h), "O shows B's overlay"); + exec(&mut h, "mask.select", json!({"id": a})); + h.app.ui.mask_hover = None; + h.app.ui.mask_hover_prev = None; + assert!(!shown(&h), "A is still hidden"); + h.settle(SETTLE); +} + +/// The all-masks overlay waits while an AI selection is computed: its stand-in would look like the +/// result. +#[test] +fn the_all_masks_overlay_waits_for_an_ai_selection() { + use lightcraft_develop::{Mask, MaskComponent, MaskOp, MaskShape}; + use lightcraft_geom::Point; + let component = |shape| MaskComponent { name: None, op: MaskOp::Add, invert: false, shape }; + let linear = component(MaskShape::Linear { start: Point::new(0.5, 0.2), end: Point::new(0.5, 0.7) }); + let mut d = lightcraft_develop::DevelopSettings::default(); + d.masks.push(Mask { id: 1, components: vec![linear], visible: true, ..Default::default() }); + assert!(crate::panels::detail::all_masks_showable(&d, true)); + let object = component(MaskShape::Object { hint: vec![Point::new(0.5, 0.5)], exclude: Vec::new(), seg: None, detail: Vec::new(), edge: 0.0 }); + d.masks.push(Mask { id: 2, components: vec![object], visible: true, ..Default::default() }); + assert!(!crate::panels::detail::all_masks_showable(&d, true), "an Object selection is being computed"); + assert!(crate::panels::detail::all_masks_showable(&d, false), "nothing is computing"); +} + +/// A deleted mask's id goes to the next new mask: O having hid the deleted one's overlay says nothing about the +/// new one (CodeRabbit on #2920). +#[test] +fn a_new_mask_with_a_deleted_masks_id_shows_its_overlay() { + use lightcraft_pipeline::Overlay; + let mut h = detail("panel.masking"); + exec(&mut h, "mask.add", json!({"kind": "linear", "start": [0.5, 0.2], "end": [0.5, 0.7]})); + let mask = h.app.session.active_mask.unwrap(); + let shown = |h: &Headless| matches!(crate::panels::detail::view_overlay(&h.app, &develop(h)), Overlay::Mask { .. }); + h.request("ui.key", json!({"key": "o"}), T); + assert!(!shown(&h)); + crate::panels::masking::delete_mask(&mut h.app, None); + assert!(h.app.ui.mask_overlay_hidden.is_empty(), "forgotten with the mask"); + exec(&mut h, "mask.add", json!({"kind": "radial", "center": [0.4, 0.5], "rx": 0.2, "ry": 0.2})); + assert_eq!(h.app.session.active_mask, Some(mask), "the same id again"); + h.app.ui.mask_hover = None; + h.app.ui.mask_hover_prev = None; + assert!(shown(&h), "the new mask shows"); + h.settle(SETTLE); +} + +/// Undo taking a new mask away frees its id the same way: O having hid its overlay says nothing about the next +/// new mask (CodeRabbit on #2920). +#[test] +fn a_new_mask_after_undoing_a_hidden_one_shows_its_overlay() { + use lightcraft_pipeline::Overlay; + let mut h = detail("panel.masking"); + exec(&mut h, "mask.add", json!({"kind": "linear", "start": [0.5, 0.2], "end": [0.5, 0.7]})); + let mask = h.app.session.active_mask.unwrap(); + let shown = |h: &Headless| matches!(crate::panels::detail::view_overlay(&h.app, &develop(h)), Overlay::Mask { .. }); + h.request("ui.key", json!({"key": "o"}), T); + assert!(!shown(&h)); + exec(&mut h, "edit.undo", json!({})); + assert!(develop(&h).masks.iter().all(|m| m.id != mask), "the mask is undone"); + assert!(h.app.ui.mask_overlay_hidden.is_empty(), "forgotten with the mask"); + exec(&mut h, "mask.add", json!({"kind": "radial", "center": [0.4, 0.5], "rx": 0.2, "ry": 0.2})); + assert_eq!(h.app.session.active_mask, Some(mask), "the same id again"); + h.app.ui.mask_hover = None; + h.app.ui.mask_hover_prev = None; + assert!(shown(&h), "the new mask shows"); + h.settle(SETTLE); +} + +/// Painting on a mask that has settings shows its effect as it is painted (the stroke goes to the +/// photo live, one undo step), never the red stroke; a mask without settings, or O, still shows the +/// red stroke while painting (found in an evening of real editing). +#[test] +fn painting_a_mask_with_settings_shows_its_effect_not_red() { + let mut h = detail("panel.masking"); + h.settle(SETTLE); + exec(&mut h, "tool.brush", json!({"new": true})); + h.app.ui.brush_auto_mask = false; + let strokes = |h: &Headless, mid: u32| -> Vec { + develop(h) + .masks + .iter() + .find(|m| m.id == mid) + .map(|m| { + m.components.iter().filter_map(|c| if let MaskShape::Brush { strokes } = &c.shape { Some(strokes.len()) } else { None }).collect() + }) + .unwrap_or_default() + }; + // no settings: the red stroke while painting + pointer(&mut h, json!([{"kind": "down", "x": 0.2, "y": 0.5}, {"kind": "drag", "x": 0.25, "y": 0.5}, {"kind": "drag", "x": 0.3, "y": 0.5}])); + assert!(h.app.brush_live.is_some(), "a mask without settings shows the red stroke"); + pointer(&mut h, json!([{"kind": "up", "x": 0.3, "y": 0.5}])); + let mid = h.app.session.active_mask.expect("the brush mask"); + assert_eq!(strokes(&h, mid), vec![1]); + // with settings: no red; the stroke is on the photo while painted, one undo step + exec(&mut h, "mask.adjust", json!({"values": {"exposure": 1.0}})); + assert_eq!(h.app.ui.tool, "brush", "the brush stays armed on its mask"); + pointer(&mut h, json!([{"kind": "down", "x": 0.2, "y": 0.7}, {"kind": "drag", "x": 0.25, "y": 0.7}, {"kind": "drag", "x": 0.3, "y": 0.7}])); + assert!(h.app.brush_live.is_none(), "no red stroke on a mask with settings"); + assert_eq!(strokes(&h, mid), vec![2], "the stroke shows its effect on the photo while painted"); + assert!(h.app.session.interaction.is_some(), "one undo step stays open while painting"); + pointer(&mut h, json!([{"kind": "up", "x": 0.3, "y": 0.7}])); + h.step(); + assert_eq!(strokes(&h, mid), vec![2]); + assert!(h.app.session.interaction.is_none()); + exec(&mut h, "edit.undo", json!({})); + assert_eq!(strokes(&h, mid), vec![1], "one undo removes the whole stroke"); + // O shows the overlay on purpose: the red stroke again + exec(&mut h, "view.maskOverlay", json!({"show": true})); + pointer(&mut h, json!([{"kind": "down", "x": 0.2, "y": 0.3}, {"kind": "drag", "x": 0.25, "y": 0.3}, {"kind": "drag", "x": 0.3, "y": 0.3}])); + assert!(h.app.brush_live.is_some(), "O: the overlay colour while painting"); + pointer(&mut h, json!([{"kind": "up", "x": 0.3, "y": 0.3}])); + h.settle(SETTLE); +} + +/// A live stroke the photo refused (here: more pressure values than points) is not live: the release +/// adds it as a new stroke instead of replacing the mask's previous one (CodeRabbit on #2920). +#[test] +fn a_refused_live_stroke_does_not_replace_the_previous_stroke() { + let mut h = detail("panel.masking"); + h.settle(SETTLE); + exec(&mut h, "tool.brush", json!({"new": true})); + h.app.ui.brush_auto_mask = false; + brush_at(&mut h, 0.2, 0.5); + exec(&mut h, "mask.adjust", json!({"values": {"exposure": 1.0}})); + let before = develop(&h).masks.last().map(|m| m.components.clone()); + let p = |x: f64| lightcraft_geom::Point::new(x, 0.7); + h.app.gesture = Some(crate::panels::detail::Gesture::Brush { points: vec![p(0.2), p(0.3)], pressure: vec![1.0; 3], live: None }); + h.step(); + assert!(matches!(h.app.gesture, Some(crate::panels::detail::Gesture::Brush { live: None, .. })), "a refused stroke must not count as live"); + assert!(h.app.session.interaction.is_none(), "the refused stroke's undo step is closed"); + assert_eq!(develop(&h).masks.last().map(|m| m.components.clone()), before, "the previous stroke is untouched"); + h.app.gesture = None; + h.settle(SETTLE); +} + +/// Another tool chosen while a live Brush stroke is open (a gradient's key mid-stroke) ends the stroke first: the +/// new mask is a step of its own, not folded into the "Brush" step (CodeRabbit on #2920). +#[test] +fn a_gradient_chosen_mid_stroke_is_its_own_undo_step() { + let mut h = detail("panel.masking"); + h.settle(SETTLE); + exec(&mut h, "tool.brush", json!({"new": true})); + h.app.ui.brush_auto_mask = false; + brush_at(&mut h, 0.2, 0.5); + exec(&mut h, "mask.adjust", json!({"values": {"exposure": 1.0}})); + pointer(&mut h, json!([{"kind": "down", "x": 0.2, "y": 0.7}, {"kind": "drag", "x": 0.25, "y": 0.7}, {"kind": "drag", "x": 0.3, "y": 0.7}])); + assert!(matches!(h.app.gesture, Some(crate::panels::detail::Gesture::Brush { live: Some(_), .. })), "a live stroke"); + let masks = develop(&h).masks.len(); + exec(&mut h, "tool.linear", json!({})); + assert!(h.app.gesture.is_none(), "the stroke ended"); + assert!(h.app.session.interaction.is_none(), "its undo step closed"); + assert_eq!(develop(&h).masks.len(), masks + 1); + exec(&mut h, "edit.undo", json!({})); + assert_eq!(develop(&h).masks.len(), masks, "one undo takes the gradient alone"); + pointer(&mut h, json!([{"kind": "up", "x": 0.3, "y": 0.7}])); + h.settle(SETTLE); +} + +/// A stroke that never went live (its mask has no settings) still ends when another tool is chosen +/// mid-stroke: back on the brush, the next stroke starts afresh instead of carrying on from it +/// (CodeRabbit on #2920). +#[test] +fn a_tool_chosen_mid_stroke_drops_a_stroke_that_was_not_live() { + let mut h = detail("panel.masking"); + h.settle(SETTLE); + exec(&mut h, "tool.brush", json!({"new": true})); + h.app.ui.brush_auto_mask = false; + pointer(&mut h, json!([{"kind": "down", "x": 0.2, "y": 0.5}, {"kind": "drag", "x": 0.25, "y": 0.5}, {"kind": "drag", "x": 0.3, "y": 0.5}])); + assert!(matches!(h.app.gesture, Some(crate::panels::detail::Gesture::Brush { live: None, .. })), "a stroke, not live"); + exec(&mut h, "tool.linear", json!({})); + assert!(h.app.gesture.is_none(), "the stroke is dropped"); + assert!(h.app.brush_live.is_none()); + pointer(&mut h, json!([{"kind": "up", "x": 0.3, "y": 0.5}])); + exec(&mut h, "tool.brush", json!({})); + pointer(&mut h, json!([{"kind": "down", "x": 0.6, "y": 0.4}, {"kind": "drag", "x": 0.65, "y": 0.4}])); + let first = match &h.app.gesture { + Some(crate::panels::detail::Gesture::Brush { points, .. }) => points.first().map(|p| p.x), + _ => None, + }; + assert!(first.is_some_and(|x| x > 0.5), "the next stroke starts where it was painted: {first:?}"); + pointer(&mut h, json!([{"kind": "up", "x": 0.65, "y": 0.4}])); + h.settle(SETTLE); +} + +/// The overlay falls back to the last frame's hovered mask while this frame's panels set the new one, so a frame in +/// which the hovered row or pin changed (or the pointer left them) asks for one more: the overlay follows the +/// pointer at once, not at the next input (CodeRabbit on #2920). +#[test] +fn a_frame_whose_hovered_mask_changed_asks_for_another() { + let mut h = detail("panel.masking"); + let row = Some((lightcraft_catalog::PhotoId(1), 1)); + let asks = |h: &mut Headless, now, before| { + h.app.ui.mask_hover = now; + h.app.ui.mask_hover_prev = before; + // (a settled context: its own first frames asked for, so only this frame's request counts) + let ctx = egui::Context::default(); + for _ in 0..3 { + ctx.run_ui(egui::RawInput::default(), |_| {}).textures_delta.clear(); + } + let asked = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let seen = asked.clone(); + ctx.set_request_repaint_callback(move |_| seen.store(true, std::sync::atomic::Ordering::Relaxed)); + h.app.repaint_on_mask_hover_change(&ctx); + asked.load(std::sync::atomic::Ordering::Relaxed) + }; + assert!(asks(&mut h, row, None), "onto a row"); + assert!(asks(&mut h, None, row), "off it"); + assert!(asks(&mut h, Some((lightcraft_catalog::PhotoId(1), 2)), row), "onto another"); + assert!(!asks(&mut h, row, row), "resting on the same row"); + assert!(!asks(&mut h, None, None), "nowhere near"); +} + +/// Picking another mask or another photo (also with the arrow keys), Undo, or a Brush request that makes a new mask +/// while a live Brush stroke is held ends the stroke first: its next live update or its release can't replace the +/// picked mask's strokes, the stroke before the undone one, or start a mask on the new photo, and the pointer +/// still held paints nothing more until it is let go (CodeRabbit on #2920). +#[test] +fn picking_another_mask_or_photo_mid_stroke_ends_the_stroke() { + let stroke_count = |h: &Headless, id: u32| -> usize { + develop(h) + .masks + .iter() + .find(|m| m.id == id) + .map(|m| m.components.iter().map(|c| if let MaskShape::Brush { strokes } = &c.shape { strokes.len() } else { 0 }).sum()) + .unwrap_or(0) + }; + for pick in ["mask", "photo", "next", "undo", "new"] { + let mut h = detail("panel.masking"); + h.settle(SETTLE); + exec(&mut h, "tool.brush", json!({"new": true})); + h.app.ui.brush_auto_mask = false; + brush_at(&mut h, 0.2, 0.5); + exec(&mut h, "mask.adjust", json!({"values": {"exposure": 1.0}})); + let first = h.app.session.active_mask.expect("the first mask"); + exec(&mut h, "tool.brush", json!({"new": true})); + brush_at(&mut h, 0.6, 0.5); + exec(&mut h, "mask.adjust", json!({"values": {"exposure": -1.0}})); + let second = h.app.session.active_mask.expect("the second mask"); + assert_ne!(first, second); + let second_before = develop(&h).masks.iter().find(|m| m.id == second).cloned(); + // a live stroke on the second mask (it has settings: its effect shows while painting) + pointer(&mut h, json!([{"kind": "down", "x": 0.6, "y": 0.7}, {"kind": "drag", "x": 0.65, "y": 0.7}, {"kind": "drag", "x": 0.7, "y": 0.7}])); + h.step(); + assert!(matches!(h.app.gesture, Some(crate::panels::detail::Gesture::Brush { live: Some(_), .. })), "{pick}: a live stroke"); + let photo = h.app.session.active().expect("a photo"); + let (first_strokes, masks) = (stroke_count(&h, first), develop(&h).masks.len()); + match pick { + "mask" => { + exec(&mut h, "mask.select", json!({"id": first})); + } + "photo" => { + let other = h.app.session.visible_cloned().into_iter().find(|p| *p != photo).expect("another photo"); + exec(&mut h, "library.select", json!({"ids": [other.0]})); + } + "next" => { + exec(&mut h, "library.next", json!({})); + assert_ne!(h.app.session.active(), Some(photo), "stepped to the next photo"); + } + "undo" => { + exec(&mut h, "edit.undo", json!({})); + } + _ => { + exec(&mut h, "tool.brush", json!({"new": true})); + } + } + let (third, second_now) = (h.app.session.active_mask, stroke_count(&h, second)); + assert!(h.app.gesture.is_none(), "{pick}: the stroke ended"); + assert!(h.app.session.interaction.is_none(), "{pick}: its undo step closed"); + // the pointer carries on and lets go: nothing lands on what was picked + pointer(&mut h, json!([{"kind": "drag", "x": 0.75, "y": 0.7}, {"kind": "drag", "x": 0.8, "y": 0.7}, {"kind": "up", "x": 0.8, "y": 0.7}])); + h.step(); + h.step(); + match pick { + "mask" => { + assert_eq!(stroke_count(&h, first), first_strokes, "the picked mask's strokes are untouched"); + assert_eq!(develop(&h).masks.len(), masks, "no new mask"); + } + "undo" => { + let second_after = develop(&h).masks.iter().find(|m| m.id == second).cloned(); + assert_eq!(second_after, second_before, "the stroke before the undone one is kept as it was"); + } + "new" => { + assert_ne!(third, Some(second), "a new mask"); + assert_eq!(stroke_count(&h, second), second_now, "what was painted stays on its mask, nothing more"); + assert_eq!(third.map_or(0, |m| stroke_count(&h, m)), 0, "nothing of the old stroke lands on the new mask"); + } + _ => assert!(develop(&h).masks.is_empty(), "{pick}: no mask started on the new photo: {:?}", develop(&h).masks.len()), + } + // and the next press paints again (the brush armed again: picking a mask or photo puts it down) + exec(&mut h, "tool.brush", json!({})); + h.step(); + pointer(&mut h, json!([{"kind": "down", "x": 0.3, "y": 0.3}, {"kind": "drag", "x": 0.35, "y": 0.3}, {"kind": "up", "x": 0.35, "y": 0.3}])); + h.step(); + assert!(!develop(&h).masks.is_empty(), "{pick}: a new press paints"); + h.settle(SETTLE); + } +} + /// Lens Blur Brush Refinement: Focus / Blur pick a brush that paints on the photo from the Edit /// panel (one `lensBlur.brushStroke` per drag, with the brush's settings); ⌥ erases; Reset clears. #[test] diff --git a/crates/ui-egui/src/tests/panel_restore.rs b/crates/ui-egui/src/tests/panel_restore.rs new file mode 100644 index 0000000000..cb775e324e --- /dev/null +++ b/crates/ui-egui/src/tests/panel_restore.rs @@ -0,0 +1,393 @@ +//! The panel a tool takes the place of comes back when the tool closes (item 12 of the evening +//! retest): open Edit → Masking (or Crop) → close it → Edit again, at the same width and scroll +//! position, with the photo where it was; a hidden panel stays hidden. + +use std::time::Duration; + +use serde_json::json; + +use crate::headless::Headless; +use crate::state::RightPanel; +use crate::{LightcraftApp, Services}; + +const T: Duration = Duration::from_secs(20); +const SETTLE: Duration = Duration::from_secs(120); + +fn detail() -> Headless { + let services = Services { png: None, ..Default::default() }; + let app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), services); + let mut h = Headless::new(app, [1400.0, 900.0], 1.0); + let r = h.request("ui.set", json!({"view": "detail", "right": "edit"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(SETTLE); + h +} + +fn exec(h: &mut Headless, command: &str) { + let r = h.request("engine.execute", json!({"command": command, "params": {}}), T); + assert_eq!(r["ok"], true, "{command}: {r}"); + h.step(); + h.step(); +} + +fn widget(h: &Headless, id: &str) -> Option { + h.app.widgets.iter().find(|(w, _)| w == id).map(|(_, r)| *r) +} + +/// The Edit panel's first slider on show (its id and where it is: it moves when the panel scrolls). +fn first_slider(h: &Headless) -> (String, egui::Rect) { + let panel = widget(h, "panel:right_panel").expect("the right panel"); + h.app + .widgets + .iter() + .filter(|(w, r)| w.starts_with("slider:") && panel.contains_rect(*r)) + .min_by(|a, b| a.1.top().total_cmp(&b.1.top())) + .map(|(w, r)| (w.clone(), *r)) + .expect("a slider in the Edit panel") +} + +#[test] +fn the_edit_panel_comes_back_after_masking_and_crop_where_it_was() { + let mut h = detail(); + // scroll the Edit panel down a little (the wheel scrolls what the pointer is over) + let panel = widget(&h, "panel:right_panel").expect("the right panel"); + h.request("ui.move", json!({"x": panel.center().x, "y": panel.center().y}), T); + let r = h.request("ui.scroll", json!({"dy": -300.0}), T); + assert_eq!(r["ok"], true, "{r}"); + for _ in 0..60 { + h.step(); + } + let (slider, at) = first_slider(&h); + let photo = widget(&h, "canvas:image").expect("the photo"); + for tool in ["panel.masking", "panel.crop", "panel.remove", "panel.redeye"] { + exec(&mut h, tool); + assert!(h.app.ui.right.is_tool(), "{tool}: {:?}", h.app.ui.right); + assert_eq!(widget(&h, "panel:right_panel"), Some(panel), "{tool}: the panel keeps its place and width"); + // the same button again closes the tool: Edit is back, as it was + exec(&mut h, tool); + assert_eq!(h.app.ui.right, RightPanel::Edit, "{tool}: the Edit panel comes back"); + assert_eq!(widget(&h, "panel:right_panel"), Some(panel), "{tool}: same place and width"); + assert_eq!(widget(&h, "canvas:image"), Some(photo), "{tool}: the photo didn't move"); + assert_eq!(widget(&h, &slider), Some(at), "{tool}: Edit kept its scroll position"); + } + // Masking, then Crop from it, then Crop closed: exactly what was there before, Masking (note 21); then Edit + exec(&mut h, "panel.masking"); + exec(&mut h, "panel.crop"); + exec(&mut h, "panel.crop"); + assert_eq!(h.app.ui.right, RightPanel::Masking); + exec(&mut h, "panel.masking"); + assert_eq!(h.app.ui.right, RightPanel::Edit); + // Return (Done) in a tool also goes back + exec(&mut h, "panel.masking"); + exec(&mut h, "tool.done"); + assert_eq!(h.app.ui.right, RightPanel::Edit); +} + +#[test] +fn a_hidden_panel_stays_hidden_after_a_tool() { + let mut h = detail(); + exec(&mut h, "panel.close"); + assert_eq!(h.app.ui.right, RightPanel::None); + let photo = widget(&h, "canvas:image").expect("the photo"); + for tool in ["panel.masking", "panel.crop"] { + exec(&mut h, tool); + assert!(h.app.ui.right.is_tool(), "{tool} shows"); + exec(&mut h, tool); + assert_eq!(h.app.ui.right, RightPanel::None, "{tool}: nothing shows again"); + h.settle(SETTLE); + assert_eq!(widget(&h, "canvas:image"), Some(photo), "{tool}: the photo is where it was"); + } + exec(&mut h, "panel.masking"); + exec(&mut h, "tool.done"); + assert_eq!(h.app.ui.right, RightPanel::None, "Done: hidden as before"); + // a panel picked meanwhile is what comes back: Info → Masking → closed = Info + exec(&mut h, "panel.info"); + exec(&mut h, "panel.masking"); + exec(&mut h, "panel.masking"); + assert_eq!(h.app.ui.right, RightPanel::Info); +} + +/// "I" toggles the Info panel; pressing it again brings back exactly what the right column showed before, closed +/// included (test notes 2026-10-24 note 21: the Edit sliders stayed gone). +#[test] +fn info_toggled_off_brings_back_exactly_what_was_there() { + let mut h = detail(); + assert_eq!(h.app.ui.right, RightPanel::Edit); + // the key, as the user pressed it + let key = |h: &mut Headless| { + let r = h.request("ui.key", json!({"key": "I"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + h.step(); + }; + key(&mut h); + assert_eq!(h.app.ui.right, RightPanel::Info); + key(&mut h); + assert_eq!(h.app.ui.right, RightPanel::Edit, "Edit → I → I = Edit"); + exec(&mut h, "panel.masking"); + key(&mut h); + assert_eq!(h.app.ui.right, RightPanel::Info); + key(&mut h); + assert_eq!(h.app.ui.right, RightPanel::Masking, "Masks → I → I = Masks"); + // and Masks still closes back to Edit + exec(&mut h, "panel.masking"); + assert_eq!(h.app.ui.right, RightPanel::Edit); + for panel in ["panel.keywords", "panel.versions", "panel.activity"] { + exec(&mut h, panel); + exec(&mut h, panel); + assert_eq!(h.app.ui.right, RightPanel::Edit, "{panel} toggled off: Edit again"); + } + exec(&mut h, "panel.close"); + key(&mut h); + assert_eq!(h.app.ui.right, RightPanel::Info); + key(&mut h); + assert_eq!(h.app.ui.right, RightPanel::None, "closed → I → I = closed"); +} + +/// A `ui.set` that changes something else (here the panel width) keeps a pending toggle: I still puts Edit back +/// (CodeRabbit on #3031). +#[test] +fn a_ui_set_between_the_two_presses_keeps_the_toggle() { + let mut h = detail(); + exec(&mut h, "panel.info"); + assert_eq!(h.app.ui.right, RightPanel::Info); + let r = h.request("ui.set", json!({"rightWidth": 320.0}), T); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + exec(&mut h, "panel.info"); + assert_eq!(h.app.ui.right, RightPanel::Edit, "Edit → I → ui.set → I = Edit"); +} + +/// A tool panel restored from the saved UI state (the panel before it unknown) closes to Edit, not to a hidden column. +#[test] +fn a_tool_restored_from_saved_state_closes_to_edit() { + let mut ui: crate::state::UiState = serde_json::from_str(r#"{"right": "crop"}"#).unwrap(); + assert_eq!(ui.right, RightPanel::Crop); + ui.note_right(); + assert_eq!(ui.leave_tool(), RightPanel::Edit); +} + +/// F8 hiding a tool and F8 showing it again keeps what the tool closes to: Info → Crop → F8 → F8 → Done = Info, not a +/// hidden column (CodeRabbit on #3031). +#[test] +fn a_tool_hidden_and_shown_by_f8_still_closes_to_the_panel_before_it() { + let mut h = detail(); + for close in ["tool.done", "panel.crop"] { + exec(&mut h, "panel.close"); + exec(&mut h, "panel.info"); + assert_eq!(h.app.ui.right, RightPanel::Info); + exec(&mut h, "panel.crop"); + assert_eq!(h.app.ui.right, RightPanel::Crop); + exec(&mut h, "view.rightPanel"); + assert_eq!(h.app.ui.right, RightPanel::None, "F8 hides Crop"); + exec(&mut h, "view.rightPanel"); + assert_eq!(h.app.ui.right, RightPanel::Crop, "F8 shows Crop again"); + exec(&mut h, close); + assert_eq!(h.app.ui.right, RightPanel::Info, "{close}: Info → Crop → F8 → F8 → closed = Info"); + } + // a panel picked while the tool was hidden is not undone: Crop → F8 → Masking → closed = closed, as before + exec(&mut h, "panel.close"); + exec(&mut h, "panel.crop"); + exec(&mut h, "view.rightPanel"); + exec(&mut h, "panel.info"); + exec(&mut h, "panel.masking"); + exec(&mut h, "panel.masking"); + assert_eq!(h.app.ui.right, RightPanel::Info, "a panel picked after F8 is what comes back"); +} + +/// A tool opened another way on the column F8 hid is not F8 showing a tool again: Info → Crop → F8 → Brush → Done +/// leaves the column hidden, as it was when the brush was picked (CodeRabbit on #3031). +#[test] +fn a_tool_opened_on_the_column_f8_hid_closes_to_the_hidden_column() { + let mut h = detail(); + exec(&mut h, "panel.close"); + exec(&mut h, "panel.info"); + exec(&mut h, "panel.crop"); + exec(&mut h, "view.rightPanel"); + assert_eq!(h.app.ui.right, RightPanel::None, "F8 hides Crop"); + exec(&mut h, "tool.brush"); + assert_eq!(h.app.ui.right, RightPanel::Masking); + exec(&mut h, "tool.done"); + assert_eq!(h.app.ui.right, RightPanel::None, "Info → Crop → F8 → Brush → Done = hidden"); +} + +/// A tool opened from another tool keeps where it closes to across F8: Masking → Crop → F8 → F8 → closed = Masking, +/// and Masking then closes to Edit (CodeRabbit on #3031). +#[test] +fn a_nested_tool_hidden_and_shown_by_f8_still_closes_to_the_tool_before_it() { + let mut h = detail(); + for close in ["tool.done", "panel.crop"] { + exec(&mut h, "panel.masking"); + exec(&mut h, "panel.crop"); + assert_eq!(h.app.ui.right, RightPanel::Crop); + exec(&mut h, "view.rightPanel"); + assert_eq!(h.app.ui.right, RightPanel::None, "F8 hides Crop"); + exec(&mut h, "view.rightPanel"); + assert_eq!(h.app.ui.right, RightPanel::Crop, "F8 shows Crop again"); + exec(&mut h, close); + assert_eq!(h.app.ui.right, RightPanel::Masking, "{close}: Masking → Crop → F8 → F8 → closed = Masking"); + exec(&mut h, "panel.masking"); + assert_eq!(h.app.ui.right, RightPanel::Edit, "{close}: then Masking closes to Edit"); + } +} + +/// Toggles nest: Edit → I → K → K → I = Edit, each press taking back exactly the one before it (CodeRabbit on #3031). +#[test] +fn nested_panel_toggles_come_back_one_at_a_time() { + let mut h = detail(); + exec(&mut h, "panel.info"); + exec(&mut h, "panel.keywords"); + assert_eq!(h.app.ui.right, RightPanel::Keywords); + exec(&mut h, "panel.keywords"); + assert_eq!(h.app.ui.right, RightPanel::Info, "Keywords toggled off: Info again"); + exec(&mut h, "panel.info"); + assert_eq!(h.app.ui.right, RightPanel::Edit, "Info toggled off: Edit again"); + // pressing two keys in turn many times keeps a bounded history and still unwinds to a panel + for _ in 0..crate::state::TOGGLE_HISTORY { + exec(&mut h, "panel.info"); + exec(&mut h, "panel.keywords"); + } + assert!(h.app.ui.toggle_return.len() <= crate::state::TOGGLE_HISTORY); + exec(&mut h, "panel.keywords"); + assert_eq!(h.app.ui.right, RightPanel::Info); +} + +/// A tool opened by a command from another tool closes back to that tool, and the panels before it still come back +/// in turn: Info → Crop → B → Done = Crop, Crop closed = Info, I = Edit (CodeRabbit on #3031). +#[test] +fn a_tool_opened_from_another_tool_closes_back_to_it() { + let mut h = detail(); + exec(&mut h, "panel.info"); + exec(&mut h, "panel.crop"); + exec(&mut h, "tool.brush"); + assert_eq!(h.app.ui.right, RightPanel::Masking); + exec(&mut h, "tool.done"); + assert_eq!(h.app.ui.right, RightPanel::Crop, "Info → Crop → B → Done = Crop"); + exec(&mut h, "tool.done"); + assert_eq!(h.app.ui.right, RightPanel::Info, "then Crop closes to Info"); + exec(&mut h, "panel.info"); + assert_eq!(h.app.ui.right, RightPanel::Edit, "and I gives back Edit"); + // a tool opened by a command from a panel closes to that panel + exec(&mut h, "tool.brush"); + exec(&mut h, "tool.done"); + assert_eq!(h.app.ui.right, RightPanel::Edit); +} + +/// Commands run back to back with no frame between them (a batch of control requests) see F8's hide at once: +/// Info → Crop → F8 → Brush → Done leaves the column hidden (CodeRabbit on #3031). +#[test] +fn f8_is_noted_before_the_next_command_of_the_same_frame() { + let mut h = detail(); + exec(&mut h, "panel.close"); + for command in ["panel.info", "panel.crop", "view.rightPanel", "tool.brush", "tool.done"] { + h.app.run(command, json!({})).unwrap_or_else(|e| panic!("{command}: {e}")); + } + assert_eq!(h.app.ui.right, RightPanel::None, "the brush was opened on the hidden column"); +} + +/// Info → Remove → F8 → A (Visualize Spots opens Remove again on the hidden column) → Done leaves the column +/// hidden: F8 kept Remove's record, but this opening is a new one, from the hidden column (CodeRabbit on #3031). +#[test] +fn a_tool_hidden_by_f8_and_opened_again_by_a_command_closes_to_the_hidden_column() { + let mut h = detail(); + for command in ["panel.info", "view.visualizeSpots", "view.rightPanel", "view.visualizeSpots"] { + h.app.run(command, json!({})).unwrap_or_else(|e| panic!("{command}: {e}")); + } + assert_eq!(h.app.ui.right, RightPanel::Remove); + h.app.run("tool.done", json!({})).unwrap_or_else(|e| panic!("tool.done: {e}")); + assert_eq!(h.app.ui.right, RightPanel::None, "Remove was opened again on the hidden column"); + // the same steps a frame apart + let mut h = detail(); + for command in ["panel.info", "view.visualizeSpots", "view.rightPanel", "view.visualizeSpots", "tool.done"] { + exec(&mut h, command); + } + assert_eq!(h.app.ui.right, RightPanel::None, "frame by frame"); +} + +/// Commands run in one frame (a script, queued shortcuts) each see the panel the one before left: Close Panel → +/// B → Done keeps the column hidden, and B → A → Done goes back to Masking (CodeRabbit on #3031). +#[test] +fn every_command_notes_the_panel_it_leaves_on_show() { + let mut h = detail(); + for command in ["panel.close", "tool.brush", "tool.done"] { + h.app.run(command, json!({})).unwrap_or_else(|e| panic!("{command}: {e}")); + } + assert_eq!(h.app.ui.right, RightPanel::None, "the brush was opened on the hidden column"); + let mut h = detail(); + for command in ["tool.brush", "view.visualizeSpots", "tool.done"] { + h.app.run(command, json!({})).unwrap_or_else(|e| panic!("{command}: {e}")); + } + assert_eq!(h.app.ui.right, RightPanel::Masking, "Remove was opened from Masking"); +} + +/// `ui.set` changing the panel notes it at once: a tool opened before the next frame closes back to that panel +/// (CodeRabbit on #3031). +#[test] +fn a_panel_set_by_ui_set_is_noted_before_the_next_command() { + let mut h = detail(); + let (req, _rx) = crate::control::ControlRequest::new("ui.set", json!({"right": "info"})); + let ctx = h.view.ctx.clone(); + let _ = crate::control::handle(&mut h.app, &ctx, &req); + assert_eq!(h.app.ui.right, RightPanel::Info); + for command in ["tool.brush", "tool.done"] { + h.app.run(command, json!({})).unwrap_or_else(|e| panic!("{command}: {e}")); + } + assert_eq!(h.app.ui.right, RightPanel::Info, "the brush was opened from Info"); +} + +/// A tool panel put back by a toggle brings its own on-canvas tool back: Masking's Brush, Remove's Heal or Clone +/// (CodeRabbit on #3031). The panels come back as before (Edit → I → K → K → I = Edit). +#[test] +fn a_panel_put_back_by_a_toggle_keeps_its_tool() { + let mut h = detail(); + exec(&mut h, "panel.masking"); + h.app.ui.tool = "brush".into(); + exec(&mut h, "panel.info"); + assert_eq!(h.app.ui.right, RightPanel::Info); + exec(&mut h, "panel.info"); + assert_eq!(h.app.ui.right, RightPanel::Masking, "Masks → I → I = Masks"); + assert_eq!(h.app.ui.tool, "brush", "Masks → I → I keeps the Brush"); + exec(&mut h, "panel.masking"); + assert_eq!(h.app.ui.right, RightPanel::Edit); + assert_eq!(h.app.ui.tool, "", "Edit comes back with no tool"); + + exec(&mut h, "panel.remove"); + assert_eq!(h.app.ui.right, RightPanel::Remove); + for mode in ["heal", "clone"] { + h.app.ui.tool = mode.into(); + exec(&mut h, "panel.info"); + exec(&mut h, "panel.info"); + assert_eq!(h.app.ui.right, RightPanel::Remove); + assert_eq!(h.app.ui.tool, mode, "Remove → I → I keeps {mode}"); + } + exec(&mut h, "panel.remove"); + assert_eq!(h.app.ui.right, RightPanel::Edit); + + // the panels themselves come back as before + for (command, right) in [ + ("panel.info", RightPanel::Info), + ("panel.keywords", RightPanel::Keywords), + ("panel.keywords", RightPanel::Info), + ("panel.info", RightPanel::Edit), + ] { + exec(&mut h, command); + assert_eq!(h.app.ui.right, right, "Edit → I → K → K → I, after {command}"); + } +} + +/// A toggle that opens a panel while the Tools column is behind another dock tab remembers the +/// column as hidden: toggled off, it doesn't come back with the panel or the on-canvas tool it held +/// out of sight (CodeRabbit on #3031: Remove in Heal behind another tab came back with Heal armed). +#[test] +fn a_toggle_over_a_hidden_tools_column_puts_back_a_hidden_column() { + let mut ui = crate::state::UiState { right: RightPanel::Remove, tool: "heal".into(), ..Default::default() }; + assert!(ui.toggle_panel(RightPanel::Info, false), "Info comes up"); + assert_eq!(ui.right, RightPanel::Info); + assert!(!ui.toggle_panel(RightPanel::Info, true), "and goes"); + assert_eq!(ui.right, RightPanel::None, "the column was out of sight: it stays out of sight"); + assert_eq!(ui.tool, "heal", "no tool put back (the command clears it)"); + let mut ui = crate::state::UiState { right: RightPanel::Edit, ..Default::default() }; + ui.toggle_panel(RightPanel::Info, false); + ui.toggle_panel(RightPanel::Info, true); + assert_eq!(ui.right, RightPanel::None, "Edit behind another tab isn't brought forward either"); +} diff --git a/crates/ui-egui/src/tests/panels.rs b/crates/ui-egui/src/tests/panels.rs index 3e5201a642..3c10e088a9 100644 --- a/crates/ui-egui/src/tests/panels.rs +++ b/crates/ui-egui/src/tests/panels.rs @@ -292,18 +292,18 @@ fn exec(h: &mut Headless, command: &str, params: serde_json::Value) -> serde_jso r["result"].clone() } -/// The View ▸ Sidebar Sections items: (section id or command, checked). +/// The Window ▸ Sidebar Sections items: (section id or command, checked). fn sidebar_menu_items(h: &Headless) -> Vec<(String, Option)> { use crate::menubar::MenuNode; let bar = crate::menubar::menu_bar(&h.app); - let view = &bar.iter().find(|(t, _)| t == "View").expect("View menu").1; - let children = view + let window = &bar.iter().find(|(t, _)| t == "Window").expect("Window menu").1; + let children = window .iter() .find_map(|n| match n { MenuNode::Submenu { label, children } if label == "Sidebar Sections" => Some(children.clone()), _ => None, }) - .expect("View ▸ Sidebar Sections"); + .expect("Window ▸ Sidebar Sections"); children .iter() .filter_map(|n| match n { @@ -313,11 +313,11 @@ fn sidebar_menu_items(h: &Headless) -> Vec<(String, Option)> { .collect() } -/// Given the sidebar, when a section is unchecked in View ▸ Sidebar Sections, then it leaves the +/// Given the sidebar, when a section is unchecked in Window ▸ Sidebar Sections, then it leaves the /// sidebar (header and rows) and the menu shows it unchecked; checking it again brings it back /// as it was. The choice is part of the saved UI state. #[test] -fn a_section_is_hidden_and_shown_from_the_view_menu() { +fn a_section_is_hidden_and_shown_from_the_window_menu() { let mut h = demo([1400.0, 1400.0], json!({"view": "photoGrid", "leftPanel": true})); let checked = |h: &Headless, id: &str| sidebar_menu_items(h).into_iter().find(|(s, _)| s == id).unwrap_or_else(|| panic!("no {id} item")).1; assert_eq!(checked(&h, "byDate"), Some(true)); @@ -2584,7 +2584,8 @@ fn local_photos_cannot_be_added_to_albums_until_they_join_my_photos() { assert_eq!(r["ok"], true, "{r}"); h.step(); - // Photo ▸ Add to Album: the hint item first (off), the album and New Album… off + // Photo ▸ Add to Album: the album and New Album… off, and Add to My Photos is not repeated in it: the Photo + // menu's own item, right below the submenu, is the one row for that command (on for a Local photo) let add_to_album = |app: &LightcraftApp| -> Vec { let bar = crate::menubar::menu_bar(app); let photo = &bar.iter().find(|(t, _)| t == "Photo").expect("Photo menu").1; @@ -2603,7 +2604,12 @@ fn local_photos_cannot_be_added_to_albums_until_they_join_my_photos() { }) }; let nodes = add_to_album(&h.app); - assert!(matches!(nodes.first(), Some(crate::menubar::MenuNode::Item { id, enabled: false, .. }) if id == "photo.addToLibrary"), "{nodes:?}"); + assert_eq!(enabled_of(&nodes, "photo.addToLibrary"), None, "{nodes:?}"); + let bar = crate::menubar::menu_bar(&h.app); + let photo = &bar.iter().find(|(t, _)| t == "Photo").expect("Photo menu").1; + let rows = photo.iter().filter(|n| matches!(n, crate::menubar::MenuNode::Item { id, .. } if id == "photo.addToLibrary")).count(); + assert_eq!(rows, 1, "one Add to My Photos row in the Photo menu: {photo:?}"); + assert_eq!(enabled_of(photo, "photo.addToLibrary"), Some(true), "{photo:?}"); assert_eq!(enabled_of(&nodes, "album.addPhotos"), Some(false), "{nodes:?}"); assert_eq!(enabled_of(&nodes, "dialog.newAlbum"), Some(false), "{nodes:?}"); diff --git a/crates/ui-egui/src/tests/preview_limit.rs b/crates/ui-egui/src/tests/preview_limit.rs index 248ce781cc..d7dfb39475 100644 --- a/crates/ui-egui/src/tests/preview_limit.rs +++ b/crates/ui-egui/src/tests/preview_limit.rs @@ -233,13 +233,16 @@ mod in_the_loupe { } h.request("engine.execute", json!({"command": "view.zoom100"}), T); h.app.ui.pan = (0.3, 0.4); + // (a mask without settings shows its overlay by itself: O hides it for that mask) h.app.ui.mask_overlay = false; + h.app.ui.mask_overlay_hidden = h.app.session.active().zip(h.app.session.active_mask).into_iter().collect(); h.settle(SETTLE); let (zoom, pan) = (h.app.ui.zoom, h.app.ui.pan); assert_eq!(zoom, crate::state::Zoom::Percent(100.0)); let plain = h.app.region_view.expect("a window render without the overlay"); h.app.ui.mask_overlay = true; + h.app.ui.mask_overlay_hidden.clear(); h.settle(SETTLE); let id = h.app.session.active().expect("a photo"); let d = h.app.session.develop_of(id).expect("settings"); @@ -253,6 +256,7 @@ mod in_the_loupe { assert_ne!(shown.settings, plain.settings, "the overlay is part of the window's look"); h.app.ui.mask_overlay = false; + h.app.ui.mask_overlay_hidden = h.app.session.active().zip(h.app.session.active_mask).into_iter().collect(); h.settle(SETTLE); assert_eq!((h.app.ui.zoom, h.app.ui.pan), (zoom, pan), "hiding it keeps them too"); assert_eq!(h.app.region_view.map(|r| r.settings), Some(plain.settings), "back to the plain window"); diff --git a/crates/ui-egui/src/tests/progress.rs b/crates/ui-egui/src/tests/progress.rs index 0371ba61db..259e4ad68b 100644 --- a/crates/ui-egui/src/tests/progress.rs +++ b/crates/ui-egui/src/tests/progress.rs @@ -280,6 +280,9 @@ fn an_activity_bar_is_named_after_its_task() { cancellable: true, cancelling: false, age_ms: 600, + waiting: false, + place: 0, + lane: None, }; let (nodes, _, _) = frames(Vec::new(), |ui| crate::panels::activity::bar(ui, &task, 200.0).rect.width()); let bar = nodes.iter().find(|n| n.role == "ProgressIndicator").unwrap_or_else(|| panic!("{nodes:?}")); diff --git a/crates/ui-egui/src/tests/spot_stroke.rs b/crates/ui-egui/src/tests/spot_stroke.rs new file mode 100644 index 0000000000..c331697fac --- /dev/null +++ b/crates/ui-egui/src/tests/spot_stroke.rs @@ -0,0 +1,267 @@ +//! Headless tests of the Remove tool's brush stroke (issue #2359): points are recorded at a spacing, not one per +//! frame, and a stroke can be grabbed anywhere along it. + +use std::time::Duration; + +use serde_json::json; + +use crate::headless::Headless; +use crate::{LightcraftApp, Services}; + +const T: Duration = Duration::from_secs(20); + +fn remove_tool() -> Headless { + let services = Services { png: None, ..Default::default() }; + let app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), services); + let mut h = Headless::new(app, [1200.0, 800.0], 1.0); + for (req, params) in [("ui.set", json!({"view": "detail"})), ("engine.execute", json!({"command": "panel.remove"}))] { + let r = h.request(req, params, T); + assert_eq!(r["ok"], true, "{r}"); + } + // spots show and can be grabbed whatever the pointer does + let r = h.request("engine.execute", json!({"command": "view.toolOverlay", "params": {"mode": "always"}}), T); + assert_eq!(r["ok"], true, "{r}"); + h.app.ui.remove_size = 0.04; + h +} + +fn pointer(h: &mut Headless, kind: &str, x: f64, y: f64) { + let r = h.request("ui.pointer", json!({"events": [{"kind": kind, "x": x, "y": y}]}), T); + assert_eq!(r["ok"], true, "{r}"); + h.step(); +} + +fn spots(h: &Headless) -> Vec { + h.app.session.develop_of(h.app.session.active().expect("active photo")).unwrap_or_default().spots.clone() +} + +#[test] +fn a_brushed_stroke_stores_points_at_a_spacing_and_ignores_a_held_pointer() { + let mut h = remove_tool(); + pointer(&mut h, "down", 0.3, 0.5); + // 40 frames of 0.002 of the photo's width each: about 1.4 px at this size, a point every r/4 = 8 px + for i in 1..=40 { + pointer(&mut h, "drag", 0.3 + 0.002 * f64::from(i), 0.5); + } + // held still for a while: no point per frame + for _ in 0..15 { + pointer(&mut h, "drag", 0.38, 0.5); + } + pointer(&mut h, "up", 0.38, 0.5); + let s = spots(&h); + assert_eq!(s.len(), 1, "one spot"); + let p = &s[0].points; + assert!((3..=12).contains(&p.len()), "a stroke of ~64 px with a point every ~8 px is a handful of points, got {}", p.len()); + assert!((p[0].x - 0.3).abs() < 0.02, "starts where the button went down: {:?}", p[0]); + let end = p[p.len() - 1]; + assert!((end.x - 0.38).abs() < 0.003 && (end.y - 0.5).abs() < 0.003, "reaches where the pointer was released: {end:?}"); +} + +#[test] +fn a_click_is_still_a_single_point_spot() { + let mut h = remove_tool(); + pointer(&mut h, "down", 0.6, 0.4); + pointer(&mut h, "up", 0.6, 0.4); + let s = spots(&h); + assert_eq!((s.len(), s[0].points.len()), (1, 1)); +} + +#[test] +fn a_stroke_is_grabbed_anywhere_along_it() { + let mut h = remove_tool(); + let r = h.request( + "engine.execute", + json!({"command": "spot.add", "params": {"mode": "heal", "points": [[0.3, 0.5], [0.34, 0.5], [0.38, 0.5], [0.42, 0.5]], "size": 0.04, "source": [0.0, 0.2]}}), + T, + ); + assert_eq!(r["ok"], true, "{r}"); + assert_eq!(spots(&h)[0].points.len(), 4); + // the third point is 0.08 of the width (about 60 px) from the pin: grabbing there moves the spot, adds none + pointer(&mut h, "move", 0.38, 0.5); + pointer(&mut h, "down", 0.38, 0.5); + pointer(&mut h, "drag", 0.38, 0.55); + pointer(&mut h, "drag", 0.38, 0.6); + pointer(&mut h, "up", 0.38, 0.6); + let s = spots(&h); + assert_eq!(s.len(), 1, "grabbed the stroke instead of painting a new spot"); + assert!((s[0].points[0].y - 0.6).abs() < 0.03 && (s[0].points[0].x - 0.3).abs() < 0.01, "{:?}", s[0].points); + assert_eq!(s[0].points.len(), 4); +} + +fn wheel(h: &mut Headless, dy: f32, modifiers: egui::Modifiers) { + h.events.push(egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: egui::vec2(0.0, dy), + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Unknown, + modifiers, + }); + h.step(); +} + +#[test] +fn the_wheel_over_the_photo_sizes_and_feathers_the_brush_instead_of_zooming() { + let mut h = remove_tool(); + let c = h.app.image_rect.expect("photo drawn").center(); + h.request("ui.move", json!({"x": c.x, "y": c.y}), T); + h.step(); + let (zoom, size, feather) = (h.app.ui.zoom, h.app.ui.remove_size, h.app.ui.remove_feather); + wheel(&mut h, 2.0, egui::Modifiers::NONE); + for _ in 0..30 { + h.step(); + } + assert!((h.app.ui.remove_size / size - 1.21).abs() < 0.01, "two notches up: ×1.1², got {} from {size}", h.app.ui.remove_size); + assert_eq!(h.app.ui.zoom, zoom, "the wheel doesn't zoom while the Remove tool is open"); + wheel(&mut h, -1.0, egui::Modifiers::SHIFT); + assert_eq!(h.app.ui.remove_feather, feather - 5.0, "Shift+wheel feathers"); +} + +#[test] +fn a_smooth_scrolling_mouse_sizes_the_brush_too() { + // macOS reports a Magic Mouse, a smooth-scrolling wheel and a trackpad in points, not lines + let mut h = remove_tool(); + let c = h.app.image_rect.expect("photo drawn").center(); + h.request("ui.move", json!({"x": c.x, "y": c.y}), T); + h.step(); + let (zoom, pan, size, feather) = (h.app.ui.zoom, h.app.ui.pan, h.app.ui.remove_size, h.app.ui.remove_feather); + let line = h.view.ctx.options(|o| o.input_options.line_scroll_speed); + for (y, modifiers) in [(line, egui::Modifiers::NONE), (line, egui::Modifiers::NONE), (-line, egui::Modifiers::SHIFT)] { + h.events.push(egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(0.0, y), + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Unknown, + modifiers, + }); + h.step(); + } + for _ in 0..30 { + h.step(); + } + assert!((h.app.ui.remove_size / size - 1.21).abs() < 0.01, "two lines' worth of points: ×1.1², got {} from {size}", h.app.ui.remove_size); + assert_eq!(h.app.ui.remove_feather, feather - 5.0, "Shift+scroll feathers"); + assert_eq!((h.app.ui.zoom, h.app.ui.pan), (zoom, pan), "nor does it zoom or pan"); +} + +#[test] +fn the_wheel_sizes_the_spot_under_the_pointer_and_elsewhere_the_next_stroke() { + let mut h = remove_tool(); + let r = h.request( + "engine.execute", + json!({"command": "spot.add", "params": {"mode": "heal", "points": [[0.3, 0.5]], "size": 0.04, "feather": 40.0, "source": [0.0, 0.2]}}), + T, + ); + assert_eq!(r["ok"], true, "{r}"); + // away from the spot just added (still selected): the brush changes, the spot doesn't + pointer(&mut h, "move", 0.7, 0.5); + let brush = h.app.ui.remove_size; + wheel(&mut h, 1.0, egui::Modifiers::NONE); + assert!((h.app.ui.remove_size / brush - 1.1).abs() < 0.01, "the next stroke's brush grows"); + assert_eq!(spots(&h)[0].size, 0.04, "the selected spot keeps its size"); + assert_eq!(h.app.session.active_spot, None, "and is let go, so the brush no longer shows its settings"); + h.step(); + assert!((h.app.ui.remove_size / brush - 1.1).abs() < 0.01, "the brush keeps its new size"); + // over the spot: that spot changes (and is selected again) + pointer(&mut h, "move", 0.3, 0.5); + wheel(&mut h, 1.0, egui::Modifiers::NONE); + wheel(&mut h, -1.0, egui::Modifiers::SHIFT); + let s = spots(&h); + assert!((s[0].size / 0.04 - 1.1).abs() < 0.01, "the spot under the pointer grows, got {}", s[0].size); + assert_eq!(s[0].feather, 35.0, "and Shift+wheel feathers it"); + assert_eq!(h.app.session.active_spot, Some(0)); +} + +#[test] +fn notches_on_consecutive_frames_all_count_and_undo_as_one_step() { + let mut h = remove_tool(); + let r = h.request( + "engine.execute", + json!({"command": "spot.add", "params": {"mode": "heal", "points": [[0.3, 0.5]], "size": 0.04, "feather": 40.0, "source": [0.0, 0.2]}}), + T, + ); + assert_eq!(r["ok"], true, "{r}"); + pointer(&mut h, "move", 0.3, 0.5); + // a spun wheel: a notch on each of four frames + for _ in 0..4 { + wheel(&mut h, 1.0, egui::Modifiers::NONE); + } + let grown = spots(&h)[0].size; + assert!((grown / 0.04 - 1.1f64.powi(4)).abs() < 0.01, "four notches: ×1.1⁴, got {grown}"); + // the gesture ends off the spot; one undo takes back all of it + pointer(&mut h, "move", 0.7, 0.5); + assert!(h.app.session.interaction.is_none(), "the wheel gesture is committed"); + let r = h.request("engine.execute", json!({"command": "edit.undo"}), T); + assert_eq!(r["ok"], true, "{r}"); + assert_eq!(spots(&h)[0].size, 0.04, "one undo step for the whole gesture"); +} + +#[test] +fn leaving_the_loupe_ends_a_wheel_gesture() { + let mut h = remove_tool(); + let r = h.request( + "engine.execute", + json!({"command": "spot.add", "params": {"mode": "heal", "points": [[0.3, 0.5]], "size": 0.04, "source": [0.0, 0.2]}}), + T, + ); + assert_eq!(r["ok"], true, "{r}"); + pointer(&mut h, "move", 0.3, 0.5); + wheel(&mut h, 1.0, egui::Modifiers::NONE); + assert!(h.app.session.interaction.is_some(), "the wheel gesture is open"); + // straight to the grid, where the loupe (and its wheel handling) no longer draws + let r = h.request("ui.set", json!({"view": "photoGrid"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + assert!(h.app.session.interaction.is_none(), "the wheel gesture is committed, so no later edit joins it"); + let r = h.request("engine.execute", json!({"command": "edit.undo"}), T); + assert_eq!(r["ok"], true, "{r}"); + assert_eq!(spots(&h)[0].size, 0.04, "and is one undo step"); +} + +#[test] +fn the_wheel_sizes_the_spot_the_pointer_has_just_moved_onto() { + let mut h = remove_tool(); + for x in [0.3, 0.7] { + let r = h.request( + "engine.execute", + json!({"command": "spot.add", "params": {"mode": "heal", "points": [[x, 0.5]], "size": 0.04, "source": [0.0, 0.2]}}), + T, + ); + assert_eq!(r["ok"], true, "{r}"); + } + pointer(&mut h, "move", 0.3, 0.5); + // in one frame the pointer moves onto the other spot and the wheel turns + let img = h.app.image_rect.expect("photo drawn"); + let to = egui::pos2(img.min.x + 0.7 * img.width(), img.min.y + 0.5 * img.height()); + h.events.push(egui::Event::PointerMoved(to)); + wheel(&mut h, 1.0, egui::Modifiers::NONE); + let s = spots(&h); + assert_eq!(s[0].size, 0.04, "the spot the pointer left keeps its size"); + assert!((s[1].size / 0.04 - 1.1).abs() < 0.01, "the spot under the pointer grows, got {}", s[1].size); +} + +#[test] +fn a_spot_the_wheel_has_grown_is_grabbed_out_to_its_new_edge() { + let mut h = remove_tool(); + let r = h.request( + "engine.execute", + json!({"command": "spot.add", "params": {"mode": "heal", "points": [[0.5, 0.5]], "size": 0.02, "feather": 0.0, "source": [0.0, 0.2]}}), + T, + ); + assert_eq!(r["ok"], true, "{r}"); + pointer(&mut h, "move", 0.5, 0.5); + // grow it to twice its size, then, in the next frame, move to where only the grown spot reaches and turn on + for _ in 0..8 { + wheel(&mut h, 1.0, egui::Modifiers::NONE); + } + let grown = spots(&h)[0].size; + assert!(grown > 0.04, "{grown}"); + let img = h.app.image_rect.expect("photo drawn"); + let long = img.width().max(img.height()); + // between the outline drawn before the last notch and the grown one (3 pt outside the radius, no feather) + let between = (grown / 1.1 + grown) as f32 / 2.0 * long + 3.0; + let to = egui::pos2(img.center().x + between, img.center().y); + h.events.push(egui::Event::PointerMoved(to)); + wheel(&mut h, 1.0, egui::Modifiers::NONE); + assert!((spots(&h)[0].size / grown - 1.1).abs() < 0.01, "the grown spot is still under the pointer: {}", spots(&h)[0].size); + assert_eq!(h.app.session.active_spot, Some(0), "and stays selected (the brush isn't resized instead)"); +} diff --git a/crates/ui-egui/src/tests/switch_library.rs b/crates/ui-egui/src/tests/switch_library.rs index e2e4f4d115..198c3a3956 100644 --- a/crates/ui-egui/src/tests/switch_library.rs +++ b/crates/ui-egui/src/tests/switch_library.rs @@ -87,6 +87,20 @@ fn switching_libraries_restarts_the_brief_info_overlay() { let _ = std::fs::remove_dir_all(dir); } +/// Masks hidden with O are keyed by photo and mask ID, both local to a library: a mask in the new +/// library with the same IDs is not hidden by them. +#[test] +fn switching_libraries_forgets_the_masks_hidden_with_o() { + let dir = temp("switch-hidden-masks"); + let mut app = app_in(&dir); + app.ui.mask_overlay_hidden = vec![(lightcraft_catalog::PhotoId(1), 1)]; + app.ui.mask_hover = Some((lightcraft_catalog::PhotoId(1), 1)); + app.run("app.newLibrary", json!({"path": dir.to_string_lossy(), "name": "Second"})).unwrap(); + assert!(app.ui.mask_overlay_hidden.is_empty()); + assert_eq!(app.ui.mask_hover, None); + let _ = std::fs::remove_dir_all(dir); +} + fn recent_submenu(app: &LightcraftApp) -> Vec { use crate::menubar::MenuNode; let bar = crate::menubar::menu_bar(app); diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 965944a026..22b461cc00 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -584,6 +584,9 @@ pub fn apply_kind(ctx: &egui::Context, kind: ThemeKind) { s.text_styles.insert(egui::TextStyle::Small, FontId::proportional(11.0)); s.text_styles.insert(egui::TextStyle::Heading, FontId::new(16.0, FontFamily::Name(FONT_SEMIBOLD.into()))); s.animation_time = animation_time; + // Captions and headings are not text to select (#1885); text meant for copying opts in + // with `Label::selectable(true)`. + s.interaction.selectable_labels = false; }); } @@ -695,6 +698,46 @@ mod tests { } } + /// Drag the pointer across `label` from end to end, press Copy, and return what egui copied. + fn drag_and_copy(label: impl Fn() -> egui::Label) -> Option { + let ctx = egui::Context::default(); + apply_kind(&ctx, ThemeKind::default()); + let frame = |events: Vec| { + let input = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(400.0, 200.0))), + events, + ..Default::default() + }; + let mut rect = egui::Rect::NOTHING; + let mut out = ctx.run_ui(input, |ui| rect = ui.add(label()).rect); + out.textures_delta.clear(); + (out.platform_output.commands, rect) + }; + let (_, rect) = frame(vec![]); + let (from, to) = (rect.left_center() + egui::vec2(1.0, 0.0), rect.right_center() - egui::vec2(1.0, 0.0)); + let button = + |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + let mut commands = Vec::new(); + for events in [ + vec![egui::Event::PointerMoved(from)], + vec![button(from, true)], + vec![egui::Event::PointerMoved(to)], + vec![button(to, false)], + vec![egui::Event::Copy], + ] { + commands.extend(frame(events).0); + } + commands.into_iter().find_map(|c| if let egui::OutputCommand::CopyText(text) = c { Some(text) } else { None }) + } + + /// #1885: a panel caption is not text to select, as in Lightroom; text a dialog offers for + /// copying (a path) opts in and still copies. + #[test] + fn static_labels_cannot_be_drag_selected_but_opted_in_text_can() { + assert_eq!(drag_and_copy(|| egui::Label::new("Exposure")), None, "a plain label was selected and copied"); + assert_eq!(drag_and_copy(|| egui::Label::new("/Users/me/Pictures").selectable(true)).as_deref(), Some("/Users/me/Pictures")); + } + /// #736: the release input must carry Thai, not silently skip the check with an older pin. /// Exercise the Thai characters of the reported folder name through every egui family. #[test] diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 64cd1db99e..37270e628b 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -993,7 +993,7 @@ mod slider; pub use hit_area::{HitArea, HitAreaOutput}; pub use icon_button::IconButtonOutput; pub(crate) use slider::{Row as SliderRow, field as slider_field, slider_row, slider_salted}; -pub use slider::{SliderOut, slider}; +pub use slider::{SliderOut, slider, slider_named}; mod text_button; pub mod text_field; pub use text_button::TextButtonOutput; diff --git a/crates/ui-egui/src/widgets/slider.rs b/crates/ui-egui/src/widgets/slider.rs index d39b3075df..50594dd87b 100644 --- a/crates/ui-egui/src/widgets/slider.rs +++ b/crates/ui-egui/src/widgets/slider.rs @@ -59,6 +59,17 @@ pub fn slider(ui: &mut Ui, spec: &ControlSpec, value: f64, enabled: bool, label_ slider_salted(ui, spec, value, enabled, label_override, egui::Id::NULL) } +/// [`slider`] with an already translated spoken name, distinct from the short painted caption. +/// HSL's All view repeats each colour under three group headings. +pub fn slider_named(ui: &mut Ui, spec: &ControlSpec, value: f64, enabled: bool, label: Option<&str>, spoken: Option<&str>) -> SliderOut { + let row = Row { spec, value, enabled, label, salt: egui::Id::NULL, record: None }; + let shown = field_named(ui, &row, spoken); + if !real(ui) { + return SliderOut::default(); + } + summarize(&shown.out.events, value) +} + /// [`slider`], its state kept apart per `salt` (the photo it edits). pub(crate) fn slider_salted(ui: &mut Ui, spec: &ControlSpec, value: f64, enabled: bool, label: Option<&str>, salt: egui::Id) -> SliderOut { slider_row(ui, &Row { spec, value, enabled, label, salt, record: None }) @@ -116,6 +127,10 @@ pub(crate) fn summarize(events: &EditEvents, current: f64) -> SliderOut { /// The framework row for `row`, with LightCraft's steps, grammar, track and automation names. pub(crate) fn field(ui: &mut Ui, row: &Row<'_>) -> Shown { + field_named(ui, row, None) +} + +fn field_named(ui: &mut Ui, row: &Row<'_>, spoken: Option<&str>) -> Shown { let spec = row.spec; let number_spec = *spec; let name = crate::i18n::tr(row.label.unwrap_or(spec.label)).to_owned(); @@ -183,7 +198,7 @@ pub(crate) fn field(ui: &mut Ui, row: &Row<'_>) -> Shown { }); let mut track = None; if let Some(record) = record { - track = publish(ui, row, id, &name, &out, &record); + track = publish(ui, row, id, spoken.unwrap_or(&name), &out, &record); } Shown { out, track } } @@ -250,6 +265,8 @@ fn publish( match prefix { "slider" => { track = Some(element.id); + // Keep the framework slider and all its semantics; only qualify its spoken name. + super::screen_reader_name(ctx, element.id, name); let thumb = record .hits .iter() diff --git a/crates/ui-egui/src/window_place.rs b/crates/ui-egui/src/window_place.rs index c37f6064b7..20e6d1f80e 100644 --- a/crates/ui-egui/src/window_place.rs +++ b/crates/ui-egui/src/window_place.rs @@ -318,5 +318,166 @@ impl WindowWatch { } } +/// How long after the window first shows it is maximized (Windows): a frame or two, so that it is on +/// its screen and the system maximizes it to that screen's work area. +const MAXIMIZE_AFTER_SECONDS: f64 = 0.1; +/// How long after asking the window is checked: the system animates a maximize. +const MAXIMIZE_CHECK_SECONDS: f64 = 0.6; +/// A maximized window this much of its screen across, and down, fills it (the taskbar, and the +/// borders Windows keeps off screen, take the rest). +const MAXIMIZED_ACROSS: f32 = 0.9; +const MAXIMIZED_DOWN: f32 = 0.75; +/// `zoom` when it is a usable interface zoom, else 1. +fn interface_zoom(zoom: f32) -> f32 { + if zoom.is_finite() && zoom > 0.0 { zoom } else { 1.0 } +} + +/// The window's minimum in the system's points: [`MIN_SIZE`] is in the interface's, which `zoom` scales (at 2× a +/// 900 × 560 minimum holds the window to 1800 × 1120). +fn native_min(zoom: f32) -> [f32; 2] { + [MIN_SIZE[0] * zoom, MIN_SIZE[1] * zoom] +} + +/// When the window's minimum (at `zoom`) is larger than `room` (system points) on either side: the command that lowers +/// it to `room`, in the interface's points. Nothing when the minimum fits. +fn min_within(room: [f32; 2], zoom: f32) -> Vec { + let min = native_min(zoom); + if min[0] > room[0] || min[1] > room[1] { + let lowered = [min[0].min(room[0]), min[1].min(room[1])]; + return vec![egui::ViewportCommand::MinInnerSize(egui::vec2(lowered[0] / zoom, lowered[1] / zoom))]; + } + Vec::new() +} + +/// A window opened larger than its screen is fitted to this much of it. +const FIT_TO_SCREEN: f32 = 0.9; +/// How long after its first frame the window is placed at most: one that stays unseen, full +/// screen or minimized that long is left as it is. +const PLACE_WITHIN_SECONDS: f64 = 5.0; + +/// The window as it first shows. On Windows a window built maximized could open +/// covering half the screen while the system took it for maximized: its maximize button then +/// restored it, smaller. So there it opens at its remembered size and is maximized once it is on its +/// screen ([`StartPlace::new`] with `maximize_after`); if it then says it is maximized but doesn't +/// fill its screen, it is restored and maximized again, once. A window remembered larger than the +/// screen it opens on (a display unplugged, a smaller one, another scale) is fitted to that screen. +#[derive(Debug)] +pub struct StartPlace { + /// Maximize once the window shows. + maximize: bool, + /// When it was asked to (seconds), and whether it has been asked again. + asked: Option, + retried: bool, + /// When the window first showed, and when it was first looked at. + shown: Option, + first_step: Option, + done: bool, + /// The size it was remembered at (system points), before the system or eframe fitted it to its screen. + remembered: Option<[f32; 2]>, +} + +impl StartPlace { + /// `maximize_after`: the window was built at its size and should be maximized once it shows. + pub fn new(maximize_after: bool) -> StartPlace { + StartPlace { maximize: maximize_after, asked: None, retried: false, shown: None, first_step: None, done: false, remembered: None } + } + + /// The size the window was remembered at and built with (`size`, system points): a window remembered larger + /// than its screen is fitted to it even when it was clamped to the whole screen before it was first seen + /// (eframe clamps a remembered 1600 × 1000 to a 1280 × 720 screen). + pub fn remembered(mut self, size: Option<[f32; 2]>) -> StartPlace { + self.remembered = size.filter(|s| s.iter().all(|v| v.is_finite())); + self + } + + /// Whether there is nothing more to do. + pub fn done(&self) -> bool { + self.done + } + + /// The window is `seen` at time `now` (seconds), with the interface zoomed by `zoom`: what to + /// tell it. + pub fn step(&mut self, seen: &Seen, now: f64, zoom: f32) -> Vec { + if self.done { + return Vec::new(); + } + // (not shown yet, its screen unknown, full screen or minimized: wait, but not for ever) + if self.out_of_time(now) { + return Vec::new(); + } + if seen.full_screen || seen.minimized { + return Vec::new(); + } + let (Some(size), Some(screen)) = (seen.size, seen.screen) else { return Vec::new() }; + let shown = *self.shown.get_or_insert(now); + if !self.maximize { + self.done = true; + // remembered larger than this screen: fitted to it, and never larger than it (a screen smaller than + // the window's minimum lowers the minimum to the screen) + let larger = |s: [f32; 2]| s[0] > screen[0] + SAME_WITHIN || s[1] > screen[1] + SAME_WITHIN; + if !seen.zoomed && (larger(size) || self.remembered.is_some_and(larger)) { + // (`seen` is in the system's points, the commands in the interface's) + let zoom = interface_zoom(zoom); + let min = native_min(zoom); + let side = |i: usize| (screen[i] * FIT_TO_SCREEN).max(min[i]).min(screen[i]); + let fit = [side(0), side(1)]; + // a minimum larger than the fitted size (a small screen, a zoomed interface) is lowered to it first + let mut told = min_within(fit, zoom); + told.push(egui::ViewportCommand::InnerSize(egui::vec2(fit[0] / zoom, fit[1] / zoom))); + return told; + } + return Vec::new(); + } + let fills = size[0] >= screen[0] * MAXIMIZED_ACROSS && size[1] >= screen[1] * MAXIMIZED_DOWN; + match self.asked { + None if now - shown >= MAXIMIZE_AFTER_SECONDS => { + self.asked = Some(now); + // a screen smaller than the window's minimum lowers it first, or the maximized window would stay wider + let mut told = min_within(screen, interface_zoom(zoom)); + told.push(egui::ViewportCommand::Maximized(true)); + told + } + None => Vec::new(), + Some(at) if now - at < MAXIMIZE_CHECK_SECONDS => Vec::new(), + Some(_) if seen.zoomed && fills => { + self.done = true; + Vec::new() + } + Some(_) if !self.retried => { + // maximized in name only (or not at all): restore it, and maximize it again + self.retried = true; + self.asked = Some(now); + vec![egui::ViewportCommand::Maximized(false), egui::ViewportCommand::Maximized(true)] + } + Some(_) => { + self.done = true; + Vec::new() + } + } + } + + /// A pass with nothing to place by (the window is hidden: its size is stale) at time `now`: the time limit + /// still runs, so a window kept hidden ends the placement and stops asking to be looked at. + pub fn idle(&mut self, now: f64) { + if !self.done { + self.out_of_time(now); + } + } + + /// Whether placing has gone on for longer than it may (it is then done); its clock starts at the first pass. + fn out_of_time(&mut self, now: f64) -> bool { + let first = *self.first_step.get_or_insert(now); + if now - first > PLACE_WITHIN_SECONDS { + self.done = true; + } + self.done + } + + /// When to look again while it waits (the app may have nothing else to draw). + pub fn waits(&self) -> Option { + (!self.done).then(|| std::time::Duration::from_millis(100)) + } +} + #[cfg(test)] mod tests; diff --git a/crates/ui-egui/src/window_place/tests.rs b/crates/ui-egui/src/window_place/tests.rs index 80d463f197..2ada192d28 100644 --- a/crates/ui-egui/src/window_place/tests.rs +++ b/crates/ui-egui/src/window_place/tests.rs @@ -592,3 +592,113 @@ fn what_was_remembered_is_checked_and_never_costs_the_other_settings() { assert_eq!(place(size, false).checked(), None, "{size:?}"); } } + +/// On Windows the window opens at its size and is maximized once it shows; a +/// window that says it is maximized but covers half its screen is restored and maximized again, +/// once; a window remembered larger than its screen is fitted to it. +#[test] +fn the_window_is_maximized_once_it_shows_and_again_if_it_only_says_so() { + use egui::ViewportCommand as C; + let mut s = StartPlace::new(true); + assert!(s.step(&Seen::default(), 0.0, 1.0).is_empty(), "not shown yet"); + assert!(s.step(&window([1300.0, 800.0]), 0.0, 1.0).is_empty(), "a frame first"); + assert_eq!(s.step(&window([1300.0, 800.0]), 0.2, 1.0), vec![C::Maximized(true)]); + assert!(s.step(&window([1300.0, 800.0]), 0.3, 1.0).is_empty(), "the system animates"); + // maximized in name, half the screen: once more + let half = Seen { zoomed: true, ..window([1280.0, 1400.0]) }; + assert_eq!(s.step(&half, 1.0, 1.0), vec![C::Maximized(false), C::Maximized(true)]); + let full = Seen { zoomed: true, ..window([2560.0, 1392.0]) }; + assert!(s.step(&full, 1.2, 1.0).is_empty()); + assert!(s.step(&full, 1.7, 1.0).is_empty() && s.done()); + assert_eq!(s.waits(), None); + // it filled its screen the first time: nothing more + let mut s = StartPlace::new(true); + s.step(&window([1300.0, 800.0]), 0.0, 1.0); + s.step(&window([1300.0, 800.0]), 0.2, 1.0); + assert!(s.step(&full, 1.0, 1.0).is_empty() && s.done()); + // never more than one retry + let mut s = StartPlace::new(true); + s.step(&window([1300.0, 800.0]), 0.0, 1.0); + s.step(&window([1300.0, 800.0]), 0.2, 1.0); + assert_eq!(s.step(&half, 1.0, 1.0).len(), 2); + assert!(s.step(&half, 2.0, 1.0).is_empty() && s.done()); + // not to be maximized: a window larger than its screen is fitted to it + let mut s = StartPlace::new(false); + let big = Seen { size: Some([3000.0, 2000.0]), screen: Some([1920.0, 1080.0]), ..Default::default() }; + assert_eq!(s.step(&big, 0.0, 1.0), vec![C::InnerSize(egui::vec2(1728.0, 972.0))]); + assert!(s.done() && s.step(&big, 1.0, 1.0).is_empty()); + let mut s = StartPlace::new(false); + assert!(s.step(&window([1300.0, 800.0]), 0.0, 1.0).is_empty() && s.done()); + // full screen or minimized: left alone + let mut s = StartPlace::new(true); + assert!(s.step(&Seen { full_screen: true, ..window([2560.0, 1440.0]) }, 1.0, 1.0).is_empty()); + // ... but not for ever: it stops asking for frames + assert!(s.step(&Seen { full_screen: true, ..window([2560.0, 1440.0]) }, 6.5, 1.0).is_empty()); + assert!(s.done() && s.waits().is_none()); + // a window that never says its size or screen is given up on too + let mut s = StartPlace::new(true); + assert!(s.step(&Seen::default(), 0.0, 1.0).is_empty()); + assert!(s.step(&Seen::default(), 5.5, 1.0).is_empty() && s.done()); + // the interface zoomed 2×: the fitted size is asked for in its points, half the system's + let mut s = StartPlace::new(false); + // (its 900 × 560 minimum is 1800 × 1120 there, taller than the 1080 screen: lowered to the fitted size first) + assert_eq!(s.step(&big, 0.0, 2.0), vec![C::MinInnerSize(egui::vec2(900.0, 540.0)), C::InnerSize(egui::vec2(900.0, 540.0))]); +} + +/// A screen smaller than the window's minimum (800 × 600 beside a 900 pt minimum): the window is fitted within it +/// and the minimum is lowered to it, so it never asks for more than the screen (CodeRabbit on #2974). +#[test] +fn a_window_on_a_screen_smaller_than_its_minimum_fits_within_the_screen() { + use egui::ViewportCommand as C; + let mut s = StartPlace::new(false); + let small = Seen { size: Some([900.0, 560.0]), screen: Some([800.0, 600.0]), ..Default::default() }; + assert_eq!(s.step(&small, 0.0, 1.0), vec![C::MinInnerSize(egui::vec2(800.0, 560.0)), C::InnerSize(egui::vec2(800.0, 560.0))]); + // remembered maximized on that screen: the minimum is lowered before it is maximized, or it would stay wider + let mut s = StartPlace::new(true); + s.step(&small, 0.0, 1.0); + assert_eq!(s.step(&small, 0.2, 2.0), vec![C::MinInnerSize(egui::vec2(400.0, 300.0)), C::Maximized(true)]); + // a screen larger than the minimum, but not than the minimum the zoomed interface makes of it (CodeRabbit on #2974) + let mut s = StartPlace::new(true); + let laptop = Seen { size: Some([1100.0, 700.0]), screen: Some([1200.0, 800.0]), ..Default::default() }; + s.step(&laptop, 0.0, 2.0); + assert_eq!(s.step(&laptop, 0.2, 2.0), vec![C::MinInnerSize(egui::vec2(600.0, 400.0)), C::Maximized(true)]); + let mut s = StartPlace::new(false); + let wide = Seen { size: Some([1600.0, 1000.0]), ..laptop }; + assert_eq!(s.step(&wide, 0.0, 2.0), vec![C::MinInnerSize(egui::vec2(600.0, 400.0)), C::InnerSize(egui::vec2(600.0, 400.0))]); + // a screen the minimum fits on keeps the minimum + let mut s = StartPlace::new(true); + s.step(&window([1300.0, 800.0]), 0.0, 1.0); + assert_eq!(s.step(&window([1300.0, 800.0]), 0.2, 1.0), vec![C::Maximized(true)]); + let mut s = StartPlace::new(false); + let big = Seen { size: Some([3000.0, 2000.0]), screen: Some([1920.0, 1080.0]), ..Default::default() }; + assert_eq!(s.step(&big, 0.0, 1.0), vec![C::InnerSize(egui::vec2(1728.0, 972.0))]); +} + +/// eframe clamps a remembered 1600 × 1000 window to a 1280 × 720 screen before it is first seen: the remembered +/// size still has it fitted to 90 % of the screen, not left covering all of it (CodeRabbit on #2974). +#[test] +fn a_window_clamped_to_its_screen_before_it_shows_is_still_fitted() { + use egui::ViewportCommand as C; + let clamped = Seen { size: Some([1280.0, 720.0]), screen: Some([1280.0, 720.0]), ..Default::default() }; + let mut s = StartPlace::new(false).remembered(Some([1600.0, 1000.0])); + assert_eq!(s.step(&clamped, 0.0, 1.0), vec![C::InnerSize(egui::vec2(1152.0, 648.0))]); + // remembered within the screen: left as it is + let mut s = StartPlace::new(false).remembered(Some([1200.0, 700.0])); + assert!(s.step(&clamped, 0.0, 1.0).is_empty() && s.done()); + // nothing remembered: as before + let mut s = StartPlace::new(false); + assert!(s.step(&clamped, 0.0, 1.0).is_empty()); +} + +/// A window kept hidden while it is being placed still ends the placement in time, and then stops asking to be +/// looked at (CodeRabbit on #2974). +#[test] +fn placement_ends_in_time_while_the_window_is_hidden() { + let mut s = StartPlace::new(true); + s.idle(0.0); + assert!(!s.done() && s.waits().is_some(), "still within its time"); + s.idle(PLACE_WITHIN_SECONDS + 0.1); + assert!(s.done()); + assert_eq!(s.waits(), None); + assert!(s.step(&window([1300.0, 800.0]), PLACE_WITHIN_SECONDS + 0.2, 1.0).is_empty()); +} diff --git a/crates/ui-egui/tests/it/accessibility.rs b/crates/ui-egui/tests/it/accessibility.rs index b8b6cd4958..76b79f3d3f 100644 --- a/crates/ui-egui/tests/it/accessibility.rs +++ b/crates/ui-egui/tests/it/accessibility.rs @@ -3,7 +3,10 @@ //! node with no name, a slider without its value and range, or a canvas tool no key can reach. use egui::accesskit::Role; use egui::vec2; -use egui_kittest::{Harness, kittest::NodeT}; +use egui_kittest::{ + Harness, + kittest::{NodeT, Queryable}, +}; use lightcraft_ui_egui::{ LightcraftApp, Services, state::{RightPanel, ViewMode}, @@ -345,3 +348,30 @@ fn import_button_describes_its_shortcut_as_this_platform_writes_it() { let help = lightcraft_ui_egui::menubar::shortcut_text(sc, mac); assert!(button_described(&h, "Import Photos…", &help), "a button named \"Import Photos…\" describing {help:?}"); } + +/// Settings' filter reads every tab by drawing it in a context of its own. That reading leaves the +/// window's tree as it was: one Settings window, no interactive node left unnamed by it, and what was found +/// listed as the window's own widgets. +#[test] +fn the_settings_filter_reads_the_tabs_without_touching_the_tree() { + let mut h = harness(ViewMode::PhotoGrid, RightPanel::None); + // (the External Editor tab's text has a "▸" the fonts lack: drawn as a box here, as in the app, + // not a panic as the kittest harness has it by default) + h.ctx.set_missing_glyph_policy(egui::MissingGlyphPolicy::Tofu); + h.state_mut().run("app.settings", serde_json::json!({"tab": "general"})).unwrap(); + h.run_steps(8); + let windows = + |h: &Harness<'_, LightcraftApp>| h.root().children_recursive().map(|n| n.accesskit_node()).filter(|n| n.role() == Role::Window).count(); + let before = windows(&h); + // (what Settings leaves unnamed of its own is not this test's: the filter adds none to it) + let unnamed = |h: &Harness<'_, LightcraftApp>| audit(h, "settings").len(); + let unnamed_before = unnamed(&h); + let filter = h.get_by_label("Filter settings"); + filter.click(); + h.run_steps(2); + h.get_by_label("Filter settings").type_text("cache"); + h.run_steps(8); + assert!(h.state().widgets.iter().any(|(id, _)| id.starts_with("settingsFound:")), "the filter lists what it found"); + assert_eq!(windows(&h), before, "reading the tabs adds no window to the tree"); + assert!(unnamed(&h) <= unnamed_before, "the filter and what it found are named: {} unnamed, {unnamed_before} before", unnamed(&h)); +} diff --git a/docs/ai-masks.md b/docs/ai-masks.md index a10933a3f9..20c3b13d87 100644 --- a/docs/ai-masks.md +++ b/docs/ai-masks.md @@ -2,8 +2,10 @@ LightCraft selects objects with **SAM 3** (Segment Anything with Concepts, Meta 2025), run in pure Rust by `crates/segment` on [candle](https://github.com/huggingface/candle): on the GPU -through Metal on macOS, on the CPU elsewhere (for now). If the Mac's GPU can't run it, it runs on -the CPU (see the worker below). +through Metal on macOS (if the Mac's GPU can't run it, it runs on the CPU, see the worker below); on Linux and Windows the image encoder (most of the work) runs on the GPU +through wgpu (Vulkan / DX12), with the two necks and the text detector's DETR encoder and mask +decoder, and the rest on the CPU, falling back to the CPU when there is no usable GPU +([Where it runs](#where-it-runs)). **The model is optional.** It is not part of LightCraft, and nothing requires it: without it, Object, Describe and Lens Blur's **Find Subject** offer to download it, every other feature (and @@ -48,19 +50,91 @@ In the Masking panel (M): so small objects get 5–10× finer edges than one pass over the whole photo gives. The first Object or Describe on a photo analyzes it (the image encoder runs once per photo and -look: ~3 s on an Apple M4 Pro, ~11 s on the CPU of a 12-core Ryzen 9 3900X, plus a one-time ~6 s -for compiling GPU kernels and loading the model after launch). That starts in the background as -soon as you pick Object; after it, each click takes ~35 ms and each description ~0.6 s (~0.15 s -and ~2 s on that CPU). Everything the model does runs on its own worker thread: the window stays -responsive, a click shows its dot at once and the selection follows when it's computed -("Selecting…" / "Analyzing the photo…" under the mask tiles). The model is unloaded after 10 -minutes without use (it takes several GB of memory) and loaded again when needed. +look: ~3 s on an Apple M4 Pro, plus a one-time ~6 s for compiling GPU kernels and loading the +model after launch; ~0.6 s on an RTX 5070 under Linux, of which 0.45 s is the image encoder and +0.12 s the click features, plus ~1–2 s once for loading the model onto the GPU; ~11 s with all of +it on the CPU of a 12-core Ryzen 9 3900X). That starts in the background as soon as you pick +Object; after it, each click takes ~35 ms and each description ~0.6 s (~0.15 s and ~2 s on that +CPU). Everything the model does runs on its own worker thread: the window stays responsive, a +click shows its dot at once and the selection follows when it's computed ("Selecting…" / +"Analyzing the photo…" under the mask tiles). The model is unloaded after 10 minutes without use +(it takes several GB of memory) and loaded again when needed. The result is stored with the mask: the model's 288 × 288 mask logits over the uncropped photo (quantized, compressed, ~10–30 KB). Renders and exports sample them at any resolution and never need the model, so masks survive moving the library to a machine without it, and the web build renders them. Editing the photo's look later does not recompute a mask (click again to update). +## Where it runs + +| | Image encoder (once per photo) | Click features, clicks, descriptions | +|---|---|---| +| macOS | GPU: Metal (candle) | GPU: Metal (candle) | +| Linux, Windows | GPU: wgpu compute on Vulkan / DX12 (`lightcraft-gpu`, module `sam3`) | the two necks and the text detector's DETR encoder and mask decoder on the GPU (wgpu); the click decoder, the text encoder and the DETR decoder on the CPU (candle) | +| no usable GPU, `LIGHTCRAFT_GPU=0` / `LIGHTCRAFT_GPU_BACKEND=off`, or the GPU failed; outside macOS also GPU rendering off | CPU (candle) | CPU (candle) | +| **CPU** chosen in Settings (any platform, macOS included) | CPU (candle) | CPU (candle) | + +Measured on Linux (AMD Ryzen 9 3900X, 12 cores / 24 threads; NVIDIA RTX 5070), release build, +the photo already rendered: + +| Step | CPU only | On the GPU | +|---|---|---| +| Image encoder (once per photo) | 30.2–31.2 s | 0.49–0.57 s (0.43–0.44 s of it on the GPU, see [gpu-pipeline.md](gpu-pipeline.md#sam-3-backbone-m12)) | +| Loading the model (once, and again after 10 min idle) | ~1.5 s | ~1.8 s (device and kernels 0.16–1 s, weight upload ~1.1 s) | +| A photo's whole analysis before its first click | 32.3–33.4 s | 0.56–0.69 s | +| Click features (once per photo, before the first click) | 2.1–2.3 s | 0.12–0.19 s (the tracker neck on the GPU, 38 ms) | +| A click | ~0.14 s | ~0.14 s (CPU) | +| First description on a photo (detector features + text) | 6.3–6.9 s | 0.5–0.8 s (1.3 s the very first time, with the detector loading) (the detector neck, the DETR encoder and the mask decoder on the GPU) | +| A further description | 4.4–4.5 s | ~0.7 s (the DETR encoder and the mask decoder on the GPU, 24 + 33 ms; the rest on the CPU) | +| A prompt used before (on this or an earlier photo; the latest 16 are kept) | ~4.35 s | 0.45–0.46 s (no text encoder) | + +(CPU: `cargo run -p lightcraft-segment --release --example sam3_bench -- `; GPU: +`LIGHTCRAFT_SAM3_DIR= cargo run -p lightcraft-gpu --release --features sam --example +sam3_backbone_bench -- --app`, and the desktop app's log lines, `SAM 3 loaded in …` and `SAM 3 +analyzed …`. What each GPU part takes: [gpu-pipeline.md](gpu-pipeline.md#sam-3-backbone-m12).) + +**Falling back.** When the GPU can't be used (no adapter, a software one, the driver refuses the +device, not enough memory) the model loads with the image encoder on the CPU. When the GPU fails +on a photo (device lost, an output of the wrong size or with NaN), that photo is analyzed again on +the CPU and the model stays there until it loads again (except while LightCraft is closing: then +the work ends with its error, and nothing starts on the CPU). Neither is an error: the log says why +(`SAM 3 backbone accelerator unavailable (…)`, `SAM 3 backbone failed on … (…)`), and so do +Settings and `segment.model.status`. + +**Forcing the CPU.** Choose **Settings ▸ Performance ▸ AI masks ▸ Run on: CPU** +(`segment.settings {"runOn": "cpu"}`; back with `"auto"`, the default). It puts all of SAM 3 on the +CPU on every platform, macOS included (candle's CPU device instead of Metal), for a GPU that can't +run the model, and leaves GPU rendering alone. The choice is kept in +`/models/sam3-settings.json` (`{"runOn": "cpu"}`) and `segment.model.status` reports it as +`runOn`. Automatic also gives way to the switches every GPU compute in LightCraft follows (AI +Denoise, faces): `LIGHTCRAFT_GPU=0` / `LIGHTCRAFT_GPU_BACKEND=off` at start (no GPU at all for the +process) put SAM 3 on the CPU on every platform, macOS included; **Settings ▸ Performance ▸ Use the +GPU for rendering** off (`app.gpu {"enabled": false}`) does so outside macOS, where it governs the +wgpu kernels, while on macOS candle keeps Metal. When a switch changes where it runs, a model +already loaded moves at its next request (it loads again). + +**Seeing where it runs.** Settings ▸ Performance ▸ AI masks shows what the image encoder runs on +(the GPU's name, "Metal GPU" or "CPU", with the reason when it is not on the GPU) and how long the +last photo took. `segment.model.status` → `backend` says the same for agents and scripts: + +```json +"backend": { + "device": "NVIDIA GeForce RTX 5070 (Vulkan)", + "runtime": "wgpu", + "heads": "CPU; the necks, the DETR encoder and the mask decoder on the GPU", + "fallback": null, + "encodeMs": 1234, + "analyzeMs": 3456 +} +``` + +`device` is what runs the image encoder (`null` until the model first loads), `runtime` `wgpu` +(LightCraft's kernels) or `candle`, `heads` what runs the rest, `fallback` why the encoder is not on +the GPU where it could be, `encodeMs` the last image encoder run and `analyzeMs` the last photo's +analysis before its first click (encoder and click features). The log (info level) has each load +(`SAM 3 loaded in …: the backbone on the …, the rest on the CPU; the necks, the DETR encoder and the +mask decoder on the GPU`) and each photo (`SAM 3 analyzed W×H in …: backbone … on the …, click features … on the …`). + ## Remote Metal inference Native builds with `sam` can keep the editor, RAW files, library, and exports local while @@ -81,13 +155,17 @@ LIGHTCRAFT_SAM3_REMOTE=127.0.0.1:8793 lightcraft Object clicks, Describe prompts, detail refinement and Lens Blur's Find Subject (people and animals, from the camera's focus point when the file records it) use the remote worker; a worker older than the -app rejects a request it doesn't know with an error, so update both together. Only the +app rejects a request it doesn't know with an error, so update both together. **Run on** (Settings +▸ Performance ▸ AI masks, `segment.settings`) only places local inference: the remote worker +always runs on the Mac's Metal device, whatever is chosen here. Only the rendered model input (long edge at most 1008 pixels) and prompts cross the tunnel. The worker caches the current photo; detail crops do not replace that cache. Returned masks stay in the local library, so later adjustments and exports work without the connection. The worker requires Metal and accepts one editing connection at a time. It loads weights on demand and releases them when the client disconnects or remains idle for ten minutes. +If the listener reports an accept error, the worker logs it, waits 100 ms, and retries; startup +validation and bind errors still stop the worker. Both endpoints require loopback addresses: SSH provides authentication and encryption. The listener has no independent authentication; do not expose it through a public proxy. Any process of any user on the worker Mac can connect to it, and on the editing computer a local @@ -209,11 +287,14 @@ Therefore: | `mask.objectPoint` | `{x, y, exclude?: bool, id?}` | one click on the selected mask's Object selection (≤ 64 clicks) | | `mask.refineDetail` | `{id?, component?}` | the zoomed-in detail pass → `{started}` | | `segment.prepare` | `{}` | load the model and analyze the active photo → `{busy}` | -| `segment.model.status` | `{}` | `{available, installed, remote, dir, loaded, busy, analyzing, sizeBytes, license, licenseUrl, mirrors, download}` | +| `segment.model.status` | `{}` | `{available, installed, remote, dir, loaded, busy, analyzing, runOn, backend, sizeBytes, license, licenseUrl, mirrors, download}` | +| `segment.settings` | `{runOn?: "auto" \| "cpu"}` | where SAM 3 runs ([Where it runs](#where-it-runs)) → `{runOn}` | | `segment.model.download` | `{acknowledged: true}` | start the download in the background → `{started}` | | `segment.model.cancel` | `{}` | stop it (it resumes next time) → `{cancelled}` | `remote` reports the configured endpoint, not its health. `installed` describes local weights only. +`backend` is where the model runs and how long the last photo took ([Where it runs](#where-it-runs)); `null` in a +build without AI masks. `download` is `{running, done, total, file, error, cancelled, finished}`: `cancelled` is true when the last download was cancelled (its `error` says so in words; decide on the flag). An AI mask command refused because the model is not installed (or still downloading) fails with an error that starts with "The SAM 3 model is @@ -245,6 +326,13 @@ wait and return the result (when built with the `sam` feature; the default CLI h memory map: `unsafe` stays in `lightcraft-sysmem`), only the tensors a path needs, and every tensor's byte range is checked against the file's length when it is opened (a truncated or damaged file is an error, never a crash). +- The image encoder can run outside candle: `lightcraft_segment::BackboneAccel` (pixels in, the + backbone's `[1024, 72, 72]` features out), built from the checkpoint through `WeightReader` and + given to `Sam3::load_accelerated`. `lightcraft-gpu` (feature `sam`, on with the engine's `sam`) + implements it in WGSL. `Sam3` checks every result (size, finite values) and drops the + accelerator for the candle backbone on the first failure; `Sam3::backbone_device` / + `accelerated` / `backbone_fallback` report it. The engine's worker picks the placement + (`Placement` in `worker.rs`). - The engine (`crates/engine/src/segment/`) owns one worker thread with the model and the last encoded photo; the session sends it jobs and receives results over channels, never holding a lock the model holds. Each job runs under `catch_unwind`: a panic inside candle becomes an diff --git a/docs/background-tasks.md b/docs/background-tasks.md index 6f2b003477..650a94063f 100644 --- a/docs/background-tasks.md +++ b/docs/background-tasks.md @@ -49,6 +49,18 @@ guard.detail(&file_name); - **Quiet periodic work** shows no row: the auto-import folder listing runs every few seconds through `tasks::spawn(.., None, ..)`. +## Waiting in line + +Jobs that must not run side by side share a lane (`activity::Lane`; for now only the preview builds: Build Previews and +the background Build / Discard Smart Previews). A call that sets `queue: true` while its lane is busy does not fail: +`Activity::enqueue` keeps what it was asked (`Request`: the command and its parameters, with the photos written out) +and `Session::start_waiting` runs it, under the id it had in line, once the lane is free. The engine calls it after +every command and the app every frame. `activity.list` shows a waiting task after the running ones (`waiting`, +`place`, `lane`); the activity stack in the app draws only running tasks. `activity.cancel` takes a waiting task out +of the line, `activity.cancel {all: true}` empties it, and opening another library drops it: the photos it names +belong to the old one. At most `MAX_WAITING` (100) tasks wait. Without `queue` a call is refused while its lane is +busy, as before. A waiting task whose start fails (there is no smart previews folder any more, say) is logged and the next in line goes on. + ## Examples in the code | Job | Where | Shows how to | diff --git a/docs/camera-preview-colour.md b/docs/camera-preview-colour.md index da58c69e4b..23e57bba17 100644 --- a/docs/camera-preview-colour.md +++ b/docs/camera-preview-colour.md @@ -136,7 +136,30 @@ it (Enable Profile Corrections). The camera applied the same correction to its J (`fit_preview`, `monochrome_look`, the near-black tone fallback) therefore takes its sensor proxy through `look_proxies`, which multiplies it by that gain as `fit_dng_tone` already did (`correct_vignetting`). Before `LOOK_VERSION` 13 the RAF fit saw the uncorrected sensor: the tone curve learned the JPEG's corrected brightness, and -the render added the correction again. Lens-database corrections (`LIGHTCRAFT_LENSFUN_DIR`) reach the fit the same way. +the render added the correction again. A lens-database profile (`LIGHTCRAFT_LENSFUN_DIR`, the downloaded lensfun data) +describes the lens, not what the camera did to its JPEG, so since `LOOK_VERSION` 26 it reaches the fit only in the +share the JPEG shows (`camera_vignetting_amount`): the camera's tone curve is monotone, so the share whose corrected +sensor ranks its pixels' luminance most like the JPEG wins (0 to 100 % in 5 % steps). The ranks are compared within +classes of similar sensor chromaticity (near-neutral and eight hue sectors), weighted by their pixel counts: a camera +that renders some hues brighter than others would otherwise read as vignetting where those hues gather toward the +corners. A CR3 proxy moved to its JPEG's framing gets the gain of the position each pixel shows, and a DNG's tone fit +(`fit_dng_tone`) takes a database profile in the measured share too. The whole correction is kept when nothing can +be measured: proxies of different sizes, fewer than 256 usable pixels (pixels clipped on the sensor or in the camera +JPEG, black and non-finite ones are left out, as are chromaticity classes under 32 pixels), a lens-warped sensor proxy (the gain would no longer be at each +pixel's source position); shares that rank alike keep the larger one. Within a class the camera's rendering is taken as alike, so two +saturations of one hue that it renders differently, one gathered toward the corners, can still read as vignetting. +With the whole profile, an ILCE-7M3 frame at f/2 with an FE 28mm F2 (lensfun: corners at 16 % of the centre) fitted +0.062 held-out RMS instead of 0.027 and rendered darker and orange. Its camera JPEG, with vignetting correction Auto +in the maker note, is measured as showing none of that correction relative to the raw, like the A7CR JPEGs in +[sony-lens-corrections.md](sony-lens-corrections.md). Of 91 CC0 corpus raws (all 37 ARWs, 19 ORFs, 15 PEFs, 20 +NEFs), 10 get a lens database vignetting profile into their fit (7 Sony, 2 Olympus, 1 Nikon). The shares measured +are 0 % on two, 5 % on three (SLT-A33, ILCE-7SM2, DSC-RX1RM3) and 10–45 % on five, and the mean CIEDE2000 of the +central half of the render against the camera JPEG goes from 4.69 to 3.96 (6 better, 3 within 0.05, the SLT-A33 0.12 +worse). The whole profile had made 9 of the 10 darker (0.4 to 8.5 L*), with small, scene-dependent colour shifts +(mostly lost chroma). Of the 35 corpus CR3s, 22 get a lens database vignetting profile into their fit; their camera +JPEGs show 0 to 100 % of it (median 45 %), the held-out RMS is lower on 21, and the mean CIEDE2000 goes from 2.86 to +2.62 (13 better, 5 within 0.05, 4 worse by up to 0.22). Their framing is estimated on the uncorrected sensor and came +out the same as on the corrected one for all 22. `proxies` applies the gain before it moves the sensor into the JPEG's lens geometry, so each pixel gets the gain of the position it samples, as in the render. The choice between the warped and the plain sensor (`alignment`) leaves out the pixels the warp finds no sensor for. It used to read them as black, a false edge along the border that made the @@ -155,7 +178,7 @@ on a 4× finer proxy roughly halves it in a simulation, but the acceptance gates One photo can show too little of a colour for its own fit to learn it: in a second shot of the lime shirt only a few dozen proxy pixels show it, next to a hillside of foliage at the same hue that the camera renders differently, and the shirt stayed yellow (hue 68° against the JPEG's 82°; a 192-pixel proxy only reached 74°). `lightcraft-cli calibrate [--max N] [--out DIR] FOLDERS…` therefore pools the colour pairs of many ARWs, NEFs or RAFs per camera model — each against its own embedded JPEG, at a 192-pixel proxy, at most 4000 pairs per photo, files spread evenly over the folders — and fits one matrix (from white-balanced camera RGB, so no single photo's white point is baked in) and one hue/saturation/value table. Models need at least 5 usable photos. -Profiles are JSON files `.json` in `$LIGHTCRAFT_CAMERA_PROFILES`, else `/camera-profiles` (macOS `~/Library/Application Support/LightCraft/camera-profiles`); a local profile replaces a built-in one. Built-in profiles live in `assets/camera-profiles/` (listed in `assets/ATTRIBUTION.md`) and are compiled in, so the app, CLI and web build share them: ILCE-7M4, fitted to 597 photos (2.2 million colour pairs) shot in 2026, mostly with the Standard creative style and DRO Auto; ILCE-7CR, 125 photos, and ILCA-99M2, 144 photos (both below); ILCE-7RM5, 220 photos (Standard creative style); X-H2S, 201 photos; X-T4, 545 photos; NIKON Z 6_2, 296 photos; NIKON Z 8, 261 photos; NIKON D5300, 264 photos (below). They hold aggregate colour statistics only. A photo of a profiled model takes its colour from the profile and fits only its own tone and chroma curves (picture styles vary per shot; with Sony's DRO on, that tone curve is then lowered as described below); the acceptance gates still apply. A rejected profile fit retries the photo's own colour and tone fit before falling back to neutral rendering. Files are read once per process and validated (version, bounded invertible matrix, table shape and finite data); a damaged file is ignored with a warning. The profiles folder's contents are part of the render cache keys, so thumbnails rendered before a profile existed are redone; smart previews built before keep their colour until rebuilt. +Profiles are JSON files `.json` in `$LIGHTCRAFT_CAMERA_PROFILES`, else `/camera-profiles` (macOS `~/Library/Application Support/LightCraft/camera-profiles`); a local profile replaces a built-in one. Built-in profiles live in `assets/camera-profiles/` (listed in `assets/ATTRIBUTION.md`) and are compiled in, so the app, CLI and web build share them: ILCE-7M4, fitted to 597 photos (2.2 million colour pairs) shot in 2026, mostly with the Standard creative style and DRO Auto; ILCE-7CR, 125 photos, and ILCA-99M2, 144 photos (both below); ILCE-7RM5, 220 photos (Standard creative style); X-H2S, 201 photos; X-T4, 545 photos; NIKON Z 6_2, 296 photos; NIKON Z 8, 261 photos; NIKON D5300, 264 photos (below). They hold aggregate colour statistics only. A photo of a profiled model takes its colour from the profile and fits only its own tone and chroma curves (picture styles vary per shot; with Sony's DRO on, that tone curve is then lowered as described below); the acceptance gates still apply. A rejected profile fit retries the photo's own colour and tone fit; when no look fits at all, the photo keeps the profile's colour (below). Files are read once per process and validated (version, bounded invertible matrix, table shape and finite data); a damaged file is ignored with a warning. The profiles folder's contents are part of the render cache keys, so thumbnails rendered before a profile existed are redone; smart previews built before keep their colour until rebuilt. ### Sony ILCE-7CR @@ -177,7 +200,7 @@ Without a profile all 150 photos accept their own fit (ΔE 1.8–13.5). For vali With CR3 and CR2 input to `calibrate` (#1073), tried on one photographer's library (CR3, RAW and C-RAW, October 2025 to September 2026) and measured as above, against each file's own full-size embedded JPEG (6960 × 4640 R7, 6000 × 4000 R6 Mark II): - Held out: 40 photos per body from different shoots, every fifth withheld (8 per body), profiles fitted on the other 32 (30 R7 photos with 107,286 colour pairs, 28 R6 Mark II with 93,200; both with a hue/saturation table). On the withheld photos the profile changes little: R7 mean ΔE 2.52 → 2.57 (median 2.37 → 2.25; 3 better, 3 worse, 2 unchanged; largest regression +0.51 on an almost colourless photo), R6 Mark II 6.12 → 6.09 (median 5.73 → 5.50; 3 better, 4 worse, 1 unchanged; largest regression +0.48, best gain −0.67). Mean ΔL\* 0.00 (R7) and +0.57 (R6 Mark II) either way. Not bundled. -- The profile only replaces the colour inside an accepted per-photo fit (`fit_preview`), so a photo whose own fit is rejected renders the neutral fallback with or without it: 2 of the 16 withheld photos (one per body), plus one with a black-and-white camera JPEG, rendered identically both ways. Unlike the ILCE-7CR, where the profile rescued every rejected photo, here it cannot. +- When this was measured the profile only replaced the colour inside an accepted per-photo fit (`fit_preview`), so a photo whose own fit was rejected rendered the neutral fallback with or without it (since `LOOK_VERSION` 14 it keeps the profile's colour, below): 2 of the 16 withheld photos (one per body), plus one with a black-and-white camera JPEG, rendered identically both ways. Unlike the ILCE-7CR, where the profile rescued every rejected photo, here it cannot. - Library-wide (`--max 600` over 35,796 CR3s): 410 R7 photos (1.39 million pairs), 119 R6 Mark II (386k) and 38 EOS R100 (129k) gave profiles; 32 photos had no usable camera JPEG or colour (mostly moon, night and other near-colourless scenes) and one did not decode. The R6 Mark II writes its Exif model as "Canon EOS R6m2", the profile's file name too. - Decoding: 4 of the R6 Mark II C-RAW files tried (3 of 40 sampled, 1 of 119 in the library run) are refused with "unsupported raw variant: Canon CRX adaptive QP value 172" (or 175) and open preview-only. @@ -233,7 +256,13 @@ A raw starts from the first of these that is available (`camera_preview::startin 4. the model's spectral matrices, with LightCraft's default tone curve and no JPEG fit; 5. the neutral fallback. -When the file's JPEG is black and white, step 2 fits the tone curve alone with the profile's colour; without a profile, or when that fit fails, 4 and 5 take the tone curve fitted to it (see the black-and-white JPEG paragraph above). If every existing JPEG fit fails, a near-black frame may take the guarded tone-only fallback described above, after its spectral or neutral colour has been chosen. +When no look fits a photo of a profiled model (step 2 and 3 both fail: a black-and-white JPEG has no colour, a dark one too few colour pairs), it keeps the profile's colour, with the tone curve fitted alone to its JPEG when that passes the checks of the black-and-white JPEG paragraph above (continued along the profile's pooled tone curve when it has one, below), else the pooled tone curve whole, else LightCraft's default tone curve (`with_profile_colour`). Without a profile, a black-and-white JPEG gives 4 and 5 the tone curve fitted to it. Without a profile, if every existing JPEG fit fails, a near-black frame may take the guarded tone-only fallback described above, after its spectral or neutral colour has been chosen. + +Before this, such a photo fell to 4 or 5 and the profile did nothing for it. Measured on two bracketed bursts of one NIKON D780 scene (a colourful woven runner in low sun, ISO 100, f/8, frames 1.1 to 3.7 EV under the burst's brightest, each rendered with Exposure raised by its measured offset and compared with the brightest frame, CIEDE2000 and chroma of the colourful areas), with a local profile pooled from 255 of the photographer's D780 photos: the five frames 2.8 EV or more under have no look (their camera JPEGs are nearly black) and rendered at 35-48% of the reference's chroma with hue off by up to 9° whether or not the profile existed; with the profile's colour kept they render at 88-99% of it, hue within 5°. Frames up to 2.3 EV under fit a look and are unchanged. The pushed frames remain 4-7 L\* darker than the reference: a dark photo's tone curve is fitted to its shadows only (or is the default curve), which the profile's colour doesn't change (the pooled tone curve, next, does). + +**A pooled tone curve.** A photo's tone curve only reaches as far as its JPEG's own pixels: a dark photo's ends in the shadows, and past its last knot `CameraTone::apply` goes on as a bounded shoulder whose rate comes from the last two knots. Push such a photo's exposure up and most of it lands on that shoulder. `lightcraft-cli calibrate` therefore also pools tone samples (white-balanced camera RGB → the camera JPEG's luminance, every proxy pixel whose sensor channels are above 0.0001 and whose JPEG luminance is in 0.0003-0.85; the floor applies before the profile's matrix, so channels the matrix sends negative stay in the luminance, as in the render, at most 4,000 per photo; a photo too dark or colourless for colour pairs still gives these, without counting toward the profile's photos, and a black-and-white camera JPEG gives none), and after fitting the matrix fits one curve through it by quantile matching (`fit_profile_tone`): every photo went through the same camera curve, so the pooled scene and JPEG distributions are still one monotone map apart, and dark photos supply the shadows while bright ones supply the highlights (picture styles and Active D-Lighting are averaged). The profile stores it as `tone` (absent in profiles fitted before; the bundled ones have none yet). A photo of the model whose look takes the profile's colour keeps its own curve up to its last knot and from there follows the pooled curve, faded from its own level over 1 EV (`extend_tone`; to make room in the curve's 32 knots it drops the photo's knots its curve needs least, by at most one 8-bit code where the JPEG taught it, using fewer extension knots or keeping the photo's curve as fitted otherwise: `thinned_knots`, `LOOK_VERSION` 17); a look fitted with the photo's own matrix (the profile's colour rejected) keeps its curve as fitted, since the pooled one maps luminance through the profile's matrix (`with_pooled_tone`, `LOOK_VERSION` 16); a photo no look fits continues its tone-only curve along the pooled one in the same way, or takes the pooled curve whole instead of the default one when no tone-only curve passes. + +On the same D780 brackets with the profile refitted with its tone curve (255 photos), the pushed frames match the reference's lightness: ΔL\* −0.2 to +0.5 for every frame (−1 to −7 before), median CIEDE2000 in the L\* 40-70 band 0.9-2.6 (2.0-13.5 before), hue within 5°. Colourfulness in the second burst comes out 16-28% above the reference in midtones. On 40 D780 photos the profile never saw, rendered unedited and compared with their camera JPEGs, the curve changes nothing that matters: mean ΔE 2.67 with the colour-only profile, 2.68 with the curve (2.77 without a profile), mean ΔL\* +0.71 → +0.73, one photo worse by more than 0.25 (0.38). The spectral matrices only replace the neutral fallback: a photo whose JPEG fit is accepted (with or without a profile) renders exactly as before, and a covered model takes its spectral matrices only when that fit fails the diff --git a/docs/catalog-persistence.md b/docs/catalog-persistence.md new file mode 100644 index 0000000000..9ab9a4a84c --- /dev/null +++ b/docs/catalog-persistence.md @@ -0,0 +1,57 @@ +# Catalog persistence + +The catalog is two files in the library folder (`crates/catalog/src/journal.rs`): `catalog.snap`, a JSON snapshot of +the whole catalog, and `catalog.log`, one JSON line per change made since. Every change is handed to the log before +its command returns; natively the log's own thread writes and fsyncs it right after, so appending a change never waits for the +drive (a write that fails is held and retried, and switching the library or quitting waits for it). `library.compact` does +wait: it writes and syncs its snapshot before it returns, and the first snapshot after a deferred upgrade copies the files +it keeps on the caller's thread. Now and then the log is +compacted into a new snapshot. This page covers what happens to a library's files when a newer version opens it. + +## Going back to an older version + +Opening a library saved in an older catalog format with a newer LightCraft rewrites it in that version's format, and +versions that don't know that format then refuse it (safely: they say so and change nothing). So that this is not a +one-way step, the upgrade first keeps the files the library was, byte for byte, beside it: + +- `catalog.snap.v-` and `catalog.log.v-`, where `` is the format they are in and + `` the number of the last change the library held when it was upgraded (or, where the upgrade was left for a + later snapshot, when the library was opened; a library that had no log, or only a log, has only the one file). `Journal::open` reports their names (`LoadReport::kept`) and logs them. + A file already there under such a name is never replaced or removed (a library restored from an older backup can reach + the same format and change as a set kept before): if it holds other bytes, the new files are kept as `…-2` (then + `-3`, and so on, up to 100 sets, after which the upgrade is refused) instead, both alike; if it holds the same bytes, it is the copy already. +- The files kept at open stay unless the library is known to be in its old format still, because the upgrade at open + did not happen (then the files that open wrote are removed again; a copy kept earlier stays): once the upgrade is written, nothing that fails + after it takes them away. The files a later snapshot keeps (below) stay too, even if that snapshot then fails and + the library is still in its old format. +- A library whose files can't be kept, or whose upgrade can't be written (a full disk, a folder that can't be written + to), is not upgraded: it opens as it is, with no copy of this attempt left lying about, and the next open tries again. If what is on + disk after a failed write can't be read back to say whether the upgrade was written, the library is refused instead + (its way back stays). A library left like that is upgraded by its next snapshot, during the session or when it is + closed, and that snapshot keeps the files first too (and is not written when they can't be kept). When a snapshot + during the session does that, LightCraft tells where the files are kept, as it does at open (a snapshot when the + library is closed, or switched away from in Settings, has no one left to tell: the files are in the folder, named + as above). The files kept are the library as it was when it opened (the snapshot, and the log up to where it ended + then): what was changed since is in the files that replace them, not in the kept ones. (An earlier session of this + version may have added changes while the library stayed in its old format: they are in the log it opened with, and + an older version may refuse them.) Until then, changes + go on being appended to the library as it is, so that they can be saved at all where there is no room for a copy of + its files. (If the session ends without that snapshot, the next open keeps the log as it is then, which holds + those changes, and tells so; the files kept earlier stay beside it.) +- A library whose log was damaged is upgraded like any other. What it was is then its snapshot, kept under the name + above, and its log, kept as `catalog.log.damaged-`: the snapshot alone is the library without the changes + that log held. If the snapshot can't be kept, the library is refused and left as it was; if the damaged log can't + be replaced after the upgrade was written, it is refused too, and its way back (the kept snapshot and + `catalog.log.damaged-`) stays (changes made in it would be appended after the damage, where the next open + would not read them). +- Nothing removes the kept files. They are as large as the library was; LightCraft says so once when it has upgraded + a library (and `library.info` lists it under `settingsWarnings`). Delete them once the older version is no longer + wanted. The browser build keeps none (it always runs the newest version). + +**To go back**, with LightCraft closed: move `catalog.snap` and `catalog.log` away, then rename each kept file that exists +to `catalog.snap` and `catalog.log` (a library that had no log, or only a log, kept only the one file: rename only that +one, and leave the other name unused). Where the log was damaged, the kept log is `catalog.log.damaged-`: it takes +the place of `catalog.log` like any kept log (the older version reads it up to the damage and handles it as it did +before), beside the kept snapshot when there is one. The older version opens the library as it was when it was upgraded (where the upgrade came +from a later snapshot: as it was when it was opened, so the changes made between that and the upgrade are not carried +back either); changes made since, in the newer version, are in the files that were moved away. diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 655a1fbf36..18e89dcfe1 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -89,7 +89,7 @@ filmstrip is visible. | `engine.commands` | — | Engine + UI commands: id, label, menu, shortcut, params doc, enabled | | `ui.menu.list` | — | Menu entries (flat: id, label, menu path, shortcut, enabled) | | `ui.menu.tree` | — | The menu bar as shown (File … Help): items `{id, params?, label, shortcut?, enabled, checked?}`, separators, submenus — the model behind the native macOS menu bar and the in-window menus | -| `ui.inspect` | — | UI state, window, `loupe` (`source`, `pending`, `failed` = why its render failed, else `null`, and `region: {full, window, pending}` when a zoomed view also renders the window on screen at no more than 100 % — `full` is the frame it is cut from, `window` its `[x, y, w, h]` — and `regionBefore` for the Before side of a Before/After view), canvas/image rects, `scroll: {grid, filmstrip}` (scroll offsets in points, `null` until drawn), active photo, selection, perf (`frameMs` = layout, `logicMs` = per-frame logic before it, `updateMs` = both, `maxUpdateMs`, `fps`, render queue …, `gpu` = adapter in use, `gpuReason` = why renders don't use the GPU, `gpuFallback` = latest render redone on the CPU and why, `gpuWindowDevice` / `screenTextures` / `mainOnGpu` = renders run on the window's device / can be drawn from the GPU / the loupe shows one now — see `docs/gpu-pipeline.md`, `loupeSteps` = how the loupe showed each photo it was stepped to, measured on the frames it drew: `{steps: [{photo, anyMs, anySource, fullMs, fullSource, sharpMs, dwellMs}], total, current}` — ms from the step to the first frame with anything of the photo, with a full-size picture (`embedded` camera JPEG, `cached` or `render`), and with LightCraft's own render; `dwellMs` is how long it stayed, the latest 256 steps; `total` counts every step finished since launch, a cursor that keeps rising when old steps leave the list; `thumbsMade` = photos given a grid thumbnail since launch (never lowered when old thumbnails are evicted, unlike `thumbTextures`); `previewCache` = the rendered-preview cache: `memEntries` / `memBytes` in memory, the disk cache's `diskHits`, `diskMisses`, `diskWrites` and `diskBudget` (bytes; all `null` without a library on disk), and `loupeEdge` (px, the loupe's longest edge, the size standard previews are built at)), status, memory (bytes per cache, see `library.memory`; plus stage caches — `budgetBytes`, `trimmed`, `sharedSourceBytes` (the one device copy of a big original) — and textures), `export: {running: {total, done, current} \| null, last}`, `notices` (warnings waiting to be shown, e.g. a damaged settings file, or once per session the drive holding the preview cache running low; OK = `button:noticeOk`, and the low-drive notice's `button:noticeSettings` opens Settings ▸ Performance), `quitPrompt` (why quitting was stopped: tasks that would be cut short are running — `button:quitAnyway` cancels them and quits, `button:quitCancel` keeps working — or unsaved changes: `button:quitRetry` / `button:quitAnyway` / `button:quitCancel`), `import: {done, total, imported, cancelled} \| null` (an import runs on a worker thread), `tasks` (other background work: `Find Missing Photos`, `Auto Import`), `activity` (every long-running task in flight as the activity stack in the top-left corner shows it, same shape as `activity.list`; a row appears once its task is 0.5 s old, ids `activity:row:`, ✕ = `activity:cancel:`, `activity:more` expands past 3 rows), `fileDialogs` (commands waiting on a native file dialog, which runs off the UI thread; they run again with the answer when it closes), `copied` (the text the UI last put on the clipboard, `null` until something is copied) | +| `ui.inspect` | — | UI state, window, `loupe` (`source`, `pending`, `failed` = why its render failed, else `null`, and `region: {full, window, pending}` when a zoomed view also renders the window on screen at no more than 100 % — `full` is the frame it is cut from, `window` its `[x, y, w, h]` — and `regionBefore` for the Before side of a Before/After view), canvas/image rects, `scroll: {grid, filmstrip}` (scroll offsets in points, `null` until drawn), active photo, selection, perf (`frameMs` = layout, `logicMs` = per-frame logic before it, `updateMs` = both, `maxUpdateMs`, `fps`, render queue …, `gpu` = adapter in use, `gpuReason` = why renders don't use the GPU, `gpuFallback` = latest render redone on the CPU and why, `gpuWindowDevice` / `screenTextures` / `mainOnGpu` = renders run on the window's device / can be drawn from the GPU / the loupe shows one now — see `docs/gpu-pipeline.md`, `loupeSteps` = how the loupe showed each photo it was stepped to, measured on the frames it drew: `{steps: [{photo, anyMs, anySource, fullMs, fullSource, sharpMs, dwellMs}], total, current}` — ms from the step to the first frame with anything of the photo, with a full-size picture (`embedded` camera JPEG, `cached` or `render`), and with LightCraft's own render; `dwellMs` is how long it stayed, the latest 256 steps; `total` counts every step finished since launch, a cursor that keeps rising when old steps leave the list; `thumbsMade` = photos given a grid thumbnail since launch (never lowered when old thumbnails are evicted, unlike `thumbTextures`); `previewCache` = the rendered-preview cache: `memEntries` / `memBytes` in memory, the disk cache's `diskHits`, `diskMisses`, `diskWrites` and `diskBudget` (bytes; all `null` without a library on disk), and `loupeEdge` (px, the loupe's longest edge, the size standard previews are built at)), status, memory (bytes per cache, see `library.memory`; plus stage caches — `budgetBytes`, `trimmed`, `sharedSourceBytes` (the one device copy of a big original) — and textures), `export: {running: {total, done, current} \| null, last}`, `notices` (warnings waiting to be shown, e.g. a damaged settings file, or once per session the drive holding the preview cache running low; OK = `button:noticeOk`, and the low-drive notice's `button:noticeSettings` opens Settings ▸ Performance), `quitPrompt` (why quitting was stopped: tasks that would be cut short are running — `button:quitAnyway` cancels them and quits, `button:quitCancel` keeps working — or unsaved changes: `button:quitRetry` / `button:quitAnyway` / `button:quitCancel`), `import: {done, total, imported, cancelled} \| null` (an import runs on a worker thread), `tasks` (other background work: `Find Missing Photos`, `Auto Import`), `activity` (every long-running task in flight, same shape as `activity.list` (including tasks waiting in line, which have no row); the activity stack in the top-left corner shows the running ones, and a row appears once its task is 0.5 s old, ids `activity:row:`, ✕ = `activity:cancel:`, `activity:more` expands past 3 rows), `fileDialogs` (commands waiting on a native file dialog, which runs off the UI thread; they run again with the answer when it closes), `copied` (the text the UI last put on the clipboard, `null` until something is copied) | | `ui.widgets` | `{filter?}` | On-screen widgets `{id, rect: [x, y, w, h]}` (screen points) | | `ui.clickWidget` / `ui.dragWidget` / `ui.hoverWidget` | `{id, count?, button?, fx?, fy?, alt?, shift?, cmd?, ctrl?}` (`button: "right"` right-clicks; `count` is capped at 16; the modifiers are held for the click or drag, e.g. `alt: true` on a sidebar triangle opens or folds the row with all the rows inside it; in Local it folds them and opens the one row) / `{id, fx?, fy?, toX?, toY?, dx?, dy?, steps?, alt?, shift?, cmd?, ctrl?}` (steps are capped at 1000) / `{id, fx?, fy?}` | Real egui input on a widget (hover: the pointer rests on it, e.g. for preset/profile previews). `fx`/`fy` are fractions of the registered rect and may lie outside `[0,1]`; the resulting point must still be inside egui's clipped interaction rect, and a non-finite fraction or resolved point is rejected before any input is queued. Geometry comes from the latest completed layout; if the widget moves before the first event or before a press, or its latest clipped rect no longer contains the point, the request fails with an error instead of clicking another widget or retargeting. A target below an ordinary modal dialog may succeed as a no-op or a backdrop click, because egui routes that input to the dialog; a target covered by a non-modal overlay fails. The blocking library-problem/launch-list window is explicit: its dim takes the modal layer, but a background target fails instead of reporting a no-op success, and only that window's own controls (`button:library…`) pass. Its creation frame is shielded and redrawn with empty input like a prompt's, so background text/pointer input cannot act while the new modal areas settle. A quit prompt or settings notice is a real egui modal scope with a foreground backdrop. Only its own buttons (`button:quit…`, `button:noticeOk`) accept a `ui.clickWidget`; background targets fail, and background keystrokes, text/clipboard input, wheel/zoom input and AccessKit actions are dropped before panels see them. The prompt itself takes Tab/Shift+Tab, Enter/Space on the focused button, and Escape/Enter for the safe default Cancel; AccessKit Focus/Click works when targeted at a prompt button. Its first creation frame (including a Tasks→Unsaved or notice→next-notice transition) is shielded and redrawn with empty input, so a press/release in that frame, or a held press from before it, cannot act underneath it; a synthetic drag already in progress is canceled. Once settled, raw `ui.click`/`ui.drag`/`ui.pointer` and backdrop clicks are still delivered to the prompt backdrop as no-ops, and the prompt's own button clicks work normally. The area/layer check cannot see a different widget covering the point in the same layer. A `ui.clickWidget` whose widget disappears before its release also fails, after canceling the pointer press without a click or drag (the same rules apply when a click spans several host frames) | | `ui.move` / `ui.click` / `ui.drag` | `{x, y, count?, button?}` / `{x, y, toX, toY, steps?}` | Raw pointer input, screen points (the same click and step caps apply). In every pointer and scroll gesture a number other than `count` and `steps` must lie between −1,000,000 and 1,000,000, or the request is refused and queues nothing | @@ -106,8 +106,8 @@ filmstrip is visible. | `ui.zoomFactor` | `{factor}` | Set the interface scale (0.5–3; egui's zoom keys are off, Cmd+= / Cmd+- zoom the photo) | | `ui.screenshot` | `{path?, headless?}` | `{path, width, height}` once the frame (with finished renders) is captured. A `path` that did not exist when the request was admitted is written with create-new semantics and is never replaced if a file (including a newly imported original) appears there while the capture is queued; an existing ordinary file may be refreshed. `headless: true` draws the UI on the CPU (no compositor needed); a windowed capture that gets no frame within 2 s falls back to headless automatically. While the loupe still waits for a render, `ui.widgets {filter: "loupe:rendering"}` lists its "Rendering…" pill; `loupe:renderFailed` is the pill saying a render failed behind a stand-in; Compare and Reference panes have their own (`compare:rendering:`, `compare:renderFailed:`) | | `engine.execute {command: "app.export", params}` | export params (see `docs/mcp.md`), plus `preset`, `dir` / `path`, `ids`, `background`; `destinationMode: "sameAsOriginal"` writes each photo into its original's folder (+ `subfolder`) instead of `dir` | Writes the files and returns `{files}` (one `{path, width, height, bytes, sidecars}` per file, plus `gpuFallback` — why that render fell back from the GPU to the CPU — when it did; see `docs/gpu-pipeline.md`); with `background: true` (what the Export dialog and menus use) it returns `{background: true, total}` at once and the batch runs on a worker thread — poll `ui.inspect` → `export` | -| `engine.execute {command: "activity.list"}` | — | The long-running tasks in flight (imports, exports, preview builds, downloads, the face scan…), oldest first: `{tasks: [{id, kind, label, done, total, unit, detail, cancellable, cancelling, ageMs}]}`; `total` 0 = not known yet; `unit` is `count`, `bytes` or `percent`; `label` is English (the app shows it translated) | -| `engine.execute {command: "activity.cancel"}` | `{id}` or `{all: true}` | Asks the task (or every cancellable one) to stop at its next file or photo → `{cancelled: n}`; an unknown id (it may have just finished) or a task that can't be cancelled is an error | +| `engine.execute {command: "activity.list"}` | — | The long-running tasks in flight (imports, exports, preview builds, downloads, the face scan…), oldest first: `{tasks: [{id, kind, label, done, total, unit, detail, cancellable, cancelling, ageMs, waiting, place, lane}]}`, then the tasks waiting in line for one of their lane (`waiting: true`, `place` 1 = next in its lane, `lane: "previews"`, `done` and `total` 0; `queue: true` on `library.buildPreviews` / `library.smartPreviews` puts a build there instead of refusing it); `total` 0 = not known yet; `unit` is `count`, `bytes` or `percent`; `label` is English (the app shows it translated) | +| `engine.execute {command: "activity.cancel"}` | `{id}` or `{all: true}` | Asks the task (or every cancellable one) to stop at its next file or photo (a waiting task leaves the line and never runs; `all` empties it) → `{cancelled: n}`; an unknown id (it may have just finished) or a task that can't be cancelled is an error | | `ui.render` | `{id?, size?, path?}` | Render a photo (PNG to `path`), `{width, height}` | | `engine.execute {command: "slideshow.layout"}` | `{margins?, marginLeft?, …, zoomToFill?, strokeBorder?, castShadow?, backdropColor?, colorWash?, backgroundImage?, …}` (see `engine.commands`) | The slideshow's slide layout (Layout, Options, Backdrop), saved with the library; omitted keys keep their value, `{}` reads it; out-of-range numbers are clamped, a wrong type or unknown key is refused and nothing changes | | `engine.execute {command: "slideshow.overlays"}` | `{identityPlate?: {enabled?, text?, image?, size?, color?, opacity?, anchor?, offsetX?, offsetY?, relativeTo?, behind?}, ratingStars?: {enabled?, color?, size?, anchor?, …}, texts?: [{text?, size?, color?, opacity?, anchor?, offsetX?, offsetY?, relativeTo?, shadow?, shadowOpacity?, shadowOffset?, shadowRadius?, shadowAngle?}], addText?, removeText?, showWatermark?, watermark?}` (see `engine.commands`) | The overlays drawn on every slide, saved with the library: sizes and offsets are fractions of the slide's shorter side, anchors `topLeft`…`bottomRight` of the `slide` or the `photo`; text overlays expand tokens (`{caption}`, `{exposure}`, `{date}`, the file-naming tokens…; unknown tags show as typed); `watermark` takes the export watermark's keys. Replies with the settings and `warnings` | @@ -119,7 +119,7 @@ filmstrip is visible. | `engine.execute {command: "slideshow.templates.import"}` / `export` | `{path}` / `{id, path}` | Import a template `.json` (at most 256 KB; format, version and every setting checked; a taken name gets " (2)") → `{id, name, renamed, warnings}`; export any template as `.json` | | `engine.execute {command: "slideshow.export"}` | `{format: "pdf"\|"jpeg"\|"video", path, size?, quality?, fps?, container?: "mp4"\|"webm", fullScreen?, speed?, name?, ids?, wait?}` | The slideshow (the photos in view, or `ids`, as composed slides between the intro and ending screens that are on) as a PDF (one page per slide; `size` = long side 64–8192 px, default 1920), a JPEG sequence (`path` = the folder, files `-001.jpg`…) or AV1 video in MP4 / WebM (`size` = frame height 64–2160 or `"720p"` / `"1080p"`, `fps` 24 / 25 / 30 / 60; fades rendered as frames; no audio; at most 2 hours). Runs in the background → `{taskId, background, slides, seconds, total, width, height, warnings}`; its row is in `activity.list` (`kind: "export"`, label "Exporting slideshow"), `activity.cancel {id: taskId}` stops it and leaves no file (outputs are written as `.part` and renamed when complete). `wait: true` runs it in the call and replies with the result. One at a time | | `engine.execute {command: "slideshow.exportStatus"}` | — | The last slideshow export: `{taskId, format, path, running, done, total, cancelled, result?, error?}`; `result` has `pages` (PDF), `files` (JPEG) or `frames`, `samples`, `keyFrames`, `seconds`, `fps`, `container`, `codec: "av1"`, `audio: false` (video), and `skipped` / `warnings` for photos that could not be rendered | -| `engine.execute {command: "dialog.slideshowExport"}` / `app.slideshowExport` | `{format?}` / `{format, size?, quality?, fps?, container?, fullScreen?, path?}` | View ▸ Export Slideshow…: opens the dialog; `app.slideshowExport` asks for the path with a save dialog when none is given, then starts `slideshow.export` | +| `engine.execute {command: "dialog.slideshowExport"}` / `app.slideshowExport` | `{format?}` / `{format, size?, quality?, fps?, container?, fullScreen?, path?}` | View ▸ Slideshow ▸ Export Slideshow…: opens the dialog; `app.slideshowExport` asks for the path with a save dialog when none is given, then starts `slideshow.export` | | `app.quit` | — | Close the app | White balance (`develop.set` with `wb.temp` / `wb.tint`, `develop.wb`, `develop.wbPick`) is in Kelvin and tint on diff --git a/docs/faces.md b/docs/faces.md index 07909a18f4..66881415a0 100644 --- a/docs/faces.md +++ b/docs/faces.md @@ -11,7 +11,7 @@ No model weights are part of LightCraft. Each one is a file you choose to get, f - **Face detection:** [YuNet](https://github.com/opencv/opencv_zoo/tree/main/models/face_detection_yunet) (232 KB, MIT). It runs in LightCraft's own code, with no extra runtime. It was trained on the WIDER FACE dataset; an MIT licence on weights does not settle that dataset's terms, so this is flagged for the maintainer. It finds faces; it does not - identify anyone. **Photo ▸ Detect Faces** offers the download the first time you use it. + identify anyone. **Photo ▸ Metadata ▸ Detect Faces** offers the download the first time you use it. - **Face recognition models** are large (AuraFace is 261 MB), and their licences and training data deserve a decision by the person installing them. Everything works without one: names from XMP, the People view, the face boxes. - **Recognition runs in LightCraft's own pure-Rust CPU interpreter**, shared with the detector. Dense @@ -39,7 +39,7 @@ does check is listed under "Agreement and regression coverage". ## Downloading a model -**Settings ▸ Faces ▸ Download** (or Photo ▸ Detect Faces, which offers it for the detector): +**Settings ▸ Faces ▸ Download** (or Photo ▸ Metadata ▸ Detect Faces, which offers it for the detector): 1. A dialog shows the model's licence, whether commercial use is allowed, what it was trained on (or that this is not known) and which site the file comes from. **Download stays disabled until you tick "I have read these terms and @@ -226,7 +226,7 @@ a ResNet-100 (so it is not the accuracy choice its size suggests). InsightFace's ## Finding faces yourself -**Photo ▸ Detect Faces** (`faces.detect`) runs the YuNet detector on the selected photos and adds what it finds as +**Photo ▸ Metadata ▸ Detect Faces** (`faces.detect`) runs the YuNet detector on the selected photos and adds what it finds as unnamed face boxes, in one undo step. A new run replaces earlier detections; boxes that came from XMP, or that you drew or named, are never touched (and a face that already has one is not boxed a second time), and no sidecar is written. It looks at the photo upright and uncropped with default settings, so your edits and crops do not matter. `apply: false` only reports. It finds faces of about 10 pixels and up in a @@ -248,7 +248,7 @@ suggest names for the ones you have not: - **Nothing is ever named for you.** A suggestion is only a label until you confirm it, and a suggestion appears only when the match is strong *and* clearly ahead of the next person: it is better to leave a face unnamed than to name it wrongly. Naming a face also makes it one of the faces the others are compared with, so the suggestions improve as you go. -- Faces come from the names other apps wrote into your photos (read from XMP), from Photo ▸ Detect Faces, or both. A face is +- Faces come from the names other apps wrote into your photos (read from XMP), from Photo ▸ Metadata ▸ Detect Faces, or both. A face is aligned using the detector's five landmarks (eyes, nose, mouth corners) when it finds the same face, and cut out by its box otherwise. - Everything stays on your computer. The embeddings (one short list of numbers per face) are cached in the library folder in diff --git a/docs/focus-points.md b/docs/focus-points.md index e17e60d1d0..9b05f08632 100644 --- a/docs/focus-points.md +++ b/docs/focus-points.md @@ -6,10 +6,10 @@ zooms to it, so checking whether the subject is sharp takes one key while cullin ## Using it -- **View ▸ Focus Point** (⌥F; `view.focusPoint {on?}`) draws the camera's AF frame as green corner brackets in +- **View ▸ Loupe Overlay ▸ Focus Point** (⌥F; `view.focusPoint {on?}`) draws the camera's AF frame as green corner brackets in Detail, Compare and Survey. It follows Rotate, flips and the crop; a point cropped away is not drawn. Off by default; the choice is saved with the app's settings. -- **View ▸ Zoom to Focus Point** (`view.zoomToFocus {on?}`, on by default): Toggle Zoom (Z or Space) zooms in +- **View ▸ Loupe Overlay ▸ Zoom to Focus Point** (`view.zoomToFocus {on?}`, on by default): Toggle Zoom (Z or Space) zooms in centred on the focus point instead of the last position. A click on the photo still zooms where you click, and a photo without a focus point zooms as before. On by default because it changes nothing for photos without a point, and for those with one the focus point is what a 1:1 check is for. In Compare the two panes share one pan, so Z @@ -29,7 +29,7 @@ unchanged (no catalog format change). A library imported before focus points were read gets them by itself: when a library opens and some of its photos from a supported body have no point and haven't been looked at, LightCraft reads them in the background, with a -**Reading focus points** row in the activity stack (n of N; ✕ stops it). **Photo ▸ Read Focus Points** +**Reading focus points** row in the activity stack (n of N; ✕ stops it). **Photo ▸ Metadata ▸ Read Focus Points** (`photo.readFocusPoints`) starts the same job by hand. Photo ▸ Reload from Disk still fills a missing point too, but it re-reads and hashes whole files and runs while you wait, so it is for a few photos, not a library. diff --git a/docs/gaps.md b/docs/gaps.md index ca8bb59af5..ecd205f707 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -45,6 +45,7 @@ Hours are Opus 5.5 agent wall-clock hours (see [target-app-parity.md](target-app | 29 | **HDR merge leftovers** (LR-MERGE-HDR): AI Denoise doesn't run on merged (linear) DNGs; JPEG brackets are treated as linear (no camera response curve); every frame is held as 32-bit float, ~0.86 GB per 67 MP frame (half-float frames would halve it) | tested on Sony A7R VI brackets 2026-10-14 ([merge.md](merge.md)); Lightroom's Denoise supports HDR DNGs | HDR shooters who denoise their merges, merge JPEGs, or merge 7+ frames of high-resolution raws on 16 GB machines | 10–20 (+ denoise linear-RGB contract, gap 11) | [merge](merge.md) | | 28 | **Small Classic shortcuts and keys**: Tab / ⇧Tab (hide the side panels / all panels; Tab moves the keyboard focus here) and F5. Rating `[` `]`, flag cycling (`` ` ``), `\` (Filter Bar), ⌘L (Enable Filters), ⌘⌥⇧C / ⌘⌥⇧V (Copy / Paste Metadata), F1 help, F6 / F7 / F8 (filmstrip, left panel, right panel) are bound; the grid-cycle key is shown beside both grid rows in View (#2500) | [ui-parity](ui-parity.md#shortcuts) | Classic muscle memory | 2–4 | [ui-parity](ui-parity.md) | | 30 | **Multi-select metadata editing in the UI**: `photo.setMeta` already iterates all selected photos, so the engine applies changes to every target. The Info panel's Show Metadata For choice (Target Photo / Selected Photos) shows the values the selected photos share and marks each field where they differ as Mixed; the All Metadata dialog still shows one photo's values with no "mixed" indication | standard in Lightroom Classic's multi-select Info panel | anyone editing metadata on a batch (copyright, keywords, custom fields) | 1–3 | [ui-parity](ui-parity.md) | +| 31 | **Sidebar multi-selection** (LR-BEHAV-MULTISELECT): `album.delete` / `album.move` take `ids`, `keyword.delete` / `keyword.move` take `keywords`, and `library.removeFolder` / `folder.label` take `paths`, each as one undo step, but the sidebar has no Cmd/Shift-click rows to choose several albums, keywords or library folders, so only the automation interface reaches the batch forms | LR-BEHAV-MULTISELECT 🟡 (engine only) | anyone tidying many albums, keywords or folders at once in the sidebar | 2–4 | [parity-checklist](parity-checklist.md) | Beta-blocking gaps (B) total **~230–430 h**; with the stability and platform work they need around them, **~340–600 h** to beta (incl. 40–80 h for the ~92 open core-path user issues) (see [target-app-parity.md](target-app-parity.md#stage)). @@ -52,7 +53,7 @@ Beta-blocking gaps (B) total **~230–430 h**; with the stability and platform w ## Gaps by kind - **Feature:** 5, 8, 11, 12, 13, 15, 16, 18, 19, 29 -- **UI / UX:** 4, 23, 24, 28, 30 +- **UI / UX:** 4, 23, 24, 28, 30, 31 - **File format:** 2, 6, 7, 10, 13, 20, 25 (raw ones in [raw-parity.md](raw-parity.md)) - **Hardware:** 14, 17, 22, 27 - **Localization:** 21 @@ -90,6 +91,7 @@ Beta-blocking gaps (B) total **~230–430 h**; with the stability and platform w | Date | Change | Summary | |---|---|---| +| 2026-11-26 | minor | Gap 31 added: sidebar multi-selection — the batch album, keyword and library-folder commands (#2757) have no sidebar caller yet | | 2026-11-01 | minor | Gap 13: Lightroom catalog backup zips import directly, and a backup of an imported catalog adds no collection twice (#2592); the gap stays open | | 2026-11-07 | correction | Compressed ORF sensor support withdrawn pending provenance review; embedded preview fallback remains. Coverage regenerated without the removed decoder: 557 verified, 665 unverified, 187 preview-only, 37 unsupported; 94% use-weighted coverage. | | 2026-11-23 | minor | Gap 3: process V13 eases global Shadows off at large amounts, and negative Texture and the Global grading wheel act less, fitted to 56 Lightroom exports of real Canon edits (mean ΔE 9.5 → 9.0, #523); the gap stays open and hours are unchanged | @@ -98,6 +100,8 @@ Beta-blocking gaps (B) total **~230–430 h**; with the stability and platform w | 2026-10-27 | minor | Gap 26: the loupe shows built previews (they were rendered again), photos ahead and the whole view are prepared in the background with settings per mode; gap not closed | | 2026-10-27 | minor | Gap 26: culling speed measured and improved (progressive Local browse, camera previews made ahead, a CR3's smallest covering JPEG, camera JPEG first at 100 %); what is left listed; gap not closed | | 2026-11-02 | minor | PERF-STEP-STALL: the catalog log is written and synced off the UI thread, so stepping and flagging never wait for the drive (a 300 ms sync: slowest flag 0.2 ms, was 305 ms); a failed write is held and retried, counted as unsaved, never dropped; gap 26 not closed | +| 2026-11-04 | patch | LR-MASK-OBJECTS, #2574: remote SAM worker logs and retries listener accept errors after 100 ms; startup and bind failures remain errors; gap ranking and readiness unchanged | +| 2026-11-04 | patch | #3028: launch image paths honor explicit Detail; Grid and Last keep Photo Grid; populated-library launches without image arguments keep their saved view; ranked gaps and readiness estimates unchanged | | 2026-10-28 | minor | Gap 8 shrinks: the desktop app offers lensfun's lens database (CC BY-SA, pinned) once on the first launch and downloads it on request and looks the library's raws up when it arrives; validation, a profile picker and own calibration remain | | 2026-10-23 | patch | Gap 8: the Sigma 10–18 mm on the ILCE-6700 gets a measured lens exception at 10–10.5 mm (0.55 px worst over 99 photos, was about 1.4 px) | | 2026-10-29 | minor | Import thumbnails render when the camera JPEG is too small, retaining preview-only/error fallbacks; import review: remembered thumbnail size and density-aware previews (#2237, part of #2056); pre-import loupe/keyboard culling remains open; no ranked gap closes | diff --git a/docs/gpu-pipeline.md b/docs/gpu-pipeline.md index 701a64659e..5f9b12c888 100644 --- a/docs/gpu-pipeline.md +++ b/docs/gpu-pipeline.md @@ -479,6 +479,176 @@ A view's stages keep an uploaded source only up to 96 MB (a Preview-level source - Result (M4 Pro, 14 raws, loupe, 12 steps): peak RSS 1.9–2.3 GB → 0.83–0.99 GB, peak footprint 2.5–2.6 GB → 0.91–0.96 GB, heap peak 930 → ~600 MB; stepping median ~13 ms (unchanged). +## SAM 3 backbone (M12) +AI masks (Object, Subject, Describe) spend almost all of their time in SAM 3's vision backbone, a 32-layer ViT +(`crates/segment/src/vit.rs`, ~4.6 TFLOP plus attention per photo): ~37–40 s on the CPU through candle. With the +`sam` feature, `lightcraft_gpu::sam3::backbone(&WeightReader)` runs it with wgpu compute kernels instead and returns +a `lightcraft_segment::BackboneAccel` for `Sam3::load_accelerated`; the heads stay on candle (the necks: below). It has a +device of its own (like denoise and faces) with the same switches, crash sentinel, shutdown gate and +stop-after-a-device-error handling; any failure is an `Err` and the candle backbone runs instead. +- Same math as `vit.rs`: patch embedding (im2col + matrix product, 24 × 24 position table tiled), `ln_pre`, then per + layer LN → one q|k|v product (the three weights concatenated) → 2-D RoPE (`rope_tables`, recomputed bit for bit) + → attention over 24 × 24 windows, or all 5184 tokens in layers 7/15/23/31 → output projection + residual → LN → + MLP 1024 → 4736 → 1024 with GELU (erf form; A&S 7.1.26, |error| < 1.5e-7) + residual. +- Tokens stay in *window order* (window-major, row-major inside a window) from the patch embedding to the last + layer: a window is a contiguous range of keys, the position table repeats per window (a bias table indexed by + row % 576), and global attention does not depend on order (its RoPE table is stored in window order). The last + kernel writes the `[1024, 72, 72]` channels-first output. +- Kernels (`wgsl/sam3_*.wgsl`): `sam3_matmul` (Y = X · Wᵀ with the checkpoint's `[N, K]` weights as they are, + 64 × 64 tiles, 4 × 4 per thread, k in steps of 16 through padded workgroup memory, bias/GELU/residual in the + epilogue; written out per tile size with one variable per accumulator), `sam3_attention` (flash style: one query + per thread, keys and values 32 at a time through workgroup memory, online softmax; the 16 × 5184² scores of a + global layer never exist; also written out, since arrays indexed in loops spilled to local memory and ran 3.5 × + slower), `sam3_ops` (layer norm, RoPE in place with the 1/8 scale folded into q, im2col, the final reorder). No + subgroups and no shader-f16 needed. +- All 228 dispatches, their parameters (one uniform buffer) and bind groups are recorded once with the weights; a + forward pass writes the pixels, submits one command buffer per layer and reads the result back once. +- Limits requested: WebGPU downlevel defaults plus 98 MB storage bindings / buffers (the MLP's activations, + 5184 × 4736 floats) and 16 KB of workgroup memory. Device memory: 1.8 GB of f32 weights + 0.2 GB of work + buffers. When the f32 weights don't fit (out-of-memory while uploading), it retries with f16 weights (pairs + packed in u32, unpacked with `unpack2x16float`, products still in f32): 0.9 GB, but ~20 × the error (below). + An adapter short of a limit gets no device (`short_limits`, e.g. "max_storage_buffer_binding_size 67108864 < + 98205696"), nor does one whose device creation fails or panics (the crash sentinel keeps a driver crash from + repeating on the next start); SAM 3 then runs in candle on the CPU, and `segment.model.status` → `backend.fallback` + and Settings ▸ Performance ▸ AI masks say why. +- Measured (RTX 5070, Vulkan, `examples/sam3_backbone_bench.rs`): device + kernel compile 0.16–0.3 s (≈1 s with a + cold driver shader cache), weight upload 1.1 s, first forward 0.43–0.47 s, warm forward 0.43–0.44 s; candle on + the CPU 36–40 s. Matrix products ~13.5 TFLOP/s (~80 % of the time), attention ~12 TFLOP/s. f16 weights: 0.47 s + (no faster: the products are compute-bound), upload 2.9 s. +- Accuracy (`tests/it/sam3_backbone.rs`, a photo with a Hugging Face reference from `tools/sam3_reference.py`): GPU vs + CPU backbone max abs 5.3e-2 at a scale of 223 (max rel 2.4e-4), mean abs 2.2e-5; against Hugging Face the GPU is + as close as the CPU port (max rel 1.4e-4 vs 2.0e-4). Click masks and a Describe mask ("person") from either + backbone: IoU 1.0. With f16 weights: max rel 3.8e-3, mean abs 5.4e-4, mask IoU ≥ 0.9997. +- Tests: kernel unit tests against plain loops (`src/sam3/tests.rs`: cut-off tiles, K not a multiple of the tile, + windowed and global attention, LN, RoPE, im2col/reorder, f16 rounding), skipped without a GPU; the end-to-end + test runs with `LIGHTCRAFT_SAM3_DIR` set. Tested on NVIDIA (RTX 5070, Vulkan), Apple silicon (M4 Pro, Metal + through wgpu: first forward 3.1 s, CPU 17.2 s; max rel 4.9e-5, masks IoU ≥ 0.99992) and AMD (RX 7900 XTX on + Windows 11, DX12 and Vulkan, all four `sam3_` tests: backbone 0.46 s on DX12 and 0.51 s on Vulkan against 26 s in + candle on the CPU, max rel 4.3e-5 / 5.1e-5; on DX12 Describe, semantic and click masks IoU ≥ 0.9993). Intel is untested. + +### SAM 3 necks +After the backbone, the click decoder needs the tracker neck (`tracker_neck`) and Describe the detector's +(`detector_model.vision_encoder.neck`): the same `Sam3VisionNeck` (`crates/segment/src/neck.rs`) with other weights, +three levels each (288², 144² and 72², 256 channels; the 36² level is used by neither head). In candle on the CPU +they took ~2.3 and ~2.6 s per photo, more than the GPU backbone. `BackboneAccel::neck` runs them with the backbone's +device (`crates/gpu/src/sam3/neck.rs`); `Sam3` turns the levels into candle tensors on its device, checks their +sizes and values, and on any `Err` warns once and runs that neck in candle from then on (the other neck and the +backbone stay on the GPU). +- Images are pixel rows (`[pixels, channels]`), so every step is the backbone's matrix kernel. A 2 × 2 stride-2 + transposed convolution is one product per input pixel, `[pixels, cin] · [cin, 4 · cout]` (PyTorch's + `[cin, cout, 2, 2]` weight laid out as `[(ky, kx, cout), cin]` on upload, the bias repeated 4 ×), GELU (erf) + between level 0's two in the epilogue. Its output rows hold each pixel's four outputs one after the other; `proj1` + (1 × 1) doesn't care about pixel order, so one reorder (`unshuffle` in `wgsl/sam3_neck.wgsl`) after it puts the + pixels of one or two up-samplings in row-major order. +- `proj2` (3 × 3, padding 1) is an implicit GEMM: the matrix kernel with another A-tile loader + (`wgsl/sam3_conv.wgsl`, spliced in place of the dense one between `// #if dense` marks of `sam3_matmul.wgsl`) that + reads the 9 · 256 numbers of a pixel's neighbourhood straight from the image (K ordered tap-major, so each vec4 is + four channels of one pixel; zero outside). The im2col matrix (764 MB at 288²) never exists. The weights go to + `[cout, ky, kx, cin]` on upload. The last step is `to_chw` with one window over the whole image. +- Built on first use, not with the backbone: the three kernels compile (≈0.2 s with a cold driver cache, a few ms + warm), the work buffers are made (pixel rows of the backbone, 21 MB, and two 85 MB buffers the steps alternate + between, shared by both necks), and the neck's weights (~27 MB) are read, laid out and uploaded (~0.1 s). Each + level is recorded once and is one submission with its own read-back (85 / 21 / 5 MB), so no buffer exceeds the + backbone's 98 MB limits and no limit is raised. Device memory: ~245 MB with both necks built. +- Measured (RTX 5070, Vulkan, `examples/sam3_backbone_bench.rs`; `--app` times the app's per-photo steps, + `--cpu-necks` the same with candle's necks): a neck 38 ms warm (level 0: 13 ms of products at ~12 TFLOP/s, the + rest mostly the 85 MB read-back), first use 0.08–0.12 s (0.4 s with a cold driver shader cache); candle 2.3–3.5 s. + Per photo in the app's order: click features (the tracker neck plus the tracker's two 1 × 1 convolutions, still + candle) 0.11–0.19 s instead of 2.0–2.3 s, so encode + click features 0.56–0.69 s instead of 2.4–2.9 s; the first + Describe 5.1–5.8 s instead of 7.0–7.4 s (the rest of it is the DETR encoder and decoder in candle). +- Accuracy (`tests/it/sam3_necks.rs`, both models fed the same GPU backbone output): every level of both necks within + max rel 2.1e-6, mean abs ≤ 7.7e-7 of candle; click and Describe masks IoU 1.0. +- Tests: kernel unit tests against plain f64 loops (`src/sam3/neck/tests.rs`: transposed convolutions + reorder + with odd sides, the 3 × 3 convolution at every border, single-pixel and odd sizes, cut-off tiles, the weight + layouts, a whole small neck against a transcription of `Neck::forward`); `crates/segment` tests the fallback + (wrong sizes, NaN) with a fake accelerator. + +### SAM 3 DETR encoder +Each text prompt (Describe; Subject's "person") runs the text detector (`crates/segment/src/detector.rs`), whose +DETR encoder fuses the prompt into the 72 × 72 image tokens: ~4–5 s of the ~5–7 s a prompt took on the CPU. The +same accelerator runs it (`BackboneAccel::detr_encoder`, `src/sam3/detr.rs`); `Detector::predict` uses its result +as the encoder memory and runs the rest in candle. Any failure (no such accelerator, out of memory, a wrong-sized +or non-finite result) is logged once and noted (`Sam3::detr_fallback`), and from then on candle runs the encoder +for that model. +- Same math as `detector.rs`, six layers over 5184 tokens of 256: LN (eps 1e-5, PyTorch's default) → self-attention + (8 heads of 32; q and k from the normed tokens plus their sine position encoding, v from the normed tokens; q | k + one product with the weights concatenated) → output projection + residual → LN → cross-attention to the prompt's + 32 tokens (k | v one product) with the key-padding bias → output projection + residual → LN → MLP 256 → 2048 → + 256 with ReLU + residual. +- Kernels: the backbone's matrix product (ReLU as a third epilogue activation) and layer norm (with eps 1e-5), and + `wgsl/sam3_detr.wgsl`: attention for heads of 32 (flash style, written out like the backbone's) whose q, k and v + come from separate buffers with their own strides and offsets, with an optional per-key bias stored after the + prompt's k | v (0 or f32::MIN, as candle's `padding_bias`; the running maximum starts at f32::MIN, so a padded key + weighs exactly nothing and an all-padding prompt averages, as candle's softmax does); and a sum (tokens + position). +- Loaded on the first prompt, not with the backbone: kernels, 38 MB of f32 weights, 80 MB of work buffers (model + load time and memory before the first Describe are unchanged). 84 dispatches, recorded once; a prompt writes the + tokens, their position encoding, the prompt's tokens and its padding bias, submits one command buffer per layer + and reads the memory back. +- Measured (RTX 5070, Vulkan; CPU busy with parallel builds, load ~7–10): the encoder 23–25 ms with uploads and + read-back (self-attention 2.2 ms a layer at 12 TFLOP/s, products 10–12 TFLOP/s), candle 4.6–5.7 s (3.9–4.4 s on + an idle CPU). A Describe on a photo already analyzed (second prompt) 6.6 s → 2.0 s. What remains, per prompt: + CLIP text encoder 0.27–0.46 s, DETR decoder 0.75–1.3 s (of it the box relative-position bias ~75 ms a layer), + mask head ~0.9–1.4 s (pixel decoder 3 × 3 convs at 144² and 288² ~0.75–1.2 s, 1 × 1 instance projection 0.12 s, + mask products 25 ms; now on the GPU, below). +- Accuracy (`tests/it/sam3_detr.rs`, the photo of `tools/sam3_reference.py`, prompts "person", "sky", "the red car"; + both models share one GPU backbone, so only the encoder differs): memory max rel 1.7e-6–4.2e-6, mean abs + 2.3e-6–7.7e-6; query logits max abs ≤ 2.5e-4; presence logits ≤ 2.3e-5 apart; boxes ≤ 1.2e-4; the same instances + and Describe mask IoU 1.0. Kernel unit tests (`src/sam3/detr/tests.rs`): self-attention with 8 × 32 heads and a + part-empty last workgroup, cross-attention to 32 keys with 0, 1, 5 and 32 real tokens, ReLU, the sum, the eps. + +### SAM 3 mask head +A prompt's masks come from the detector's mask decoder (`mask_decoder` in the checkpoint): the encoder memory attends +to the prompt (`prompt_cross_attn`, after its layer norm) and is added to it; the pixel decoder brings it from 72² to +288² in two stages, each nearest 2 × up-sampling + the detector neck's level of that size → 3 × 3 convolution → +GroupNorm (8 groups, eps 1e-5) → ReLU; the 1 × 1 instance projection follows, and each query's mask embedding (the +`mask_embedder` MLP on the decoder's queries) times that is its mask logits. ~0.7–1.4 s per prompt in candle on the +CPU, most of it the 288² convolution. `BackboneAccel::mask_decoder` runs it on the accelerator (`src/sam3/pixel.rs`); +any failure (out of memory, a wrong-sized or non-finite result) is logged once and noted (`Sam3::mask_fallback`), and +candle runs the decoder for that model from then on. +- Interface: the encoder memory, the prompt's tokens and which are real, both neck levels (channels-first, as + `Features` holds them) and `rows` `[r, 256]` with a bias `[r]` (r ≤ 256), each row a 1 × 1 projection of the pixel + decoder's output; it returns `[r, 288, 288]`. The detector folds the instance projection into its 200 mask + embeddings on the CPU (e · (W x + b) = (e W) x + e b: 13 MFLOP instead of the projection's 11 GFLOP), so one + product `[82944, 256] · [200, 256]ᵀ` on the GPU gives the masks and the CPU fallback stays the candle code as it was. + SAM 3's semantic segmentation head (the semantic mask Describe and Subject share out to their instances, #1963) is + another 1 × 1 read-out of the same output, so it is one more row: 201 rows, the last one the semantic mask. +- Kernels: the prompt attention is the DETR encoder's (torch-eps layer norm, products, attention with the padding + bias); the convolutions are the necks' implicit GEMM; `wgsl/sam3_pixel.wgsl` adds the up-sampling, which adds the + neck level as uploaded (channels-first, so no separate reorder), and GroupNorm + ReLU: two-pass statistics per + chunk of 256 pixels (thread = channel, so the loads are contiguous), merged per group with the parallel variance + formula, then normalized in place. The projection's `[pixels, r]` goes channels-first with `to_chw`. +- Loaded on the first prompt, like the encoder: kernels, 6 MB of weights, 282 MB of work buffers (and an 85 MB + read-back buffer in host memory). 17 dispatches, recorded once per row count; a prompt uploads the memory (5 MB), + the prompt, both neck levels (106 MB) and the rows, submits once and reads `r · 288²` numbers back (66 MB). + Keeping the levels on the device after `BackboneAccel::neck` would save the 106 MB upload (a few ms) but needs an + image identity in the interface and another 106 MB of device memory per photo; not done. +- Measured (RTX 5070, Vulkan, `examples/sam3_backbone_bench.rs`, quiet machine): the decoder 33 ms warm with the + uploads and the read-back (by FLOP count about a third of it kernels, the 288² convolution ~8 ms at ~12 TFLOP/s; + the rest transfers), first use 0.09–0.17 s. Per prompt in the app (`--app`, against `--cpu-masks`): a Describe on a + photo already analyzed 1.9–2.2 s → 1.04–1.06 s, the first on a photo 2.0–2.1 s → 1.11–1.12 s (2.5 s → 1.65 s with + the first load); under load (~15, parallel builds) 1.9 s → 1.1–1.2 s. With the CPU-side text cache and one-pass box + bias as well: a new prompt on an analyzed photo ~0.7 s, a prompt used before 0.45–0.46 s. What remains is in candle + on the CPU: the DETR decoder (~0.4 s) and, for a new prompt, the CLIP text encoder (~0.25 s). +- Accuracy (`tests/it/sam3_mask_decoder.rs`; both models share one GPU accelerator, so only the mask decoder differs): + against the decoder transcribed with candle's tensor ops in f64, the GPU's instance features are within max rel + 4.2e-6, mean abs 1.7e-7; candle's own f32 decoder is 1.1e-3–1.5e-3 / 2e-4 from it, all of that from its GroupNorm's + f32 sums over 2.6 M numbers per group (with those in f64 the f32 transcription is within 1.1e-6). So GPU vs candle, + all 200 queries' mask logits: max rel 1.0e-3–1.7e-3; the same instances, Describe mask IoU 1.0 ("person", "sky", + "the red car" on the photo of `tools/sam3_reference.py`). Kernel unit tests (`src/sam3/pixel/tests.rs`): the + up-sampling + level (odd sizes), GroupNorm + ReLU (cut-off chunks, a mean of 50, 1–8 groups), a two-stage small + decoder (up-sampling → convolution at every border → GroupNorm) against f64 loops, and the size checks. +- Not done: masks only for the queries above the threshold (`merge` keeps sigmoid(logit) · sigmoid(presence) > 0.5). + `Sam3::detect` returns all 200 and the reference test (`crates/segment/tests/reference.rs`) checks the + best-scoring query's mask, which need not pass the threshold; with `rows` it is a matter of passing fewer of them. + +### SAM 3 on the GPU: device memory in all +With every part on the GPU (after a photo's analysis and a first Describe): the backbone's 1.8 GB of f32 weights and +0.2 GB of work buffers, both necks ~245 MB, the DETR encoder 38 MB of weights and 80 MB of work buffers, the mask +decoder 6 MB and 282 MB: ~2.7 GB of device memory, ~1.8 GB when the backbone falls back to f16 weights. The parts +after the backbone load on first use, each on its own; one that runs out of memory (or fails otherwise) stays in +candle on the CPU from then on (`Sam3::detr_fallback`, `Sam3::mask_fallback`, the necks per kind) and the others stay +on the GPU. Settings ▸ Performance ▸ AI masks ▸ Run on: CPU keeps all of it off the GPU. + ## Open items - WebGPU in the browser build (async init, single device per canvas). - Sky/Subject heuristics (replaced by the segmenter in M12); the ProRAW local tone map. diff --git a/docs/hardware-parity.md b/docs/hardware-parity.md index ea357161ef..d933d180de 100644 --- a/docs/hardware-parity.md +++ b/docs/hardware-parity.md @@ -10,7 +10,7 @@ What Lightroom does with the machine's hardware, per platform, and what LightCra |---|---|---|---|---|---|---| | GPU for display and editing | Metal / DX12, "Use GPU for display / image processing / export" | wgpu Metal: geometry, resize, blur, WB, NR, guided filter, dehaze, masks, finish; CPU fallback per render | DX12 only (Vulkan opt-in, #136) | Vulkan (CPU ↔ GPU equivalence verified on an AMD Radeon 8060S, RADV) | CPU only (no WebGPU yet) | 🟡 defringe, spot removal, heuristic masks, long brushes and high-bit exports stay on CPU | | GPU export | ✅ | ✅ (6000 × 4000 in ~0.3 s vs ~1.2 s CPU) | ✅ | ✅ | — | ✅ (black-export fix on an Intel iGPU, #78) | -| AI on GPU / neural engine | Metal / DirectML / Core ML, model per feature | AI denoise on GPU or CPU (setting); SAM 3 on Metal via candle; faces on CPU | CPU / GPU denoise | CPU / GPU denoise | — | 🟡 no Core ML / Neural Engine / DirectML | +| AI on GPU / neural engine | Metal / DirectML / Core ML, model per feature | AI denoise on GPU or CPU (setting); SAM 3 on Metal via candle; faces on GPU when faster (CPU-only setting) | CPU / GPU denoise; SAM 3 image encoder, necks, DETR encoder and mask decoder on the GPU (wgpu, DX12), the rest of the heads on CPU (untested on DX12 so far); faces GPU / CPU | CPU / GPU denoise; SAM 3 image encoder, necks, DETR encoder and mask decoder on the GPU (wgpu, Vulkan), the rest of the heads on CPU (a photo's analysis ~0.6 s on an RTX 5070 vs ~33 s on a Ryzen 9 3900X, a description ~0.5–0.7 s vs ~4.5 s); faces GPU / CPU | — | 🟡 no Core ML / Neural Engine / DirectML; SAM 3's click decoder, text encoder and DETR decoder on CPU outside macOS | | HDR (EDR) display | ✅ (macOS EDR, Windows HDR) | ⬜ | ⬜ | ⬜ | ⬜ | ⬜ (LR-VIEW-HDR-DISPLAY) | | Monitor profile | automatic per display, follows the window | ✅ the screen's profile, followed across screens | ✅ the profile Windows Color System assigns to the window's monitor, followed across monitors and profile changes; sRGB while Windows colour-manages the desktop (HDR, Auto Color Management) | 🟡 colord's profile (one display, or all sharing one); no follow across monitors | — | 🟡 Linux per-monitor follow missing | | Second window / second monitor | ✅ (Classic) | ✅ (⌘F11) | ✅ | ✅ | — | ✅ (Classic secondary-window keys missing) | @@ -50,6 +50,9 @@ NVIDIA, Intel and Windows DX12 still rely on user reports. | Date | Change | Summary | |---|---|---| | 2026-10-20 | minor | Monitor profile: Windows reads the window's monitor profile from Windows Color System (`crates/wincolor`), sRGB while Windows colour-manages the desktop; verified on Windows 11 by setting and clearing a Display P3 profile while the app ran. Remaining monitor-profile work 4–8 h → 2–4 h | +| 2026-10-17 | minor | AI on GPU: SAM 3's text detector mask decoder also runs on the GPU through wgpu on Windows and Linux (a description ~0.5–0.7 s with the text cache and box bias of the same change) | +| 2026-10-17 | minor | AI on GPU: SAM 3's necks and DETR encoder also run on the GPU through wgpu on Windows and Linux | +| 2026-10-17 | minor | AI on GPU: SAM 3's image encoder runs on the GPU through wgpu on Windows and Linux (CPU fallback; follows the GPU switches); faces run on the GPU when faster | | 2026-10-12 | minor | Monitor profile: Linux reads the display profile from colord; macOS row reflects #787 | | 2026-10-12 | minor | CPU ↔ GPU equivalence suite run on an AMD Radeon 8060S (Vulkan, RADV, Linux): 16 tests / 135 cases pass, max 2 LSB, mean ≤ 0.0003; first GPU verified outside Apple | | 2026-10-12 | minor | Pen pressure: strokes record per-point pressure from egui touch force, scaling dab size and flow; per-platform status | diff --git a/docs/lens-profiles.md b/docs/lens-profiles.md index 4e72251b14..facb067bdb 100644 --- a/docs/lens-profiles.md +++ b/docs/lens-profiles.md @@ -82,6 +82,13 @@ corrections: **Enable Profile Corrections** and its Distortion / Vignetting amou stage (one resample), orientation handling and DNG export. A conversion whose radial error exceeds 0.001 of the half diagonal, or that would fold the image, is not applied. +A raw whose look is fitted to its own camera JPEG (Sony, Nikon, Pentax, Olympus and others without a colour +matrix, and a DNG whose tone is fitted to its preview, [camera-preview-colour.md](camera-preview-colour.md)) has that fit made on the sensor with only the +share of a profile's vignetting correction its camera JPEG shows, measured per photo: the profile describes the +lens, not what the camera did to its JPEG relative to the raw (a Sony JPEG with shading compensation Auto can show +none of it). When the share can't be measured (too few usable pixels, or a lens-warped sensor proxy) the fit keeps +the whole correction. The render still applies the profile at the Vignetting amount. + Normalisation follows lensfun's documentation: distortion and TCA radii are 1 at half the shorter side of the calibration frame (its `cropfactor` and `aspect-ratio`), vignetting radii 1 at its corner; the optical centre is the image centre (lensfun's `
` offsets are not read). Missing or invalid crop factors remain unknown; diff --git a/docs/lightroom-catalog-import.md b/docs/lightroom-catalog-import.md index d2316d17bc..87d17c999e 100644 --- a/docs/lightroom-catalog-import.md +++ b/docs/lightroom-catalog-import.md @@ -86,8 +86,11 @@ Before changing records, the importer attempts to save source image records, dec verbatim develop settings, history, snapshots and collection content to compressed `Interop/lightroom-import-N.lca` recovery archives in the LightCraft library. Archiving is best-effort: a size limit or write failure produces a warning and does not prevent photo import. -Unchanged source data reuses its existing archive. Opaque SQL BLOBs are skipped. Each archive is -capped at 32 MiB (uncompressed and on disk), with at most eight archives and 128 MiB total +Unchanged source data reuses its existing archive. History-step and snapshot settings that Lightroom +Classic 13 and later store compressed are decoded into it; one that can't be decoded, or past 32 MiB of +them in one table, is archived without its settings, with a warning. Other opaque SQL BLOBs are skipped. Each archive is +capped at 32 MiB (uncompressed and on disk); one past that with its history-step and snapshot settings is +saved without them, with a warning, and skipped only when still too big. At most eight archives and 128 MiB total are retained. Oldest managed archives are retired; legacy `.json` archives remain untouched. `Interop/lightroom-index.json` records imported identities. Source catalogs and originals are never overwritten. diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 23e932937d..890ae54995 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -36,7 +36,7 @@ every PR would edit and conflict on. A row marked ✅ that is wrong or incomplet | C. Views & navigation (VIEW) | 16 | 1 | 1 | 0 | 9/9 (100%) | 4/4 (100%) | | D. Search & filter (FILT) | 11 | 1 | 1 | 0 | 4/4 (100%) | 4/4 (100%) | | E. Metadata (META) | 5 | 1 | 0 | 0 | 2/2 (100%) | 2/2 (100%) | -| F. Edit panel — global adjustments (EDIT) | 42 | 6 | 2 | 1 | 25/28 (89%) | 14/15 (93%) | +| F. Edit panel — global adjustments (EDIT) | 41 | 7 | 2 | 1 | 25/28 (89%) | 13/15 (87%) | | G. Profiles (PROF) | 7 | 1 | 3 | 0 | 3/4 (75%) | 3/3 (100%) | | H. Crop & rotate (CROP) | 10 | 1 | 0 | 1 | 8/8 (100%) | 2/3 (67%) | | I. Remove / healing (REM) | 8 | 1 | 2 | 2 | 4/4 (100%) | 2/3 (67%) | @@ -54,13 +54,13 @@ every PR would edit and conflict on. A row marked ✅ that is wrong or incomplet | U. Map & location (MAP) | 0 | 1 | 1 | 0 | — | 0/1 (0%) | | V. Preferences (PREF) | 6 | 2 | 2 | 2 | 1/1 (100%) | 4/5 (80%) | | W. Cloud & AI infrastructure (CLOUD / AI) | 1 | 0 | 1 | 2 | — | — | -| X. Cross-cutting behaviours (BEHAV) | 23 | 6 | 1 | 1 | 8/8 (100%) | 7/10 (70%) | +| X. Cross-cutting behaviours (BEHAV) | 22 | 8 | 1 | 1 | 7/8 (88%) | 7/10 (70%) | | Y. Menus | 85 | 0 | 4 | 8 | 47/47 (100%) | 23/23 (100%) | | Z. Keyboard shortcuts (desktop) | 77 | 5 | 2 | 1 | 49/52 (94%) | 24/26 (92%) | | Lightroom Classic extras | 41 | 26 | 21 | 8 | — | 24/27 (89%) | -| **Total** | 419 | 71 | 56 | 35 | 193/203 (95%) | 147/163 (90%) | +| **Total** | 417 | 74 | 56 | 35 | 192/203 (95%) | 146/163 (90%) | -Weighted completion (✅ = 1, 🟡 = ½, 🚫 left out): **83.2%** of 546 in-scope rows — P0 97.5% of 203 · P1 94.2% of 163 · P2 57.0% of 179. +Weighted completion (✅ = 1, 🟡 = ½, 🚫 left out): **83.0%** of 547 in-scope rows — P0 97.3% of 203 · P1 93.9% of 163 · P2 56.9% of 180. ## Top gaps and shortcut notes @@ -76,7 +76,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). |---|---|---|---|---|---| | LR-IMP-ADD-DIALOG | Add photos/folders | P0 | ✅ | `cmd:file.addPhotos`, `cmd:view.importThumbSize`, `cmd:library.importPreview`, `cmd:library.import` (`mode`, `album`, `albumName`, `preset`, `keywords`), `crates/ui-egui/src/dialogs/import.rs` | review dialog (Import Photos): the scanned source (a scanned folder is not added to Local), candidate grid with a remembered 80–320 pt thumbnail-size slider (default 116, independent of the library grid), density-aware previews capped at 1024 px and retention limited to nearby cells; tiny sources are tried once per requested size bucket; renderable raws use a sharper render when the camera JPEG is undersized, retaining the JPEG for preview-only raws or an unavailable/failed render; the pre-import loupe and keyboard culling remain open under #2056; thumbnails and checkboxes (duplicates by path/content marked and unchecked; with several file types, a toggle per type checks or unchecks all of its files, e.g. the raws without the JPEGs beside them, issue #344) filling a resizable window (issue #337), transfer mode (add in place / copy / move, each explained), album (existing/new): the destination picker follows the sidebar folder hierarchy and order, searches full paths, and distinguishes duplicate names by their folder path; folders navigate and smart albums are excluded, with None, New album and album-context preselection retained (#2362; `crates/ui-egui/src/widgets/album_picker.rs`, `crates/ui-egui/src/tests/album_picker.rs`); preset, keywords; the folder scan runs on a background thread, shown in the activity stack with ✕ to cancel (a NAS folder no longer freezes the window); the import itself (probing, sidecars, copying / moving files) runs on a worker thread and its batches join the library between frames, shown in the activity stack with ✕ to cancel; one undo step; when a Copy rename sequence runs out, remaining files are reported as failed and earlier completed transfers stay accounted for. Drag-and-drop goes through the same background import. File dialogs list the importable extensions (`lightcraft_engine::import::EXTENSIONS`) in any letter case on Linux, where GTK and the desktop portal match globs case-sensitively (`apps/lightcraft/src/dialog_filter.rs`, issue #342; 0.4.0 hid `.JPG` / `.NEF`, issue #705). The folder scan, Browse Folder, drag-and-drop and the sidecar lookup match extensions in any case (`crates/engine/src/tests/import.rs`). An import (and a scan of a folder scanned before) checks that each file a scan already probed is as it was by asking the disk about up to 16 files at a time (an import batch's files, at most), not one after another (`stat_all`, `crates/engine/src/import/files.rs`), and looks up the sidecars of a batch's photos the same way (`sidecars_of`); on a network share each file was a round trip When the scan left something out, one line under the count says so: the folder walk stopped at its depth or entry limit (“Stopped at the scan limit: there may be more photos”), folders it could not read, and files in the folders that are not a supported photo type (XMP sidecars, which the import reads with their photos, and hidden files are never counted; a file named on its own is always tried); nothing is shown when nothing was left out. `library.importPreview` returns the same as `scanLimited` and `skipped` (`unreadable`, `unsupported`). Browse Folder, Find Missing Photos and the command-line / MCP folder expansion walk with the same limits but do not report these counts (`crates/engine/src/walk.rs`, `crates/engine/src/import.rs`) | | LR-IMP-DRAGDROP | Drop files/folders to import | P0 | ✅ | `crates/ui-egui/src/lib.rs` (dropped files → the import review), `crates/ui-egui/src/drop_overlay.rs`, `crates/ui-egui/src/tests/drop_import.rs` | while files are dragged over the window a veil and a card say what dropping does (review N items for import, import N presets, open the face model; a note to close the open dialog first when one is open); photos and folders open the import review as File ▸ Import does (Settings ▸ Import ▸ Import dropped files without review imports them at once; the web build always does); with no library open on the desktop (the launch list, a library that couldn't open) photos wait for the library opened and presets are refused, and the card says so; a drop while a dialog is open (also in the web build) or while an import is running is refused with a toast, and the card says so; a finished scan waits for an open dialog to close before its review opens; the control channel's `ui.dropFiles` hovers or drops files for scripts; dropping onto a specific album not supported | -| LR-IMP-DUPES | Skip duplicates by content | P1 | ✅ | `crates/engine/src/import.rs`, `crates/engine/src/tests/import.rs` | | +| LR-IMP-DUPES | Skip duplicates by content | P1 | ✅ | `crates/engine/src/import.rs`, `crates/engine/src/tests/import.rs`, `crates/ui-egui/src/dialogs/import.rs`, `crates/ui-egui/src/headless/tests.rs` | Only library records (including Recently Deleted) count as existing content; a copy merely browsed in Local does not block importing another path. A browsed file at the same path is offered by the scan (not "In library") and promoted with its edits, unless a library match or an earlier promotion already has its content; background import batches deduplicate promoted files too. The review offers such a file only when adding in place (copy and move would add it where it is), and notes that keywords and presets apply to new files only. | | LR-IMP-DEVICE | Import from camera/card | P1 | ✅ | `cmd:library.devices`, `cmd:file.addFromDevice`, `crates/engine/src/devices.rs` | mounted volumes with a DCIM folder (macOS /Volumes, Linux /media and /run/media, Windows drive letters); File → Import from Device → the import review, copying into the library by default; menus serve the last scan and rescan in the background (never blocking a frame; hot-plugs repaint); copies are verified (a new file, synced, checked against the content hash the scan computed — byte compare with the source when there is none, issue #134; a bad copy is removed and reported as failed, never counted as imported; taken names get -1, -2…, never replaced — issue #96, `crates/engine/src/import_move.rs`); no PTP/MTP (cameras that don't mount as a disk); Settings → Import → Cameras and Cards can open the import review when a camera or card is connected (off by default; a card that was already in doesn't ask, and an open dialog or running import is finished first; `crates/ui-egui/src/dialogs/import.rs`) | | LR-IMP-AUTO | Watched-folder auto import | P2 | ✅ | `cmd:library.autoImport`, `cmd:library.autoImportScan`, `crates/ui-egui/src/dialogs/settings.rs` | Settings ▸ Import ▸ Auto Import: a watched folder whose new photos are added (in place or copied) once complete, into an optional album; scanned every 3 s | | LR-IMP-PRESET | Preset on import | P2 | ✅ | `cmd:library.import` (`preset`) | chosen in the import review; one History entry | @@ -100,9 +100,9 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-LIB-ALLPHOTOS | All photos | P0 | ✅ | `cmd:library.source`, `crates/ui-egui/src/panels/left.rs` | | | LR-LIB-RECENT-ADDED | Recently added | P1 | ✅ | `cmd:library.source` (`recentlyAdded`), `crates/engine/src/view.rs` (`RECENT_DAYS`) | photos imported in the 30 days up to the latest import, newest import first, grouped by import day | | LR-LIB-BYDATE | Browse by date | P1 | ✅ | `cmd:library.filter` (`date`), `crates/ui-egui/src/panels/left.rs` (`date_row`), `crates/catalog/src/query.rs` (`date_groups`) | year → month → day tree with library-wide counts; a row filters the current source by that date. Active filters show as removable chips under the grid header (`crates/ui-egui/src/panels/chips.rs`, with “+N more” and Clear all), the header counts “N of M photos” (matching of the source's total), a badge on the top-bar filter icon counts them, and an empty result says no photos match the active filters | -| LR-LIB-ALBUM | Albums | P0 | ✅ | `cmd:album.create`, `cmd:album.rename`, `cmd:album.delete`, `cmd:album.addPhotos`, `cmd:album.removePhotos`, `cmd:dialog.newAlbum`, `crates/engine/src/tests/albums_local.rs`, `crates/ui-egui/src/tests/panels.rs` | photos dragged from the grid onto an album row are added to it (LR-BEHAV-DRAGDROP); albums hold library photos (issue #684): `album.create {addSelected}`, `album.addPhotos` and `album.toggleTarget` (B) skip browsed Local photos and return `skipped` (a toast says so), a Local-only selection is an error and leaves Photo ▸ Add to Album, the grid's right-click Add to Album, a folder row's Add Selected Photos and a drop onto an album row off with the hint to Add to My Photos first (`button:contextAddToAlbum`, `button:contextAlbum:`); right-click a photo ▸ Add to Album lists the albums and ends with New Album…, which creates one holding the selection — also when the library has no album yet (issue #676; `button:contextNewAlbum`); New Album's "Include selected photos" (`check:albumIncludeSelected`, on by default; `dialog.newAlbum {includeSelected}`) leaves the selection out when unticked, and, as in Lightroom, is only shown when something is selected (never for a folder); album commands only take photos the library has (`album.create {addSelected}`, `album.addPhotos` and `album.toggleTarget` drop ids it lacks) and `album.addPhotos` with nothing to add (all photos already in, or none left) records no undo step and leaves redo alone; `album.toggleTarget` with none left changes nothing (`added` is null, no toast) | +| LR-LIB-ALBUM | Albums | P0 | ✅ | `cmd:album.create`, `cmd:album.rename`, `cmd:album.delete`, `cmd:album.addPhotos`, `cmd:album.removePhotos`, `cmd:dialog.newAlbum`, `crates/engine/src/tests/albums_local.rs`, `crates/ui-egui/src/tests/panels.rs`, `crates/ui-egui/src/tests/drag_contract.rs` | photos dragged from the grid onto an album row are added to it: the dragged label says how many it adds, and the toast how many were there already (LR-BEHAV-DRAGDROP); albums hold library photos (issue #684): `album.create {addSelected}`, `album.addPhotos` and `album.toggleTarget` (B) skip browsed Local photos and return `skipped` (a toast says so), a Local-only selection is an error and leaves Photo ▸ Add to Album, the grid's right-click Add to Album, a folder row's Add Selected Photos and a drop onto an album row off with the hint to Add to My Photos first (`button:contextAddToAlbum`, `button:contextAlbum:`); right-click a photo ▸ Add to Album lists the albums and ends with New Album…, which creates one holding the selection — also when the library has no album yet (issue #676; `button:contextNewAlbum`); New Album's "Include selected photos" (`check:albumIncludeSelected`, on by default; `dialog.newAlbum {includeSelected}`) leaves the selection out when unticked, and, as in Lightroom, is only shown when something is selected (never for a folder); album commands only take photos the library has (`album.create {addSelected}`, `album.addPhotos` and `album.toggleTarget` drop ids it lacks) and `album.addPhotos` with nothing to add (all photos already in, or none left) records no undo step and leaves redo alone; `album.toggleTarget` with none left changes nothing (`added` is null, no toast) | | LR-LIB-FOLDER | Folders of albums | P0 | ✅ | `cmd:album.create` (`folder`, `parent`), `cmd:album.move`, `cmd:album.reorder`, `cmd:album.sort`, `cmd:dialog.newAlbum` / `cmd:dialog.newFolder` / `cmd:dialog.smartAlbum` / `cmd:dialog.newSmartAlbum` (`parent`), `crates/ui-egui/src/panels/left.rs` (`albums_tree`, `folder_menu`, `disclosure_triangle`), `crates/ui-egui/src/tests/panels.rs` | Delete removes a folder and its nested albums as one undoable edit, keeps photos in the library and returns a deleted album view to All Photos (issue #501); folders nest and fold with the same disclosure triangle as Local / By Date / Folders / Keywords (`albumToggle:`; the row folds them too; open by default); right-click a folder ▸ New ▸ Create Album… / Create Smart Album… / Create Smart Album from Filter… / Create Folder… creates inside it (the `dialog.new*` commands take `parent`), opening the folders down to the new row; creating is only allowed inside folders; moving: drag an album or folder row onto a folder (outlined when allowed; a closed folder opens after 0.6 s under the pointer; the "Albums" header takes an item that sits in a folder back to the top level while it is dragged), the Move to menu or `album.move` — one undo step each; not onto a plain album, itself or something inside it; drop on the top / bottom half of an album or the edge of a folder to place it there by hand (`cmd:album.reorder`, a line shows the place; ordered per folder, folders stay first, new albums go after the ordered ones; right-click ▸ Sort Contents A–Z or + ▸ Sort Albums A–Z = `cmd:album.sort`) | -| LR-LIB-SMARTALBUM | Smart albums | P1 | ✅ | `cmd:album.createSmart`, `cmd:album.setRules`, `cmd:library.holdView`, `cmd:library.refresh`, `crates/catalog/src/query.rs`, `crates/ui-egui/src/panels/filterbar.rs`, `crates/ui-egui/src/lib.rs` (`album_counts`) | saved filters (rating/flag/label/kind/edited/keyword/camera/lens/date range/text/album) or a rule set from the rule editor (match all / any / none, nested groups; see LRC-LIB-SMARTCOLL), live; views and source counts with direct or nested relative-date rules expire on the session-clock minute; sidebar counts remain cached without building id lists; an edit to a few photos is followed photo by photo (a keyword created in the keyword list too: no rule reads the list), and a count of every photo (an album's rules or photos changed, a stack, an edit to more than 256 photos) runs on a worker thread while the sidebar keeps the counts it showed (none before the first count), so the window doesn't freeze; View ▸ Hold View Until Refreshed (`library.holdView`, off by default) keeps a photo that an edit or clock expiry made stop matching (a smart album, Picks, the filter bar) in the view until Refresh View, Reshuffle or another source, filter or sort, while newly matching photos enter at once | +| LR-LIB-SMARTALBUM | Smart albums | P1 | ✅ | `cmd:album.createSmart`, `cmd:album.setRules`, `cmd:library.holdView`, `cmd:library.refresh`, `crates/catalog/src/query.rs`, `crates/ui-egui/src/panels/filterbar.rs`, `crates/ui-egui/src/lib.rs` (`album_counts`) | saved filters (rating/flag/label/kind/edited/keyword/camera/lens/date range/text/album) or a rule set from the rule editor (match all / any / none, nested groups; see LRC-LIB-SMARTCOLL), live; views and source counts with direct or nested relative-date rules expire on the session-clock minute; sidebar counts remain cached without building id lists; an edit to a few photos is followed photo by photo (a keyword created in the keyword list too: no rule reads the list), and a count of every photo (an album's rules or photos changed, a stack, an edit to more than 256 photos) runs on a worker thread while the sidebar keeps the counts it showed (none before the first count), so the window doesn't freeze; View ▸ Sort ▸ Hold View Until Refreshed (`library.holdView`, off by default) keeps a photo that an edit or clock expiry made stop matching (a smart album, Picks, the filter bar) in the view until Refresh View, Reshuffle or another source, filter or sort, while newly matching photos enter at once | | LR-LIB-SHARED-ALBUM | Shared albums | P2 | ⬜ | | needs a sharing service | | LR-LIB-OFFLINE | Keep album offline | P2 | 🚫 | | not applicable: local-first library | | LR-LIB-TARGET | Target album | P2 | ✅ | `cmd:album.setTarget`, `cmd:album.toggleTarget` | see LRC-LIB-COLLECTIONS | @@ -110,7 +110,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-LIB-FLAG | Pick / reject flags | P0 | ✅ | `cmd:photo.pick`, `cmd:photo.reject`, `cmd:photo.unflag`, `cmd:photo.flag`, `crates/ui-egui/src/thumb.rs` | a rejected photo is dimmed on the grids and on the filmstrip, under its marks (the flag keeps its red); P pick, X reject, U clear; a flag or rating never waits for the drive: the catalog log is written and synced by a thread of its own, a failed write is held, retried and counted as unsaved (`crates/catalog/src/log_writer.rs`, PERF-STEP-STALL); Shift+P picks and advances in both grids (Presets elsewhere); Shift+X/U and legacy Shift+Z advance; no flag cycle; rejection does not delete the file; a pick shows as a filled flag on thumbnails, in Compare, in the loupe and on the Pick button, a reject outlined (#1013) | | LR-LIB-LABEL | Colour labels | P1 | ✅ | `cmd:photo.label`, `cmd:photo.clearLabel`, `cmd:label.setNames`, `cmd:label.names`, `cmd:dialog.labelNames`, keys 6–9 in `crates/ui-egui/src/shortcuts.rs`, `crates/ui-egui/src/thumb.rs` | Photo menu and grid context menu (coloured, named), Info-panel swatches, the label is a dot in the marks row on every surface (justified grid, square grid, filmstrip) plus translucent colour on the square-grid and filmstrip surrounds; nothing is laid over the photo's pixels (the justified grid's tinted footer band is gone). On the justified grid, which has no surround, the dot is kept before the stars and flag on a narrow photo and stays when Ratings & flags is Never; elsewhere the surround says the label; colour-label toasts have pale matching backgrounds; setting/clearing through keys (including Shift), menus or Info swatches shows the same bottom toast as ratings, with the colour/custom name; editable label names (undoable, journaled); no purple key (as in Lightroom), Clear Color Label (`photo.clearLabel`) has no key until one is given in Help → Keyboard Shortcuts, no custom extra labels | | LR-LIB-KEYWORD | Keywords | P0 | ✅ | `cmd:panel.keywords`, `cmd:photo.setMeta` (`addKeywords`/`removeKeywords`), `cmd:keyword.list`, `cmd:keyword.rename`, `cmd:keyword.delete`, `cmd:keyword.merge`, `cmd:keyword.suggest`, `crates/catalog/src/keywords.rs`, `crates/ui-egui/src/panels/left.rs` | left-panel keyword tree with counts (click filters, children included; context menu rename / merge / delete / add / remove); library-wide ops are one undo step and replay from the op log; suggestions (co-occurring / most used / completions) in the Keywords panel; keywords reorganize by drag and drop in the Keyword List (LRC-LIB-KEYWORDS) | -| LR-LIB-PEOPLE | People / faces | P2 | 🟡 | `cmd:faces.detect`, `cmd:view.people`, `cmd:view.faceBoxes`, `cmd:photo.removeRegion`, `cmd:photo.setRegion`, `cmd:library.filter`, `crates/ui-egui/src/panels/people.rs`, `crates/catalog/src/query.rs` (`people`), `crates/engine/src/media.rs` (`face_job`), `crates/meta/src/xmp.rs` | MVP: named face regions read from XMP (MWG-RS, read-only, see `docs/xmp-interop.md`; clipped to the photo; Lightroom's `Rotation` of ±π/2 and π handled, mirrored orientations taken as written; boxes follow Rotate Left/Right and flips; a sidecar stating `mwg-rs:Regions`, even empty, replaces the photo's on re-read, one without leaves them) become cards in the People view (View ▸ People, or the People button in the toolbar): a close-up of the person's largest face, name and photo count; a click filters the grid (`person` in `library.filter`, `person:` search token, filter chip). Face boxes in the loupe can be switched off (View ▸ Face Boxes, toolbar) resized with eight drag handles and removed with the × shown on hover (catalog-only and undoable, one undo step per drag; the sidecar is never rewritten for either); no moving a box by dragging it yet. Photo ▸ Detect Faces (`cmd:faces.detect`) finds faces with the YuNet detector (pure Rust, about 200 ms a photo, matches OpenCV's own YuNet on a 45-photo test set; the 232 KB model is a one-time download offered in the same step, never part of LightCraft) and adds them as unnamed boxes; names are suggested from the faces already named (recognition models are opt-in downloads, run on the CPU in a background thread; a face is named only when you confirm it); a person's page shows their cropped faces and the unnamed faces that look like them (LRC-LIB-PEOPLE), with a user-triggered ↑ action or targeted A key to name all shown suggestions at or above one score in one undo step; with recognition on, a background scan finds faces in photos that have none and embeds every face (one to three worker threads, raws through their embedded preview); an Unnamed faces section orders faces by likeness and names a selected group at once; no separated clusters, no manual tagging, no writing regions back | +| LR-LIB-PEOPLE | People / faces | P2 | 🟡 | `cmd:faces.detect`, `cmd:view.people`, `cmd:view.faceBoxes`, `cmd:photo.removeRegion`, `cmd:photo.setRegion`, `cmd:library.filter`, `crates/ui-egui/src/panels/people.rs`, `crates/catalog/src/query.rs` (`people`), `crates/engine/src/media.rs` (`face_job`), `crates/meta/src/xmp.rs` | MVP: named face regions read from XMP (MWG-RS, read-only, see `docs/xmp-interop.md`; clipped to the photo; Lightroom's `Rotation` of ±π/2 and π handled, mirrored orientations taken as written; boxes follow Rotate Left/Right and flips; a sidecar stating `mwg-rs:Regions`, even empty, replaces the photo's on re-read, one without leaves them) become cards in the People view (View ▸ People, or the People button in the toolbar): a close-up of the person's largest face, name and photo count; a click filters the grid (`person` in `library.filter`, `person:` search token, filter chip). Face boxes in the loupe can be switched off (View ▸ Loupe Overlay ▸ Face Boxes, toolbar) resized with eight drag handles and removed with the × shown on hover (catalog-only and undoable, one undo step per drag; the sidecar is never rewritten for either); no moving a box by dragging it yet. Photo ▸ Metadata ▸ Detect Faces (`cmd:faces.detect`) finds faces with the YuNet detector (pure Rust, about 200 ms a photo, matches OpenCV's own YuNet on a 45-photo test set; the 232 KB model is a one-time download offered in the same step, never part of LightCraft) and adds them as unnamed boxes; names are suggested from the faces already named (recognition models are opt-in downloads, run on the CPU in a background thread; a face is named only when you confirm it); a person's page shows their cropped faces and the unnamed faces that look like them (LRC-LIB-PEOPLE), with a user-triggered ↑ action or targeted A key to name all shown suggestions at or above one score in one undo step; with recognition on, a background scan finds faces in photos that have none and embeds every face (one to three worker threads, raws through their embedded preview); an Unnamed faces section orders faces by likeness and names a selected group at once; no separated clusters, no manual tagging, no writing regions back | | LR-LIB-STACK | Stacks | P1 | ✅ | `cmd:stack.group`, `cmd:stack.ungroup`, `cmd:stack.toggle`, `cmd:stack.setTop`, `cmd:stack.remove`, `cmd:stack.auto`, `cmd:photo.delete`, `crates/catalog/src/stacks.rs`, `crates/ui-egui/src/thumb.rs` | grid/filmstrip count badges (the same badge on both, a click expands or collapses the stack, selected or not, one translated tooltip; widgets `stack:`, `film:stack:`), expand/collapse (a click or double-click on a grid badge toggles the stack once, #2233), auto-stack by capture time; delete / remove folder drop the photo from the stack so `i/n` updates (#1493); no visual-similarity auto-stack | | LR-LIB-VERSIONS | Versions | P1 | ✅ | `cmd:version.create` | see section M | | LR-LIB-DELETE | Delete / Recently Deleted | P0 | ✅ | `cmd:photo.delete`, `cmd:photo.restore`, `cmd:photo.deletePermanently` | Delete and Delete Permanently retain surviving selected photos; if none remain, select the next visible survivor (previous at the end) in the current source/filter/sort; permanent deletion removes catalog records, not files on disk; Restore and Delete Permanently in the Photo menu and the photo context menus for photos in Recently Deleted (before, the UI had no way to restore); importing a file that is in Recently Deleted again restores the photo with its edits, rating and albums (issues #298, #706: before, the import skipped it as "already in the library" while the grid showed it deleted) — the review dialog checks it, badges it "Will be restored", counts it as "in Recently Deleted" rather than "already in the library", and its choice Restore them / Import as new / Leave them starts on Restore; with Leave them such a file starts unchecked and Check All and the file-type toggles leave it out, but a click still checks it and it is restored (issue #1285: before, the click did nothing and the "In Recently Deleted" badge was drawn over the checkbox, which now sits above it); dropped files restore too ("Restored 1 photo from Recently Deleted"); a deleted photo matched by content whose file is gone is relinked to the imported file; Photo ▸ Empty Recently Deleted (`cmd:library.emptyRecentlyDeleted`, one undo step, shown while the trash is the source); import takes `onDeleted` restore (default) / skip / fresh for files in the trash (`cmd:library.import`; the report lists `restored`, and with skip flags the duplicate `existingDeleted`); browsing a folder in Local (`cmd:library.browse`), Auto Import and a Lightroom catalog import never restore a deleted photo; no confirmation dialog, no auto-purge after N days (needs a deleted-at date in the catalog); Delete asks first ("Move this photo to Recently Deleted?") from the key, the Photo menu and the photo context menu, on by default and switched off in Settings ▸ General (#1239: before, it was off by default and the context menu never asked); no auto-purge after N days (needs a deleted-at date in the catalog) | @@ -120,7 +120,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-LIB-CAPTURETIME | Edit capture time | P1 | ✅ | `cmd:photo.setCaptureTime`, `cmd:dialog.captureTime`, `crates/catalog/src/dates.rs` | set (the other selected photos shift by the same amount, or `each`), shift by days/hours/minutes, time-zone shift; one undo step, journaled; Info panel button; no “revert to original capture time”. Impossible calendar dates cannot anchor relative shifts; rejection preserves metadata, selection, Undo and Redo. A capture time that doesn't fully read (cut short, or text after it) is left as it is and counted (`unreadable`); it can't anchor a set that moves other photos, and set alone repairs it. | | LR-LIB-SHOWFINDER | Reveal original in file manager | P0 | ✅ | `cmd:app.showInFinder` | ⌘R (see MENU-FILE-SHOWFINDER) | | LR-LIB-COVER | Album cover | P2 | ✅ | `cmd:album.setCover` | | -| LR-LIB-CULL | Assisted culling | P2 | 🟡 | `cmd:photo.analyze`, `cmd:dialog.cull`, `crates/pipeline/src/cull.rs` | Photo ▸ Assisted Culling…: focus score (0–100), clipping, burst grouping (look-alike shots within 10 s, both limits adjustable in the dialog and as `burstGap` / `similarity`, #2275) with the sharpest marked, optionally stacked collapsed with the best photo on top (`stackGroups`, #2277; photos already stacked are left alone); reject below a focus score, pick each burst's best; classical measures — no eyes-closed / expression detection | +| LR-LIB-CULL | Assisted culling | P2 | 🟡 | `cmd:photo.analyze`, `cmd:dialog.cull`, `cmd:photo.moveToBurst`, `cmd:panel.bursts`, `crates/pipeline/src/cull.rs`, `crates/ui-egui/src/panels/bursts.rs` | Photo ▸ Assisted Culling…: focus score (0–100), clipping, burst grouping (look-alike shots within 10 s, both limits adjustable in the dialog and as `burstGap` / `similarity`, #2275) with the sharpest marked, optionally stacked collapsed with the best photo on top (`stackGroups`, #2277; photos already stacked are left alone); reject below a focus score, pick each burst's best; bursts put right by hand in Window ▸ Bursts (drag a photo within its burst — first place is the pick, and the Pick flag culling set, Best of Similar Shots and a stacked burst's top follow — into another burst, a new one or none; drag a burst onto another to merge; kept when culling runs again unless *Regroup bursts I arranged by hand*); classical measures — no eyes-closed / expression detection | | LR-LIB-ACTIVITY | Comments & likes | OOS | 🚫 | | | | LR-LIB-QUICKCOLL | Quick collection [Classic] | P2 | ✅ | `cmd:album.toggleTarget`, `cmd:album.clearQuick` | B in the grids | | LR-LIB-VIRTUALCOPY | Virtual copies [Classic] | P1 | ✅ | `cmd:photo.virtualCopy`, `cmd:photo.delete`, `crates/engine/src/cmd/organize.rs`, `crates/ui-egui/src/thumb.rs` | “Copy N” tag on the grid and on the filmstrip (widgets `copy:`, `film:copy:`; on a narrow thumbnail it drops its name and then hides rather than meet the stack badge), stacked with the original, same albums, no XMP writes; default numbers are checked across the batch before copies are created, while explicit names bypass the counter; deleting a copy dissolves or renumbers the stack (#1493); no “Set Copy as Master” | @@ -136,13 +136,13 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-VIEW-FULLSCREEN | Full-screen preview | P1 | ✅ | `cmd:view.fullScreenPreview`, `cmd:view.enterFullScreen` | photo on black, arrows step, Esc exits; ⇧⌘F window full screen | | LR-VIEW-FILMSTRIP | Filmstrip | P0 | ✅ | `cmd:view.filmstrip`, `crates/ui-egui/src/panels/detail.rs`, `crates/ui-egui/src/thumb.rs` | its thumbnails wear the overlay of the grid's (one painter, `thumb.rs`): the virtual-copy tag, a clickable stack badge with the grid's tooltip, the label dot, the grid's placeholder until the picture is drawn, a rejected photo dimmed as in the grid, and a failure mark that says why on hover (`film:failed:`); on a narrow thumbnail the marks degrade (edited mark, then the stars as ★ and the number, then what does not fit); the stack badge sheds its icon, then the `i/n`) and nothing is painted outside the photo; the preview pill keeps clear of the stack badge; right-click on the stack badge opens the photo menu; the photo context menu on right-click; the mouse wheel scrolls it sideways, a third of its width per notch as in Lightroom Classic (trackpads scroll the points they report); it follows the active photo only when that changes (centred if off screen), so a scrolled strip stays put; every selected photo has the selected background; selected photos with a loaded thumbnail also show a ring, the active one in the heavier two-tone ring and the others in the lighter one, in the theme's colours, as in the grid (a selected cell with no thumbnail, still loading or failed, has the background and the same ring (the filmstrip paints the ring on its placeholder too, as the grid does)); a drag from a cell carries the selection (a photo outside it drags alone and replaces it; in Compare it drags alone and leaves the selection, the active photo and the pair as they are) to the same sidebar rows as a drag from the grid, and a click without movement works as before (it selects the photo; in Compare it goes to the active side, see LR-VIEW-COMPARE) | | LR-VIEW-ZOOM | Zoom & pan | P0 | ✅ | `cmd:view.zoomFit`, `cmd:view.zoom100`, `cmd:view.zoomIn`, `cmd:view.zoomOut`, `cmd:view.zoomToggle`, `cmd:view.clickZoom`, `cmd:view.navigate`, `crates/ui-egui/src/panels/detail.rs`, `crates/ui-egui/src/headless.rs` | continuous native pinch / modifier-wheel zoom (Fit–800%, anchored under the pointer), two-finger scroll / touch pan with edge limits; in Detail a middle-button drag (the wheel pressed) pans with a hand cursor whatever tool is active, so Remove / Heal / Clone, mask brushes and Crop don't paint or move meanwhile (`middle_pan`, `tests_canvas_pan.rs`); in Detail a middle-button drag (the wheel pressed) pans with a hand cursor whatever tool is active, so Remove / Heal / Clone, mask brushes and Crop don't paint or move meanwhile (`middle_pan`, `tests_canvas_pan.rs`); Detail (including tools, Before/After and full-screen preview), Compare and Reference; fractional percentages preserve small gestures; image, picker and targeted-adjustment cursors stay steady between gesture events; keyboard steps 25–800 % (not 6–1600 %); Fill in the bottom bar; click / Z / Space eases to the chosen ratio (1:1 default, 2:1, 3:1, 4:1, 8:1). The loupe's cost follows the canvas, not the zoom (issue #323): the whole frame is rendered at about canvas size (at most the 2560 px preview source level unless a larger Preview size is chosen, and never above the GPU's texture side), and once the view is zoomed well past that (more than 25 %) the window on screen is rendered too, cut from a frame of at most the photo's own pixels, so beyond 100 % the GPU magnifies it (`region::plan`, `RenderRequest::window`, `Session::region_job`, `crates/ui-egui/src/region.rs`); 1:1 and 2:1–8:1 are sharp at any photo size. A slider tick takes 7–12 ms on a 1400 × 900 canvas and 11–25 ms on a 2800 × 1700 one at 100 % and 400 % of a 24 MP photo (M1 Max, GPU, `profile_slider_drag`); about 20–25 ms at 100 % on the big canvas is over a 16 ms frame. A slider drag renders the whole frame at full size where the GPU draws the view, so the fit view stays sharp while dragging, and at 0.6 of it where that would be too slow: on the CPU, with an output-device profile proof or the HDR range shown, or for a control whose full-size drafts on this photo went clearly over the 16 ms slider budget (more than 20 ms) in two drags in a row (a LUT profile or refined mask the CPU renders, a photo past a GPU limit, a slow GPU); a draft's time is its render plus the frame that uploads and shows it, and a host frame time over 1 s (a hidden or stalled window) counts as unknown. A slow verdict is per photo and control (the same control on another photo, or another control on this one, is timed afresh) and expires: after 30 s a drag tries full size again, the wait doubling after each slow retry up to 240 s. Only a drag timed at full size changes it: one whose full-size drafts' median time (leaving out the first) is at most 20 ms forgets it; a drag that drafts small from its start (while the verdict holds, or where the GPU does not draw the view) or times fewer than two full-size drafts leaves it unchanged. At most 256 (photo, control) pairs are remembered, the oldest forgotten first. The size is chosen when a drag starts and kept until it ends, unless its full-size drafts take more than twice the budget, when it drops to 0.6 after three of them (`region::DragScale`, issue #330). Zoomed in, the whole-frame draft under the window is the 0.6 one (only the histogram and the window's stand-in use it). Render workers convert the pixels for their textures, not the UI thread. Handing GPU renders to egui without a CPU readback is #1228. A continuous pinch holds the render sizes (and the windows there are) and the size the fit view is shrunk to until it is quiet. A fit view on a canvas up to about 3200 px (a Retina Mac) never decodes the original; larger displays get a window at fit, which does. Diagnostic overlays (Visualize Spots, Point Color range, HDR range) get windows too, tested equal to the whole-frame render's pixels. Photos whose spots or Auto Mask strokes read too far for one window (only photos longer than 8192 px) render the whole frame at the size it is drawn, as before windows; while a preset or profile is hovered, or over a picture that is not the frame (an unsupported raw's embedded JPEG), the whole frame stays canvas-sized. Before/After (side by side, stacked, `\\` and both wipes) gets the same windows on both sides, clipped to their pane or side of the line. Windows render on the GPU like whole frames (equivalence-tested against the CPU), in the browser build too (windows no wider than its GPU's texture side, at most 3072 px), and are not made while hovering a look, nor over a picture that is not the frame (an unsupported raw's embedded JPEG with another crop). No texture is larger than the GPU allows. Spots and Auto Mask brushes work while what a window reads fits one render (8192 px along an axis, 4096 in the browser): the window grows to hold the spot and its source patch, or the dabs near it, and if that would take more (a clone from far away at 8:1) the loupe keeps the whole-frame render instead, and spots with an automatic source pick it from a fixed-size render of the whole frame (so a window's choice can differ from a whole-frame render's, which picks at its own resolution). The wide stages (dehaze, clarity, highlights/shadows base) and Refine Edges on masks read a window margin capped at 768 px; measured on hard-edged blocks that costs at most a few levels at 8:1. the histogram and Navigator come from the whole-frame render. Compare and Reference get the same windows, one per pane (`Slot::CompareRegion`, `panels/compare.rs`), over each pane's whole-frame render (at most 2560 px); while either view is open two originals stay decoded (`MediaCache::set_full_capacity`), so one pane's window does not evict the other's source; a pinch, or a slider drag on the active photo in Reference, keeps the windows there are until it ends. Mask overlays and soft proofing get the same windows (the window carries the overlay or the proof; only an output-device-profile proof renders on the CPU, where a tick at 100 % on a 1400 × 900 canvas takes about 36 ms instead of a full-size 24 MP proof). Verified: a 1:1 window of a 24 MP photo with tone and colour edits is the full-size export to within one level (`one_to_one_window_pixels_are_export_pixels`). Measured on Linux (Ryzen AI Max+ 395, Radeon 8060S, GPU, `profile_slider_drag`): median tick→shown 7 ms at fit, 33 ms at 100 % and 6 ms at 400 % on 1400 × 900; 21 ms at 100 % and 9 ms at 400 % on 2800 × 1700; 36 ms at 100 % with an output-device-profile soft proof (the CPU path) | -| LR-VIEW-FOCUSPOINT | Camera focus point overlay and zoom (beyond Lightroom) | P2 | 🟡 | `cmd:view.focusPoint`, `cmd:view.zoomToFocus`, `cmd:view.zoomToggle`, `cmd:photo.reload`, `cmd:photo.readFocusPoints`, `cmd:focus.pump`, `crates/meta/src/focus.rs`, `crates/meta/src/focus.rs`, `crates/engine/src/focus_scan.rs`, `crates/engine/src/tests/focus_scan.rs`, `crates/ui-egui/src/panels/detail.rs` (`focus_box`, `draw_focus_point`), `crates/ui-egui/src/panels/compare.rs`, `crates/ui-egui/src/tests/focus_point.rs`, `docs/focus-points.md` | an extra (Lightroom shows no focus points): the AF frame read from the file at import; photos imported earlier get it in the background from a header-only read of each file (about 32 KB, ~100 photos/s from a spinning disk; activity row, cancellable, resumable; Photo ▸ Read Focus Points) as a box on the upright photo, drawn in Detail, Compare and Survey through rotation and crop (View ▸ Focus Point, ⌥F); Toggle Zoom centres on it (View ▸ Zoom to Focus Point, on by default); Info panel row `AF-C · Wide · Animal Eye Tracking`; `meta.focus` in `photo.inspect`. Partial: Sony ILCE-1 and ILCE-7SM3 only (layout checked against 333 files); other Sony bodies and other makers not yet; manual focus and centre-only Wide reports show nothing; Compare panes share one pan, so Z centres on the active photo's point only | +| LR-VIEW-FOCUSPOINT | Camera focus point overlay and zoom (beyond Lightroom) | P2 | 🟡 | `cmd:view.focusPoint`, `cmd:view.zoomToFocus`, `cmd:view.zoomToggle`, `cmd:photo.reload`, `cmd:photo.readFocusPoints`, `cmd:focus.pump`, `crates/meta/src/focus.rs`, `crates/meta/src/focus.rs`, `crates/engine/src/focus_scan.rs`, `crates/engine/src/tests/focus_scan.rs`, `crates/ui-egui/src/panels/detail.rs` (`focus_box`, `draw_focus_point`), `crates/ui-egui/src/panels/compare.rs`, `crates/ui-egui/src/tests/focus_point.rs`, `docs/focus-points.md` | an extra (Lightroom shows no focus points): the AF frame read from the file at import; photos imported earlier get it in the background from a header-only read of each file (about 32 KB, ~100 photos/s from a spinning disk; activity row, cancellable, resumable; Photo ▸ Metadata ▸ Read Focus Points) as a box on the upright photo, drawn in Detail, Compare and Survey through rotation and crop (View ▸ Loupe Overlay ▸ Focus Point, ⌥F); Toggle Zoom centres on it (View ▸ Loupe Overlay ▸ Zoom to Focus Point, on by default); Info panel row `AF-C · Wide · Animal Eye Tracking`; `meta.focus` in `photo.inspect`. Partial: Sony ILCE-1 and ILCE-7SM3 only (layout checked against 333 files); other Sony bodies and other makers not yet; manual focus and centre-only Wide reports show nothing; Compare panes share one pan, so Z centres on the active photo's point only | | LR-VIEW-NAVIGATOR | Navigator mini map | P1 | ✅ | `cmd:view.navigator`, `crates/ui-egui/src/panels/detail.rs` | shown while zoomed (bottom right); click/drag pans | -| LR-VIEW-BEFOREAFTER | Before / after | P0 | ✅ | `cmd:view.showOriginal`, `cmd:view.beforeAfter`, `cmd:view.beforeAfterSplit`, `cmd:view.beforeAfterTopBottom`, `cmd:view.beforeAfterSplitTopBottom`, `cmd:beforeAfter.setBefore`, `cmd:beforeAfter.copyAfterToBefore`, `cmd:beforeAfter.copyBeforeToAfter`, `cmd:beforeAfter.swap`, `cmd:beforeAfter.resetBefore` | all four layouts; before = the import state (defaults + import preset) or a chosen history step / version / the current settings; copy and swap (View → Before/After Settings, History row menu). The chosen before lasts for the session; in side by side and top / bottom, clicks with the white-balance selector, colour samplers and targeted adjustment work in the Before view too (`crates/ui-egui/src/tests/before_after.rs`). Zoomed in, the side by side and stacked views each stay in their pane, with their labels under it. Click zoom animates both panes together, including cached window tiles; input follows the displayed image and render requests use the final size (#1821) | +| LR-VIEW-BEFOREAFTER | Before / after | P0 | ✅ | `cmd:view.showOriginal`, `cmd:view.beforeAfter`, `cmd:view.beforeAfterSplit`, `cmd:view.beforeAfterTopBottom`, `cmd:view.beforeAfterSplitTopBottom`, `cmd:beforeAfter.setBefore`, `cmd:beforeAfter.copyAfterToBefore`, `cmd:beforeAfter.copyBeforeToAfter`, `cmd:beforeAfter.swap`, `cmd:beforeAfter.resetBefore` | all four layouts; before = the import state (defaults + import preset) or a chosen history step / version / the current settings; copy and swap (View → Before/After, History row menu). The chosen before lasts for the session; in side by side and top / bottom, clicks with the white-balance selector, colour samplers and targeted adjustment work in the Before view too (`crates/ui-egui/src/tests/before_after.rs`). Zoomed in, the side by side and stacked views each stay in their pane, with their labels under it. Click zoom animates both panes together, including cached window tiles; input follows the displayed image and render requests use the final size (#1821) | | LR-VIEW-COMPARE | Compare two photos | P1 | ✅ | `cmd:view.compare`, `cmd:compare.swap`, `cmd:compare.makeSelect`, `cmd:compare.set`, `crates/ui-egui/src/panels/compare.rs`, `crates/ui-egui/src/tests/compare.rs` | select / candidate, synced zoom + pan, arrows move the candidate; a filmstrip click puts the photo into the active side (a photo on the other side swaps), so the active photo is always one of the two shown; a ⌘/Ctrl- or Shift-click on the filmstrip changes the selection as in the grid while the two photos shown stay selected and the active photo is unchanged (#187); the active pane is framed in the active photo's two-tone selection ring (theme tokens, 3 pt), as in the grids; 1:1 to 8:1 sharp on both sides (zoom windows, see LR-VIEW-ZOOM); no zoom-link toggle; each pane says “Rendering…” (widget `compare:rendering:`) or “This photo can't be opened” (`compare:renderFailed:`) as the loupe does | | LR-VIEW-SURVEY | Survey view [Classic] | P2 | ✅ | `cmd:view.survey`, `crates/ui-egui/src/panels/compare.rs` | selection tiled (≤ 48), keys, the bottom bar and the Info panel's stars and colour labels act on the active photo (ringed as in the grid), each tile's caption shows its colour label, hover × or ⌘/Ctrl-click removes a photo; the tiles fit the photos' shapes (the column count that shows the most of them, so four portrait photos stand side by side; an incomplete last row is centred) and glide to their new places when a photo leaves or joins, each keeping its render (`crates/ui-egui/src/panels/compare/survey.rs`) | | LR-VIEW-INFOOVERLAY | Info overlay on the photo | P1 | ✅ | `cmd:view.infoOverlay`, `cmd:view.viewOptions`, `crates/ui-egui/src/panels/detail.rs` (`info_overlay`) | off / Info 1 (by default file name, capture date, size) / Info 2 (file name, exposure, camera + lens), each three lines chosen in View Options; ⌘I cycles (I in full screen; elsewhere I stays the Info panel); the star rating and flag show under the lines when the photo has them, and in the full-screen preview on macOS the overlay starts below the window controls (issue #2460) | -| LR-VIEW-SLIDESHOW | Slideshow | P2 | ✅ | `cmd:view.slideshow` | View ▸ Slideshow (⌥⌘↩): the photos in view full screen from the selected one, played with the library's playback settings (see LRC-SS-PLAYBACK: fades, random order, repeat, previews prepared ahead; `interval` / any setting overrides one run); Space pauses, ←/→ step (a cut), Esc ends; playback controls on pointer movement | +| LR-VIEW-SLIDESHOW | Slideshow | P2 | ✅ | `cmd:view.slideshow` | View ▸ Slideshow ▸ Slideshow (⌥⌘↩): the photos in view full screen from the selected one, played with the library's playback settings (see LRC-SS-PLAYBACK: fades, random order, repeat, previews prepared ahead; `interval` / any setting overrides one run); Space pauses, ←/→ step (a cut), Esc ends; playback controls on pointer movement | | LR-VIEW-SECONDWINDOW | Second display window [Classic] | P2 | ✅ | `cmd:view.secondWindow`, `crates/ui-egui/src/panels/second.rs` | Window ▸ Second Window (⌘F11): the active photo fitted in its own native window with its own render (a floating panel where there are no native windows); loupe view only (no grid / compare / survey there) | | LR-VIEW-CLIPPING | Clipping indicators | P0 | ✅ | `cmd:view.clipping` | | | LR-VIEW-HISTOGRAM | Histogram | P0 | ✅ | `cmd:view.histogram`, `crates/ui-egui/src/panels/edit/histogram.rs`, `crates/ui-egui/src/panels/right.rs`, `crates/pipeline/src/lib.rs` (`hdr_histogram`) | stays at the top of the Edit panel while its sliders scroll under it (issue #2679, `the_histogram_stays_in_view_while_the_sliders_scroll`); HDR edits: SDR on the left half, the HDR range (0 to 5 stops above SDR white, a fixed scale) on the right with the headroom limit marked; colour bar (white, or Visualize HDR range's colours when that is on) and SDR / HDR labels; the plot's five tonal zones also drag to adjust their Basic control (LRC-DEV-HISTOGRAM-DRAG); it follows slider drags of an HDR edit live (a small render beside the drafts, `Slot::HdrHistogram`) and never drops to the SDR layout mid-drag; an edit with HDR switched off keeps its SDR histogram while it is dragged (#2819); turning HDR on or off flows between the layouts (`crates/ui-egui/src/panels/edit/hdr_flow.rs`: the SDR curve squeezes into the HDR layout's SDR section as the HDR section and legend open, and stretches back); the shadow and highlight clipping buttons at its top corners are the theme's raised fill with a chevron that stands 3:1 on it in every theme and state | @@ -201,7 +201,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-EDIT-COLOR-TINT | Tint | P0 | ✅ | `ctl:wb.tint`, `docs/tint-direction.md` | DNG / Lightroom sign: negative (left) adds green, positive (right) magenta; XMP `crs:Tint` values render as in Lightroom (issue #188); CPU/GPU regression tests | | LR-EDIT-COLOR-VIBRANCE | Vibrance | P0 | ✅ | `ctl:color.vibrance` | | | LR-EDIT-COLOR-SATURATION | Saturation | P0 | ✅ | `ctl:color.saturation` | | -| LR-EDIT-COLOR-MIXER-HSL | 8-band colour mixer | P0 | ✅ | `ctl:mixer.*` | no targeted (drag-on-image) mode | +| LR-EDIT-COLOR-MIXER-HSL | 8-band colour mixer | P0 | ✅ | `ctl:mixer.*`, `cmd:view.colorMixer`, `crates/ui-egui/src/panels/edit/mixer.rs` (`mixer`), `crates/ui-egui/src/tests/color_mixer.rs` | Lightroom Classic's layout: Mixer \| Point Color tabs, then Adjust HSL / Color; HSL shows Hue \| Saturation \| Luminance \| All (the three stacked with headings), eight sliders per group with coloured tracks and a targeted adjustment per group; Color shows one colour at a time; HSL by default, remembered | | LR-EDIT-COLOR-MIXER-BW | B&W mix | P1 | ✅ | `ctl:bw.*`, `cmd:develop.autoBwMix` | eight bands; Auto pushes each hue band's colourful pixels away from the mean lightness (own rule) | | LR-EDIT-COLOR-POINTCOLOR | Point colour | P1 | ✅ | `cmd:pointColor.pick`, `cmd:pointColor.delete` | | | LR-EDIT-COLOR-GRADING | Colour grading wheels | P0 | ✅ | `ctl:grading.*`, `crates/ui-egui/src/panels/edit.rs` (`grading`) | 3-Way / Shadows / Midtones / Highlights tabs; a range tab shows one large wheel with Hue, Saturation and Luminance sliders; Blending and Balance in every tab; 3-Way shows the hovered wheel's hue and saturation; every wheel marks its neutral centre; wheel modifiers as in Lightroom: Shift-drag keeps the puck's hue and changes saturation only (the spoke is the guide; a puck at the centre has no hue, so it takes the angle where the pointer pressed), Cmd/Ctrl-drag keeps the saturation and changes hue only (the circle is the guide), Alt/Option-drag fine-adjusts at 0.1x and combines with either lock, and a hover tooltip lists them (issues #559, #1160; tests `shift_dragging_across_the_tangent_keeps_the_hue_and_moves_saturation`, `shift_drag_keeps_the_pucks_hue_wherever_the_pointer_grabs`, `cmd_drag_keeps_the_saturation_and_changes_only_the_hue`, `alt_drag_fine_adjusts_to_a_tenth_of_the_pointers_travel`, `alt_works_with_shift_and_cmd_constraints` in `crates/ui-egui/src/tests/grading.rs`); a wheel drag holds the pointer as in Lightroom: hidden while dragging (the puck follows the mouse's travel; on macOS the pointer is locked in place), back where the button went down on release, and given back at once on Esc, a lost window focus or a wheel that goes away mid-drag; the browser can't move the pointer, so there it only shows again where the drag ended (issue #1899; tests `a_held_wheel_follows_the_mouses_motion_not_where_the_pointer_sits`, `a_wheel_drag_hides_the_pointer_and_releasing_puts_it_back_where_it_was_pressed`, `escape_or_losing_focus_gives_the_pointer_back_mid_drag`, `a_wheel_that_goes_away_mid_drag_gives_the_pointer_back`); the large wheel adds 25/50/75 % saturation rings (issue #559); each wheel's eye hides its effect for viewing only (`RenderJob::with_hidden_grading`, not saved, export unaffected) (issue #737). No Global wheel tab yet; from process V13 the Global wheel tints at 0.45 of the other wheels at the same saturation, measured against Lightroom exports (`colorops::global_wheel`) | @@ -223,7 +223,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). ) | LR-EDIT-OPTICS-DEFRINGE | Defringe | P1 | ✅ | `ctl:optics.defringe*` | no fringe eyedropper | | LR-EDIT-OPTICS-MANUAL | Manual distortion / vignetting | P1 | ✅ | `ctl:optics.distortion`, `ctl:optics.vignetting`, `ctl:optics.vignettingMidpoint` | | -| LR-EDIT-GEOM-UPRIGHT | Upright | P1 | ✅ | `cmd:geometry.upright`, `cmd:geometry.guides` | | +| LR-EDIT-GEOM-UPRIGHT | Upright | P1 | 🟡 | `cmd:geometry.upright`, `cmd:geometry.guides`, `crates/pipeline/src/upright.rs` | a vertical family is accepted when most of it agrees, or when the lines that disagree (people, folds, foliage) gather at no rival point half as strong, so two long posts flanking a crowd decide (`upright_corrects_converging_posts_among_people`); a mode that finds nothing to correct says why (`note`, shown over the photo: too few / too short lines, one object, lines that disagree, lines meeting inside the photo) and suggests Guided. Downgraded from ✅: a user's real pavilion shots (thick posts, thin poles) were not corrected and the tuning is so far proven on synthetic scenes only; thin poles below a pixel at the 1024 px analysis size are still lost | | LR-EDIT-GEOM-MANUAL | Manual transform | P1 | ✅ | `ctl:geometry.*` | | | LR-EDIT-GEOM-CONSTRAIN | Constrain crop | P1 | ✅ | `crates/ui-egui/src/panels/right.rs` (checkbox → `cmd:develop.merge`), `crates/engine/src/lib.rs` (`fit_constrained_crop`) | Ticking it, or changing Geometry, Upright or lens corrections while it is ticked, shrinks the stored crop about its centre until no blank corner is left, so the Crop tool shows it (it used to apply at render time only, outside the Crop tool: issue #1927; tests in `crates/engine/src/tests/constrain_crop.rs`). A crop drawn by hand is kept as drawn; unticking keeps the tighter crop | | LR-EDIT-GEOM-GRID | Grid while transforming | P2 | ✅ | `crates/ui-egui/src/panels/detail.rs` | a fine grid over the photo while a geometry slider is dragged | @@ -276,8 +276,8 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-REM-CLONE | Clone | P0 | ✅ | `cmd:spot.add` (`mode: clone`), `crates/pipeline/src/spots.rs` | Hard-edge source copying and unchanged radius pixels regression-tested at two output sizes; from process V14 the source is read at whole pixels | | LR-REM-GEN | Generative remove | OOS | 🚫 | | | | LR-REM-DETECT | Object detection for remove | P2 | ⬜ | | | -| LR-REM-BRUSH-PARAMS | Brush size / feather / opacity | P0 | ✅ | `cmd:spot.add` (`size`, `feather`, `opacity`), `cmd:brush.smaller`, `cmd:brush.larger`, `cmd:brush.featherLess`, `cmd:brush.featherMore`, `crates/ui-egui/src/panels/right.rs` | Size / Feather / Opacity sliders (for new spots and the selected one); `[` `]` size, ⇧`[` ⇧`]` feather (also the Masking brush) | -| LR-REM-SPOT-EDIT | Edit existing spots | P0 | ✅ | `cmd:spot.select`, `cmd:spot.update`, `cmd:spot.refreshSource`, `cmd:spot.delete`, `cmd:view.toolOverlay` | click a pin to select, drag target or source, ⌫ deletes the selected spot, `/` picks another source; automatic sources are resolved when the spot is added; Tool Overlay (Remove panel, View menu, ⇧H) shows the spots' pins Auto (pointer over the photo, hidden while painting) / Always / Selected / Never, and a hidden spot can't be grabbed (#224) | +| LR-REM-BRUSH-PARAMS | Brush size / feather / opacity | P0 | ✅ | `cmd:spot.add` (`size`, `feather`, `opacity`), `cmd:brush.smaller`, `cmd:brush.larger`, `cmd:brush.featherLess`, `cmd:brush.featherMore`, `crates/ui-egui/src/panels/right.rs` | Size / Feather / Opacity sliders (for new spots and the selected one); `[` `]` size, ⇧`[` ⇧`]` feather (also the Masking brush); the mouse wheel over the photo sizes the Remove / Masking brush and Shift+wheel feathers it, ⌃⌥-drag (⌥-right-drag) sets both at once, as in Photoshop (#2359) | +| LR-REM-SPOT-EDIT | Edit existing spots | P0 | ✅ | `cmd:spot.select`, `cmd:spot.update`, `cmd:spot.refreshSource`, `cmd:spot.delete`, `cmd:view.toolOverlay` | click a pin to select, drag target or source, ⌫ deletes the selected spot, `/` picks another source; automatic sources are resolved when the spot is added; Tool Overlay (Remove panel, View menu, ⇧H) shows the spots' pins Auto (pointer over the photo, hidden while painting) / Always / Selected / Never, and a hidden spot can't be grabbed (#224); a brushed spot records a point every r/4 of movement (a held pointer adds none; `spot.add` thins the same way, #2359) and shows as one outline, the boundary of the union of its discs, with the source the same, dashed; its pin or anywhere within r of its stroke grabs it (`crates/ui-egui/src/panels/spot_outline.rs`) | | LR-REM-VISUALIZE | Visualize spots | P1 | ✅ | `cmd:view.visualizeSpots` | | | LR-REM-PEOPLE | Remove people (generative) | OOS | 🚫 | | | | LR-REM-REFLECT | Remove reflections | P2 | ⬜ | | | @@ -300,7 +300,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-MASK-SUBJECT | Select subject | P2 | 🟡 | `cmd:mask.add` (`subject`), `crates/pipeline/src/masks.rs` | saliency heuristic, no segmentation model; a photo that carries person mattes (DNG semantic masks: iPhone ProRAW portrait / skin / hair / teeth / glasses mattes) uses them instead (synthetic files only: no corpus file carries person mattes) | | LR-MASK-SKY | Select sky | P2 | 🟡 | `cmd:mask.add` (`sky`), `crates/pipeline/src/masks.rs` (`Mattes`), `crates/raw/src/semantic.rs` | heuristic; a photo that carries a sky matte (DNG semantic mask, e.g. iPhone ProRAW) uses it instead, through orientation / crop / lens corrections, preview = export (checked on one CC0 iPhone 12 Pro ProRAW and synthetic files) | | LR-MASK-BACKGROUND | Select background | P2 | 🟡 | `cmd:mask.add` (`background`) | inverse of the subject mask (heuristic, or the photo's person mattes) | -| LR-MASK-OBJECTS | Object selection | P2 | 🟡 | `cmd:mask.add` (`object`, `prompt`), `cmd:mask.objectPoint`, `cmd:mask.refineDetail`, `cmd:segment.prepare`, `cmd:segment.model.status`, `cmd:segment.model.download`, `cmd:segment.model.cancel`, `cmd:app.openSamModelFolder`, `crates/segment`, `crates/engine/src/segment.rs` | SAM 3 in pure Rust (candle; Metal on macOS, CPU elsewhere): Object tile → click to include, ⌥-click to leave out; Describe tile → a text prompt selects every instance ("sky", "the red car"); both also as Add/Subtract/Intersect components; + / − under the selected mask; comma lists (`car, road`); a zoomed-in detail pass for 5–10× finer edges on small objects; per-selection Edge (hard ↔ soft); the stored grid is enlarged along the photo's edges (a guided filter of its logits by log luminance, so no outline spills onto the background under a raised Exposure, #3272). The model runs on its own worker thread (the UI never waits; panics become errors; a job that fails on the Mac's GPU runs again on the CPU, which then serves the rest of the session, #1974), is unloaded after 10 min idle, and is optional: the segmentation is stored with the mask (288² logits), so renders and exports never need it. Weights are never bundled (SAM License): without them the app offers a consented background download (mirrors, resume, timeouts, SHA-256) — **but no default download location is configured yet** (users set `LIGHTCRAFT_SAM3_MIRRORS` or install by hand: the dialog names the three files, opens the configured model folder with the host opener, preserves setup on an open error, and links docs/ai-masks.md; Meta's original checkpoint installed in place of the Hugging Face one is named as such, #3378). Not verified against Lightroom's Select Object; no brush/box object mode; the first click on a photo waits for its analysis (~4 s on an M4 Pro, much longer on CPU) | +| LR-MASK-OBJECTS | Object selection | P2 | 🟡 | `cmd:mask.add` (`object`, `prompt`), `cmd:mask.objectPoint`, `cmd:mask.refineDetail`, `cmd:segment.prepare`, `cmd:segment.model.status`, `cmd:segment.settings`, `cmd:segment.model.download`, `cmd:segment.model.cancel`, `cmd:app.openSamModelFolder`, `crates/segment`, `crates/engine/src/segment.rs` | SAM 3 in pure Rust (candle; Metal on macOS; on Windows and Linux the image encoder, the two necks and the text detector's DETR encoder and mask decoder on the GPU through wgpu (`lightcraft-gpu` `sam3`) and the rest of the heads on the CPU; a description ~0.5–0.7 s with an RTX 5070, falling back to the CPU without a usable GPU or when the GPU is switched off; Settings ▸ Performance ▸ AI masks ▸ Run on: CPU puts all of it on the CPU on every platform (`segment.settings`); Settings ▸ Performance ▸ AI masks and `segment.model.status` → `backend` show where it runs and the last photo's time): Object tile → click to include, ⌥-click to leave out; Describe tile → a text prompt selects every instance ("sky", "the red car"); both also as Add/Subtract/Intersect components; + / − under the selected mask; comma lists (`car, road`); a zoomed-in detail pass for 5–10× finer edges on small objects; per-selection Edge (hard ↔ soft); the stored grid is enlarged along the photo's edges (a guided filter of its logits by log luminance, so no outline spills onto the background under a raised Exposure, #3272). The model runs on its own worker thread (the UI never waits; panics become errors; a job that fails on the Mac's GPU runs again on the CPU, which then serves the rest of the session, #1974), is unloaded after 10 min idle; the remote worker retries listener accept errors after 100 ms (#2574), isolating client failures; it is optional: the segmentation is stored with the mask (288² logits), so renders and exports never need it. Weights are never bundled (SAM License): without them the app offers a consented background download (mirrors, resume, timeouts, SHA-256) — **but no default download location is configured yet** (users set `LIGHTCRAFT_SAM3_MIRRORS` or install by hand: the dialog names the three files, opens the configured model folder with the host opener, preserves setup on an open error, and links docs/ai-masks.md; Meta's original checkpoint installed in place of the Hugging Face one is named as such, #3378). Not verified against Lightroom's Select Object; no brush/box object mode; the first click on a photo waits for its analysis (~4 s on an M4 Pro, ~0.6 s with an RTX 5070 under Linux, ~32 s on a 12-core CPU) | | LR-MASK-PEOPLE | People parts | P2 | ⬜ | | shape exists (no UI): uses the photo's person / skin / hair / teeth / glasses mattes when it carries them (DNG semantic masks), else the subject heuristic | | LR-MASK-LANDSCAPE | Landscape classes | P2 | ⬜ | | shape exists, evaluates empty | | LR-MASK-BRUSH | Brush mask | P0 | 🟡 | `cmd:tool.brush`, `cmd:mask.brushStroke` (`autoMask`), `crates/pipeline/src/masks.rs`, `crates/ui-egui/src/brush_live.rs` | size/feather/flow/density/erase; Create New Mask starts a separate brush in paint mode; the stroke shows while the button is held with the committed stroke's dab spacing, feather and flow, so fast strokes have no gaps (#517); with the mask overlay hidden (O / the eye, or after a mask slider hid it) or a colour overlay at opacity 0 it is not tinted while painting either, so dodging and burning is judged on the photo, and its effect shows once the stroke is committed (#2549); coverage builds up by passes, not hold time (holding the brush still adds nothing, live or committed, #518); oversized path segments skip intermediate dabs instead of allocating a million samples; Auto Mask: dabs weighted by similarity to the colour under the dab centre, refined by a guided filter on luminance (CPU + GPU); ⇧-click draws a straight stroke from where the last stroke ended (`connect`), tapering size, feather and flow from that stroke's values when they changed; no A/B brushes; pen pressure (Brush ▸ Pen Pressure, on by default; `pressure` per point in `mask.brushStroke`) scales each dab's size (a tenth to all of it) and flow, live and committed alike, where winit reports a pen force (Windows; not macOS / Linux tablets yet); no tilt | @@ -315,7 +315,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-MASK-FEATHER-EDGE | Refine mask edges | P2 | ✅ | `cmd:mask.refine`, `crates/pipeline/src/masks.rs` (`evaluate_one`) | Refine Edges slider per mask: guided filter on the photo's luminance snaps soft mask edges to the photo's edges (rendered on the CPU) | | LR-MASK-SLIDERS | Local adjustment sliders | P0 | ✅ | `cmd:mask.adjust`, `crates/pipeline/src/finish.rs`, `crates/pipeline/src/lens_blur.rs` | every slider renders (CPU + GPU), incl. Noise, Moiré, Defringe (negative Defringe has no effect); no local curve. Beyond Lightroom: a Lens Blur block in every mask (`crates/ui-egui/src/panels/masking.rs`, `lens_blur_block`): blur the selection or what it leaves out, Amount, Boost, Transition (the blur grows away from what stays sharp), an eye to switch it off; disc bokeh, no halo | | LR-MASK-EFFECTS | Local adjustment (effect / brush) presets | P1 | ✅ | `cmd:mask.effects`, `cmd:mask.applyEffect`, `cmd:mask.saveEffect`, `cmd:mask.updateEffect`, `cmd:mask.renameEffect`, `cmd:mask.duplicateEffect`, `cmd:mask.deleteEffect`, `cmd:mask.favoriteEffect`, `cmd:mask.setEffectGroup`, `cmd:mask.renameEffectGroup`, `cmd:mask.toolEffect`, `cmd:mask.importEffects`, `cmd:mask.exportEffects`, `cmd:dialog.saveMaskEffect`, `cmd:dialog.manageMaskEffects`, `cmd:file.exportMaskEffects`, `crates/engine/src/cmd/mask_effects.rs`, `crates/engine/src/cmd/mask_effect_files.rs`, `crates/ui-egui/src/panels/mask_effects.rs` | Effect menu above the mask sliders: grouped (folders, ★ Favorites first), searchable, scrolls, ↑ ↓ Return, ✓ on the matching effect (else Custom), resting on an effect previews it on the photo; right-click: apply to all masks / to the same-named mask on the selected photos (one undo step), update, rename, duplicate, star, move to group, delete (asks first); Reset Sliders; New Effect Preset dialog: which sliders (All / None / Changed Only), Amount, brush size/feather/flow; any mask type; Manage Effect Presets window (search, inline rename, update, duplicate, stars, groups, export, delete with confirmation); a new mask starts with the effect last applied to a mask of its kind (per tool, kept with the library); imports Lightroom Classic local `.lrtemplate` presets, Camera Raw local-correction `.xmp` presets, `.lceffect` and `.zip` bundles, through File ▸ Import Profiles & Presets… and drag & drop too; folders and LrC divider presets (`10 ----- DETAIL ----- 10`) become groups; settings with no local slider here (`grain`, Point Color `pointColors`, `toningLuminance`) are reported and kept with the effect for export, not applied (🟡 for those); brush size/feather/flow aren't in LrC presets (it keeps them per brush), so only `.lceffect` carries them; no built-in effects | -| LR-MASK-OVERLAY | Mask overlay | P0 | ✅ | `cmd:view.maskOverlay`, `cmd:view.maskOverlayMode`, `cmd:view.maskOverlayColor`, `crates/pipeline/src/visualize.rs` | rendered alpha of the selected mask (CPU + GPU): colour, colour on B&W, image on black/white, white on black; ⇧O cycles while masking; successful local adjustments (including Amount) hide the overlay until O / the eye shows it again or a mask is created, picked, duplicated or added to (issue #1800); shape/edge edits retain it; zoomed in, the overlay is rendered on the same sharp window as the plain view (zoom and pan unchanged; `crates/ui-egui/src/tests/preview_limit.rs`, `crates/pipeline/src/tests_window.rs`); no auto-show on hover | +| LR-MASK-OVERLAY | Mask overlay | P0 | ✅ | `cmd:view.maskOverlay`, `cmd:view.maskOverlayMode`, `cmd:view.maskOverlayColor`, `crates/pipeline/src/visualize.rs`, `crates/ui-egui/src/panels/detail.rs` (`overlay_mask`, `adjusting`) | one rule decides when the overlay shows: O / the eye by the Masks title (on to stay), or the pointer on one of a mask's component rows or its pin while nothing is being adjusted (the mask's own row shows none: its eye judges the effect with nothing over the photo), or by itself for a mask without settings yet; a mask with settings never shows by itself (picking, creating, duplicating or adding to it shows its effect, replacing #1800's re-show); nothing shows while a slider is at work, and it comes back when let go; during a mask drag or brush stroke hovering shows no overlay, while O and a mask without settings keep theirs; no stand-in overlay while an Object click or a description is still being computed; rendered alpha of the selected mask (CPU + GPU): colour, colour on B&W, image on black/white, white on black; ⇧O cycles while masking; zoomed in, the overlay is rendered on the same sharp window as the plain view (zoom and pan unchanged; `crates/ui-egui/src/tests/preview_limit.rs`, `crates/pipeline/src/tests_window.rs`) | | LR-MASK-OVERLAYALL | Show all mask overlays | P1 | ✅ | `cmd:view.maskOverlayAll`, `crates/ui-egui/src/panels/masking.rs`, `crates/pipeline/src/visualize.rs` | one diagnostic tint over every visible mask at once (CPU + GPU): the masks still stack their adjustments as before — this only paints each mask's region together, so you can see all masked areas at a glance (⌘⇧O / Ctrl+Shift+O) | | LR-MASK-PINS | Pins | P1 | ✅ | `cmd:view.maskPins`, `cmd:view.toolOverlay`, `crates/ui-egui/src/panels/detail.rs`, `crates/ui-egui/src/tests/tool_overlay.rs`, `crates/ui-egui/src/tests/masking.rs` | a pin per radial/linear/brush component: click selects its mask, drag moves it; Object (at its first click) and Describe (on what it found) components have pins too: click selects, drag changes nothing (issue #3049); Show Pins on follows the Tool Overlay mode (Auto: while the pointer is over the photo, hidden while brushing; Always; Selected: the selected mask's; Never; ⇧H cycles, #224); no pins for range components or Subject, Sky, Background, People and Landscape | | LR-MASK-UPDATE | Recompute AI masks | P2 | ⬜ | | | @@ -329,7 +329,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-PRE-PANEL | Presets panel | P0 | ✅ | `cmd:panel.presets`, `cmd:preset.apply`, `crates/ui-egui/src/panels/presets.rs` | grouped list with amount; the preset applied to a photo stays marked on returning to it until the photo is edited further (issue #2392); resting on a preset previews it in the loupe (no history entry); optional live thumbnails (⋯ → Show Thumbnails); a preset changes only the settings it names: each is computed on the photo's import state (or on its current settings when no default preset recorded one), and every setting it does not name keeps the photo's value, so a second preset restores what an earlier one changed in the settings it names (issue #2159) | | LR-PRE-CREATE | Create preset | P0 | ✅ | `cmd:dialog.createPreset`, `cmd:preset.create` (`groups`) | name, group and a checklist of settings groups (crop, masks, remove, red eye off by default; All / None) | | LR-PRE-MANAGE | Manage presets | P1 | ✅ | `cmd:preset.delete`, `cmd:preset.favorite`, `cmd:preset.import`, `cmd:preset.export`, `cmd:preset.rename`, `cmd:preset.update`, `cmd:preset.move` | rename, update with current settings, move to a group (existing or new); starred presets are listed in a Favorites section on top, as in the Profile browser (issue #1999, `crates/ui-egui/src/tests/preset_favorites.rs`); no hiding of groups | -| LR-PRE-AMOUNT | Preset amount | P1 | ✅ | `cmd:preset.apply` (`amount` 0–200) | each named setting moves from the photo's import look (or, when none is recorded, from its current value) towards the preset's value; 0 % gives the import look's value for the settings the preset names, and the current value when no look is recorded | +| LR-PRE-AMOUNT | Preset amount | P1 | ✅ | `cmd:preset.apply` (`amount` 0–200) | each named setting moves from the photo's import look (or, when none is recorded, from its current value) towards the preset's value; 0 % gives the import look's value for the settings the preset names, and the current value when no look is recorded; sliders and tone-curve points blend with the amount, switches and choices (profile/LUT, treatment, styles) take the preset's value from half amount, and the strength of a profile or `enabled` group the preset changes fades in from 0 there; white balance on another scale (Kelvin vs relative) is never blended (`interpolate_object`, `crates/develop/src/presets.rs`, issue #2669) | | LR-PRE-ADAPTIVE | Adaptive presets | P2 | ⬜ | | | | LR-PRE-PREMIUM | Built-in presets (own) | P2 | ✅ | `crates/engine/src/presets.rs` | 41 own-authored presets in 10 groups (Color, Film, B&W incl. toners, Portrait, Landscape, Urban, Food, Seasons, Vintage, Style) | | LR-PRE-RECOMMENDED | Community recommendations | OOS | 🚫 | | | @@ -436,7 +436,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | Id | Feature | Tier | Status | Evidence | Missing / notes | |---|---|---|---|---|---| -| LR-PREF-GENERAL | General settings | P0 | ✅ | `cmd:app.settings`, `cmd:app.openLibrary`, `crates/ui-egui/src/dialogs/settings.rs`, `crates/ui-egui/src/panels/notices.rs` | General / Import / Performance / Display / Interface tabs; app settings in ui.json (written atomically, saved when the library changes and every few seconds), library settings in prefs.json; At launch: open the last library or ask (see LRC-LIB-CATALOG-SWITCH); a damaged settings file is kept as `.corrupt-