Merge storytold/main at eaef01e9

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CvoftP5JSqAEJ9t7FSczTs
This commit is contained in:
insideTheFluxandClaude Opus 5.5 committed 2026-11-04 23:26:09 -08:00
commit 4c1d2e919b
314 files changed
+22816 -1213

No files matched your search

+1
View File
@@ -85,3 +85,4 @@ jobs:
AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }}
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}
+3
View File
@@ -14,3 +14,6 @@ plan/
# model weights are never committed (SAM 3: docs/ai-masks.md)
*.safetensors
*.safetensors.part
# Python tools import their public operator family.
__pycache__/
Generated
+70 -5
View File
@@ -1181,6 +1181,14 @@ dependencies = [
"libc",
]
[[package]]
name = "craft-crw"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=f3b62ec61f45534392376492fc5ad33047375205#f3b62ec61f45534392376492fc5ad33047375205"
dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-docpath"
version = "0.1.0"
@@ -1680,6 +1688,19 @@ dependencies = [
"winit",
]
[[package]]
name = "egui_extras"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a"
dependencies = [
"ahash",
"egui",
"enum-map",
"itertools 0.15.0",
"log",
"profiling",
]
[[package]]
name = "egui_glow"
version = "0.37.0"
@@ -1766,6 +1787,26 @@ dependencies = [
"syn 2.0.119",
]
[[package]]
name = "enum-map"
version = "3.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d4532960034c15ba2f55e9eee631040ecc473c32e6c4b200828c759840f13a06"
dependencies = [
"enum-map-derive",
]
[[package]]
name = "enum-map-derive"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7127272f64b3e098f7d81f350d672081b879bff896d219c42370dc858b1af9ff"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.6",
]
[[package]]
name = "enumflags2"
version = "0.7.12"
@@ -3724,6 +3765,7 @@ dependencies = [
"serde",
"serde_json",
"thiserror 2.0.21",
"unicode-normalization",
"unicode-segmentation",
"web-time",
]
@@ -3754,6 +3796,13 @@ dependencies = [
"webpki-roots",
]
[[package]]
name = "lightcraft-film"
version = "0.18.0"
dependencies = [
"libm",
]
[[package]]
name = "lightcraft-geocode"
version = "0.18.0"
@@ -3902,6 +3951,8 @@ dependencies = [
name = "lightcraft-raw"
version = "0.18.0"
dependencies = [
"chrono",
"craft-crw",
"dhat",
"jpeg-encoder",
"jxl-oxide",
@@ -3981,6 +4032,7 @@ dependencies = [
"craft-update",
"craft-window",
"egui",
"egui_extras",
"egui_kittest",
"lightcraft-catalog",
"lightcraft-codecs",
@@ -3998,6 +4050,7 @@ dependencies = [
"lightcraft-slideshow",
"lightcraft-testkit",
"log",
"pollster 1.0.1",
"serde",
"serde_json",
"toml",
@@ -4013,9 +4066,11 @@ dependencies = [
"egui",
"js-sys",
"lightcraft-codecs",
"lightcraft-color",
"lightcraft-engine",
"lightcraft-preview",
"lightcraft-raster",
"lightcraft-raw",
"lightcraft-ui-egui",
"log",
"serde",
@@ -6598,6 +6653,12 @@ dependencies = [
"zerovec",
]
[[package]]
name = "tinyvec"
version = "1.13.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee"
[[package]]
name = "tokio"
version = "1.53.1"
@@ -6804,6 +6865,15 @@ version = "1.0.26"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954"
[[package]]
name = "unicode-normalization"
version = "0.1.26"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d"
dependencies = [
"tinyvec",
]
[[package]]
name = "unicode-properties"
version = "0.1.4"
@@ -8211,11 +8281,6 @@ name = "egui_demo_lib"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a"
[[patch.unused]]
name = "egui_extras"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a"
[[patch.unused]]
name = "egui_inspection"
version = "0.37.0"
+4
View File
@@ -12,6 +12,8 @@ repository = "https://github.com/storytold/lightcraft"
[workspace.dependencies]
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["serde"] }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" }
# Canon CRW decoder shared with the other Craft apps
craft-crw = { git = "https://github.com/storytold/craft-libs", rev = "f3b62ec61f45534392376492fc5ad33047375205" }
# craft-update: app-specific pretend versions apply to startup and manual checks.
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["egui"] }
craft-window = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["egui"] }
@@ -28,6 +30,7 @@ lightcraft-raw = { path = "crates/raw" }
lightcraft-codecs = { path = "crates/codecs" }
lightcraft-meta = { path = "crates/meta" }
lightcraft-develop = { path = "crates/develop" }
lightcraft-film = { path = "crates/film" }
lightcraft-lensdb = { path = "crates/lensdb" }
lightcraft-inpaint = { path = "crates/inpaint" }
lightcraft-scenes = { path = "crates/scenes" }
@@ -60,6 +63,7 @@ proptest = "1"
bytemuck = { version = "1", features = ["derive"] }
crc32fast = "1"
siphasher = "1"
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
+1 -1
View File
@@ -349,7 +349,7 @@ LightCraft is young and moving fast: **alpha**. **Where we honestly stand** (det
casual use.** It's great for JPEG/DNG and most Sony / Panasonic /
Fujifilm / Nikon / older-Canon raws on one machine; see [docs/raw-parity.md](docs/raw-parity.md) for your camera.
- **The biggest gaps:**
- **camera colour calibration:** Sony, Nikon, Panasonic, Fujifilm and Canon CR3 raws have guarded estimates from their camera JPEGs, with built-in ILCA-99M2, ILCE-7CR, ILCE-7M4, ILCE-7RM5, X-H2S, X-T4, Nikon Z 6II, Z 8 and D5300 profiles; measured calibration is missing, and other raws or rejected fits retain a neutral matrix;
- **camera colour calibration:** Sony, Nikon, Panasonic, Fujifilm and Canon CR3 and CRW raws have guarded estimates from their camera JPEGs, with built-in Canon EOS D60, ILCA-99M2, ILCE-7CR, ILCE-7M4, ILCE-7RM5, X-H2S, X-T4, Nikon Z 6II, Z 8 and D5300 profiles; measured calibration covers one model so far (chart-measured matrices for the Canon EOS D60), and other raws or rejected fits retain a neutral matrix;
- **compressed Olympus raws and unsupported CR3 variants:** these use embedded JPEG previews when present. Fujifilm lossless/lossy compressed RAF now decodes sensor data; [verification and existing-library reload instructions](docs/raf-compression.md);
- **AI quality and model setup:** Subject and Sky selection are classical heuristics; Object/Describe use an
optional SAM 3 model. AI Denoise supports Bayer RAW with separately installed weights, while X-Trans and
+9 -2
View File
@@ -2,7 +2,7 @@
**Stage: alpha** · next: beta, ~14 points and ~340–600 h away
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-24 · **Change:** minor (gap 9: CI runs the tests on Linux x64 since #2667; macOS, Windows and the GPU equivalence tests still don't; the lens profile database priority links its tracking issue #329; Print: Japanese photo and postcard paper sizes — L判, 2L判, KG判, はがき, 往復はがき, 六切, 四切, 名刺; Minolta MRW decoded, 6 bodies verified; RAW: 83% of Adobe's models decode, 38% verified after the camera-coverage sweep #1327; German catalog 91% → 97%: interface strings and What's New lines translated) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-24 · **Change:** minor (Canon CRW decoded clean-room, 6 bodies verified, 557 models verified; gap 9: CI runs the tests on Linux x64 since #2667; macOS, Windows and the GPU equivalence tests still don't; the lens profile database priority links its tracking issue #329; Print: Japanese photo and postcard paper sizes — L判, 2L判, KG判, はがき, 往復はがき, 六切, 四切, 名刺; Minolta MRW decoded, 6 bodies verified; RAW: 85% of Adobe's models decode, 39% verified after the camera-coverage sweep #1327; German catalog 91% → 97%: interface strings and What's New lines translated) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6
One-page summary of how close LightCraft is to Adobe Lightroom. Agents: read this, then pick work
from [docs/gaps.md](docs/gaps.md). The full assessment, method and evidence are in
@@ -45,7 +45,7 @@ Hours are calibrated on this repo's PR history; see
| Dimension | Ready | Breadth | Remaining | Doc |
|---|---:|---:|---:|---|
| Features | ~61% | ~77% (checklist 81.1%) | 600–1,100 h | [target-app-parity](docs/target-app-parity.md#features) |
| ↳ RAW cameras, colour, lens profiles | ~60% | 83% of 1,446 Adobe models decode, 38% verified | 255–480 h | [raw-parity](docs/raw-parity.md) |
| ↳ RAW cameras, colour, lens profiles | ~60% | 85% of 1,446 Adobe models decode, 39% verified | 255–480 h | [raw-parity](docs/raw-parity.md) |
| UI/UX fidelity | ~70% | ~85% | 32–54 h | [ui-parity](docs/ui-parity.md) |
| File formats (non-raw) | ~70% | ~85% | 30–55 h | [file-format-parity](docs/file-format-parity.md) |
| Hardware | ~40% | ~50% | 40–80 h | [hardware-parity](docs/hardware-parity.md) |
@@ -119,6 +119,12 @@ Ranked toward beta; detail in [docs/roadmap.md](docs/roadmap.md), gaps in [docs/
六切 (203 × 254), 四切 (254 × 305) and 名刺 (55 × 91) — at their exact metric sizes. The Print dialog
and `print.set` take their customary names, and names are matched case-, space- and
punctuation-insensitively (`L判`, `l`, `L-size` are one paper).
- 2026-10-13: Canon CRW (the 2000–2004 CIFF bodies) decodes from sensor data: compression
derived clean-room against a black-box reference and frozen (`craft-libs crates/crw/clean-room/02-crw-format.md`);
EOS D30/D60/10D/300D and PowerShot G1/G6 verified pixel-exact on 28 of 29 corpus files (18 of
them the maintainer's D60 shots); as-shot white balance, black level, rotation and capture time
from the CIFF records; the PowerShot G5's anomalous coding stays preview-only. With the
camera-coverage sweep and MRW merged, 557 models verified; Canon bucket 95% → 98%.
- 2026-10-14: Camera-coverage sweep verifies 30 more models on 40 CC0 files, with file and sensor
hashes pinned (`docs/raw/coverage.py`: 515 → 545 verified). Eleven candidates excluded after rechecking
identity, provenance and camera-image agreement. Phone and drone DNG tone differences remain tracked in #1277.
@@ -194,6 +200,7 @@ Ranked toward beta; detail in [docs/roadmap.md](docs/roadmap.md), gaps in [docs/
| 2026-10-24 | patch | Alpha rationale: tests run in CI on Linux x64 (#2667) and FreeBSD nightly, not on macOS or Windows; ranked item 8 now reads "Tests in CI on macOS and Windows, and the GPU tests in CI"; percentages and hours unchanged |
| 2026-10-22 | minor | Print: Japanese photo and postcard paper sizes (L判, 2L判, KG判, はがき, 往復はがき, 六切, 四切, 名刺) in the page setup, Print dialog and PDF output; headline numbers unchanged |
| 2026-10-19 | minor | Indonesian interface (`id`): every plain and formats message, plus 69 command labels, locale, menu command and tests; What's New left in English; Localization ~55% → ~64% (mean of the 12 key languages), 8 of 12 present |
| 2026-10-13 | minor | Canon CRW decoded (clean-room): 6 bodies verified pixel-exact, G5 preview; 551 models verified after merging the coverage sweep |
| 2026-10-12 | minor | Italian interface (`it`, #1192): 2,201 of 2,398 messages, locale, menu command and tests; headline numbers unchanged |
| 2026-10-13 | minor | Sony ILCA-99M2 camera colour profile in the log; numbers unchanged |
| 2026-10-14 | minor | Localization ~52% → ~55% (mean of the 12 key languages): de, es, fr, ja and uk catalogs filled |
+94 -23
View File
@@ -106,7 +106,7 @@ USAGE:
lightcraft-cli controls [--json] list every develop control id with its range
lightcraft-cli calibrate [--max N] [--out DIR] FOLDERS/FILES…
Fit a colour profile per camera model from raw files and their embedded camera JPEGs
(Sony ARW, Nikon NEF, Fujifilm RAF): up to N files spread over the folders (default 300; 0 = all), pooled per
(Sony ARW, Nikon NEF, Fujifilm RAF, Canon CRW): up to N files spread over the folders (default 300; 0 = all), pooled per
model, written as <model>.json to DIR (default: the profiles folder LightCraft reads,
<config>/camera-profiles, or $LIGHTCRAFT_CAMERA_PROFILES). Raws of a profiled model then
take their colour from the profile and only their tone from their own JPEG.
@@ -196,26 +196,35 @@ fn main() -> ExitCode {
}
/// Raw files below `path` (or `path` itself), skipping hidden and NAS metadata folders.
fn raw_files(path: &Path, out: &mut Vec<std::path::PathBuf>, depth: usize) {
let is_raw =
|p: &Path| p.extension().and_then(|e| e.to_str()).is_some_and(|e| ["arw", "nef", "nrw", "raf"].iter().any(|x| e.eq_ignore_ascii_case(x)));
///
/// Folders go through the engine's bounded walk ([`lightcraft_engine::walk::files_in`]): it enters
/// a folder reached through a link once at most and stops at a depth and an entry budget. A
/// folder of links pointing back at their parents made the old recursive walk re-read the same
/// folders exponentially often before its depth limit cut it off (CWE-400).
fn raw_files(path: &Path, out: &mut Vec<std::path::PathBuf>) {
let is_raw = |p: &Path| {
p.extension().and_then(|e| e.to_str()).is_some_and(|e| ["arw", "nef", "nrw", "raf", "crw"].iter().any(|x| e.eq_ignore_ascii_case(x)))
};
if path.is_file() {
if is_raw(path) {
out.push(path.to_path_buf());
}
return;
}
let Ok(entries) = std::fs::read_dir(path) else { return };
if depth > 32 {
return;
}
for entry in entries.flatten() {
let name = entry.file_name();
if name.to_string_lossy().starts_with(['.', '@']) {
continue;
}
raw_files(&entry.path(), out, depth + 1);
// (hidden entries are left out by the walk; `@eaDir` and other NAS metadata folders and files
// here, folders before they are listed so their entries do not use up the walk's budget)
let nas_metadata = |p: &Path| p.file_name().is_some_and(|n| n.to_string_lossy().starts_with('@'));
let walked = lightcraft_engine::walk::files_in_entering(
path,
None,
lightcraft_engine::walk::Limits::default(),
|p| is_raw(p) && !nas_metadata(p) && p.is_file(),
|p| !nas_metadata(p),
);
if walked.truncated {
eprintln!("calibrate: {} has more folders or entries than a walk looks at; the rest is left out", path.display());
}
out.extend(walked.files);
}
fn calibrate(args: &[String]) -> Result<(), String> {
@@ -237,7 +246,7 @@ fn calibrate(args: &[String]) -> Result<(), String> {
}
let mut files = Vec::new();
for input in &inputs {
raw_files(Path::new(input), &mut files, 0);
raw_files(Path::new(input), &mut files);
}
files.sort();
files.dedup();
@@ -425,7 +434,7 @@ fn merge(args: &[String]) -> Result<(), String> {
}
i += 1;
}
let mut s = Session::new().with_fs().with_default_denoise_models().with_system_clock();
let mut s = file_session();
let paths = expand_paths(&files);
let r = s.execute("library.import", &json!({"paths": paths})).map_err(|e| e.to_string())?;
let mut ids: Vec<u64> = r["imported"].as_array().map(|a| a.iter().filter_map(Value::as_u64).collect()).unwrap_or_default();
@@ -703,6 +712,12 @@ fn read_settings(p: &str) -> Result<SettingsFile, String> {
}
}
/// The session `render` and `merge` develop files in: with the lens database the desktop app downloaded, when it is
/// there (never fetched from here: scripts and tests stay offline).
fn file_session() -> Session {
Session::new().with_fs().with_default_denoise_models().with_system_clock().with_default_lens_database()
}
fn render(args: &[String]) -> Result<(), String> {
let mut input = None;
let mut output = None;
@@ -741,7 +756,7 @@ fn render(args: &[String]) -> Result<(), String> {
}
let input = input.ok_or("render: missing input file")?;
let output = output.ok_or("render: missing -o OUTPUT")?;
let mut s = Session::new().with_fs().with_default_denoise_models().with_system_clock();
let mut s = file_session();
let abs = expand_paths(std::slice::from_ref(&input));
let r = s.execute("library.import", &json!({"paths": abs})).map_err(|e| e.to_string())?;
let id = r["imported"][0].as_u64().ok_or_else(|| format!("{input}: not a readable photo"))?;
@@ -836,15 +851,30 @@ fn snapshot(args: &[String]) -> Result<(), String> {
let t0 = Instant::now();
let mut session = match &library {
Some(dir) => {
let mut s =
Session::new().with_fs().with_default_denoise_models().with_system_clock().with_default_face_models().with_default_slide_templates();
let mut s = Session::new()
.with_fs()
.with_default_denoise_models()
.with_system_clock()
.with_default_face_models()
.with_default_lens_database()
.with_default_slide_templates();
s.open_library(dir, false).map_err(|e| library_error(dir, e))?;
s
}
None if files.is_empty() => {
Session::with_demo().with_fs().with_default_denoise_models().with_system_clock().with_default_face_models().with_default_slide_templates()
}
None => Session::new().with_fs().with_default_denoise_models().with_system_clock().with_default_face_models().with_default_slide_templates(),
None if files.is_empty() => Session::with_demo()
.with_fs()
.with_default_denoise_models()
.with_system_clock()
.with_default_face_models()
.with_default_lens_database()
.with_default_slide_templates(),
None => Session::new()
.with_fs()
.with_default_denoise_models()
.with_system_clock()
.with_default_face_models()
.with_default_lens_database()
.with_default_slide_templates(),
};
// Apply compute policy before imports or the first scripted query can discover an adapter.
session.execute("app.gpu", &json!({"enabled": false})).map_err(|e| e.to_string())?;
@@ -1069,6 +1099,47 @@ fn denoise_serve(_: &[String]) -> Result<(), String> {
Err("denoise-serve: this build has no denoise support (build with the `denoise` feature)".into())
}
#[cfg(all(test, unix))]
mod raw_files_tests {
use super::raw_files;
/// Links back to their own folders are entered once, not once per path that reaches them: a
/// handful of such links made the old walk list the same folders exponentially often.
#[test]
fn folder_links_back_up_are_walked_once() {
let dir = std::env::temp_dir().join(format!("lightcraft-cli-raw-files-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let a = dir.join("a");
std::fs::create_dir_all(a.join("@eaDir")).unwrap();
std::fs::write(a.join("one.NEF"), b"").unwrap();
std::fs::write(a.join("@eaDir").join("thumb.nef"), b"").unwrap();
std::fs::write(a.join("notes.txt"), b"").unwrap();
for i in 0..8 {
std::os::unix::fs::symlink(&dir, a.join(format!("up{i}"))).unwrap();
}
// a named pipe with a raw extension: not a file, so never opened (a read would block)
assert!(std::process::Command::new("mkfifo").arg(a.join("pipe.nef")).status().unwrap().success());
let started = std::time::Instant::now();
let mut files = Vec::new();
raw_files(&dir, &mut files);
assert!(started.elapsed() < std::time::Duration::from_secs(10), "walk took {:?}", started.elapsed());
assert_eq!(files, vec![a.join("one.NEF")]);
let _ = std::fs::remove_dir_all(&dir);
}
}
#[cfg(test)]
mod tests {
/// `render` and `merge` read the lens database the desktop app downloaded, as the desktop does (the same raw
/// gets the same profile everywhere), but never fetch it.
#[test]
fn render_reads_the_downloaded_lens_database() {
let s = super::file_session();
assert_eq!(lightcraft_engine::lens_profiles::host_dir(), lightcraft_engine::lensfun_download::default_dir());
assert!(!s.lens_auto_download, "selecting it is not permission to download it");
}
}
#[cfg(test)]
mod import_target_tests {
use super::{import_and_select, import_targets, json};
+2
View File
@@ -80,3 +80,5 @@ heif = ["lightcraft-codecs/heif"]
[dev-dependencies]
egui = { workspace = true }
lightcraft-color = { workspace = true }
lightcraft-raw = { workspace = true }
+36
View File
@@ -233,6 +233,25 @@ pub fn parse_central(cd: &[u8]) -> Result<Vec<ZipEntry>, String> {
Ok(out)
}
/// What a restore writes, each storage key once, checked against the whole directory before any
/// payload is read: a backup names a file once, so a directory naming the same destination again
/// is damaged or altered, and its entries' bytes can't add up to more than the file holds (a
/// directory can point many entries at one stored range and have each read, checked and written).
pub fn restore_plan<'a>(entries: &'a [ZipEntry], dir: &str, file_len: u64) -> Result<Vec<(String, &'a ZipEntry)>, String> {
let mut seen = std::collections::HashSet::new();
let mut plan = Vec::new();
let mut bytes = 0u64;
for e in entries {
let Some(key) = restore_key(&e.name, dir) else { continue };
if !seen.insert(key.clone()) {
return Err(format!("{}: listed twice (damaged or altered backup)", e.name));
}
bytes = bytes.checked_add(e.size).filter(|&b| b <= file_len).ok_or_else(|| format!("{}: entries larger than the backup itself", e.name))?;
plan.push((key, e));
}
Ok(plan)
}
/// Offset of an entry's data from its local header's first 30 bytes.
pub fn data_offset(entry: &ZipEntry, local: &[u8]) -> Result<u64, String> {
if rd32(local, 0) != Some(LOCAL_SIG) {
@@ -342,6 +361,23 @@ mod tests {
assert!(!valid_library_dir("library-../x") && !valid_library_dir("originals") && !valid_library_dir("library-"));
}
#[test]
fn restore_plan_refuses_repeated_and_oversized_entries() {
let entry = |name: &str, size: u64| ZipEntry { name: name.into(), crc: 0, size, header: 0, method: 0 };
let ok = [entry("README.txt", 10), entry("library/catalog.log", 10), entry("originals/abc123/a.jpg", 100)];
let plan = restore_plan(&ok, "d", 200).unwrap();
assert_eq!(plan.iter().map(|(k, _)| k.as_str()).collect::<Vec<_>>(), ["d/catalog.log", "originals/abc123"]);
// one stored range named 3 times would be read, checked and written 3 times
let twice = [entry("originals/abc123/a.jpg", 100), entry("originals/abc123/b.jpg", 100)];
assert!(restore_plan(&twice, "d", 1000).unwrap_err().contains("twice"));
let twice = [entry("library/catalog.log", 10), entry("library/catalog.log", 10)];
assert!(restore_plan(&twice, "d", 1000).is_err());
// entries claiming more bytes than the file has
let big = [entry("library/catalog.log", 150), entry("originals/abc123/a.jpg", 100)];
assert!(restore_plan(&big, "d", 200).is_err());
assert!(restore_plan(&[entry("library/catalog.log", u64::MAX), entry("library/presets.json", 1)], "d", u64::MAX).is_err());
}
#[test]
fn size_limits_are_errors_not_panics() {
let mut w = ZipWriter { offset: MAX_BYTES - 10, ..Default::default() };
+3
View File
@@ -2,6 +2,9 @@
//! control exactly like a slider drag (begin interaction → N `develop.set` → end) and time each
//! step from the command to the moment the new loupe texture is ready. Results go to the log
//! (the browser console on the web) as one `lightcraft-bench {…json…}` line.
//!
//! The web host runs it only on the generated demo photos in an unsaved library (`?bench` implies `?store=memory`): it
//! commits edits to the photo it opens, which must never be one in the user's stored library.
use lightcraft_ui_egui::LightcraftApp;
use lightcraft_ui_egui::render::Slot;
+2 -1
View File
@@ -11,7 +11,8 @@
//! - export downloads the file through the browser.
//!
//! `?bench` in the URL runs a scripted first-paint / slider-latency measurement and logs it to the
//! console (see [`bench`]); `?store=idb` forces the IndexedDB backend, `?store=memory` disables
//! console (see [`bench`]) on the generated demo photos in an unsaved library (it implies `?store=memory`, so it never edits
//! the library in browser storage); `?store=idb` forces the IndexedDB backend, `?store=memory` disables
//! persistence and `?workers=0` renders on the main thread.
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
+2 -3
View File
@@ -13,7 +13,7 @@ use wasm_bindgen_futures::JsFuture;
use crate::backend::Backend;
use crate::backup::{
ACTIVE_LIBRARY, README, ZipWriter, data_offset, find_central, original_entry, parse_central, restore_key, restored_dir_name, tail_len,
ACTIVE_LIBRARY, README, ZipWriter, data_offset, find_central, original_entry, parse_central, restore_plan, restored_dir_name, tail_len,
valid_hash, verify, verify_original,
};
use crate::files::{Files, LIBRARY_FILES};
@@ -214,8 +214,7 @@ pub async fn restore(file: web_sys::File, backend: Backend) -> Result<String, St
}
let dir = restored_dir_name(js_sys::Date::now());
let mut written = 0usize;
for e in &entries {
let Some(key) = restore_key(&e.name, &dir) else { continue };
for (key, e) in restore_plan(&entries, &dir, len)? {
// originals are named by their content: one already stored is the same file
if key.starts_with("originals/") && backend.exists(&key).await? {
continue;
+63 -3
View File
@@ -12,7 +12,7 @@
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use lightcraft_engine::files::{load_bytes, probe_bytes};
use lightcraft_engine::files::{load_bytes_with, probe_bytes};
use lightcraft_engine::media::{FileLoader, FileProbe};
/// Prefix of the catalog paths of files kept in browser storage.
@@ -144,9 +144,11 @@ impl Originals {
/// Engine hooks that decode/probe from memory.
pub fn hooks(&self) -> (FileLoader, FileProbe) {
let s = self.clone();
let loader: FileLoader = Arc::new(move |path: &str, max_edge: usize| {
// (an imported camera profile is not applied on the web, as in the render worker: a raw keeps its own colour,
// whether it decodes in a worker or inline when workers are unavailable)
let loader: FileLoader = Arc::new(move |path: &str, max_edge: usize, _dcp: Option<&lightcraft_engine::media::DcpProfile>| {
let bytes = s.get(path).ok_or_else(|| format!("{path}: the original is still loading from browser storage"))?;
load_bytes(&bytes, max_edge)
load_bytes_with(&bytes, max_edge, None)
});
let s = self.clone();
let probe: FileProbe = Arc::new(move |path: &str| {
@@ -237,6 +239,64 @@ mod tests {
assert_eq!(out.image.width, 20);
}
/// CodeRabbit on #1063: without web workers a render runs inline and handed the selected camera profile to this
/// loader, which applied it, so the picture differed from the worker's (which keeps the raw's own colour, the
/// documented web behaviour). The loader now ignores it.
#[test]
fn the_web_loader_keeps_a_raws_own_colour_with_a_camera_profile() {
use lightcraft_raw::*;
let (w, h) = (32usize, 24usize);
let raw = RawImage {
format: RawFormat::Dng,
width: w,
height: h,
cpp: 1,
data: RawData::U16((0..w * h).map(|i| 256 + ((i % w) * 300 + (i / w) * 200) as u16).collect()),
cfa: Cfa::bayer("RGGB"),
bits: 14,
black: BlackLevel::uniform(256.0),
white: vec![16000.0],
active_area: Rect::new(0, 0, w, h),
crop: Rect::new(0, 0, w, h),
orientation: Orientation::Normal,
color: ColorData {
illuminant: [21, 0],
color_matrix: [Some(lightcraft_color::Mat3([[0.9, 0.2, -0.15], [-0.3, 1.25, 0.08], [0.02, -0.12, 0.85]])), None],
as_shot_neutral: Some([0.5, 1.0, 0.7]),
..Default::default()
},
wb_multipliers: None,
linearized: false,
pixel_aspect: 1.0,
opcodes: OpcodeLists::default(),
metadata: Default::default(),
lens_metadata: Default::default(),
};
let dng = write_dng(&raw, &DngWriteOptions::default()).unwrap();
// our own numbers: a matrix that swaps the camera's red and blue
let swap = lightcraft_color::Mat3([[0.0, 0.0, 1.0], [0.0, 1.0, 0.0], [1.0, 0.0, 0.0]]).mul(&lightcraft_color::Mat3([
[3.2406, -1.5372, -0.4986],
[-0.9689, 1.8758, 0.0415],
[0.0557, -0.2040, 1.0570],
]));
let profile = dcp::DcpProfile {
name: "Swap".into(),
camera_model: "LightCraft Test Camera".into(),
color: ColorData { illuminant: [21, 0], color_matrix: [Some(swap), None], ..Default::default() },
};
assert_ne!(
load_bytes_with(&dng, 64, Some(&profile)).unwrap().0.data,
load_bytes_with(&dng, 64, None).unwrap().0.data,
"the profile changes a raw's colour where it is applied"
);
let store = Originals::default();
store.insert("h1", Arc::from(dng));
let (loader, _) = store.hooks();
let with = loader("web/h1/a.dng", 64, Some(&profile)).unwrap();
let without = loader("web/h1/a.dng", 64, None).unwrap();
assert_eq!(with.0.data, without.0.data, "the web loader leaves it out");
}
#[test]
fn download_names() {
assert_eq!(download_name("dir/x-lightcraft.png"), "x-lightcraft.png");
+10 -3
View File
@@ -90,10 +90,13 @@ impl Options {
})
.collect();
let get = |k: &str| params.iter().find(|(n, _)| n == k).map(|(_, v)| v.clone());
let bench = get("bench").is_some();
Options {
bench: get("bench").is_some(),
store: get("store").filter(|s| s == "idb" || s == "memory").unwrap_or_else(|| "opfs".into()),
workers: get("workers").and_then(|v| v.parse().ok()),
bench,
// the benchmark edits the first photo it finds: a link with `?bench` must never reach
// the library in browser storage, so it always runs on the demo photos in an unsaved library
store: if bench { "memory".into() } else { get("store").filter(|s| s == "idb" || s == "memory").unwrap_or_else(|| "opfs".into()) },
workers: get("workers").and_then(|v| v.parse().ok()).map(|n: usize| n.min(crate::workers::MAX_WORKERS)),
reset: get("reset").is_some(),
}
}
@@ -496,6 +499,10 @@ impl WebApp {
});
}
}
// `?bench` never has storage (see `Options::from_url`): it measures the generated demo photos
if opts.bench && backend.is_none() && session.catalog.len() == 0 {
lightcraft_engine::demo::load(&mut session);
}
if backend.is_some() {
notice(
"LightCraft in the browser is experimental. Your library is kept in this browser's storage: keep your original photos \
+21 -1
View File
@@ -207,6 +207,15 @@ impl Inner {
}
}
/// The most workers started, whatever `?workers=` asks: more than this brings nothing to a
/// render queue and a link can't make the page spawn workers (and their copies of the module)
/// without end.
pub const MAX_WORKERS: usize = 16;
/// Worker constructions failing in a row after which the rest are not tried: a browser that
/// refused this many refuses the next ones too.
const MAX_FAILED_STARTS: usize = 3;
/// The main thread's handle on the render workers.
#[derive(Clone)]
pub struct Workers(Rc<RefCell<Inner>>);
@@ -244,7 +253,12 @@ impl Workers {
return w;
}
let mut slots = WorkerSlots::default();
for attempt in 0..n {
let mut failed = 0;
for attempt in 0..n.min(MAX_WORKERS) {
if failed >= MAX_FAILED_STARTS {
log::warn!("render workers: {failed} failed to start in a row; not trying the rest");
break;
}
// The callbacks name their worker by its place in `workers`; a failed attempt takes none.
let i = slots.peek();
let opts = web_sys::WorkerOptions::new();
@@ -254,6 +268,7 @@ impl Workers {
Ok(x) => x,
Err(e) => {
log::warn!("render worker {attempt}: {e:?}");
failed += 1;
continue;
}
};
@@ -274,10 +289,12 @@ impl Workers {
worker.set_onmessage(None);
worker.set_onerror(None);
worker.terminate();
failed += 1;
continue;
}
w.0.borrow_mut().workers.push(W { worker, ready: false, dead: false, busy: None });
slots.commit();
failed = 0;
}
w
}
@@ -301,6 +318,7 @@ impl Workers {
loaded: None,
quick: None,
display: None,
frame: None,
};
g.done.push((b.slot, r, 0.0));
}
@@ -392,6 +410,7 @@ impl Workers {
loaded: None,
quick: None,
display: None,
frame: None,
},
ms,
));
@@ -446,6 +465,7 @@ impl RenderOffload for Workers {
loaded: None,
quick: None,
display: None,
frame: None,
};
g.done.push((slot, r, 0.0));
return None;
+13 -1
View File
@@ -167,7 +167,19 @@ pub fn rotate(dir: &Path) -> std::io::Result<(PathBuf, File)> {
/// One formatted log line: `<timestamp> <LEVEL> [<thread>] <target>: <message>\n`.
pub fn format_line(ts: &str, level: log::Level, thread: &str, target: &str, message: &str) -> String {
let message = message.strip_suffix('\n').unwrap_or(message);
format!("{ts} {level:<5} [{thread}] {target}: {message}\n")
// A message can carry text from files and peers (a file name, a rejected value): it must not be able to start a
// record of its own. Later lines of a multi-line message (a panic report) are indented, so none begins like a
// record; other control characters (a bare CR, an escape sequence) are shown escaped.
let mut safe = String::with_capacity(message.len());
for c in message.chars() {
match c {
'\n' => safe.push_str("\n "),
'\t' => safe.push(c),
c if c.is_control() => safe.extend(c.escape_default()),
c => safe.push(c),
}
}
format!("{ts} {level:<5} [{thread}] {target}: {safe}\n")
}
/// Where formatted lines go besides standard error: kept in memory until a file is attached,
+6 -2
View File
@@ -167,7 +167,11 @@ fn a_line_carries_time_level_thread_target_and_message() {
"2026-10-08T07:59:17.728Z INFO [main] lightcraft: library /photos: 12 photos\n"
);
// A multi-line message keeps its lines; the record still ends in one newline.
assert!(format_line("t", log::Level::Error, "w", "x", "a\nb\n").ends_with("x: a\nb\n"));
// later lines are indented and control characters escaped, so a message cannot forge a record
assert!(format_line("t", log::Level::Error, "w", "x", "a\nb\n").ends_with("x: a\n b\n"));
let forged = format_line("t", log::Level::Info, "w", "x", "name\r\n2026-01-01T00:00:00Z ERROR [main] x: fake\u{1b}[2J");
assert!(forged.lines().skip(1).all(|l| l.starts_with(' ')), "{forged:?}");
assert!(!forged.contains('\r') && !forged.contains('\u{1b}'), "{forged:?}");
}
#[test]
@@ -357,7 +361,7 @@ fn a_panic_report_goes_to_the_file_and_never_deadlocks() {
logger.record_panic("main", "while the sink is held");
}
let text = read(&path);
assert!(text.contains(" ERROR [render] lightcraft: panicked at crates/x/src/lib.rs:3:5:\nboom\n"), "{text}");
assert!(text.contains(" ERROR [render] lightcraft: panicked at crates/x/src/lib.rs:3:5:\n boom\n"), "{text}");
assert!(!text.contains("while the sink is held"), "{text}");
let _ = std::fs::remove_dir_all(&dir);
}
+76 -2
View File
@@ -79,7 +79,67 @@ fn app_icon() -> egui::IconData {
eframe::icon_data::from_png_bytes(png).unwrap_or_default()
}
struct App(LightcraftApp, PrefsWriter, #[cfg(target_os = "macos")] Option<native_menu::NativeMenu>);
struct App(LightcraftApp, PrefsWriter, Option<WindowTextures>, #[cfg(target_os = "macos")] Option<native_menu::NativeMenu>);
/// Draws renders that stayed on the GPU: registers their textures with the window's egui-wgpu
/// renderer (the GPU renderer runs on the window's device, see [`adopt_window_device`]).
struct WindowTextures {
device: eframe::wgpu::Device,
queue: eframe::wgpu::Queue,
renderer: std::sync::Arc<egui::mutex::RwLock<eframe::egui_wgpu::Renderer>>,
}
impl lightcraft_ui_egui::render::ScreenTextures for WindowTextures {
fn show(&mut self, frame: &lightcraft_engine::media::ScreenFrame, id: Option<egui::TextureId>) -> Option<egui::TextureId> {
let view = frame.texture.create_view(&Default::default());
let mut r = self.renderer.write();
let filter = eframe::wgpu::FilterMode::Linear;
Some(match id {
Some(id) => {
r.update_egui_texture_from_wgpu_texture(&self.device, &view, filter, id);
id
}
None => r.register_native_texture(&self.device, &view, filter),
})
}
fn free(&mut self, id: egui::TextureId) {
self.renderer.write().free_texture(&id);
}
fn read(&self, frame: &lightcraft_engine::media::ScreenFrame) -> Option<egui::ColorImage> {
match lightcraft_engine::gpu::read_texture(&self.device, &self.queue, &frame.texture, frame.width, frame.height) {
Ok(img) => Some(egui::ColorImage::from_rgba_unmultiplied([img.width, img.height], img.data.as_flattened())),
Err(e) => {
log::warn!("gpu: a view can't be read back for the screenshot: {e}");
None
}
}
}
}
/// Render on the window's device (off the UI thread: building the kernels takes a moment), so the
/// loupe's drafts are drawn straight from the GPU; the textures they leave are shown through
/// [`WindowTextures`] once that worked. Otherwise the GPU renderer makes a device of its own, as
/// before, and every render comes back as pixels.
fn adopt_window_device(rs: &eframe::egui_wgpu::RenderState, ctx: &egui::Context) -> WindowTextures {
let (device, queue, info) = (rs.device.clone(), rs.queue.clone(), rs.adapter.get_info());
let ctx = ctx.clone();
// before the first frame's GPU warm-up can start a device of its own
lightcraft_engine::gpu::set_window_device_pending(true);
let spawned = std::thread::Builder::new().name("lc-gpu-window".into()).spawn(move || {
match lightcraft_engine::gpu::adopt_window_device(device, queue, info) {
Ok(()) => log::info!("gpu: rendering on the window's device"),
Err(e) => log::info!("gpu: renders come back as pixels: {e}"),
}
ctx.request_repaint();
});
if let Err(e) = spawned {
log::warn!("gpu: {e}");
lightcraft_engine::gpu::set_window_device_pending(false);
}
WindowTextures { device: rs.device.clone(), queue: rs.queue.clone(), renderer: rs.renderer.clone() }
}
impl eframe::App for App {
fn clear_color(&self, _visuals: &egui::Visuals) -> [f32; 4] {
@@ -89,7 +149,7 @@ impl eframe::App for App {
}
fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
#[cfg(target_os = "macos")]
if let Some(m) = self.2.as_mut()
if let Some(m) = self.3.as_mut()
&& m.update(&mut self.0, ctx)
&& lightcraft_ui_egui::panels::notices::may_close(&mut self.0)
{
@@ -109,6 +169,13 @@ impl eframe::App for App {
}
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
self.0.perf.host_frame_ms = frame.info().cpu_usage.map(|s| f64::from(s) * 1000.0);
// the GPU renderer adopted the window's device: its renders can be drawn as they are
if self.2.is_some()
&& lightcraft_engine::gpu::on_window_device()
&& let Some(t) = self.2.take()
{
self.0.renderer.set_screen_textures(Box::new(t));
}
self.0.ui(ui);
}
fn on_exit(&mut self, _gl: Option<&eframe::glow::Context>) {
@@ -358,9 +425,16 @@ fn main() -> eframe::Result {
#[cfg(target_os = "macos")]
let menu =
(std::env::var_os("LIGHTCRAFT_NO_NATIVE_MENU").is_none()).then(|| native_menu::NativeMenu::install(&mut app, &cc.egui_ctx));
// the GPU renderer on the window's device, when GPU rendering is on
// (LIGHTCRAFT_GPU_WINDOW=0: a device of its own, renders read back - for comparison or a driver
// that misbehaves with compute and drawing on one device)
let window_device = std::env::var_os("LIGHTCRAFT_GPU_WINDOW").is_none_or(|v| v != "0");
let window_textures =
cc.wgpu_render_state.as_ref().filter(|_| gpu_on && window_device).map(|rs| adopt_window_device(rs, &cc.egui_ctx));
Ok(Box::new(App(
app,
writer,
window_textures,
#[cfg(target_os = "macos")]
menu,
)))
+4
View File
@@ -255,6 +255,10 @@ pub(crate) fn open_session(in_memory: bool, launch: &Launch, seed_demo: bool) ->
Launch::Ask => (Session::new().with_fs().with_default_denoise_models().with_system_clock(), None),
Launch::Open { dir, remembered, .. } => open_library_session(in_memory, dir.clone(), *remembered, seed_demo),
};
// lens profiles from the app's own lensfun copy, offered on the first launch (not for a throwaway session)
if !in_memory {
s = s.with_default_lens_database().with_lens_auto_download();
}
s.face_models_dir = lightcraft_engine::config::default_face_models_dir();
s.slide_templates_dir = lightcraft_engine::config::config_dir().map(|d| d.join(lightcraft_engine::slide_template::DIR_NAME));
// Control requests are answered on the UI thread: Add to Apple Photos must not wait there
+3
View File
@@ -5,6 +5,7 @@ fn desktop_clear_color_stays_opaque_with_a_modal_open() {
let mut app = App(
LightcraftApp::new(Session::new(), Services::default()),
PrefsWriter::default(),
None,
#[cfg(target_os = "macos")]
None,
);
@@ -566,6 +567,7 @@ fn on_exit_ends_the_process_on_macos() {
let mut app = App(
app,
PrefsWriter::default(),
None,
#[cfg(target_os = "macos")]
None,
);
@@ -598,6 +600,7 @@ fn on_exit_removes_the_lock_owner_note() {
let mut app = App(
LightcraftApp::new(session, Services::default()),
PrefsWriter::default(),
None,
#[cfg(target_os = "macos")]
None,
);
+11 -1
View File
@@ -154,6 +154,15 @@ pub fn base_options() -> WgpuConfiguration {
n.instance_descriptor.backend_options = backend::backend_options();
// no indirect-call validation pipeline: Intel Metal fails to compile it and the window never opens (#250)
n.instance_descriptor.flags = backend::instance_flags_from_env(n.instance_descriptor.flags);
// the GPU renderer may run on this device (`adopt_window_device`): it needs the adapter's
// buffer limits (a 24 MP photo is a 275 MiB buffer), not wgpu's defaults
let default = n.device_descriptor.clone();
n.device_descriptor = std::sync::Arc::new(move |adapter| {
if adapter.get_info().backend == wgpu::Backend::Gl {
return default(adapter);
}
wgpu::DeviceDescriptor { label: Some("lightcraft window"), required_limits: adapter.limits(), ..Default::default() }
});
}
c
}
@@ -192,7 +201,8 @@ fn probe(backends: Backends, compose_window: bool) -> Result<WgpuSetupExisting,
..Default::default()
}))
.map_err(|e| format!("no adapter: {e}"))?;
let base = if adapter.get_info().backend == wgpu::Backend::Gl { wgpu::Limits::downlevel_webgl2_defaults() } else { wgpu::Limits::default() };
// (not GL: the adapter's own limits, which the GPU renderer needs when it adopts this device)
let base = if adapter.get_info().backend == wgpu::Backend::Gl { wgpu::Limits::downlevel_webgl2_defaults() } else { adapter.limits() };
let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor {
label: Some("egui wgpu device"),
required_limits: wgpu::Limits { max_texture_dimension_2d: 8192, ..base },
+2
View File
@@ -19,11 +19,13 @@ covers a whole directory), or if a licence file referenced in the Licence column
| `assets/camera-profiles/ILCA-99M2.json` | Sony ILCA-99M2 camera colour profile (matrix + hue/saturation/value table), built into LightCraft | LightCraft contributors; source photographs supplied by @PiMinusMax | original work: fitted by `lightcraft-cli calibrate` to 144 usable ILCA-99M2 ARWs (of 150, seven shooting days, Standard creative style) and their in-camera JPEGs; aggregate colour statistics only, no image content; no Adobe or third-party profile data | MIT OR Apache-2.0 | 2026-10-11 | none |
| `assets/camera-profiles/ILCE-7CR.json` | Sony ILCE-7CR camera colour profile (matrix + hue/saturation/value table), built into LightCraft | LightCraft contributors; source photographs supplied by @AlexChambers | original work: fitted by `lightcraft-cli calibrate` to 125 usable ILCE-7CR ARWs (of 131, September 2025 to September 2026, Standard creative style) and their in-camera JPEGs; aggregate colour statistics only, no image content; no Adobe or third-party profile data | MIT OR Apache-2.0 | 2026-10-09 | none |
| `assets/camera-profiles/X-H2S.json`, `assets/camera-profiles/X-T4.json` | Fujifilm camera colour profiles (matrix + hue/saturation/value table), built into LightCraft | LightCraft contributors; source photographs supplied by Sebastian Pfluegelmeier | original work: fitted by `lightcraft-cli calibrate` to 201 X-H2S and 545 X-T4 RAFs and their in-camera JPEGs; aggregate colour statistics only, no image content; no Adobe or third-party profile data | MIT OR Apache-2.0 | 2026-10-08 | none |
| `assets/camera-profiles/Canon_EOS_D60.json` | Canon EOS D60 camera colour profile (matrix + hue/saturation/value table), built into LightCraft | LightCraft contributors; source photographs supplied by Robert Woldberg | original work: fitted by `lightcraft-cli calibrate` to 1,424 usable EOS D60 CRWs (of 1,520, 2005 to 2014, Auto white balance) and their in-camera JPEGs; aggregate colour statistics only, no image content; no Adobe or third-party profile data | MIT OR Apache-2.0 | 2026-10-13 | none |
| `assets/camera-profiles/NIKON_Z_6_2.json` | Nikon Z 6II camera colour profile (matrix + hue/saturation/value table), built into LightCraft | Michael Anderson (@endthestart) | original work: fitted by `lightcraft-cli calibrate` to 296 usable Z 6II NEFs of my own (of 299, 2024 to 2026, Standard and Auto picture controls; NIKKOR Z 20mm f/1.8 S, Z 24-70mm f/4 S and AF-S 70-200mm f/2.8G on the FTZ) and their in-camera JPEGs; aggregate colour statistics only, no image content; no Adobe or third-party profile data | MIT OR Apache-2.0 | 2026-10-13 | none |
| `assets/camera-profiles/NIKON_Z_8.json` | Nikon Z 8 camera colour profile (matrix + hue/saturation/value table), built into LightCraft | Michael Anderson (@endthestart) | original work: fitted by `lightcraft-cli calibrate` to 261 usable Z 8 NEFs of my own (of 278, 2023 and 2026, nearly all Standard picture control, lossless 14-bit; NIKKOR Z 24-120mm f/4 S and AF-S 70-200mm f/2.8G on the FTZ) and their in-camera JPEGs; aggregate colour statistics only, no image content; no Adobe or third-party profile data | MIT OR Apache-2.0 | 2026-10-13 | none |
| `assets/camera-profiles/NIKON_D5300.json` | Nikon D5300 camera colour profile (matrix + hue/saturation/value table), built into LightCraft | Michael Anderson (@endthestart) | original work: fitted by `lightcraft-cli calibrate` to 264 usable D5300 NEFs of my own (of 273, 2014 to 2017, mostly Standard picture control, lossy 12-bit, mostly the AF-S DX 35mm f/1.8G) and their in-camera JPEGs; aggregate colour statistics only, no image content; no Adobe or third-party profile data | MIT OR Apache-2.0 | 2026-10-13 | none |
| `assets/camera-profiles/ILCE-7RM5.json` | Sony ILCE-7RM5 camera colour profile (matrix + hue/saturation/value table), built into LightCraft | Yule (Brian) Wang (@peaperfish) | original work: fitted by `lightcraft-cli calibrate` to 220 usable ILCE-7RM5 ARWs of my own (of 241, 2025 to 2026, Standard creative style; Sigma 24-70mm F2.8 DG DN II Art and Sony FE 200-600mm F5.6-6.3 G OSS) and their in-camera JPEGs; aggregate colour statistics only, no image content; no Adobe or third-party profile data | MIT OR Apache-2.0 | 2026-10-26 | none |
| `crates/raw/src/spectral_table.rs` | Camera colour matrices (DNG ColorMatrix1/2 and ForwardMatrix1/2 for Standard Illuminant A and D65) for 52 camera models, and the model alias list | Derived by LightCraft contributors from rawtoaces-data (Academy Software Foundation): camera spectral sensitivities measured by Weta Digital (44 cameras), scitech (7) and Jonathon Irons at the National Physical Laboratory (Nikon D5100); training reflectances; CIE 1931 colour-matching functions (CIE, CC-BY-4.0, as shipped in rawtoaces-data) | https://github.com/AcademySoftwareFoundation/rawtoaces-data, tag v1.1.0, commit 5cfa53707b053594b2d0d48e8019fb56e6582d6c | Apache-2.0 (`LICENSE-APACHE`); the colour-matching functions CC-BY-4.0 | 2026-10-08 | generated by `tools/spectral_camera_table.py`: a 3×3 matrix per illuminant fitted to the spectral data (no measurement copied verbatim); aliases copied from `data/aliases.json`; no Adobe or third-party camera matrix |
| `crates/raw/src/chart_table.rs` | Chart-measured camera colour matrices (DNG ColorMatrix1/2 and ForwardMatrix1/2 for Standard Illuminant A and D50) for the Canon EOS D60 | LightCraft contributors; ColorChecker photographs taken by Robert Woldberg on the maintainer's EOS D60 | original work: fitted to our own CRWs of a ColorChecker Classic (post-November-2014 formulation) under a ~2,900 K tungsten bulb (11 frames) and direct sun (~4,850 K, 20 frames); reference colours: X-Rite's published L*a*b* (D50) for the chart, as packaged by [colour-science](https://github.com/colour-science/colour) (BSD-3-Clause), used for fitting only and not shipped; method in `clean-room/crw/10-chart-calibration.md` | MIT OR Apache-2.0 | 2026-10-25 | kept by hand: a 3×3 matrix per illuminant fitted on chromaticity with neutral held at D50; no Adobe or third-party camera matrix, no number from a GPL raw decoder |
| `assets/camera-tone/sony-dro-off.json` | Sony global tone curve with the Dynamic Range Optimizer off (32 knots), built into LightCraft for ARWs shot with DRO on | LightCraft contributors; source photographs by raw.pixls.us contributors | original work: tone curve quantile-matched over the pooled pixel pairs of 12 CC0 raw.pixls.us ARWs (DRO off, Standard creative style; ILCE-3500, -5000, -6600, -7CR, -7M3 ×3, -7S, -9M2, ILCA-77M2, SLT-A57, NEX-F3) and their embedded camera JPEGs; the file lists each source URL and SHA-256 and how the curve was derived (see also `docs/camera-preview-colour.md`); aggregate tone statistics only, no image content; no Adobe or third-party profile data | MIT OR Apache-2.0 (sources CC0) | 2026-10-09 | none |
| `crates/scenes/` (generated images) | Procedural demo photographs | LightCraft contributors | original work (generated at runtime, no source imagery) | MIT OR Apache-2.0 | 2026-09-30 | n/a |
| `crates/ui-egui/src/icons.rs` | UI icons drawn as vector paths in code | LightCraft contributors | original work | MIT OR Apache-2.0 | 2026-09-30 | n/a |
@@ -0,0 +1 @@
{"version":1,"model":"Canon EOS D60","files":1424,"samples":5140322,"matrix":[[1.13012,-0.360203,0.234919],[-0.0483286,1.21254,-0.166746],[-0.0238897,-0.834382,1.86577]],"hue_sat":{"hue_divisions":72,"sat_divisions":5,"val_divisions":5,"data":[[0.0,1.0,1.0],[8.29241,1.23189,1.0],[6.24278,1.25426,1.0],[5.85238,1.20774,1.0],[3.78008,1.10233,1.0],[0.0,1.0,1.0],[7.49695,1.19919,1.0],[4.58151,1.21364,1.0],[3.60262,1.15474,1.0],[2.74306,1.07068,1.0],[0.0,1.0,1.0],[6.97455,1.16634,1.0],[3.67004,1.18558,1.0],[1.9923,1.12524,1.0],[0.245554,0.982395,1.0],[0.0,1.0,1.0],[6.42589,1.13738,1.0],[2.66266,1.14834,1.0],[0.226251,1.09372,1.0],[-2.23194,0.930707,1.0],[0.0,1.0,1.0],[6.09352,1.1248,1.0],[1.65699,1.12876,1.0],[-1.52059,1.07635,1.0],[-3.87766,0.926268,1.0],[0.0,1.0,1.0],[6.2146,1.10729,1.0],[1.13044,1.11602,1.0],[-2.4179,1.08135,1.0],[-4.69366,0.96409,1.0],[0.0,1.0,1.0],[6.73255,1.09443,1.0],[1.15502,1.09451,1.0],[-2.95449,1.05376,1.0],[-5.86916,0.954201,1.0],[0.0,1.0,1.0],[7.0143,1.0883,1.0],[1.25698,1.07945,1.0],[-3.3853,1.03275,1.0],[-6.46471,0.9465,1.0],[0.0,1.0,1.0],[7.44031,1.08414,1.0],[1.9515,1.06401,1.0],[-3.08108,1.00026,1.0],[-6.03475,0.917114,1.0],[0.0,1.0,1.0],[8.29527,1.07925,1.0],[2.86018,1.03974,1.0],[-2.25228,0.96454,1.0],[-4.98936,0.860481,1.0],[0.0,1.0,1.0],[9.14683,1.08392,1.0],[3.8335,1.01361,1.0],[-1.06889,0.935075,1.0],[-4.04616,0.821455,1.0],[0.0,1.0,1.0],[9.19479,1.10285,1.0],[4.68727,1.00463,1.0],[0.536387,0.911486,1.0],[-2.795,0.795914,1.0],[0.0,1.0,1.0],[8.67599,1.12913,1.0],[5.14131,1.01389,1.0],[1.77075,0.910094,1.0],[-0.965505,0.813756,1.0],[0.0,1.0,1.0],[7.95628,1.12916,1.0],[5.32373,1.0083,1.0],[2.91716,0.905281,1.0],[1.05035,0.834887,1.0],[0.0,1.0,1.0],[6.83544,1.13214,1.0],[4.95639,1.00769,1.0],[3.81032,0.903303,1.0],[2.8937,0.82685,1.0],[0.0,1.0,1.0],[5.89142,1.1369,1.0],[4.55603,1.00893,1.0],[4.04927,0.902735,1.0],[3.59749,0.8313,1.0],[0.0,1.0,1.0],[5.07797,1.14498,1.0],[4.14717,1.01358,1.0],[3.95316,0.909713,1.0],[4.03064,0.834461,1.0],[0.0,1.0,1.0],[3.93584,1.15444,1.0],[3.29081,1.02539,1.0],[3.28057,0.922408,1.0],[3.7798,0.840035,1.0],[0.0,1.0,1.0],[2.45431,1.17195,1.0],[2.1184,1.04565,1.0],[2.31804,0.94015,1.0],[2.84532,0.862496,1.0],[0.0,1.0,1.0],[0.914128,1.1919,1.0],[0.658994,1.06124,1.0],[1.06903,0.95232,1.0],[1.60007,0.890999,1.0],[0.0,1.0,1.0],[-0.709287,1.20875,1.0],[-0.970683,1.0793,1.0],[-0.571268,0.969075,1.0],[-0.0688885,0.893104,1.0],[0.0,1.0,1.0],[-2.56506,1.23369,1.0],[-2.97984,1.10163,1.0],[-2.79742,0.983848,1.0],[-2.01335,0.892256,1.0],[0.0,1.0,1.0],[-4.47609,1.26079,1.0],[-4.91221,1.12068,1.0],[-4.5471,1.00002,1.0],[-2.72325,0.931381,1.0],[0.0,1.0,1.0],[-6.07811,1.27839,1.0],[-6.49836,1.12664,1.0],[-5.47092,0.99826,1.0],[-1.83561,0.972328,1.0],[0.0,1.0,1.0],[-8.37879,1.29932,1.0],[-8.93662,1.13395,1.0],[-7.32093,1.02059,1.0],[-0.98037,0.994534,1.0],[0.0,1.0,1.0],[-10.2729,1.25707,1.0],[-11.0599,1.09129,1.0],[-9.32287,1.00616,1.0],[-1.21689,0.994275,1.0],[0.0,1.0,1.0],[-11.9931,1.22624,1.0],[-12.4979,1.05021,1.0],[-10.2083,0.969313,1.0],[-1.172,0.991243,1.0],[0.0,1.0,1.0],[-13.5442,1.18901,1.0],[-13.5809,1.00396,1.0],[-10.7308,0.93446,1.0],[-1.1717,0.98724,1.0],[0.0,1.0,1.0],[-14.1202,1.16045,1.0],[-14.1451,0.982771,1.0],[-10.5188,0.911345,1.0],[-1.10721,0.983353,1.0],[0.0,1.0,1.0],[-14.5581,1.16209,1.0],[-13.8126,0.986909,1.0],[-8.30721,0.90898,1.0],[-0.995621,0.97911,1.0],[0.0,1.0,1.0],[-14.4013,1.1613,1.0],[-13.2596,0.979666,1.0],[-8.95671,0.890826,1.0],[-2.10024,0.967003,1.0],[0.0,1.0,1.0],[-15.1417,1.16939,1.0],[-13.2246,0.977241,1.0],[-9.7885,0.871629,1.0],[-2.78003,0.957243,1.0],[0.0,1.0,1.0],[-16.0188,1.15745,1.0],[-14.0864,0.974714,1.0],[-10.4183,0.871201,1.0],[-2.37086,0.964302,1.0],[0.0,1.0,1.0],[-16.2546,1.14581,1.0],[-13.912,0.987045,1.0],[-8.19204,0.901434,1.0],[-1.1791,0.982516,1.0],[0.0,1.0,1.0],[-16.3253,1.14274,1.0],[-13.1974,0.996884,1.0],[-7.37707,0.909881,1.0],[-0.796766,0.988333,1.0],[0.0,1.0,1.0],[-17.4833,1.13741,1.0],[-13.1058,0.977386,1.0],[-5.85941,0.919339,1.0],[-0.352557,0.99447,1.0],[0.0,1.0,1.0],[-17.5235,1.10838,1.0],[-13.7099,0.974525,1.0],[-5.10075,0.930882,1.0],[-0.176921,0.995738,1.0],[0.0,1.0,1.0],[-17.5967,1.05115,1.0],[-13.6048,0.938325,1.0],[-5.27843,0.910606,1.0],[-0.167657,0.994507,1.0],[0.0,1.0,1.0],[-17.4696,0.996524,1.0],[-13.115,0.908347,1.0],[-4.95967,0.899867,1.0],[-0.174963,0.992617,1.0],[0.0,1.0,1.0],[-16.5982,0.955417,1.0],[-11.0254,0.879437,1.0],[-3.31212,0.863198,1.0],[-0.175046,0.977174,1.0],[0.0,1.0,1.0],[-15.5952,0.929258,1.0],[-8.31794,0.86823,1.0],[-0.528212,0.846517,1.0],[0.380461,0.923401,1.0],[0.0,1.0,1.0],[-14.4398,0.910204,1.0],[-8.05514,0.876305,1.0],[-0.57323,0.868118,1.0],[0.470409,0.948896,1.0],[0.0,1.0,1.0],[-13.0585,0.905534,1.0],[-7.90773,0.889057,1.0],[-0.976436,0.905932,1.0],[0.542039,0.983099,1.0],[0.0,1.0,1.0],[-11.876,0.908437,1.0],[-7.06937,0.903432,1.0],[-0.539651,0.916127,1.0],[0.779286,0.983595,1.0],[0.0,1.0,1.0],[-10.0702,0.929172,1.0],[-5.39408,0.937425,1.0],[-0.2061,0.920171,1Line truncated
+97
View File
@@ -0,0 +1,97 @@
# EOS D60 colour matrices from a ColorChecker (2026-10-25)
The Canon EOS D60 has no published spectral sensitivities, so it is not in `spectral_table.rs`.
These are its DNG-style matrices (`ColorMatrix1/2`, `ForwardMatrix1/2`), fitted to our own
photographs of a ColorChecker Classic under two lights. They are in
`crates/raw/src/chart_table.rs`. Measurements come from the maintainer's own captures (names,
sizes and SHA-256 in `logs/chart-captures.tsv`; no image content recorded) and the chart's
published reference colours (craft-libs `crates/crw/clean-room/sources.md`). Scripts and measurements are local-only, in
`plan/crw/chart/`.
## Captures
| Set | Frames used | Light | Notes |
|---|---:|---|---|
| `SunlightColorCard/` | 20 of 22 | Direct afternoon sun, ISO 100 | Calibrite ColorChecker Classic (50th-anniversary edition, post-2014 formulation) leaning on a wall, filling most of the frame. Auto and Daylight white balance, a shutter bracket. Two frames dropped: a white-patch sample ≥ 3900 (clip ≈ 4000 at ISO 100, craft-libs `crates/crw/clean-room/04-color.md` §2). |
| `TungstonColorChart/` 2696–2706 | 11 | One household tungsten bulb, ISO 100 | Chart flat on a wall, a shutter bracket. Brightest white patch 2657 of ~4000. |
| `TungstonColorChart/` 2688–2691 | not used | Same bulb, 8 minutes earlier | Steady within the set, but its neutral reads ~3,040 K against ~2,900 K for the later set: the light changed (window light or bulb warm-up). The later, warmer and better-exposed set is used. |
All 37 frames decode sample-exact against the black-box reference (`craft-crw`'s digest-pinned sample test, formerly `crw_oracle.rs` here).
An earlier set on a ColorChecker-layout clone (Pixel Perfect "24 Standard Color Calibration
Chart", 2026-10-15) was not used. The maker publishes no reference values, and its grey patches
are not neutral: against an 18 % grey board they read R/G 0.88–0.94 in shade and B/G up to
1.29 under warm LED light, the darker patches drifting most. That is the sign of greys printed
from coloured inks.
## Measurement
- Patches are located on the embedded JPEG (four corner patch centres, bilinear grid), tracked
per frame by phase correlation, and checked visually on drawn boxes. The tungsten-set chart
was upside down in the first four frames; patch order is mapped accordingly.
- Each patch is measured in a central box of about 40 % of its width in the linear raw (black
from the far masked border per CFA site; R, mean of both G, B per 2×2 site). Uniformity
across the box (3×3 sub-blocks): ≤ 4 % in sun, ≤ 7 % under the bulb (light falloff across
the closer chart).
- Frames are normalised by the four middle neutrals (patches 20–23), averaged, and white
balanced on those neutrals. White balance (R, B multipliers, G = 1): sun 2.362, 1.298; bulb
1.353, 2.213. The neutrals agree on it to ±2 %.
## Fit
- The reference is X-Rite's published L\*a\*b\* (D50) for charts made after November 2014.
- The model is a 3×3 matrix from white-balanced camera RGB to XYZ (D50), with neutral (1, 1, 1)
held exactly at the engine's D50 white (`lightcraft_color::D50`): the third column is D50
minus the first two. That is a DNG `ForwardMatrix`.
- **Chromaticity only.** Each prediction is scaled to the patch's reference luminance before
the CIEDE2000 residual. In the sun the chart warped as it heated: the grey row's brightness
slope swung from +4 % to −7 % across the 70 s of shooting, in time order, and the per-patch
brightness needed was not smooth across the chart. A fit including lightness would have
absorbed that into the matrix. Chromaticity still determines the whole 3×3 up to scale,
which the white constraint fixes. The cost is that luminance of saturated blues and purples
rests on the model, not the measurement.
- `ColorMatrix` per light = diag(1 / multipliers) · ForwardMatrix⁻¹ · Bradford(light → D50),
scaled so the light's white maps to camera values with maximum 1. By construction it maps
the filed illuminant's white to the measured camera neutral.
| Light | CIEDE2000 on the 24 patches | Leaving each patch out | Worst |
|---|---|---|---|
| Sun (filed as D50) | mean 1.70, median 1.46 | mean 1.97 | white 4.5 |
| Bulb (filed as A) | mean 2.42, median 1.79 | mean 2.74 | bluish green 6.7 |
- One matrix does not serve both lights: the sun's matrix on the bulb's chart gives mean 3.6
(cyan 9.0), the bulb's on the sun's 3.4 (red 7.7). Hence the dual-illuminant entry.
- The neutral row reads a\* within ±0.4 for the middle greys; white and the darkest patches
are off by up to 2 (white patch sheen, flare).
## Which illuminants
The two lights' colour temperatures come from the camera's own white-balance presets
(ColorBalance slots, craft-libs `crates/crw/clean-room/04-color.md` §3) at the temperatures Canon's manuals give them (Daylight
5200 K, Tungsten 3200 K, Fluorescent 4000 K), interpolated in mired on ln(R/B): sun ~4,850 K,
bulb ~2,900 K. They are filed under the nearest DNG illuminants the engine knows, **D50
(5003 K) and Standard Illuminant A (2856 K)**, so `Camera` now carries its own illuminant
pair (spectral rows: A and D65).
## Checks in the app
- `spectral::tests::the_chart_measured_eos_d60_reads_its_presets_in_kelvin`: the camera's
presets, which the fit never saw, read through the matrices as Tungsten 3,264 K, Daylight
5,603 K, Cloudy 6,613 K, Flash 7,085 K, near the locus. Canon's nominal values are 3200, 5200,
6000 and 6000 K. Order and spacing hold; the daylight presets read 8–15 % high, as Sony's
dial does against its spectral matrices (#730).
- Real files through the headless app (As Shot): WBModes Fluorescent 4,103 K, tint +26 (green
compensation); LED-lit room, Auto 3,761 K; open shade, Auto 6,596 K; sunlit chart, Auto
4,762 K.
- `files::tests::crw_probes_name_their_camera_from_the_ciff_records`: CRW imports now take make,
model and capture time from the decoder's CIFF records (no Exif in a CRW; the catalog had an
empty camera, so a D60 stayed on the relative white-balance scale).
## Limits
- One body, one bulb, one afternoon. The chart is 24 patches; a 3×3 matrix cannot follow the
sensor's departures from the CIE observer (the bulb fit's worst patches are 5–7 ΔE).
- The lights are filed under standard illuminants they only approximate (~50 K for the bulb,
~150 K for the sun).
- The D60's look is still the per-file JPEG fit and the pooled profile; these matrices give the
white-balance scale and the fallback colour only.
+18
View File
@@ -0,0 +1,18 @@
# Canon CRW: where the record is
The Canon CRW (CIFF) decoder and its clean-room record (the frozen format, the verification
summary, the colour, geometry and metadata notes, the private-corpus summary and the source log)
live in craft-libs:
[`crates/crw/clean-room/`](https://github.com/storytold/craft-libs/tree/main/crates/crw/clean-room).
The derivation trail and the frozen table-generation materials stay in LightCraft PR #3021.
LightCraft uses the crate `craft-crw` through the adapter `crates/raw/src/vendor/crw.rs`.
What stays here is LightCraft's own colour work on these cameras:
- [`10-chart-calibration.md`](10-chart-calibration.md): the EOS D60 colour matrices fitted to
ColorChecker captures, implemented in `crates/raw/src/chart_table.rs`.
- [`logs/chart-captures.tsv`](logs/chart-captures.tsv): names, sizes and SHA-256 of the chart
frames (no image content).
The capture statistics those documents cite (`04-color.md`, `05-private-corpus.md`, `sources.md`)
are in the craft-libs record.
+39
View File
@@ -0,0 +1,39 @@
# EOS D60 ColorChecker Classic captures (maintainer, local only; never committed). Names, sizes, SHA-256; no image content. Generated 2026-10-25.
file bytes sha256
SunlightColorCard/CRW_2666.CRW 7791628 371d8e18c12801c72754dd7b277163a866afc422c8edf6ad1ea822009e4170f8
SunlightColorCard/CRW_2667.CRW 6638578 188d625c31ab44475a6cf54a5dae00fd861e26aafc90f4b5d18a1905c0a3cef5
SunlightColorCard/CRW_2668.CRW 6832770 1189b8dc79642c57a8c9496b5629e36a1741c545d2b0b864d6e6e20d901510c1
SunlightColorCard/CRW_2669.CRW 7079102 baf1686b27a9e0a04bf87c0b6cf55168f398d85247f8115a0af69b5e9ea1884c
SunlightColorCard/CRW_2670.CRW 7225298 067ba3f4d3026b8009cfe4babb5e4c3b28f988d95c48024a75c6715de32afccf
SunlightColorCard/CRW_2671.CRW 7504700 cf81cbb96389624318e890b5506221d49f5fba8e2d45447d87e0f3ff3e9bdc72
SunlightColorCard/CRW_2672.CRW 7830852 7a59446bfb1f00d6eabd0115b8e5451c34f5d3d48f483cb27608ce9508e43ee5
SunlightColorCard/CRW_2673.CRW 8053180 feeb8f818325d6ddb4e88b5eabe4a74f4cb5e1da9f70135ae3f85938c86695dc
SunlightColorCard/CRW_2674.CRW 8312060 45e7402c888582adadb607599eae80644d657d61c9607b426c411ee306e42daf
SunlightColorCard/CRW_2675.CRW 8565950 be28d2fa049aa4158ae9e3ec49dd28eb56fcd0ffa7af060235b8bda0d89dfd0a
SunlightColorCard/CRW_2676.CRW 7795508 76f7418a82e45e1034b3adacacf4bc756cb65a0d683e5bb3631992784e654f93
SunlightColorCard/CRW_2677.CRW 7747450 a5e7bc618e6b80ea70f9bad6a1bf41ee63eadbc51df28b82d0864a73434f7964
SunlightColorCard/CRW_2678.CRW 6815054 28824f0f64b087488d8dc5a66a8bdf717e83a4d4e1660676d07991bf32dffb96
SunlightColorCard/CRW_2679.CRW 7050606 b5c915fa89542265deb4fa16da3ca7ffda01b1d961903836b0059d024316673a
SunlightColorCard/CRW_2680.CRW 7231410 a5780dfe99a2df2a3ed9de1888e91baa614b2e009a2b6e0a84d442b6bf1af9fd
SunlightColorCard/CRW_2681.CRW 7438088 eb4475919c2770f816d47787656ab7ecb5396f30d2c03628c3ab167ebbc47c65
SunlightColorCard/CRW_2682.CRW 7584262 a6fe417b90ce41b03552963dee6b21e4f02b59a5c51148edc04af7224e8c59e9
SunlightColorCard/CRW_2683.CRW 7811474 5402ad40e2689d78ade083d8855ecced5caea9368b9d77ecc4a61a16dc55aa36
SunlightColorCard/CRW_2684.CRW 8043372 bbef5da457c0b6d6c45c74a99f3e318e6c80a7d3a0ad5c7cb7e13d24205f64fa
SunlightColorCard/CRW_2685.CRW 8242344 8d68d592a5c8933f0f35630114fe7017be808b007867beaf1a8d6d2bd1441f70
SunlightColorCard/CRW_2686.CRW 8462380 79f7db32b18a834d5408500185c65d316387d1440aa61e26a11be85883fcc382
SunlightColorCard/CRW_2687.CRW 7690732 0333d8d18390e77128f186239e6de71c0432ab6ee9669a71c210255e4d915d19
TungstonColorChart/CRW_2688.CRW 6269390 d9c4334edfe3636a8a7e69f29c1d1e89f820b7b704697684d7996faee41f5d43
TungstonColorChart/CRW_2689.CRW 6001348 1e8b47645d76a71fd9fb4111c4dce805d6dcd41ac82e6b4ce52debbf71565455
TungstonColorChart/CRW_2690.CRW 6114056 f63fe49a9ed13af33ddb8d8ed8d75de4e304a3bc2c1f1d4275ba7edbc4f459f3
TungstonColorChart/CRW_2691.CRW 6299730 ad8a2844c00965fb6a12e8fc85a6e8bfbdf1924e6d1a68b55472701cb8ffa115
TungstonColorChart/CRW_2696.CRW 6169684 105ee515c94da78dedc1f8d777982c4a1e62781b160428524fbe922f62b3ef5c
TungstonColorChart/CRW_2697.CRW 5565982 327eebf702185127feb8a5f4bfac5d7ebad5532f7417b302997b19b97d7ff4a8
TungstonColorChart/CRW_2698.CRW 5709092 f0fca20f8dcd51046e53bebf9fb9f624677ee674ad739622cdb2578977669705
TungstonColorChart/CRW_2699.CRW 5873492 57724a1ff507cf4e78c80a34cd4e0b77eac397322228d32e5215fc3869853dd1
TungstonColorChart/CRW_2700.CRW 5988146 6c97ae2c72114034e2fbe6aed0ef97f475696e43b56ed62273eccbfbba4cbaa0
TungstonColorChart/CRW_2701.CRW 6202756 c4032e46b753a718d8748e269a9da5d124891d07912542368ea867529143aa62
TungstonColorChart/CRW_2702.CRW 6409582 89b65c1c07e0685841046db85923b0bf80e747fed141ddf0335ba12dc75f3f3c
TungstonColorChart/CRW_2703.CRW 6407270 50179d0a330c967a74d76bc8342eea1052689c5c544aa1a913769b241ac6f736
TungstonColorChart/CRW_2704.CRW 6483154 6bac4d8229a8d0fff1445d212ca63e53911dc7bda988743215009257b87787fa
TungstonColorChart/CRW_2705.CRW 7170488 629f94131e7f598964d2635e3039a20c441563201c4f3cbf177d83ad6b061f78
TungstonColorChart/CRW_2706.CRW 6383026 67657e7a21f6fd8580012fccd2210afccf285e747bc4d39b8ea775811528ce83
1 # EOS D60 ColorChecker Classic captures (maintainer, local only; never committed). Names, sizes, SHA-256; no image content. Generated 2026-10-25.
2 file bytes sha256
3 SunlightColorCard/CRW_2666.CRW 7791628 371d8e18c12801c72754dd7b277163a866afc422c8edf6ad1ea822009e4170f8
4 SunlightColorCard/CRW_2667.CRW 6638578 188d625c31ab44475a6cf54a5dae00fd861e26aafc90f4b5d18a1905c0a3cef5
5 SunlightColorCard/CRW_2668.CRW 6832770 1189b8dc79642c57a8c9496b5629e36a1741c545d2b0b864d6e6e20d901510c1
6 SunlightColorCard/CRW_2669.CRW 7079102 baf1686b27a9e0a04bf87c0b6cf55168f398d85247f8115a0af69b5e9ea1884c
7 SunlightColorCard/CRW_2670.CRW 7225298 067ba3f4d3026b8009cfe4babb5e4c3b28f988d95c48024a75c6715de32afccf
8 SunlightColorCard/CRW_2671.CRW 7504700 cf81cbb96389624318e890b5506221d49f5fba8e2d45447d87e0f3ff3e9bdc72
9 SunlightColorCard/CRW_2672.CRW 7830852 7a59446bfb1f00d6eabd0115b8e5451c34f5d3d48f483cb27608ce9508e43ee5
10 SunlightColorCard/CRW_2673.CRW 8053180 feeb8f818325d6ddb4e88b5eabe4a74f4cb5e1da9f70135ae3f85938c86695dc
11 SunlightColorCard/CRW_2674.CRW 8312060 45e7402c888582adadb607599eae80644d657d61c9607b426c411ee306e42daf
12 SunlightColorCard/CRW_2675.CRW 8565950 be28d2fa049aa4158ae9e3ec49dd28eb56fcd0ffa7af060235b8bda0d89dfd0a
13 SunlightColorCard/CRW_2676.CRW 7795508 76f7418a82e45e1034b3adacacf4bc756cb65a0d683e5bb3631992784e654f93
14 SunlightColorCard/CRW_2677.CRW 7747450 a5e7bc618e6b80ea70f9bad6a1bf41ee63eadbc51df28b82d0864a73434f7964
15 SunlightColorCard/CRW_2678.CRW 6815054 28824f0f64b087488d8dc5a66a8bdf717e83a4d4e1660676d07991bf32dffb96
16 SunlightColorCard/CRW_2679.CRW 7050606 b5c915fa89542265deb4fa16da3ca7ffda01b1d961903836b0059d024316673a
17 SunlightColorCard/CRW_2680.CRW 7231410 a5780dfe99a2df2a3ed9de1888e91baa614b2e009a2b6e0a84d442b6bf1af9fd
18 SunlightColorCard/CRW_2681.CRW 7438088 eb4475919c2770f816d47787656ab7ecb5396f30d2c03628c3ab167ebbc47c65
19 SunlightColorCard/CRW_2682.CRW 7584262 a6fe417b90ce41b03552963dee6b21e4f02b59a5c51148edc04af7224e8c59e9
20 SunlightColorCard/CRW_2683.CRW 7811474 5402ad40e2689d78ade083d8855ecced5caea9368b9d77ecc4a61a16dc55aa36
21 SunlightColorCard/CRW_2684.CRW 8043372 bbef5da457c0b6d6c45c74a99f3e318e6c80a7d3a0ad5c7cb7e13d24205f64fa
22 SunlightColorCard/CRW_2685.CRW 8242344 8d68d592a5c8933f0f35630114fe7017be808b007867beaf1a8d6d2bd1441f70
23 SunlightColorCard/CRW_2686.CRW 8462380 79f7db32b18a834d5408500185c65d316387d1440aa61e26a11be85883fcc382
24 SunlightColorCard/CRW_2687.CRW 7690732 0333d8d18390e77128f186239e6de71c0432ab6ee9669a71c210255e4d915d19
25 TungstonColorChart/CRW_2688.CRW 6269390 d9c4334edfe3636a8a7e69f29c1d1e89f820b7b704697684d7996faee41f5d43
26 TungstonColorChart/CRW_2689.CRW 6001348 1e8b47645d76a71fd9fb4111c4dce805d6dcd41ac82e6b4ce52debbf71565455
27 TungstonColorChart/CRW_2690.CRW 6114056 f63fe49a9ed13af33ddb8d8ed8d75de4e304a3bc2c1f1d4275ba7edbc4f459f3
28 TungstonColorChart/CRW_2691.CRW 6299730 ad8a2844c00965fb6a12e8fc85a6e8bfbdf1924e6d1a68b55472701cb8ffa115
29 TungstonColorChart/CRW_2696.CRW 6169684 105ee515c94da78dedc1f8d777982c4a1e62781b160428524fbe922f62b3ef5c
30 TungstonColorChart/CRW_2697.CRW 5565982 327eebf702185127feb8a5f4bfac5d7ebad5532f7417b302997b19b97d7ff4a8
31 TungstonColorChart/CRW_2698.CRW 5709092 f0fca20f8dcd51046e53bebf9fb9f624677ee674ad739622cdb2578977669705
32 TungstonColorChart/CRW_2699.CRW 5873492 57724a1ff507cf4e78c80a34cd4e0b77eac397322228d32e5215fc3869853dd1
33 TungstonColorChart/CRW_2700.CRW 5988146 6c97ae2c72114034e2fbe6aed0ef97f475696e43b56ed62273eccbfbba4cbaa0
34 TungstonColorChart/CRW_2701.CRW 6202756 c4032e46b753a718d8748e269a9da5d124891d07912542368ea867529143aa62
35 TungstonColorChart/CRW_2702.CRW 6409582 89b65c1c07e0685841046db85923b0bf80e747fed141ddf0335ba12dc75f3f3c
36 TungstonColorChart/CRW_2703.CRW 6407270 50179d0a330c967a74d76bc8342eea1052689c5c544aa1a913769b241ac6f736
37 TungstonColorChart/CRW_2704.CRW 6483154 6bac4d8229a8d0fff1445d212ca63e53911dc7bda988743215009257b87787fa
38 TungstonColorChart/CRW_2705.CRW 7170488 629f94131e7f598964d2635e3039a20c441563201c4f3cbf177d83ad6b061f78
39 TungstonColorChart/CRW_2706.CRW 6383026 67657e7a21f6fd8580012fccd2210afccf285e747bc4d39b8ea775811528ce83
+70
View File
@@ -0,0 +1,70 @@
//! Fault injection for the catalog log's writer thread (tests only: nothing in the product
//! installs a hook, and with none installed a check is one uncontended lock of an empty list).
//!
//! A test makes the drive under one library directory slow (a hook that sleeps) or failing (a
//! hook that returns an error) and proves that a flag never waits for it and that nothing handed
//! over is lost: `crates/catalog/src/tests_log_thread.rs`, `crates/engine/src/tests/slow_drive.rs`.
use std::io;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, PoisonError};
/// Where the log thread is about to touch the drive.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Step {
/// Writing bytes to the log (or to the file that replaces it).
Write,
/// Syncing them.
Sync,
}
/// Runs before each [`Step`] in the hooked directory: an error fails that step.
pub type Hook = Arc<dyn Fn(Step) -> io::Result<()> + Send + Sync>;
static HOOKS: Mutex<Vec<(PathBuf, Hook)>> = Mutex::new(Vec::new());
/// Run `hook` before every write and sync of the catalog log in `dir` (replacing an earlier one).
#[doc(hidden)]
pub fn install(dir: &Path, hook: Hook) {
let mut hooks = HOOKS.lock().unwrap_or_else(PoisonError::into_inner);
hooks.retain(|(d, _)| d != dir);
hooks.push((dir.to_path_buf(), hook));
}
/// Remove the hook of `dir`.
#[doc(hidden)]
pub fn remove(dir: &Path) {
HOOKS.lock().unwrap_or_else(PoisonError::into_inner).retain(|(d, _)| d != dir);
}
static ON_CALLER: Mutex<Vec<PathBuf>> = Mutex::new(Vec::new());
/// Write the log in `dir` on the caller's thread, syncing before each append returns, as builds
/// before PERF-STEP-STALL did: a test's "before" (stores opened afterwards; the hooks run there too).
#[doc(hidden)]
pub fn write_on_caller(dir: &Path, on: bool) {
let mut dirs = ON_CALLER.lock().unwrap_or_else(PoisonError::into_inner);
dirs.retain(|d| d != dir);
if on {
dirs.push(dir.to_path_buf());
}
}
pub(crate) fn on_caller(dir: &Path) -> bool {
let dirs = ON_CALLER.lock().unwrap_or_else(PoisonError::into_inner);
!dirs.is_empty() && dirs.iter().any(|d| d == dir)
}
pub(crate) fn check(dir: &Path, step: Step) -> io::Result<()> {
let hook = {
let hooks = HOOKS.lock().unwrap_or_else(PoisonError::into_inner);
if hooks.is_empty() {
return Ok(());
}
hooks.iter().find(|(d, _)| d == dir).map(|(_, h)| h.clone())
};
match hook {
Some(h) => h(step),
None => Ok(()),
}
}
+35 -3
View File
@@ -6,7 +6,10 @@
//! rename).
//! - `catalog.log` — JSON lines, one per op applied after the snapshot:
//! `{"seq":N,"crc":C,"op":{…}}` where `C` is the CRC-32 of the op's JSON text. Appends are
//! fsynced before [`Journal::append`] returns.
//! fsynced before [`Journal::append`] returns, except natively: [`crate::FsStore`] hands them to
//! a thread of its own that writes and syncs them in order right after (so a flag never waits
//! for the drive), holds and retries whatever fails ([`Journal::unwritten`]) and refuses later
//! appends meanwhile, so the log never has a gap and nothing handed over is dropped.
//!
//! Loading = snapshot + replay of the records with `seq > snapshot seq`. Recovery rules:
//! - a **torn final record** (crash mid-append: truncated line or bad CRC at the end) is dropped
@@ -52,6 +55,8 @@
//! | 7 | Kelvin white balance for raws whose camera has matrices (#730) | `Op::SetAsShotWb`, `WhiteBalance.scale` |
//! | 8 | History cursor: Go to History Step adds no step | `Op::SetHistoryCursor`, `Photo.history_cursor` |
//! | 9 | preview-only recheck | `Photo.preview_checked`, `Op::SetContent.preview_checked` |
//! | 10 | masks stay on the photo under lens corrections, Upright and Transform | `Mask.on_photo` (develop settings) |
//! | 11 | lens database profiles named in the Optics panel | `EmbeddedLens.source` |
//!
//! Rules:
//! - **Bump [`VERSION`]** (and add a row above) in the change that adds an [`Op`] variant or a
@@ -76,7 +81,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 = 9;
pub const VERSION: u32 = 11;
/// When [`Journal::wants_snapshot`] says it's time to compact the log.
#[derive(Clone, Copy, Debug)]
@@ -193,6 +198,10 @@ pub struct Journal {
/// A failed append may have left part of its records after `log_bytes`, and cutting them off
/// failed too: the next append cuts the log back to `log_bytes` first.
tail_dirty: bool,
/// An append failed (natively that can be the store's own log thread failing to write records
/// handed over before, which it holds and retries): the next chance writes a snapshot, a fresh
/// file holding everything, in case only the log's file is broken.
snapshot_due: bool,
}
/// A background snapshot in flight.
@@ -381,6 +390,7 @@ impl Journal {
pending: None,
retry_at_records: 0,
tail_dirty: false,
snapshot_due: false,
};
let log = log.unwrap_or_default();
@@ -514,6 +524,7 @@ impl Journal {
self.tail_dirty = false;
}
if let Err(e) = self.store.append(LOG, buf.as_bytes()) {
self.snapshot_due = true;
// Part of the batch may be in the file. Cut it back to the last whole record, so the
// retry (same seqs) starts on a clean line instead of after a fragment that would
// read back as damage.
@@ -676,6 +687,7 @@ impl Journal {
}
fn record_snapshot(&mut self, t: SnapshotTiming) {
self.snapshot_due = false;
self.stats.snapshots += 1;
self.stats.last_snapshot = t;
self.stats.max_snapshot_ms = self.stats.max_snapshot_ms.max(t.total_ms);
@@ -695,6 +707,23 @@ impl Journal {
}
}
/// Wait until every appended record is in the file and synced (natively the store writes the
/// log on a thread of its own, [`crate::FsStore`]): before the files are read or copied from
/// outside. An error says why some aren't yet: they are held and retried, never dropped.
pub fn flush(&mut self) -> Result<()> {
self.store.flush().map_err(io)
}
/// Appended records the store holds because writing them failed (retried), and why; `None`
/// when nothing is held back. Never waits for the drive.
pub fn unwritten(&self) -> Option<(usize, String)> {
// a snapshot that holds every op holds whatever the log's thread still holds
if self.snapshot_seq >= self.seq && self.pending.is_none() {
return None;
}
self.store.unwritten()
}
/// Where persistence time went so far.
pub fn stats(&self) -> PersistStats {
PersistStats { snapshot_running: self.pending.is_some(), ..self.stats }
@@ -704,7 +733,10 @@ impl Journal {
pub fn wants_snapshot(&self) -> bool {
self.pending.is_none()
&& self.log_records >= self.retry_at_records
&& (self.log_records >= self.policy.max_records || self.log_bytes >= self.policy.max_bytes)
&& (self.snapshot_due
|| self.unwritten().is_some()
|| self.log_records >= self.policy.max_records
|| self.log_bytes >= self.policy.max_bytes)
}
pub fn seq(&self) -> u64 {
+60 -22
View File
@@ -87,6 +87,12 @@ pub fn from_file(flat: &[String], hierarchical: &[String]) -> Vec<String> {
/// The deepest a keyword list file may nest keywords: a file is input, so its nesting is bounded.
pub const MAX_LEVELS: usize = 64;
/// The most bytes of full keyword paths a keyword list file may spell out. Every line names its
/// keyword by its whole path (`parent|child`), so a file of one long keyword with many short ones
/// inside it would otherwise grow into far more memory than its own size (CWE-400). Lightroom
/// Classic's own lists of tens of thousands of keywords come to a few MiB.
pub const MAX_LIST_PATH_BYTES: usize = 64 << 20; // 64 MiB
/// A keyword list as written by [`Catalog::keyword_list_text`]: the file's text, the keywords in
/// it (paths), and what the format can't hold and so is left out (a keyword, with those inside it,
/// as its path; a synonym as `path {synonym}`).
@@ -114,6 +120,8 @@ pub fn parse_keyword_list(text: &str) -> Result<Vec<(String, KeywordInfo)>> {
let mut synonyms: std::collections::HashMap<usize, std::collections::HashSet<String>> = std::collections::HashMap::new();
// the keyword at each level above the line: its path and where it is in `out`
let mut above: Vec<(String, usize)> = Vec::new();
// bytes of full paths spelled out so far, checked against `MAX_LIST_PATH_BYTES` before each
let mut path_bytes = 0usize;
for (i, line) in text.split('\n').enumerate() {
let n = i + 1;
if line.trim().is_empty() {
@@ -162,6 +170,11 @@ pub fn parse_keyword_list(text: &str) -> Result<Vec<(String, KeywordInfo)>> {
return Err(bad(n, "“|” separates a keyword's levels: a name can't hold one"));
}
above.truncate(depth);
let parent_len = above.last().map_or(0, |(parent, _)| parent.len().saturating_add(1));
path_bytes = path_bytes.saturating_add(parent_len.saturating_add(name.len()));
if path_bytes > MAX_LIST_PATH_BYTES {
return Err(bad(n, &format!("the keywords' full paths come to more than {} MiB", MAX_LIST_PATH_BYTES >> 20)));
}
let path = match above.last() {
Some((parent, _)) => format!("{parent}{SEP}{name}"),
None => name.to_string(),
@@ -189,6 +202,14 @@ pub fn closest<'a>(k: &str, from: &'a [String]) -> Option<&'a String> {
from.iter().filter(|f| is_under(k, f)).max_by_key(|f| f.split(SEP).count())
}
/// Add each of `more` to `synonyms` that isn't there in any case, in order. One lowered set of
/// what is there, not a search of the growing list per synonym: an imported list can give a
/// keyword many synonyms, and the search was quadratic in them (CWE-407).
fn merge_synonyms(synonyms: &mut Vec<String>, more: impl IntoIterator<Item = String>) {
let mut seen: std::collections::HashSet<String> = synonyms.iter().map(|s| s.to_lowercase()).collect();
synonyms.extend(more.into_iter().filter(|s| seen.insert(s.to_lowercase())));
}
/// Keep the first of case-insensitively equal keywords.
fn dedupe(v: &mut Vec<String>) {
let mut seen = std::collections::HashSet::new();
@@ -402,11 +423,7 @@ impl Catalog {
Some(there) => {
there.info.new_keywords_inside |= l.info.new_keywords_inside;
there.info.keyword_shortcut |= l.info.keyword_shortcut;
for s in l.info.synonyms {
if !there.info.synonyms.iter().any(|x| same(x, &s)) {
there.info.synonyms.push(s);
}
}
merge_synonyms(&mut there.info.synonyms, l.info.synonyms);
}
None => {
list.insert(path.to_lowercase(), ListedKeyword { path, info: l.info });
@@ -467,8 +484,11 @@ impl Catalog {
let defaults = KeywordInfo::default();
let info = |path: &str| self.keyword_info(path).unwrap_or(&defaults);
let mut out = ExportKeywords::default();
let push = |v: &mut Vec<String>, s: &str| {
if !s.is_empty() && !v.iter().any(|x| same(x, s)) {
// what each list holds, lowered: a search of the list per name was quadratic in a keyword's
// synonyms, which an imported list sets (CWE-407)
let (mut flat_seen, mut paths_seen) = (std::collections::HashSet::new(), std::collections::HashSet::new());
let push = |v: &mut Vec<String>, seen: &mut std::collections::HashSet<String>, s: &str| {
if !s.is_empty() && seen.insert(s.to_lowercase()) {
v.push(s.to_string());
}
};
@@ -481,11 +501,11 @@ impl Catalog {
let levels: Vec<&str> = path.split(SEP).collect();
let mut names = |at: usize, i: &KeywordInfo| {
if let Some(name) = levels.get(at) {
push(&mut out.flat, name);
push(&mut out.flat, &mut flat_seen, name);
}
if i.export_synonyms {
for s in &i.synonyms {
push(&mut out.flat, s.trim());
push(&mut out.flat, &mut flat_seen, s.trim());
}
}
};
@@ -499,7 +519,7 @@ impl Catalog {
}
}
}
push(&mut out.hierarchical, &path);
push(&mut out.hierarchical, &mut paths_seen, &path);
}
out
}
@@ -509,6 +529,13 @@ impl Catalog {
/// keyword, a keyword left out of export in square brackets; by name. What the format can't hold
/// is left out and named, so the file always reads back.
pub fn keyword_list_text(&self) -> KeywordListFile {
self.keyword_list_text_within(MAX_LIST_PATH_BYTES)
}
/// [`keyword_list_text`](Self::keyword_list_text) with the full paths written held to
/// `max_path_bytes` as [`parse_keyword_list`] holds them: a keyword past it is named
/// unwritable, with its subtree, so the file reads back.
fn keyword_list_text_within(&self, max_path_bytes: usize) -> KeywordListFile {
// a name the list would read as something else, or not at all
fn unwritable(name: &str) -> bool {
name.trim().is_empty()
@@ -519,14 +546,27 @@ impl Catalog {
|| (name.starts_with('[') && name.ends_with(']'))
|| (name.starts_with('{') && name.ends_with('}'))
}
fn write(c: &Catalog, nodes: &[KeywordNode], depth: usize, file: &mut KeywordListFile) {
fn write(
c: &Catalog,
nodes: &[KeywordNode],
depth: usize,
file: &mut KeywordListFile,
path_bytes: &mut usize,
max_path_bytes: usize,
parent_len: usize,
) {
let tabs = "\t".repeat(depth);
for n in nodes {
// the keywords inside go with it: under its parent they'd be other keywords
if depth >= MAX_LEVELS || unwritable(&n.name) {
// (a line's full path is what the reader counts against its path budget)
// the path the reader rebuilds from the lines written: the parent as emitted, a
// separator, the name (a child's `n.path` can spell its parent in another case)
let emitted = if depth == 0 { n.name.len() } else { parent_len + SEP.len_utf8() + n.name.len() };
if depth >= MAX_LEVELS || unwritable(&n.name) || path_bytes.saturating_add(emitted) > max_path_bytes {
file.unwritable.push(n.path.clone());
continue;
}
*path_bytes += emitted;
let info = c.keyword_info(&n.path).cloned().unwrap_or_default();
if info.include_on_export {
file.text.push_str(&format!("{tabs}{}\n", n.name));
@@ -536,19 +576,21 @@ impl Catalog {
file.written.push(n.path.clone());
// the reader trims synonyms and takes one per spelling: an empty one, or another's
// in a different case, is no loss; a line break or a “|” is
let mut synonyms: Vec<&str> = Vec::new();
// (one lowered set, not a search of those written so far per synonym: quadratic
// in a keyword's synonyms, which an imported list sets — CWE-407)
let mut synonyms: std::collections::HashSet<String> = std::collections::HashSet::new();
for s in info.synonyms.iter().map(|s| s.trim()) {
if s.is_empty() || synonyms.iter().any(|x| same(x, s)) {
if s.is_empty() || synonyms.contains(&s.to_lowercase()) {
continue;
}
if s.chars().any(char::is_control) || s.contains(SEP) {
file.unwritable.push(format!("{} {{{s}}}", n.path));
} else {
synonyms.push(s);
synonyms.insert(s.to_lowercase());
file.text.push_str(&format!("{tabs}\t{{{s}}}\n"));
}
}
write(c, &n.children, depth + 1, file);
write(c, &n.children, depth + 1, file, path_bytes, max_path_bytes, emitted);
}
}
let mut file = KeywordListFile::default();
@@ -568,7 +610,7 @@ impl Catalog {
}
}
}
write(self, &self.keyword_tree(), 0, &mut file);
write(self, &self.keyword_tree(), 0, &mut file, &mut 0, max_path_bytes, 0);
file.unwritable.extend(over_deep);
file
}
@@ -632,11 +674,7 @@ impl Catalog {
// one the library has: the list's synonyms join its own (listed only if it gains some)
let mut info_now = list.get(&key).map(|l| l.info.clone()).unwrap_or_default();
let before = info_now.synonyms.len();
for s in &info.synonyms {
if !info_now.synonyms.iter().any(|x| same(x, s)) {
info_now.synonyms.push(s.clone());
}
}
merge_synonyms(&mut info_now.synonyms, info.synonyms.iter().cloned());
if info_now.synonyms.len() > before {
let path = list.get(&key).map_or(path, |l| l.path.clone());
list.insert(key, ListedKeyword { path, info: info_now });
+55
View File
@@ -556,6 +556,17 @@ fn the_keyword_list_is_written_as_tab_indented_text() {
assert_eq!(c.keyword_list_text().text, "beach\nEvents\n\tWeddings\n[Places]\n\tLisbon\n\t\t{Lisboa}\n");
}
/// The path budget the reader enforces holds for the writer too: a keyword past it, and its
/// subtree, is named unwritable instead of making a file `keyword.import` rejects.
#[test]
fn the_keyword_list_written_stays_within_the_path_budget() {
let (c, _) = lib(&[&["Places|Lisbon", "beach"], &["Events|Weddings"]]);
let file = c.keyword_list_text_within(17);
assert_eq!(file.text, "beach\nEvents\nPlaces\n");
assert_eq!(file.unwritable, ["Events|Weddings", "Places|Lisbon"]);
assert_eq!(c.keyword_list_text().unwritable, Vec::<String>::new());
}
/// Reading a list gives each keyword's path and attributes: what was written comes back, and a
/// file from elsewhere (Windows line ends, a byte-order mark, blank lines) reads too.
#[test]
@@ -765,3 +776,47 @@ fn keyword_tree_caps_a_keyword_at_the_list_depth() {
let deepest = tree_paths(&c.keyword_tree()).iter().map(|(p, _)| p.split(SEP).count()).max().unwrap_or(0);
assert_eq!(deepest, MAX_LEVELS);
}
/// A keyword list file spells each keyword's whole path, so one long keyword with many short ones
/// inside it expands into far more than its own size: past `MAX_LIST_PATH_BYTES` it is refused
/// with the line where that happened, instead of growing without bound (CWE-400).
#[test]
fn a_list_whose_paths_expand_past_the_budget_is_refused() {
let parent = "p".repeat(1 << 20);
let children = MAX_LIST_PATH_BYTES / parent.len() + 2;
let mut text = format!("{parent}\n");
for i in 0..children {
text.push_str(&format!("\tc{i}\n"));
}
let err = parse_keyword_list(&text).unwrap_err().to_string();
assert!(err.contains("full paths come to more than"), "{err}");
// a list within the budget still reads
let ok = parse_keyword_list(&format!("{parent}\n\tchild\n")).unwrap();
assert_eq!(ok.len(), 2);
assert_eq!(ok[1].0, format!("{parent}|child"));
}
/// Many synonyms joining a keyword the library has, its export and its keyword list file each keep
/// every spelling once, in order, without a search of the growing list per synonym (CWE-407).
#[test]
fn many_synonyms_are_gathered_once_each_in_order() {
const N: usize = 40_000;
let mut c = Catalog::new();
c.apply(Op::SetKeyword { path: "travel".into(), info: Some(with_synonyms(&["Trip"])) }).unwrap();
let mut incoming: Vec<String> = (0..N).map(|i| format!("syn{i}")).collect();
incoming.push("TRIP".into());
incoming.push("SYN7".into());
let started = std::time::Instant::now();
let (op, added, updated) = c.import_keywords_ops(&[("travel".into(), KeywordInfo { synonyms: incoming, ..KeywordInfo::default() })]);
c.apply(op).unwrap();
assert_eq!((added, updated), (0, 1));
let synonyms = c.keyword_info("travel").unwrap().synonyms.clone();
assert_eq!(synonyms.len(), N + 1);
assert_eq!(synonyms[0], "Trip");
assert_eq!(synonyms[8], "syn7");
let exported = c.export_keywords(&["travel".into()]);
assert_eq!(exported.flat.len(), N + 2);
let file = c.keyword_list_text();
assert_eq!(file.text.lines().count(), N + 2);
assert!(started.elapsed() < std::time::Duration::from_secs(20), "took {:?}", started.elapsed());
}
+7
View File
@@ -14,12 +14,17 @@
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
pub mod dates;
#[cfg(not(target_arch = "wasm32"))]
#[doc(hidden)]
pub mod fault;
pub mod folders;
mod index;
pub mod journal;
pub mod keywords;
pub mod local;
pub mod lock;
#[cfg(not(target_arch = "wasm32"))]
mod log_writer;
pub mod model;
pub mod query;
pub mod rules;
@@ -1490,6 +1495,8 @@ mod tests_journal;
mod tests_local;
#[cfg(test)]
mod tests_lock;
#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests_log_thread;
#[cfg(test)]
mod tests_repair;
#[cfg(test)]
+377
View File
@@ -0,0 +1,377 @@
//! The thread that writes the catalog log for [`crate::FsStore`] (natively).
//!
//! An append hands its bytes over and returns; the thread writes them in order and makes each batch
//! durable (`sync_data`) before the next. The caller (the UI thread, for the app) never waits for
//! the drive: on Windows a write to a file waits for a sync of that file in flight, so with the log
//! written and synced on the UI thread every flag, rating and step waited for the drive, 30–90 ms
//! on a busy disk in a test and over a second on a photographer's machine while previews were
//! written.
//!
//! **Nothing handed over is ever dropped.** The store's log is the file's first `good` bytes (written
//! and synced) followed by `held`, the bytes handed over and not yet synced. A write or sync that
//! fails keeps `held` and retries it (on every later message, and every [`RETRY`] meanwhile), first
//! cutting the file back to `good` so a fragment of the failed write never stays in it. While a
//! failure stands, [`LogWriter::append`] refuses new bytes with the failure (the journal keeps those
//! records queued, as for any failed append) and [`LogWriter::unwritten`] says how many records are
//! held, so the app counts them as not saved and its quit prompt warns before anything could be
//! lost. Cutting the log back, replacing it and reading it act on that logical content, after
//! everything handed over before; the caller waits for them. Dropping the writer waits for
//! everything handed over and tries a last time.
use std::io::{self, Seek, Write};
use std::path::PathBuf;
use std::sync::mpsc::{Receiver, RecvTimeoutError, Sender, channel};
use std::sync::{Arc, Mutex, PoisonError};
use std::time::Duration;
/// How long a caller waits for the thread at most (a cut, a replace, a read, a flush).
const WAIT: Duration = Duration::from_secs(60);
/// How often held bytes are retried while a failure stands and nothing else arrives.
pub(crate) const RETRY: Duration = Duration::from_millis(500);
enum Msg {
Append(Vec<u8>),
Truncate(u64, Sender<io::Result<()>>),
Replace(Vec<u8>, Sender<io::Result<()>>),
Read(Sender<io::Result<Option<Vec<u8>>>>),
/// Reply once everything before is written and synced (or why it isn't).
Flush(Sender<io::Result<()>>),
}
/// What the caller can see without waiting.
#[derive(Default)]
struct Shared {
/// Why the held bytes couldn't be written (until they are, or the log is cut or replaced).
failed: Option<String>,
/// Records (lines) handed over and not yet written and synced, while `failed` stands.
held_records: usize,
}
pub(crate) struct LogWriter {
pub(crate) name: String,
tx: Option<Sender<Msg>>,
shared: Arc<Mutex<Shared>>,
thread: Option<std::thread::JoinHandle<()>>,
}
fn stopped() -> io::Error {
io::Error::other("the catalog log writer stopped")
}
fn not_written(why: &str) -> io::Error {
io::Error::other(format!("the catalog log could not be written: {why}"))
}
impl LogWriter {
/// A writer for `dir/name` (`None` when no thread can start: the store then writes itself).
pub(crate) fn start(dir: PathBuf, name: &str) -> Option<LogWriter> {
let (tx, rx) = channel::<Msg>();
let shared = Arc::new(Mutex::new(Shared::default()));
let sh = shared.clone();
let mut w = Writer::new(dir, name);
let thread = std::thread::Builder::new().name("catalog-log".into()).spawn(move || w.run(&rx, &sh)).ok()?;
Some(LogWriter { name: name.to_string(), tx: Some(tx), shared, thread: Some(thread) })
}
fn send(&self, m: Msg) -> io::Result<()> {
self.tx.as_ref().ok_or_else(stopped)?.send(m).map_err(|_| stopped())
}
fn ask<T>(&self, make: impl FnOnce(Sender<io::Result<T>>) -> Msg) -> io::Result<T> {
let (tx, rx) = channel();
self.send(make(tx))?;
rx.recv_timeout(WAIT).map_err(|e| match e {
RecvTimeoutError::Timeout => io::Error::new(io::ErrorKind::TimedOut, "the drive took over a minute to write the catalog log"),
RecvTimeoutError::Disconnected => stopped(),
})?
}
/// Hand `data` over (never waits for the drive). Refused while bytes handed over before can't
/// be written: the caller keeps `data` and appends it again later.
pub(crate) fn append(&self, data: &[u8]) -> io::Result<()> {
if let Some(why) = self.shared.lock().unwrap_or_else(PoisonError::into_inner).failed.clone() {
return Err(not_written(&why));
}
self.send(Msg::Append(data.to_vec()))
}
/// Cut the log to `len` bytes, after everything handed over; waits for it.
pub(crate) fn truncate(&self, len: u64) -> io::Result<()> {
self.ask(|r| Msg::Truncate(len, r))
}
/// Replace the log with `data` (atomically, durably), after everything handed over; waits.
pub(crate) fn replace(&self, data: &[u8]) -> io::Result<()> {
self.ask(|r| Msg::Replace(data.to_vec(), r))
}
/// The log as appended so far (written or still held), after everything handed over.
pub(crate) fn read(&self) -> io::Result<Option<Vec<u8>>> {
self.ask(Msg::Read)
}
/// Wait until everything handed over is written and synced; an error says why it isn't (the
/// bytes are still held and retried).
pub(crate) fn flush(&self) -> io::Result<()> {
self.ask(Msg::Flush)
}
/// Records handed over that can't be written yet, and why (`None`: nothing is held back by a
/// failure). Never waits.
pub(crate) fn unwritten(&self) -> Option<(usize, String)> {
let sh = self.shared.lock().unwrap_or_else(PoisonError::into_inner);
sh.failed.clone().map(|why| (sh.held_records.max(1), why))
}
}
impl Drop for LogWriter {
fn drop(&mut self) {
drop(self.tx.take());
if let Some(t) = self.thread.take() {
let _ = t.join();
}
}
}
/// The thread's side: the file and what is held for it.
struct Writer {
dir: PathBuf,
path: PathBuf,
tmp: PathBuf,
file: Option<std::fs::File>,
/// Bytes of the file written whole and synced (`None` until the file was first opened).
good: Option<u64>,
/// Handed over, not yet written and synced.
held: Vec<u8>,
failed: Option<String>,
}
fn lines(b: &[u8]) -> usize {
b.iter().filter(|c| **c == b'\n').count()
}
impl Writer {
fn new(dir: PathBuf, name: &str) -> Writer {
let path = dir.join(name);
let tmp = dir.join(format!("{name}.tmp"));
Writer { dir, path, tmp, file: None, good: None, held: Vec::new(), failed: None }
}
fn hook(&self, step: crate::fault::Step) -> io::Result<()> {
crate::fault::check(&self.dir, step)
}
/// Open the file positioned at `good` (a fragment past it, from a write that failed, is cut).
fn open(&mut self) -> io::Result<u64> {
if let (Some(_), Some(g)) = (&self.file, self.good) {
return Ok(g);
}
// (a link or a device planted at the name meanwhile is refused, as at the first append)
crate::store::check_regular_directory_entry(&self.path)?;
let mut f = std::fs::OpenOptions::new().write(true).create(true).truncate(false).open(&self.path)?;
let len = f.metadata()?.len();
let good = match self.good {
None => len,
Some(g) if len > g => {
f.set_len(g)?;
g
}
Some(g) if len < g => {
// shorter than what was synced: someone else cut it; continue at its end
log::error!("catalog: {} is {len} bytes, {g} were written", self.path.display());
len
}
Some(g) => g,
};
f.seek(io::SeekFrom::Start(good))?;
self.good = Some(good);
self.file = Some(f);
Ok(good)
}
/// Write and sync what is held.
fn write_held(&mut self) -> io::Result<()> {
if self.held.is_empty() {
return Ok(());
}
let r = (|| {
self.hook(crate::fault::Step::Write)?;
self.open()?;
let f = self.file.as_mut().ok_or_else(|| io::Error::other("catalog log not open"))?;
f.write_all(&self.held)?;
self.hook(crate::fault::Step::Sync)?;
self.file.as_ref().ok_or_else(|| io::Error::other("catalog log not open"))?.sync_data()
})();
match r {
Ok(()) => {
let n = self.held.len() as u64;
self.good = Some(self.good.unwrap_or(0).saturating_add(n));
self.held.clear();
Ok(())
}
Err(e) => {
// the handle may be dead (a network share that reconnected, a removed volume): the
// retry opens the file again and cuts what this attempt left past `good`
self.file = None;
Err(e)
}
}
}
/// Cut the logical log (file then held) to `len` bytes.
fn truncate(&mut self, len: u64) -> io::Result<()> {
let good = match self.good {
Some(g) => g,
None => match self.open() {
Ok(g) => g,
Err(e) if e.kind() == io::ErrorKind::NotFound => 0,
Err(e) => return Err(e),
},
};
// (to exactly `good` with bytes held: the file is cut, since a write that failed may have
// left some of them past `good`)
if len > good || (len == good && self.held.is_empty()) {
// within what is held: nothing on the drive changes (what a failed write left past
// `good` is cut before the next write)
let keep = usize::try_from(len - good).unwrap_or(usize::MAX).min(self.held.len());
self.held.truncate(keep);
return Ok(());
}
self.file = None;
let f = match std::fs::OpenOptions::new().write(true).open(&self.path) {
Ok(f) => f,
Err(e) if e.kind() == io::ErrorKind::NotFound => {
self.good = None;
self.held.clear();
return Ok(());
}
Err(e) => return Err(e),
};
f.set_len(len)?;
f.sync_all()?;
self.good = Some(len);
self.held.clear();
Ok(())
}
fn replace(&mut self, data: &[u8]) -> io::Result<()> {
self.file = None;
let written = (|| {
self.hook(crate::fault::Step::Write)?;
let mut f = crate::store::create_staging(&self.tmp)?;
f.write_all(data)?;
self.hook(crate::fault::Step::Sync)?;
f.sync_all()?;
drop(f);
std::fs::rename(&self.tmp, &self.path)
})();
match written {
Ok(()) => {
// what was held is part of what the caller replaced the log with (a snapshot holds
// the records before it, `data` the ones after)
self.good = Some(data.len() as u64);
self.held.clear();
self.failed = None;
Ok(())
}
Err(e) => {
let _ = std::fs::remove_file(&self.tmp);
Err(e)
}
}
}
fn read(&mut self) -> io::Result<Option<Vec<u8>>> {
let mut bytes = match std::fs::read(&self.path) {
Ok(b) => b,
Err(e) if e.kind() == io::ErrorKind::NotFound && self.held.is_empty() => return Ok(None),
Err(e) if e.kind() == io::ErrorKind::NotFound => Vec::new(),
Err(e) => return Err(e),
};
if let Some(g) = self.good {
bytes.truncate(usize::try_from(g).unwrap_or(usize::MAX));
}
bytes.extend_from_slice(&self.held);
Ok(Some(bytes))
}
fn publish(&self, shared: &Mutex<Shared>) {
let mut sh = shared.lock().unwrap_or_else(PoisonError::into_inner);
sh.failed = self.failed.clone().filter(|_| !self.held.is_empty());
sh.held_records = if sh.failed.is_some() { lines(&self.held) } else { 0 };
}
fn run(&mut self, rx: &Receiver<Msg>, shared: &Mutex<Shared>) {
loop {
let first = if self.failed.is_some() && !self.held.is_empty() {
match rx.recv_timeout(RETRY) {
Ok(m) => Some(m),
Err(RecvTimeoutError::Timeout) => None,
Err(RecvTimeoutError::Disconnected) => break,
}
} else {
match rx.recv() {
Ok(m) => Some(m),
Err(_) => break,
}
};
let mut batch: Vec<Msg> = first.into_iter().collect();
while let Ok(m) = rx.try_recv() {
batch.push(m);
}
let mut flushes = Vec::new();
for m in batch {
match m {
Msg::Append(data) => self.held.extend_from_slice(&data),
// (published before the reply: the caller reads what it left at once)
Msg::Truncate(len, reply) => {
let r = self.truncate(len);
self.publish(shared);
let _ = reply.send(r);
}
Msg::Replace(data, reply) => {
let r = self.replace(&data);
self.publish(shared);
let _ = reply.send(r);
}
Msg::Read(reply) => {
let _ = reply.send(self.read());
}
Msg::Flush(reply) => flushes.push(reply),
}
}
self.step();
self.publish(shared);
for r in flushes {
let _ = r.send(match &self.failed {
Some(why) if !self.held.is_empty() => Err(not_written(why)),
_ => Ok(()),
});
}
}
// the store is closing: everything handed over gets one more try
self.step();
self.publish(shared);
if !self.held.is_empty() {
log::error!("catalog: {} record(s) could not be written to {} (the closing snapshot holds them)", lines(&self.held), self.path.display());
}
}
/// Write what is held; a failure is kept (and logged when it is new).
fn step(&mut self) {
match self.write_held() {
Ok(()) => {
if self.failed.take().is_some() {
log::info!("catalog: {} written again", self.path.display());
}
}
Err(e) => {
let why = e.to_string();
if self.failed.as_deref() != Some(why.as_str()) {
log::error!("catalog: {}: {why} ({} record(s) held, retried)", self.path.display(), lines(&self.held));
}
self.failed = Some(why);
}
}
}
}
+3 -1
View File
@@ -332,7 +332,9 @@ pub struct Analysis {
/// file's white balance is edited relative to its as-shot look or in Kelvin depends on the camera:
/// [`relative_wb_camera`].
pub fn relative_wb_format(format: &str) -> bool {
["ARW", "NEF", "NRW", "RW2", "RWL", "RAW", "RAF", "CR3", "CR2", "PEF", "SRW", "ORF", "ERF", "MRW"].iter().any(|f| format.eq_ignore_ascii_case(f))
["ARW", "NEF", "NRW", "RW2", "RWL", "RAW", "RAF", "CR3", "CR2", "PEF", "SRW", "ORF", "ERF", "MRW", "CRW"]
.iter()
.any(|f| format.eq_ignore_ascii_case(f))
}
/// Whether a raw of `format` shot on `camera` (Exif make and model, as [`Meta::camera`] keeps them) is developed
+100 -6
View File
@@ -28,7 +28,9 @@ pub trait Store: Send {
self.write_atomic(name, &buf)?;
Ok(buf.len() as u64)
}
/// Append and make durable (fsync) before returning. On an error, part of `data` may have
/// Append and make durable (fsync): before returning, or, natively, by the store's own log
/// thread right after ([`FsStore`]: a write that fails is returned by a later append, and a
/// read through the store sees every byte handed over). On an error, part of `data` may have
/// been written (a full disk, a dropped network share): the journal cuts the file back to its
/// previous length with [`Store::truncate`] before appending again.
fn append(&mut self, name: &str, data: &[u8]) -> io::Result<()>;
@@ -43,12 +45,23 @@ pub trait Store: Send {
fn background_writer(&self) -> Option<Box<dyn Store>> {
None
}
/// Wait until every append handed over is in the file and synced ([`FsStore`] writes them on a
/// thread of its own; the default has nothing to wait for). An error says why some aren't: they
/// are still held and retried, never dropped.
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
/// Records handed over by [`Store::append`] that can't be written yet (a write or sync on the
/// store's own thread failed: they are held and retried), and why. `None`: nothing held back.
fn unwritten(&self) -> Option<(usize, String)> {
None
}
}
/// Appends and truncates open the name's own file, so anything else at the name is the library's
/// problem: a link planted there redirects the write outside the directory (CWE-59), and a device
/// hangs the open. Refused with an error the open can show, before anything is written through.
fn check_regular_directory_entry(path: &Path) -> io::Result<()> {
pub(crate) fn check_regular_directory_entry(path: &Path) -> io::Result<()> {
match std::fs::symlink_metadata(path) {
Ok(md) if md.is_file() => Ok(()),
Ok(md) => Err(io::Error::other(format!("{} is a {:?}, not a regular file", path.display(), md.file_type()))),
@@ -60,15 +73,24 @@ fn check_regular_directory_entry(path: &Path) -> io::Result<()> {
/// Files in a directory.
pub struct FsStore {
dir: PathBuf,
/// Open append handle (kept between appends; dropped on rewrite/truncate).
/// Open append handle (kept between appends; dropped on rewrite/truncate). Used when no thread
/// writes the log (the browser build, or one that couldn't start).
appender: Option<(String, std::fs::File)>,
/// The thread that writes the log (natively; started by the first append).
#[cfg(not(target_arch = "wasm32"))]
log: Option<crate::log_writer::LogWriter>,
}
impl FsStore {
/// Use `dir` (created if missing).
pub fn open(dir: impl AsRef<Path>) -> io::Result<FsStore> {
std::fs::create_dir_all(dir.as_ref())?;
Ok(FsStore { dir: dir.as_ref().to_path_buf(), appender: None })
Ok(FsStore {
dir: dir.as_ref().to_path_buf(),
appender: None,
#[cfg(not(target_arch = "wasm32"))]
log: None,
})
}
pub fn dir(&self) -> &Path {
&self.dir
@@ -76,6 +98,21 @@ impl FsStore {
fn path(&self, name: &str) -> PathBuf {
self.dir.join(name)
}
/// The log thread, when it writes `name`.
#[cfg(not(target_arch = "wasm32"))]
fn log_for(&self, name: &str) -> Option<&crate::log_writer::LogWriter> {
self.log.as_ref().filter(|w| w.name == name)
}
/// Wait until the log thread has written and synced everything handed to it.
pub fn flush_log(&self) -> io::Result<()> {
#[cfg(not(target_arch = "wasm32"))]
if let Some(w) = &self.log {
return w.flush();
}
Ok(())
}
fn sync_dir(&self) {
// Makes the rename durable on POSIX; opening a directory fails on Windows (where
// `rename` is already journaled by NTFS), so errors are ignored.
@@ -97,6 +134,11 @@ pub(crate) fn create_staging(tmp: &std::path::Path) -> io::Result<std::fs::File>
impl Store for FsStore {
fn read(&mut self, name: &str) -> io::Result<Option<Vec<u8>>> {
#[cfg(not(target_arch = "wasm32"))]
if let Some(w) = self.log_for(name) {
// what was handed over, written or still held
return w.read();
}
match std::fs::read(self.path(name)) {
Ok(b) => Ok(Some(b)),
Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None),
@@ -106,6 +148,13 @@ impl Store for FsStore {
fn write_atomic(&mut self, name: &str, data: &[u8]) -> io::Result<()> {
use std::io::Write;
#[cfg(not(target_arch = "wasm32"))]
if let Some(w) = self.log_for(name) {
// (after the appends handed over before)
w.replace(data)?;
self.sync_dir();
return Ok(());
}
if self.appender.as_ref().is_some_and(|(n, _)| n == name) {
self.appender = None;
}
@@ -122,6 +171,15 @@ impl Store for FsStore {
fn write_atomic_with(&mut self, name: &str, fill: &mut dyn FnMut(&mut dyn io::Write) -> io::Result<()>) -> io::Result<u64> {
use std::io::Write;
#[cfg(not(target_arch = "wasm32"))]
if let Some(w) = self.log_for(name) {
// (the log is small: buffered, and replaced by its thread after the appends before)
let mut buf = Vec::new();
fill(&mut buf)?;
w.replace(&buf)?;
self.sync_dir();
return Ok(buf.len() as u64);
}
if self.appender.as_ref().is_some_and(|(n, _)| n == name) {
self.appender = None;
}
@@ -148,6 +206,23 @@ impl Store for FsStore {
fn append(&mut self, name: &str, data: &[u8]) -> io::Result<()> {
use std::io::Write;
#[cfg(not(target_arch = "wasm32"))]
{
if self.log.is_none() && !crate::fault::on_caller(&self.dir) {
check_regular_directory_entry(&self.path(name))?;
if !self.path(name).exists() {
// created here, so the open's errors are this append's and its entry is durable
std::fs::OpenOptions::new().create(true).append(true).open(self.path(name))?;
self.sync_dir();
}
self.appender = None;
self.log = crate::log_writer::LogWriter::start(self.dir.clone(), name);
}
// (another name than the log's is written here, as without a thread)
if let Some(w) = self.log_for(name) {
return w.append(data);
}
}
if self.appender.as_ref().is_none_or(|(n, _)| n != name) {
check_regular_directory_entry(&self.path(name))?;
let existed = self.path(name).exists();
@@ -158,6 +233,12 @@ impl Store for FsStore {
self.appender = Some((name.to_string(), f));
}
let Some((_, f)) = self.appender.as_mut() else { return Err(io::Error::other("appender not open")) };
#[cfg(not(target_arch = "wasm32"))]
let written = crate::fault::check(&self.dir, crate::fault::Step::Write)
.and_then(|()| f.write_all(data))
.and_then(|()| crate::fault::check(&self.dir, crate::fault::Step::Sync))
.and_then(|()| f.sync_data());
#[cfg(target_arch = "wasm32")]
let written = f.write_all(data).and_then(|()| f.sync_data());
if written.is_err() {
// The handle may be dead (a network share that reconnected, a removed volume): the next
@@ -169,6 +250,10 @@ impl Store for FsStore {
}
fn truncate(&mut self, name: &str, len: u64) -> io::Result<()> {
#[cfg(not(target_arch = "wasm32"))]
if let Some(w) = self.log_for(name) {
return w.truncate(len);
}
if self.appender.as_ref().is_some_and(|(n, _)| n == name) {
self.appender = None;
}
@@ -189,7 +274,16 @@ impl Store for FsStore {
#[cfg(not(target_arch = "wasm32"))]
fn background_writer(&self) -> Option<Box<dyn Store>> {
Some(Box::new(FsStore { dir: self.dir.clone(), appender: None }))
Some(Box::new(FsStore { dir: self.dir.clone(), appender: None, log: None }))
}
fn flush(&mut self) -> io::Result<()> {
self.flush_log()
}
#[cfg(not(target_arch = "wasm32"))]
fn unwritten(&self) -> Option<(usize, String)> {
self.log.as_ref().and_then(|w| w.unwritten())
}
}
@@ -256,13 +350,13 @@ impl Store for MemStore {
}
}
// (its one test plants a symlink, so the module is Unix-only: elsewhere `use super::*` would be unused)
#[cfg(all(test, unix))]
mod tests_staging {
use super::*;
/// A link planted at a staging name (`<name>.tmp`) is removed, never followed: the file it points to keeps its
/// bytes and the save still lands (issue #1502).
#[cfg(unix)]
#[test]
fn a_link_at_the_staging_name_is_never_written_through() {
let dir = std::env::temp_dir().join(format!("lc-staging-link-{}", std::process::id()));
+2 -1
View File
@@ -636,7 +636,8 @@ fn set_embedded_lens_is_undoable_and_journaled() {
photo: Box::new(Photo::new(a, Source::File { path: "/x.rw2".into() }, "x.rw2", "RW2", 4000, 3000, "2026-10-06T00:00:00")),
})
.unwrap();
let lens = lightcraft_develop::EmbeddedLens { warp: Some(Default::default()), vignette: None, stages: Default::default() };
let lens =
lightcraft_develop::EmbeddedLens { warp: Some(Default::default()), vignette: None, stages: Default::default(), source: Default::default() };
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();
+2 -1
View File
@@ -269,9 +269,10 @@ fn fs_store_background_snapshot() {
}
// a previous crash mid-snapshot left a partial temp file
std::fs::write(dir.join(format!("{SNAPSHOT}.tmp")), b"{\"format\":\"lightcraft-catal").unwrap();
// (closed first: its log thread writes what was handed over)
drop(j);
let (mut j2, c2, r) = Journal::open(Box::new(FsStore::open(&dir).unwrap())).unwrap();
assert_eq!((c2.to_snapshot(), r.snapshot_seq), (live.to_snapshot(), 0));
drop(j);
let n = j2.seq();
j2.snapshot_in_background(&live).unwrap();
for k in 200..260 {
+2 -2
View File
@@ -238,8 +238,8 @@ fn op_variants_are_versioned() {
Op::SetHistoryCursor { .. } => 8,
}
}
/// v9: `Photo.preview_checked` and `Op::SetContent.preview_checked`.
const NEWEST_FIELDS: u32 = 9;
/// v11: `EmbeddedLens.source` (v10: `Mask.on_photo`; v9: `Photo.preview_checked` and `Op::SetContent.preview_checked`).
const NEWEST_FIELDS: u32 = 11;
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");
}
+232
View File
@@ -0,0 +1,232 @@
//! PERF-STEP-STALL: the catalog log's own thread ([`crate::log_writer`]). Appends return at once
//! however slow the drive is; everything handed over is written in order; a write that fails is
//! held, reported and retried, never dropped, and the log never has a gap.
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::time::{Duration, Instant};
use crate::fault::{self, Step};
use crate::store::{FsStore, Store};
const LOG: &str = "catalog.log";
fn temp_dir(tag: &str) -> std::path::PathBuf {
let d = std::env::temp_dir().join(format!("lc-log-thread-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
d
}
fn wait_until(what: &str, mut done: impl FnMut() -> bool) {
let t = Instant::now();
while !done() {
assert!(t.elapsed() < Duration::from_secs(20), "{what}");
std::thread::sleep(Duration::from_millis(10));
}
}
/// Appends are written by the thread in order; a read through the store sees every one; a cut
/// and a replace come after the appends before them; dropping the store writes what is left.
#[test]
fn appends_are_written_in_order_and_cuts_and_replaces_come_after_them() {
let dir = temp_dir("order");
let mut store = FsStore::open(&dir).unwrap();
let mut want = Vec::new();
for i in 0..200u32 {
let line = format!("{i}\n");
store.append(LOG, line.as_bytes()).unwrap();
want.extend_from_slice(line.as_bytes());
if i % 50 == 0 {
assert_eq!(store.read(LOG).unwrap().unwrap(), want, "all of it, through the store");
}
}
store.flush().unwrap();
assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), want, "all of it, in the file");
store.truncate(LOG, 4).unwrap();
assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), b"0\n1\n");
// never longer than it is
store.truncate(LOG, 400).unwrap();
assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), b"0\n1\n");
store.append(LOG, b"x\n").unwrap();
store.write_atomic(LOG, b"tail\n").unwrap();
assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), b"tail\n");
store.append(LOG, b"more\n").unwrap();
drop(store);
assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), b"tail\nmore\n");
let _ = std::fs::remove_dir_all(&dir);
}
/// (a) Each sync takes 300 ms: 100 appends still return at once, and a flush then finds all of
/// them in the file (before, each append waited for its own sync: 30 s for these).
#[test]
fn an_append_never_waits_for_a_slow_sync() {
let dir = temp_dir("slow");
let mut store = FsStore::open(&dir).unwrap();
store.append(LOG, b"first\n").unwrap();
let syncs = Arc::new(AtomicUsize::new(0));
let n = syncs.clone();
fault::install(
&dir,
Arc::new(move |step| {
if step == Step::Sync {
n.fetch_add(1, Ordering::SeqCst);
std::thread::sleep(Duration::from_millis(300));
}
Ok(())
}),
);
let mut want = b"first\n".to_vec();
let mut slowest = Duration::ZERO;
for i in 0..100u32 {
let line = format!("{i}\n");
let t = Instant::now();
store.append(LOG, line.as_bytes()).unwrap();
slowest = slowest.max(t.elapsed());
want.extend_from_slice(line.as_bytes());
std::thread::sleep(Duration::from_millis(2));
}
assert!(slowest < Duration::from_millis(50), "an append waited {slowest:?}");
store.flush().unwrap();
assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), want);
// batched: far fewer syncs than appends
assert!(syncs.load(Ordering::SeqCst) < 50, "{} syncs", syncs.load(Ordering::SeqCst));
fault::remove(&dir);
let _ = std::fs::remove_dir_all(&dir);
}
/// (c) Writes fail for a while: what was handed over is held (reported, with the reason), later
/// appends are refused so the caller keeps them, and once writes work again the held bytes land,
/// in order, with no fragment of the failed attempts and no gap.
#[test]
fn a_failed_write_is_held_reported_and_retried() {
let dir = temp_dir("fail");
let mut store = FsStore::open(&dir).unwrap();
store.append(LOG, b"0\n").unwrap();
store.flush().unwrap();
let fail = Arc::new(AtomicBool::new(true));
let f = fail.clone();
fault::install(&dir, Arc::new(move |_| if f.load(Ordering::SeqCst) { Err(std::io::Error::other("disk full (test)")) } else { Ok(()) }));
// (one append: the log thread can fail the first before a second arrives, and then refuses it)
store.append(LOG, b"1\n2\n").unwrap();
wait_until("the failure is published", || store.unwritten().is_some());
let (held, why) = store.unwritten().unwrap();
assert!(why.contains("disk full"), "{why}");
assert!(held >= 1, "{held}");
let refused = store.append(LOG, b"3\n");
assert!(refused.is_err(), "refused while held");
assert!(store.flush().is_err(), "a flush says it isn't written");
// a read through the store still sees what was handed over
assert_eq!(store.read(LOG).unwrap().unwrap(), b"0\n1\n2\n");
// a cut within what is held keeps it (the journal cuts back to its own length on an error)
store.truncate(LOG, 6).unwrap();
assert_eq!(store.read(LOG).unwrap().unwrap(), b"0\n1\n2\n");
// a fragment of a failed write left in the file is cut before the retry
{
use std::io::Write;
let mut file = std::fs::OpenOptions::new().append(true).open(dir.join(LOG)).unwrap();
file.write_all(b"{\"seq\":").unwrap();
}
fail.store(false, Ordering::SeqCst);
wait_until("retried on its own", || store.unwritten().is_none());
store.append(LOG, b"3\n").unwrap();
store.flush().unwrap();
assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), b"0\n1\n2\n3\n");
fault::remove(&dir);
let _ = std::fs::remove_dir_all(&dir);
}
/// (b, c) Through the journal: ops appended while the drive is slow or failing all reopen, and a
/// journal over a log that failed has no gap (no damage on load).
#[test]
fn the_journal_reopens_every_op_after_a_slow_then_failing_drive() {
use crate::{Catalog, Journal, Op, Photo, PhotoId, Source};
let dir = temp_dir("journal");
let (mut j, mut c, _) = Journal::open(Box::new(FsStore::open(&dir).unwrap())).unwrap();
let fail = Arc::new(AtomicBool::new(false));
let f = fail.clone();
fault::install(
&dir,
Arc::new(move |step| {
if f.load(Ordering::SeqCst) {
return Err(std::io::Error::other("network share dropped (test)"));
}
if step == Step::Sync {
std::thread::sleep(Duration::from_millis(40));
}
Ok(())
}),
);
let mut queued: Vec<Op> = Vec::new();
for id in 1..=60u64 {
if id == 20 {
fail.store(true, Ordering::SeqCst);
}
if id == 40 {
fail.store(false, Ordering::SeqCst);
}
let p = Photo::new(PhotoId(id), Source::Demo { scene: 0 }, &format!("p{id}.jpg"), "JPEG", 4, 3, "2026-11-02");
let op = Op::AddPhoto { photo: Box::new(p) };
c.apply(op.clone()).unwrap();
queued.push(op);
// as the engine does: a failed append keeps its ops queued for the next one
if j.append(&queued).is_ok() {
queued.clear();
}
std::thread::sleep(Duration::from_millis(5));
}
wait_until("everything written", || {
if !queued.is_empty() && j.append(&queued).is_ok() {
queued.clear();
}
queued.is_empty() && j.unwritten().is_none()
});
j.flush().unwrap();
let expect = c.to_snapshot();
drop(j);
fault::remove(&dir);
let (_, again, report): (_, Catalog, _) = Journal::open(Box::new(FsStore::open(&dir).unwrap())).unwrap();
assert!(report.damaged.is_none(), "{report:?}");
assert_eq!(again.to_snapshot(), expect);
assert_eq!(again.len(), 60);
let _ = std::fs::remove_dir_all(&dir);
}
/// A sync that fails leaves the written bytes past the synced length in the file; a cut to exactly
/// that length removes them from the file too, so they never come back on the next open (review
/// of #3557).
#[test]
fn a_cut_to_the_synced_length_removes_bytes_a_failed_sync_left() {
let dir = temp_dir("cut-synced");
let mut store = FsStore::open(&dir).unwrap();
store
.append(
LOG, b"0
",
)
.unwrap();
store.flush().unwrap();
fault::install(&dir, Arc::new(|step| if step == Step::Sync { Err(std::io::Error::other("sync failed (test)")) } else { Ok(()) }));
store
.append(
LOG, b"1
",
)
.unwrap();
wait_until("the failure is published", || store.unwritten().is_some());
assert_eq!(
std::fs::read(dir.join(LOG)).unwrap(),
b"0
1
",
"written, not synced"
);
store.truncate(LOG, 2).unwrap();
fault::remove(&dir);
drop(store);
assert_eq!(
std::fs::read(dir.join(LOG)).unwrap(),
b"0
"
);
let _ = std::fs::remove_dir_all(&dir);
}
+3
View File
@@ -88,6 +88,9 @@ fn partial_append_then_retry_loads_cleanly() {
assert!(j.append(&batch).is_err(), "tear at {tear}");
// cut back to the last whole record
assert_eq!(t.files.get(LOG).unwrap().len(), good_len, "tear at {tear}");
// and a snapshot is due (records handed over before may be missing from a log written
// by a thread of its own: note 2 of 2026-10-25)
assert!(j.wants_snapshot(), "tear at {tear}");
j.append(&batch).unwrap();
let more = apply(&mut c, vec![Op::SetLabel { id, label: Some(ColorLabel::ALL[0]) }]);
j.append(&more).unwrap();
+4 -1
View File
@@ -55,5 +55,8 @@ fn a_file_path_rule_allocates_nothing_per_photo() {
}
let blocks = dhat::HeapStats::get().total_blocks - before;
assert!(hits > 0, "the rules matched nothing: the test measures nothing");
assert_eq!(blocks, 0, "{blocks} heap blocks for {} rule tests", 100 * rules.len() * photos.len());
// dhat counts every thread, and the test harness's own thread can allocate a few blocks while this
// runs. An allocation per photo would be thousands, two per rule test.
let tests = 100 * rules.len() * photos.len();
assert!(blocks < 64, "{blocks} heap blocks for {tests} rule tests");
}
+20 -1
View File
@@ -160,7 +160,10 @@ pub fn write(path: &Path, img: &Rgb32f, key: &str) -> Result<(), ProductError> {
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir)?;
}
let mut f = std::io::BufWriter::new(std::fs::File::create(&tmp)?);
// a new temp file: an entry already under the name (a link planted in the cache folder
// would be written through) is removed, never opened
let _ = std::fs::remove_file(&tmp);
let mut f = std::io::BufWriter::new(std::fs::OpenOptions::new().write(true).create_new(true).open(&tmp)?);
f.write_all(MAGIC)?;
f.write_all(&[VERSION, 0, 0, 0])?;
f.write_all(&(header.len() as u32).to_le_bytes())?;
@@ -459,6 +462,22 @@ mod tests {
std::env::temp_dir().join(format!("lc-denoise-{name}-{}.lcdn", std::process::id()))
}
#[cfg(unix)]
#[test]
fn a_link_planted_under_the_temp_name_is_not_written_through() {
let p = temp("planted");
let victim = temp("victim");
std::fs::write(&victim, b"keep").unwrap();
let _ = std::fs::remove_file(p.with_extension("tmp"));
std::os::unix::fs::symlink(&victim, p.with_extension("tmp")).unwrap();
write(&p, &picture(16, 4), "k").unwrap();
assert_eq!(std::fs::read(&victim).unwrap(), b"keep");
assert!(read_header_at(&p).is_ok());
for f in [p, victim] {
let _ = std::fs::remove_file(f);
}
}
fn picture(w: usize, h: usize) -> Rgb32f {
Rgb32f {
width: w,
+52 -3
View File
@@ -84,17 +84,25 @@ pub enum Process {
/// Highlights and Shadows keep the local contrast of the tones they move: their edge-aware base
/// is taken of a fine median of log luminance (issue #632).
V2,
/// Pixel-scale sharpening with working Radius and Detail controls.
V3,
/// V3, with Contrast and Blacks on a raw's camera look calibrated to Lightroom: the
/// camera curve keeps V2 Whites and fitted pointwise operators follow it
/// (`lightcraft_pipeline::light_v3`, `docs/light-v3.md`).
V4,
}
impl Process {
/// Every process, oldest first.
pub const ALL: [Process; 2] = [Process::V1, Process::V2];
pub const LATEST: Process = Process::V2;
pub const ALL: [Process; 4] = [Process::V1, Process::V2, Process::V3, Process::V4];
pub const LATEST: Process = Process::V4;
pub const fn version(self) -> ProcessVersion {
match self {
Process::V1 => ProcessVersion(1),
Process::V2 => ProcessVersion(2),
Process::V3 => ProcessVersion(3),
Process::V4 => ProcessVersion(4),
}
}
}
@@ -699,11 +707,32 @@ impl Default for Optics {
pub struct EmbeddedLens {
pub warp: Option<EmbeddedWarp>,
pub vignette: Option<EmbeddedVignette>,
/// Where the correction came from: the file itself, or a lens database looked up by the
/// lens named in the file (what the Optics panel says is loaded).
#[serde(skip_serializing_if = "LensSource::is_file")]
pub source: LensSource,
/// A DNG 1.6 `WarpRectilinear2` chain (up to [`WARP_STAGES`] stages, in `OpcodeList3` order; each stage warps
/// the result of the one before it). When any is set, `warp` is `None`: the chain holds every warp opcode.
pub stages: [Option<EmbeddedWarpStage>; WARP_STAGES],
}
/// Where an [`EmbeddedLens`] came from.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum LensSource {
/// The file's own correction (DNG opcodes, a camera's correction a raw reader converts).
#[default]
File,
/// A profile from a lensfun-format lens database, matched by the lens named in the file.
Database,
}
impl LensSource {
pub fn is_file(&self) -> bool {
*self == LensSource::File
}
}
/// Most warp stages an [`EmbeddedLens`] chain keeps.
pub const WARP_STAGES: usize = 3;
@@ -1054,15 +1083,35 @@ pub struct Mask {
/// Refine Edges 0..100: the mask's edges snap to the photo's (guided filter).
#[serde(skip_serializing_if = "is_zero")]
pub refine: f64,
/// Where its coordinates (gradients, brush strokes, AI selections) live: `true`, on the photo as
/// shot (user orientation, before lens corrections, Upright and Transform), so the mask stays
/// on the same content whatever those do; `false`, a mask from before that, on the corrected
/// frame. Read as `false` when absent; [`Mask::default`] (every new mask) is `true`, and an
/// edit converts an old one (`lightcraft_pipeline::mask_space::attach`).
#[serde(default, skip_serializing_if = "is_false")]
pub on_photo: bool,
}
fn is_zero(v: &f64) -> bool {
*v == 0.0
}
fn is_false(v: &bool) -> bool {
!*v
}
impl Default for Mask {
fn default() -> Self {
Self { id: 0, name: "Mask 1".into(), visible: true, invert: false, components: Vec::new(), adjust: LocalAdjustments::default(), refine: 0.0 }
Self {
id: 0,
name: "Mask 1".into(),
visible: true,
invert: false,
components: Vec::new(),
adjust: LocalAdjustments::default(),
refine: 0.0,
on_photo: true,
}
}
}
+1
View File
@@ -40,6 +40,7 @@ log = { workspace = true }
ab_glyph = { workspace = true }
# Apply the font’s vertical substitutions and origins to Japanese watermarks.
harfrust = { version = "0.13", default-features = false, features = ["std"] }
unicode-normalization = "0.1"
unicode-segmentation = "1.13"
lightcraft-segment = { workspace = true, optional = true }
+12 -1
View File
@@ -65,6 +65,7 @@ fn craft_fonts(dir: &Path, required: bool) -> Result<String, String> {
let manifest = dir.join("fonts/manifest.txt");
println!("cargo::rerun-if-changed={}", manifest.display());
let text = std::fs::read_to_string(&manifest).map_err(|e| format!("{}: {e}", manifest.display()))?;
let root = dir.canonicalize().map_err(|e| format!("{}: {e}", dir.display()))?;
let wasm = std::env::var("CARGO_CFG_TARGET_ARCH").is_ok_and(|a| a == "wasm32");
let mut out = String::new();
let mut has_japanese_ui = false;
@@ -82,7 +83,17 @@ fn craft_fonts(dir: &Path, required: bool) -> Result<String, String> {
continue;
}
let path = dir.join(file).canonicalize().map_err(|e| format!("{file}: {e}"))?;
println!("cargo::rerun-if-changed={}", path.display());
// a font is a file of the checkout: a manifest entry or a link reaching outside it would
// embed some other file of the build machine
if !path.starts_with(&root) || !path.is_file() {
return Err(format!("{file}: not a file inside {}", root.display()));
}
let shown = path.display().to_string();
// one cargo instruction per line: a line break in the path would print a second one
if shown.contains(['\n', '\r']) {
return Err(format!("{file}: the path contains a line break"));
}
println!("cargo::rerun-if-changed={shown}");
let scripts: Vec<String> = scripts.split(',').map(|s| format!("{:?}", s.trim())).collect();
let _ = writeln!(
out,
+1 -1
View File
@@ -144,7 +144,7 @@ fn benchmark_load(args: &[String], n: usize, only: &str) {
}
println!(" {:<36} {}", "load_bytes(2560):", best(n, || drop(lightcraft_engine::files::load_bytes(&bytes, 2560).expect("load"))));
let (loader, _) = lightcraft_engine::files::fs_hooks();
println!(" {:<36} {}", "fs loader (2560, read+load):", best(n, || drop(loader(path, 2560).expect("load"))));
println!(" {:<36} {}", "fs loader (2560, read+load):", best(n, || drop(loader(path, 2560, None).expect("load"))));
}
}
@@ -27,6 +27,7 @@ pub(crate) fn file_local_look(format: RawFormat) -> bool {
| RawFormat::Pef
| RawFormat::Srw
| RawFormat::Orf
| RawFormat::Crw
| RawFormat::Mrw
| RawFormat::Erf
)
+8 -4
View File
@@ -1,6 +1,6 @@
//! Camera colour profiles of our own, pooled from many photos of one camera model.
//!
//! A raw file without colour matrices (Sony ARW, Nikon NEF, Fujifilm RAF) gets its look fitted to its own embedded camera
//! A raw file without colour matrices (Sony ARW, Nikon NEF, Fujifilm RAF, Canon CRW) gets its look fitted to its own embedded camera
//! JPEG (`camera_preview`), but one photo shows too little of some colours: a lime shirt covering a
//! few dozen proxy pixels next to a hillside of foliage at the same hue. `lightcraft-cli calibrate`
//! pools the colour pairs of many photos per model and fits one matrix and hue/saturation/value
@@ -25,6 +25,7 @@ const MAX_FILE: u64 = 4 << 20;
/// Profiles built into LightCraft (`assets/camera-profiles/`, see `assets/ATTRIBUTION.md`):
/// `(model, JSON)`.
pub const BUNDLED: &[(&str, &str)] = &[
("Canon EOS D60", include_str!("../../../assets/camera-profiles/Canon_EOS_D60.json")),
("ILCA-99M2", include_str!("../../../assets/camera-profiles/ILCA-99M2.json")),
("ILCE-7CR", include_str!("../../../assets/camera-profiles/ILCE-7CR.json")),
("ILCE-7M4", include_str!("../../../assets/camera-profiles/ILCE-7M4.json")),
@@ -115,9 +116,9 @@ pub fn save(profile: &CameraProfile, dir: &Path) -> Result<PathBuf, String> {
std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
let path = dir.join(file_name(&profile.model));
let json = serde_json::to_vec_pretty(profile).map_err(|e| e.to_string())?;
let tmp = path.with_extension("json.tmp");
std::fs::write(&tmp, json).map_err(|e| format!("{}: {e}", tmp.display()))?;
std::fs::rename(&tmp, &path).map_err(|e| format!("{}: {e}", path.display()))?;
// a fresh temp file renamed over the profile: never a fixed `.tmp` name, which a planted link
// would have written through
lightcraft_catalog::safe_file::write_atomic(&path, &json).map_err(|e| format!("{}: {e}", path.display()))?;
Ok(path)
}
@@ -295,6 +296,9 @@ mod tests {
assert_eq!(bundled(model), Some(p));
}
assert!(bundled("No Such Camera").is_none());
// a model name with spaces is stored under its safe file name
assert!(bundled("Canon EOS D60").is_some_and(|p| p.files > 1000));
assert_eq!(file_name("Canon EOS D60"), "Canon_EOS_D60.json");
}
#[test]
+5
View File
@@ -11,6 +11,7 @@ mod color;
pub(crate) mod convert;
mod cull;
pub mod curves;
pub mod dcp_profiles;
pub(crate) mod denoise;
mod develop;
mod edit;
@@ -22,6 +23,7 @@ pub mod filters;
mod focus;
pub mod geocode;
pub mod keywords;
pub mod lens_refresh;
pub mod library;
pub mod lut_profiles;
pub mod manage;
@@ -39,6 +41,7 @@ mod print;
mod query;
pub mod recheck;
pub mod reload;
pub mod similar;
mod slideshow;
mod sync;
mod xmp;
@@ -152,6 +155,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(manage::specs());
v.extend(previews::specs());
v.extend(lut_profiles::specs());
v.extend(dcp_profiles::specs());
v.extend(mask_effects::specs());
v.extend(cull::specs());
v.extend(convert::specs());
@@ -168,6 +172,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(browse::specs());
v.extend(missing::specs());
v.extend(recheck::specs());
v.extend(lens_refresh::specs());
v.extend(sync::specs());
v.extend(metadata::specs());
v.extend(geocode::specs());
+9 -2
View File
@@ -433,6 +433,7 @@ fn move_to_folder(s: &mut Session, p: &Value) -> Result<Value> {
}
let mut plans: Vec<crate::rename::RenamePlan> = Vec::new();
let mut taken: std::collections::HashSet<String> = std::collections::HashSet::new();
let mut moving: std::collections::HashSet<&str> = std::collections::HashSet::new();
let mut clashes: Vec<String> = Vec::new();
for id in ids {
let ph = s.catalog.photo(id).ok_or_else(|| bad(C, format!("no photo {}", id.0)))?;
@@ -442,7 +443,7 @@ fn move_to_folder(s: &mut Session, p: &Value) -> Result<Value> {
let lightcraft_catalog::Source::File { path } = &ph.source else {
return Err(bad(C, format!("{} has no file on disk", ph.file_name)));
};
if plans.iter().any(|pl| pl.from_path.as_deref() == Some(path.as_str())) {
if !moving.insert(path.as_str()) {
continue; // a virtual copy of a photo already moving
}
let src = Path::new(path);
@@ -521,7 +522,13 @@ pub(crate) fn move_folder(s: &mut Session, from: &str, to: &str) -> std::result:
if !src.is_dir() {
return Err(format!("{from} is not a folder"));
}
if s.library.as_ref().is_some_and(|l| l.dir.starts_with(src) || src.starts_with(&l.dir)) {
// 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)
};
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());
}
// Repairs retain their exact old paths, including those on surviving history entries.
+1
View File
@@ -456,6 +456,7 @@ mod tests {
warp: Some(lightcraft_develop::EmbeddedWarp { planes: [[1.0, -0.1, 0.03, 0.0, 0.0, 0.0]; 3], ..Default::default() }),
vignette: None,
stages: Default::default(),
source: Default::default(),
}
}
fn old_rw2() -> lightcraft_catalog::Photo {
+3 -40
View File
@@ -105,43 +105,6 @@ fn burst_params(p: &Value) -> Result<(f64, f32)> {
Ok((num("burstGap", BURST_GAP, MAX_GAP)?, num("similarity", SAME, 1.0)? as f32))
}
/// Find Similar: photos that look like `id` (signatures from thumbnail-level sources, cached by
/// content), most similar first; the view is filtered to them.
fn find_similar(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "library.findSimilar";
let id = super::photo_id(p, C)?.or(s.active()).ok_or_else(|| super::bad(C, "no photo"))?;
let min = p.get("similarity").and_then(Value::as_f64).unwrap_or(0.8) as f32;
let all: Vec<PhotoId> = s.catalog.photos().filter(|q| q.in_library()).map(|q| q.id).collect();
let sig = |s: &mut Session, id: PhotoId| -> Option<[f32; 64]> {
let key = s.catalog.photo(id).map(|p| crate::media::content_key(p))?;
if let Some(v) = s.signatures.get(&key) {
return Some(*v);
}
let src = s.source_now(id, crate::media::SourceLevel::Thumb).ok()?;
let v = lightcraft_pipeline::cull::signature(&src);
s.signatures.insert(key, v);
Some(v)
};
let me = sig(s, id).ok_or_else(|| super::bad(C, "can't read the photo"))?;
let mut hits: Vec<(PhotoId, f32)> = Vec::new();
for q in all {
if let Some(v) = sig(s, q) {
let sim = lightcraft_pipeline::cull::similarity(&me, &v);
if sim >= min {
hits.push((q, sim.clamp(0.0, 1.0)));
}
}
}
hits.sort_by(|a, b| b.1.total_cmp(&a.1));
if p.get("filter").and_then(Value::as_bool).unwrap_or(true) {
s.shelved_filter = None;
s.filter.only = hits.iter().map(|h| h.0).collect();
// an empty `only` means "no constraint": no hits is its own state that shows no photos
s.filter.only_none = s.filter.only.is_empty();
}
Ok(json!({"photos": hits.iter().map(|(i, v)| json!({"id": i.0, "similarity": (v * 1000.0).round() / 1000.0})).collect::<Vec<_>>()}))
}
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
@@ -149,9 +112,9 @@ pub fn specs() -> Vec<CommandSpec> {
"Find Similar Photos",
["Photo"],
None,
"{id?, similarity?: 0..1 (0.8), filter?: bool (true)} — photos that look like the active one (composition and tones), most similar first; filters the view to them (Clear Filters to go back) → {photos: [{id, similarity}]}",
always,
find_similar
"{id?, similarity?: 0..1 (0.8), filter?: bool (true)} — photos that look like the active one (composition and tones), most similar first; filters the view to them (Clear Filters to go back) → {photos: [{id, similarity}]}. In the app the photos are read on a worker thread under an activity row: a control request is answered with this when the search ends, and from a menu the answer is {background: true, count}",
super::similar::no_search_running,
super::similar::run
),
cmd!(
"photo.analyze",
+212
View File
@@ -0,0 +1,212 @@
//! Imported camera profiles: the user's own DNG Camera Profiles (`.dcp`), chosen like any other
//! profile (`develop.profile {id: "dcp:…"}`). Unlike the built-in looks and LUT profiles, which
//! work on developed colour, a camera profile replaces the raw file's colour model when it is
//! decoded (its matrices and hue/saturation map; see [`lightcraft_raw::dcp`]), so the photo's
//! source is decoded again when it changes. Other photos (JPEG, TIFF…) ignore it.
//!
//! A library on disk keeps a copy of each file in its `Profiles/` folder; the list lives in the
//! library's prefs and the profiles are parsed again when the library opens.
use std::path::{Path, PathBuf};
use serde_json::{Value, json};
use super::{CommandSpec, always, bad, cmd, str_param};
use crate::media::LoadedCameraProfile;
use crate::{Result, Session};
/// Profile id prefix of imported camera profiles.
pub const DCP_PREFIX: &str = "dcp:";
/// Profile browser group of imported camera profiles.
pub const DCP_GROUP: &str = "Camera Profiles";
/// One imported camera profile.
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DcpEntry {
/// `dcp:<slug>`.
pub id: String,
/// `ProfileName`, else the file name.
pub name: String,
/// The camera it was made for (`UniqueCameraModel`).
#[serde(default)]
pub camera_model: String,
/// The `.dcp` file (the library's copy when there is a library on disk).
pub file: String,
}
/// Is `id` an imported camera profile id?
pub fn is_dcp_id(id: &str) -> bool {
id.starts_with(DCP_PREFIX)
}
fn profiles_dir(s: &Session) -> Option<PathBuf> {
s.library.as_ref().filter(|l| l.on_disk).map(|l| l.dir.join("Profiles"))
}
/// Parse every imported camera profile again and hand them to the decoder (missing or damaged
/// files are skipped: photos using them develop with the file's own colour, and the profile is not offered or
/// accepted by `develop.profile` until its file is back; the entry is kept).
///
/// A library's own copies are found in `profiles`, the `Profiles/` folder of the library being opened (`None`: not on
/// disk), wherever the saved path points: a library moved or restored elsewhere keeps its profiles (the saved path is
/// updated).
pub fn register_all(s: &mut Session, profiles: Option<&Path>) {
if let Some(dir) = profiles {
for p in &mut s.dcp_profiles {
if let Some(here) = library_copy(dir, &p.file) {
p.file = here.to_string_lossy().to_string();
}
}
}
let loaded: Vec<(String, LoadedCameraProfile)> = s
.dcp_profiles
.iter()
.filter_map(|p| {
lightcraft_raw::dcp::read_dcp(Path::new(&p.file)).ok().and_then(|b| LoadedCameraProfile::parse(&b).ok()).map(|d| (p.id.clone(), d))
})
.collect();
s.media.camera_profiles = loaded.into_iter().collect();
}
/// The copy of saved profile file `file` in the open library's profiles folder `dir`, when it is there under the
/// same name and `file` is not already it.
fn library_copy(dir: &Path, file: &str) -> Option<PathBuf> {
let saved = Path::new(file);
let here = dir.join(saved.file_name()?);
(here != saved && here.is_file()).then_some(here)
}
/// `.dcp` files under `paths` (folders searched).
pub fn dcp_files(paths: &[String]) -> Vec<PathBuf> {
let is_dcp = |f: &Path| f.extension().is_some_and(|x| x.eq_ignore_ascii_case("dcp"));
let mut out = Vec::new();
for p in paths {
let path = Path::new(p);
if path.is_dir() {
out.extend(crate::walk::files_in(path, None, crate::walk::Limits::default(), is_dcp).files);
} else if is_dcp(path) {
out.push(path.to_path_buf());
}
}
out
}
/// Import the `.dcp` files under `paths` → (imported `[{id, name, cameraModel}]`, failed `[[file, error]]`).
/// A profile already imported (same name, camera and bytes) is not added twice.
pub fn import_files(s: &mut Session, paths: &[String]) -> Result<(Vec<Value>, Vec<Value>)> {
const C: &str = "profile.import";
let dir = profiles_dir(s);
if let Some(d) = &dir {
std::fs::create_dir_all(d).map_err(|e| bad(C, format!("{}: {e}", d.display())))?;
}
let (mut imported, mut failed) = (Vec::new(), Vec::new());
for f in dcp_files(paths) {
let shown = f.display().to_string();
let bytes = match lightcraft_raw::dcp::read_dcp(&f) {
Ok(b) => b,
Err(e) => {
failed.push(json!([shown, e.to_string()]));
continue;
}
};
let loaded = match LoadedCameraProfile::parse(&bytes) {
Ok(p) => p,
Err(e) => {
failed.push(json!([shown, e.to_string()]));
continue;
}
};
let profile = loaded.profile.clone();
let stem = f.file_stem().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "Camera Profile".into());
let name = if profile.name.trim().is_empty() { stem.clone() } else { profile.name.trim().to_string() };
// the same profile imported again: keep the one there is
let same = s.dcp_profiles.iter().find(|p| {
p.name == name && p.camera_model == profile.camera_model && lightcraft_raw::dcp::read_dcp(Path::new(&p.file)).is_ok_and(|b| b == bytes)
});
if let Some(p) = same {
imported.push(json!({"id": p.id, "name": p.name, "cameraModel": p.camera_model, "existing": true}));
continue;
}
// (the file name keeps profiles with the same ProfileName apart, e.g. per-body copies)
let slug = crate::presets::slug(&format!("{}-{stem}", profile.camera_model));
let mut id = format!("{DCP_PREFIX}{slug}");
let mut n = 2;
while s.dcp_profiles.iter().any(|x| x.id == id) {
id = format!("{DCP_PREFIX}{slug}-{n}");
n += 1;
}
let file = match &dir {
Some(d) => {
let to = d.join(format!("{}.dcp", id.trim_start_matches(DCP_PREFIX)));
// a copy that fails (disk full, no access) fails this file only: the profiles
// copied before it stay imported, and nothing half-written is left behind
if let Err(e) = std::fs::write(&to, &bytes) {
if to.is_file() {
let _ = std::fs::remove_file(&to);
}
failed.push(json!([shown, format!("{}: {e}", to.display())]));
continue;
}
to.to_string_lossy().to_string()
}
// no library on disk: remember the original (the in-memory session ends with the app)
None => f.to_string_lossy().to_string(),
};
s.media.camera_profiles.insert(id.clone(), loaded);
s.dcp_profiles.push(DcpEntry { id: id.clone(), name: name.clone(), camera_model: profile.camera_model.clone(), file });
imported.push(json!({"id": id, "name": name, "cameraModel": profile.camera_model}));
}
Ok((imported, failed))
}
fn delete(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "profile.deleteCamera";
let id = str_param(p, "id").ok_or_else(|| bad(C, "missing id"))?.to_string();
let Some(i) = s.dcp_profiles.iter().position(|x| x.id == id) else {
return Err(bad(C, format!("no imported camera profile `{id}`")));
};
// the library's copy goes first; a file outside the library is the user's and stays. A copy that can't be
// removed (in use, no access) keeps the profile, so the library never holds a file it no longer lists. A path
// with `..` in it is never the library's copy (it could lead out of the profiles folder).
if let Some(d) = profiles_dir(s)
&& let Some(entry) = s.dcp_profiles.get(i)
&& Path::new(&entry.file).starts_with(&d)
&& !Path::new(&entry.file).components().any(|c| c == std::path::Component::ParentDir)
{
match std::fs::remove_file(&entry.file) {
Ok(()) => {}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => return Err(bad(C, format!("could not delete {}: {e}", entry.file))),
}
}
s.dcp_profiles.remove(i);
s.media.camera_profiles.remove(&id);
s.profile_favorites.retain(|f| f != &id);
s.profile_recent.retain(|f| f != &id);
s.save_prefs()?;
Ok(json!({"deleted": id}))
}
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
query "profiles.camera",
"Imported Camera Profiles",
[],
None,
"{} → {profiles: [{id, name, cameraModel, file}]}: the imported .dcp camera profiles (use with develop.profile)",
always,
|s, _| Ok(json!({"profiles": s.dcp_profiles}))
),
cmd!(
"profile.deleteCamera",
"Delete Imported Camera Profile",
[],
None,
"{id: dcp:…} — photos using it develop with their file's own colour again",
always,
delete
),
]
}
+10 -2
View File
@@ -557,9 +557,17 @@ pub fn specs() -> Vec<CommandSpec> {
}),
cmd!("develop.profile", "Set Profile", [], None, "{id: profile id (see profiles.list), amount?: 0..200}", has_active, |s, p| {
let id = str_param(p, "id").ok_or_else(|| bad("develop.profile", "missing id"))?.to_string();
if !crate::presets::PROFILES.iter().any(|x| x.id == id) && !s.lut_profiles.iter().any(|x| x.id == id) {
if !crate::presets::PROFILES.iter().any(|x| x.id == id)
&& !s.lut_profiles.iter().any(|x| x.id == id)
&& !s.dcp_profiles.iter().any(|x| x.id == id)
{
return Err(bad("develop.profile", format!("unknown profile `{id}`")));
}
// an imported camera profile whose file is missing or damaged: choosing it would develop with the
// file's own colour without saying so
if crate::cmd::dcp_profiles::is_dcp_id(&id) && !s.media.camera_profiles.contains_key(&id) {
return Err(bad("develop.profile", format!("camera profile `{id}` can't be used: its file is missing or damaged")));
}
edit(s, "develop.profile", "Profile", |d| {
d.profile.id = id.clone();
d.profile.amount = f64_or(p, "amount", d.profile.amount).clamp(0.0, 200.0);
@@ -570,7 +578,7 @@ pub fn specs() -> Vec<CommandSpec> {
}),
cmd!("profile.favorite", "Favorite Profile", [], None, "{id, favorite?: bool} (toggles when omitted)", always, |s, p| {
let id = str_param(p, "id").ok_or_else(|| bad("profile.favorite", "missing id"))?.to_string();
if crate::presets::profile(&id).is_none() && !s.lut_profiles.iter().any(|x| x.id == id) {
if crate::presets::profile(&id).is_none() && !s.lut_profiles.iter().any(|x| x.id == id) && !s.dcp_profiles.iter().any(|x| x.id == id) {
return Err(bad("profile.favorite", format!("unknown profile `{id}`")));
}
let on = s.profile_favorites.contains(&id);
+75 -10
View File
@@ -47,6 +47,10 @@ pub struct PlaceNames {
shared: Arc<Mutex<DownloadShared>>,
/// (cities file, its size, its modification time, the parsed names).
cache: Option<(PathBuf, u64, Option<SystemTime>, Arc<GeoNames>)>,
/// (folder, server) a download goes to instead of `<settings>/geonames` and GeoNames. Only
/// tests set it: no command can, so a client never chooses where the files land (#2575).
#[cfg(not(target_arch = "wasm32"))]
download_to: Option<(PathBuf, String)>,
}
impl PlaceNames {
@@ -188,10 +192,7 @@ mod download {
use lightcraft_geocode::{GEONAMES_BASE, GEONAMES_ZIP};
use super::{
Cancel, DownloadOutcome, GEONAMES_ATTRIBUTION, GEONAMES_FILES, GeoNames, PoisonError, Result, Session, Value, bad, dataset_dir, json,
str_param,
};
use super::{Cancel, DownloadOutcome, GEONAMES_ATTRIBUTION, GEONAMES_FILES, GeoNames, PoisonError, Result, Session, Value, bad, json};
use crate::activity::Unit;
const MAX_ZIP: u64 = 64 * 1024 * 1024;
@@ -218,7 +219,11 @@ mod download {
return Err("the downloaded place list is empty".into());
}
let _ = std::fs::remove_file(staging.join(GEONAMES_ZIP));
let write = |name: &str, data: &[u8]| std::fs::write(dir.join(name), data).map_err(|e| format!("could not save {name}: {e}"));
// a temp file renamed over the old one: never half-written, and a link in its place is
// replaced, not written through (#2575); not synced, as a download can always be repeated
let write = |name: &str, data: &[u8]| {
lightcraft_catalog::safe_file::write_atomic_nosync(&dir.join(name), data).map_err(|e| format!("could not save {name}: {e}"))
};
for name in &GEONAMES_FILES[1..] {
// optional: without them states stay blank and countries are ISO codes
match get(name, base, &staging, cancel, task).and_then(|()| std::fs::read(staging.join(name)).map_err(|e| e.to_string())) {
@@ -241,10 +246,21 @@ mod download {
}
/// `metadata.downloadPlaceNames`: starts a background download (shown in the activity stack, cancellable).
/// The files always go to `<settings>/geonames`, from GeoNames: a control or MCP client naming a
/// folder (`dataset`) or a server (`base`) could have written a server's bytes into any folder (#2575).
pub(super) fn start(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "metadata.downloadPlaceNames";
let dir = dataset_dir(p).ok_or_else(|| bad(C, "no settings folder: give `dataset`"))?;
let base = str_param(p, "base").unwrap_or(GEONAMES_BASE).to_string();
if p.get("dataset").is_some() || p.get("base").is_some() {
return Err(bad(C, "the place names always download from GeoNames into the settings folder: `dataset` and `base` are not accepted"));
}
let target = s.place_names.download_to.clone();
let (dir, base) = match target {
Some(t) => t,
None => (
crate::config::config_dir().ok_or_else(|| bad(C, "no settings folder to save the place names in"))?.join("geonames"),
GEONAMES_BASE.to_string(),
),
};
if !base_allowed(&base) {
return Err(bad(C, "`base` must be an https:// address"));
}
@@ -309,7 +325,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Download Place Names (GeoNames)",
["Photo"],
None,
"{dataset?: folder} → {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; no photo data is sent",
"{} → {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,
download::start
));
@@ -468,7 +484,8 @@ mod tests {
#[cfg(not(target_arch = "wasm32"))]
fn download(s: &mut Session, base: &str, dir: &Path) -> DownloadOutcome {
s.execute("metadata.downloadPlaceNames", &json!({"dataset": dir, "base": base})).unwrap();
s.place_names.download_to = Some((dir.to_path_buf(), base.to_string()));
s.execute("metadata.downloadPlaceNames", &json!({})).unwrap();
assert!(s.place_names.downloading() || s.place_names.lock().unreported.is_some());
let started = std::time::Instant::now();
loop {
@@ -493,7 +510,8 @@ mod tests {
let base = serve();
let dir = std::env::temp_dir().join(format!("lightcraft-geocode-dl-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
assert!(s.execute("metadata.downloadPlaceNames", &json!({"dataset": dir, "base": "http://example.com/"})).is_err());
s.place_names.download_to = Some((dir.clone(), "http://example.com/".into()));
assert!(s.execute("metadata.downloadPlaceNames", &json!({})).is_err(), "plain http to another machine");
for bad in ["missing", "garbage", "short"] {
let o = download(&mut s, &format!("{base}/{bad}/"), &dir);
@@ -516,6 +534,53 @@ mod tests {
let _ = std::fs::remove_dir_all(&dir);
}
/// Issue #2575: a control or MCP client named the folder (`dataset`) and the server (`base`),
/// so it could have a server's bytes written as `cities15000.txt`, `admin1CodesASCII.txt` and
/// `countryInfo.txt` into any folder. Both are refused now, before anything starts.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_client_cannot_choose_where_the_place_names_download_to() {
let mut s = Session::with_demo();
let dir = std::env::temp_dir().join(format!("lightcraft-geocode-elsewhere-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
for p in [json!({"dataset": dir}), json!({"base": "https://example.com/"}), json!({"dataset": dir, "base": "https://example.com/"})] {
let e = s.execute("metadata.downloadPlaceNames", &p).unwrap_err().to_string();
assert!(e.contains("not accepted"), "{p}: {e}");
}
assert!(!s.place_names.downloading() && s.activity.list().is_empty(), "nothing started");
assert!(!dir.exists(), "nothing written");
}
/// The downloaded files replace what is there by renaming a complete temp file over it, so a
/// link planted under one of their names is replaced, not followed to the file it points at.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_download_replaces_a_planted_link_instead_of_writing_through_it() {
let mut s = Session::with_demo();
let base = serve();
let root = std::env::temp_dir().join(format!("lightcraft-geocode-link-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
let dir = root.join("geonames");
std::fs::create_dir_all(&dir).unwrap();
let victim = root.join("victim.txt");
std::fs::write(&victim, "keep me").unwrap();
let link = dir.join("countryInfo.txt");
#[cfg(unix)]
let linked = std::os::unix::fs::symlink(&victim, &link);
#[cfg(windows)]
let linked = std::os::windows::fs::symlink_file(&victim, &link);
if let Err(e) = linked {
lightcraft_testkit::skip!(System, "can't create a symbolic link here: {e}");
let _ = std::fs::remove_dir_all(&root);
return;
}
assert_eq!(download(&mut s, &format!("{base}/good/"), &dir), DownloadOutcome::Done(2));
assert_eq!(std::fs::read_to_string(&victim).unwrap(), "keep me", "the link's target is untouched");
assert!(!std::fs::symlink_metadata(&link).unwrap().file_type().is_symlink(), "the link is now the downloaded file");
assert!(std::fs::read_to_string(&link).unwrap().contains("France"));
let _ = std::fs::remove_dir_all(&root);
}
#[test]
fn download_base_is_https_or_loopback_only() {
assert!(download::base_allowed("https://download.geonames.org/export/dump/"));
+212
View File
@@ -0,0 +1,212 @@
//! Lens profiles looked up again when the lens database appears or changes. A photo's lens data is
//! stored when it is imported ([`Photo::embedded_lens`]), so photos imported before the database was there say "no
//! profile" until something reads their file again. When the database arrives (downloaded on the user's request) or is updated,
//! and when "Enable Lens Corrections" is ticked on a photo without a profile, every library raw that has no profile
//! but whose lens the database knows by name is probed again and gets what Reload from Disk would give it: the
//! profile, and the correction switched on where its settings are still what import gave it (an edited photo keeps
//! its settings).
//!
//! Split like [`super::recheck`] so the app probes on a worker thread: [`missing`] lists what to probe (no
//! file-system calls), [`probe`] reads the files without the session, [`apply`] applies the results as LightCraft's
//! own bookkeeping (journaled, not an undo step). Agents and tests use `library.refreshLensProfiles`.
use lightcraft_catalog::{Catalog, Op, Photo, PhotoId};
use lightcraft_develop::LensSource;
use serde_json::{Value, json};
use super::{CommandSpec, always, bad, cmd};
use crate::media::{FileProbe, ProbeInfo};
use crate::{Result, Session};
/// A photo to probe again, and its file when listed (a result for a photo moved meanwhile is dropped).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Missing {
pub id: PhotoId,
pub path: String,
}
/// Library raws with a file, no lens profile and a lens the database `db` knows by name (`ids`: only these; virtual
/// copies follow the photo they were copied from). With `again` (the database's files were replaced, or an agent
/// asked for every photo), also the raws whose profile came from the database (the new data may give another one, or
/// none) and the raws whose file named no lens when they were imported (a newer LightCraft may read their lens).
/// No file-system calls.
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);
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))
.filter(|p| p.develops_raw())
.filter(|p| {
let lens = p.meta.lens.trim();
match &p.embedded_lens {
None if lens.is_empty() => again,
None => crate::lens_profiles::profile_name(db, &p.meta.camera, lens).is_some(),
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(|m| seen.insert(m.id))
.collect()
}
/// Probe each listed photo's file as Reload would. Doesn't touch the session.
pub fn probe(probe: &FileProbe, list: Vec<Missing>) -> Vec<(Missing, std::result::Result<ProbeInfo, String>)> {
let paths: Vec<String> = list.iter().map(|x| x.path.clone()).collect();
list.into_iter().zip(crate::import::probe_with(probe, &paths)).collect()
}
/// Apply [`probe`]'s results: each photo and its virtual copies get the lens data their file gives now, in one batch
/// that is journaled but isn't an undo step: a profile found (or a different one from a replaced database), a
/// database profile the database no longer gives removed, and the lens's name where the catalog had none. Returns
/// the photos that gained or changed a profile.
pub fn apply(s: &mut Session, results: Vec<(Missing, std::result::Result<ProbeInfo, String>)>) -> Result<Vec<PhotoId>> {
let mut ops = Vec::new();
let mut found = Vec::new();
let mut changed = Vec::new();
// each photo's virtual copies, gathered once for the whole batch (the catalog doesn't change until it's applied)
let mut copies: std::collections::HashMap<PhotoId, Vec<PhotoId>> = std::collections::HashMap::new();
for p in s.catalog.photos() {
if let Some(original) = p.copy_of {
copies.entry(original).or_default().push(p.id);
}
}
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()) {
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);
if info.embedded_lens.is_some() || from_database {
let mine = crate::cmd::convert::lens_ops(id, p, &info);
if !mine.is_empty() {
ops.extend(mine);
changed.push(id);
if info.embedded_lens.is_some() {
found.push(id);
}
}
}
let named = info.meta.lens.trim();
if p.meta.lens.trim().is_empty() && !named.is_empty() {
let mut meta = p.meta.clone();
meta.lens = named.to_string();
ops.push(Op::SetMeta { id, meta: Box::new(meta) });
}
}
}
if !ops.is_empty() {
s.apply_system(Op::Batch { ops })?;
}
for id in &changed {
s.media.forget(*id);
}
Ok(found)
}
/// Why a photo has no lens profile, in words for the Optics panel: `None` when it has one.
pub fn no_profile_reason(p: &Photo) -> Option<String> {
if p.embedded_lens.is_some() {
return None;
}
let lens = p.meta.lens.trim();
Some(if lens.is_empty() { "This file names no lens.".to_string() } else { format!("No lens profile found for {lens}.") })
}
fn refresh(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "library.refreshLensProfiles";
let fp = super::recheck::file_probe(s).ok_or_else(|| bad(C, "this session has no file access"))?;
let ids: Option<Vec<PhotoId>> = match p.get("ids") {
None | Some(Value::Null) => None,
Some(Value::Array(a)) => Some(a.iter().map(|v| v.as_u64().map(PhotoId).ok_or_else(|| bad(C, "ids are photo ids"))).collect::<Result<_>>()?),
Some(_) => return Err(bad(C, "ids is a list of photo ids")),
};
let again = match p.get("all") {
None | Some(Value::Null) => false,
Some(Value::Bool(b)) => *b,
Some(_) => return Err(bad(C, "all is true or false")),
};
let Some(db) = crate::lens_profiles::database() else {
return Ok(json!({"checked": 0, "found": [], "database": false}));
};
let listed = missing(&s.catalog, &db, ids.as_deref(), again);
let n = listed.len();
let found = apply(s, probe(&fp, listed))?;
Ok(json!({"checked": n, "found": found.iter().map(|i| i.0).collect::<Vec<_>>(), "database": true}))
}
fn download(s: &mut Session, _: &Value) -> Result<Value> {
const C: &str = "lens.downloadDatabase";
let dir = crate::lensfun_download::default_dir().ok_or_else(|| bad(C, "this session has no data folder"))?;
start_download(s, &dir, crate::lensfun_download::mirrors(), crate::lensfun_download::FILES).map_err(|e| bad(C, e))?;
Ok(json!({"started": true, "dir": dir.to_string_lossy()}))
}
/// Fetch the database into `dir` and select it, so this session reads it once it is in place (a session that
/// selected no database, e.g. a bare headless one, would otherwise download it and go on without it; the user's
/// `LIGHTCRAFT_LENSFUN_DIR` still wins). Until the download is whole the folder has no marker and isn't read.
pub fn start_download(
s: &mut Session,
dir: &std::path::Path,
mirrors: Vec<String>,
files: &'static [crate::lensfun_download::Pin],
) -> std::result::Result<(), String> {
let activity = s.activity.clone();
s.lensfun.start(dir, mirrors, files, &activity)?;
if crate::lens_profiles::host_dir().as_deref() != Some(dir) {
crate::lens_profiles::use_dir(Some(dir.to_path_buf()));
}
Ok(())
}
fn status(s: &mut Session, _: &Value) -> Result<Value> {
use crate::lensfun_download::State;
let state = match s.lensfun.state() {
State::Idle => json!({"state": "idle"}),
State::Running { bytes, total } => json!({"state": "running", "bytes": bytes, "total": total}),
State::Done { files } => json!({"state": "done", "files": files}),
State::Failed(e) => json!({"state": "failed", "error": e}),
State::Cancelled => json!({"state": "cancelled"}),
};
let dir = crate::lens_profiles::dir();
let lenses = crate::lens_profiles::database().map_or(0, |db| db.lenses.len());
Ok(json!({"download": state, "dir": dir.map(|d| d.to_string_lossy().to_string()), "lenses": lenses}))
}
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
"library.refreshLensProfiles",
"Look Up Lens Profiles Again",
[],
None,
"{ids?: [photo ids], all?: bool} — library raws without a lens profile whose lens the lens database knows are read again and get their profile (the correction is switched on where the photo's settings are still as imported); with all, also raws whose profile came from the database (it may give another, or none) and raws whose file named no lens at import; the app does this by itself when the database arrives (all: when its files were replaced) and when Enable Lens Corrections is ticked; not an undo step → {checked, found: [ids], database: bool}",
always,
refresh
),
cmd!(
"lens.downloadDatabase",
"Download the Lens Database",
[],
None,
"{} — fetch lensfun's lens database (CC BY-SA 3.0, pinned to one commit, checked file by file) into the app's data folder in the background, with an activity row, and read lens profiles from it once it is in place (unless LIGHTCRAFT_LENSFUN_DIR names another folder); the desktop app offers it on its first launch and in Settings. LIGHTCRAFT_LENSFUN_URL lists other places to fetch the same files from → {started, dir}",
always,
download
),
cmd!(
"lens.databaseStatus",
"Lens Database Status",
[],
None,
"{} → {download: {state: idle|running|done|failed|cancelled, …}, dir, lenses (in the database in use)}",
always,
status
),
]
}
+7 -2
View File
@@ -182,12 +182,17 @@ pub(super) fn rotate(s: &mut Session, p: &Value, cw: bool) -> Result<Value> {
let targets = s.targets(p)?;
let mut ops = Vec::new();
for id in targets {
if let Some(d) = s.develop_of(id) {
let mut d = (*d).clone();
if let Some(before) = s.develop_of(id) {
let mut d = (*before).clone();
d.orientation = d.orientation.rotated(cw);
// the crop lives in the oriented frame, so it turns with the image (else it keeps the old width and height and cuts the photo)
let turn = lightcraft_geom::Orientation::Normal.rotated(cw);
d.crop.geometry.rect = turn.map_norm_rect(d.crop.geometry.rect);
// and so do the masks: on the photo first (an old one), then turned with it
s.attach_masks(id, &before, &mut d);
for m in &mut d.masks {
lightcraft_pipeline::mask_space::turn(m, turn);
}
d.crop.aspect = d.crop.aspect.map(|(w, h)| (h, w));
ops.extend(s.develop_op(id, d, "Rotate"));
}
+12 -8
View File
@@ -757,25 +757,29 @@ pub fn specs() -> Vec<CommandSpec> {
}
}
// keywords are stored cleaned (`a | b ` is `a|b`), each once whatever its case
use lightcraft_catalog::keywords::{clean, same};
let add = |m: &mut lightcraft_catalog::Meta, k: &str| {
use lightcraft_catalog::keywords::clean;
// (a set of the lower-cased keywords keeps this linear however many are supplied)
let mut seen: std::collections::HashSet<String> = m.keywords.iter().map(|x| x.to_lowercase()).collect();
let add = |m: &mut lightcraft_catalog::Meta, seen: &mut std::collections::HashSet<String>, k: &str| {
let k = clean(k);
if !k.is_empty() && !m.keywords.iter().any(|x| same(x, &k)) {
if !k.is_empty() && seen.insert(k.to_lowercase()) {
m.keywords.push(k);
}
};
if let Some(k) = strs("keywords") {
m.keywords.clear();
seen.clear();
for k in k {
add(&mut m, &k);
add(&mut m, &mut seen, &k);
}
}
for k in strs("addKeywords").unwrap_or_default() {
add(&mut m, &k);
add(&mut m, &mut seen, &k);
}
for k in strs("removeKeywords").unwrap_or_default() {
let k = clean(&k);
m.keywords.retain(|x| !same(&clean(x), &k));
let removed: std::collections::HashSet<String> =
strs("removeKeywords").unwrap_or_default().iter().map(|k| clean(k).to_lowercase()).collect();
if !removed.is_empty() {
m.keywords.retain(|x| !removed.contains(&clean(x).to_lowercase()));
}
ops.push(Op::SetMeta { id, meta: Box::new(m) });
}
+16 -4
View File
@@ -77,11 +77,14 @@ fn cube_files(paths: &[String]) -> (Vec<(String, String, Option<String>)>, Vec<V
));
}
}
} else {
} else if path.extension().is_some_and(|x| x.eq_ignore_ascii_case("cube")) {
match std::fs::read_to_string(path) {
Ok(t) => out.push((stem(path), t, None)),
Err(e) => failed.push(json!([stem(path), e.to_string()])),
}
} else if !path.extension().is_some_and(|x| x.eq_ignore_ascii_case("dcp")) {
// (a .dcp is a camera profile: `dcp_profiles::import_files` takes it)
failed.push(json!([stem(path), "not a .cube, .dcp or .zip file"]));
}
}
(out, failed)
@@ -120,7 +123,9 @@ fn import(s: &mut Session, p: &Value) -> Result<Value> {
let file = match &dir {
Some(d) => {
let f = d.join(format!("{}.cube", id.trim_start_matches("lut:")));
std::fs::write(&f, &text).map_err(|e| bad(C, format!("{}: {e}", f.display())))?;
// a new file renamed into place: an entry already under the name (a link planted
// in the Profiles folder) is replaced, never written through
lightcraft_catalog::safe_file::write_atomic(&f, text.as_bytes()).map_err(|e| bad(C, format!("{}: {e}", f.display())))?;
f.to_string_lossy().to_string()
}
// no library on disk: the registered LUT is all this session needs (a copy would only
@@ -131,6 +136,10 @@ fn import(s: &mut Session, p: &Value) -> Result<Value> {
s.lut_profiles.push(LutProfile { id: id.clone(), name: display.clone(), group: group.clone(), file });
imported.push(json!({"id": id, "name": display, "group": group}));
}
// camera profiles (.dcp) among them
let (cameras, camera_failed) = super::dcp_profiles::import_files(s, &paths)?;
imported.extend(cameras);
failed.extend(camera_failed);
s.save_prefs()?;
// presets that name these profiles use them now
crate::profile_refs::refresh(s);
@@ -144,12 +153,15 @@ pub fn specs() -> Vec<CommandSpec> {
"Import Profiles",
[],
None,
"{paths: [.cube file, folder or .zip]} — 3D LUTs become creative profiles (Amount 0–200 %; rendered on the CPU) in the profile browser's groups (folder / zip name, else Imported) → {imported: [{id, name, group}], failed}",
"{paths: [.cube / .dcp file, folder or .zip]} — 3D LUTs become creative profiles (Amount 0–200 %; rendered on the CPU) in the profile browser's groups (folder / zip name, else Imported); DNG camera profiles (.dcp, the user's own) become camera profiles (dcp: ids, group Camera Profiles) that replace a raw file's colour model when it is decoded → {imported: [{id, name, group | cameraModel}], failed}",
always,
import
),
cmd!("profile.deleteImported", "Delete Imported Profile", [], None, "{id: lut:…}", always, |s, p| {
cmd!("profile.deleteImported", "Delete Imported Profile", [], None, "{id: lut:… | dcp:…}", always, |s, p| {
let id = str_param(p, "id").ok_or_else(|| bad("profile.deleteImported", "missing id"))?.to_string();
if super::dcp_profiles::is_dcp_id(&id) {
return s.execute("profile.deleteCamera", p);
}
let Some(i) = s.lut_profiles.iter().position(|x| x.id == id) else {
return Err(bad("profile.deleteImported", format!("no imported profile `{id}`")));
};
+25
View File
@@ -464,6 +464,31 @@ pub fn specs() -> Vec<CommandSpec> {
let exclude = bool_or(p, "exclude", false);
let id = s.active().ok_or_else(|| bad(c, "no active photo"))?;
let mid = mask_id(p, s.active_mask, c)?;
// an old mask (on the corrected frame, as the click then is) goes onto the photo
// first, and the click with it: the model works on the photo before lens
// corrections, Upright and Transform, and reads every click there
let mut at = at;
if let Some(cur) = s.develop_of(id).filter(|d| d.masks.iter().any(|m| m.id == mid && !m.on_photo)) {
if let Some(f) = s.mask_frame(id, &cur) {
// a click on the corrected frame's blank space is off the photo, not on
// its edge (a hair past it, from rounding, is on the edge)
const EDGE: f64 = 1e-6;
let n = f.for_mask(true).norm_to_mask(at);
let on = |v: f64| v.is_finite() && (-EDGE..=1.0 + EDGE).contains(&v);
if !(on(n.x) && on(n.y)) {
return Err(bad(c, "the point is outside the photo"));
}
at = Point::new(n.x.clamp(0.0, 1.0), n.y.clamp(0.0, 1.0));
}
let mut on = (*cur).clone();
s.attach_masks(id, &cur, &mut on);
s.apply_silent(lightcraft_catalog::Op::SetDevelop {
id,
settings: std::sync::Arc::new(on),
label: "Masks".into(),
edited: None,
})?;
}
let d = s.develop_of(id).unwrap_or_default();
let m = d.masks.iter().find(|m| m.id == mid).ok_or_else(|| bad(c, format!("no mask {mid}")))?;
let k = m
+8 -1
View File
@@ -163,7 +163,11 @@ fn stored_hash(p: &Photo) -> Option<&str> {
/// The content hash of the file at `path` (as import computes it), if it can be read. Read in
/// pieces: the file is whatever is on the disk, of any size.
fn file_hash(path: &str) -> Option<String> {
hash_reader(std::fs::File::open(path).ok()?)
use std::io::Read;
// the opened file must be regular (a FIFO or device would never end), and no more than its size at open is read
let file = std::fs::File::open(path).ok()?;
let meta = file.metadata().ok().filter(|m| m.is_file())?;
hash_reader(file.take(meta.len()))
}
/// The content hash of what `r` gives, read in pieces (the hash import computes of the whole).
@@ -230,6 +234,9 @@ mod tests {
std::fs::write(&f, b"pixels").unwrap();
assert_eq!(file_hash(f.to_str().unwrap()), Some(lightcraft_preview::hash_bytes(b"pixels").to_string()));
assert_eq!(file_hash(dir.0.join("nope").to_str().unwrap()), None);
assert_eq!(file_hash(dir.0.to_str().unwrap()), None, "a folder has no content hash");
#[cfg(unix)]
assert_eq!(file_hash("/dev/zero"), None, "a device never ends");
}
}
+14 -4
View File
@@ -360,8 +360,9 @@ struct SmartCounts {
fn original_only(source: crate::media::SourceRef) -> Option<crate::media::SourceRef> {
use crate::media::SourceRef;
match source {
// (a smart preview keeps the file's own colour: an imported camera profile is applied when the original is read)
SourceRef::File { path, max_edge, loader, denoise, .. } => {
Some(SourceRef::File { path, max_edge, loader, fallback: None, denoise, reduced: None })
Some(SourceRef::File { path, max_edge, loader, fallback: None, denoise, camera_profile: None, reduced: None })
}
SourceRef::Loaded(d) if d.info.is_some() && !d.from_proxy && !d.reduced => Some(SourceRef::Loaded(d)),
_ => None,
@@ -486,7 +487,9 @@ fn smart(s: &mut Session, p: &Value) -> Result<Value> {
continue;
}
let path = crate::smart::sharded_file_path(&dir, &ph);
let source = (!discard).then(|| s.media.source_ref(&ph, crate::media::SourceLevel::Preview));
// (a smart preview keeps the file's own colour: never built with the photo's imported camera profile, nor
// from a cached source developed with it)
let source = (!discard).then(|| s.media.source_ref_without_profile(&ph, crate::media::SourceLevel::Preview));
jobs.push((id, path, source, preview_fitted_look(&ph)));
}
let custom = s.smart_previews_dir.is_some();
@@ -720,8 +723,15 @@ mod tests {
let mut jobs = jobs_for(&mut s, id, Some(512));
assert_eq!(jobs.len(), 2, "view and thumbnail");
assert!(jobs[0].view_cache.is_some(), "the view renders first");
jobs[1].source =
SourceRef::File { path: "/nonexistent/photo.arw".into(), max_edge: 512, loader: None, fallback: None, denoise: None, reduced: None };
jobs[1].source = SourceRef::File {
path: "/nonexistent/photo.arw".into(),
max_edge: 512,
loader: None,
fallback: None,
denoise: None,
camera_profile: None,
reduced: None,
};
assert!(run_photo(jobs), "the thumbnail rendered from the view's decoded source");
}
+399
View File
@@ -0,0 +1,399 @@
//! Find Similar (`library.findSimilar`), split so the app can read the photos on a worker thread: the
//! first search reads a thumbnail-level source of every photo in the library, and in a large
//! library that froze the window for as long as it took (issue #3468). [`plan`] lists what is to be
//! read (no file-system calls), [`measure`] reads it without the session (cancellable, with
//! progress), [`keep`] adds what it found to the session's signatures and [`apply`] answers from
//! those. The command itself (the CLI, MCP without an app) does all of them at once.
//!
//! A search keeps no decoded source and learns nothing from one: it only looks, and in a large library
//! it would push out of memory what the grid and the loupe are showing.
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Mutex, PoisonError};
use lightcraft_catalog::PhotoId;
use serde_json::{Value, json};
use super::bad;
use crate::media::{SourceLevel, SourceRef, content_key};
use crate::{Result, Session};
const C: &str = "library.findSimilar";
/// The kind of the row in the activity stack that a search on a worker thread holds.
pub const KIND: &str = "similar";
/// A content key and that content's look-alike signature.
pub type Signature = (String, [f32; 64]);
/// Whether a search can start (the command's `enabled`): one at a time, for what a second one would
/// read the first is reading.
pub fn no_search_running(s: &Session) -> std::result::Result<(), String> {
if s.activity.list().iter().any(|r| r.kind == KIND) { Err("a search for similar photos is already running".to_string()) } else { Ok(()) }
}
/// What a search asks.
#[derive(Debug)]
pub struct Search {
id: PhotoId,
min: f32,
filter: bool,
}
/// A content whose signature isn't known yet, and how to read it: from the first of its photos that
/// can be read (a copy that is offline gives way to the next).
struct Content {
key: String,
sources: Vec<SourceRef>,
}
/// What a search has to read: the searched photo first, as nothing can be compared without it.
pub struct Reads {
me: Option<Content>,
rest: Vec<Content>,
}
impl Reads {
/// How many contents are to be read.
pub fn len(&self) -> usize {
self.rest.len().saturating_add(usize::from(self.me.is_some()))
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
/// The search `p` asks for and what it has to read, once for each content not known yet. No
/// file-system calls.
pub fn plan(s: &mut Session, p: &Value) -> Result<(Search, Reads)> {
let id = super::photo_id(p, C)?.or(s.active()).ok_or_else(|| bad(C, "no photo"))?;
let min = p.get("similarity").and_then(Value::as_f64).unwrap_or(0.8) as f32;
let filter = p.get("filter").and_then(Value::as_bool).unwrap_or(true);
let photo = s.catalog.photo(id).ok_or_else(|| bad(C, "can't read the photo"))?;
let my_key = content_key(photo);
let me =
(!s.signatures.contains_key(&my_key)).then(|| Content { sources: vec![s.media.source_ref(photo, SourceLevel::Thumb)], key: my_key.clone() });
let mut rest: Vec<Content> = Vec::new();
let mut at = std::collections::HashMap::new();
for q in s.catalog.photos().filter(|q| q.in_library()) {
let key = content_key(q);
// (the searched photo's content is known by the time these are read, or the search has ended)
if key == my_key || s.signatures.contains_key(&key) {
continue;
}
let source = s.media.source_ref(q, SourceLevel::Thumb);
match at.get(&key).and_then(|i: &usize| rest.get_mut(*i)) {
Some(content) => content.sources.push(source),
None => {
at.insert(key.clone(), rest.len());
rest.push(Content { key, sources: vec![source] });
}
}
}
Ok((Search { id, min, filter }, Reads { me, rest }))
}
/// `content`'s signature, or `None` when none of its photos can be read or `cancel` is set first. A
/// decoder's panic is that photo's failure, not the search's.
fn signature_of(content: &Content, cancel: &AtomicBool) -> Option<[f32; 64]> {
content.sources.iter().find_map(|source| {
if cancel.load(Ordering::Relaxed) {
return None;
}
crate::guard::catch("Find Similar", || {
crate::memory::in_background(|| source.load_source()).ok().map(|decoded| lightcraft_pipeline::cull::signature(&decoded.image))
})
.ok()
.flatten()
})
}
/// Read what [`plan`] listed, several photos at once. Doesn't touch the session. `progress(done)` is
/// called from the threads doing the reading; once `cancel` is set no further file is started, and
/// what was read until then comes back. A searched photo that can't be read ends it there.
pub fn measure(reads: Reads, cancel: &AtomicBool, progress: &(dyn Fn(usize) + Sync)) -> Vec<Signature> {
let found = Mutex::new(Vec::with_capacity(reads.len().min(4096)));
let done = AtomicUsize::new(0);
let keep = |key: String, v: [f32; 64]| found.lock().unwrap_or_else(PoisonError::into_inner).push((key, v));
if let Some(me) = reads.me {
let Some(v) = signature_of(&me, cancel) else { return Vec::new() };
keep(me.key, v);
done.store(1, Ordering::Relaxed);
progress(1);
}
let lanes = crate::export::export_parallelism(reads.rest.len());
let queue = Mutex::new(reads.rest.into_iter());
let work = || {
while !cancel.load(Ordering::Relaxed) {
let next = queue.lock().unwrap_or_else(PoisonError::into_inner).next();
let Some(content) = next else { break };
if let Some(v) = signature_of(&content, cancel) {
keep(content.key, v);
}
progress(done.fetch_add(1, Ordering::Relaxed).saturating_add(1));
}
};
#[cfg(not(target_arch = "wasm32"))]
std::thread::scope(|sc| {
for k in 1..lanes.max(1) {
// a lane that can't start leaves its photos to the others (and to this thread)
if std::thread::Builder::new().name(format!("similar-{k}")).spawn_scoped(sc, work).is_err() {
break;
}
}
work();
});
#[cfg(target_arch = "wasm32")]
{
let _ = lanes;
work();
}
found.into_inner().unwrap_or_else(PoisonError::into_inner)
}
/// Add what [`measure`] found to the signatures, also when the search was stopped: they hold for the
/// contents they were read from, and the next search doesn't read those again.
pub fn keep(s: &mut Session, found: Vec<Signature>) {
s.signatures.extend(found);
}
/// Answer `search` from the signatures known now, most similar first, and filter the view to the
/// photos found. A photo with none (it can't be read, or came after the [`plan`]) isn't compared.
pub fn apply(s: &mut Session, search: &Search) -> Result<Value> {
let known = s.catalog.photo(search.id).and_then(|photo| s.signatures.get(&content_key(photo)));
let me = *known.ok_or_else(|| bad(C, "can't read the photo"))?;
let mut hits: Vec<(PhotoId, f32)> = Vec::new();
for q in s.catalog.photos().filter(|q| q.in_library()) {
if let Some(v) = s.signatures.get(&content_key(q)) {
let sim = lightcraft_pipeline::cull::similarity(&me, v);
if sim >= search.min {
hits.push((q.id, sim.clamp(0.0, 1.0)));
}
}
}
hits.sort_by(|a, b| b.1.total_cmp(&a.1));
if search.filter {
s.shelved_filter = None;
s.filter.only = hits.iter().map(|h| h.0).collect();
// an empty `only` means "no constraint": no hits is its own state that shows no photos
s.filter.only_none = s.filter.only.is_empty();
}
Ok(json!({"photos": hits.iter().map(|(i, v)| json!({"id": i.0, "similarity": (v * 1000.0).round() / 1000.0})).collect::<Vec<_>>()}))
}
/// Find Similar: photos that look like `id` (signatures from thumbnail-level sources, cached by
/// content), most similar first; the view is filtered to them.
pub(super) fn run(s: &mut Session, p: &Value) -> Result<Value> {
let (search, reads) = plan(s, p)?;
let found = measure(reads, &AtomicBool::new(false), &|_| {});
keep(s, found);
apply(s, &search)
}
#[cfg(test)]
mod tests {
use std::collections::HashMap;
use std::sync::Arc;
use lightcraft_catalog::{Op, Photo, Source};
use lightcraft_raster::Rgb32f;
use super::*;
/// Reads per file, the files that can't be read and the file whose decoder panics.
#[derive(Default)]
struct Files {
reads: Mutex<HashMap<String, usize>>,
unreadable: Mutex<Vec<String>>,
panics: Mutex<Option<String>>,
/// Set once this many reads have started.
cancel_after: Option<(usize, Arc<AtomicBool>)>,
}
impl Files {
fn reads_of(&self, path: &str) -> usize {
self.reads.lock().unwrap().get(path).copied().unwrap_or(0)
}
fn reads(&self) -> usize {
self.reads.lock().unwrap().values().sum()
}
}
/// A session of photos `/p/<name>.jpg`, each with its content hash when it has one. Odd numbers
/// in a name mean a picture that gets brighter to the right, others one that does downwards.
fn session(photos: &[(&str, Option<&str>)], files: Files) -> (Session, Arc<Files>) {
let files = Arc::new(files);
let mut s = Session::new();
for (i, (name, hash)) in photos.iter().enumerate() {
let source = Source::File { path: format!("/p/{name}.jpg") };
let mut p = Photo::new(PhotoId(i as u64 + 1), source, &format!("{name}.jpg"), "JPEG", 64, 64, "2026-01-01T00:00:00");
p.content_hash = hash.map(str::to_string);
s.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap();
}
let seen = files.clone();
s.media.file_loader = Some(Arc::new(move |path: &str, _, _| {
let started = {
let mut reads = seen.reads.lock().unwrap();
*reads.entry(path.to_string()).or_default() += 1;
reads.values().sum::<usize>()
};
if let Some((after, cancel)) = &seen.cancel_after
&& started >= *after
{
cancel.store(true, Ordering::SeqCst);
}
if seen.panics.lock().unwrap().as_deref() == Some(path) {
panic!("a decoder fails on {path}");
}
if seen.unreadable.lock().unwrap().iter().any(|f| f == path) {
return Err(format!("{path}: gone"));
}
let across = path.bytes().filter(u8::is_ascii_digit).any(|b| b % 2 == 1);
let image = Rgb32f::from_fn(64, 64, |x, y| {
let v = if across { x } else { y };
[v as f32 / 64.0; 3]
});
Ok((image, Default::default()))
}));
(s, files)
}
fn ids(r: &Value) -> Vec<u64> {
r["photos"].as_array().unwrap().iter().map(|h| h["id"].as_u64().unwrap()).collect()
}
/// A search on a worker thread holds a row of its kind: the command is off until the row goes.
#[test]
fn a_running_search_turns_the_command_off() {
let (mut s, files) = session(&[("a1", None), ("b2", None)], Files::default());
let row = s.activity.start(KIND, "Find Similar Photos", crate::activity::Cancel::No);
let off = s.commands().into_iter().find(|c| c.id == C).is_some_and(|c| !c.enabled);
assert!(off, "the menu shows it off");
assert!(matches!(s.execute(C, &json!({"id": 1})), Err(crate::EngineError::Disabled(..))));
assert_eq!(files.reads(), 0);
drop(row);
assert!(s.execute(C, &json!({"id": 1})).is_ok());
}
#[test]
fn making_the_plan_reads_no_file() {
let (mut s, files) = session(&[("a1", None), ("b2", None), ("c1", None)], Files::default());
let (_, reads) = plan(&mut s, &json!({"id": 1})).unwrap();
assert_eq!(reads.len(), 3);
assert_eq!(files.reads(), 0);
}
#[test]
fn the_command_reads_each_photo_and_finds_the_ones_alike() {
let names: Vec<String> = (0..40).map(|i| format!("p{i}")).collect();
let photos: Vec<(&str, Option<&str>)> = names.iter().map(|n| (n.as_str(), None)).collect();
let (mut s, files) = session(&photos, Files::default());
let r = s.execute("library.findSimilar", &json!({"id": 1})).unwrap();
assert_eq!(files.reads(), 40, "each once");
assert!(ids(&r).contains(&1) && ids(&r).len() < 40, "{r}");
// known now: no file is read again
let again = s.execute("library.findSimilar", &json!({"id": 1})).unwrap();
assert_eq!(files.reads(), 40);
assert_eq!(ids(&again), ids(&r));
}
#[test]
fn a_content_is_read_once_and_an_unreadable_copy_gives_way_to_the_next() {
let files = Files::default();
files.unreadable.lock().unwrap().push("/p/copy2.jpg".into());
let photos = [("me1", None), ("copy2", Some("h")), ("copy4", Some("h")), ("copy6", Some("h"))];
let (mut s, files) = session(&photos, files);
let r = s.execute("library.findSimilar", &json!({"id": 1, "similarity": -1.0})).unwrap();
assert_eq!(files.reads_of("/p/copy2.jpg"), 1);
assert_eq!(files.reads_of("/p/copy4.jpg"), 1, "the next copy stands in");
assert_eq!(files.reads_of("/p/copy6.jpg"), 0, "its content is known by then");
assert_eq!(ids(&r).len(), 4, "every copy is compared: {r}");
}
#[test]
fn a_searched_photo_that_cannot_be_read_ends_the_search_before_any_other_is_read() {
let files = Files::default();
files.unreadable.lock().unwrap().push("/p/me1.jpg".into());
let (mut s, files) = session(&[("me1", None), ("b2", None), ("c1", None)], files);
let e = s.execute("library.findSimilar", &json!({"id": 1})).unwrap_err();
assert!(e.to_string().contains("can't read the photo"), "{e}");
assert_eq!(files.reads(), 1, "only the searched photo");
assert!(s.signatures.is_empty());
assert_eq!(s.filter, Default::default(), "the view stays as it was");
}
#[test]
fn a_photo_nobody_has_is_refused_at_once() {
let (mut s, files) = session(&[("a1", None)], Files::default());
assert!(matches!(plan(&mut s, &json!({"id": 99})), Err(crate::EngineError::BadParams { .. })));
assert_eq!(files.reads(), 0);
}
#[test]
fn a_photo_whose_decoder_panics_is_left_out_and_the_search_goes_on() {
let files = Files::default();
*files.panics.lock().unwrap() = Some("/p/bad3.jpg".into());
let (mut s, _) = session(&[("me1", None), ("bad3", None), ("ok1", None), ("ok5", None)], files);
let r = s.execute("library.findSimilar", &json!({"id": 1, "similarity": -1.0})).unwrap();
assert_eq!(ids(&r).len(), 3, "{r}");
assert!(!ids(&r).contains(&2), "{r}");
}
/// Stopped after some reads: what was read is kept, the view is left alone, and the next search
/// reads only the rest.
#[test]
fn a_stopped_search_keeps_what_it_read_and_the_next_reads_the_rest() {
let cancel = Arc::new(AtomicBool::new(false));
let files = Files { cancel_after: Some((5, cancel.clone())), ..Default::default() };
let names: Vec<String> = (0..64).map(|i| format!("p{i}")).collect();
let photos: Vec<(&str, Option<&str>)> = names.iter().map(|n| (n.as_str(), None)).collect();
let (mut s, _) = session(&photos, files);
let (_, reads) = plan(&mut s, &json!({"id": 1})).unwrap();
let found = measure(reads, &cancel, &|_| {});
let read = found.len();
assert!((1..64).contains(&read), "stopped along the way: {read}");
keep(&mut s, found);
assert_eq!(s.filter, Default::default());
let (_, rest) = plan(&mut s, &json!({"id": 1})).unwrap();
assert_eq!(rest.len(), 64 - read);
}
#[test]
fn a_stopped_search_reads_nothing_more() {
let (mut s, files) = session(&[("a1", None), ("b2", None), ("c1", None)], Files::default());
let (_, reads) = plan(&mut s, &json!({"id": 1})).unwrap();
assert!(measure(reads, &AtomicBool::new(true), &|_| {}).is_empty());
assert_eq!(files.reads(), 0);
}
/// What changed while the files were read: a photo deleted since isn't an answer, and one added
/// since has no signature to compare.
#[test]
fn photos_that_changed_during_the_search_are_answered_as_they_are_now() {
let (mut s, _) = session(&[("a1", None), ("b1", None), ("c1", None)], Files::default());
let (search, reads) = plan(&mut s, &json!({"id": 1, "similarity": -1.0})).unwrap();
let found = measure(reads, &AtomicBool::new(false), &|_| {});
s.catalog.apply(Op::RemovePhoto { id: PhotoId(2) }).unwrap();
let added = Photo::new(PhotoId(9), Source::File { path: "/p/new1.jpg".into() }, "new1.jpg", "JPEG", 64, 64, "2026-01-01T00:00:00");
s.catalog.apply(Op::AddPhoto { photo: Box::new(added) }).unwrap();
keep(&mut s, found);
let mut answer = ids(&apply(&mut s, &search).unwrap());
answer.sort_unstable();
assert_eq!(answer, [1, 3]);
}
#[test]
fn progress_counts_every_content_read_or_not() {
let files = Files::default();
files.unreadable.lock().unwrap().push("/p/b2.jpg".into());
let (mut s, _) = session(&[("a1", None), ("b2", None), ("c1", None), ("d2", None)], files);
let (_, reads) = plan(&mut s, &json!({"id": 1})).unwrap();
let top = AtomicUsize::new(0);
let found = measure(reads, &AtomicBool::new(false), &|done| {
top.fetch_max(done, Ordering::SeqCst);
});
assert_eq!(top.load(Ordering::SeqCst), 4);
assert_eq!(found.len(), 3);
}
}
+20
View File
@@ -146,6 +146,26 @@ impl Session {
self
}
/// Read lens profiles from the app's own copy of the lens database ([`crate::lensfun_download::default_dir`],
/// unless `LIGHTCRAFT_LENSFUN_DIR` names another) when it is there. Every host with a file system selects it
/// (desktop, CLI, headless MCP), so the same raw gets the same profile everywhere; it never fetches anything
/// ([`Self::with_lens_auto_download`] is that permission).
pub fn with_default_lens_database(self) -> Self {
let dir = crate::lensfun_download::default_dir();
if let Some(d) = &dir {
crate::lensfun_download::recover(d);
}
crate::lens_profiles::use_dir(dir);
self
}
/// Let the host offer the lens database at its start, and fetch it there once the user said yes
/// ([`crate::lensfun_download::fetch_on_start`] decides). Separate from selecting a database that is already there ([`Self::with_default_lens_database`]).
pub fn with_lens_auto_download(mut self) -> Self {
self.lens_auto_download = true;
self
}
/// Keep denoise models in the shared default folder ([`default_denoise_models_dir`]).
pub fn with_default_denoise_models(mut self) -> Self {
self.set_denoise_models_dir(default_denoise_models_dir());
+2 -1
View File
@@ -5,7 +5,8 @@ use lightcraft_denoise::manifest::{Domain, Gain};
fn folder(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("lc-engine-gpu-{}-{name}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
// exclusive: a directory planted at this predictable name fails the test instead of receiving its files
std::fs::create_dir(&dir).unwrap();
dir
}
+2 -1
View File
@@ -1,4 +1,5 @@
use super::options::{Conflict, DestinationMode, ExportFormat, HdrCurve, MetadataPolicy, Resize, ResizeMode, SharpenAmount, SharpenFor};
use super::place::clean_subfolder;
use super::prepare::DngCompression;
use super::watermark::{Anchor, Watermark};
use super::{ExportOptions, JxlColour, JxlEffort, JxlOptions, OutputDepth, OutputSpace, TiffCompression};
@@ -429,7 +430,7 @@ impl ExportOptions {
naming: s("naming").map_or(d.naming, str::to_string),
start_number: u("startNumber").map_or(d.start_number, |v| v.min(999_999) as u32),
destination_mode: s("destinationMode").and_then(DestinationMode::parse).unwrap_or(d.destination_mode),
subfolder: s("subfolder").map_or(d.subfolder, |v| v.trim().replace(['\\', ':', '\0'], "_")),
subfolder: s("subfolder").map_or(d.subfolder, clean_subfolder),
conflict: s("conflict").and_then(Conflict::parse).unwrap_or(d.conflict),
tiff_compression: match s("tiffCompression").map(str::to_ascii_lowercase).as_deref() {
Some("none") => TiffCompression::None,
+10 -1
View File
@@ -60,6 +60,14 @@ fn join_path(a: &str, b: &str) -> String {
if a.is_empty() { b.to_string() } else { format!("{}/{b}", a.trim_end_matches('/')) }
}
/// 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 {
let s = s.trim().replace(['\\', ':', '\0'], "_");
s.split('/').map(str::trim).filter(|p| !p.is_empty() && *p != "." && *p != "..").collect::<Vec<_>>().join("/")
}
impl<'a> Placer<'a> {
pub(super) fn new(
o: &'a ExportOptions,
@@ -89,7 +97,8 @@ impl<'a> Placer<'a> {
d.to_string()
}
};
Ok(if self.o.subfolder.is_empty() { base } else { join_path(&base, &self.o.subfolder) })
let sub = clean_subfolder(&self.o.subfolder);
Ok(if sub.is_empty() { base } else { join_path(&base, &sub) })
}
/// Place photo `photo`'s export result (file `name`, its original in `source_dir`): write it
+2
View File
@@ -912,6 +912,8 @@ fn ramp(depth: OutputDepth, space: OutputSpace) -> lightcraft_pipeline::Rendered
fn distinct_levels(bytes: &[u8]) -> (usize, lightcraft_codecs::Decoded) {
let d = lightcraft_codecs::decode(bytes, Default::default()).expect("decodes");
let mut v: Vec<u32> = (0..d.image.width).map(|x| d.image.get(x, 1)[1].to_bits()).collect();
// sorted first: 8-bit output is dithered, so equal levels aren't all side by side
v.sort_unstable();
v.dedup();
(v.len(), d)
}
+6 -6
View File
@@ -214,9 +214,9 @@ impl Index {
for (k, e) in &self.entries {
buf.extend(self.record(k, e));
}
let part = path.with_extension("part");
std::fs::write(&part, &buf)?;
std::fs::rename(&part, &path)?;
// a fresh temp file (never a `.part` entry left in the library, which could be a link
// to a file outside it) renamed over the cache
lightcraft_catalog::safe_file::write_atomic_nosync(&path, &buf)?;
self.file_matches = true;
self.rewrite = false;
}
@@ -367,9 +367,9 @@ impl Scanned {
} else {
let mut buf = self.header();
buf.extend(self.set.iter().flat_map(|id| id.to_le_bytes()));
let part = path.with_extension("part");
std::fs::write(&part, &buf)?;
std::fs::rename(&part, &path)?;
// a fresh temp file (never a `.part` entry left in the library, which could be a link
// to a file outside it) renamed over the cache
lightcraft_catalog::safe_file::write_atomic_nosync(&path, &buf)?;
self.file_matches = true;
self.rewrite = false;
}
+3 -1
View File
@@ -11,6 +11,8 @@ use lightcraft_pipeline::SourceInfo;
use lightcraft_raster::Rgb32f;
use lightcraft_raster::resample::{Filter, fit};
use lightcraft_raw::dcp::DcpProfile;
use crate::media::{DenoiseSpec, FileLoader, FileProbe, PairLoader, PreviewLoader, ProbeInfo, ReducedLoader};
mod colour;
@@ -25,7 +27,7 @@ pub(crate) use colour::clipped_white;
use fs::quick_image_srgb;
pub use fs::{fs_hooks, fs_pair_loader, fs_reduced_loader};
pub(crate) use load::{DngWhite, WbScaleOf, dng_tone_curve};
pub use load::{load_bytes, load_vec, load_vec_pair, load_vec_reduced};
pub use load::{load_bytes, load_bytes_with, load_vec, load_vec_pair, load_vec_reduced};
#[cfg(test)]
use preview::PLAN_PREFIX;
pub(crate) use preview::decode_raw_preview;
+6 -5
View File
@@ -1,7 +1,7 @@
use super::load::{load_vec, load_vec_pair, load_vec_reduced};
use super::preview::{fit_box, fs_preview_loader, preview_orientation};
use super::probe::probe_bytes;
use super::{Arc, DenoiseSpec, FileLoader, FileProbe, Filter, PairLoader, ReducedLoader, fit};
use super::{Arc, DcpProfile, DenoiseSpec, FileLoader, FileProbe, Filter, PairLoader, ReducedLoader, fit};
/// The file's first [`lightcraft_raw::PREVIEW_PREFIX`] bytes (or the whole file when it is shorter),
/// which is what every format [`lightcraft_raw::bounded_preview`] covers keeps its pointer in.
@@ -54,13 +54,13 @@ pub(super) fn quick_image_srgb(header: &[u8], window: &[u8], adobe_rgb: bool, ma
/// The filesystem-backed [`PairLoader`]: the file is read and decoded once, and developed as usual and from the photo's
/// denoised picture. It holds two pictures at once, so it counts for more at the memory gate than a plain load.
pub fn fs_pair_loader() -> PairLoader {
Arc::new(|path: &str, max_edge: usize, spec: &DenoiseSpec| {
Arc::new(|path: &str, max_edge: usize, spec: &DenoiseSpec, dcp: Option<&DcpProfile>| {
let len = std::fs::metadata(path).map(|m| m.len() as usize).unwrap_or(0);
let weight = len * if max_edge <= crate::media::SourceLevel::Thumb.max_edge() { 4 } else { 10 };
let gate = crate::memory::work_gate();
let _permit = if crate::memory::is_background() { gate.acquire(weight) } else { gate.acquire_urgent(weight) };
let bytes = std::fs::read(path).map_err(|e| format!("{path}: {e}"))?;
let r = load_vec_pair(bytes, max_edge, spec);
let r = load_vec_pair(bytes, max_edge, spec, dcp);
crate::memory::release();
r
})
@@ -74,7 +74,8 @@ pub fn fs_pair_loader() -> PairLoader {
/// interactive loads (the loupe, exports) never wait — they are counted, so background work
/// yields to them.
pub fn fs_hooks() -> (FileLoader, FileProbe) {
let loader: FileLoader = Arc::new(|path: &str, max_edge: usize| fs_load(path, max_edge, |bytes| load_vec(bytes, max_edge)));
let loader: FileLoader =
Arc::new(|path: &str, max_edge: usize, dcp: Option<&DcpProfile>| fs_load(path, max_edge, |bytes| load_vec(bytes, max_edge, dcp)));
let probe: FileProbe = Arc::new(|path: &str| {
use std::io::Read;
// one open, then everything from the open file: its size and modification time are not
@@ -94,7 +95,7 @@ pub fn fs_hooks() -> (FileLoader, FileProbe) {
/// The filesystem [`ReducedLoader`]: [`load_vec_reduced`] of the file, gated like [`fs_hooks`]' loader.
pub fn fs_reduced_loader() -> ReducedLoader {
Arc::new(|path: &str, max_edge: usize| fs_load(path, max_edge, |bytes| load_vec_reduced(bytes, max_edge)))
Arc::new(|path: &str, max_edge: usize, dcp: Option<&DcpProfile>| fs_load(path, max_edge, |bytes| load_vec_reduced(bytes, max_edge, dcp)))
}
/// Read `path` and `load` it, waiting on [`crate::memory::work_gate`] as [`fs_hooks`] explains.
+172 -17
View File
@@ -1,7 +1,7 @@
use super::colour::bin_factor;
use super::preview::{fit_box, load_embedded_preview};
use super::probe::preview_reason;
use super::{Arc, CameraColourModel, DenoiseSpec, Filter, HIGHLIGHT_CLIP, Orientation, Rgb32f, SourceInfo, fit, xy_to_temp_tint};
use super::{Arc, CameraColourModel, DcpProfile, DenoiseSpec, Filter, HIGHLIGHT_CLIP, Orientation, Rgb32f, SourceInfo, fit, xy_to_temp_tint};
/// Decode a file into a linear Rec.2020 image no larger than `max_edge`, oriented.
///
@@ -9,27 +9,41 @@ use super::{Arc, CameraColourModel, DenoiseSpec, Filter, HIGHLIGHT_CLIP, Orienta
/// instead of each one waking the pool from outside and waiting for it (which costs more than the
/// loops themselves when the machine is busy).
pub fn load_bytes(bytes: &[u8], max_edge: usize) -> Result<(Rgb32f, SourceInfo), String> {
rayon::scope(|_| load_bytes_now(std::borrow::Cow::Borrowed(bytes), max_edge, None, false).map(|(img, _, info, _)| (img, info)))
rayon::scope(|_| load_bytes_now(std::borrow::Cow::Borrowed(bytes), max_edge, None, false, None).map(|(img, _, info, _)| (img, info)))
}
/// [`load_bytes`] developing a raw file with an imported camera profile (`dcp`) in place of its own colour model.
pub fn load_bytes_with(bytes: &[u8], max_edge: usize, dcp: Option<&DcpProfile>) -> Result<(Rgb32f, SourceInfo), String> {
rayon::scope(|_| load_bytes_now(std::borrow::Cow::Borrowed(bytes), max_edge, None, false, dcp).map(|(img, _, info, _)| (img, info)))
}
/// [`load_bytes`] taking the file's bytes: a raw file's bytes are freed as soon as it is decoded
/// (less memory held while it is developed).
pub fn load_vec(bytes: Vec<u8>, max_edge: usize) -> Result<(Rgb32f, SourceInfo), String> {
rayon::scope(move |_| load_bytes_now(std::borrow::Cow::Owned(bytes), max_edge, None, false).map(|(img, _, info, _)| (img, info)))
pub fn load_vec(bytes: Vec<u8>, max_edge: usize, dcp: Option<&DcpProfile>) -> Result<(Rgb32f, SourceInfo), String> {
rayon::scope(move |_| load_bytes_now(std::borrow::Cow::Owned(bytes), max_edge, None, false, dcp).map(|(img, _, info, _)| (img, info)))
}
/// [`load_vec`] for a thumbnail: a DNG that keeps reduced-resolution copies of its raw image (Lightroom's HDR and
/// panorama merges) develops the smallest that covers `max_edge` instead of the whole image. The flag says whether
/// it did: such a picture is not the full image, and an export never renders from it.
pub fn load_vec_reduced(bytes: Vec<u8>, max_edge: usize) -> Result<(Rgb32f, SourceInfo, bool), String> {
rayon::scope(move |_| load_bytes_now(std::borrow::Cow::Owned(bytes), max_edge, None, true).map(|(img, _, info, reduced)| (img, info, reduced)))
pub fn load_vec_reduced(bytes: Vec<u8>, max_edge: usize, dcp: Option<&DcpProfile>) -> Result<(Rgb32f, SourceInfo, bool), String> {
rayon::scope(move |_| {
load_bytes_now(std::borrow::Cow::Owned(bytes), max_edge, None, true, dcp).map(|(img, _, info, reduced)| (img, info, reduced))
})
}
/// [`load_vec`] that also develops the photo's cached denoised picture (`spec`) from the same decode: the plain
/// picture, the denoised one (`None` when it cannot be read or does not fit this raw: the plain one is then all
/// there is) and the source facts. Both pictures are the same size.
pub fn load_vec_pair(bytes: Vec<u8>, max_edge: usize, spec: &DenoiseSpec) -> Result<(Rgb32f, Option<Rgb32f>, SourceInfo), String> {
rayon::scope(move |_| load_bytes_now(std::borrow::Cow::Owned(bytes), max_edge, Some(spec), false).map(|(img, twin, info, _)| (img, twin, info)))
pub fn load_vec_pair(
bytes: Vec<u8>,
max_edge: usize,
spec: &DenoiseSpec,
dcp: Option<&DcpProfile>,
) -> Result<(Rgb32f, Option<Rgb32f>, SourceInfo), String> {
rayon::scope(move |_| {
load_bytes_now(std::borrow::Cow::Owned(bytes), max_edge, Some(spec), false, dcp).map(|(img, twin, info, _)| (img, twin, info))
})
}
/// The denoised camera RGB of `raw` from its cached product, as the plain development would have it: the default
@@ -59,6 +73,7 @@ fn load_bytes_now(
max_edge: usize,
denoise: Option<&DenoiseSpec>,
allow_reduced: bool,
dcp: Option<&DcpProfile>,
) -> Result<(Rgb32f, Option<Rgb32f>, SourceInfo, bool), String> {
if lightcraft_raw::probe(&bytes).is_some() {
// a thumbnail (`allow_reduced`, never an export) of a DNG that keeps smaller copies of its raw image
@@ -92,20 +107,46 @@ fn load_bytes_now(
let dng_lens_ops = (raw.format == lightcraft_raw::RawFormat::Dng && raw.opcodes.list3.iter().any(|op| op.is_lens_correction()))
.then(|| raw.opcodes.list3.clone());
raw.opcodes.list3.retain(|op| !op.is_lens_correction());
// A camera profile without a tone curve of its own (most chart-made ones: a matrix, maybe a hue/saturation map)
// keeps the contrast the photo has without it: the file's own DNG tone curve, else the tone of the look fitted
// to its camera JPEG. (A chart pins colour, not a rendering: its curve would be a choice, and this one is the
// camera's.)
let kept_tone = match dcp {
Some(p) if p.color.profile.tone_curve.is_none() => raw.color.profile.tone_curve.as_ref().and_then(dng_tone_curve).or_else(|| {
let own = raw.color.clone();
// the same proxy as the starting colour's fit below: the DNG's lens opcodes back in, no embedded lens
let tone = with_dng_lens_ops(&mut raw, dng_lens_ops.as_ref(), lens.as_ref(), list3, |raw, embedded| {
crate::camera_preview::starting_colour(raw, &bytes, lens_geometry.as_ref(), embedded)
})
.2
.map(|look| look.tone);
raw.color = own;
tone
}),
_ => None,
};
// An imported camera profile replaces the file's colour model (its matrices and look; the shot's white stays), so
// the starting colour and the white balance scale below come from it, not from a fitted or built-in look.
// (the white balance stays on the scale the file and its camera give, the one the catalog's
// `Photo::relative_wb` and the quick previews use: a profile's matrices must not turn a relative white balance
// into Kelvin, which would read existing edits as absolute temperatures)
let own_scale = dcp.map(|_| WbScaleOf::new(raw.format, &raw.color, raw.wb_multipliers, &raw.metadata));
if let Some(p) = dcp {
raw.color = p.applied_to(&raw.color);
}
// Which scale white balance is edited on, and the as-shot white on it, from the file's own colour tags or
// the camera's measured matrices (`Photo::relative_wb` decides the same from the catalog's camera)
let scale = WbScaleOf::new(raw.format, &raw.color, raw.wb_multipliers, &raw.metadata);
let scale = match &own_scale {
Some(own) => scale.keeping_classification_of(own),
None => scale,
};
// the source's segmentation mattes (DNG semantic masks), read while the starting colour is fitted
let ((xy, t, camera_look), mattes) = rayon::join(
|| {
let removed = dng_lens_ops.map(|ops| std::mem::replace(&mut raw.opcodes.list3, ops));
// With the opcodes restored, the proxy already includes vignetting; do not apply it twice.
let embedded = if removed.is_some() { None } else { lens.as_ref() };
let colour = crate::camera_preview::starting_colour(&mut raw, &bytes, lens_geometry.as_ref(), embedded);
if let Some(ops) = removed {
raw.opcodes.list3 = ops;
}
colour
with_dng_lens_ops(&mut raw, dng_lens_ops.as_ref(), lens.as_ref(), list3, |raw, embedded| {
crate::camera_preview::starting_colour(raw, &bytes, lens_geometry.as_ref(), embedded)
})
},
|| dng_mattes(&bytes, &info),
);
@@ -183,7 +224,12 @@ fn load_bytes_now(
let tags = lightcraft_raw::ColorData { profile: Default::default(), ..raw.color.clone() };
Arc::new(lightcraft_pipeline::CameraColor { tags, developed_for: xy })
});
let camera_tone = camera_look.as_ref().map(|p| p.tone).or_else(|| raw.color.profile.tone_curve.as_ref().and_then(dng_tone_curve));
let camera_tone = camera_tone_of(
dcp.is_some(),
camera_look.as_ref().map(|p| p.tone),
raw.color.profile.tone_curve.as_ref().and_then(dng_tone_curve),
kept_tone,
);
let local_tone = local_tone(&raw);
let (temp, tint) = scale.as_shot(xy);
return Ok((
@@ -262,6 +308,13 @@ impl WbScaleOf {
WbScaleOf { own_matrix, relative: fitted && !covered, legacy_relative: fitted && covered, scale_white, camera }
}
/// This scale (a raw's, with an imported camera profile's colour model) on the white-balance scale `own` (the
/// same raw's with its own colour) gives: relative, or Kelvin edited on the relative scale before. The matrices,
/// and so the colour and the as-shot reading, stay this scale's.
pub(super) fn keeping_classification_of(self, own: &WbScaleOf) -> Self {
WbScaleOf { relative: own.relative, legacy_relative: own.legacy_relative, ..self }
}
/// What a DNG of this raw's camera RGB declares so that it shows the white balance as this scale does: the
/// camera's measured matrices when they give the scale, else the white the scale shows at As Shot (the presets'
/// reading; 6500 K / 0 on the relative scale; else `own`, the white the file's tags give).
@@ -348,3 +401,105 @@ pub(crate) fn dng_tone_curve(curve: &lightcraft_raw::profile::ToneCurve) -> Opti
});
lightcraft_pipeline::tone::CameraTone::new(knots)
}
/// A raw's `OpcodeList3`.
fn list3(raw: &mut lightcraft_raw::RawImage) -> &mut Vec<lightcraft_raw::Opcode> {
&mut raw.opcodes.list3
}
/// `fit(raw, embedded)` with a DNG's lens opcodes `ops` back in `raw`'s `OpcodeList3` (`list3`), as its preview has
/// them applied, and the list as it was afterwards. With the opcodes restored the proxy already includes the
/// vignetting, so `embedded` is `None` then (else `lens`): every tone fit of one photo sees the same proxy.
fn with_dng_lens_ops<R, L, T>(
raw: &mut R,
ops: Option<&Vec<lightcraft_raw::Opcode>>,
lens: Option<&L>,
list3: fn(&mut R) -> &mut Vec<lightcraft_raw::Opcode>,
fit: impl FnOnce(&mut R, Option<&L>) -> T,
) -> T {
let removed = ops.map(|ops| std::mem::replace(list3(raw), ops.clone()));
let embedded = if removed.is_some() { None } else { lens };
let out = fit(raw, embedded);
if let Some(ops) = removed {
*list3(raw) = ops;
}
out
}
/// The tone a raw's starting look gets from its camera: `look` (the tone of the look fitted to the camera JPEG),
/// `curve` (the colour model's own tone curve: the file's, or with an imported camera profile, the profile's) and
/// `kept` (the photo's own tone, kept for a profile without a curve). With a camera profile (`profile`), its curve
/// comes first, then the kept tone, and the fitted look's only last: the look was fitted without the profile, so it
/// must not replace the profile's curve or the contrast kept for it. Without one, the fitted look leads as before.
fn camera_tone_of<T>(profile: bool, look: Option<T>, curve: Option<T>, kept: Option<T>) -> Option<T> {
if profile { curve.or(kept).or(look) } else { look.or(curve).or(kept) }
}
#[cfg(test)]
mod camera_tone_tests {
use super::camera_tone_of;
/// CodeRabbit on #1063: with an imported camera profile, a fitted camera look's tone replaced the profile's own
/// tone curve and the tone kept for a profile without one. Without a profile the order is unchanged.
#[test]
fn a_camera_profiles_curve_and_kept_tone_come_before_the_fitted_look() {
assert_eq!(camera_tone_of(true, Some("look"), Some("profile"), Some("kept")), Some("profile"));
assert_eq!(camera_tone_of(true, Some("look"), None, Some("kept")), Some("kept"));
assert_eq!(camera_tone_of(true, Some("look"), None, None), Some("look"));
assert_eq!(camera_tone_of(false, Some("look"), Some("file"), Some("kept")), Some("look"));
assert_eq!(camera_tone_of(false, None, Some("file"), Some("kept")), Some("file"));
assert_eq!(camera_tone_of::<&str>(false, None, None, None), None);
}
}
#[cfg(test)]
mod wb_scale_tests {
use super::WbScaleOf;
/// CodeRabbit on #1063: a raw edited on the relative white-balance scale (no colour matrices, none measured for
/// its camera) turned to Kelvin once an imported camera profile's matrices replaced its colour, so its existing
/// edits (6500 K / 0 = as shot) were read as absolute temperatures, and the catalog and quick previews still
/// used the relative scale. The profile's matrices stay; the scale is the file's.
#[test]
fn a_camera_profile_keeps_a_relative_white_balance_relative() {
let format = lightcraft_raw::RawFormat::Cr3;
let meta = lightcraft_meta::Metadata::default();
let own_color = lightcraft_raw::ColorData::default();
let own = WbScaleOf::new(format, &own_color, Some([2.0, 1.0, 1.5]), &meta);
assert!(own.relative && !own.own_matrix, "a matrix-less raw of an unmeasured camera is relative");
let m = lightcraft_color::Mat3([[0.9, 0.1, 0.0], [0.1, 0.8, 0.1], [0.0, 0.2, 0.8]]);
let profiled = lightcraft_raw::ColorData { illuminant: [21, 0], color_matrix: [Some(m), None], ..Default::default() };
let with = WbScaleOf::new(format, &profiled, Some([2.0, 1.0, 1.5]), &meta);
assert!(!with.relative, "the profile's matrices alone would make it Kelvin");
let kept = with.keeping_classification_of(&own);
assert!(kept.relative && !kept.legacy_relative && kept.own_matrix, "relative, with the profile's matrices");
assert_eq!(kept.as_shot(lightcraft_color::Xy { x: 0.3127, y: 0.329 }), (6500.0, 0.0));
}
}
#[cfg(test)]
mod lens_ops_tests {
use lightcraft_raw::Opcode;
use super::with_dng_lens_ops;
fn same(v: &mut Vec<Opcode>) -> &mut Vec<Opcode> {
v
}
/// Both tone fits of a DNG (the kept tone for a camera profile without a curve, and the starting colour) see its
/// lens opcodes restored and no embedded lens; the list is as it was afterwards (CodeRabbit on #1063: the
/// kept-tone fit ran without the opcodes and with the embedded lens).
#[test]
fn a_dngs_tone_fit_sees_its_lens_opcodes_and_no_embedded_lens() {
let vignette = Opcode::FixVignetteRadial { k: [0.1, 0.0, 0.0, 0.0, 0.0], center: [0.5, 0.5] };
let ops = vec![vignette.clone()];
let mut list: Vec<Opcode> = Vec::new();
let lens = 7;
let seen = with_dng_lens_ops(&mut list, Some(&ops), Some(&lens), same, |l, embedded| (l.clone(), embedded.copied()));
assert_eq!(seen, (vec![vignette], None), "the opcodes are in, the embedded lens is not");
assert!(list.is_empty(), "the list is as it was");
let seen = with_dng_lens_ops(&mut list, None, Some(&lens), same, |l, embedded| (l.len(), embedded.copied()));
assert_eq!(seen, (0, Some(7)), "without DNG lens opcodes the embedded lens is used");
}
}
+7
View File
@@ -149,6 +149,13 @@ pub fn probe_bytes(name: &str, bytes: &[u8]) -> Result<ProbeInfo, String> {
}
Err(Err(e)) => return Err(e),
};
// what the Exif reader can't see, the decoder may have read from the raw's own records (a CRW keeps make,
// model and capture time in CIFF records, no Exif): it fills the gaps, so the catalog knows the camera
let (meta, captured) = {
let mut m = m.clone();
m.fill_missing(&raw.metadata);
meta_of(&m)
};
let (w, h) = raw.developed_size();
let (mut w, mut h) = (w.max(1) as u32, h.max(1) as u32);
if raw.orientation.swaps_axes() {
+39 -4
View File
@@ -44,6 +44,30 @@ fn psd_probe_reads_embedded_capture_time_gps_and_title() {
use super::*;
use lightcraft_codecs::{ChromaSubsampling, EncodeImage, EncodeMeta, Samples, encode_jpeg};
#[test]
fn crw_probes_name_their_camera_from_the_ciff_records() {
// no Exif in a CRW: the camera and capture time come from the decoder's records, and the catalog's camera
// string decides the white-balance scale (the D60 has chart-measured matrices, the 10D none)
let dir = std::env::var_os("LIGHTCRAFT_CORPUS")
.map(std::path::PathBuf::from)
.unwrap_or_else(|| std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus"))
.join("raw");
for (name, camera, kelvin) in [("crw-canon-eos-d60.crw", "Canon Canon EOS D60", true), ("crw-canon-eos-10d-a.crw", "Canon Canon EOS 10D", false)]
{
let Ok(bytes) = std::fs::read(dir.join(name)) else {
lightcraft_testkit::skip!(Corpus, "{name} absent");
continue;
};
assert!(lightcraft_meta::extract(&bytes).model.is_none(), "{name}: no Exif to read");
let info = probe_bytes(name, &bytes).unwrap();
assert_eq!(info.meta.camera, camera, "{name}");
assert!(info.captured.is_some(), "{name}");
assert_eq!(lightcraft_catalog::relative_wb_camera(&info.format, &info.meta.camera), !kelvin, "{name}");
let (t, _) = info.as_shot_wb.unwrap();
assert_eq!(t != 6500.0, kelvin, "{name}: {t}");
}
}
/// Which white-balance scale a raw gets (issue #730): a file with matrices of its own is absolute from them; a
/// fitted-look file is absolute through its camera's measured matrices, which only read the as-shot
/// multipliers as Kelvin; any other raw stays relative (6500 / 0 = as shot). The catalog's decision from the
@@ -110,6 +134,17 @@ fn white_balance_scale_follows_the_files_matrices_then_the_cameras() {
assert!(other.relative && other.scale_white.is_none());
let unknown = WbScaleOf::new(RawFormat::Nef, &ColorData::default(), mul, &lightcraft_meta::Metadata::default());
assert!(unknown.relative && unknown.as_shot(d65) == (6500.0, 0.0));
// CRW: no matrices in the file. The EOS D60 has chart-measured matrices: Kelvin through them, its multipliers
// for the sun its D50 matrix was measured under reading as D50; another body stays relative, so its
// JPEG-fitted look applies
let d60 = WbScaleOf::new(RawFormat::Crw, &ColorData::default(), Some([2.362, 1.0, 1.298]), &meta("Canon", "Canon EOS D60"));
assert!(!d60.own_matrix && !d60.relative && d60.legacy_relative && d60.scale_white.is_some());
let ((t, tint), (t50, tint50)) = (d60.as_shot(d65), xy_to_temp_tint(lightcraft_color::D50));
assert!((t - t50).abs() < 50.0 && (tint - tint50).abs() < 2.0, "{t} {tint} vs D50 {t50} {tint50}");
assert!(!lightcraft_catalog::relative_wb_camera("CRW", "Canon Canon EOS D60"));
let crw = WbScaleOf::new(RawFormat::Crw, &ColorData::default(), mul, &meta("Canon", "Canon EOS 10D"));
assert!(crw.relative && !crw.legacy_relative && crw.scale_white.is_none());
assert!(lightcraft_catalog::relative_wb_camera("CRW", "Canon Canon EOS 10D"));
// a file with matrices of its own (DNG): absolute from them, no matter whose camera
let own = ColorData { illuminant: [21, 0], color_matrix: [Some(lightcraft_color::Mat3::IDENTITY), None], ..Default::default() };
let dng = WbScaleOf::new(RawFormat::Dng, &own, mul, &meta("SONY", "ILCE-7M3"));
@@ -556,7 +591,7 @@ fn cached_denoise_uses_the_same_white_balance_profile_and_orientation_as_plain_r
product::write(&path, &camera_rgb, key).unwrap();
let spec = DenoiseSpec { product: path, key: key.into(), make: None };
let (ordinary, _) = load_bytes(&bytes, 2048).unwrap();
let (plain, cached, _) = load_vec_pair(bytes, 2048, &spec).unwrap();
let (plain, cached, _) = load_vec_pair(bytes, 2048, &spec, None).unwrap();
assert_eq!(plain.data, ordinary.data, "requesting a twin must not change the ordinary path");
let cached = cached.unwrap();
assert_eq!((plain.width, plain.height), (24, 32));
@@ -1220,10 +1255,10 @@ fn exports_never_develop_a_dngs_reduced_copy() {
let mean = |img: &lightcraft_raster::Rgba8| img.data.iter().map(|p| p[1] as f64).sum::<f64>() / img.data.len().max(1) as f64;
// the loaders: only the thumbnail's develops the copy, and only when it covers the size
let (copy, _, used) = load_vec_reduced(bytes.clone(), 512).unwrap();
let (copy, _, used) = load_vec_reduced(bytes.clone(), 512, None).unwrap();
assert!(used, "a thumbnail develops the copy");
assert!(!load_vec_reduced(bytes.clone(), 1024).unwrap().2, "no copy covers 1024 px");
let (full, _) = load_vec(bytes.clone(), 512).unwrap();
assert!(!load_vec_reduced(bytes.clone(), 1024, None).unwrap().2, "no copy covers 1024 px");
let (full, _) = load_vec(bytes.clone(), 512, None).unwrap();
assert!(g(&copy) > 4.0 * g(&full), "the fixture's copy is much brighter: {} vs {}", g(&copy), g(&full));
let dir = std::env::temp_dir().join(format!("lc-reduced-export-{}", std::process::id()));
+4 -3
View File
@@ -9,6 +9,10 @@ use super::{HashMap, Op, Path, PathBuf, Photo, PhotoId, ProbeInfo, Session, Sour
pub(super) struct Plan {
pub(super) slots: Vec<Slot>,
pub(super) transfers: Vec<Transfer>,
/// The content hashes and name families of [`Plan::transfers`], so each new file is checked against them in
/// constant time rather than by scanning the pending transfers.
pub(super) pending_hashes: std::collections::HashSet<String>,
pub(super) pending_families: std::collections::HashSet<(String, String)>,
}
pub(super) enum Slot {
@@ -26,9 +30,6 @@ pub(super) struct Transfer {
pub(super) how: How,
/// Copy as DNG.
pub(super) dng: bool,
/// The folder (lowercase) and [`name_family`]: transfers of one family can take each other's
/// names, so they never run at the same time.
pub(super) family: (String, String),
}
pub(super) enum How {
+9 -3
View File
@@ -329,7 +329,7 @@ impl ImportJob {
// a copy of a file whose transfer is still pending: a duplicate only if that one succeeds
if !opts.local
&& let Some(h) = &info.content_hash
&& plan.transfers.iter().any(|t| t.info.content_hash.as_ref() == Some(h))
&& plan.pending_hashes.contains(h)
{
self.run_plan(&mut plan, &mut out, cancel);
if cancel.load(Relaxed) {
@@ -403,7 +403,7 @@ impl ImportJob {
// into the same folder ends up with: that one goes first
let as_named = name.as_deref().unwrap_or(if own.is_empty() { "photo" } else { own.as_str() });
let family = (dir.to_string_lossy().to_lowercase(), name_family(as_named));
if plan.transfers.iter().any(|t| t.family == family) {
if plan.pending_families.contains(&family) {
self.run_plan(&mut plan, &mut out, cancel);
if cancel.load(Relaxed) {
break;
@@ -421,7 +421,10 @@ impl ImportJob {
// Copy as DNG: the copied raw becomes a DNG (the copy is ours to replace)
let dng = opts.convert_dng && mode == ImportMode::Copy && raw && !info.format.eq_ignore_ascii_case("DNG");
plan.slots.push(Slot::Transfer);
plan.transfers.push(Transfer { path, info, sidecar, dir, how, dng, family });
// (transfers of one folder and name family can take each other's names, so they never run together)
plan.pending_families.insert(family);
plan.pending_hashes.extend(info.content_hash.clone());
plan.transfers.push(Transfer { path, info, sidecar, dir, how, dng });
continue;
}
(ImportMode::Move, _) => {
@@ -444,6 +447,8 @@ impl ImportJob {
/// Run the transfers `plan` collected (on several threads) and append its items to `out` in
/// file order. Transfers not started because `cancel` was set leave no item.
fn run_plan(&mut self, plan: &mut Plan, out: &mut Prepared, cancel: &std::sync::atomic::AtomicBool) {
plan.pending_hashes.clear();
plan.pending_families.clear();
let mut done = run_transfers(std::mem::take(&mut plan.transfers), self.file_bytes.as_ref(), cancel, &self.done).into_iter();
for slot in std::mem::take(&mut plan.slots) {
let item = match slot {
@@ -507,6 +512,7 @@ impl Session {
stages: None,
view_cache: None,
display: None,
on_screen: false,
slide: None,
preview_cut: None,
display_fit: None,
+1 -1
View File
@@ -14,7 +14,7 @@ fn fixture(preview_edge: Option<usize>, renderable: bool, preview_only: bool) ->
let mut session = Session::new();
let reads = Arc::new(AtomicUsize::new(0));
let count = reads.clone();
session.media.file_loader = Some(Arc::new(move |_, edge| {
session.media.file_loader = Some(Arc::new(move |_, edge, _| {
count.fetch_add(1, Ordering::SeqCst);
if !renderable {
return Err("synthetic raw cannot be rendered".into());
+187 -29
View File
@@ -1,38 +1,153 @@
//! Lens profile corrections from a lens database the user supplies ([`lightcraft_lensdb`]).
//! Lens profile corrections from a lens database ([`lightcraft_lensdb`]).
//!
//! When a raw carries no lens correction of its own (DNG opcodes, or a camera correction a raw reader converts,
//! [`crate::files::embedded_lens`]), the lens named in its EXIF is looked up in a lensfun-format database: the
//! directory in `LIGHTCRAFT_LENSFUN_DIR` (e.g. lensfun's `data/db`, CC-BY-SA, which is never bundled with the app).
//! The profile is converted to the same [`lightcraft_develop::EmbeddedLens`] form, so "Enable Profile Corrections", its
//! amount sliders, the GPU path and DNG export treat both alike. Without the variable nothing changes.
use std::path::PathBuf;
use std::sync::OnceLock;
//! [`crate::files::embedded_lens`]), the lens named in its EXIF is looked up in a lensfun-format database. The
//! database is lensfun's `data/db` (CC BY-SA 3.0): never bundled with the app, it is downloaded at run time into the
//! app's data folder ([`crate::lensfun_download`], which the desktop app offers on its first launch and Settings can start), or it is the
//! directory in `LIGHTCRAFT_LENSFUN_DIR` (which wins). The profile is converted to the same
//! [`lightcraft_develop::EmbeddedLens`] form (marked [`LensSource::Database`]), so "Enable Profile Corrections", its
//! amount sliders, the GPU path and DNG export treat both alike. Without a database nothing changes.
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, PoisonError, RwLock};
use lightcraft_develop::EmbeddedLens;
use lightcraft_develop::{EmbeddedLens, LensSource};
use lightcraft_lensdb::{LensDb, Shot};
/// The environment variable naming the lens database directory.
pub const ENV: &str = "LIGHTCRAFT_LENSFUN_DIR";
/// The configured database, read once per process; `None` when none is configured or it holds no lenses.
pub fn database() -> Option<&'static LensDb> {
static DB: OnceLock<Option<LensDb>> = OnceLock::new();
DB.get_or_init(|| {
let dir = PathBuf::from(std::env::var_os(ENV)?);
match LensDb::load_dir(&dir) {
Ok((db, errors)) => {
for (file, e) in errors {
log::warn!("lens database: skipped {file}: {e}");
}
(!db.lenses.is_empty()).then_some(db)
}
Err(e) => {
log::warn!("{e}");
None
/// The database folder a host set up ([`use_dir`]), read when `LIGHTCRAFT_LENSFUN_DIR` is not set.
static HOST_DIR: RwLock<Option<PathBuf>> = RwLock::new(None);
/// The loaded database and the folder it was read from (`None` inside: nothing usable there).
static LOADED: RwLock<Option<(PathBuf, Option<Arc<LensDb>>)>> = RwLock::new(None);
/// Bumped whenever the database in use changes ([`reload`]): photos looked up before may now find a profile.
static GENERATION: AtomicU64 = AtomicU64::new(0);
/// Bumped when the database's files were replaced ([`replaced`]): profiles found before may now be different.
static REPLACED: AtomicU64 = AtomicU64::new(0);
/// Use `dir` (the app's downloaded lensfun data, [`crate::lensfun_download::default_dir`]) when
/// `LIGHTCRAFT_LENSFUN_DIR` is not set. Hosts with a file system call it; tests and sessions that don't stay
/// without a database.
pub fn use_dir(dir: Option<PathBuf>) {
*HOST_DIR.write().unwrap_or_else(PoisonError::into_inner) = dir;
reload();
}
/// The database's files were replaced (a download put a new database in place): read it again, and photos whose
/// profile came from the old one are looked up again too ([`replacements`]).
pub fn replaced() {
REPLACED.fetch_add(1, Ordering::Relaxed);
reload();
}
/// Changes whenever the database's files were replaced ([`replaced`]); selecting a folder ([`use_dir`]) or reading
/// it again doesn't change it, so photos with a profile are not read again at every start.
pub fn replacements() -> u64 {
REPLACED.load(Ordering::Relaxed)
}
/// The folder the host selected ([`use_dir`]), whatever `LIGHTCRAFT_LENSFUN_DIR` says.
pub fn host_dir() -> Option<PathBuf> {
HOST_DIR.read().unwrap_or_else(PoisonError::into_inner).clone()
}
/// Read the database again (after a download or an update): the next lookup sees the new data.
pub fn reload() {
// under the cache lock, so a load of the old files that finishes meanwhile can't be published ([`database`])
let mut loaded = LOADED.write().unwrap_or_else(PoisonError::into_inner);
*loaded = None;
GENERATION.fetch_add(1, Ordering::Relaxed);
}
/// Changes whenever the database in use may have changed.
pub fn generation() -> u64 {
GENERATION.load(Ordering::Relaxed)
}
/// The folder the database is read from: `LIGHTCRAFT_LENSFUN_DIR`, else the host's ([`use_dir`]).
pub fn dir() -> Option<PathBuf> {
source().map(|(d, _)| d)
}
/// [`dir`], and whether it is the app's own downloaded folder (read only when whole, [`crate::lensfun_download::complete`])
/// rather than the user's.
fn source() -> Option<(PathBuf, bool)> {
match std::env::var_os(ENV).filter(|v| !v.is_empty()) {
Some(d) => Some((PathBuf::from(d), false)),
None => HOST_DIR.read().unwrap_or_else(PoisonError::into_inner).clone().map(|d| (d, true)),
}
}
/// The database in use, read once per folder (and again after [`reload`]); `None` when none is configured, the
/// folder is missing or it holds no lenses.
pub fn database() -> Option<Arc<LensDb>> {
let (dir, downloaded) = source()?;
if let Some((d, db)) = LOADED.read().unwrap_or_else(PoisonError::into_inner).as_ref()
&& *d == dir
{
return db.clone();
}
let generation = generation();
// the app's own folder without its marker is a download that never finished: not read (the start fetches it)
let db = if downloaded && !crate::lensfun_download::complete(&dir) {
// info, not a warning: before the first download this is every user's state (logged once per reload)
log::info!("lens database: no finished download in {} yet; lens profiles are not applied", dir.display());
None
} else {
load(&dir, downloaded)
};
let mut loaded = LOADED.write().unwrap_or_else(PoisonError::into_inner);
// a reload while the files were read: they may be the old ones, so they aren't kept (the next call reads again)
if GENERATION.load(Ordering::Relaxed) == generation {
*loaded = Some((dir, db.clone()));
}
db
}
fn load(dir: &Path, downloaded: bool) -> Option<Arc<LensDb>> {
let whose = if downloaded { "downloaded" } else { ENV };
if !dir.is_dir() {
log::warn!("lens database: {} ({whose}) is missing or not a folder", dir.display());
return None;
}
match LensDb::load_dir(dir) {
Ok((db, errors)) => {
for (file, e) in errors {
log::warn!("lens database: skipped {file}: {e}");
}
let (level, line) = summary(dir, whose, &db);
log::log!(level, "{line}");
(!db.lenses.is_empty()).then(|| Arc::new(db))
}
})
.as_ref()
Err(e) => {
log::warn!("{e}");
None
}
}
}
/// The log line for a database read from `dir`: where it is and how many lenses and cameras it has, so a user
/// setting up `LIGHTCRAFT_LENSFUN_DIR` can see whether it was found; a folder without lenses is a warning.
fn summary(dir: &Path, whose: &str, db: &LensDb) -> (log::Level, String) {
let (lenses, cameras) = (db.lenses.len(), db.cameras.len());
if lenses == 0 {
(
log::Level::Warn,
format!("lens database: no lenses in {} ({whose}): lenses 0, cameras {cameras}; lens profiles are not applied", dir.display()),
)
} else {
(log::Level::Info, format!("lens database: read {} ({whose}): lenses {lenses}, cameras {cameras}", dir.display()))
}
}
/// The database's name for the lens a photo's file calls `lens` (taken with `camera`, the make and model as the
/// library shows them): "Canon EF 70-200mm f/2.8L IS II USM". `None` without a database or a match.
pub fn profile_name(db: &LensDb, camera: &str, lens: &str) -> Option<String> {
let cam = camera.split_once(' ').and_then(|(make, model)| db.find_camera(make, model).or_else(|| db.find_camera(make, camera)));
let p = db.find_lens(None, lens, cam)?;
let model = p.models.first()?;
Some(if model.to_lowercase().starts_with(&p.maker.to_lowercase()) || p.maker.is_empty() { model.clone() } else { format!("{} {model}", p.maker) })
}
/// The database profile for a photo with metadata `m`, for its `w × h` (unoriented, default-cropped) image,
@@ -49,10 +164,10 @@ pub fn lookup(db: &LensDb, m: &lightcraft_meta::Metadata, w: f64, h: f64, orient
db.find_lens_named(m.lens_make.as_deref(), &name, camera)?
}
};
let crop = frame_crop_factor(camera.map(|c| c.crop_factor), focal, m.focal_length_35mm);
let crop = frame_crop_factor(camera.and_then(|c| c.crop_factor), focal, m.focal_length_35mm);
let shot = Shot { focal, aperture: m.f_number, distance: None, crop_factor: crop, width: w, height: h };
let corr = lens.correction(&shot)?;
Some(lightcraft_pipeline::optics::reorient_lens(&corr, orientation, w, h))
Some(EmbeddedLens { source: LensSource::Database, ..lightcraft_pipeline::optics::reorient_lens(&corr, orientation, w, h) })
}
/// The crop factor of the recorded frame, which scales the profile's radii: the body's (`camera`), else what the
@@ -73,7 +188,7 @@ pub fn for_raw(raw: &lightcraft_raw::RawInfo, meta: impl FnOnce() -> lightcraft_
crate::files::embedded_lens(raw).or_else(|| {
let db = database()?;
let (w, h) = raw.developed_size();
lookup(db, &meta(), w as f64, h as f64, raw.orientation)
lookup(&db, &meta(), w as f64, h as f64, raw.orientation)
})
}
@@ -102,11 +217,26 @@ mod tests {
}
}
/// The log says where the database was read from and what it holds, and warns when it holds no lenses (#2511).
#[test]
fn the_log_names_the_folder_and_what_it_holds() {
let dir = Path::new("/lensfun/db");
let (level, line) = summary(dir, ENV, &LensDb::parse(DB).unwrap());
assert_eq!(level, log::Level::Info);
assert!(line.contains("lenses 1, cameras 1") && line.contains("/lensfun/db") && line.contains(ENV), "{line}");
let (level, line) = summary(dir, "downloaded", &LensDb::parse("<lensdatabase></lensdatabase>").unwrap());
assert_eq!(level, log::Level::Warn);
assert!(line.contains("no lenses") && line.contains("downloaded") && line.contains("lenses 0, cameras"), "{line}");
}
#[test]
fn exif_lens_is_found_and_converted() {
let db = LensDb::parse(DB).unwrap();
let lens = lookup(&db, &meta(), 6000.0, 4000.0, Orientation::Normal).unwrap();
assert!(lens.warp.is_some() && lens.vignette.is_some());
assert_eq!(lens.source, LensSource::Database, "the Optics panel says where it came from");
assert_eq!(profile_name(&db, "Testcam TC-1", "18-55mm F3.5-5.6").as_deref(), Some("Testcam 18-55mm f/3.5-5.6"));
assert_eq!(profile_name(&db, "Testcam TC-1", "70-200mm F4"), None);
let rotated = lookup(&db, &meta(), 6000.0, 4000.0, Orientation::Rotate90).unwrap();
assert_eq!(rotated.warp.unwrap().center, lightcraft_geom::Point::new(0.5, 0.5));
// no lens name, no focal length, an unknown lens: nothing
@@ -164,7 +294,7 @@ mod tests {
};
let at = |crop: f64, w: f64, h: f64| {
let shot = Shot { focal: 70.0, aperture: Some(2.8), distance: None, crop_factor: Some(crop), width: w, height: h };
db.lenses[0].correction(&shot).unwrap()
EmbeddedLens { source: LensSource::Database, ..db.lenses[0].correction(&shot).unwrap() }
};
let aps_c = lookup(&db, &m(Some(105.0)), 5616.0, 3744.0, Orientation::Normal).unwrap();
assert_eq!(aps_c, at(1.5, 5616.0, 3744.0));
@@ -177,6 +307,34 @@ mod tests {
assert_eq!(frame_crop_factor(Some(1.0), 0.0, Some(105.0)), Some(1.0), "a hostile focal length is ignored");
}
#[test]
fn unknown_camera_crop_uses_exif_equivalent_without_full_frame_assumption() {
for crop in [
"",
"<cropfactor/>",
"<cropfactor>bad</cropfactor>",
"<cropfactor>NaN</cropfactor>",
"<cropfactor>inf</cropfactor>",
"<cropfactor>0.049</cropfactor>",
"<cropfactor>21</cropfactor>",
] {
let xml = DB.replacen("<cropfactor>1.5</cropfactor>", crop, 1).replace("-0.03", "-0.003").replace("-0.4", "-0.04");
let db = LensDb::parse(&xml).unwrap();
// A below-1 crop exposes the old synthetic 1.0 body: the 10% crop-mode policy would keep it.
let m = lightcraft_meta::Metadata { focal_length_35mm: Some(17.1), ..meta() };
let expected = db.lenses[0]
.correction(&Shot { focal: 18.0, aperture: Some(3.5), distance: None, crop_factor: Some(17.1 / 18.0), width: 6000.0, height: 4000.0 })
.map(|lens| EmbeddedLens { source: LensSource::Database, ..lens })
.unwrap();
assert_eq!(lookup(&db, &m, 6000.0, 4000.0, Orientation::Normal).unwrap(), expected, "{crop}");
let fallback = db.lenses[0]
.correction(&Shot { focal: 18.0, aperture: Some(3.5), distance: None, crop_factor: None, width: 6000.0, height: 4000.0 })
.map(|lens| EmbeddedLens { source: LensSource::Database, ..lens })
.unwrap();
assert_eq!(lookup(&db, &meta(), 6000.0, 4000.0, Orientation::Normal).unwrap(), fallback, "no equivalent: {crop}");
}
}
/// A synthetic grid recorded through the profile's barrel distortion comes out of the pipeline's geometry
/// stage with straight lines.
#[test]
+837
View File
@@ -0,0 +1,837 @@
//! The lensfun lens database, downloaded on request: the desktop app offers it once on the first launch
//! ([`fetch_on_start`]: nothing is fetched without the user's click).
//!
//! lensfun's `data/db` (CC BY-SA 3.0, <https://github.com/lensfun/lensfun>) is data, never bundled with LightCraft and
//! never committed to its repository: the desktop app fetches it at run time, when the user chooses Download, into its data folder
//! ([`default_dir`]), with a row in the activity stack, and [`crate::lens_profiles`] reads it from there. The files are
//! pinned to one lensfun commit ([`COMMIT`]) by name, size and SHA-256 ([`FILES`]), so whatever mirror serves them
//! ([`URL_ENV`] lists others, e.g. a copy on LightCraft's own server), what arrives is exactly that commit's data or
//! it is thrown away. A new pin in a later build replaces the folder's files once ([`installed`] compares the pin).
//!
//! The transfer is [`lightcraft_fetch`] (pure-Rust HTTPS, resume, size and hash checks) on a background thread; the
//! files land in a staging folder beside the database folder, the marker is written there last, and only then does the
//! staged folder replace the database folder as a whole ([`publish`]): the previous complete database stays in use
//! until the new one is in place, and comes back if the swap fails. The loader reads the app's folder only when it has
//! the marker ([`complete`]), and [`installed`] also checks every pinned file is there, so a damaged folder is
//! downloaded again. Failure is a message, never a panic.
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, PoisonError};
use crate::activity::{Activity, Cancel, TaskHandle, Unit};
/// The lensfun commit the files are pinned to (2026-10-08).
pub const COMMIT: &str = "43f9e001ab66c4fcdd4f400463f13b72f94b2288";
/// Where the files are fetched from by default: lensfun's repository at [`COMMIT`].
pub const DEFAULT_MIRROR: &str = "https://raw.githubusercontent.com/lensfun/lensfun/43f9e001ab66c4fcdd4f400463f13b72f94b2288/data/db";
/// Other places to fetch the same files from, tried first (base URLs separated by commas or spaces).
pub const URL_ENV: &str = "LIGHTCRAFT_LENSFUN_URL";
/// The file written once every database file is in place: the pin it holds says which data the folder has.
pub const MARKER: &str = "SOURCE.txt";
/// The suffix of the folder beside the database folder where files wait until all have arrived.
#[cfg(not(target_arch = "wasm32"))]
const STAGING: &str = "download";
/// The suffix of the folder the previous database is moved to while the new one takes its place.
const PREVIOUS: &str = "previous";
/// The suffix of the file that says a download into the folder is under way (another window or session of the
/// app may be the one downloading).
#[cfg(not(target_arch = "wasm32"))]
const LOCK: &str = "lock";
/// Largest database file accepted (the biggest is under 1 MB).
#[cfg(not(target_arch = "wasm32"))]
const MAX_FILE: u64 = 8 << 20;
/// The database files at [`COMMIT`]: name, size in bytes, SHA-256.
pub const FILES: &[(&str, u64, &str)] = &[
("6x6.xml", 29550, "ca13c2756b32d728675372695c072517a0e38af5eff2ecd3e17599dee7fc58b3"),
("actioncams.xml", 17188, "79a5da0322574b95690464444c9d9ba1da0e1f827da44fd6bff120a0ec10e4b4"),
("compact-canon.xml", 247046, "bae47e4b3a0f8852641038ae2dcca5b28ed7965e65ca795fd676f9de857c4670"),
("compact-casio.xml", 6889, "ab35433879c4574ef8f97cd4e3d114d7ff8db4e7279da9d502fc9e911b51ee27"),
("compact-fujifilm.xml", 67954, "58af9ebef2410c428ae2c5d01003d2247330d47d918823e63522b4d897a997d1"),
("compact-kodak.xml", 2091, "377018ccd74f58e966b37a11e5a8689be4268153bebece9f1f2a0dbfa8234845"),
("compact-konica-minolta.xml", 13349, "832a7473951ab625e10c48af6cf60f89b57280016d45729e2584cf9e41ad3cc7"),
("compact-leica.xml", 9113, "8e4676679377576dc19e7900ce86fc69b0248ea1d4538aa22ee1ee09431a3be3"),
("compact-nikon.xml", 40003, "5393bdb8223e13d21b85818e96571e97c035470b49b0452dfcedc2e1ff512d3b"),
("compact-olympus.xml", 34454, "7637d469ad54a02ebce9492a9aa9424a2ff1ec07b0398158076f762fdc08389b"),
("compact-panasonic.xml", 70621, "f191fc2a5d49fb50c06f4c399ee8c1a83a05f93a0efaecd352ec5c1479b8e60b"),
("compact-pentax.xml", 6689, "596fae3edaadcf2d90ae930fc1bec42597ca0b2bd11842e686e1b915f3736390"),
("compact-ricoh.xml", 18424, "46df96ebc367d5170cb6b7dfc3742093f0ad946264518fc5488573ba052f29d7"),
("compact-samsung.xml", 13875, "36e3a778046d56385c387d48474cd32a89a5da94d99e640b5ce716ce747f898d"),
("compact-sigma.xml", 2395, "0ddc265e3e580da05dcd4664d1b9c2464838d74dd02519c826520950c8f1759e"),
("compact-sony.xml", 126229, "be146388b4f6f7bf0d73394e20386ce6ccef3559ab39f1268ba3c14aaef03207"),
("contax.xml", 1696, "5eba12e6fd4913470afb6fe25fee47a263084b6cec830297273909872f47669a"),
("generic.xml", 5416, "cd572d4110981546b2c4cd296c2ff16755b30063fa136d8b06ad2ca13ab4c59f"),
("mil-canon.xml", 247994, "2de8e9467a6af6f83cc9da834d3d3b94d1aaf54519f60c68ac6bc02780a77516"),
("mil-fujifilm.xml", 210586, "64586336153b948fe2325f6c46679149a4e3c114a70bee4bd1de88721cb4de72"),
("mil-hasselblad.xml", 1048, "13e1fa55d36c2ed7d22964c21ce6c21d887bfe4506e840e425da1ce4157c3756"),
("mil-leica.xml", 11663, "c691037e2e0743388473c2a0545e340462c412b7e3b57e451f4f9c89dde2388a"),
("mil-nikon.xml", 178941, "dcae5ec2e505411a7f00b6b8dd03825e55620403b558b156be15e9ddfbeaf159"),
("mil-olympus.xml", 147123, "989a3d88ef07a286efc2755df214792fdf71d60366932a1b369a77ad39cf2abb"),
("mil-panasonic.xml", 299264, "eb5f01f33e65721f3900786d5970c7e220dd042aaa56968be33c009a358ff3c5"),
("mil-pentax.xml", 1385, "675a94f52794868ad9f1d79e17b7128783c34b3db23e9eac346c5963812a16e5"),
("mil-samsung.xml", 13007, "10130e9e125e0882a16fd3033cfed0175e9c14cb7d35e630cdb94736f27e5dc3"),
("mil-samyang.xml", 25990, "ae3bf262f12facdc6f81b837cf6d36fdde2a930d2bfb0918d5abaa47fcfea3ab"),
("mil-sigma.xml", 126080, "5f39b232efba5c208e5a98d8afe92cb2eee879213322d47827fcc6f0dc3a06f9"),
("mil-sony.xml", 274541, "f9f7e5d7461ac58f76eb55dcc5b211f2e9a451402ddb4a9ecb12d1e4dc04f2b8"),
("mil-tamron.xml", 106950, "2f0c9c4dfb9b0419ba0fac2e618bc251c2e71e068b6e09a23d7994b0ff62db0a"),
("mil-tokina.xml", 1014, "addb27bd82b0d729644b9da1342f92401f63cc5945309ed17f38f4b7af1649e3"),
("mil-zeiss.xml", 19171, "ef8a238904fc9ea6fdb6171863dfd70cd94814af19ecd8c31ee000ca1864589d"),
("misc.xml", 176039, "2000a347d9dc37d908ea5b56c760de5b2b4ab475857959ae2e901c31339b01bb"),
("om-system.xml", 35344, "a53a627e6ba79fbabb0fa7552ce2b6e56e206425d2eaf0e8ccdb6b8c40c20755"),
("rf-leica.xml", 6712, "f93636e1980ad308d1873cc3ac078cdc77c0d529d777cd45c5c8d0e4781981e3"),
("slr-canon.xml", 780353, "5244e6df8f2522f829c57e2073313ce31a624e9ed9605310fe43613b9d588c99"),
("slr-hasselblad.xml", 642, "97602c467699904bf101179ea2fa24f05f3e1879250498a6ba306cd95a3b7a6b"),
("slr-konica-minolta.xml", 47170, "5639ca94f121f609247c2c120b65830b3ef7784db6ecfa7e8eb3d29ff5046c1b"),
("slr-leica.xml", 432, "c5e74cb511712e99ed60a066e85c842fea58f693c5039c3819485619f5293d0e"),
("slr-nikon.xml", 550157, "5e591e8b1032203cce4c822f1da3d49524a78e7d71c594ea5a4533f2e57aacdf"),
("slr-olympus.xml", 116602, "f7693b6779edd8ed10d7dc23113669255bfa4987cea7db0e843f7f5f2bbbe615"),
("slr-panasonic.xml", 419, "cd79acb49d9ce5f2a4cecc572b3e117f03da380bed2dcbfd52327192d8ce2381"),
("slr-pentax.xml", 209552, "2fba773e41a1cfb70f0c85efdab6d78944bf80ddf89bc2035ef6db39da352f29"),
("slr-ricoh.xml", 2869, "c835798136a53535fdf4f81312ac9aad0ea3de3ef732c183d8cc4d2f432011d9"),
("slr-samsung.xml", 1110, "dc0a29e424ff96e4316ddeb76126fa6f6c73a8836905a3e1f56f0c493826148f"),
("slr-samyang.xml", 16811, "fb1585bea91f5f59e1fae8811dd76c92252ee5d52e3647df2aff4695048443b5"),
("slr-schneider.xml", 5890, "de607cfe4ba6e7debc61e282ce39b72825c07601572e14af2bc9108ba67faf81"),
("slr-sigma.xml", 444640, "f55f41c144fbb72e3c51d2dfef40e918930d37db1b4150bd02bd746406c036d2"),
("slr-soligor.xml", 573, "1aba0aab19bce87ea86175b6551cb5306a512eb54be1698b89991b86008f6a04"),
("slr-sony.xml", 88865, "e5ca7f532afe23ff380bf2f9e5458f687bed603355d73a254d85c4e692942fdc"),
("slr-tamron.xml", 201992, "c62090789cebe6bbb663111c6e97beeb1111852bb735088e29cf8782df4bab45"),
("slr-tokina.xml", 91977, "b1213eda81a613bc3976340398c6b8ce8b7dc29423476fc565d5f8e5cf612ecf"),
("slr-ussr.xml", 19024, "1fd6acc8a8f40373379bea2899ffd96fc34b22d9b044d0474dabd4c89af44efb"),
("slr-vivitar.xml", 2157, "c5c67e3fe38e8fa19044acadc7730047690435f66aac563f55ffe04997a88111"),
("slr-zeiss.xml", 14957, "49aa211a41fd5fe391d26af5fa65bdf9428d60863ffff15d3916fa1c520dc101"),
];
/// The app's own copy of the database: `<config dir>/lensfun`.
pub fn default_dir() -> Option<PathBuf> {
crate::config::config_dir().map(|d| d.join("lensfun"))
}
/// The folder holds the pinned data: [`MARKER`] names [`COMMIT`] and every pinned file is there at its pinned size
/// (a folder whose files went missing is downloaded again).
pub fn installed(dir: &Path) -> bool {
installed_with(dir, FILES)
}
fn installed_with(dir: &Path, files: &[Pin]) -> bool {
std::fs::read_to_string(dir.join(MARKER)).is_ok_and(|s| s.contains(COMMIT))
&& files.iter().all(|(name, size, _)| std::fs::metadata(dir.join(name)).is_ok_and(|m| m.is_file() && m.len() == *size))
}
/// The folder holds a whole database, of this pin or an older one: its [`MARKER`], written last, is there. The app's
/// own folder is read only then ([`crate::lens_profiles::database`]).
pub fn complete(dir: &Path) -> bool {
dir.join(MARKER).is_file()
}
/// `dir` with `suffix` added to its name: a folder beside it (`lensfun` → `lensfun.download`).
fn beside(dir: &Path, suffix: &str) -> PathBuf {
let mut name = dir.file_name().map(|n| n.to_os_string()).unwrap_or_default();
name.push(format!(".{suffix}"));
dir.with_file_name(name)
}
/// Put back the previous database when a swap ([`publish`]) was interrupted between its two moves (the app quit or
/// the machine stopped): `dir` is missing and the previous folder is whole. Best effort; says why it couldn't. Done
/// under the folder's download lock (`DirLock`) and skipped while a download, in this or another LightCraft, holds
/// it: that download is between its own two moves, not interrupted, and puts the folder right itself.
pub fn recover(dir: &Path) {
if !needs_recovery(dir) {
return;
}
#[cfg(not(target_arch = "wasm32"))]
let _lock = match DirLock::take(dir) {
Ok(lock) => lock,
Err(e) => {
log::warn!("lens database: the previous database is not put back now: {e}");
return;
}
};
recover_locked(dir);
}
/// What a swap interrupted between its two moves leaves: no database folder, and a whole previous one.
fn needs_recovery(dir: &Path) -> bool {
!dir.exists() && complete(&beside(dir, PREVIOUS))
}
/// [`recover`] by a caller that already holds the folder's lock (a download).
fn recover_locked(dir: &Path) {
if needs_recovery(dir)
&& let Err(e) = std::fs::rename(beside(dir, PREVIOUS), dir)
{
log::warn!("lens database: could not put back the previous database: {e}");
}
}
/// The user's answer to the first-launch offer of the database (the desktop app keeps it in its settings).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum Offer {
/// Not asked yet: the first start asks.
#[default]
Ask,
/// Download was clicked (in the offer or in Settings): a start downloads the pinned database when it is missing
/// or from an older pin (an interrupted or failed download is tried again).
Accepted,
/// Not Now: nothing is downloaded and the start doesn't ask again (Settings can download it, or turn the offer
/// back on).
Declined,
}
/// What a start does about the database ([`fetch_on_start`]).
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Start {
Nothing,
/// Ask the user (once): download into this folder, or not now.
Ask(PathBuf),
/// Download into this folder (the user said yes before).
Fetch(PathBuf),
}
/// The first-start policy, in one place: what a start does about the database. Nothing touches the network
/// without the user's click: the host must allow the question at all (`auto`, [`crate::Session::lens_auto_download`],
/// the desktop app only), a folder of the user's own (`LIGHTCRAFT_LENSFUN_DIR`) is never replaced, an installed
/// database needs nothing, and otherwise the user's answer (`offer`) decides: ask, download, or nothing.
pub fn fetch_on_start(auto: bool, offer: Offer) -> Start {
let own = std::env::var_os(crate::lens_profiles::ENV).is_some_and(|v| !v.is_empty());
let dir = default_dir();
if let Some(d) = dir.as_deref().filter(|_| auto && !own) {
recover(d);
}
let installed = dir.as_deref().is_some_and(installed);
decide(auto, own, dir, installed, offer)
}
/// [`fetch_on_start`] without the file system: `own` (`LIGHTCRAFT_LENSFUN_DIR` is set), the app's folder `dir` and
/// whether it holds the pinned data.
pub fn decide(auto: bool, own: bool, dir: Option<PathBuf>, installed: bool, offer: Offer) -> Start {
let Some(dir) = dir.filter(|_| auto && !own && !installed) else { return Start::Nothing };
match offer {
Offer::Ask => Start::Ask(dir),
Offer::Accepted => Start::Fetch(dir),
Offer::Declined => Start::Nothing,
}
}
/// The download's size in bytes: the pinned files' sizes added up (what the offer says).
pub fn download_size() -> u64 {
FILES.iter().map(|f| f.1).fold(0u64, u64::saturating_add)
}
/// [`download_size`] in whole megabytes for people ("about 5 MB"), never 0.
pub fn download_megabytes() -> u64 {
(download_size().saturating_add(500_000) / 1_000_000).max(1)
}
/// The mirrors to try, in order: [`URL_ENV`]'s, then lensfun's own ([`DEFAULT_MIRROR`]).
pub fn mirrors() -> Vec<String> {
#[cfg(not(target_arch = "wasm32"))]
{
lightcraft_fetch::mirrors(std::env::var(URL_ENV).ok().as_deref(), None, &[DEFAULT_MIRROR])
}
#[cfg(target_arch = "wasm32")]
{
Vec::new()
}
}
/// Where the download stands.
#[derive(Clone, Debug, PartialEq, Eq, Default)]
pub enum State {
/// Not started this session.
#[default]
Idle,
Running {
bytes: u64,
total: u64,
},
/// In place and loaded: `files` database files.
Done {
files: usize,
},
Failed(String),
Cancelled,
}
struct Shared {
state: Mutex<State>,
cancel: Arc<AtomicBool>,
task: Option<TaskHandle>,
}
impl Shared {
fn set(&self, s: State) {
if let (State::Running { bytes, total }, Some(task)) = (&s, &self.task) {
task.progress(*bytes, *total);
}
*self.state.lock().unwrap_or_else(PoisonError::into_inner) = s;
}
fn get(&self) -> State {
self.state.lock().unwrap_or_else(PoisonError::into_inner).clone()
}
}
/// The session's lens database download.
#[derive(Default)]
pub struct Download {
job: Option<Arc<Shared>>,
}
/// One pinned file: name, size in bytes, SHA-256.
pub type Pin = (&'static str, u64, &'static str);
impl Download {
pub fn state(&self) -> State {
self.job.as_ref().map_or(State::Idle, |j| j.get())
}
pub fn running(&self) -> bool {
matches!(self.state(), State::Running { .. })
}
/// Fetch `files` from `mirrors` into `dir` on a background thread, shown in the activity stack until it ends
/// (its ✕ stops it). Started once at a time; when it ends the database is read again
/// ([`crate::lens_profiles::replaced`]).
pub fn start(&mut self, dir: &Path, mirrors: Vec<String>, files: &'static [Pin], activity: &Activity) -> Result<(), String> {
if self.running() {
return Err("the lens database is already downloading".into());
}
if mirrors.is_empty() {
return Err("no download location is configured for the lens database".into());
}
let cancel = Arc::new(AtomicBool::new(false));
let task = activity.start("download", "Downloading the lens database", Cancel::Flag(cancel.clone()));
task.set_unit(Unit::Bytes);
task.detail("lensfun (CC BY-SA 3.0)");
let total = files.iter().map(|f| f.1).fold(0u64, u64::saturating_add);
task.progress(0, total);
let shared = Arc::new(Shared { state: Mutex::new(State::Running { bytes: 0, total }), cancel, task: Some(task.handle()) });
let worker = shared.clone();
let dir = dir.to_path_buf();
std::thread::Builder::new()
.name("lens-database-download".into())
.spawn(move || {
// the row goes when the thread ends, however it ends
let _task = task;
let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| run(&dir, &mirrors, files, &worker)));
if outcome.is_err() {
worker.set(State::Failed("the lens database download stopped unexpectedly".into()));
}
})
.map_err(|e| format!("could not start the lens database download: {e}"))?;
self.job = Some(shared);
Ok(())
}
}
impl Drop for Download {
/// Quitting while it runs stops it (the staged files stay for the next try to resume).
fn drop(&mut self) {
if let Some(j) = &self.job {
j.cancel.store(true, Ordering::Relaxed);
}
}
}
/// The whole job: fetch and check every file into the staging folder, then move them into `dir`, write the marker
/// and read the database again. Always ends in a final [`State`].
fn run(dir: &Path, mirrors: &[String], files: &[Pin], shared: &Shared) {
match fetch_all(dir, mirrors, files, shared) {
Ok(n) => {
crate::lens_profiles::replaced();
shared.set(State::Done { files: n });
}
Err(e) if shared.cancel.load(Ordering::Relaxed) => {
log::info!("lens database download stopped: {e}");
shared.set(State::Cancelled);
}
Err(e) => {
log::warn!("lens database download: {e}");
shared.set(State::Failed(e));
}
}
}
/// Held while one download (or a [`recover`]) uses a folder's staging and previous folders, across sessions and
/// processes: an exclusive operating-system lock on a file beside the folder (`File::try_lock`: `flock` on Unix,
/// `LockFileEx` on Windows), held by the open file. The system lets go of it when the file closes, on drop or when the
/// process ends however it ends, so an app that crashed never leaves the folder locked and no age guess is needed.
/// The file itself stays (empty): removing it would let a second app lock a new file of the same name while the first
/// still holds the old one. Dropping it unlocks explicitly: a process another thread is spawning holds a copy of the
/// file until it execs, and on Unix the lock would last as long as that copy.
#[cfg(not(target_arch = "wasm32"))]
struct DirLock {
file: std::fs::File,
}
#[cfg(not(target_arch = "wasm32"))]
impl Drop for DirLock {
fn drop(&mut self) {
let _ = self.file.unlock();
}
}
#[cfg(not(target_arch = "wasm32"))]
impl DirLock {
fn take(dir: &Path) -> Result<DirLock, String> {
let path = beside(dir, LOCK);
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).map_err(|e| format!("could not create {}: {e}", parent.display()))?;
}
let file = std::fs::OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(&path)
.map_err(|e| format!("could not create {}: {e}", path.display()))?;
match file.try_lock() {
Ok(()) => Ok(DirLock { file }),
Err(std::fs::TryLockError::WouldBlock) => Err("the lens database is already downloading (in another LightCraft window)".into()),
Err(std::fs::TryLockError::Error(e)) => Err(format!("could not lock {}: {e}", path.display())),
}
}
}
#[cfg(not(target_arch = "wasm32"))]
fn fetch_all(dir: &Path, mirrors: &[String], files: &[Pin], shared: &Shared) -> Result<usize, String> {
// (from before the recovery through the swap: another download of this folder would move the same folders)
let _lock = DirLock::take(dir)?;
recover_locked(dir);
let staging = beside(dir, STAGING);
std::fs::create_dir_all(&staging).map_err(|e| format!("could not create {}: {e}", staging.display()))?;
let specs: Vec<lightcraft_fetch::FileSpec<'_>> =
files.iter().map(|(name, size, sha)| lightcraft_fetch::FileSpec { name, size: Some(*size), sha256: Some(sha), max: MAX_FILE }).collect();
let total = files.iter().map(|f| f.1).fold(0u64, u64::saturating_add);
lightcraft_fetch::download(&specs, mirrors, &staging, &lightcraft_fetch::Options::default(), &shared.cancel, &mut |p| {
shared.set(State::Running { bytes: p.done.min(total), total });
})
.map_err(|e| match e {
lightcraft_fetch::DownloadError::AllMirrorsFailed { errors, .. } => {
let detail: String = errors.join("; ").chars().take(300).collect();
format!("could not download the lens database ({detail}): check the internet connection; LightCraft tries again next time it starts")
}
other => other.to_string(),
})?;
// every file is here and checked. The staged folder becomes the database: first without database files another
// pin left in it (a resumed older attempt), then with the marker, written last, then in place of the old folder
// as a whole
remove_stale(&staging, files, |p| std::fs::remove_file(p))?;
let readme = format!(
"lensfun lens database (data/db), commit {COMMIT}
from https://github.com/lensfun/lensfun, downloaded by LightCraft.
Licence: Creative Commons Attribution-ShareAlike 3.0 (https://creativecommons.org/licenses/by-sa/3.0/), by the lensfun contributors.
Data only, read by LightCraft at run time; not part of LightCraft.
"
);
std::fs::write(staging.join(MARKER), readme).map_err(|e| format!("could not write {}: {e}", staging.join(MARKER).display()))?;
publish(&staging, dir, |from, to| std::fs::rename(from, to))?;
Ok(files.len())
}
/// Replace the database folder `dir` with the complete `staged` one, moving with `rename`: the old folder is moved
/// aside, the staged one takes its place, and the old one is removed. When the second move fails the old folder is
/// put back, so `dir` is always either the previous complete database or the new one, never a mix.
#[cfg(not(target_arch = "wasm32"))]
fn publish(staged: &Path, dir: &Path, rename: impl Fn(&Path, &Path) -> std::io::Result<()>) -> Result<(), String> {
let previous = beside(dir, PREVIOUS);
let had = dir.exists();
// left by a swap that ended after its second move: `dir` is the database, so this copy can go. Without `dir`
// (a recovery that couldn't put it back) it may be the only whole database: kept until the new one is in place
if had && previous.exists() {
std::fs::remove_dir_all(&previous).map_err(|e| format!("could not remove {}: {e}", previous.display()))?;
}
if had {
rename(dir, &previous).map_err(|e| format!("could not move the old lens database aside ({}): {e}", dir.display()))?;
}
if let Err(e) = rename(staged, dir) {
if had && let Err(back) = rename(&previous, dir) {
// (the next start puts it back: [`recover`])
log::warn!("lens database: could not put back the previous database yet: {back}");
}
return Err(format!("could not move the new lens database into {}: {e}", dir.display()));
}
if previous.exists()
&& let Err(e) = std::fs::remove_dir_all(&previous)
{
log::warn!("lens database: could not remove the previous database {}: {e}", previous.display());
}
Ok(())
}
/// Remove the XML files in `dir` that are not among `files` (nothing else in the folder is touched) with `remove`: an
/// error names the first that could not be removed, or why the folder could not be listed.
#[cfg(not(target_arch = "wasm32"))]
fn remove_stale(dir: &Path, files: &[Pin], remove: impl Fn(&Path) -> std::io::Result<()>) -> Result<(), String> {
// a folder that can't be listed (or an entry that can't be read) may still hold an old file: an error, not success
let listing = |e: std::io::Error| format!("could not list the lens database folder {}: {e}", dir.display());
for entry in std::fs::read_dir(dir).map_err(listing)? {
let entry = entry.map_err(listing)?;
let name = entry.file_name();
let name = name.to_string_lossy();
let xml = std::path::Path::new(&*name).extension().is_some_and(|e| e.eq_ignore_ascii_case("xml"));
if xml
&& entry.path().is_file()
&& !files.iter().any(|(pinned, _, _)| *pinned == name)
&& let Err(e) = remove(&entry.path())
{
return Err(format!("could not remove the old lens database file {name}: {e}"));
}
}
Ok(())
}
#[cfg(target_arch = "wasm32")]
fn fetch_all(_: &Path, _: &[String], _: &[Pin], _: &Shared) -> Result<usize, String> {
Err("the web build downloads no lens database".into())
}
#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
use super::*;
use std::io::{BufRead, BufReader, Write};
use std::net::TcpListener;
use std::time::Duration;
/// Two downloads into one folder (two windows, or two sessions of one app) never share its staging and previous
/// folders: the second is refused while the first holds the folder, however old the first's lock file is, and
/// may go once it ends; the file an app that quit mid-download leaves holds nothing (the system let go of it).
#[test]
fn one_download_at_a_time_holds_a_folder() {
let d = scratch("lock");
let _ = std::fs::remove_file(beside(&d, LOCK));
let first = DirLock::take(&d).unwrap();
// (a download running for a week on a slow line: its lock file is old, and it still holds the folder)
let old = std::time::SystemTime::now() - Duration::from_secs(7 * 24 * 60 * 60);
std::fs::OpenOptions::new().write(true).open(beside(&d, LOCK)).unwrap().set_modified(old).unwrap();
for _ in 0..3 {
let second = DirLock::take(&d);
assert!(second.as_ref().is_err_and(|e| e.contains("already downloading")), "{:?}", second.as_ref().err());
}
drop(first);
drop(DirLock::take(&d).unwrap());
// (what an app that quit mid-download leaves: the file, unlocked)
assert!(beside(&d, LOCK).exists());
drop(DirLock::take(&d).unwrap());
let _ = std::fs::remove_file(beside(&d, LOCK));
}
/// The start's recovery moves nothing while a download holds the folder: between that download's two moves the
/// folder is missing and the previous one whole, which is not an interrupted swap.
#[test]
fn recovery_leaves_a_folder_a_download_holds() {
let dir = scratch("recover-locked");
std::fs::remove_dir_all(&dir).unwrap();
let previous = beside(&dir, PREVIOUS);
std::fs::create_dir_all(&previous).unwrap();
std::fs::write(previous.join(MARKER), "older").unwrap();
let held = DirLock::take(&dir).unwrap();
recover(&dir);
assert!(!dir.exists() && complete(&previous), "a download's swap is left alone");
drop(held);
recover(&dir);
assert!(complete(&dir) && !previous.exists(), "an interrupted swap is put back");
let _ = std::fs::remove_dir_all(&dir);
let _ = std::fs::remove_file(beside(&dir, LOCK));
}
/// The lock holds across processes: while another process (another LightCraft) holds the folder, a download
/// here is refused; once that process is gone (killed, like a crash), the system has let go and it may start.
#[test]
fn another_process_holding_the_folder_refuses_a_download_here() {
let dir = scratch("lock-child");
let ready = dir.join("child-locked");
let exe = std::env::current_exe().unwrap();
let mut child = std::process::Command::new(exe)
.args(["--exact", "lensfun_download::tests::lock_holder_child", "--ignored", "--test-threads=1"])
.env("LC_LENSFUN_LOCK_CHILD_DIR", &dir)
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.spawn()
.unwrap();
let deadline = std::time::Instant::now() + Duration::from_secs(60);
while !ready.exists() {
assert!(child.try_wait().unwrap().is_none(), "the child exited before locking");
assert!(std::time::Instant::now() < deadline, "the child never locked");
std::thread::sleep(Duration::from_millis(20));
}
let here = DirLock::take(&dir);
let refused = here.as_ref().is_err_and(|e| e.contains("already downloading"));
child.kill().unwrap();
child.wait().unwrap();
assert!(refused, "{:?}", here.as_ref().err());
drop(DirLock::take(&dir).expect("the system let go of the dead process's lock"));
let _ = std::fs::remove_dir_all(&dir);
let _ = std::fs::remove_file(beside(&dir, LOCK));
}
/// Run by [`another_process_holding_the_folder_refuses_a_download_here`] in a child process: take the folder's
/// lock, say so, and wait to be killed.
#[test]
#[ignore = "helper process for another_process_holding_the_folder_refuses_a_download_here"]
fn lock_holder_child() {
let Some(dir) = std::env::var_os("LC_LENSFUN_LOCK_CHILD_DIR") else { return };
let dir = PathBuf::from(dir);
let _held = DirLock::take(&dir).unwrap();
std::fs::write(dir.join("child-locked"), b"").unwrap();
std::thread::sleep(Duration::from_secs(120));
}
/// A swap into a folder that is missing, with the previous database still beside it (a recovery that couldn't
/// put it back), keeps that previous database until the new one is in place: when the new one can't be moved
/// in, the previous one is still there for the next start to put back.
#[test]
fn a_failed_swap_keeps_the_only_whole_database() {
let dir = scratch("keep-previous");
std::fs::remove_dir_all(&dir).unwrap();
let previous = beside(&dir, PREVIOUS);
std::fs::create_dir_all(&previous).unwrap();
std::fs::write(previous.join(MARKER), "older").unwrap();
let staged = beside(&dir, STAGING);
std::fs::create_dir_all(&staged).unwrap();
std::fs::write(staged.join(MARKER), COMMIT).unwrap();
let err = publish(&staged, &dir, |_, _| Err(std::io::Error::other("in use"))).unwrap_err();
assert!(err.contains("in use"), "{err}");
assert!(complete(&previous), "the previous database is kept");
recover(&dir);
assert_eq!(std::fs::read_to_string(dir.join(MARKER)).unwrap(), "older", "and the next start puts it back");
// a swap that works into a missing folder removes the previous copy once the new one is in place
std::fs::remove_dir_all(&dir).unwrap();
std::fs::create_dir_all(&previous).unwrap();
std::fs::write(previous.join(MARKER), "older").unwrap();
publish(&staged, &dir, |from, to| std::fs::rename(from, to)).unwrap();
assert_eq!(std::fs::read_to_string(dir.join(MARKER)).unwrap(), COMMIT);
assert!(!previous.exists());
let _ = std::fs::remove_dir_all(&dir);
let _ = std::fs::remove_file(beside(&dir, LOCK));
}
fn scratch(name: &str) -> PathBuf {
let d = std::env::temp_dir().join(format!("lc-lensfun-{name}-{}", std::process::id()));
for leftover in [d.clone(), beside(&d, STAGING), beside(&d, PREVIOUS)] {
let _ = std::fs::remove_dir_all(leftover);
}
std::fs::create_dir_all(&d).unwrap();
d
}
/// A local server answering `GET /db/<name>` with that file's body (404 otherwise).
fn serve(files: Vec<(&'static str, Vec<u8>)>) -> String {
let l = TcpListener::bind("127.0.0.1:0").unwrap();
let base = format!("http://{}/db", l.local_addr().unwrap());
std::thread::spawn(move || {
for mut s in l.incoming().flatten() {
let mut r = BufReader::new(s.try_clone().unwrap());
let mut first = String::new();
let _ = r.read_line(&mut first);
loop {
let mut line = String::new();
if r.read_line(&mut line).unwrap_or(0) == 0 || line.trim().is_empty() {
break;
}
}
let path = first.split_whitespace().nth(1).unwrap_or_default().to_string();
match files.iter().find(|(n, _)| path == format!("/db/{n}")) {
Some((_, body)) => {
let _ = s.write_all(format!("HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len()).as_bytes());
let _ = s.write_all(body);
}
None => {
let _ = s.write_all(b"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n");
}
}
}
});
base
}
fn wait(what: &str, done: impl Fn() -> bool) {
let t = std::time::Instant::now();
while !done() {
assert!(t.elapsed() < Duration::from_secs(20), "{what}");
std::thread::sleep(Duration::from_millis(10));
}
}
const LENS: &str = r#"<lensdatabase><lens><maker>Testcam</maker><model>Testcam 50mm f/1.8</model><mount>T</mount><cropfactor>1</cropfactor>
<calibration><distortion model="poly3" focal="50" k1="-0.01" /></calibration></lens></lensdatabase>"#;
const CAMERA: &str =
r#"<lensdatabase><camera><maker>Testcam</maker><model>TC-1</model><mount>T</mount><cropfactor>1</cropfactor></camera></lensdatabase>"#;
fn sha(s: &str) -> &'static str {
Box::leak(lightcraft_faces::hash::sha256_hex(s.as_bytes()).into_boxed_str())
}
fn pins() -> &'static [Pin] {
Box::leak(vec![("lenses.xml", LENS.len() as u64, sha(LENS)), ("cameras.xml", CAMERA.len() as u64, sha(CAMERA))].into_boxed_slice())
}
/// Every pinned file lands in the folder with the marker, the activity row shows the download until it ends,
/// and the database reads.
#[test]
fn downloads_checks_and_installs_the_pinned_files() {
let dir = scratch("ok");
let base = serve(vec![("lenses.xml", LENS.as_bytes().to_vec()), ("cameras.xml", CAMERA.as_bytes().to_vec())]);
let activity = Activity::default();
let mut d = Download::default();
assert!(!installed_with(&dir, pins()));
// an older pin's database: replaced as a whole, so a file this pin doesn't list is not read beside the new ones
std::fs::write(dir.join("dropped.xml"), CAMERA).unwrap();
std::fs::write(dir.join(MARKER), "older").unwrap();
// a resumed older attempt left a file this pin doesn't list in the staging folder: not published
std::fs::create_dir_all(beside(&dir, STAGING)).unwrap();
std::fs::write(beside(&dir, STAGING).join("old-staged.xml"), CAMERA).unwrap();
d.start(&dir, vec![base], pins(), &activity).unwrap();
let rows = activity.list();
assert!(rows.iter().any(|r| r.kind == "download" && r.label == "Downloading the lens database" && r.cancellable), "{rows:?}");
wait("the download never ended", || !d.running());
assert_eq!(d.state(), State::Done { files: 2 });
assert!(installed_with(&dir, pins()), "the marker names the pinned commit and every file is there");
assert!(!beside(&dir, STAGING).exists() && !beside(&dir, PREVIOUS).exists(), "no staging or previous folder is left");
let (db, errors) = lightcraft_lensdb::LensDb::load_dir(&dir).unwrap();
assert!(errors.is_empty() && db.lenses.len() == 1 && db.cameras.len() == 1);
assert!(!dir.join("dropped.xml").exists() && !dir.join("old-staged.xml").exists(), "only this pin's files");
wait("the row stayed", || activity.list().is_empty());
let _ = std::fs::remove_dir_all(&dir);
}
/// A file that is not the pinned one (another commit, a hostile mirror) is refused and nothing is installed:
/// the previous complete database stays as it was.
#[test]
fn a_file_that_is_not_the_pinned_one_installs_nothing() {
let dir = scratch("bad");
std::fs::write(dir.join("cameras.xml"), "previous").unwrap();
std::fs::write(dir.join(MARKER), "older").unwrap();
let base = serve(vec![("lenses.xml", LENS.replace("0.01", "0.02").into_bytes()), ("cameras.xml", CAMERA.as_bytes().to_vec())]);
let mut d = Download::default();
d.start(&dir, vec![base], pins(), &Activity::default()).unwrap();
wait("the download never ended", || !d.running());
assert!(matches!(d.state(), State::Failed(_)), "{:?}", d.state());
assert!(!installed_with(&dir, pins()) && complete(&dir), "the previous database is still whole");
assert_eq!(std::fs::read_to_string(dir.join("cameras.xml")).unwrap(), "previous", "nothing moved into place");
// no mirror at all is an error, not a thread
assert!(Download::default().start(&dir, Vec::new(), pins(), &Activity::default()).is_err());
let _ = std::fs::remove_dir_all(beside(&dir, STAGING));
let _ = std::fs::remove_dir_all(&dir);
}
/// The new database replaces the old folder as a whole or not at all: when moving it into place fails, the
/// previous database is put back (and when even that fails, the next start puts it back).
#[test]
fn a_failed_swap_keeps_the_previous_database() {
let dir = scratch("swap");
std::fs::write(dir.join("lenses.xml"), "old").unwrap();
std::fs::write(dir.join(MARKER), "older").unwrap();
let staged = beside(&dir, STAGING);
std::fs::create_dir_all(&staged).unwrap();
std::fs::write(staged.join("lenses.xml"), "new").unwrap();
std::fs::write(staged.join(MARKER), COMMIT).unwrap();
let read = |d: &Path| std::fs::read_to_string(d.join("lenses.xml")).unwrap();
// the staged folder can't be moved into place: the old one comes back
let calls = std::cell::Cell::new(0);
let second_fails = |from: &Path, to: &Path| {
calls.set(calls.get() + 1);
if calls.get() == 2 { Err(std::io::Error::other("in use")) } else { std::fs::rename(from, to) }
};
let err = publish(&staged, &dir, second_fails).unwrap_err();
assert!(err.contains("in use"), "{err}");
assert_eq!(read(&dir), "old", "the previous database is in place");
assert!(complete(&dir) && !beside(&dir, PREVIOUS).exists());
// neither move back works either (the app stops here): the next start puts the previous database back
let calls = std::cell::Cell::new(0);
let all_but_first_fail = |from: &Path, to: &Path| {
calls.set(calls.get() + 1);
if calls.get() == 1 { std::fs::rename(from, to) } else { Err(std::io::Error::other("in use")) }
};
assert!(publish(&staged, &dir, all_but_first_fail).is_err());
assert!(!dir.exists() && complete(&beside(&dir, PREVIOUS)));
recover(&dir);
assert_eq!(read(&dir), "old");
// and a swap that works leaves only the new database
publish(&staged, &dir, |from, to| std::fs::rename(from, to)).unwrap();
assert_eq!(read(&dir), "new");
assert!(!staged.exists() && !beside(&dir, PREVIOUS).exists());
let _ = std::fs::remove_dir_all(&dir);
}
/// A folder whose marker is there but whose database files went missing (or were cut short) is not installed,
/// so the start downloads it again.
#[test]
fn installed_needs_every_pinned_file() {
let dir = scratch("installed");
std::fs::write(dir.join(MARKER), format!("commit {COMMIT}")).unwrap();
assert!(complete(&dir) && !installed_with(&dir, pins()), "the marker alone is not a database");
std::fs::write(dir.join("lenses.xml"), LENS).unwrap();
std::fs::write(dir.join("cameras.xml"), CAMERA).unwrap();
assert!(installed_with(&dir, pins()));
std::fs::write(dir.join("cameras.xml"), &CAMERA[..10]).unwrap();
assert!(!installed_with(&dir, pins()), "a file cut short");
std::fs::remove_file(dir.join("cameras.xml")).unwrap();
assert!(!installed_with(&dir, pins()), "a file gone");
std::fs::write(dir.join(MARKER), "an older commit").unwrap();
std::fs::write(dir.join("cameras.xml"), CAMERA).unwrap();
assert!(!installed_with(&dir, pins()) && complete(&dir), "an older pin: whole, but replaced");
let _ = std::fs::remove_dir_all(&dir);
}
/// An old database file that can't be removed is an error (so no marker is written and the next start tries
/// again); the pinned files and other files are left alone.
#[test]
fn an_old_file_that_cannot_be_removed_is_an_error() {
let dir = scratch("stale");
for name in ["lenses.xml", "old-lenses.xml", "notes.txt"] {
std::fs::write(dir.join(name), "x").unwrap();
}
let failing = |_: &Path| Err(std::io::Error::other("in use"));
let err = remove_stale(&dir, pins(), failing).unwrap_err();
assert!(err.contains("old-lenses.xml") && err.contains("in use"), "{err}");
remove_stale(&dir, pins(), |p| std::fs::remove_file(p)).unwrap();
assert!(!dir.join("old-lenses.xml").exists());
assert!(dir.join("lenses.xml").exists() && dir.join("notes.txt").exists());
// a folder that can't be listed is an error too, not "nothing stale"
let not_a_folder = dir.join("notes.txt");
let err = remove_stale(&not_a_folder, pins(), |p| std::fs::remove_file(p)).unwrap_err();
assert!(err.contains("could not list"), "{err}");
let err = remove_stale(&dir.join("missing"), pins(), |p| std::fs::remove_file(p)).unwrap_err();
assert!(err.contains("could not list"), "{err}");
let _ = std::fs::remove_dir_all(&dir);
}
/// The first start asks before anything is downloaded; Download (or Settings) means a start fetches a missing
/// database; Not Now means nothing, ever, on its own; an installed database, a folder of the user's own or a host
/// that may not ask (CLI, MCP) mean nothing whatever the answer.
#[test]
fn the_start_asks_once_and_downloads_only_after_a_yes() {
let dir = || Some(PathBuf::from("lensfun"));
assert_eq!(decide(true, false, dir(), false, Offer::Ask), Start::Ask(PathBuf::from("lensfun")), "the first start asks");
assert_eq!(decide(true, false, dir(), false, Offer::Accepted), Start::Fetch(PathBuf::from("lensfun")));
assert_eq!(decide(true, false, dir(), false, Offer::Declined), Start::Nothing, "Not Now: never asked again");
for offer in [Offer::Ask, Offer::Accepted, Offer::Declined] {
assert_eq!(decide(true, false, dir(), true, offer), Start::Nothing, "installed: no question, no download");
assert_eq!(decide(false, false, dir(), false, offer), Start::Nothing, "a headless host never asks or fetches");
assert_eq!(decide(true, true, dir(), false, offer), Start::Nothing, "the user's own folder");
assert_eq!(decide(true, false, None, false, offer), Start::Nothing, "no data folder");
}
// the size the offer names comes from the pins
assert_eq!(download_size(), FILES.iter().map(|f| f.1).sum::<u64>());
assert!((4..=8).contains(&download_megabytes()), "{}", download_megabytes());
}
/// The pinned list is lensfun's whole `data/db` at the commit: unique XML names, sane sizes, hex hashes.
#[test]
fn the_pins_are_well_formed() {
assert_eq!(FILES.len(), 56);
let mut names: Vec<&str> = FILES.iter().map(|f| f.0).collect();
names.sort_unstable();
names.dedup();
assert_eq!(names.len(), FILES.len());
for (name, size, sha) in FILES {
assert!(name.ends_with(".xml") && !name.contains(['/', '\\']), "{name}");
assert!(*size > 0 && *size < MAX_FILE, "{name}");
assert!(sha.len() == 64 && sha.bytes().all(|b| b.is_ascii_hexdigit()), "{name}");
}
assert!(DEFAULT_MIRROR.contains(COMMIT));
}
}
+117 -10
View File
@@ -46,6 +46,7 @@ pub mod guard;
pub mod import;
mod import_move;
pub mod lens_profiles;
pub mod lensfun_download;
pub mod library;
mod lightroom_archive;
pub mod lightroom_catalog;
@@ -79,6 +80,7 @@ pub mod slideshow;
pub mod slideshow_export;
pub mod smart;
pub mod sync;
mod sync_same;
pub mod text;
mod view;
pub mod walk;
@@ -284,6 +286,11 @@ pub struct Session {
pub face_models_dir: Option<std::path::PathBuf>,
/// Face model downloads started this session (the staged files wait in `<face_models_dir>/.downloads`).
pub face_downloads: face_download::Downloads,
/// The lens database download ([`lensfun_download`]).
pub lensfun: lensfun_download::Download,
/// The host may offer the lens database at its start, and fetch it after the user's yes
/// ([`Session::with_lens_auto_download`]; when: [`lensfun_download::fetch_on_start`]).
pub lens_auto_download: bool,
/// Reverse geocoding: the parsed place names and their download (`metadata.*PlaceNames`).
pub place_names: cmd::geocode::PlaceNames,
/// The user's own list of models to download (`catalog.json` in the models folder), as last read.
@@ -353,6 +360,8 @@ pub struct Session {
/// The user's point-curve presets (`curve.*`; built-ins: [`cmd::curves::builtin_presets`]),
/// persisted in prefs.json.
pub curve_presets: Vec<cmd::curves::CurvePreset>,
/// Imported camera profiles (`.dcp`).
pub dcp_profiles: Vec<cmd::dcp_profiles::DcpEntry>,
/// Mask effect presets (the Masking panel's Effect menu).
pub mask_effects: Vec<cmd::mask_effects::MaskEffect>,
/// The effect a new mask of each kind (`brush`, `linear`…) starts with: the one last applied
@@ -476,6 +485,8 @@ impl Session {
denoise: Default::default(),
face_models_dir: None,
face_downloads: Default::default(),
lensfun: Default::default(),
lens_auto_download: false,
place_names: Default::default(),
face_catalog: Default::default(),
#[cfg(not(target_arch = "wasm32"))]
@@ -510,6 +521,7 @@ impl Session {
metadata_presets: Vec::new(),
filter_presets: Vec::new(),
curve_presets: Vec::new(),
dcp_profiles: Vec::new(),
mask_effects: Vec::new(),
mask_tool_effects: Default::default(),
label_sets: Vec::new(),
@@ -606,7 +618,8 @@ impl Session {
}
}
if self.depth == 0 && self.library.is_some() {
// Make the command durable before reporting success. When the command's own records
// Make the command durable before reporting success (natively: handed to the catalog
// log's own thread, which syncs it right after and holds it until it can). When the command's own records
// can't be appended, it fails with `NotSaved`: the change stays applied in memory and
// queued, and the next save (any later command, or the frame loop) retries it. Other
// persistence trouble (a failed compaction, an older queued change still unwritten by
@@ -938,8 +951,9 @@ impl Session {
i.crop_edited |= crop_edited;
return self.apply_silent(Op::SetDevelop { id, settings, label: label.into(), edited: Some(now) });
}
let own_auto = self.own_auto_wb(id, &requested, label);
let mut ops = vec![self.develop_op(id, (*settings).clone(), label).ok_or(lightcraft_catalog::CatalogError::NoPhoto(id))?];
ops.extend(self.auto_sync_ops(id, &requested, label));
ops.extend(self.auto_sync_ops(id, &requested, label, &own_auto));
let op = if ops.len() == 1 { ops.remove(0) } else { Op::Batch { ops } };
self.commit(label, op)
}
@@ -980,13 +994,12 @@ impl Session {
/// never spot removal or red eye (they belong to one photo's pixels), nor the rendering process
/// (Sync doesn't carry it either), nor history / snapshot restores. Constrain Crop then fits each
/// photo's own crop: the active photo's fitted crop is never copied over another's.
fn auto_sync_ops(&self, id: PhotoId, new: &DevelopSettings, label: &str) -> Vec<Op> {
if !self.auto_sync
|| self.active() != Some(id)
|| self.selection.ids.len() < 2
|| label.starts_with("History:")
|| label.starts_with("Restore ")
{
///
/// White balance goes on each photo as the active photo's mode or value on the photo's own
/// scale ([`sync_same`]): As Shot its own camera white, Auto its own (`own_auto`, worked out on
/// its pixels), a Temp or Tint the same number, only the slider that moved.
fn auto_sync_ops(&self, id: PhotoId, new: &DevelopSettings, label: &str, own_auto: &std::collections::HashMap<PhotoId, (f64, f64)>) -> Vec<Op> {
if !self.auto_sync_applies(id, label) {
return Vec::new();
}
let Some(old) = self.develop_of(id) else { return Vec::new() };
@@ -1008,21 +1021,62 @@ impl Session {
return Vec::new();
}
}
let ainfo = self.source_info(id);
let wb_changed = old.wb != new.wb;
self.selection
.ids
.iter()
.filter(|x| **x != id)
.filter_map(|x| self.develop_of(*x).map(|d| (*x, d)))
.filter_map(|(x, d)| {
let synced = self.fit_constrained_crop(x, lightcraft_develop::apply_partial(&d, &delta, 1.0));
let mut synced = lightcraft_develop::apply_partial(&d, &delta, 1.0);
if wb_changed {
sync_same::synced_wb(&ainfo, &old, new, &self.source_info(x), &d, own_auto.get(&x).copied(), &mut synced);
}
let synced = self.fit_constrained_crop(x, synced);
(synced != *d).then(|| self.develop_op(x, synced, label)).flatten()
})
.collect()
}
/// Auto Sync carries an edit of photo `id` labelled `label` to the other selected photos: it is
/// on, `id` is the active photo of a selection of two or more, and the edit is not a History or
/// snapshot restore.
fn auto_sync_applies(&self, id: PhotoId, label: &str) -> bool {
self.auto_sync
&& self.active() == Some(id)
&& self.selection.ids.len() >= 2
&& !label.starts_with("History:")
&& !label.starts_with("Restore ")
}
/// The op that sets a photo's develop settings and appends a History entry (for batches).
pub fn develop_op(&self, id: PhotoId, settings: DevelopSettings, label: &str) -> Option<Op> {
self.catalog.photo(id)?;
let mut settings = settings;
// old masks (on the corrected frame) go onto the photo, from the frame they were drawn on:
// masks this edit kept, under the photo's settings before it (a geometry edit then moves
// the photo, not them); masks it brought in (paste, sync, a preset, a history step, a
// sidecar), under the settings they came with, where they render now. Kept masks also
// turn with an orientation change the edit makes (a sync or paste of the Crop group).
let before = match &self.interaction {
Some(i) if i.photo == id => Some(i.original.clone()),
_ => self.develop_of(id),
};
let turn = before.as_ref().and_then(|b| orientation_change(b.orientation, settings.orientation));
if settings.masks.iter().any(|m| !m.on_photo) || turn.is_some() {
let kept_frame = before.as_ref().and_then(|b| self.mask_frame(id, b));
let new_frame = self.mask_frame(id, &settings);
for m in &mut settings.masks {
let kept = before.as_ref().is_some_and(|b| b.masks.contains(m));
if let Some(f) = if kept { kept_frame.as_ref() } else { new_frame.as_ref() } {
lightcraft_pipeline::mask_space::attach(m, f);
}
if let (true, Some(t)) = (kept, turn) {
lightcraft_pipeline::mask_space::turn(m, t);
}
}
}
let settings = Arc::new(settings);
let step = lightcraft_catalog::HistoryStep { label: label.into(), settings: settings.clone() };
Some(Op::Batch {
@@ -1030,11 +1084,45 @@ impl Session {
})
}
/// Put the old masks of `d` (on the corrected frame, `Mask::on_photo` false) on photo `id`
/// before the warp, from the frame of `drawn` (the settings they were drawn under): they
/// render where they did and from then on stay on their content when lens corrections,
/// Upright or Transform change.
pub fn attach_masks(&self, id: PhotoId, drawn: &DevelopSettings, d: &mut DevelopSettings) {
if d.masks.iter().all(|m| m.on_photo) {
return;
}
let Some(frame) = self.mask_frame(id, drawn) else { return };
for m in &mut d.masks {
lightcraft_pipeline::mask_space::attach(m, &frame);
}
}
/// The uncropped frame of photo `id` under settings `d`, with its lens: where mask
/// coordinates go through its warp ([`lightcraft_pipeline::geometry::Frame::for_mask`]).
pub(crate) fn mask_frame(&self, id: PhotoId, d: &DevelopSettings) -> Option<lightcraft_pipeline::geometry::Frame> {
let p = self.catalog.photo(id)?;
Some(lightcraft_pipeline::geometry::Frame::with_lens(
p.width.max(1) as usize,
p.height.max(1) as usize,
&d.effective(),
false,
p.embedded_lens.as_ref(),
))
}
pub fn begin_interaction(&mut self, label: &str) -> Result<()> {
if self.interaction.is_some() {
self.end_interaction()?;
}
let id = self.active().ok_or_else(|| EngineError::Other("no active photo".into()))?;
// old masks go onto the photo before a drag moves the frame under them (they then stay on
// their content while it does, not only once it ends)
if let Some(d) = self.develop_of(id).filter(|d| d.masks.iter().any(|m| !m.on_photo)) {
let mut on = (*d).clone();
self.attach_masks(id, &d, &mut on);
self.apply_silent(Op::SetDevelop { id, settings: Arc::new(on), label: label.into(), edited: None })?;
}
let original = self.develop_of(id).unwrap_or_default();
self.interaction = Some(Interaction { label: label.into(), photo: id, original, crop_edited: false });
Ok(())
@@ -1373,3 +1461,22 @@ mod tests;
use tests::face_recognize as tests_face_recognize;
#[cfg(test)]
use tests::xmp as tests_xmp;
/// The turn or flip that takes orientation `from` to `to` (`None` when they are the same): what the
/// masks, on the oriented photo, must follow ([`lightcraft_pipeline::mask_space::turn`]).
pub(crate) fn orientation_change(from: lightcraft_geom::Orientation, to: lightcraft_geom::Orientation) -> Option<lightcraft_geom::Orientation> {
use lightcraft_geom::Orientation;
if from == to {
return None;
}
let inv = from.inverse();
let probes = [(0.2, 0.3), (0.7, 0.1), (0.4, 0.9)];
let close = |a: (f64, f64), b: (f64, f64)| (a.0 - b.0).abs() < 1e-9 && (a.1 - b.1).abs() < 1e-9;
(0..8u8).map(|k| Orientation::from_parts(k >= 4, k % 4)).find(|t| {
probes.iter().all(|&(x, y)| {
let (rx, ry) = inv.map(x, y, 1.0, 1.0);
let (tx, ty) = from.map(rx, ry, 1.0, 1.0);
close(t.map(tx, ty, 1.0, 1.0), to.map(rx, ry, 1.0, 1.0))
})
})
}
+74 -13
View File
@@ -13,8 +13,12 @@
//! The files live in [`Store`]s: a directory ([`FsStore`]) natively, or any other implementation
//! via [`Session::open_library_in`] (the browser build keeps them in OPFS or IndexedDB).
//!
//! Every top-level [`Session::execute`] persists the ops it produced (fsynced) before returning,
//! so a crash loses at most the command in flight. When that write fails the command returns
//! Every top-level [`Session::execute`] persists the ops it produced before returning: fsynced
//! there, or natively handed to the catalog log's own thread, which writes and syncs them right
//! after (the UI thread never waits for the drive), so a crash or power cut loses at most the
//! batch in flight (what arrived during one sync). A write that thread
//! can't make is held and retried, counts as unsaved ([`Session::unsaved`]) and makes a snapshot
//! due. When that write fails the command returns
//! [`EngineError::NotSaved`]: its change stays applied in memory and queued, and every later save
//! retries the queue ([`Session::unsaved`] reports it meanwhile), so nothing is lost once the
//! disk is writable again. The log is compacted into a snapshot when it
@@ -134,6 +138,10 @@ pub struct Library {
/// Why the last write of presets.json failed; `None` once it is written. While set, the preset
/// changes exist only in memory and count as unsaved ([`Session::unsaved`], issue #2266).
presets_error: Option<String>,
/// Records the catalog log's own thread holds because writing them failed (it retries them),
/// and why; refreshed by every persist and every frame ([`Session::persist_if_dirty`]). While
/// set they count as unsaved ([`Session::unsaved`]), so quitting asks first.
log_held: Option<(usize, String)>,
/// When the frame loop may retry a failed append ([`Session::persist_if_dirty`] backs off).
retry_at: Option<web_time::Instant>,
/// What forgetting untouched Local records did when the library opened.
@@ -277,6 +285,8 @@ struct PrefsFile {
label_sets: Vec<crate::cmd::manage::LabelSet>,
/// Imported LUT profiles.
lut_profiles: Vec<crate::cmd::lut_profiles::LutProfile>,
/// Imported camera profiles (`.dcp`).
dcp_profiles: Vec<crate::cmd::dcp_profiles::DcpEntry>,
/// Keyword sets, the one in use, recent keywords.
keyword_sets: Vec<crate::cmd::keywords::KeywordSet>,
keyword_set: Option<String>,
@@ -322,6 +332,8 @@ fn poll_compaction(lib: &mut Library) {
log::error!("library: compaction: {e}");
lib.last_error = Some(format!("compaction: {e}"));
}
// (never waits: the log's thread publishes what it holds)
lib.log_held = lib.journal.unwritten();
}
/// How long the frame loop waits before retrying a failed append (commands retry at once).
@@ -501,13 +513,24 @@ impl Session {
/// Open `stores`; the new library takes `lock` once nothing can fail any more.
fn open_stores(&mut self, stores: LibraryStores, seed_demo: bool, lock: &mut Option<LibraryLock>) -> Result<()> {
let LibraryStores { dir, catalog, mut files, on_disk } = stores;
self.media.smart_dir = on_disk.then(|| crate::smart::dir(&dir));
// the current library may be these same files: let its background snapshot land first
if let Some(old) = self.library.as_mut()
&& let Err(e) = old.journal.wait()
{
log::error!("library: {e}");
// the current library may be these same files: let its background snapshot land first, and
// what its log's thread was handed reach the file before the new journal reads it. When
// that can't be written, the open fails and the current library stays open with what its
// thread holds (retried): read now, the files would miss it (review of #3557).
if let Some(old) = self.library.as_mut() {
if let Err(e) = old.journal.wait() {
log::error!("library: {e}");
}
if let Err(e) = old.journal.flush() {
old.log_held = old.journal.unwritten();
// a snapshot that holds every op leaves nothing for the files to miss
if old.journal.snapshot_seq() < old.journal.seq() {
return Err(EngineError::NotSaved(format!("the open library's changes aren't on disk yet, so it stays open: {e}")));
}
log::error!("library: {e} (every change is in its snapshot)");
}
}
self.media.smart_dir = on_disk.then(|| crate::smart::dir(&dir));
// Photo ids belong to one library; denoise work must not carry into the next.
self.denoise.library_changed();
self.media.denoise.clear();
@@ -555,6 +578,8 @@ impl Session {
self.label_sets = prefs.label_sets;
self.lut_profiles = prefs.lut_profiles;
crate::cmd::lut_profiles::register_all(self);
self.dcp_profiles = prefs.dcp_profiles;
crate::cmd::dcp_profiles::register_all(self, on_disk.then(|| dir.join("Profiles")).as_deref());
self.keyword_sets = prefs.keyword_sets;
self.keyword_set = prefs.keyword_set;
self.recent_keywords = prefs.recent_keywords;
@@ -582,7 +607,11 @@ impl Session {
self.presets.push(u);
}
}
let known = |id: &String| crate::presets::profile(id).is_some() || self.lut_profiles.iter().any(|p| &p.id == id);
let known = |id: &String| {
crate::presets::profile(id).is_some()
|| self.lut_profiles.iter().any(|p| &p.id == id)
|| self.dcp_profiles.iter().any(|p| &p.id == id)
};
self.profile_favorites = f.profile_favorites.into_iter().filter(known).collect();
self.profile_recent = f.profile_recent.into_iter().filter(known).take(crate::presets::RECENT_PROFILES).collect();
}
@@ -631,6 +660,7 @@ impl Session {
last_error: None,
unsaved_error: None,
presets_error: None,
log_held: None,
retry_at: None,
forgot_local: None,
presets_saved,
@@ -661,7 +691,7 @@ impl Session {
Ok(())
}
/// Write pending ops to the log (fsynced), compact when due, and save changed presets.
/// 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.
pub fn persist(&mut self) -> Result<()> {
@@ -726,13 +756,40 @@ impl Session {
pub fn persist_if_dirty(&mut self) {
let backing_off = self.library.as_ref().and_then(|l| l.retry_at).is_some_and(|t| web_time::Instant::now() < t);
let presets_unsaved = self.library.as_ref().is_some_and(|l| l.presets_error.is_some());
if self.library.is_some() && (!self.pending_log.is_empty() || presets_unsaved) && !backing_off {
// records the log's thread can't write: a snapshot (a fresh file holding everything) is due
let log_held = self.library.as_ref().is_some_and(|l| l.log_held.is_some());
if self.library.is_some() && (!self.pending_log.is_empty() || presets_unsaved || log_held) && !backing_off {
let _ = self.persist();
} else if let Some(lib) = self.library.as_mut() {
poll_compaction(lib);
}
}
/// Read again what the catalog log's own thread holds because writing it failed (never waits):
/// before a check of [`Session::unsaved`] that must be current, such as the quit prompt's.
pub fn refresh_unsaved(&mut self) {
if let Some(lib) = self.library.as_mut() {
lib.log_held = lib.journal.unwritten();
}
}
/// Every change applied is in the library's last snapshot (a closing snapshot landed), whatever
/// the catalog log's thread still holds or failed to reset. `false` without a library.
pub fn snapshot_holds_everything(&self) -> bool {
self.pending_log.is_empty() && self.library.as_ref().is_some_and(|l| l.journal.snapshot_seq() >= l.journal.seq())
}
/// Wait until what the catalog log's thread was handed is on disk, then read again what it
/// holds ([`Session::refresh_unsaved`]). Before the quit check: a change the thread accepted
/// but hasn't written yet is in no count of [`Session::unsaved`]. An error (a write failed, or
/// the drive took over a minute) means some changes may not be on disk yet.
pub fn flush_log(&mut self) -> Result<()> {
let Some(lib) = self.library.as_mut() else { return Ok(()) };
let flushed = lib.journal.flush();
lib.log_held = lib.journal.unwritten();
Ok(flushed?)
}
/// Changes applied in memory but not yet written to disk because saving failed: the number of
/// queued ops (plus one for presets.json) and why (`None` when everything is saved, or no library
/// is open). Retried by every command and by [`Session::persist_if_dirty`].
@@ -740,8 +797,9 @@ impl Session {
let lib = self.library.as_ref()?;
let ops = lib.unsaved_error.as_deref().filter(|_| !self.pending_log.is_empty());
let presets = lib.presets_error.as_deref();
let n = ops.map_or(0, |_| self.pending_log.len()) + usize::from(presets.is_some());
ops.or(presets).map(|why| (n, why))
let held = lib.log_held.as_ref().map(|(n, why)| (*n, why.as_str()));
let n = ops.map_or(0, |_| self.pending_log.len()) + held.map_or(0, |(n, _)| n) + usize::from(presets.is_some());
ops.or(held.map(|(_, why)| why)).or(presets).map(|why| (n, why))
}
/// Flush everything and write a snapshot (on quit). Ends an open interaction first.
@@ -760,6 +818,8 @@ impl Session {
let Some(lib) = self.library.as_mut() else { return Ok(()) };
let before = lib.journal.seq();
let snapshot = lib.journal.snapshot_with_unlogged(&self.catalog, unlogged);
// (a snapshot that landed holds what the log's thread held)
lib.log_held = lib.journal.unwritten();
if unlogged > 0 && lib.journal.seq() == before + unlogged {
// the snapshot holds the queued ops: they are saved, never append them again
log::info!("library: {unlogged} queued change(s) saved in the closing snapshot");
@@ -834,6 +894,7 @@ impl Session {
mask_tool_effects: self.mask_tool_effects.clone(),
label_sets: self.label_sets.clone(),
lut_profiles: self.lut_profiles.clone(),
dcp_profiles: self.dcp_profiles.clone(),
keyword_sets: self.keyword_sets.clone(),
keyword_set: self.keyword_set.clone(),
recent_keywords: self.recent_keywords.clone(),
+1 -1
View File
@@ -1139,7 +1139,7 @@ pub(crate) fn apply_prepared(s: &mut crate::Session, mut data: CatalogImport, co
number(&src.image, "fileHeight").max(0) as u32,
&now,
);
if ["RAW", "DNG", "ARW", "CR2", "CR3", "NEF", "NRW", "RAF", "ORF", "RW2", "PEF"].contains(&p.format.to_uppercase().as_str()) {
if ["RAW", "DNG", "ARW", "CR2", "CR3", "CRW", "NEF", "NRW", "RAF", "ORF", "RW2", "PEF"].contains(&p.format.to_uppercase().as_str()) {
p.kind = lightcraft_catalog::MediaKind::Raw;
}
p
+22 -1
View File
@@ -24,6 +24,7 @@ use lightcraft_develop::DevelopSettings;
use lightcraft_pipeline::{Quality, RenderRequest, Rendered, SourceInfo, StageCache};
use lightcraft_preview::{Hash128, Hasher128, Lru, PreviewCache};
use lightcraft_raster::{Histogram, Rgb32f, Rgba8};
pub use lightcraft_raw::dcp::DcpProfile;
use serde::{Deserialize, Serialize};
mod cache;
@@ -35,7 +36,7 @@ mod source;
pub use cache::DenoiseIndex;
pub use quick::{QuickJob, QuickSource, content_key, source_info};
pub use render::{RenderJob, RenderResult, develop, develop_reporting, fit_for_display};
pub use render::{RenderJob, RenderResult, ScreenFrame, develop, develop_reporting, fit_for_display};
#[cfg(test)]
use settings_hash::SETTINGS_HASH_ENTRIES;
use settings_hash::SettingsHashes;
@@ -79,6 +80,26 @@ pub struct MediaCache {
pub rendered: Arc<PreviewCache>,
/// Which photos have a cached denoised picture, and how to read it.
pub denoise: DenoiseIndex,
/// Imported camera profiles by id ([`crate::cmd::dcp_profiles`]), handed to the decoder of photos using them.
pub camera_profiles: std::collections::HashMap<String, LoadedCameraProfile>,
}
/// An imported camera profile ready for the decoder, with a fingerprint of its file: decoded sources and cached renders
/// made with it carry the fingerprint, so a profile deleted, or replaced by another under the same id, never has
/// its old pictures stand in.
#[derive(Clone, Debug)]
pub struct LoadedCameraProfile {
pub profile: Arc<DcpProfile>,
/// Never 0 (0 is "no camera profile" in a render key).
pub fingerprint: u64,
}
impl LoadedCameraProfile {
/// Parse a `.dcp` file's bytes.
pub fn parse(bytes: &[u8]) -> Result<Self, lightcraft_raw::dcp::DcpError> {
let profile = lightcraft_raw::dcp::parse_dcp(bytes)?;
Ok(LoadedCameraProfile { profile: Arc::new(profile), fingerprint: Hasher128::new().update(bytes).finish().0 as u64 | 1 })
}
}
#[cfg(test)]
+86 -14
View File
@@ -1,6 +1,6 @@
use super::settings_hash::SettingsHashes;
use super::source::{DecodedSource, DenoiseSpec, PairLoader, RENDERED_MEM_BYTES, SourceLevel, SourceRef, THUMB_SOURCE_BYTES};
use super::{Arc, DevelopSettings, Hasher128, Lru, MediaCache, Photo, PhotoId, PreviewCache, Rgb32f, Source, SourceInfo};
use super::{Arc, DcpProfile, DevelopSettings, HashMap, Hasher128, Lru, MediaCache, Photo, PhotoId, PreviewCache, Rgb32f, Source, SourceInfo};
/// The photos that have a cached denoised picture for the denoise model in use. Only memory: nothing here touches the
/// file system, so it can be asked on the UI thread.
@@ -70,6 +70,7 @@ impl Default for MediaCache {
scenes: Vec::new(),
rendered: Arc::new(PreviewCache::memory(rendered_budget(budget))),
denoise: DenoiseIndex::default(),
camera_profiles: HashMap::new(),
}
}
}
@@ -202,14 +203,16 @@ impl MediaCache {
}
/// The facts of photo `id`'s cached sources: the decoder's when one has them, else `header`
/// (with a smart preview's stored camera tone curve).
pub(super) fn source_facts(&self, id: PhotoId, header: SourceInfo) -> SourceInfo {
/// (with a smart preview's stored camera tone curve). Only sources developed with `profile` (the photo's imported
/// camera profile tag, [`Self::camera_profile_of`], or none) count: one made with another profile has its facts.
pub(super) fn source_facts(&self, id: PhotoId, header: SourceInfo, profile: Option<&str>) -> SourceInfo {
let cached = || {
self.thumbs
.peek(&id)
.into_iter()
.chain(self.previews.iter().filter(|e| e.0 == id).map(|e| &e.1))
.chain(self.full.iter().filter(|e| e.0 == id).map(|e| &e.1))
.filter(|s| s.camera_profile.as_deref() == profile)
};
match cached().find(|s| s.info.is_some()).or_else(|| cached().next()) {
Some(s) => s.info_or(header),
@@ -221,7 +224,13 @@ impl MediaCache {
self.insert_source(id, level, DecodedSource::new(img, None));
}
pub(super) fn insert_source(&mut self, id: PhotoId, level: SourceLevel, img: DecodedSource) {
/// A decoded source with what the decoder reported about it (tests: photos of another as-shot white).
#[cfg(test)]
pub(crate) fn insert_with_info(&mut self, id: PhotoId, level: SourceLevel, img: Arc<Rgb32f>, info: lightcraft_pipeline::SourceInfo) {
self.insert_source(id, level, DecodedSource::new(img, Some(info)));
}
pub(crate) fn insert_source(&mut self, id: PhotoId, level: SourceLevel, img: DecodedSource) {
let tick = lightcraft_preview::next_tick();
match level {
SourceLevel::Thumb => {
@@ -296,24 +305,49 @@ impl MediaCache {
self.source_ref_with(p, level, false)
}
/// [`Self::source_ref`] without the photo's imported camera profile (keeping its denoised picture): a smart
/// preview keeps the file's own colour, and a cached source developed with the profile doesn't stand in for it.
#[cfg(not(target_arch = "wasm32"))]
pub fn source_ref_without_profile(&mut self, p: &Photo, level: SourceLevel) -> SourceRef {
self.source_ref_for(p, level, true, None)
}
fn source_ref_with(&mut self, p: &Photo, level: SourceLevel, cached: bool) -> SourceRef {
let mut r = self.source_ref_plain(p, level, cached);
let wanted = self.camera_profile_of(p);
self.source_ref_for(p, level, cached, wanted)
}
/// [`Self::source_ref_with`] developed with camera profile `wanted` (none: the file's own colour).
fn source_ref_for(&mut self, p: &Photo, level: SourceLevel, cached: bool, wanted: Option<(String, Arc<DcpProfile>)>) -> SourceRef {
let mut r = self.source_ref_plain(p, level, cached, wanted);
if let (SourceRef::File { denoise, .. }, Some((spec, loader))) = (&mut r, self.denoise.get(p.id)) {
*denoise = Some((spec.clone(), loader.clone()));
}
r
}
fn source_ref_plain(&mut self, p: &Photo, level: SourceLevel, cached: bool) -> SourceRef {
if cached && let Some(a) = self.get_source(p.id, level) {
/// Is photo `p`'s original known to be missing (cached answer only)?
fn original_offline(&self, p: &Photo) -> bool {
matches!(&p.source, Source::File { path } if self.availability.is_offline(path))
}
fn source_ref_plain(&mut self, p: &Photo, level: SourceLevel, cached: bool, wanted: Option<(String, Arc<DcpProfile>)>) -> SourceRef {
// (a source developed with another camera profile, or none, doesn't stand in; a smart preview
// has no camera profile, and decoding it again gives the same picture, so it stands in while the
// original is offline)
if cached
&& let Some(a) = self.get_source(p.id, level)
&& (a.camera_profile == wanted.as_ref().map(|(id, _)| id.clone()) || (a.from_proxy && self.original_offline(p)))
{
return SourceRef::Loaded(Box::new(a));
}
// a thumbnail of a photo whose preview is decoded (the one in the loupe) is cut from it; not
// with a denoised picture, which the thumbnail would lose
// with a denoised picture, which the thumbnail would lose, nor from one decoded with another camera profile
if cached
&& level == SourceLevel::Thumb
&& self.denoise.spec(p.id).is_none()
&& let Some(big) = self.get_source(p.id, SourceLevel::Preview)
&& (big.camera_profile == wanted.as_ref().map(|(tag, _)| tag.clone()) || (big.from_proxy && self.original_offline(p)))
{
return SourceRef::Fit { from: Box::new(big), max_edge: level.max_edge() };
}
@@ -336,12 +370,36 @@ impl MediaCache {
return SourceRef::Smart { path: sp };
}
let mut r = self.origin_ref(&p.source, max_edge);
if let SourceRef::File { fallback, .. } = &mut r {
if let SourceRef::File { fallback, camera_profile, .. } = &mut r {
*fallback = Some(sp);
*camera_profile = wanted;
}
return r;
}
self.origin_ref(&p.source, max_edge)
let mut r = self.origin_ref(&p.source, max_edge);
if let SourceRef::File { camera_profile, .. } = &mut r {
*camera_profile = wanted;
}
r
}
/// The imported camera profile photo `p` develops with, when its profile setting names one this library has: what a
/// source decoded with it is tagged with (its id and the file's fingerprint), and the profile.
pub fn camera_profile_of(&self, p: &Photo) -> Option<(String, Arc<DcpProfile>)> {
let id = &p.develop.profile.id;
if !crate::cmd::dcp_profiles::is_dcp_id(id) {
return None;
}
self.camera_profiles.get(id).map(|d| (format!("{id}#{:016x}", d.fingerprint), d.profile.clone()))
}
/// What a render with profile `profile_id` adds to its cache keys: the imported camera profile's fingerprint, 0
/// for any other profile and for a camera profile this library no longer has (it renders without it).
pub fn camera_profile_salt(&self, profile_id: &str) -> u64 {
if !crate::cmd::dcp_profiles::is_dcp_id(profile_id) {
return 0;
}
self.camera_profiles.get(profile_id).map_or(0, |d| d.fingerprint)
}
/// How to load `origin` at most `max_edge` pixels long, ignoring decoded sources in memory (a
@@ -354,12 +412,26 @@ impl MediaCache {
}
match self.scenes.iter().find(|s| s.id == *scene) {
Some(s) => SourceRef::Demo { scene: Box::new(s.clone()), max_edge },
None => SourceRef::File { path: format!("demo:{scene}"), max_edge, loader: None, fallback: None, denoise: None, reduced: None },
None => SourceRef::File {
path: format!("demo:{scene}"),
max_edge,
loader: None,
fallback: None,
denoise: None,
camera_profile: None,
reduced: None,
},
}
}
Source::File { path } => {
SourceRef::File { path: path.clone(), max_edge, loader: self.file_loader.clone(), fallback: None, denoise: None, reduced: None }
}
Source::File { path } => SourceRef::File {
path: path.clone(),
max_edge,
loader: self.file_loader.clone(),
fallback: None,
denoise: None,
camera_profile: None,
reduced: None,
},
}
}
}
+32 -1
View File
@@ -1,6 +1,6 @@
use super::render::{RenderJob, RenderResult};
use super::source::{PreviewLoader, SourceLevel};
use super::{Arc, Deserialize, Hash128, Histogram, Photo, PhotoId, PreviewCache, Rendered, Rgba8, Serialize, Source, SourceInfo};
use super::{Arc, Deserialize, Hash128, Hasher128, Histogram, Photo, PhotoId, PreviewCache, Rendered, Rgba8, Serialize, Source, SourceInfo};
/// Where a [`QuickJob`]'s stand-in image came from.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
@@ -49,6 +49,7 @@ impl QuickJob {
loaded: None,
quick: None,
display: None,
frame: None,
})
}
@@ -66,6 +67,7 @@ impl QuickJob {
loaded: None,
quick,
display: None,
frame: None,
};
let rendered = |image: Rgba8| {
let histogram = Histogram::of_srgb8(&image);
@@ -99,6 +101,20 @@ impl QuickJob {
}
/// What identifies a photo's pixels for caching: its content hash, else its source.
/// Which decode of a photo a loaded source is: its file's content and, when it has one, its database lens profile
/// ([`lens_key`]; the decode fits the starting colour through it). A job's source is kept only when this still
/// matches when the job finishes ([`super::Session::accept`]), so a decode started before a profile change never
/// returns to the cache after `cmd::lens_refresh` has dropped the photo's sources.
pub fn source_identity(p: &Photo) -> Hash128 {
let mut k = Hasher128::new();
k.str(&content_key(p));
let lens = lens_key(p);
if lens != 0 {
k.u64(lens);
}
k.finish()
}
pub fn content_key(p: &Photo) -> String {
match (&p.content_hash, &p.source) {
(Some(h), _) => h.clone(),
@@ -107,6 +123,21 @@ pub fn content_key(p: &Photo) -> String {
}
}
/// What a photo's lens profile adds to its render and thumbnail keys: a database profile (0 without one), with the
/// correction on or off: a raw's starting colour is fitted through the profile's vignetting either way
/// (`camera_preview::starting_colour`), so the decoded picture depends on it. When a database update gives the
/// photo another profile, its cached renders and thumbnails no longer match. (The file's own correction changes only with the file, which the content
/// key covers, so it adds nothing and existing thumbnails stay valid.)
pub fn lens_key(p: &Photo) -> u64 {
match &p.embedded_lens {
Some(l) if l.source == lightcraft_develop::LensSource::Database => {
let k = Hasher128::new().str("lens").str(&format!("{l:?}")).finish();
(k.0 as u64) ^ ((k.0 >> 64) as u64) | 1
}
_ => 0,
}
}
pub fn source_info(p: &Photo) -> SourceInfo {
// Procedural demo scenes are scene-referred HDR (like raw files): use the filmic tone map.
// (They are drawn afresh at every size, so they have no original size.)
+95 -10
View File
@@ -32,6 +32,9 @@ pub struct RenderJob {
pub view_cache: Option<(Arc<PreviewCache>, Hash128)>,
/// Render for this monitor profile ([`Self::with_display`]).
pub display: Option<Arc<crate::display::Display>>,
/// Shown on screen at once and not kept: the result may stay on the GPU as a texture
/// ([`Self::on_screen`]).
pub on_screen: bool,
/// Compose the render into a slideshow slide ([`Self::with_slide`]).
pub slide: Option<Arc<crate::slide::SlideCompose>>,
/// A face tile that can be cut from the raw's embedded preview, tried before `source`
@@ -57,6 +60,17 @@ pub fn fit_for_display(img: &Rgba8, max_w: usize, max_h: usize) -> Rgba8 {
Rgba8 { width: small.width, height: small.height, data: small.data.iter().map(|p| [c(p[0]), c(p[1]), c(p[2]), c(p[3])]).collect() }
}
/// A render left on the GPU for the window to draw ([`RenderResult::frame`]).
#[cfg(not(target_arch = "wasm32"))]
pub type ScreenFrame = lightcraft_gpu::DisplayFrame;
/// A render left on the GPU for the window to draw (never, in the browser build).
#[cfg(target_arch = "wasm32")]
#[derive(Clone, Debug)]
pub struct ScreenFrame {
pub width: usize,
pub height: usize,
}
pub struct RenderResult {
pub request_id: u64,
pub source_key: Option<Hash128>,
@@ -74,6 +88,9 @@ pub struct RenderResult {
/// The display profile (id) the image is encoded for; `None`: sRGB (see
/// [`crate::display::present`]).
pub display: Option<u64>,
/// The result as a texture on the window's GPU device ([`RenderJob::on_screen`]); `rendered`
/// then holds its histogram and an empty image.
pub frame: Option<ScreenFrame>,
}
impl RenderJob {
@@ -123,6 +140,15 @@ impl RenderJob {
self
}
/// The result is only drawn (an interactive draft of a view): when the GPU renderer runs on the
/// window's device it may hand back a texture ([`RenderResult::frame`]) instead of reading the
/// pixels back. Ignored where pixels are needed: thumbnails (cached), a full-quality render
/// kept as the view preview, and a monitor profile (corrected on the CPU).
pub fn on_screen(mut self) -> Self {
self.on_screen = true;
self
}
/// Render with some colour grading wheels (shadows, midtones, highlights) switched off for
/// viewing (the wheel eyes in the Edit panel). The photo's settings are untouched; the result
/// gets its own key and is never cached as the photo's preview or thumbnail.
@@ -189,6 +215,7 @@ impl RenderJob {
loaded: None,
quick: None,
display: None,
frame: None,
}
}
@@ -232,6 +259,7 @@ impl RenderJob {
loaded: None,
quick: None,
display: None,
frame: None,
};
}
// a face tile of an unedited raw: cut from the camera's embedded preview when it is big enough
@@ -252,6 +280,7 @@ impl RenderJob {
loaded: None,
quick: None,
display: None,
frame: None,
};
}
let was_loaded = matches!(self.source, SourceRef::Loaded(_));
@@ -267,14 +296,43 @@ impl RenderJob {
// the plain picture, or (Denoise amount above 0 and a denoised picture cached) the mix the amount asks for
let src = &source.image_for(self.settings.denoise_amount());
let info = source.info_or(self.info);
// Thumbnails (many small jobs side by side) stay on the CPU; views and exports use
// the GPU when there is one.
let gpu = self.cache.is_none();
// Views and exports use the GPU when there is one (waiting for the device if it is
// still being created). Thumbnails (grid, filmstrip, preset and profile previews)
// use it once it is ready - ~20-30 % faster than the CPU at 256 px with six jobs
// side by side (`crates/gpu/tests/it/thumbs_bench.rs`), and the cores stay free for
// decoding - but never wait for it: at startup they render on the CPU.
let gpu = self.cache.is_none() || lightcraft_gpu::ready();
// a clipping preview tests sRGB values, like the histogram: rendered in sRGB, then
// converted for the display below
let clip_view = self.request.overlay.is_clipping();
let request = if clip_view { RenderRequest { display: None, ..self.request } } else { self.request };
let (mut rendered, gpu_fallback) = develop_reporting(src, &info, &self.settings, &request, self.stages.as_deref(), gpu);
let pixels_needed =
self.cache.is_some() || self.display.is_some() || (self.view_cache.is_some() && self.request.quality == Quality::Full);
let frame = (self.on_screen && !pixels_needed && gpu)
.then(|| develop_on_screen(src, &info, &self.settings, &request, self.stages.as_deref()));
let (mut rendered, gpu_fallback) = match frame {
Some(OnScreen::Frame(frame, histogram)) => {
return RenderResult {
request_id: self.request_id,
source_key: self.source_key,
photo: self.photo,
level: self.level,
key: self.key,
rendered: Ok(Rendered {
image: lightcraft_raster::Rgba8 { width: 0, height: 0, data: Vec::new() },
histogram,
deep: None,
}),
gpu_fallback: None,
loaded: (!was_loaded).then_some(source),
quick: None,
display: None,
frame: Some(frame),
};
}
Some(OnScreen::Pixels(r)) => (r, None),
None => develop_reporting(src, &info, &self.settings, &request, self.stages.as_deref(), gpu),
};
// for a display profile: the image goes to the display's values, the histogram
// and the cached view preview stay sRGB
let mut srgb = None;
@@ -329,6 +387,7 @@ impl RenderJob {
loaded: (!was_loaded).then_some(source),
quick: None,
display,
frame: None,
}
}
Err(e) => self.failed(e),
@@ -370,12 +429,8 @@ fn develop_image(
stages: Option<&StageCache>,
gpu: bool,
) -> (Rendered, Option<String>) {
// LUT profiles have no GPU stage: they render on the CPU
let fallback = if gpu
&& !lightcraft_pipeline::lut::is_lut_profile(&s.profile.id)
&& !s.masks.iter().any(|m| m.visible && m.refine > 0.0)
&& req.proof.is_none()
{
// (LUT profiles, Refine Edges and soft proofs render on the GPU too)
let fallback = if gpu {
match lightcraft_gpu::try_render(src, info, s, req, stages) {
Ok(r) => return (r, None),
Err(lightcraft_gpu::Fallback::Failed(why)) => Some(why),
@@ -390,3 +445,33 @@ fn develop_image(
};
(rendered, fallback)
}
/// What [`develop_on_screen`] made.
enum OnScreen {
/// A texture on the window's device, and the histogram (never in the browser build).
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
Frame(ScreenFrame, Histogram),
/// Pixels (GPU or CPU).
Pixels(Rendered),
}
/// [`develop`] for a render that is only drawn: a texture on the window's device when the GPU
/// renderer can hand one over, else the pixels.
fn develop_on_screen(src: &Arc<Rgb32f>, info: &SourceInfo, s: &DevelopSettings, req: &RenderRequest, stages: Option<&StageCache>) -> OnScreen {
#[cfg(not(target_arch = "wasm32"))]
match lightcraft_gpu::render_display(src, info, s, req, stages) {
// an HDR edit's histogram shows the HDR range, as `develop_reporting` gives it
Some(lightcraft_gpu::Output::Display { frame, histogram }) => {
OnScreen::Frame(frame, lightcraft_pipeline::hdr_histogram(src, info, s, req).unwrap_or(histogram))
}
Some(lightcraft_gpu::Output::Image(mut r)) => {
if let Some(h) = lightcraft_pipeline::hdr_histogram(src, info, s, req) {
r.histogram = h;
}
OnScreen::Pixels(r)
}
None => OnScreen::Pixels(develop(src, info, s, req, stages, false)),
}
#[cfg(target_arch = "wasm32")]
OnScreen::Pixels(develop(src, info, s, req, stages, false))
}
+125 -36
View File
@@ -1,5 +1,6 @@
use super::quick::{QuickJob, content_key, source_info};
use super::render::{RenderJob, RenderResult};
use super::settings_hash::with_process;
use super::source::{PreviewLoader, RENDER_CACHE_VERSION, SourceLevel, SourceRef, THUMB_SIZES, face_edge, source_edge_needed, thumb_bucket};
use super::{Arc, DevelopSettings, Hash128, Hasher128, MediaKind, Op, Photo, PhotoId, RenderRequest, Rendered, Rgb32f, Source, SourceInfo};
@@ -41,17 +42,26 @@ impl crate::Session {
} else {
source_edge_needed(&p, &settings, apply_crop, max_w.max(max_h))
});
let source = self.media.source_ref(&p, level);
// the Before side develops with the Before settings' camera profile (or none), not the edit's
let source = if before {
let mut q = (*p).clone();
q.develop = settings.clone();
self.media.source_ref(&q, level)
} else {
self.media.source_ref(&p, level)
};
let request = RenderRequest { apply_crop, ..RenderRequest::fit(max_w, max_h) };
// the photo id is part of the key: two photos with the same settings and size must not
// share a result (a view slot showing photo A would otherwise look current for photo B)
// …and so is the file's content: a file changed on disk (Reload) renders afresh
let content_key = content_key(&p);
let source_key = Hasher128::new().str(&content_key).finish();
let content = source_key.0 as u64;
let content = Hasher128::new().str(&content_key).finish().0 as u64;
let source_key = super::quick::source_identity(&p);
// Temporary "before" settings must not replace the photo's cached develop hash.
let settings_hash = if before { settings.hash64() } else { self.media.settings_hashes.get(id, &settings) };
let salt = self.media.denoise_salt(id, &settings);
let profile_salt = self.media.camera_profile_salt(&settings.profile.id);
let lens = super::quick::lens_key(&p);
let key = settings_hash
^ ((max_w as u64) << 40)
^ ((max_h as u64) << 20)
@@ -59,14 +69,25 @@ impl crate::Session {
^ (level as u64) << 60
^ id.0.wrapping_mul(0x9e37_79b9_7f4a_7c15)
^ content.rotate_left(17)
^ salt;
^ salt
^ profile_salt.rotate_left(29)
^ lens.rotate_left(37);
let cache = thumb_bucket.map(|b| {
let mut k = Hasher128::new();
k.str(&content_key).u64(settings_hash).u64(b as u64).u64(RENDER_CACHE_VERSION).u64(crate::camera_profiles::cache_key());
k.str(&content_key).u64(settings_hash).u64(b as u64).u64(RENDER_CACHE_VERSION);
with_process(&mut k, &settings).u64(crate::camera_profiles::cache_key());
// (only a render that uses a denoised picture has it in its key, so every other thumbnail stays valid)
if salt != 0 {
k.u64(salt);
}
// (likewise an imported camera profile's file: deleted or replaced, the thumbnail renders afresh)
if profile_salt != 0 {
k.str("dcp").u64(profile_salt);
}
// (likewise a database lens profile: thumbnails of every other photo keep their keys)
if lens != 0 {
k.u64(lens);
}
(self.media.rendered.clone(), k.finish())
});
Some(RenderJob {
@@ -85,6 +106,7 @@ impl crate::Session {
stages: None,
view_cache: None,
display: None,
on_screen: false,
slide: None,
preview_cut: None,
display_fit: None,
@@ -95,21 +117,43 @@ impl crate::Session {
/// temporary preview while hovering a preset or profile; nothing is committed or cached).
pub fn preview_job(&mut self, id: PhotoId, max_w: usize, max_h: usize, apply_crop: bool, settings: &DevelopSettings) -> Option<RenderJob> {
let mut job = self.render_job(id, max_w, max_h, false, apply_crop)?;
// the source as these settings develop it: another camera profile (or none) decodes anew
let mut p = (**self.catalog.photo(id)?).clone();
let own_profile = self.media.camera_profile_of(&p).map(|c| c.0);
p.develop = Arc::new(settings.clone());
if self.media.camera_profile_of(&p).map(|c| c.0) != own_profile {
job.source = self.media.source_ref(&p, job.level);
}
job.settings = Arc::new(settings.clone());
job.key = settings.hash64() ^ ((max_w as u64) << 40) ^ ((max_h as u64) << 20) ^ (apply_crop as u64) ^ (job.level as u64) << 60;
// (the imported camera profile's file is in the key, as in `render_job`'s: a profile file replaced under the
// same id is a new picture)
let profile_salt = self.media.camera_profile_salt(&settings.profile.id);
// (the photo's database lens profile stays part of it: a profile looked up again renders afresh)
let lens = self.catalog.photo(id).map_or(0, |p| super::quick::lens_key(p));
job.key = settings.hash64()
^ ((max_w as u64) << 40)
^ ((max_h as u64) << 20)
^ (apply_crop as u64)
^ (job.level as u64) << 60
^ profile_salt.rotate_left(29)
^ lens.rotate_left(37);
Some(job)
}
/// Cache key of a variant thumbnail ([`Self::variant_job`]).
pub fn variant_key(p: &Photo, settings: &DevelopSettings, edge: usize) -> Hash128 {
Hasher128::new()
.str(&content_key(p))
.str("variant")
.u64(settings.hash64())
.u64(edge as u64)
.u64(RENDER_CACHE_VERSION)
.u64(crate::camera_profiles::cache_key())
.finish()
/// `profile_salt`: [`MediaCache::camera_profile_salt`] of `settings`' profile.
pub fn variant_key(p: &Photo, settings: &DevelopSettings, edge: usize, profile_salt: u64) -> Hash128 {
let mut k = Hasher128::new();
k.str(&content_key(p)).str("variant").u64(settings.hash64()).u64(edge as u64).u64(RENDER_CACHE_VERSION);
with_process(&mut k, settings).u64(crate::camera_profiles::cache_key());
if profile_salt != 0 {
k.str("dcp").u64(profile_salt);
}
let lens = super::quick::lens_key(p);
if lens != 0 {
k.u64(lens);
}
k.finish()
}
/// A thumbnail of `id` rendered with `settings` instead of its own (profile and preset
@@ -118,15 +162,17 @@ impl crate::Session {
/// hash, so a variant renders once; `key` is derived from the same hash, so a frontend can
/// keep one texture per variant.
pub fn variant_job(&mut self, id: PhotoId, settings: &DevelopSettings, edge: usize) -> Option<RenderJob> {
let p = self.catalog.photo(id)?.clone();
let mut p = (**self.catalog.photo(id)?).clone();
let edge = edge.clamp(16, SourceLevel::Thumb.max_edge());
let level = SourceLevel::Thumb;
// decoded as these settings develop it (their camera profile, or none)
p.develop = Arc::new(settings.clone());
let source = self.media.source_ref(&p, level);
let ck = Self::variant_key(&p, settings, edge);
let ck = Self::variant_key(&p, settings, edge, self.media.camera_profile_salt(&settings.profile.id));
Some(RenderJob {
request_id: 0,
cache_generation: self.media.rendered.generation(),
source_key: Some(Hasher128::new().str(&content_key(&p)).finish()),
source_key: Some(super::quick::source_identity(&p)),
photo: id,
level,
source,
@@ -139,6 +185,7 @@ impl crate::Session {
stages: None,
view_cache: None,
display: None,
on_screen: false,
slide: None,
preview_cut: None,
display_fit: None,
@@ -176,12 +223,12 @@ impl crate::Session {
let needed = (edge as f64 * w.max(h) / side).ceil().min(SourceLevel::Preview.max_edge() as f64);
let level = SourceLevel::for_size(needed as usize);
let source = self.media.source_ref(&p, level);
let ck = Self::variant_key(&p, &settings, edge);
let ck = Self::variant_key(&p, &settings, edge, self.media.camera_profile_salt(&settings.profile.id));
let preview_cut = self.face_preview_cut(&p, rect, edge, needed as usize);
Some(RenderJob {
request_id: 0,
cache_generation: self.media.rendered.generation(),
source_key: Some(Hasher128::new().str(&content_key(&p)).finish()),
source_key: Some(super::quick::source_identity(&p)),
photo: id,
level,
source,
@@ -194,6 +241,7 @@ impl crate::Session {
stages: None,
view_cache: None,
display: None,
on_screen: false,
slide: None,
preview_cut,
display_fit: None,
@@ -216,16 +264,20 @@ impl crate::Session {
Some(crate::face_tiles::PreviewCut { path, loader, want, min, rect, aspect, edge })
}
/// Size-independent cache key of a photo's view render (loupe) for its current settings.
fn view_key(p: &Photo, apply_crop: bool) -> Hash128 {
Hasher128::new()
.str(&content_key(p))
.str("view")
.u64(p.develop.hash64())
.u64(apply_crop as u64)
.u64(RENDER_CACHE_VERSION)
.u64(crate::camera_profiles::cache_key())
.finish()
/// Size-independent cache key of a photo's view render (loupe) for its current settings, its lens profile
/// included as in [`Self::variant_key`]. `profile_salt`: [`MediaCache::camera_profile_salt`] of the photo's profile.
pub(crate) fn view_key(p: &Photo, apply_crop: bool, profile_salt: u64) -> Hash128 {
let mut k = Hasher128::new();
k.str(&content_key(p)).str("view").u64(p.develop.hash64()).u64(apply_crop as u64).u64(RENDER_CACHE_VERSION);
with_process(&mut k, &p.develop).u64(crate::camera_profiles::cache_key());
if profile_salt != 0 {
k.str("dcp").u64(profile_salt);
}
let lens = super::quick::lens_key(p);
if lens != 0 {
k.u64(lens);
}
k.finish()
}
/// The loupe's render job: like [`Self::render_job`], and a full-quality result is kept as the
@@ -233,7 +285,8 @@ impl crate::Session {
pub fn loupe_job(&mut self, id: PhotoId, max_w: usize, max_h: usize, apply_crop: bool) -> Option<RenderJob> {
let mut job = self.render_job(id, max_w, max_h, false, apply_crop)?;
let p = self.catalog.photo(id)?;
job.view_cache = Some((self.media.rendered.clone(), Self::view_key(p, apply_crop)));
let profile_salt = self.media.camera_profile_salt(&p.develop.profile.id);
job.view_cache = Some((self.media.rendered.clone(), Self::view_key(p, apply_crop, profile_salt)));
Some(job)
}
@@ -342,8 +395,9 @@ impl crate::Session {
let p = self.catalog.photo(id)?.clone();
let small = self.thumb_job(id, THUMB_SIZES[THUMB_SIZES.len() - 1])?;
// (the thumbnail job itself starts with the cached thumbnail, after the sharper embedded preview)
let cached = vec![(self.media.rendered.clone(), Self::view_key(&p, apply_crop))];
let h = Hasher128::new().str(&content_key(&p)).str("quick").u64(p.develop.hash64()).u64(apply_crop as u64).finish();
let profile_salt = self.media.camera_profile_salt(&p.develop.profile.id);
let cached = vec![(self.media.rendered.clone(), Self::view_key(&p, apply_crop, profile_salt))];
let h = Hasher128::new().str(&content_key(&p)).str("quick").u64(p.develop.hash64()).u64(apply_crop as u64).u64(profile_salt).finish();
let key = h.0 as u64;
let embedded = self.embedded_of(&p).map(|(path, l)| (path, l, max_edge.clamp(1, SourceLevel::Preview.max_edge())));
Some(QuickJob { request_id: 0, photo: id, key, cached, embedded, minimum_embedded_edge: None, small: apply_crop.then(|| Box::new(small)) })
@@ -374,7 +428,7 @@ impl crate::Session {
/// has wrong is corrected too ([`Self::learn_as_shot_wb`]).
pub fn accept(&mut self, r: &RenderResult) {
if let Some(src) = &r.loaded
&& r.source_key.is_none_or(|key| self.catalog.photo(r.photo).is_some_and(|p| Hasher128::new().str(&content_key(p)).finish() == key))
&& r.source_key.is_none_or(|key| self.catalog.photo(r.photo).is_some_and(|p| super::quick::source_identity(p) == key))
{
if let Some(info) = &src.info {
self.learn_as_shot_wb(r.photo, info);
@@ -474,8 +528,10 @@ impl crate::Session {
/// Prefer decoder facts to header-only metadata for pixel-statistics commands.
pub fn source_info(&self, id: PhotoId) -> SourceInfo {
let header = self.catalog.photo(id).map(|p| source_info(p)).unwrap_or_default();
self.media.source_facts(id, header)
let photo = self.catalog.photo(id);
let header = photo.map(|p| source_info(p)).unwrap_or_default();
let profile = photo.and_then(|p| self.media.camera_profile_of(p)).map(|(tag, _)| tag);
self.media.source_facts(id, header, profile.as_deref())
}
/// The source proxy for pixel-statistics commands (auto tone/WB), loading synchronously.
@@ -489,4 +545,37 @@ impl crate::Session {
self.media.insert_source(id, level, r);
Ok(image)
}
/// [`Session::source_now`] for several photos at once, each with the facts its decoder gave
/// ([`Session::source_info`], read before another photo can push it out of the cache): the
/// ones not in memory are decoded in parallel, so a selection costs about one decode per core,
/// not one after another. In the order of `ids`. Callers pass a few at a time (all of them are
/// held decoded until this returns).
pub(crate) fn sources_now(&mut self, ids: &[PhotoId], level: SourceLevel) -> Vec<(PhotoId, Result<(Arc<Rgb32f>, SourceInfo), String>)> {
use rayon::prelude::*;
let refs: Vec<(PhotoId, Option<SourceRef>)> =
ids.iter().map(|&id| (id, self.catalog.photo(id).cloned().map(|p| self.media.source_ref(&p, level)))).collect();
let loaded: Vec<(PhotoId, Result<super::source::DecodedSource, String>)> =
refs.into_par_iter().map(|(id, r)| (id, r.ok_or_else(|| "no such photo".to_string()).and_then(|r| r.load_source()))).collect();
loaded
.into_iter()
.map(|(id, r)| {
let r = r.map(|r| {
let image = r.image.clone();
if let Some(info) = &r.info {
self.learn_as_shot_wb(id, info);
}
// read before the insert: the cache's budget may evict this very entry, and
// the header facts alone lack the decoder's camera colour
let facts = match r.info {
Some(_) => r.info_or(self.catalog.photo(id).map(|p| source_info(p)).unwrap_or_default()),
None => self.source_info(id),
};
self.media.insert_source(id, level, r);
(image, facts)
});
(id, r)
})
.collect()
}
}
+16 -1
View File
@@ -1,4 +1,4 @@
use super::{Arc, DevelopSettings, HashMap, PhotoId, VecDeque, Weak};
use super::{Arc, DevelopSettings, HashMap, Hasher128, PhotoId, VecDeque, Weak};
pub(super) const SETTINGS_HASH_ENTRIES: usize = 1024;
@@ -34,3 +34,18 @@ impl SettingsHashes {
hash
}
}
/// Add the rendering process `s` renders with in this build to persistent render key `h`, from
/// process V3 on: a process number from a newer LightCraft renders with an older build's latest
/// process, so the same settings (and settings hash) render differently in a build that knows that
/// process, and the keys must tell those renders apart. Builds before V3 (which have no process in
/// their keys) resolve every number above V2 to V2: naming V3 and later keeps this build's renders
/// of those numbers apart from theirs, and V1 and V2 keep the keys they always had, so their
/// cached renders stay valid (`docs/process-versions.md`).
pub(super) fn with_process<'a>(h: &'a mut Hasher128, s: &DevelopSettings) -> &'a mut Hasher128 {
let v = s.process.process().version().0;
if v >= lightcraft_develop::Process::V3.version().0 {
h.u64(u64::from(v));
}
h
}
+48 -13
View File
@@ -1,7 +1,7 @@
use super::{Arc, Deserialize, DevelopSettings, MediaKind, Photo, Rgb32f, Rgba8, Serialize, SourceInfo};
use super::{Arc, DcpProfile, Deserialize, DevelopSettings, MediaKind, Photo, Rgb32f, Rgba8, Serialize, SourceInfo};
/// Bump when the pipeline's output changes, to invalidate cached thumbnails.
pub const RENDER_CACHE_VERSION: u64 = 72;
pub const RENDER_CACHE_VERSION: u64 = 75;
/// 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];
@@ -75,12 +75,14 @@ pub(super) fn source_edge_needed(p: &Photo, settings: &DevelopSettings, apply_cr
}
/// Decodes a file into a linear Rec.2020 image no larger than `max_edge` (set by the app).
pub type FileLoader = Arc<dyn Fn(&str, usize) -> Result<(Rgb32f, SourceInfo), String> + Send + Sync>;
/// The third argument is the photo's imported camera profile ([`crate::cmd::dcp_profiles`]): a raw file is developed
/// with its colour model.
pub type FileLoader = Arc<dyn Fn(&str, usize, Option<&DcpProfile>) -> Result<(Rgb32f, SourceInfo), String> + Send + Sync>;
/// [`FileLoader`] for a thumbnail: a raw file that keeps smaller copies of its raw image (Lightroom's merged DNGs)
/// develops the smallest that covers `max_edge` (set by the app); the flag says it did. Never used for an export,
/// which must render the full image.
pub type ReducedLoader = Arc<dyn Fn(&str, usize) -> Result<(Rgb32f, SourceInfo, bool), String> + Send + Sync>;
pub type ReducedLoader = Arc<dyn Fn(&str, usize, Option<&DcpProfile>) -> Result<(Rgb32f, SourceInfo, bool), String> + Send + Sync>;
/// A raw file's embedded (camera-rendered) preview as display sRGB, oriented, no larger than
/// `max_edge` (set by the app). `None`: no usable preview.
@@ -103,7 +105,8 @@ pub struct DenoiseSpec {
/// Decodes a raw file once and develops it twice: as usual, and from the denoised picture in `spec` when that can be
/// read (`None` when it cannot). Both are at most `max_edge` long and the same size.
pub type PairLoader = Arc<dyn Fn(&str, usize, &DenoiseSpec) -> Result<(Rgb32f, Option<Rgb32f>, SourceInfo), String> + Send + Sync>;
pub type PairLoader =
Arc<dyn Fn(&str, usize, &DenoiseSpec, Option<&DcpProfile>) -> Result<(Rgb32f, Option<Rgb32f>, SourceInfo), String> + Send + Sync>;
/// A photo's denoised picture next to its plain one, and the last mix of the two that was asked for.
pub struct Twin {
@@ -133,6 +136,9 @@ pub struct DecodedSource {
pub camera_tone: Option<lightcraft_pipeline::tone::CameraTone>,
/// The same picture developed from the AI-denoised mosaic, when the photo has one cached.
pub denoised: Option<Arc<Twin>>,
/// The imported camera profile (`dcp:…` id) the raw file was developed with, if any: a cached source made with
/// another one (or none) doesn't stand in for it.
pub camera_profile: Option<String>,
/// These pixels came from the photo's smart preview (an offline original), not from its file.
/// A refresh must never rebuild a proxy from itself: that would stamp its older look as current.
pub from_proxy: bool,
@@ -143,7 +149,7 @@ pub struct DecodedSource {
impl DecodedSource {
pub fn new(image: Arc<Rgb32f>, info: Option<SourceInfo>) -> Self {
DecodedSource { image, info, camera_tone: None, denoised: None, from_proxy: false, reduced: false }
DecodedSource { image, info, camera_tone: None, denoised: None, camera_profile: None, from_proxy: false, reduced: false }
}
/// The picture to develop for a Denoise `amount` (0 to 1, see [`DevelopSettings::denoise_amount`]): the plain one,
@@ -183,14 +189,35 @@ impl DecodedSource {
/// What to render these pixels against: the decoder's facts, else `header` (the catalog's)
/// with any stored camera tone curve. The original's size comes from `header` either way: the
/// decoder only sees the level it decoded.
///
/// A lens profile from the lens database is the catalog's too ([`pinned_lens`]): the decoder looks the lens up in
/// the database in use when it reads the file, which may be newer than the one the photo's profile came from.
pub fn info_or(&self, header: SourceInfo) -> SourceInfo {
match &self.info {
Some(info) => SourceInfo { native_long: info.native_long.or(header.native_long), ..info.clone() },
Some(info) => {
SourceInfo { native_long: info.native_long.or(header.native_long), lens: pinned_lens(info.lens, header.lens), ..info.clone() }
}
None => SourceInfo { camera_tone: self.camera_tone.or(header.camera_tone), ..header },
}
}
}
/// The lens profile a render uses: the file's own correction as decoded (`decoded`, it is part of the file), else the
/// catalog's database profile (`catalog`, [`lightcraft_catalog::Photo::embedded_lens`]). A file correction the
/// catalog still holds but the decode no longer finds (the original was replaced) is not restored. A database profile
/// is never taken from the decode, so a cached render, a fresh decode and the Optics panel all use the one profile the photo holds, and a
/// change to it (a database update looked up again, `cmd::lens_refresh`) changes the render keys
/// ([`super::quick::lens_key`]).
pub(crate) fn pinned_lens(
decoded: Option<lightcraft_develop::EmbeddedLens>,
catalog: Option<lightcraft_develop::EmbeddedLens>,
) -> Option<lightcraft_develop::EmbeddedLens> {
match decoded {
Some(l) if l.source == lightcraft_develop::LensSource::File => Some(l),
_ => catalog.filter(|c| c.source == lightcraft_develop::LensSource::Database),
}
}
#[derive(Clone)]
pub enum SourceRef {
Loaded(Box<DecodedSource>),
@@ -214,6 +241,8 @@ pub enum SourceRef {
fallback: Option<std::path::PathBuf>,
/// The photo has a cached denoised picture: load it with the plain one (see [`PairLoader`]).
denoise: Option<(DenoiseSpec, PairLoader)>,
/// The photo's imported camera profile (id and profile): its raw file is developed with it.
camera_profile: Option<(String, Arc<DcpProfile>)>,
/// A thumbnail's loader, used instead of `loader` (see [`ReducedLoader`]); `None` for every other job.
reduced: Option<ReducedLoader>,
},
@@ -241,12 +270,17 @@ impl SourceRef {
return Ok(DecodedSource { image: Arc::new(image), denoised: None, ..(**from).clone() });
}
SourceRef::Demo { scene, max_edge } => crate::demo::scene_pixels(scene, *max_edge)?,
SourceRef::File { path, max_edge, loader, fallback, denoise, reduced } => {
SourceRef::File { path, max_edge, loader, fallback, denoise, camera_profile, reduced } => {
let dcp = camera_profile.as_ref().map(|(_, p)| p.as_ref());
let made_with = camera_profile.as_ref().map(|(id, _)| id.clone());
let plain = || match (reduced, loader) {
(Some(l), _) => {
l(path, *max_edge).map(|(image, info, reduced)| DecodedSource { reduced, ..DecodedSource::new(Arc::new(image), Some(info)) })
}
(None, Some(l)) => l(path, *max_edge).map(|(image, info)| DecodedSource::new(Arc::new(image), Some(info))),
(Some(l), _) => l(path, *max_edge, dcp).map(|(image, info, reduced)| DecodedSource {
reduced,
camera_profile: made_with.clone(),
..DecodedSource::new(Arc::new(image), Some(info))
}),
(None, Some(l)) => l(path, *max_edge, dcp)
.map(|(image, info)| DecodedSource { camera_profile: made_with.clone(), ..DecodedSource::new(Arc::new(image), Some(info)) }),
(None, None) => Err(format!("no decoder available for {path}")),
};
// the denoised picture comes with the plain one from a single decode; when it cannot be read the
@@ -260,7 +294,7 @@ impl SourceRef {
None => true,
};
if made {
pair(path, *max_edge, spec).and_then(|(image, twin, info)| {
pair(path, *max_edge, spec, dcp).and_then(|(image, twin, info)| {
if spec.make.is_some() && twin.is_none() {
return Err("the cached AI Denoise picture could not be read; clear the denoise cache and retry".into());
}
@@ -269,6 +303,7 @@ impl SourceRef {
info: Some(info),
camera_tone: None,
denoised: twin.map(|t| Arc::new(Twin::new(Arc::new(t)))),
camera_profile: made_with.clone(),
from_proxy: false,
reduced: false,
})
+4 -2
View File
@@ -83,13 +83,14 @@ fn decoder_info_survives_render_jobs_cache_and_eviction() {
job.source = SourceRef::File {
path: "synthetic.arw".into(),
max_edge: 64,
loader: Some(Arc::new(move |_, _| {
loader: Some(Arc::new(move |_, _, _| {
let mut image = Rgb32f::new(64, 64);
image.data.fill([0.1; 3]);
Ok((image, loaded_info.clone()))
})),
fallback: None,
denoise: None,
camera_profile: None,
reduced: None,
};
job.info = SourceInfo::default(); // Header facts cannot override decoder facts.
@@ -143,9 +144,10 @@ fn old_relative_white_balance_on_a_kelvin_camera_keeps_its_look_and_learns_the_a
job.source = SourceRef::File {
path: "/photos/DSC00001.ARW".into(),
max_edge: 64,
loader: Some(Arc::new(move |_, _| Ok((loaded_pixels.clone(), loaded_info.clone())))),
loader: Some(Arc::new(move |_, _, _| Ok((loaded_pixels.clone(), loaded_info.clone())))),
fallback: None,
denoise: None,
camera_profile: None,
reduced: None,
};
let undo_before = s.undo.len();
+112 -2
View File
@@ -6,6 +6,77 @@ fn session() -> crate::Session {
s.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap();
s
}
/// Settings saved by a newer LightCraft (a process number this build doesn't know) render with
/// this build's latest process, and a build that resolved the number to an older process
/// cached other pixels under the same settings hash: the persistent keys (thumbnails, the
/// loupe's view render, variants) name the process the settings render with, so those are
/// never served (review of 5a7016c8: a catalog saved with a newer process kept main's V2 thumbnails).
#[test]
fn persistent_keys_name_the_process_the_settings_render_with() {
use lightcraft_develop::ProcessVersion;
let mut s = session();
let newer = DevelopSettings { process: ProcessVersion(ProcessVersion::LATEST.0 + 1), ..DevelopSettings::default() };
s.catalog.apply(Op::SetDevelop { id: PhotoId(1), settings: Arc::new(newer.clone()), label: "newer".into(), edited: None }).unwrap();
let p = s.catalog.photo(PhotoId(1)).unwrap().clone();
let unnamed = |kind: Option<&str>, size: u64| {
let mut h = Hasher128::new();
h.str(&content_key(&p));
if let Some(k) = kind {
h.str(k);
}
h.u64(newer.hash64()).u64(size).u64(RENDER_CACHE_VERSION).u64(crate::camera_profiles::cache_key()).finish()
};
let named = |kind: Option<&str>, size: u64, process: u64| {
let mut h = Hasher128::new();
h.str(&content_key(&p));
if let Some(k) = kind {
h.str(k);
}
h.u64(newer.hash64()).u64(size).u64(RENDER_CACHE_VERSION).u64(process).u64(crate::camera_profiles::cache_key()).finish()
};
let resolved = u64::from(lightcraft_develop::Process::LATEST.version().0);
let keys = [
(s.thumb_job(PhotoId(1), 256).unwrap().cache.unwrap().1, None, 256),
(crate::Session::view_key(&p, true, 0), Some("view"), 1),
(crate::Session::variant_key(&p, &newer, 256, 0), Some("variant"), 256),
];
for (key, kind, size) in keys {
assert_ne!(key, unnamed(kind, size), "old builds did not name their resolved process");
assert_eq!(key, named(kind, size, resolved), "the key names the process used for rendering");
assert_ne!(key, named(kind, size, u64::from(newer.process.0)), "the saved future number is not the resolved process");
}
}
/// Photos on V1 and V2 keep the persistent keys builds before process V3 gave them (no process
/// in them), so their cached thumbnails, view renders and variants stay valid after upgrading
/// (review of 26cd2df1: every V1/V2 photo rendered again, and offline ones without smart
/// previews lost their thumbnails); V3 and later name their process.
#[test]
fn v1_and_v2_photos_keep_the_render_cache_keys_they_had() {
use lightcraft_develop::Process;
let mut s = session();
for process in [Process::V1, Process::V2, Process::V3] {
let settings = DevelopSettings { process: process.version(), ..DevelopSettings::default() };
s.catalog.apply(Op::SetDevelop { id: PhotoId(1), settings: Arc::new(settings.clone()), label: "p".into(), edited: None }).unwrap();
let p = s.catalog.photo(PhotoId(1)).unwrap().clone();
let before_v3 = |kind: Option<&str>, size: u64| {
let mut h = Hasher128::new();
h.str(&content_key(&p));
if let Some(k) = kind {
h.str(k);
}
h.u64(settings.hash64()).u64(size).u64(RENDER_CACHE_VERSION).u64(crate::camera_profiles::cache_key()).finish()
};
let keys = [
s.thumb_job(PhotoId(1), 256).unwrap().cache.unwrap().1 == before_v3(None, 256),
crate::Session::view_key(&p, true, 0) == before_v3(Some("view"), 1),
crate::Session::variant_key(&p, &settings, 256, 0) == before_v3(Some("variant"), 256),
];
let old = process <= Process::V2;
assert_eq!(keys, [old; 3], "{process:?}: thumbnail, view and variant keys");
}
}
#[test]
fn hashes_match_uncached_keys_and_are_not_recomputed_for_sizes_metadata_or_before() {
let mut s = session();
@@ -21,6 +92,7 @@ fn hashes_match_uncached_keys_and_are_not_recomputed_for_sizes_metadata_or_befor
.u64(settings)
.u64(b as u64)
.u64(RENDER_CACHE_VERSION)
.u64(u64::from(p.develop.process.process().version().0))
.u64(crate::camera_profiles::cache_key())
.finish();
let job = s.thumb_job(p.id, edge).unwrap();
@@ -70,7 +142,7 @@ fn hash_cache_is_bounded_weak_and_shared_settings_remain_independent() {
#[test]
fn source_from_before_content_reload_is_not_accepted() {
let mut s = session();
s.media.file_loader = Some(Arc::new(|_, _| Ok((Rgb32f::new(8, 8), SourceInfo::default()))));
s.media.file_loader = Some(Arc::new(|_, _, _| Ok((Rgb32f::new(8, 8), SourceInfo::default()))));
let old = s.thumb_job(PhotoId(1), 256).unwrap().run();
assert!(old.loaded.is_some());
s.catalog
@@ -88,13 +160,51 @@ fn source_from_before_content_reload_is_not_accepted() {
s.accept(&old);
assert_eq!(s.media.source_usage().0, 0);
}
/// A decode that started before the photo's database lens profile changed (a lens database arriving, looked up again
/// by `cmd::lens_refresh`, which drops the photo's sources) never puts its source back in the cache: the source's
/// colour was fitted through the old profile.
#[test]
fn source_from_before_a_lens_profile_change_is_not_accepted() {
let mut s = session();
s.media.file_loader = Some(Arc::new(|_, _, _| Ok((Rgb32f::new(8, 8), SourceInfo::default()))));
let old = s.thumb_job(PhotoId(1), 256).unwrap().run();
assert!(old.loaded.is_some());
let lens = lightcraft_develop::EmbeddedLens { source: lightcraft_develop::LensSource::Database, ..Default::default() };
s.catalog.apply(Op::SetEmbeddedLens { id: PhotoId(1), lens: Some(Box::new(lens)) }).unwrap();
s.media.forget(PhotoId(1));
s.accept(&old);
assert_eq!(s.media.source_usage().0, 0, "the old decode is dropped");
// a decode made with the new profile is kept
let new = s.thumb_job(PhotoId(1), 256).unwrap().run();
s.accept(&new);
assert_ne!(s.media.source_usage().0, 0);
}
/// The loupe's hover preview (a preset or profile under the pointer) is cached by its key, so a database lens
/// profile looked up again gives it a new key and the hover renders afresh instead of showing the old correction.
#[test]
fn a_hover_preview_key_follows_the_lens_profile() {
let mut s = session();
let settings = s.catalog.photo(PhotoId(1)).unwrap().develop.clone();
let before = s.preview_job(PhotoId(1), 640, 480, true, &settings).unwrap().key;
let lens = lightcraft_develop::EmbeddedLens { source: lightcraft_develop::LensSource::Database, ..Default::default() };
s.catalog.apply(Op::SetEmbeddedLens { id: PhotoId(1), lens: Some(Box::new(lens)) }).unwrap();
let after = s.preview_job(PhotoId(1), 640, 480, true, &settings).unwrap().key;
assert_ne!(before, after);
// one database profile looked up again as another (a newer database): the key follows the profile's contents,
// not only whether there is one
let vignette = lightcraft_develop::EmbeddedVignette { k: [-0.3, 0.0, 0.0, 0.0, 0.0], radius: 1.0, ..Default::default() };
let other = lightcraft_develop::EmbeddedLens { source: lightcraft_develop::LensSource::Database, vignette: Some(vignette), ..Default::default() };
s.catalog.apply(Op::SetEmbeddedLens { id: PhotoId(1), lens: Some(Box::new(other)) }).unwrap();
let again = s.preview_job(PhotoId(1), 640, 480, true, &settings).unwrap().key;
assert_ne!(after, again, "a different database profile");
}
/// A panic while rendering (here in the decoder) used to end the pool's worker thread without
/// an answer, so the view that asked showed "Rendering…" forever. It is the job's failure now,
/// for renders and for stand-ins, answering the request it came from.
#[test]
fn a_render_that_panics_fails_instead_of_never_answering() {
let mut s = session();
s.media.file_loader = Some(Arc::new(|_, _| panic!("decoder bug")));
s.media.file_loader = Some(Arc::new(|_, _, _| panic!("decoder bug")));
let mut job = s.thumb_job(PhotoId(1), 256).unwrap();
job.request_id = 42;
let (key, level, source_key) = (job.key, job.level, job.source_key);
+32 -13
View File
@@ -523,7 +523,23 @@ impl Session {
if let Some(p) = profile(id) {
return Some((p.name, p.group));
}
self.lut_profiles.iter().find(|p| p.id == id).map(|p| (p.name.as_str(), p.group.as_str()))
if let Some(p) = self.lut_profiles.iter().find(|p| p.id == id) {
return Some((p.name.as_str(), p.group.as_str()));
}
self.dcp_profiles.iter().find(|p| p.id == id).map(|p| (p.name.as_str(), crate::cmd::dcp_profiles::DCP_GROUP))
}
/// The imported profiles as (id, name, group): LUT profiles, then camera profiles (`.dcp`). A camera profile
/// whose file is missing or damaged (not loaded when the library opened) is left out, so it can't be chosen; its
/// entry stays and it is offered again once the file is back.
pub fn imported_profiles(&self) -> Vec<(String, String, String)> {
let luts = self.lut_profiles.iter().map(|p| (p.id.clone(), p.name.clone(), p.group.clone()));
let dcps = self
.dcp_profiles
.iter()
.filter(|p| self.media.camera_profiles.contains_key(&p.id))
.map(|p| (p.id.clone(), p.name.clone(), crate::cmd::dcp_profiles::DCP_GROUP.to_string()));
luts.chain(dcps).collect()
}
/// Remember `id` as the most recently applied profile.
@@ -537,28 +553,31 @@ impl Session {
pub fn profile_menu(&self) -> Value {
let item =
|p: &ProfileInfo| json!({"id": p.id, "name": p.name, "group": p.group, "favorite": self.profile_favorites.iter().any(|f| f == p.id)});
let lut_item = |id: &str| {
self.lut_profiles
.iter()
.find(|p| p.id == id)
.map(|p| json!({"id": p.id, "name": p.name, "group": p.group, "favorite": self.profile_favorites.contains(&p.id), "imported": true}))
let imported = self.imported_profiles();
let imported_item = |(id, name, group): &(String, String, String)| {
let mut v = json!({"id": id, "name": name, "group": group, "favorite": self.profile_favorites.contains(id), "imported": true});
if let Some(d) = self.dcp_profiles.iter().find(|d| &d.id == id) {
v["cameraModel"] = json!(d.camera_model);
}
v
};
let lut_item = |id: &str| imported.iter().find(|p| p.0 == id).map(imported_item);
let list = |ids: &[String]| ids.iter().filter_map(|id| profile(id).map(item).or_else(|| lut_item(id))).collect::<Vec<_>>();
let mut groups: Vec<Value> = profile_groups()
.into_iter()
.map(|g| json!({"name": g, "profiles": PROFILES.iter().filter(|p| p.group == g).map(item).collect::<Vec<_>>()}))
.collect();
// imported LUT profiles, by their groups
// imported LUT profiles by their groups, then camera profiles
let mut lut_groups: Vec<&str> = self.lut_profiles.iter().map(|p| p.group.as_str()).collect();
lut_groups.sort_unstable();
lut_groups.dedup();
// the camera profiles' group once, last (a LUT group of the same name joins it rather than showing twice)
lut_groups.retain(|g| *g != crate::cmd::dcp_profiles::DCP_GROUP);
if imported.iter().any(|p| p.2 == crate::cmd::dcp_profiles::DCP_GROUP) {
lut_groups.push(crate::cmd::dcp_profiles::DCP_GROUP);
}
for g in lut_groups {
let profiles: Vec<Value> = self
.lut_profiles
.iter()
.filter(|p| p.group == g)
.map(|p| json!({"id": p.id, "name": p.name, "group": p.group, "favorite": self.profile_favorites.contains(&p.id), "imported": true}))
.collect();
let profiles: Vec<Value> = imported.iter().filter(|p| p.2 == g).map(imported_item).collect();
groups.push(json!({"name": g, "profiles": profiles, "imported": true}));
}
json!({
+59 -1
View File
@@ -46,6 +46,9 @@ pub(crate) trait MoveFs {
fn packet_version(&self, path: &Path) -> std::io::Result<PacketVersion> {
use std::io::Read;
let mut file = std::fs::File::open(path)?;
if !file.metadata()?.is_file() {
return Err(std::io::Error::other(format!("{} is not a regular file", path.display())));
}
let mut hash = lightcraft_preview::Hasher128::new();
let mut len = 0u64;
let mut buffer = [0u8; 16 * 1024];
@@ -141,8 +144,14 @@ impl MoveFs for RealFs {
.map(|k| b.with_file_name(format!(".{name}.lc-partial-{}-{k}", std::process::id())))
.find(|p| !self.exists(p))
.ok_or_else(|| std::io::Error::other(format!("no free temporary name beside {}", b.display())))?;
// a sidecar found beside the photo by its name is copied only when it is a plain file: a
// link there would have its target's contents copied into a new, readable file
let checked = std::fs::symlink_metadata(a)?;
if !checked.is_file() {
return Err(std::io::Error::other(format!("{} is not a regular file", a.display())));
}
let copied = (|| {
let mut from = std::fs::File::open(a)?;
let mut from = open_regular(a, &checked)?;
let mut f = std::fs::OpenOptions::new().write(true).create_new(true).open(&partial)?;
std::io::copy(&mut from, &mut f)?;
f.sync_all()
@@ -163,6 +172,33 @@ impl MoveFs for RealFs {
}
}
/// Opens `a` for reading and checks the open handle is the regular file `checked` (the
/// `symlink_metadata` of `a` taken before): the path check alone can be outrun by a swap for a
/// link, whose target the open would follow.
fn open_regular(a: &Path, checked: &std::fs::Metadata) -> std::io::Result<std::fs::File> {
let mut options = std::fs::OpenOptions::new();
options.read(true);
// FILE_FLAG_OPEN_REPARSE_POINT: a symbolic link is opened itself, and then refused below
#[cfg(windows)]
std::os::windows::fs::OpenOptionsExt::custom_flags(&mut options, 0x0020_0000);
let file = options.open(a)?;
let opened = file.metadata()?;
#[cfg(unix)]
let same = {
use std::os::unix::fs::MetadataExt;
(opened.dev(), opened.ino()) == (checked.dev(), checked.ino())
};
#[cfg(not(unix))]
let same = {
let _ = checked;
true
};
if !opened.is_file() || !same {
return Err(std::io::Error::other(format!("{} is not a regular file", a.display())));
}
Ok(file)
}
/// Move `a` to `b` on another volume: copy (never replacing), compare the copy with the original
/// byte for byte, and only then remove the original. A copy that doesn't match is removed.
fn move_across_volumes(fs: &RealFs, a: &Path, b: &Path) -> std::io::Result<()> {
@@ -240,3 +276,25 @@ pub(super) fn move_one(fs: &dyn MoveFs, a: &Path, b: &Path) -> std::io::Result<(
Err(e2) => std::io::Error::other(format!("{e}; it could not be given its old name back either ({e2}): it is now {}", tmp.display())),
})
}
#[cfg(all(test, unix))]
mod open_regular_tests {
use super::open_regular;
#[test]
fn a_link_swapped_in_after_the_check_is_not_followed() {
let dir = std::env::temp_dir().join(format!("lightcraft-open-regular-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let (file, other, link) = (dir.join("a.xmp"), dir.join("secret"), dir.join("link.xmp"));
std::fs::write(&file, b"x").unwrap();
std::fs::write(&other, b"secret").unwrap();
let checked = std::fs::symlink_metadata(&file).unwrap();
assert!(open_regular(&file, &checked).is_ok());
// the name now holds a link to another file: the handle is not the one checked
std::fs::remove_file(&file).unwrap();
std::os::unix::fs::symlink(&other, &link).unwrap();
std::fs::rename(&link, &file).unwrap();
assert!(open_regular(&file, &checked).is_err(), "the link's target must not be opened");
std::fs::remove_dir_all(&dir).unwrap();
}
}
+16 -4
View File
@@ -27,7 +27,7 @@ pub fn plan_rename_photos(photos: &[std::sync::Arc<Photo>], template: &str, star
/// Plan renaming `photos`: `exists` says whether something answers to a path, `same_file` whether
/// two spellings name one file (see [`MoveFs`]).
fn plan_rename_core(
pub(super) fn plan_rename_core(
photos: &[std::sync::Arc<Photo>],
template: &str,
start: usize,
@@ -35,6 +35,9 @@ fn plan_rename_core(
same_file: &dyn Fn(&Path, &Path) -> bool,
) -> Vec<RenamePlan> {
let mut taken: HashSet<String> = HashSet::new(); // lower-case target paths/names claimed in this batch
// Per first-choice target: how many leading suffixes are all claimed in this batch (`taken` only grows), so the
// next photo with the same first choice starts after them instead of rebuilding each one.
let mut claimed_prefix: std::collections::HashMap<String, usize> = std::collections::HashMap::new();
let mut out = Vec::new();
for (i, p) in photos.iter().enumerate() {
let seq = start.saturating_add(i);
@@ -53,7 +56,9 @@ fn plan_rename_core(
let (to, to_path) = match &p.source {
Source::File { path } => {
let dir = Path::new(path).parent().map(Path::to_path_buf).unwrap_or_default();
let mut k = 0;
let base = folded_path(&dir.join(&want).to_string_lossy());
let mut k = claimed_prefix.get(&base).copied().unwrap_or(0);
let mut all_taken = true;
loop {
let name = candidate(k);
let tp = dir.join(&name).to_string_lossy().to_string();
@@ -64,18 +69,25 @@ fn plan_rename_core(
let same = from == to || (key == folded_path(path) && exists(to) && same_file(from, to));
// free: not claimed in this batch and not on disk (unless it is this very file).
// A file this batch moves away still counts as taken: simple and safe.
if !taken.contains(&key) && (same || !exists(to)) {
let claimed = taken.contains(&key);
if !claimed && (same || !exists(to)) {
taken.insert(key);
if all_taken {
claimed_prefix.insert(base, k + 1);
}
break (name, Some(tp));
}
all_taken &= claimed;
k += 1;
}
}
Source::Demo { .. } => {
let mut k = 0;
let base = format!("demo:{}", want.to_lowercase());
let mut k = claimed_prefix.get(&base).copied().unwrap_or(0);
loop {
let name = candidate(k);
if taken.insert(format!("demo:{}", name.to_lowercase())) {
claimed_prefix.insert(base, k + 1); // (every candidate before it was claimed: nothing but `taken` rejects a demo name)
break (name, None);
}
k += 1;
+34
View File
@@ -588,3 +588,37 @@ fn number_folder_and_metadata_tokens() {
// a bare {seq} is padded to the caller's width
assert_eq!(expand_tokens("{seq}|{seq:2}", &p, 7, 3), "007|07");
}
/// Many photos wanting one name take its suffixes in order without each starting over at the bare name.
#[test]
fn photos_sharing_a_target_name_do_not_rescan_the_suffixes_already_claimed() {
let photos: Vec<std::sync::Arc<Photo>> = (0..300)
.map(|i| {
std::sync::Arc::new(Photo::new(
PhotoId(i + 1),
Source::File { path: format!("/lib/src{i}.jpg") },
&format!("src{i}.jpg"),
"JPEG",
0,
0,
"2024-01-01T00:00:00Z",
))
})
.collect();
let checks = std::cell::Cell::new(0usize);
let plans = plan::plan_rename_core(
&photos,
"same",
1,
&|_| {
checks.set(checks.get() + 1);
false
},
&|_, _| false,
);
let mut names: Vec<&str> = plans.iter().map(|p| p.to.as_str()).collect();
names.sort_unstable();
names.dedup();
assert_eq!(names.len(), 300);
assert!(checks.get() <= 3 * 300, "{} disk checks", checks.get());
}
+20 -2
View File
@@ -376,12 +376,23 @@ fn clicks_of(include: &[Point], exclude: &[Point]) -> Vec<Click> {
}
impl Session {
/// The key and settings of photo `id` as the model sees it: its look without masks, uncropped.
/// The key and settings of photo `id` as the model sees it: its look without masks, uncropped
/// and unflipped, and without lens corrections, Upright and Transform. Mask coordinates
/// (clicks, stored selections) live on the photo before those (`Mask::on_photo`), so a
/// selection stays on its content when they change, and changing them doesn't ask again.
#[cfg_attr(not(feature = "sam"), allow(dead_code))]
fn segment_key(&self, id: PhotoId) -> Option<(u64, lightcraft_develop::DevelopSettings)> {
pub(crate) fn segment_key(&self, id: PhotoId) -> Option<(u64, lightcraft_develop::DevelopSettings)> {
let p = self.catalog.photo(id)?;
let mut d = (*p.develop).clone();
d.masks.clear();
// (the crop doesn't show in the uncropped input: it doesn't ask again either)
d.crop = Default::default();
d.geometry = Default::default();
d.optics.lens_profile = false;
d.optics.distortion = 0.0;
d.optics.remove_ca = false;
d.optics.ca_red = 0.0;
d.optics.ca_blue = 0.0;
let content = crate::media::content_key(p);
let mut h = mix(0xcbf2_9ce4_8422_2325, d.hash64());
h = mix(h, id.0);
@@ -410,6 +421,13 @@ impl Session {
region: Option<[f64; 4]>,
) -> Result<worker::Job, String> {
let dir = self.segmenter.model_dir()?;
// old masks go onto the photo first: the selection that comes back is in its coordinates
if let Some(cur) = self.develop_of(id).filter(|d| d.masks.iter().any(|m| !m.on_photo)) {
let mut on = (*cur).clone();
self.attach_masks(id, &cur, &mut on);
self.apply_silent(lightcraft_catalog::Op::SetDevelop { id, settings: std::sync::Arc::new(on), label: "Masks".into(), edited: None })
.map_err(|e| e.to_string())?;
}
let (key, mut d) = self.segment_key(id).ok_or("no such photo")?;
let p = self.catalog.photo(id).ok_or("no such photo")?.clone();
let missing = match &p.source {
+5
View File
@@ -455,6 +455,11 @@ fn write_atomic(path: &Path, data: &[u8]) -> std::io::Result<()> {
/// Copy `path` to a new `<name>.bak-<stamp>` (`-1`, `-2`… if taken; never overwriting).
fn backup(path: &Path, stamp: &str) -> std::io::Result<PathBuf> {
use std::io::Write;
// only a plain file is copied aside: a link under the sidecar's name would have its target's
// contents copied into a new, readable file
if !std::fs::symlink_metadata(path)?.is_file() {
return Err(std::io::Error::other(format!("{} is not a regular file", path.display())));
}
let bytes = std::fs::read(path)?;
let stamp: String = stamp.chars().filter(char::is_ascii_alphanumeric).collect();
let name = path.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
+1
View File
@@ -363,6 +363,7 @@ impl TitleCompose {
quick: None,
display: None,
gpu_fallback: None,
frame: None,
}
}
}
+4 -1
View File
@@ -389,7 +389,10 @@ impl PartFile {
let mut name = target.file_name().ok_or_else(|| format!("{}: not a file name", target.display()))?.to_os_string();
name.push(".part");
let part = target.with_file_name(name);
let f = std::fs::File::create(&part).map_err(|e| format!("{}: {e}", part.display()))?;
// an entry already under the staging name (a leftover, or a link planted to point the
// encoder's bytes at another file) is removed, never opened and written through
let _ = std::fs::remove_file(&part);
let f = std::fs::OpenOptions::new().write(true).create_new(true).open(&part).map_err(|e| format!("{}: {e}", part.display()))?;
Ok((PartFile { part, target: target.to_path_buf(), done: false }, f))
}
+10 -1
View File
@@ -268,7 +268,15 @@ pub fn check_writable(dir: &Path) -> Result<(), String> {
std::fs::create_dir(dir).map_err(|e| format!("can't create {}: {e}", dir.display()))?;
}
let probe = dir.join(format!(".lightcraft-write-test-{}", std::process::id()));
std::fs::write(&probe, b"x").map_err(|e| format!("{} is not writable (is the drive full or read-only?): {e}", dir.display()))?;
// the probe is a new entry of ours: an existing one (a link planted under the name would be
// written through) is removed first, never opened
let _ = std::fs::remove_file(&probe);
std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&probe)
.and_then(|mut f| std::io::Write::write_all(&mut f, b"x"))
.map_err(|e| format!("{} is not writable (is the drive full or read-only?): {e}", dir.display()))?;
let _ = std::fs::remove_file(&probe);
Ok(())
}
@@ -494,6 +502,7 @@ pub fn load(path: &Path) -> Result<crate::media::DecodedSource, String> {
info,
camera_tone,
denoised: None,
camera_profile: None,
from_proxy: true,
reduced: false,
})
+15
View File
@@ -18,6 +18,21 @@ fn writable_check_does_not_create_missing_parents() {
let _ = std::fs::remove_dir_all(&base);
}
#[cfg(unix)]
#[test]
fn writable_probe_never_writes_through_a_planted_link() {
let base = temp("probe-link");
std::fs::create_dir_all(&base).unwrap();
let victim = base.join("victim");
std::fs::write(&victim, b"keep").unwrap();
let probe = base.join(format!(".lightcraft-write-test-{}", std::process::id()));
std::os::unix::fs::symlink(&victim, &probe).unwrap();
assert!(check_writable(&base).is_ok());
assert_eq!(std::fs::read(&victim).unwrap(), b"keep");
assert!(!probe.exists());
let _ = std::fs::remove_dir_all(&base);
}
#[test]
fn migrate_moves_leaves_or_discards() {
let base = temp("migrate");
Loaded 100 of 314 files, more files were not shown because too many files have changed in this diff. Show more