mirror of
https://github.com/storytold/lightcraft.git
synced 2026-12-01 22:18:00 +00:00
Integrate current LightCraft main and Print folder picker
This commit is contained in:
Generated
+55
@@ -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",
|
||||
|
||||
+7
-1
@@ -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"
|
||||
|
||||
@@ -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-<family>.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/);
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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 <app> 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<NSString>, objc2::rc::Retained<NSUserDefaults>);
|
||||
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");
|
||||
}
|
||||
}
|
||||
@@ -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<String>) {
|
||||
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.
|
||||
|
||||
@@ -24,13 +24,24 @@ pub(crate) fn config_dir() -> Option<std::path::PathBuf> {
|
||||
/// 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<lightcraft_ui_egui::window_place::WindowPlace>) -> 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<lightcraft_ui_egui::window_place::WindowPlace>,
|
||||
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");
|
||||
|
||||
/// `<config>/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<std::path::PathBuf> {
|
||||
@@ -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<std::time::Instant>,
|
||||
/// 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<lightcraft_ui_egui::window_place::StartPlace>,
|
||||
}
|
||||
|
||||
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) {
|
||||
|
||||
@@ -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<u8> {
|
||||
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));
|
||||
}
|
||||
|
||||
|
||||
@@ -92,3 +92,6 @@ display_name = "Terra854"
|
||||
|
||||
[people.P2Hdontusegithub]
|
||||
display_name = "Pizhy"
|
||||
|
||||
[people.gmrmad1]
|
||||
real_name = "Madhav Agarwal"
|
||||
|
||||
@@ -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<i64>, 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<u32, Vec<PhotoId>> {
|
||||
let mut by: HashMap<u32, Vec<&Photo>> = 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<PhotoId> {
|
||||
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<PhotoId>>) -> Vec<(u32, Vec<PhotoId>)> {
|
||||
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<Analysis>) -> 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<u32>) -> Option<Analysis> {
|
||||
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);
|
||||
}
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+308
-4
@@ -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<Option<HashMap<PhotoId, StackId>>>,
|
||||
/// Album → its photos (regular albums; a smart album's list is empty).
|
||||
albums: OnceLock<HashMap<AlbumId, HashSet<PhotoId>>>,
|
||||
/// Content ([`content_key`]) → the photos that have it.
|
||||
contents: OnceLock<HashMap<String, Vec<PhotoId>>>,
|
||||
/// Whether a smart album asks whether a photo has the same content as another ([`Catalog::follows_contents`]).
|
||||
contents_asked: OnceLock<bool>,
|
||||
/// 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<HashMap<String, HashSet<PhotoId>>>,
|
||||
/// 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<BTreeSet<AlbumId>>,
|
||||
/// Photo → its lower-cased searchable text ([`PhotoText`]), for the free-text search.
|
||||
search: OnceLock<ByPhoto<PhotoText>>,
|
||||
/// Photo → the lower-cased text a smart album's Text rule looks through ([`crate::rules::rule_text`]).
|
||||
rule_text: OnceLock<ByPhoto<RuleText>>,
|
||||
}
|
||||
|
||||
/// 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<String>) {
|
||||
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<T> = HashMap<PhotoId, T, std::hash::BuildHasherDefault<IdHasher>>;
|
||||
|
||||
/// 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<Photo>` 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<str>,
|
||||
}
|
||||
|
||||
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::<usize>()
|
||||
.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<str>,
|
||||
}
|
||||
|
||||
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<String, HashSet<PhotoId>>, id: PhotoId, old: Option<String>, new: Option<String>) {
|
||||
if let Some(k) = old
|
||||
&& let Some(set) = m.get_mut(&k)
|
||||
@@ -166,7 +368,29 @@ fn sorted(set: Option<&HashSet<PhotoId>>) -> Vec<PhotoId> {
|
||||
v
|
||||
}
|
||||
|
||||
/// The content photo `p` stands for in the library: its file's hash, without the `:dup<id>` 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<AlbumId> {
|
||||
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<StackId> {
|
||||
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<String, Vec<PhotoId>> {
|
||||
self.index.contents.get_or_init(|| {
|
||||
let mut m: HashMap<String, Vec<PhotoId>> = 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<String> {
|
||||
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<String>, new: Option<String>) {
|
||||
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<PhotoId> =
|
||||
[&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<String>) -> HashMap<String, HashSet<PhotoId>> {
|
||||
let t = web_time::Instant::now();
|
||||
let mut m: HashMap<String, HashSet<PhotoId>> = HashMap::new();
|
||||
|
||||
+305
-22
@@ -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<format>-<seq>` and
|
||||
//! `catalog.log.v<format>-<seq>` (`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<String>,
|
||||
/// Those this attempt wrote. The others were there already, byte for byte the same.
|
||||
created: Vec<String>,
|
||||
}
|
||||
|
||||
/// 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<u32>,
|
||||
/// What [`Catalog::repair`] changed in a damaged snapshot (empty for a sound one).
|
||||
pub repaired: Vec<String>,
|
||||
/// 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<String>,
|
||||
/// 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<u32>,
|
||||
/// 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<Vec<String>>,
|
||||
kept_written: Vec<String>,
|
||||
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<dyn Store>) -> 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<Option<Vec<String>>> {
|
||||
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<Option<u32>> {
|
||||
match self.store.read(SNAPSHOT) {
|
||||
Ok(None) => Some(None),
|
||||
Ok(Some(bytes)) => serde_json::from_slice::<SnapHeader>(&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<Kept> {
|
||||
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::<SnapHeader>(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<String> {
|
||||
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;
|
||||
|
||||
@@ -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<Item = &str> {
|
||||
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<String> {
|
||||
let mut out: Vec<String> = hierarchical.iter().map(|k| clean(k)).collect();
|
||||
let lines = |v: &[String]| -> Vec<String> { v.iter().flat_map(|k| split_lines(k)).collect() };
|
||||
let (flat, hierarchical) = (lines(flat), lines(hierarchical));
|
||||
let mut out: Vec<String> = 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<String> = 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<String> {
|
||||
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<Op> {
|
||||
let gone: Vec<String> = 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<String> = 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<String> = Vec::new();
|
||||
let mut seen: HashSet<String> = 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<String> = 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<String> = 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<String> = 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<Op> {
|
||||
let into = clean(into);
|
||||
|
||||
@@ -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<PhotoId>) {
|
||||
let mut c = Catalog::new();
|
||||
let mut ids = Vec::new();
|
||||
|
||||
+210
-48
@@ -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<CatalogError>, remaining: Box<Op> },
|
||||
}
|
||||
|
||||
pub type Result<T> = std::result::Result<T, CatalogError>;
|
||||
@@ -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<String>,
|
||||
/// 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<DevelopSettings>, Arc<DevelopSettings>, 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<DevelopSettings>, 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<DevelopSettings>, 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<Op>,
|
||||
}
|
||||
|
||||
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<Op>) {
|
||||
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<AlbumId> {
|
||||
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<Vec<PhotoId>> {
|
||||
if !self.remembers(revision) {
|
||||
return None;
|
||||
}
|
||||
let mut ids: Vec<PhotoId> = 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<Vec<PhotoId>> {
|
||||
// (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<PhotoId> {
|
||||
let mut ids: Vec<PhotoId> = 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<Op> {
|
||||
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<Op> {
|
||||
// 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<Op> {
|
||||
// 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<String> {
|
||||
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::<Op>(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;
|
||||
|
||||
+170
-3
@@ -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<String> {
|
||||
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<String> = 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<String> = 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<String> = make.split_whitespace().map(word_key).collect();
|
||||
let run = longest(&full).max(longest(&said));
|
||||
let own: Vec<String> = 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<String> = 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<DevelopSettings>,
|
||||
#[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<DevelopSettings>,
|
||||
}
|
||||
|
||||
@@ -279,6 +357,7 @@ pub struct Photo {
|
||||
pub flag: Flag,
|
||||
#[serde(default)]
|
||||
pub label: Option<ColorLabel>,
|
||||
#[serde(deserialize_with = "crate::shared::deserialize_current")]
|
||||
pub develop: Arc<DevelopSettings>,
|
||||
#[serde(default)]
|
||||
pub edited: Option<String>,
|
||||
@@ -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<lightcraft_develop::EmbeddedLens>,
|
||||
pub embedded_lens: Option<Box<lightcraft_develop::EmbeddedLens>>,
|
||||
/// 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<Arc<DevelopSettings>>,
|
||||
/// Assisted culling scores (`None` until analysed).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
@@ -355,6 +434,20 @@ pub struct Analysis {
|
||||
pub group: Option<u32>,
|
||||
/// 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<u32>,
|
||||
}
|
||||
|
||||
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<String> {
|
||||
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"));
|
||||
}
|
||||
}
|
||||
|
||||
+48
-17
@@ -152,6 +152,10 @@ fn shuffle_rank(seed: u64, id: PhotoId) -> u64 {
|
||||
pub(crate) struct Prepared {
|
||||
root: Option<String>,
|
||||
only: Option<std::collections::HashSet<PhotoId>>,
|
||||
/// The search words ([`Filter::tokens`]).
|
||||
tokens: Vec<String>,
|
||||
/// 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<crate::RuleSet>,
|
||||
@@ -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<Option<&'a crate::index::PhotoText>>,
|
||||
own: std::cell::OnceCell<crate::index::PhotoText>,
|
||||
}
|
||||
|
||||
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<String> {
|
||||
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<String> {
|
||||
// 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))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+45
-22
@@ -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.
|
||||
|
||||
@@ -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<u64> {
|
||||
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<u64> = 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::<u64>::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");
|
||||
|
||||
@@ -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<T: serde::Serialize + ?Sized>(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: std::fmt::Display>(_: 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<T: serde::Serialize + ?Sized>(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<T: serde::Serialize + ?Sized>(self, _: &'static str, v: &T) -> Walked {
|
||||
v.serialize(Walk)
|
||||
}
|
||||
|
||||
fn serialize_newtype_variant<T: serde::Serialize + ?Sized>(self, _: &'static str, _: u32, _: &'static str, v: &T) -> Walked {
|
||||
v.serialize(Walk)
|
||||
}
|
||||
|
||||
fn serialize_seq(self, _: Option<usize>) -> Result<Walk, Found> {
|
||||
Ok(Walk)
|
||||
}
|
||||
|
||||
fn serialize_tuple(self, _: usize) -> Result<Walk, Found> {
|
||||
Ok(Walk)
|
||||
}
|
||||
|
||||
fn serialize_tuple_struct(self, _: &'static str, _: usize) -> Result<Walk, Found> {
|
||||
Ok(Walk)
|
||||
}
|
||||
|
||||
fn serialize_tuple_variant(self, _: &'static str, _: u32, _: &'static str, _: usize) -> Result<Walk, Found> {
|
||||
Ok(Walk)
|
||||
}
|
||||
|
||||
fn serialize_map(self, _: Option<usize>) -> Result<Walk, Found> {
|
||||
Ok(Walk)
|
||||
}
|
||||
|
||||
fn serialize_struct(self, _: &'static str, _: usize) -> Result<Walk, Found> {
|
||||
Ok(Walk)
|
||||
}
|
||||
|
||||
fn serialize_struct_variant(self, _: &'static str, _: u32, _: &'static str, _: usize) -> Result<Walk, Found> {
|
||||
Ok(Walk)
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! walk_elements {
|
||||
($($trait:ident::$method:ident),* $(,)?) => {
|
||||
$(impl serde::ser::$trait for Walk {
|
||||
type Ok = ();
|
||||
type Error = Found;
|
||||
|
||||
fn $method<T: serde::Serialize + ?Sized>(&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<T: serde::Serialize + ?Sized>(&mut self, k: &T) -> Walked {
|
||||
k.serialize(Walk)
|
||||
}
|
||||
|
||||
fn serialize_value<T: serde::Serialize + ?Sized>(&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<T: serde::Serialize + ?Sized>(&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<T: serde::Serialize + ?Sized>(&mut self, _: &'static str, v: &T) -> Walked {
|
||||
v.serialize(Walk)
|
||||
}
|
||||
|
||||
fn end(self) -> Walked {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn held_default() -> &'static Arc<DevelopSettings> {
|
||||
static DEFAULT: OnceLock<Arc<DevelopSettings>> = OnceLock::new();
|
||||
DEFAULT.get_or_init(|| Arc::new(DevelopSettings::default()))
|
||||
}
|
||||
|
||||
/// The default settings, held once.
|
||||
pub fn default_settings() -> Arc<DevelopSettings> {
|
||||
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<Weak<DevelopSettings>>,
|
||||
/// The last few values, the latest first.
|
||||
recent: Vec<Weak<DevelopSettings>>,
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static SEEN: RefCell<Seen> = 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<DevelopSettings>) -> Arc<DevelopSettings> {
|
||||
share(settings, false)
|
||||
}
|
||||
|
||||
/// [`settings`] for a photo's own settings (`current`): what its history is compared with first.
|
||||
fn share(settings: Arc<DevelopSettings>, current: bool) -> Arc<DevelopSettings> {
|
||||
// (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<DevelopSettings>| 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<DevelopSettings>,
|
||||
/// Whether `own` holds no negative zero (looked for once, and only when an equal value turned up).
|
||||
exact: OnceCell<bool>,
|
||||
}
|
||||
|
||||
impl Anchor {
|
||||
pub(crate) fn new(own: Arc<DevelopSettings>) -> 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<DevelopSettings>) -> Arc<DevelopSettings> {
|
||||
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<Arc<DevelopSettings>, 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<Arc<DevelopSettings>, 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<Option<Arc<DevelopSettings>>, D::Error> {
|
||||
Ok(Option::<DevelopSettings>::deserialize(d)?.map(|s| share(Arc::new(s), false)))
|
||||
}
|
||||
+113
-5
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
+165
-1
@@ -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>| 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");
|
||||
}
|
||||
|
||||
@@ -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<Option<Vec<u8>>> {
|
||||
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<N>-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<u8>, Vec<u8>) {
|
||||
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::<Vec<_>>(), [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::<Vec<_>>(), [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::<Vec<_>>(), [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> = 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> = 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<Option<Vec<u8>>> {
|
||||
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::<Vec<_>>(), [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::<Vec<_>>(), [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> = 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<Option<Vec<u8>>> {
|
||||
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::<Vec<_>>(), [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<Option<Vec<u8>>> {
|
||||
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::<Vec<_>>(), [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<Option<Vec<u8>>> {
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -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::<String>::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::<String>::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");
|
||||
}
|
||||
|
||||
@@ -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<PhotoId> {
|
||||
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, &[]);
|
||||
}
|
||||
@@ -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<u64> {
|
||||
let f = Filter { text: text.into(), ..Default::default() };
|
||||
let mut ids: Vec<u64> = c.query(&f, &Sort::default()).into_iter().map(|id| id.0).collect();
|
||||
ids.sort_unstable();
|
||||
ids
|
||||
}
|
||||
|
||||
fn expected(c: &Catalog, text: &str) -> Vec<u64> {
|
||||
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::<Vec<_>>());
|
||||
}
|
||||
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<u64> = 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<Vec<usize>> = 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<Vec<usize>> = 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<Vec<usize>> =
|
||||
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::<u64>::new(), "{text:?}");
|
||||
}
|
||||
assert_eq!(shown(&c, "c\0d"), vec![2], "a field's own NUL is still found");
|
||||
}
|
||||
@@ -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<DevelopSettings> {
|
||||
let mut s = DevelopSettings::default();
|
||||
d(&mut s);
|
||||
Arc::new(s)
|
||||
}
|
||||
|
||||
fn catalog_of(photos: impl IntoIterator<Item = Photo>) -> 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<DevelopSettings> {
|
||||
&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<DevelopSettings>| 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::<Photo>(&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<String>, out: &mut Vec<Vec<String>>) {
|
||||
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::<String>();
|
||||
*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");
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<Vec<u8>> {
|
||||
static S: OnceLock<Vec<Vec<u8>>> = OnceLock::new();
|
||||
S.get_or_init(|| {
|
||||
|
||||
@@ -35,6 +35,7 @@ fn sources(op: &Op) -> (usize, Option<usize>) {
|
||||
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<f32> = 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;
|
||||
|
||||
@@ -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 }
|
||||
|
||||
+469
-23
@@ -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<T>(why: impl Into<String>) -> Result<T, NetError> {
|
||||
Err(NetError::Unsupported(why.into()))
|
||||
@@ -62,11 +64,23 @@ fn read_bytes(bytes: &[u8]) -> Result<Net, NetError> {
|
||||
// a Concat is not a layer of its own: the convolution that reads it takes both sources
|
||||
let mut joins: HashMap<String, (TensorId, TensorId)> = HashMap::new();
|
||||
let mut ops: Vec<Op> = 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<Net, NetError> {
|
||||
"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<Net, NetError> {
|
||||
let lookup = |name: &str| -> Result<TensorId, NetError> {
|
||||
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<f32>, 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<String, (TensorId, TensorId)>| -> Result<(Option<f32>, 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<Net, NetError> {
|
||||
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<Net, NetError> {
|
||||
}
|
||||
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<Net, NetError> {
|
||||
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<Net, NetError> {
|
||||
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<i64> {
|
||||
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<usize> {
|
||||
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<u8> {
|
||||
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<u8> {
|
||||
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<u8> = values.iter().flat_map(|v| v.to_le_bytes()).collect();
|
||||
len_field(9, &raw, &mut t);
|
||||
t
|
||||
}
|
||||
|
||||
fn model(nodes: &[Vec<u8>], in_channels: u64, out: &str) -> Vec<u8> {
|
||||
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<u8>) {
|
||||
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<u8> {
|
||||
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<u8> {
|
||||
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());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -104,6 +104,16 @@ pub fn run(net: &Net, tile: usize, input: &[f32]) -> Result<Vec<f32>, 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);
|
||||
|
||||
+373
-45
@@ -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<String, Value>>, patch: &Map<String, Value>, t: f64) -> Map<String, Value> {
|
||||
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<String, Value>>| 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<String, Value>>, patch: &Map<String, Val
|
||||
out.insert(k.clone(), v);
|
||||
}
|
||||
}
|
||||
if other_scale {
|
||||
// the numbers and their scale come together from one side, never a mix of the two
|
||||
let side = if t >= 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<Value> {
|
||||
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<Value
|
||||
}
|
||||
}
|
||||
|
||||
/// `v` as a point curve: a list whose items all are `{x, y}` numbers (empty: the identity).
|
||||
fn point_curve(v: &Value) -> Option<Vec<(f64, f64)>> {
|
||||
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<f64> = 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<lightcraft_geom::Point> {
|
||||
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::<Vec<_>>()).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]
|
||||
|
||||
@@ -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"]
|
||||
|
||||
|
||||
@@ -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 (`<key>.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 -- <manifest.json> <out.jsonl> [--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<String> = std::env::args().skip(1).collect();
|
||||
let manifest: Vec<Value> = 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");
|
||||
}
|
||||
}
|
||||
@@ -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<Lane> {
|
||||
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<Vec<Arc<Entry>>>,
|
||||
/// The tasks waiting in line, in the order they were asked for.
|
||||
waiting: Mutex<Vec<Waiting>>,
|
||||
/// The id the waiting task being started keeps (its kind, its id): see [`Activity::take_ready`].
|
||||
reserved: Mutex<Option<(&'static str, u64)>>,
|
||||
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<Lane>,
|
||||
}
|
||||
|
||||
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<TaskInfo> {
|
||||
lock(&self.inner.tasks).iter().map(|e| e.info()).collect()
|
||||
let mut rows: Vec<TaskInfo> = 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<TaskInfo> {
|
||||
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<TaskInfo> {
|
||||
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<Waiting> {
|
||||
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<Waiting> {
|
||||
let mut waiting = lock(&self.inner.waiting);
|
||||
let mut held: Vec<Lane> = 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::<Vec<_>>(), (1..=MAX_WAITING).collect::<Vec<_>>());
|
||||
}
|
||||
|
||||
#[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<_>>(), 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());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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<Mat3>, pooled: Option<CameraTone>) -> 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<CameraLook>,
|
||||
colour: Option<(Mat3, Option<HsvTable>)>,
|
||||
pooled: Option<CameraTone>,
|
||||
tone_only: impl FnOnce((Mat3, Option<HsvTable>)) -> Option<CameraLook>,
|
||||
) -> Option<CameraLook> {
|
||||
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<bool>)> {
|
||||
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<Cr3Framing>,
|
||||
}
|
||||
|
||||
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<(f64, [f64; 3], [f64; 3])>> = 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<f64> {
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -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<bool>)> {
|
||||
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<bool>, Option<Cr3Framing>)> {
|
||||
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<Cr3Framing>) {
|
||||
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<Vec<([f64; 3], [f64; 3])>> {
|
||||
/// 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<ProfileSamples> {
|
||||
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<ProfileSamples> {
|
||||
// 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<CameraTone> {
|
||||
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<Vec<[f32; 2]>> {
|
||||
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<usize> = (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)
|
||||
|
||||
@@ -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<f32> = (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<bool> = 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<Cr3Framing>| {
|
||||
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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<HsvTable>,
|
||||
/// 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<CameraTone>,
|
||||
}
|
||||
|
||||
impl CameraProfile {
|
||||
pub fn new(model: &str, files: usize, samples: usize, matrix: Mat3, hue_sat: Option<HsvTable>) -> 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<CameraTone>) -> 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<String, (usize, Vec<([f64; 3], [f64; 3])>)>,
|
||||
models: HashMap<String, Model>,
|
||||
}
|
||||
|
||||
/// 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<T>(items: Vec<T>) -> impl Iterator<Item = T> {
|
||||
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<Option<String>, 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<Option<Added>, 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());
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -11,7 +11,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"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<CommandSpec> {
|
||||
"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";
|
||||
|
||||
@@ -80,28 +80,16 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
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"}))
|
||||
}),
|
||||
]
|
||||
|
||||
+243
-24
@@ -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<CommandSpec> {
|
||||
|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<CommandSpec> {
|
||||
|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<Value> {
|
||||
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<PathBuf> {
|
||||
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<String>, from: &str, to: &str) {
|
||||
fn follow_library_folder(chosen: &mut Option<String>, 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<String, String> {
|
||||
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<PathBuf> {
|
||||
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<PathBuf> {
|
||||
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<usize, String> {
|
||||
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<Op> = 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() {
|
||||
|
||||
@@ -129,16 +129,26 @@ fn targeted(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
"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;
|
||||
|
||||
@@ -294,7 +294,7 @@ fn legacy_shutter_text(t: f64) -> Option<String> {
|
||||
/// 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<Op> {
|
||||
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);
|
||||
|
||||
+249
-35
@@ -29,10 +29,14 @@ fn analyze(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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<bool> {
|
||||
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<i64>, f32, f32, [f32; 64])> = Vec::new();
|
||||
let mut failed = Vec::new();
|
||||
@@ -48,17 +52,25 @@ fn analyze(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
// 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<Analysis> { s.catalog.photo(id).and_then(|p| p.analysis).filter(|a| !reset && a.by_hand()) };
|
||||
let kept: Vec<Option<Analysis>> = rows.iter().map(|r| by_hand(r.0)).collect();
|
||||
let auto: Vec<usize> = (0..rows.len()).filter(|i| kept[*i].is_none()).collect();
|
||||
let regrouped: std::collections::HashSet<PhotoId> = 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<Option<u32>> = 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<u32, (usize, f32)> = Default::default();
|
||||
@@ -74,9 +86,16 @@ fn analyze(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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<Value> {
|
||||
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<u32, Vec<(PhotoId, f32)>> = 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<u32, Vec<(u32, PhotoId)>> = 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<PhotoId>> = 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<PhotoId> = 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<Value> {
|
||||
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<Value> {
|
||||
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<u32, Vec<PhotoId>> = 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<PhotoId>| members.len() >= 2 || (target == Some(g) && !members.is_empty());
|
||||
let mut placed: HashMap<PhotoId, (Option<u32>, 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<Vec<u64>> = 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<PhotoId, Flag> = 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<PhotoId> = 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<CommandSpec> {
|
||||
"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
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -88,7 +88,7 @@ fn recipe_partial(recipe: &[(String, f64)]) -> Option<Value> {
|
||||
/// 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<DevelopSettings> {
|
||||
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<CommandSpec> {
|
||||
"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<CommandSpec> {
|
||||
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<CommandSpec> {
|
||||
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::<Vec<_>>();
|
||||
|
||||
@@ -302,7 +302,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
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,
|
||||
|
||||
@@ -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<CommandSpec> {
|
||||
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,
|
||||
|
||||
@@ -145,7 +145,8 @@ fn reverse(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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<CommandSpec> {
|
||||
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<CommandSpec> {
|
||||
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,
|
||||
|
||||
@@ -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<Option<String>> {
|
||||
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<Vec<String>> {
|
||||
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<String> = 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<String> {
|
||||
let k = str_param(p, "keyword").ok_or_else(|| bad(command, "missing `keyword`"))?;
|
||||
@@ -493,15 +527,23 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"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<CommandSpec> {
|
||||
"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<String> = 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);
|
||||
|
||||
@@ -33,7 +33,7 @@ pub struct Missing {
|
||||
pub fn missing(cat: &Catalog, db: &lightcraft_lensdb::LensDb, ids: Option<&[PhotoId]>, again: bool) -> Vec<Missing> {
|
||||
// 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<ProbeIn
|
||||
for (item, info) in results {
|
||||
let Ok(info) = info else { continue };
|
||||
// the photo moved or left the library while its file was read: the result is stale, for its copies too
|
||||
if s.catalog.photo(item.id).and_then(|p| crate::cmd::missing::checked_path(p)) != Some(item.path.as_str()) {
|
||||
if s.catalog.photo(item.id).and_then(|p| p.library_file()) != Some(item.path.as_str()) {
|
||||
continue;
|
||||
}
|
||||
let family = std::iter::once(item.id).chain(copies.get(&item.id).into_iter().flatten().copied());
|
||||
for id in family {
|
||||
let Some(p) = s.catalog.photo(id) else { continue };
|
||||
// nothing found for a photo without a database profile: a file's own correction is Reload's business
|
||||
let from_database = p.embedded_lens.is_some_and(|l| l.source == LensSource::Database);
|
||||
let from_database = p.embedded_lens.as_deref().is_some_and(|l| l.source == LensSource::Database);
|
||||
if info.embedded_lens.is_some() || from_database {
|
||||
let mine = crate::cmd::convert::lens_ops(id, p, &info);
|
||||
if !mine.is_empty() {
|
||||
|
||||
@@ -6,8 +6,8 @@ use super::selection::{
|
||||
opt_album_param, rotate, row_step, select_after_deletion, select_by, step, strs,
|
||||
};
|
||||
use super::{
|
||||
Album, AlbumId, ColorLabel, CommandSpec, CopyrightStatus, Filter, Flag, GroupBy, LibrarySource, Op, PhotoId, Result, Selection, Sort, SortKey,
|
||||
Value, always, bad, bool_or, cmd, has_active, has_library_selection, has_selection, json, ok, str_param,
|
||||
Album, AlbumId, ColorLabel, CommandSpec, CopyrightStatus, Filter, Flag, GroupBy, LibrarySource, Op, PhotoId, Result, Selection, Session, Sort,
|
||||
SortKey, Value, always, bad, bool_or, cmd, has_active, has_library_selection, has_selection, json, ok, str_param,
|
||||
};
|
||||
|
||||
/// Seeds stay exactly representable as a JSON double, so web and agent clients read back what they wrote.
|
||||
@@ -29,6 +29,91 @@ fn next_seed(prev: u64, now: &str) -> 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<Value> {
|
||||
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<AlbumId> = 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<AlbumId> = 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<AlbumId> = 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<Op> = 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<Vec<AlbumId>> {
|
||||
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<AlbumId> = 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<Vec<String>> {
|
||||
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<String> = 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<CommandSpec> {
|
||||
vec![
|
||||
// ---- view source / filter / sort
|
||||
@@ -128,35 +213,52 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"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<PhotoId> = 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<CommandSpec> {
|
||||
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<CommandSpec> {
|
||||
"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<CommandSpec> {
|
||||
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<CommandSpec> {
|
||||
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<CommandSpec> {
|
||||
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<CommandSpec> {
|
||||
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<CommandSpec> {
|
||||
"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::<AlbumId, Vec<AlbumId>>::new();
|
||||
for album in s.catalog.albums() {
|
||||
if let Some(parent) = album.parent {
|
||||
@@ -956,32 +1089,61 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
// 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",
|
||||
|
||||
@@ -324,7 +324,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"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<Point> = p
|
||||
@@ -347,6 +347,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
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<CommandSpec> {
|
||||
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<CommandSpec> {
|
||||
"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<CommandSpec> {
|
||||
"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<CommandSpec> {
|
||||
}))
|
||||
}
|
||||
),
|
||||
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<CommandSpec> {
|
||||
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<Spo
|
||||
s.set_develop(id, d, label)
|
||||
}
|
||||
|
||||
/// A brushed spot's points as stored: consecutive near-duplicates dropped and the stroke thinned to one point
|
||||
/// every `size / 4` (long-edge units, like the mask brush's dabs), the first and the last point kept. `dims` is
|
||||
/// the oriented photo's width and height: points are normalized per axis, so a distance counts in long-edge
|
||||
/// units (issue #2359). A caller that records a point per frame (the app's brush, an agent replaying a pointer)
|
||||
/// then stores a handful of points instead of dozens that all draw and render the same disc.
|
||||
fn thin_spot_points(pts: &[Point], size: f64, (w, h): (f64, f64)) -> Vec<Point> {
|
||||
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<Point> = 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<Point>) -> Option<Point> {
|
||||
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<Point> = (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<Point> = (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<f64> = 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<Point> = (0..50).map(|i| Point::new(0.2 + 0.001 * f64::from(i), 0.3)).collect();
|
||||
let doubled: Vec<Point> = 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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<String> {
|
||||
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<Item = (PhotoId, &'a str)>) -> u64 {
|
||||
@@ -66,7 +53,7 @@ fn fingerprint_of<'a>(entries: impl Iterator<Item = (PhotoId, &'a str)>) -> 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<FindCandidate> {
|
||||
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<Value> {
|
||||
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<String> = candidates(&s.catalog).into_iter().collect();
|
||||
let mut found = Vec::new();
|
||||
let mut missing = plan.missing;
|
||||
|
||||
@@ -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<AtomicBool>,
|
||||
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<PreviewBuild>,
|
||||
task: Option<TaskGuard>,
|
||||
}
|
||||
|
||||
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<PreviewBuild>) {
|
||||
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<Result<Value>> {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
} 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<PhotoJobs> = 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<Value> {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
// (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<SmartJob> = 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<Value> {
|
||||
}
|
||||
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<CommandSpec> {
|
||||
"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<CommandSpec> {
|
||||
"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());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<Stale> {
|
||||
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()
|
||||
}
|
||||
|
||||
|
||||
@@ -84,7 +84,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
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<CommandSpec> {
|
||||
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,
|
||||
|
||||
@@ -164,11 +164,14 @@ fn sam3_dir(var: Option<std::ffi::OsString>, config: Option<PathBuf>) -> 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 `<config>/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 `<config>/models/sam3-mirrors.txt` and for where it runs in
|
||||
/// `<config>/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
|
||||
}
|
||||
|
||||
|
||||
@@ -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 },
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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>(())
|
||||
};
|
||||
|
||||
@@ -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<Vec<[f32; 3]>> {
|
||||
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<f32> = 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<f32> = (-r..=r).map(|d| (-((d * d) as f32) / (2.0 * sigma * sigma)).exp()).collect();
|
||||
let norm: f32 = taps.iter().sum();
|
||||
let taps: Vec<f32> = 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<f32> {
|
||||
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
|
||||
|
||||
@@ -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::<Vec<_>>().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<chrono::NaiveDateTime>) -> 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<chrono::NaiveDateTime> {
|
||||
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<String, String> {
|
||||
fn folder_for(&self, name: &str, source_dir: Option<&str>, subfolder: Option<&str>) -> Result<String, String> {
|
||||
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<Exported, String>,
|
||||
) -> 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,
|
||||
|
||||
@@ -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<String>,
|
||||
/// 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<crate::originals::OriginalGuard>,
|
||||
@@ -88,13 +91,23 @@ pub fn prepare_export(
|
||||
seq: usize,
|
||||
) -> Result<PreparedExport, String> {
|
||||
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<Vec<PreparedExport>, 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<crate::originals::OriginalGuard>,
|
||||
now: Option<chrono::NaiveDateTime>,
|
||||
album: Option<&str>,
|
||||
) -> Result<PreparedExport, String> {
|
||||
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
|
||||
|
||||
@@ -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<u8> {
|
||||
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::<f64>() / 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() {
|
||||
|
||||
@@ -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());
|
||||
|
||||
@@ -117,11 +117,12 @@ fn fs_load<T>(path: &str, max_edge: usize, load: impl FnOnce(Vec<u8>) -> 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<String> {
|
||||
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 {
|
||||
|
||||
@@ -121,6 +121,23 @@ pub fn embedded_lens(raw: &lightcraft_raw::RawInfo) -> Option<lightcraft_develop
|
||||
Some(lightcraft_pipeline::optics::reorient_lens(&lens, raw.orientation, cw, ch))
|
||||
}
|
||||
|
||||
fn xmp_has_rating(x: &str) -> 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<String> {
|
||||
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<ProbeInfo, String> {
|
||||
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<ProbeInfo, String> {
|
||||
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<ProbeInfo, String> {
|
||||
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<ProbeInfo, String> {
|
||||
as_shot_wb: None,
|
||||
content_hash,
|
||||
embedded_lens: None,
|
||||
xmp: None,
|
||||
xmp,
|
||||
orientation: m.orientation,
|
||||
preview_only: None,
|
||||
})
|
||||
|
||||
@@ -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:?}");
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -224,16 +224,31 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare
|
||||
let mut purged: std::collections::HashSet<PhotoId> = 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<i64> {
|
||||
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<i64> {
|
||||
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<i64> {
|
||||
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()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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<BrowsedFile> {
|
||||
// (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]
|
||||
|
||||
+132
-32
@@ -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<String, (PhotoId, bool)>,
|
||||
pub(super) by_path: HashMap<String, (PhotoId, bool, Option<String>)>,
|
||||
/// 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<String, u64>,
|
||||
/// content hash → the photo that has it (`None`: a file earlier in this import)
|
||||
pub(super) by_hash: HashMap<String, Option<PhotoId>>,
|
||||
pub(super) probe: Option<crate::media::FileProbe>,
|
||||
@@ -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<Box<ProbeInfo>>),
|
||||
Duplicate {
|
||||
path: String,
|
||||
existing: Option<PhotoId>,
|
||||
@@ -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<String>,
|
||||
verdicts: Vec<Option<BrowsedFile>>,
|
||||
local: bool,
|
||||
out: &mut Prepared,
|
||||
changed: &mut HashMap<String, PhotoId>,
|
||||
todo: &mut Vec<String>,
|
||||
) {
|
||||
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<String>) -> 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<String>, 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<String, PhotoId> = 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<Option<BrowsedFile>> = 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());
|
||||
|
||||
@@ -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<PathBuf, (PhotoId, ImportCandidate)> {
|
||||
pub(super) fn library_files(library: &lightcraft_catalog::Catalog, files: &[String]) -> HashMap<PathBuf, (PhotoId, ImportCandidate, Option<String>)> {
|
||||
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<Item = &'a str>) -> HashMap<String, PhotoId> {
|
||||
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<String>, 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<PathBuf, PhotoId> = 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<String> = 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<String>, progress: &Sc
|
||||
crate::memory::release();
|
||||
let mut probes: HashMap<String, Result<ProbeInfo, String>> = 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<String, Option<u64>> =
|
||||
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<String, String> = 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<String>, 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),
|
||||
|
||||
@@ -28,7 +28,7 @@ fn a_scan_knows_the_library_photos_of_the_files_it_found() {
|
||||
let files: Vec<String> = ["/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
|
||||
|
||||
@@ -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<String>,
|
||||
/// The photo that already has it.
|
||||
/// The photo that already has it. On a browsed candidate (`local`): its record.
|
||||
pub existing: Option<u64>,
|
||||
/// 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<String>,
|
||||
/// Not readable.
|
||||
pub error: Option<String>,
|
||||
/// A raw variant that can't be decoded yet (why): it imports as preview only.
|
||||
|
||||
+143
-18
@@ -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<dyn Fn() -> 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<u32>,
|
||||
/// 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<std::sync::Arc<cmd::previews::PreviewBuild>>,
|
||||
/// 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<Value> {
|
||||
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<Value> {
|
||||
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<cmd::previews::PreviewBuild>) {
|
||||
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::sync::Arc<cmd::previews::PreviewBuild>> {
|
||||
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<UndoEntry> {
|
||||
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<String> {
|
||||
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<Value> {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod lightroom_fixture;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -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<String> {
|
||||
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<T: serde::de::DeserializeOwned>(&mut self, store: &mut dyn Store, name: &'static str) -> Option<T> {
|
||||
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(())
|
||||
}
|
||||
|
||||
@@ -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<String> 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<PathBuf, String> {
|
||||
pub fn store(directory: &Path, data: &CatalogImport) -> Result<PathBuf, StoreError> {
|
||||
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<PathBuf, StoreError> {
|
||||
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<PathBuf, String>
|
||||
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<PathBuf, String>
|
||||
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<PathBuf, String>
|
||||
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<Option<PathBuf>, 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<Kept, String> {
|
||||
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<PathBuf, String>
|
||||
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::<TooBig>()) {
|
||||
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<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
|
||||
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<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
|
||||
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<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
|
||||
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<String, Value>]);
|
||||
/// Rows, each without the column `.1` names.
|
||||
struct RowSeq<'a>(&'a [BTreeMap<String, Value>], Option<&'a str>);
|
||||
impl Serialize for RowSeq<'_> {
|
||||
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
|
||||
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<String, Value>);
|
||||
struct RowRef<'a>(&'a BTreeMap<String, Value>, Option<&'a str>);
|
||||
impl Serialize for RowRef<'_> {
|
||||
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
|
||||
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));
|
||||
|
||||
@@ -48,8 +48,31 @@ struct Reader {
|
||||
db: Database,
|
||||
tables: Vec<LiveTable>,
|
||||
}
|
||||
/// 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<Vec<Row>, String> {
|
||||
fn table(&self, name: &str, required: bool, warnings: &mut Vec<String>) -> Result<Vec<Row>, 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<String>) -> Result<Vec<Row>, 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<String> {
|
||||
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<String>) -> Result<Vec<Row>, 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<String, String> {
|
||||
}
|
||||
}
|
||||
|
||||
fn decode_xmp_bytes(bytes: &[u8]) -> Result<String, String> {
|
||||
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<usize> {
|
||||
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<String, String> {
|
||||
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<Vec<Row>, String> {
|
||||
let table = |name: &str, required: bool, warnings: &mut Vec<String>| -> Result<Vec<Row>, 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(|| {
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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<u8>),
|
||||
}
|
||||
|
||||
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<Vec<Field>>,
|
||||
}
|
||||
|
||||
/// 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<u8> {
|
||||
compressed_bytes(text.as_bytes())
|
||||
}
|
||||
|
||||
/// [`compressed`] for any bytes, including ones that aren't UTF-8.
|
||||
pub(crate) fn compressed_bytes(bytes: &[u8]) -> Vec<u8> {
|
||||
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<Field> {
|
||||
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<Field> {
|
||||
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 (`<originals>/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<Table> {
|
||||
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<Field>], table: &str) -> Vec<u8> {
|
||||
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<u8> {
|
||||
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<u8> {
|
||||
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
|
||||
}
|
||||
@@ -31,11 +31,20 @@ fn cancelled() -> crate::EngineError {
|
||||
}
|
||||
|
||||
fn stage_archive(archive_dir: Option<&Path>, data: &mut CatalogImport) -> crate::Result<Option<PathBuf>> {
|
||||
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]
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
|
||||
@@ -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];
|
||||
|
||||
+59
-15
@@ -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<Value> {
|
||||
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<PhotoId> = 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)
|
||||
}
|
||||
|
||||
|
||||
@@ -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<DevelopSettings> {
|
||||
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::*;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<PhotoId, &'a str>) {
|
||||
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<PhotoId>) -> 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<PhotoId> = 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<Op>) {
|
||||
let mut pending = vec![op];
|
||||
|
||||
@@ -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);
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user